licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.2.1 | b66ec2223581d1c9bf99d7dd60ee0069a9a42d24 | code | 1000 | export ace_high
_ace_high = true
function ace_high(bit::Bool)::Bool
global _ace_high
_ace_high = bit
end
"""
ace_high(bit::Bool)::Bool
Determine if aces are highest value cards in a deck. After `ace_high(true)` aces are greater than kings.
After `ace_high(false)`, aces are lower than twos. This affects the result of `<` comparisons and sorting.
ace_high()::Bool
Return the current status of aces (`true` means aces are high, `false` means aces are low).
"""
function ace_high()::Bool
global _ace_high
return _ace_high
end
import Base: (<), isless
function (<)(C::Card, D::Card)::Bool
rC = rank(C)
rD = rank(D)
if ace_high()
if rC == 1
rC += 13
end
if rD == 1
rD += 13
end
end
if rC < rD
return true
end
if rC > rD
return false
end
# compare by suits
sC = suit(C).s
sD = suit(D).s
return sC < sD
end
isless(C::Card, D::Card)::Bool = C < D
| PlayingCards52 | https://github.com/scheinerman/PlayingCards52.jl.git |
|
[
"MIT"
] | 0.2.1 | b66ec2223581d1c9bf99d7dd60ee0069a9a42d24 | code | 2258 | export riffle, riffle!, cut, cut!
"""
riffle!(list)
Perform an in-place riffle shuffle permutation on
`list` using the Gilbert–Shannon–Reeds model.
"""
function riffle!(list::Vector)
n = length(list)
if n < 2
return
end
t = _simple_binomial(n)
A = list[1:t]
B = list[t+1:end]
na = length(A)
nb = length(B)
# pointers into A and B lists
a = 1
b = 1
for j = 1:n
top = na - a + 1
bot = (na - a + 1) + (nb - b + 1)
p = top / bot # prob we choose from A
if rand() <= p
list[j] = A[a]
a += 1
else
list[j] = B[b]
b += 1
end
end
list
end
"""
riffle(list)
Perform a riffle shuffle permutation on a copy of `list` using the
Gilbert–Shannon–Reeds model. The original `list` is unchanged.
"""
function riffle(list::Vector)
tmp = deepcopy(list)
riffle!(tmp)
end
"""
_simple_binomial(n::Int)
Return a random B(n,0.5) random value.
"""
function _simple_binomial(n::Int)
return sum(rand() > 0.5 for _ = 1:n)
end
"""
cut!(list,idx)
Cut the deck `list` by moving cards `1` through `idx`
(inclusive) to the back of the deck so the first card now was formerly
the one at position `idx+1`.
cut!(list)
Cut the deck at a random location. If the deck has `n`
cards, then the cut location is given by the binomial random
variable `B(n,1/2)`.
"""
function cut!(list::Vector, idx::Int)
n = length(list)
@assert 0 <= idx <= n "Cut index must be between 0 and $n [got $idx]"
if idx == 0 || idx == n
return
end
A = list[1:idx]
B = list[idx+1:end]
na = length(A)
nb = length(B)
for j = 1:nb
list[j] = B[j]
end
for j = 1:na
list[nb+j] = A[j]
end
return list
end
function cut!(list::Vector)
idx = _simple_binomial(length(list))
cut!(list, idx)
end
"""
cut(list,idx)
cut(list)
Use `cut!` to cut a copy of the deck `list`
leaving the original `list` unchanged.
"""
function cut(list::Vector, idx::Int)
tmp = deepcopy(list)
cut!(tmp, idx)
end
function cut(list::Vector)
tmp = deepcopy(list)
cut!(tmp)
end
import Random: shuffle!, shuffle
export shuffle!, shuffle
| PlayingCards52 | https://github.com/scheinerman/PlayingCards52.jl.git |
|
[
"MIT"
] | 0.2.1 | b66ec2223581d1c9bf99d7dd60ee0069a9a42d24 | code | 669 | const _club_base = 0x1F0D1
const _diamond_base = 0x1F0C1
const _heart_base = 0x1F0B1
const _spade_base = 0x1F0A1
function _make_chars(base::Integer)
vals = collect(base:base+10)
append!(vals, base + 12)
append!(vals, base + 13)
return Char.(vals)
end
_cards = _make_chars(_club_base)
append!(_cards, _make_chars(_diamond_base))
append!(_cards, _make_chars(_heart_base))
append!(_cards, _make_chars(_spade_base))
import Base.Char
"""
Char(c::Card)
Return the unicode character for that playing card.
```
julia> Char(4♣)
'🃔': Unicode U+1F0D4 (category So: Symbol, other)
```
"""
function Char(c::Card)
return @inbounds _cards[index(c)]
end
| PlayingCards52 | https://github.com/scheinerman/PlayingCards52.jl.git |
|
[
"MIT"
] | 0.2.1 | b66ec2223581d1c9bf99d7dd60ee0069a9a42d24 | code | 801 | using Test
using PlayingCards52
@test true
for k = 1:52
C = Card(k)
kk = index(C)
@test k == kk
end
ace_high(false)
x = deck()
sort!(x)
@test index(x[1]) == 1
AC = Card(:clubs, 1)
twoD = Card(:diamonds, 2)
ace_high(true)
@test twoD < AC
ace_high(false)
@test twoD > AC
@test color(Card(:clubs, 5)) == color(Card(:spades, 2))
@test color(Card(:clubs, 5)) != color(Card(:diamonds, 2))
@test color(Suit(1)) == color(♠)
@test Char(Card(:clubs, 5)) == '🃕'
d = collect(1:10)
cut!(d, 4)
cut!(d, 6)
@test d == collect(1:10)
riffle!(d)
@test sort(d) == collect(1:10)
# test alternative notation
@test A♣ == Card(:clubs, 1)
@test K♣ == 13♣
@test 7♠ == Card(:spades, 7)
@test 5♢ == 5♦
@test A♡ == A♥
@test Suit(:clubs) == ♣
@test ♡ == ♥
@test name(Card(:clubs, 13)) == "king of clubs"
| PlayingCards52 | https://github.com/scheinerman/PlayingCards52.jl.git |
|
[
"MIT"
] | 0.2.1 | b66ec2223581d1c9bf99d7dd60ee0069a9a42d24 | docs | 6549 | # PlayingCards52
Cards from a standard deck of fifty two.
## Pick a Card
A `Card` is a standard playing card from a fifty-two card deck. The
following functions return a `Card`:
* `Card(suit,rank)` where `suit` is one of the symbols `:clubs`, `:diamonds`,
`:hearts`, or `:spades` and `rank` is an integer from `1` (for Ace) to
`13` (for King).
* `Card(index)` where `index` is an integer from `1` (for the Ace of Clubs)
to `52` (for the King of Spades).
* `Card()` returns a random card.
```julia
julia> using PlayingCards
julia> Card(:diamonds,12)
Q♢
julia> Card(49)
T♠
julia> Card()
Q♠
```
The function `string` returns a two-character representation of the
`Card`:
```julia
julia> string(Card(22))
"9♢"
```
### Alternative input
Cards can be entered via their two-character representation. For example, the nine of diamonds can be entered as `9♢`. That is, type `9` then `\diamondsuit` and then TAB. One may also use `\:diamonds:`+TAB. Likewise for the other suits.
Face cards, tens, and aces can also be entered in this way (using the capital letters T, J, Q, K, and A followed by the suit symbol):
```julia
julia> c = K♠;
julia> println(c)
K♠
julia> T♡ == Card(:hearts,10)
true
```
These cards can also be entered with a leading 1, 10, 11, 12, or 13:
```julia
julia> 10♢
T♢
julia> 13♠
K♠
julia> 1♣
A♣
```
Note that the four suit symbols are defined as objects of type `Suit`.
```julia
julia> typeof(♠)
Suit
```
A `Suit` be created either by typing (say) `\heartsuit`+TAB (giving ♡) or `Suit(:hearts)`
```julia
julia> Suit(:hearts) == ♡
true
```
Cards can be created either using either a symbol `:spades` or suit `♠`:
```julia
julia> a = Card(:spades,5)
5♠
julia> b = Card(♠,5)
5♠
julia> a==b
true
```
## Determine Properties
The functions `suit` and `rank` return the suit (as a `Suit`) and the
rank (as an `Int`) of the card.
```julia
julia> c = Card()
J♣
julia> suit(c)
♣
julia> rank(c)
11
```
The function `index` returns a distinct integer value (from `1` to `52`)
for the card.
```julia
julia> c = Card(17)
4♢
julia> index(c)
17
```
Use `color` to determine if the `Card` is red or black:
```julia
julia> C = Card(:clubs,9)
9♣
julia> color(C)
:black
julia> color(Card(27)) # this is the Ace of Hearts
:red
```
## Ordering
Two `Card`s can be compared with the usual ordering operators (such as `<`).
The ordering of cards is determined first by rank and, if of the same rank,
by suit (alphabetically, as in bridge).
```julia
julia> Card(:diamonds,10) < Card(:hearts,10)
true
julia> Card(:diamonds,10) < Card(:clubs,10)
false
```
The `ace_high` function is used to determine if an Ace is higher
or lower than the other ranks. Use `ace_high(true)` or `ace_high(false)`
to set your preference. A call to `ace_high()` returns the current setting.
```julia
julia> ace_high()
true
julia> Card(:spades,1) < Card(:diamonds,5)
false
julia> ace_high(false)
false
julia> Card(:spades,1) < Card(:diamonds,5)
true
```
## Dealing
The function `deck()` returns a 52-long array containing all possible
cards in random order. Use `deck(false)` for them to be returned in a
"new box" order.
Use the function `print_deck()` to see all 52 cards in four lines of
thirteen cards each.
```julia
julia> d = deck(); print_deck(d)
2♠ J♢ K♠ 3♣ Q♢ 6♢ K♡ 9♣ A♠ 8♢ 7♡ J♣ 4♠
8♣ T♢ T♣ 2♢ 4♣ 3♡ T♡ 6♡ Q♣ A♣ 4♢ 8♡ 8♠
3♠ 3♢ 5♣ J♠ 5♢ 6♣ A♢ T♠ Q♡ 7♣ 9♠ 7♠ 6♠
Q♠ J♡ 7♢ 2♡ A♡ 9♢ 2♣ 4♡ 5♡ K♣ 9♡ 5♠ K♢
julia> d = deck(false); print_deck(d)
A♣ 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ T♣ J♣ Q♣ K♣
A♢ 2♢ 3♢ 4♢ 5♢ 6♢ 7♢ 8♢ 9♢ T♢ J♢ Q♢ K♢
A♡ 2♡ 3♡ 4♡ 5♡ 6♡ 7♡ 8♡ 9♡ T♡ J♡ Q♡ K♡
A♠ 2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ T♠ J♠ Q♠ K♠
```
Deal a random poker hand like this:
```julia
julia> using ShowSet
julia> Set(deck()[1:5])
{2♠,6♢,6♡,T♠,K♣}
```
## Long-Form Names
The `name` function returns a long-form name of a card.
```julia
julia> c = Card(:hearts,1)
A♡
julia> name(c)
"ace of hearts"
```
## Shuffling
The `deck()` function returns a randomly shuffled deck of cards with all 52!
possible orderings equally likely.
However, if one wishes to manually randomize the deck, or to randomize an ordered deck
as returned by `deck(false)`, we provide the functions `shuffle`, `riffle`, and `cut`.
These functions are typically applied to a full deck of 52 cards, but may be used
on any list.
### Shuffle
The functions `shuffle` and `shuffle!` from the `Random` module are
imported and so may be applied to card decks. These functions apply a random
permutation to the cards (all orders equally likely). The function `shuffle`
returns a new deck, leaving the original deck unchanged. The function `shuffle!`
overwrites the deck in the new order.
### Riffle
The functions `riffle` and `riffle!` apply a random riffle shuffle to the deck
using the [Gilbert–Shannon–Reeds model](https://en.wikipedia.org/wiki/Gilbert%E2%80%93Shannon%E2%80%93Reeds_model). The former leaves the original
deck unchanged and the latter overwrites the deck.
```julia
julia> d = deck(false); print_deck(d)
A♣ 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ T♣ J♣ Q♣ K♣
A♢ 2♢ 3♢ 4♢ 5♢ 6♢ 7♢ 8♢ 9♢ T♢ J♢ Q♢ K♢
A♡ 2♡ 3♡ 4♡ 5♡ 6♡ 7♡ 8♡ 9♡ T♡ J♡ Q♡ K♡
A♠ 2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ T♠ J♠ Q♠ K♠
julia> riffle!(d); print_deck(d)
A♣ 4♡ 5♡ 6♡ 2♣ 3♣ 4♣ 7♡ 8♡ 9♡ T♡ J♡ Q♡
K♡ A♠ 2♠ 5♣ 6♣ 7♣ 8♣ 9♣ T♣ J♣ Q♣ K♣ A♢
3♠ 4♠ 5♠ 6♠ 7♠ 2♢ 3♢ 8♠ 4♢ 5♢ 6♢ 7♢ 9♠
8♢ 9♢ T♠ T♢ J♢ Q♢ J♠ K♢ Q♠ A♡ 2♡ K♠ 3♡
```
Note that a single riffle shuffle does a poor job at randomizing
the deck.
### Cut
The functions `cut` and `cut!` are used to cut the deck.
* `cut!(d,idx)` moves cards `1` through `idx` to the back of the deck; the
new first card is the one formerly at position `idx+1`.
* `cut!(d)` cuts the deck a random index. If the deck has `n` cards,
then the cut location is given by the binomial random variable `B(n,1/2)`.
```julia
julia> d = deck(false);
julia> cut!(d)
julia> print_deck(d)
Q♢ K♢ A♡ 2♡ 3♡ 4♡ 5♡ 6♡ 7♡ 8♡ 9♡ T♡ J♡
Q♡ K♡ A♠ 2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ T♠ J♠
Q♠ K♠ A♣ 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ T♣ J♣
Q♣ K♣ A♢ 2♢ 3♢ 4♢ 5♢ 6♢ 7♢ 8♢ 9♢ T♢ J♢
```
## Unicode Characters
The standard playing cards have unicode character representations. Use `Char(c)` to return that character.
```julia
julia> c = Card(:diamonds, 4);
julia> Char(c)
'🃄': Unicode U+1F0C4 (category So: Symbol, other)
```
The characters are unreadable at small font sizes (e.g., 12 point); they need to be enlarged to be visible.

## Acknowledgement
Developed with input from [@charleskawczynski](https://github.com/charleskawczynski)
and in parallel with his
[PlayingCards.jl](https://github.com/charleskawczynski/PlayingCards.jl).
| PlayingCards52 | https://github.com/scheinerman/PlayingCards52.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 731 | module Gaius
import LinearAlgebra
import LoopVectorization
import StructArrays
import UnsafeArrays
import VectorizationBase
import VectorizationBase: stridedpointer
using LinearAlgebra: Adjoint, Transpose
using LoopVectorization: @avx
using StructArrays: StructArray
using UnsafeArrays: @uviews, UnsafeArray
using VectorizationBase: AbstractStridedPointer, gesp, vload, vstore!
export t_blocked_mul
export t_blocked_mul!
include("global_constants.jl")
include("types.jl")
include("block_operations.jl")
include("check_compatible_sizes.jl")
include("choose_block_size.jl")
include("kernels.jl")
include("matmul.jl")
include("public_mul.jl")
include("init.jl") # `Gaius.__init__()` is defined in this file
end # module Gaius
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 20575 | @inline function block_mat_mat_mul!(multithreaded::Multithreaded, C, A, B)
use_singlethread(multithreaded, C, A, B) &&
return block_mat_mat_mul!(multithreaded.singlethreaded, C, A, B)
sz = get_block_size(multithreaded)
mᵣ, nᵣ = LoopVectorization.matmul_params()
mstep = mᵣ * LoopVectorization.pick_vector_width(eltype(A))
m1 = min(max(sz, mstep * div(size(A, 1), 2mstep, RoundNearest)), size(A, 1) - sz)
n1 = min(max(sz, nᵣ * div(size(B, 2), 2nᵣ, RoundNearest)), size(B, 2) - sz)
k1 = min(max(sz, div(size(A, 2), 2, RoundNearest)), size(A, 2) - sz)
@inbounds @views begin
C11 = C[1:m1, 1:n1]; C12 = C[1:m1, n1+1:end]
C21 = C[m1+1:end, 1:n1]; C22 = C[m1+1:end, n1+1:end]
A11 = A[1:m1, 1:k1]; A12 = A[1:m1, k1+1:end]
A21 = A[m1+1:end, 1:k1]; A22 = A[m1+1:end, k1+1:end]
B11 = B[1:k1, 1:n1]; B12 = B[1:k1, n1+1:end]
B21 = B[k1+1:end, 1:n1]; B22 = B[k1+1:end, n1+1:end]
end
@sync begin
Threads.@spawn begin
_mul!(multithreaded, C11, A11, B11)
_mul_add!(multithreaded, C11, A12, B21)
end
Threads.@spawn begin
_mul!(multithreaded, C12, A11, B12)
_mul_add!(multithreaded, C12, A12, B22)
end
Threads.@spawn begin
_mul!(multithreaded, C21, A21, B11)
_mul_add!(multithreaded, C21, A22, B21)
end
_mul!(multithreaded, C22, A21, B12)
_mul_add!(multithreaded, C22, A22, B22)
end
end
@inline function block_mat_mat_mul!(singlethreaded::Singlethreaded, C, A, B)
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:sz, 1:sz]; C12 = C[1:sz, sz+1:end]
C21 = C[sz+1:end, 1:sz]; C22 = C[sz+1:end, sz+1:end]
A11 = A[1:sz, 1:sz]; A12 = A[1:sz, sz+1:end]
A21 = A[sz+1:end, 1:sz]; A22 = A[sz+1:end, sz+1:end]
B11 = B[1:sz, 1:sz]; B12 = B[1:sz, sz+1:end]
B21 = B[sz+1:end, 1:sz]; B22 = B[sz+1:end, sz+1:end]
end
#_mul!(singlethreaded, C11, A11, B11)
gemm_kernel!(C11, A11, B11)
_mul_add!(singlethreaded, C11, A12, B21)
_mul!(singlethreaded, C12, A11, B12)
_mul_add!(singlethreaded, C12, A12, B22)
_mul!(singlethreaded, C21, A21, B11)
_mul_add!(singlethreaded, C21, A22, B21)
_mul!(singlethreaded, C22, A21, B12)
_mul_add!(singlethreaded, C22, A22, B22)
end
function block_mat_vec_mul!(multithreaded::Multithreaded, C, A, B)
use_singlethread(multithreaded, C, A, B) &&
return block_mat_vec_mul!(multithreaded.singlethreaded, C, A, B)
sz = get_block_size(multithreaded)
mstep = LoopVectorization.pick_vector_width(eltype(A))
m1 = min(max(sz, mstep * div(size(A, 1), 2mstep, RoundNearest)), size(A, 1) - sz)
k1 = min(max(sz, div(size(A, 2), 2, RoundNearest)), size(A, 2) - sz)
@inbounds @views begin
C11 = C[1:m1, 1:end];
C21 = C[m1+1:end, 1:end];
A11 = A[1:m1, 1:k1]; A12 = A[1:m1, k1+1:end]
A21 = A[m1+1:end, 1:k1]; A22 = A[m1+1:end, k1+1:end]
B11 = B[1:k1, 1:end];
B21 = B[k1+1:end, 1:end];
end
@sync begin
Threads.@spawn begin
_mul!(multithreaded, C11, A11, B11)
_mul_add!(multithreaded, C11, A12, B21)
end
_mul!(multithreaded, C21, A21, B11)
_mul_add!(multithreaded, C21, A22, B21)
end
end
function block_mat_vec_mul!(singlethreaded::Singlethreaded, C, A, B)
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:sz, 1:end];
C21 = C[sz+1:end, 1:end];
A11 = A[1:sz, 1:sz]; A12 = A[1:sz, sz+1:end]
A21 = A[sz+1:end, 1:sz]; A22 = A[sz+1:end, sz+1:end]
B11 = B[1:sz, 1:end];
B21 = B[sz+1:end, 1:end];
end
#_mul!(singlethreaded, C11, A11, B11)
gemm_kernel!(C11, A11, B11)
_mul_add!(singlethreaded, C11, A12, B21)
_mul!(singlethreaded, C21, A21, B11)
_mul_add!(singlethreaded, C21, A22, B21)
end
function block_mat_vec_mul!(multithreaded::Multithreaded, C::VecTypes, A, B::VecTypes)
use_singlethread(multithreaded, C, A, B) &&
return block_mat_vec_mul!(multithreaded.singlethreaded, C, A, B)
sz = get_block_size(multithreaded)
mstep = LoopVectorization.pick_vector_width(eltype(A))
m1 = min(max(sz, mstep * div(size(A, 1), 2mstep, RoundNearest)), size(A, 1) - sz)
k1 = min(max(sz, div(size(A, 2), 2, RoundNearest)), size(A, 2) - sz)
@inbounds @views begin
C11 = C[1:m1 ];
C21 = C[m1+1:end];
A11 = A[1:m1, 1:k1]; A12 = A[1:m1, k1+1:end]
A21 = A[m1+1:end, 1:k1]; A22 = A[m1+1:end, k1+1:end]
B11 = B[1:k1 ];
B21 = B[k1+1:end];
end
@sync begin
Threads.@spawn begin
_mul!(multithreaded, C11, A11, B11)
_mul_add!(multithreaded, C11, A12, B21)
end
_mul!(multithreaded, C21, A21, B11)
_mul_add!(multithreaded, C21, A22, B21)
end
end
function block_mat_vec_mul!(singlethreaded::Singlethreaded, C::VecTypes, A, B::VecTypes)
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:sz ];
C21 = C[sz+1:end];
A11 = A[1:sz, 1:sz]; A12 = A[1:sz, sz+1:end]
A21 = A[sz+1:end, 1:sz]; A22 = A[sz+1:end, sz+1:end]
B11 = B[1:sz ];
B21 = B[sz+1:end];
end
gemm_kernel!(C11, A11, B11)
_mul_add!(singlethreaded, C11, A12, B21)
_mul!(singlethreaded, C21, A21, B11)
_mul_add!(singlethreaded, C21, A22, B21)
end
function block_covec_mat_mul!(multithreaded::Multithreaded, C, A, B)
use_singlethread(multithreaded, C, A, B) &&
return block_covec_mat_mul!(multithreaded.singlethreaded, C, A, B)
sz = get_block_size(multithreaded)
nstep = LoopVectorization.pick_vector_width(eltype(B))
n1 = min(max(sz, nstep * div(size(B, 2), 2nstep, RoundNearest)), size(B, 2) - sz)
k1 = min(max(sz, div(size(A, 2), 2, RoundNearest)), size(A, 2) - sz)
@inbounds @views begin
C11 = C[1:end, 1:n1]; C12 = C[1:end, n1+1:end]
A11 = A[1:end, 1:k1]; A12 = A[1:end, k1+1:end]
B11 = B[1:k1, 1:n1]; B12 = B[1:k1, n1+1:end]
B21 = B[k1+1:end, 1:n1]; B22 = B[k1+1:end, n1+1:end]
end
@sync begin
Threads.@spawn begin
_mul!(multithreaded, C11, A11, B11)
_mul_add!(multithreaded, C11, A12, B21)
end
_mul!(multithreaded, C12, A11, B12)
_mul_add!(multithreaded, C12, A12, B22)
end
end
function block_covec_mat_mul!(singlethreaded::Singlethreaded, C, A, B)
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:end, 1:sz]; C12 = C[1:end, sz+1:end]
A11 = A[1:end, 1:sz]; A12 = A[1:end, sz+1:end]
B11 = B[1:sz, 1:sz]; B12 = B[1:sz, sz+1:end]
B21 = B[sz+1:end, 1:sz]; B22 = B[sz+1:end, sz+1:end]
end
#_mul!(threading, C11, A11, B11)
gemm_kernel!(C11, A11, B11)
_mul_add!(singlethreaded, C11, A12, B21)
_mul!(singlethreaded, C12, A11, B12)
_mul_add!(singlethreaded, C12, A12, B22)
end
function block_vec_covec_mul!(multithreaded::Multithreaded, C, A, B)
use_singlethread(multithreaded, C, A, B) &&
return block_vec_covec_mul!(multithreaded.singlethreaded, C, A, B)
sz = get_block_size(multithreaded)
mᵣ, nᵣ = LoopVectorization.matmul_params()
mstep = mᵣ * LoopVectorization.pick_vector_width(eltype(A))
m1 = min(max(sz, mstep * div(size(A, 1), 2mstep, RoundNearest)), size(A, 1) - sz)
n1 = min(max(sz, nᵣ * div(size(B, 2), 2nᵣ, RoundNearest)), size(B, 2) - sz)
@inbounds @views begin
C11 = C[1:m1, 1:n1]; C12 = C[1:m1, n1+1:end]
C21 = C[m1+1:end, 1:n1]; C22 = C[m1+1:end, n1+1:end]
A11 = A[1:m1, 1:end];
A21 = A[m1+1:end, 1:end];
B11 = B[1:end, 1:n1]; B12 = B[1:end, n1+1:end]
end
@sync begin
Threads.@spawn begin
_mul!(multithreaded, C11, A11, B11)
end
Threads.@spawn begin
_mul!(multithreaded, C12, A11, B12)
end
Threads.@spawn begin
_mul!(multithreaded, C21, A21, B11)
end
_mul!(multithreaded, C22, A21, B12)
end
end
function block_vec_covec_mul!(singlethreaded::Singlethreaded, C, A, B)
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:sz, 1:sz]; C12 = C[1:sz, sz+1:end]
C21 = C[sz+1:end, 1:sz]; C22 = C[sz+1:end, sz+1:end]
A11 = A[1:sz, 1:end];
A21 = A[sz+1:end, 1:end];
B11 = B[1:end, 1:sz]; B12 = B[1:end, sz+1:end]
end
#_mul!(singlethreaded, C11, A11, B11)
gemm_kernel!(C11, A11, B11)
_mul!(singlethreaded, C12, A11, B12)
_mul!(singlethreaded, C21, A21, B11)
_mul!(singlethreaded, C22, A21, B12)
end
function block_covec_vec_mul!(threading::Threading, C, A, B)
sz = get_block_size(threading)
@inbounds @views begin
A11 = A[1:end, 1:sz]; A12 = A[1:end, sz+1:end]
B11 = B[1:sz, 1:end];
B21 = B[sz+1:end, 1:end];
end
gemm_kernel!(C, A11, B11)
#_mul!(threading, C, A11, B11)
_mul_add!(threading, C, A12, B21)
end
function block_covec_vec_mul!(threading::Threading, C::VecTypes, A, B::VecTypes)
sz = get_block_size(threading)
@inbounds @views begin
A11 = A[1:end, 1:sz]; A12 = A[1:end, sz+1:end]
B11 = B[1:sz ];
B21 = B[sz+1:end];
end
gemm_kernel!(C, A11, B11)
_mul_add!(threading, C, A12, B21)
end
@inline function block_mat_mat_mul_add!(multithreaded::Multithreaded, C, A, B, ::Val{factor} = Val(1)) where {factor}
use_singlethread(multithreaded, C, A, B) &&
return block_mat_mat_mul_add!(multithreaded.singlethreaded, C, A, B, Val(factor))
sz = get_block_size(multithreaded)
mᵣ, nᵣ = LoopVectorization.matmul_params()
mstep = mᵣ * LoopVectorization.pick_vector_width(eltype(A))
m1 = min(max(sz, mstep * div(size(A, 1), 2mstep, RoundNearest)), size(A, 1) - sz)
n1 = min(max(sz, nᵣ * div(size(B, 2), 2nᵣ, RoundNearest)), size(B, 2) - sz)
k1 = min(max(sz, div(size(A, 2), 2, RoundNearest)), size(A, 2) - sz)
@inbounds @views begin
C11 = C[1:m1, 1:n1]; C12 = C[1:m1, n1+1:end]
C21 = C[m1+1:end, 1:n1]; C22 = C[m1+1:end, n1+1:end]
A11 = A[1:m1, 1:k1]; A12 = A[1:m1, k1+1:end]
A21 = A[m1+1:end, 1:k1]; A22 = A[m1+1:end, k1+1:end]
B11 = B[1:k1, 1:n1]; B12 = B[1:k1, n1+1:end]
B21 = B[k1+1:end, 1:n1]; B22 = B[k1+1:end, n1+1:end]
end
@sync begin
Threads.@spawn begin
_mul_add!(multithreaded, C11, A11, B11, Val(factor))
_mul_add!(multithreaded, C11, A12, B21, Val(factor))
end
Threads.@spawn begin
_mul_add!(multithreaded, C12, A11, B12, Val(factor))
_mul_add!(multithreaded, C12, A12, B22, Val(factor))
end
Threads.@spawn begin
_mul_add!(multithreaded, C21, A21, B11, Val(factor))
_mul_add!(multithreaded, C21, A22, B21, Val(factor))
end
_mul_add!(multithreaded, C22, A21, B12, Val(factor))
_mul_add!(multithreaded, C22, A22, B22, Val(factor))
end
end
@inline function block_mat_mat_mul_add!(singlethreaded::Singlethreaded, C, A, B, ::Val{factor} = Val(1)) where {factor}
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:sz, 1:sz]; C12 = C[1:sz, sz+1:end]
C21 = C[sz+1:end, 1:sz]; C22 = C[sz+1:end, sz+1:end]
A11 = A[1:sz, 1:sz]; A12 = A[1:sz, sz+1:end]
A21 = A[sz+1:end, 1:sz]; A22 = A[sz+1:end, sz+1:end]
B11 = B[1:sz, 1:sz]; B12 = B[1:sz, sz+1:end]
B21 = B[sz+1:end, 1:sz]; B22 = B[sz+1:end, sz+1:end]
end
add_gemm_kernel!(C11, A11, B11, Val(factor))
_mul_add!(singlethreaded, C11, A12, B21, Val(factor))
_mul_add!(singlethreaded, C12, A11, B12, Val(factor))
_mul_add!(singlethreaded, C12, A12, B22, Val(factor))
_mul_add!(singlethreaded, C21, A21, B11, Val(factor))
_mul_add!(singlethreaded, C21, A22, B21, Val(factor))
_mul_add!(singlethreaded, C22, A21, B12, Val(factor))
_mul_add!(singlethreaded, C22, A22, B22, Val(factor))
end
function block_mat_vec_mul_add!(multithreaded::Multithreaded, C, A, B, ::Val{factor} = Val(1)) where {factor}
use_singlethread(multithreaded, C, A, B) &&
return block_mat_vec_mul_add!(multithreaded.singlethreaded, C, A, B, Val(factor))
sz = get_block_size(multithreaded)
mstep = LoopVectorization.pick_vector_width(eltype(A))
m1 = min(max(sz, mstep * div(size(A, 1), 2mstep, RoundNearest)), size(A, 1) - sz)
k1 = min(max(sz, div(size(A, 2), 2, RoundNearest)), size(A, 2) - sz)
@inbounds @views begin
C11 = C[1:m1, 1:end];
C21 = C[m1+1:end, 1:end];
A11 = A[1:m1, 1:k1]; A12 = A[1:m1, k1+1:end]
A21 = A[m1+1:end, 1:k1]; A22 = A[m1+1:end, k1+1:end]
B11 = B[1:k1, 1:end];
B21 = B[k1+1:end, 1:end];
end
@sync begin
Threads.@spawn begin
_mul_add!(multithreaded, C11, A11, B11, Val(factor))
_mul_add!(multithreaded, C11, A12, B21, Val(factor))
end
_mul_add!(multithreaded, C21, A21, B11, Val(factor))
_mul_add!(multithreaded, C21, A22, B21, Val(factor))
end
end
function block_mat_vec_mul_add!(singlethreaded::Singlethreaded, C, A, B, ::Val{factor} = Val(1)) where {factor}
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:sz, 1:end];
C21 = C[sz+1:end, 1:end];
A11 = A[1:sz, 1:sz]; A12 = A[1:sz, sz+1:end]
A21 = A[sz+1:end, 1:sz]; A22 = A[sz+1:end, sz+1:end]
B11 = B[1:sz, 1:end];
B21 = B[sz+1:end, 1:end];
end
add_gemm_kernel!(C11, A11, B11, Val(factor))
_mul_add!(singlethreaded, C11, A12, B21, Val(factor))
_mul_add!(singlethreaded, C21, A21, B11, Val(factor))
_mul_add!(singlethreaded, C21, A22, B21, Val(factor))
end
function block_mat_vec_mul_add!(multithreaded::Multithreaded, C::VecTypes, A, B::VecTypes, ::Val{factor} = Val(1)) where {factor}
use_singlethread(multithreaded, C, A, B) &&
return block_mat_vec_mul_add!(multithreaded.singlethreaded, C, A, B, Val(factor))
sz = get_block_size(multithreaded)
mstep = LoopVectorization.pick_vector_width(eltype(A))
m1 = min(max(sz, mstep * div(size(A, 1), 2mstep, RoundNearest)), size(A, 1) - sz)
k1 = min(max(sz, div(size(A, 2), 2, RoundNearest)), size(A, 2) - sz)
@inbounds @views begin
C11 = C[1:m1, ];
C21 = C[m1+1:end];
A11 = A[1:m1, 1:k1]; A12 = A[1:m1, k1+1:end]
A21 = A[m1+1:end, 1:k1]; A22 = A[m1+1:end, k1+1:end]
B11 = B[1:k1, ];
B21 = B[k1+1:end];
end
@sync begin
Threads.@spawn begin
_mul_add!(multithreaded, C11, A11, B11, Val(factor))
_mul_add!(multithreaded, C11, A12, B21, Val(factor))
end
_mul_add!(multithreaded, C21, A21, B11, Val(factor))
_mul_add!(multithreaded, C21, A22, B21, Val(factor))
end
end
function block_mat_vec_mul_add!(singlethreaded::Singlethreaded, C::VecTypes, A, B::VecTypes, ::Val{factor} = Val(1)) where {factor}
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:sz ];
C21 = C[sz+1:end];
A11 = A[1:sz, 1:sz]; A12 = A[1:sz, sz+1:end]
A21 = A[sz+1:end, 1:sz]; A22 = A[sz+1:end, sz+1:end]
B11 = B[1:sz ];
B21 = B[sz+1:end];
end
add_gemm_kernel!(C11, A11, B11, Val(factor))
_mul_add!(singlethreaded, C11, A12, B21, Val(factor))
_mul_add!(singlethreaded, C21, A21, B11, Val(factor))
_mul_add!(singlethreaded, C21, A22, B21, Val(factor))
end
function block_covec_mat_mul_add!(multithreaded::Multithreaded, C, A, B, ::Val{factor} = Val(1)) where {factor}
use_singlethread(multithreaded, C, A, B) &&
return block_covec_mat_mul_add!(multithreaded.singlethreaded, C, A, B, Val(factor))
sz = get_block_size(multithreaded)
nstep = LoopVectorization.pick_vector_width(eltype(B))
n1 = min(max(sz, nstep * div(size(B, 2), 2nstep, RoundNearest)), size(B, 2) - sz)
k1 = min(max(sz, div(size(A, 2), 2, RoundNearest)), size(A, 2) - sz)
@inbounds @views begin
C11 = C[1:end, 1:n1]; C12 = C[1:end, n1+1:end]
A11 = A[1:end, 1:k1]; A12 = A[1:end, k1+1:end]
B11 = B[1:k1, 1:n1]; B12 = B[1:k1, n1+1:end]
B21 = B[k1+1:end, 1:n1]; B22 = B[k1+1:end, n1+1:end]
end
@sync begin
Threads.@spawn begin
_mul_add!(multithreaded, C11, A11, B11, Val(factor))
_mul_add!(multithreaded, C11, A12, B21, Val(factor))
end
_mul_add!(multithreaded, C12, A11, B12, Val(factor))
_mul_add!(multithreaded, C12, A12, B22, Val(factor))
end
end
function block_covec_mat_mul_add!(singlethreaded::Singlethreaded, C, A, B, ::Val{factor} = Val(1)) where {factor}
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:end, 1:sz]; C12 = C[1:end, sz+1:end]
A11 = A[1:end, 1:sz]; A12 = A[1:end, sz+1:end]
B11 = B[1:sz, 1:sz]; B12 = B[1:sz, sz+1:end]
B21 = B[sz+1:end, 1:sz]; B22 = B[sz+1:end, sz+1:end]
end
add_gemm_kernel!(C11, A11, B11, Val(factor))
_mul_add!(singlethreaded, C11, A12, B21, Val(factor))
_mul_add!(singlethreaded, C12, A11, B12, Val(factor))
_mul_add!(singlethreaded, C12, A12, B22, Val(factor))
end
function block_vec_covec_mul_add!(multithreaded::Multithreaded, C, A, B, ::Val{factor} = Val(1)) where {factor}
use_singlethread(multithreaded, C, A, B) &&
return block_vec_covec_mul_add!(multithreaded.singlethreaded, C, A, B, Val(factor))
sz = get_block_size(multithreaded)
mᵣ, nᵣ = LoopVectorization.matmul_params()
mstep = mᵣ * LoopVectorization.pick_vector_width(eltype(A))
m1 = min(max(sz, mstep * div(size(A, 1), 2mstep, RoundNearest)), size(A, 1) - sz)
n1 = min(max(sz, nᵣ * div(size(B, 2), 2nᵣ, RoundNearest)), size(B, 2) - sz)
@inbounds @views begin
C11 = C[1:m1, 1:n1]; C12 = C[1:m1, n1+1:end]
C21 = C[m1+1:end, 1:n1]; C22 = C[m1+1:end, n1+1:end]
A11 = A[1:m1, 1:end];
A21 = A[m1+1:end, 1:end];
B11 = B[1:end, 1:n1]; B12 = B[1:end, n1+1:end]
end
@sync begin
Threads.@spawn begin
_mul_add!(multithreaded, C11, A11, B11, Val(factor))
end
Threads.@spawn begin
_mul_add!(multithreaded, C12, A11, B12, Val(factor))
end
Threads.@spawn begin
_mul_add!(multithreaded, C21, A21, B11, Val(factor))
end
_mul_add!(multithreaded, C22, A21, B12, Val(factor))
end
end
function block_vec_covec_mul_add!(singlethreaded::Singlethreaded, C, A, B, ::Val{factor} = Val(1)) where {factor}
sz = get_block_size(singlethreaded)
@inbounds @views begin
C11 = C[1:sz, 1:sz]; C12 = C[1:sz, sz+1:end]
C21 = C[sz+1:end, 1:sz]; C22 = C[sz+1:end, sz+1:end]
A11 = A[1:sz, 1:end];
A21 = A[sz+1:end, 1:end];
B11 = B[1:end, 1:sz]; B12 = B[1:end, sz+1:end]
end
add_gemm_kernel!(C11, A11, B11, Val(factor))
_mul_add!(singlethreaded, C12, A11, B12, Val(factor))
_mul_add!(singlethreaded, C21, A21, B11, Val(factor))
_mul_add!(singlethreaded, C22, A21, B12, Val(factor))
end
function block_covec_vec_mul_add!(threading::Threading, C, A, B, ::Val{factor} = Val(1)) where {factor}
sz = get_block_size(threading)
@inbounds @views begin
A11 = A[1:end, 1:sz]; A12 = A[1:end, sz+1:end]
B11 = B[1:sz, 1:end];
B21 = B[sz+1:end, 1:end];
end
add_gemm_kernel!(C, A11, B11, Val(factor))
_mul_add!(threading, C, A12, B21, Val(factor))
end
function block_covec_vec_mul_add!(threading::Threading, C::VecTypes, A, B::VecTypes, ::Val{factor} = Val(1)) where {factor}
sz = get_block_size(threading)
@inbounds @views begin
A11 = A[1:end, 1:sz]; A12 = A[1:end, sz+1:end]
B11 = B[1:sz ];
B21 = B[sz+1:end];
end
add_gemm_kernel!(C, A11, B11, Val(factor))
_mul_add!(threading, C, A12, B21, Val(factor))
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 730 | function check_compatible_sizes(C, A, B)
n, m = size(C)
a, k = size(A)
b, c = size(B)
@assert (n == a) && (m == c) && (k == b) "matrices of size $(size(C)), $(size(A)), $(size(B)) are incompatible"
nothing
end
function check_compatible_sizes(C::VecTypes, A, B::VecTypes)
n = length(C)
a, k = size(A)
b = length(B)
@assert (n == a) && (k == b) "matrices of size $(size(C)), $(size(A)), $(size(B)) are incompatible"
nothing
end
function check_compatible_sizes(C::CoVecTypes, A::CoVecTypes, B::MatTypes)
m = length(C)
n = length(A)
a, b = size(B)
@assert (n == a) && (m == b) "matrices of size $(size(C)), $(size(A)), $(size(B)) are incompatible"
nothing
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 1199 | function choose_block_size(C, A, B, ::Nothing)
if (*)(length(C) |> Int128, length(A) |> Int128, length(B) |> Int128) >= ((3default_block_size()) >>> 1)^6
default_block_size()
else
32
end
end
choose_block_size(C, A, B, block_size::Integer) = block_size
choose_singlethread_parameter(C, A, B, block_size) =
Singlethreaded(choose_block_size(C, A, B, block_size))
function choose_multithread_parameter(C, A, B, ::Nothing, block_size)
m = Int128(size(A, 1))
n = Int128(size(B, 1))
k = Int128(size(A, 2))
oversubscription_ratio = 8 # a magic constant that Works For Me
singlethread_size = cld(m * n * k, oversubscription_ratio * Threads.nthreads())
return Multithreaded(
singlethread_size,
choose_singlethread_parameter(C, A, B, block_size),
)
end
choose_multithread_parameter(C, A, B, singlethread_size::Integer, block_size) =
Multithreaded(singlethread_size, choose_singlethread_parameter(C, A, B, block_size))
function use_singlethread(multithreaded::Multithreaded, C, A, B)
m = Int128(size(A, 1))
n = Int128(size(B, 1))
k = Int128(size(A, 2))
return m * n * k <= multithreaded.singlethread_size
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 92 | default_block_size() = Bool(VectorizationBase.has_feature(Val(:x86_64_avx512f))) ? 96 : 64
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 1580 | function __init__()
_print_num_threads_warning()
return nothing
end
function _print_num_threads_warning()
sys_nc = Int(VectorizationBase.num_cores())::Int
jl_nt = Threads.nthreads()
return _print_num_threads_warning(sys_nc, jl_nt)
end
function _print_num_threads_warning(sys_nc::Integer, jl_nt::Integer)
if jl_nt < sys_nc
if !_is_suppress_warning()
msg = string(
"The system has $(_pluralize_cores(sys_nc)). ",
"However, Julia was started with $(_pluralize_threads(jl_nt)). ",
"We recommend starting Julia with at least $(_pluralize_threads(sys_nc)) ",
"to take advantage of Gaius's multithreading algorithms. ",
"To suppress this warning, set the environment variable ",
"SUPPRESS_GAIUS_WARNING=true",
)
@warn(msg)
end
end
return nothing
end
function _string_to_bool(s::AbstractString)
b = tryparse(Bool, s)
if b isa Nothing
return false
else
return b::Bool
end
end
function _is_suppress_warning()
s = get(ENV, "SUPPRESS_GAIUS_WARNING", "")
b = _string_to_bool(s)::Bool
return b
end
function _pluralize(singular::S, plural::S, n::Integer) where {S <: AbstractString}
if n == 1
return singular
else
return plural
end
end
function _pluralize_threads(nt::Integer)
return "$(nt) $(_pluralize("thread", "threads", nt))"
end
function _pluralize_cores(nc::Integer)
return "$(nc) $(_pluralize("core", "cores", nc))"
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 3097 | function gemm_kernel!(C, A, B)
@avx for n ∈ 1:size(A, 1), m ∈ 1:size(B, 2)
Cₙₘ = zero(eltype(C))
for k ∈ 1:size(A, 2)
Cₙₘ += A[n,k] * B[k,m]
end
C[n,m] = Cₙₘ
end
end
function add_gemm_kernel!(C::MatTypes, A::MatTypes, B::MatTypes)
@avx for n ∈ 1:size(A, 1), m ∈ 1:size(B, 2)
Cₙₘ = zero(eltype(C))
for k ∈ 1:size(A, 2)
Cₙₘ += A[n,k] * B[k,m]
end
C[n,m] += Cₙₘ
end
end
add_gemm_kernel!(C::MatTypes, A::MatTypes, B::MatTypes, ::Val{1}) = add_gemm_kernel!(C, A, B)
function add_gemm_kernel!(C::MatTypes, A::MatTypes, B::MatTypes, ::Val{-1})
@avx for n ∈ 1:size(A, 1), m ∈ 1:size(B, 2)
Cₙₘ = zero(eltype(C))
for k ∈ 1:size(A, 2)
Cₙₘ -= A[n,k] * B[k,m]
end
C[n,m] += Cₙₘ
end
end
function add_gemm_kernel!(C::MatTypes, A::MatTypes, B::MatTypes, ::Val{factor}) where {factor}
@avx for n ∈ 1:size(A, 1), m ∈ 1:size(B, 2)
Cₙₘ = zero(eltype(C))
for k ∈ 1:size(A, 2)
Cₙₘ += factor * A[n,k] * B[k,m]
end
C[n,m] += Cₙₘ
end
end
#____________
function gemm_kernel!(u::VecTypes, A::MatTypes, v::VecTypes)
@avx for n ∈ 1:size(A, 1)
uₙ = zero(eltype(u))
for k ∈ 1:size(A, 2)
uₙ += A[n,k] * v[k]
end
u[n] = uₙ
end
end
function add_gemm_kernel!(u::VecTypes, A::MatTypes, v::VecTypes)
@avx for n ∈ 1:size(A, 1)
uₙ = zero(eltype(u))
for k ∈ 1:size(A, 2)
uₙ += A[n,k] * v[k]
end
u[n] += uₙ
end
end
function add_gemm_kernel!(u::VecTypes, A::MatTypes, v::VecTypes, ::Val{-1})
@avx for n ∈ 1:size(A, 1)
uₙ = zero(eltype(u))
for k ∈ 1:size(A, 2)
uₙ -= A[n,k] * v[k]
end
u[n] += uₙ
end
end
function add_gemm_kernel!(u::VecTypes, A::MatTypes, v::VecTypes, ::Val{factor}) where {factor}
@avx for n ∈ 1:size(A, 1)
uₙ = zero(eltype(u))
for k ∈ 1:size(A, 2)
uₙ += A[n,k] * v[k]
end
u[n] += factor * uₙ
end
end
#____________
function gemm_kernel!(u::CoVecTypes, v::CoVecTypes, A::MatTypes)
@avx for m ∈ 1:size(A, 2)
uₘ = zero(eltype(u))
for k ∈ 1:size(A, 1)
uₘ += v[k] * A[k, m]
end
u[m] = uₘ
end
end
function add_gemm_kernel!(u::CoVecTypes, v::CoVecTypes, A::MatTypes)
@avx for m ∈ 1:size(A, 2)
uₘ = zero(eltype(u))
for k ∈ 1:size(A, 1)
uₘ += v[k] * A[k, m]
end
u[m] += uₘ
end
end
function add_gemm_kernel!(u::CoVecTypes, v::CoVecTypes, A::MatTypes, ::Val{-1})
@avx for m ∈ 1:size(A, 2)
uₘ = zero(eltype(u))
for k ∈ 1:size(A, 1)
uₘ -= v[k] * A[k, m]
end
u[m] += uₘ
end
end
function add_gemm_kernel!(u::CoVecTypes, v::CoVecTypes, A::MatTypes, ::Val{factor}) where {factor}
@avx for m ∈ 1:size(A, 2)
uₘ = zero(eltype(u))
for k ∈ 1:size(A, 1)
uₘ += v[k] * A[k, m]
end
u[m] += factor * uₘ
end
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 3166 | function _mul!(threading::Threading, C, A, B)
sz = get_block_size(threading)
n, k, m = size(C, 1), size(A, 2), size(C, 2)
if n >= sz+8 && m >= sz+8 && k >= sz+8
block_mat_mat_mul!(threading, C, A, B)
elseif n >= sz+8 && k >= sz+8 && m < sz+8
block_mat_vec_mul!(threading, C, A, B)
elseif n < sz+8 && k >= sz+8 && m >= sz+8
block_covec_mat_mul!(threading, C, A, B)
elseif n >= sz+8 && k < sz+8 && m >= sz+8
block_vec_covec_mul!(threading, C, A, B)
elseif n < sz+8 && k >= sz+8 && m < sz+8
block_covec_vec_mul!(threading, C, A, B)
else
gemm_kernel!(C, A, B)
end
end
function _mul_add!(threading::Threading, C, A, B, ::Val{factor} = Val(1)) where {factor}
sz = get_block_size(threading)
n, k, m = size(C, 1), size(A, 2), size(C, 2)
if n >= sz+8 && m >= sz+8 && k >= sz+8
block_mat_mat_mul_add!(threading, C, A, B, Val(factor))
elseif n >= sz+8 && k >= sz+8 && m < sz+8
block_mat_vec_mul_add!(threading, C, A, B, Val(factor))
elseif n < sz+8 && k >= sz+8 && m >= sz+8
block_covec_mat_mul_add!(threading, C, A, B, Val(factor))
elseif n >= sz+8 && k < sz+8 && m >= sz+8
block_vec_covec_mul_add!(threading, C, A, B, Val(factor))
elseif n < sz+8 && k >= sz+8 && m < sz+8
block_covec_vec_mul_add!(threading, C, A, B, Val(factor))
else
add_gemm_kernel!(C, A, B, Val(factor))
end
end
function _mul!(threading::Threading, C::VecTypes{T}, A::MatTypes{T}, B::VecTypes{T}) where {T<:Eltypes}
sz = get_block_size(threading)
n, k = size(A)
if n >= sz+8 && k >= sz+8
block_mat_vec_mul!(threading, C, A, B)
elseif n < sz+8 && k >= sz+8
block_covec_vec_mul!(threading, C, A, B)
else
gemm_kernel!(C, A, B)
end
end
function _mul_add!(threading::Threading, C::VecTypes{T}, A::MatTypes{T}, B::VecTypes{T}, ::Val{factor} = Val(1)) where {factor, T<:Eltypes}
sz = get_block_size(threading)
n, k = size(A)
if n >= sz+8 && k >= sz+8
block_mat_vec_mul_add!(threading, C, A, B, Val(factor))
elseif n < sz+8 && k >= sz+8
block_covec_vec_mul_add!(threading, C, A, B, Val(factor))
else
add_gemm_kernel!(C, A, B, Val(factor))
end
end
function _mul!(threading::Threading, C::CoVecTypes{T}, A::CoVecTypes{T}, B::MatTypes{T}) where {T<:Eltypes}
sz = get_block_size(threading)
n, k, m = 1, size(A, 1), length(C)
if k >= sz+8 && m >= sz+8
block_covec_mat_mul!(threading, C, A, B)
elseif k >= sz+8 && m < sz+8
block_covec_vec_mul!(threading, C, A, B)
else
gemm_kernel!(C, A, B)
end
end
function _mul_add!(threading::Threading, C::CoVecTypes{T}, A::CoVecTypes{T}, B::MatTypes{T}, ::Val{factor} = Val(1)) where {factor, T<:Eltypes}
sz = get_block_size(threading)
n, k, m = 1, size(A, 1), length(C)
if k >= sz+8 && m >= sz+8
block_covec_mat_mul!(threading, C, A, B, Val(factor))
elseif k >= sz+8 && m < sz+8
block_covec_vec_mul!(threading, C, A, B, Val(factor))
else
add_gemm_kernel!(C, A, B, Val(factor))
end
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 10968 | """
mul!(C, A, B)
mul!(C, A, B; kwargs...)
Multiply A×B and store the result in C (overwriting the contents of C).
This function uses multithreading.
This function is part of the public API of Gaius.
"""
function mul! end
"""
mul(A, B)
mul(A, B; kwargs...)
Multiply A×B and return the result.
This function uses multithreading.
This function is part of the public API of Gaius.
"""
function mul end
"""
mul_serial(A, B)
mul_serial(A, B; kwargs...)
Multiply A×B and return the result.
This function will run single-threaded.
This function is part of the public API of Gaius.
"""
function mul_serial end
"""
mul_serial!(C, A, B)
mul_serial!(C, A, B; kwargs...)
Multiply A×B and store the result in C (overwriting the contents of C).
This function will run single-threaded.
This function is part of the public API of Gaius.
"""
function mul_serial! end
function mul(A::MatTypes, B::MatTypes)
T = promote_type(eltype(A), eltype(B))
C = Matrix{T}(undef, size(A,1), size(B,2))
mul!(C, A, B)
C
end
function mul_serial(A::MatTypes, B::MatTypes)
T = promote_type(eltype(A), eltype(B))
C = Matrix{T}(undef, size(A,1), size(B,2))
mul_serial!(C, A, B)
C
end
function mul(A::StructArray{Complex{T}, 2}, B::StructArray{Complex{T}, 2}) where {T <: Eltypes}
C = StructArray{Complex{T}}((Matrix{T}(undef, size(A, 1), size(B,2)),
Matrix{T}(undef, size(A, 1), size(B,2))))
mul!(C, A, B)
C
end
function mul_serial(A::StructArray{Complex{T}, 2}, B::StructArray{Complex{T}, 2}) where {T <: Eltypes}
C = StructArray{Complex{T}}((Matrix{T}(undef, size(A, 1), size(B,2)),
Matrix{T}(undef, size(A, 1), size(B,2))))
mul_serial!(C, A, B)
C
end
function mul!(C::AbstractArray{T}, A::AbstractArray{T}, B::AbstractArray{T};
block_size = nothing, singlethread_size = nothing,
sizecheck = true) where {T <: Eltypes}
sizecheck && check_compatible_sizes(C, A, B)
multithreaded = choose_multithread_parameter(C, A, B, singlethread_size, block_size)
_mul!(multithreaded, C, A, B)
C
end
function mul_serial!(C::AbstractArray{T}, A::AbstractArray{T}, B::AbstractArray{T};
block_size = nothing, sizecheck=true) where {T <: Eltypes}
sizecheck && check_compatible_sizes(C, A, B)
singlethreaded = choose_singlethread_parameter(C, A, B, block_size)
_mul!(singlethreaded, C, A, B)
C
end
function mul!(C::StructArray{Complex{T}}, A::StructArray{Complex{T}}, B::StructArray{Complex{T}};
block_size = default_block_size(), singlethread_size = nothing,
sizecheck = true) where {T <: Eltypes}
sizecheck && check_compatible_sizes(C.re, A.re, B.re)
multithreaded = choose_multithread_parameter(C, A, B, singlethread_size, block_size)
GC.@preserve C A B begin
Cre, Cim = C.re, C.im
Are, Aim = A.re, A.im
Bre, Bim = B.re, B.im
_mul!( multithreaded, Cre, Are, Bre) # C.re = A.re * B.re
_mul_add!(multithreaded, Cre, Aim, Bim, Val(-1)) # C.re = C.re - A.im * B.im
_mul!( multithreaded, Cim, Are, Bim) # C.im = A.re * B.im
_mul_add!(multithreaded, Cim, Aim, Bre) # C.im = C.im + A.im * B.re
end
C
end
function mul_serial!(C::StructArray{Complex{T}}, A::StructArray{Complex{T}}, B::StructArray{Complex{T}};
block_size = default_block_size(), sizecheck=true) where {T <: Eltypes}
sizecheck && check_compatible_sizes(C.re, A.re, B.re)
singlethreaded = choose_singlethread_parameter(C, A, B, block_size)
GC.@preserve C A B begin
Cre, Cim = (C.re), (C.im)
Are, Aim = (A.re), (A.im)
Bre, Bim = (B.re), (B.im)
_mul!( singlethreaded, Cre, Are, Bre) # C.re = A.re * B.re
_mul_add!(singlethreaded, Cre, Aim, Bim, Val(-1)) # C.re = C.re - A.im * B.im
_mul!( singlethreaded, Cim, Are, Bim) # C.im = A.re * B.im
_mul_add!(singlethreaded, Cim, Aim, Bre) # C.im = C.im + A.im * B.re
end
C
end
function mul!(C::Adjoint{Complex{T}, <:StructArray{Complex{T}}},
A::Adjoint{Complex{T}, <:StructArray{Complex{T}}},
B::StructArray{Complex{T}};
block_size = default_block_size(), singlethread_size = nothing,
sizecheck = true) where {T <: Eltypes}
sizecheck && check_compatible_sizes(C.parent.re', A.parent.re', B.re)
multithreaded = choose_multithread_parameter(C, A, B, singlethread_size, block_size)
A.parent.im .= (-).(A.parent.im) #ugly hack
GC.@preserve C A B begin
Cre, Cim = (C.parent.re'), (C.parent.im')
Are, Aim = (A.parent.re'), (A.parent.im')
Bre, Bim = (B.re), (B.im)
_mul!( multithreaded, Cre, Are, Bre) # C.re = A.re * B.re
_mul_add!(multithreaded, Cre, Aim, Bim, Val(-1)) # C.re = C.re - A.im * B.im
_mul!( multithreaded, Cim, Are, Bim) # C.im = A.re * B.im
_mul_add!(multithreaded, Cim, Aim, Bre) # C.im = C.im + A.im * B.re
end
A.parent.im .= (-).(A.parent.im)
C.parent.im .= (-).(C.parent.im) # ugly hack
C
end
function mul_serial!(C::Adjoint{Complex{T}, <:StructArray{Complex{T}}},
A::Adjoint{Complex{T}, <:StructArray{Complex{T}}},
B::StructArray{Complex{T}};
block_size = default_block_size(), sizecheck=true) where {T <: Eltypes}
sizecheck && check_compatible_sizes(C.parent.re', A.parent.re', B.re)
singlethreaded = choose_singlethread_parameter(C, A, B, block_size)
A.parent.im .= (-).(A.parent.im) #ugly hack
GC.@preserve C A B begin
Cre, Cim = (C.parent.re'), (C.parent.im')
Are, Aim = (A.parent.re'), (A.parent.im')
Bre, Bim = (B.re), (B.im)
_mul!( singlethreaded, Cre, Are, Bre) # C.re = A.re * B.re
_mul_add!(singlethreaded, Cre, Aim, Bim, Val(-1)) # C.re = C.re - A.im * B.im
_mul!( singlethreaded, Cim, Are, Bim) # C.im = A.re * B.im
_mul_add!(singlethreaded, Cim, Aim, Bre) # C.im = C.im + A.im * B.re
end
A.parent.im .= (-).(A.parent.im)
C.parent.im .= (-).(C.parent.im) # ugly hack
C
end
function mul!(C::Transpose{Complex{T}, <:StructArray{Complex{T}}},
A::Transpose{Complex{T}, <:StructArray{Complex{T}}},
B::StructArray{Complex{T}};
block_size = default_block_size(), singlethread_size = nothing,
sizecheck = true) where {T <: Eltypes}
sizecheck && check_compatible_sizes(C.parent.re |> transpose, A.parent.re |> transpose, B.re)
multithreaded = choose_multithread_parameter(C, A, B, singlethread_size, block_size)
GC.@preserve C A B begin
Cre, Cim = (C.parent.re |> transpose), (C.parent.im |> transpose)
Are, Aim = (A.parent.re |> transpose), (A.parent.im |> transpose)
Bre, Bim = (B.re), (B.im)
_mul!( multithreaded, Cre, Are, Bre) # C.re = A.re * B.re
_mul_add!(multithreaded, Cre, Aim, Bim, Val(-1)) # C.re = C.re - A.im * B.im
_mul!( multithreaded, Cim, Are, Bim) # C.im = A.re * B.im
_mul_add!(multithreaded, Cim, Aim, Bre) # C.im = C.im + A.im * B.re
end
C
end
function mul_serial!(C::Transpose{Complex{T}, <:StructArray{Complex{T}}},
A::Transpose{Complex{T}, <:StructArray{Complex{T}}},
B::StructArray{Complex{T}};
block_size = default_block_size(), sizecheck=true) where {T <: Eltypes}
sizecheck && check_compatible_sizes(C.parent.re |> transpose, A.parent.re |> transpose, B.re)
singlethreaded = choose_singlethread_parameter(C, A, B, block_size)
GC.@preserve C A B begin
Cre, Cim = (C.parent.re |> transpose), (C.parent.im |> transpose)
Are, Aim = (A.parent.re |> transpose), (A.parent.im |> transpose)
Bre, Bim = (B.re), (B.im)
_mul!( singlethreaded, Cre, Are, Bre) # C.re = A.re * B.re
_mul_add!(singlethreaded, Cre, Aim, Bim, Val(-1)) # C.re = C.re - A.im * B.im
_mul!( singlethreaded, Cim, Are, Bim) # C.im = A.re * B.im
_mul_add!(singlethreaded, Cim, Aim, Bre) # C.im = C.im + A.im * B.re
end
C
end
function mul(A::MatTypes, B::VecTypes)
T = promote_type(eltype(A), eltype(B))
C = Vector{T}(undef, size(A,1))
mul!(C, A, B)
C
end
function mul_serial(A::MatTypes, B::VecTypes)
T = promote_type(eltype(A), eltype(B))
C = Vector{T}(undef, size(A,1))
mul_serial!(C, A, B)
C
end
function mul(A::StructArray{Complex{T}, 2}, B::StructArray{Complex{T}, 1}) where {T <: Eltypes}
C = StructArray{Complex{T}}((Vector{T}(undef, size(A, 1)),
Vector{T}(undef, size(A, 1))))
mul!(C, A, B)
C
end
function mul_serial(A::StructArray{Complex{T}, 2}, B::StructArray{Complex{T}, 1}) where {T <: Eltypes}
C = StructArray{Complex{T}}((Vector{T}(undef, size(A, 1)),
Vector{T}(undef, size(A, 1))))
mul_serial!(C, A, B)
C
end
function mul(A::CoVecTypes, B::MatTypes)
T = promote_type(eltype(A), eltype(B))
C = Vector{T}(undef, size(B,2))'
mul!(C, A, B)
C
end
function mul_serial(A::CoVecTypes, B::MatTypes)
T = promote_type(eltype(A), eltype(B))
C = Vector{T}(undef, size(B,2))'
mul_serial!(C, A, B)
C
end
function mul(A::Adjoint{Complex{T}, <:StructArray{Complex{T}, 1}},
B::StructArray{Complex{T}, 2}) where {T <: Eltypes}
C = StructArray{Complex{T}}((Vector{T}(undef, size(B, 2)),
Vector{T}(undef, size(B, 2))))'
mul!(C, A, B)
C
end
function mul_serial(A::Adjoint{Complex{T}, <:StructArray{Complex{T}, 1}},
B::StructArray{Complex{T}, 2}) where {T <: Eltypes}
C = StructArray{Complex{T}}((Vector{T}(undef, size(B, 2)),
Vector{T}(undef, size(B, 2))))'
mul_serial!(C, A, B)
C
end
function mul(A::Transpose{Complex{T}, <:StructArray{Complex{T}, 1}},
B::StructArray{Complex{T}, 2}) where {T <: Eltypes}
C = StructArray{Complex{T}}((Vector{T}(undef, size(B, 2)),
Vector{T}(undef, size(B, 2)))) |> transpose
mul!(C, A, B)
C
end
function mul_serial(A::Transpose{Complex{T}, <:StructArray{Complex{T}, 1}},
B::StructArray{Complex{T}, 2}) where {T <: Eltypes}
C = StructArray{Complex{T}}((Vector{T}(undef, size(B, 2)),
Vector{T}(undef, size(B, 2)))) |> transpose
mul_serial!(C, A, B)
C
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 962 | const Eltypes = Union{Float64, Float32, Int64, Int32, Int16}
const MatTypesC{T} = Union{Matrix{T},
SubArray{T, 2, <: AbstractArray},
UnsafeArray{T, 2}} # C for Column Major
const MatTypesR{T} = Union{Adjoint{T,<:MatTypesC{T}},
Transpose{T,<:MatTypesC{T}}} # R for Row Major
const MatTypes{T} = Union{MatTypesC{T}, MatTypesR{T}}
const VecTypes{T} = Union{Vector{T}, SubArray{T, 1, <:Array}}
const CoVecTypes{T} = Union{Adjoint{T, <:VecTypes{T}},
Transpose{T, <:VecTypes{T}}}
abstract type Threading end
struct Singlethreaded <: Threading
block_size::Int64
end
struct Multithreaded <: Threading
singlethread_size::Int64
singlethreaded::Singlethreaded
end
get_block_size(singlethreaded::Singlethreaded) = singlethreaded.block_size
get_block_size(multithreaded::Multithreaded) = get_block_size(multithreaded.singlethreaded)
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 2792 | # The following variables need to be defined before `include`-ing this file:
# `testset_name_suffix`
# `sz_values`
# `n_values`
# `k_values`
# `m_values`
@time @testset "_mul!: C, A, B $(testset_name_suffix)" begin
for sz in sz_values
singlethreaded = Gaius.Singlethreaded(sz)
multithreaded = Gaius.Multithreaded(2^24, singlethreaded)
for threading in [singlethreaded, multithreaded]
for n in n_values
for k in k_values
for m in m_values
A = randn(Float64, n, k)
B = randn(Float64, k, m)
C1 = zeros(Float64, n, m)
C2 = zeros(Float64, n, m)
Gaius._mul!( threading, C1, A, B)
Gaius._mul_add!(threading, C2, A, B, Val(1))
@test A * B ≈ C1
@test A * B ≈ C2
end
end
end
end
end
end
@time @testset "_mul!: C::VecTypes, A::MatTypes, B::VecTypes $(testset_name_suffix)" begin
for sz in sz_values
singlethreaded = Gaius.Singlethreaded(sz)
multithreaded = Gaius.Multithreaded(2^24, singlethreaded)
for threading in [singlethreaded, multithreaded]
for n in n_values
for k in k_values
for m in m_values
A = randn(Float64, n, k)
B = randn(Float64, k)
C1 = zeros(Float64, n)
C2 = zeros(Float64, n)
Gaius._mul!( threading, C1, A, B)
Gaius._mul_add!(threading, C2, A, B, Val(1))
@test A * B ≈ C1
@test A * B ≈ C2
end
end
end
end
end
end
@time @testset "_mul!: C::CoVecTypes, A::CoVecTypes, B::MatTypes $(testset_name_suffix)" begin
for sz in sz_values
singlethreaded = Gaius.Singlethreaded(sz)
multithreaded = Gaius.Multithreaded(2^24, singlethreaded)
for threading in [singlethreaded, multithreaded]
for n in n_values
for k in k_values
for m in m_values
A = adjoint(randn(Float64, n))
B = randn(Float64, n, m)
C1 = adjoint(zeros(Float64, m))
C2 = adjoint(zeros(Float64, m))
Gaius._mul!( threading, C1, A, B)
Gaius._mul_add!(threading, C2, A, B, Val(1))
@test A * B ≈ C1
@test A * B ≈ C2
end
end
end
end
end
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 12724 | # The following variables need to be defined before `include`-ing this file:
# `testset_name_suffix`
# `n_values_1`
# `n_values_2`
# `m_values_1`
# `m_values_2`
# `sz_values`
@time @testset "Float64 Matrix-Vector $(testset_name_suffix)" begin
for n ∈ n_values_1
for m ∈ m_values_1
u1 = zeros(n)
u2 = zeros(n)
A = rand(n, m)
v = rand(m)
@test Gaius.mul!(u1, A, v) ≈ A * v
@test Gaius.mul_serial!(u2, A, v) ≈ A * v
@test u1 ≈ Gaius.mul(A, v)
@test u2 ≈ Gaius.mul(A, v)
@test u1 ≈ Gaius.mul_serial(A, v)
@test u2 ≈ Gaius.mul_serial(A, v)
end
end
end
@time @testset "ComplexF64 Matrix-Vector $(testset_name_suffix)" begin
for n ∈ n_values_2
for m ∈ m_values_2
u1 = zeros(ComplexF64, n) |> StructArray
u2 = zeros(ComplexF64, n) |> StructArray
A = rand(ComplexF64, n, m) |> StructArray
v = rand(ComplexF64, m) |> StructArray
@test Gaius.mul!(u1, A, v) ≈ collect(A) * collect(v)
@test Gaius.mul_serial!(u2, A, v) ≈ collect(A) * collect(v)
@test u1 ≈ Gaius.mul(A, v)
@test u2 ≈ Gaius.mul(A, v)
@test u1 ≈ Gaius.mul_serial(A, v)
@test u2 ≈ Gaius.mul_serial(A, v)
end
end
end
@time @testset "Float32 Matrix-Vector $(testset_name_suffix)" begin
for n ∈ n_values_2
for m ∈ m_values_2
u1 = zeros(Float32, n)
u2 = zeros(Float32, n)
A = rand(Float32, n, m)
v = rand(Float32, m)
@test Gaius.mul!(u1, A, v) ≈ A * v
@test Gaius.mul_serial!(u2, A, v) ≈ A * v
@test u1 ≈ Gaius.mul(A, v)
@test u2 ≈ Gaius.mul(A, v)
@test u1 ≈ Gaius.mul_serial(A, v)
@test u2 ≈ Gaius.mul_serial(A, v)
end
end
end
@time @testset "Int64 Matrix-Vector $(testset_name_suffix)" begin
for n ∈ n_values_2
for m ∈ m_values_2
u1 = zeros(Int, n)
u2 = zeros(Int, n)
A = rand(-20:20, n, m)
v = rand(-20:20, m)
@test Gaius.mul!(u1, A, v) == A * v
@test Gaius.mul_serial!(u2, A, v) == A * v
@test u1 == Gaius.mul(A, v)
@test u2 == Gaius.mul(A, v)
@test u1 == Gaius.mul_serial(A, v)
@test u2 == Gaius.mul_serial(A, v)
end
end
end
@time @testset "ComplexInt32 Matrix-Vector $(testset_name_suffix)" begin
for n ∈ n_values_2
for m ∈ m_values_2
u1 = zeros(Complex{Int32}, n) |> StructArray
u2 = zeros(Complex{Int32}, n) |> StructArray
A = StructArray{Complex{Int32}}((rand(Int32.(-10:10), n, m), rand(Int32.(-10:10), n, m)))
v = StructArray{Complex{Int32}}((rand(Int32.(-10:10), m), rand(Int32.(-10:10), m)))
@test Gaius.mul!(u1, A, v) == collect(A) * collect(v)
@test Gaius.mul_serial!(u2, A, v) == collect(A) * collect(v)
@test u1 == Gaius.mul(A, v)
@test u2 == Gaius.mul(A, v)
@test u1 == Gaius.mul_serial(A, v)
@test u2 == Gaius.mul_serial(A, v)
end
end
end
@time @testset "Float64 CoVector-Matrix $(testset_name_suffix)" begin
for n ∈ n_values_2
for m ∈ m_values_2
u1 = zeros(m)
u2 = zeros(m)
A = rand(n, m)
v = rand(n)
@test Gaius.mul!(u1', v', A) ≈ v' * A
@test Gaius.mul_serial!(u2', v', A) ≈ v' * A
@test u1' ≈ Gaius.mul(v', A)
@test u2' ≈ Gaius.mul(v', A)
@test u1' ≈ Gaius.mul_serial(v', A)
@test u2' ≈ Gaius.mul_serial(v', A)
@test Gaius.mul!(transpose(u1), transpose(v), A) ≈ transpose(v) * A
@test Gaius.mul_serial!(transpose(u2), transpose(v), A) ≈ transpose(v) * A
@test transpose(u1) ≈ Gaius.mul(transpose(v), A)
@test transpose(u2) ≈ Gaius.mul(transpose(v), A)
@test transpose(u1) ≈ Gaius.mul_serial(transpose(v), A)
@test transpose(u2) ≈ Gaius.mul_serial(transpose(v), A)
end
end
end
@time @testset "ComplexF32 CoVector-Matrix $(testset_name_suffix)" begin
for n ∈ n_values_2
for m ∈ m_values_2
u1 = zeros(Complex{Float32}, m) |> StructArray
u2 = zeros(Complex{Float32}, m) |> StructArray
A = rand(Complex{Float32}, n, m) |> StructArray
v = rand(Complex{Float32}, n) |> StructArray
@test Gaius.mul!(u1', v', A) ≈ v' * A
@test Gaius.mul_serial!(u2', v', A) ≈ v' * A
@test u1' ≈ Gaius.mul(v', A)
@test u2' ≈ Gaius.mul(v', A)
@test u1' ≈ Gaius.mul_serial(v', A)
@test u2' ≈ Gaius.mul_serial(v', A)
@test Gaius.mul!(transpose(u1), transpose(v), A) ≈ transpose(v) * A
@test Gaius.mul_serial!(transpose(u2), transpose(v), A) ≈ transpose(v) * A
@test transpose(u1) ≈ Gaius.mul(transpose(v), A)
@test transpose(u2) ≈ Gaius.mul(transpose(v), A)
@test transpose(u1) ≈ Gaius.mul_serial(transpose(v), A)
@test transpose(u2) ≈ Gaius.mul_serial(transpose(v), A)
end
end
end
@time @testset "ComplexFloat64 Matrix-Matrix $(testset_name_suffix)" begin
for sz ∈ sz_values
n, k, m = (sz .+ rand(-5:5, 3))
@testset "($n × $k) × ($k × $m) $(testset_name_suffix)" begin
C0 = StructArray{ComplexF64}((zeros(n, m), zeros(n, m)))
C1 = StructArray{ComplexF64}((zeros(n, m), zeros(n, m)))
C2 = StructArray{ComplexF64}((zeros(n, m), zeros(n, m)))
A = StructArray{ComplexF64}((randn(n, k), randn(n, k)))
B = StructArray{ComplexF64}((randn(k, m), randn(k, m)))
LinearAlgebra.mul!(C0, A, B)
Gaius.mul!(C1, A, B)
Gaius.mul_serial!(C2, A, B)
@test C0 ≈ C1
@test C0 ≈ C2
@test C1 ≈ C2
@test Gaius.mul_serial(A, B) ≈ C0
end
end
for sz ∈ sz_values
n, k, m = shuffle([sz + rand(-5:5), sz + rand(-5:5), 10])
@testset "($n × $k) × ($k × $m) $(testset_name_suffix)" begin
C0 = StructArray{ComplexF64}((zeros(n, m), zeros(n, m)))
C1 = StructArray{ComplexF64}((zeros(n, m), zeros(n, m)))
C2 = StructArray{ComplexF64}((zeros(n, m), zeros(n, m)))
A = StructArray{ComplexF64}((randn(n, k), randn(n, k)))
B = StructArray{ComplexF64}((randn(k, m), randn(k, m)))
LinearAlgebra.mul!(C0, A, B)
Gaius.mul!(C1, A, B)
Gaius.mul_serial!(C2, A, B)
@test C0 ≈ C1
@test C0 ≈ C2
@test C1 ≈ C2
@test Gaius.mul_serial(A, B) ≈ C0
@test Gaius.mul(A, B) ≈ C0
end
end
end
@time @testset "Float64 Matrix-Matrix $(testset_name_suffix)" begin
for sz ∈ sz_values
n, k, m = (sz .+ rand(-5:5, 3))
@testset "($n × $k) × ($k × $m) $(testset_name_suffix)" begin
C0 = zeros(n, m)
C1 = zeros(n, m)
C2 = zeros(n, m)
A = randn(n, k)
B = randn(k, m)
At = copy(A')
Bt = copy(B')
LinearAlgebra.mul!(C0, A, B)
Gaius.mul!(C1, A, B)
Gaius.mul_serial!(C2, A, B)
@test C0 ≈ C1
@test C0 ≈ C2
@test C1 ≈ C2
@test Gaius.mul_serial(A, B) ≈ C0
fill!(C1, NaN); @test Gaius.mul!(C1, At', B) ≈ C0
fill!(C1, NaN); @test Gaius.mul!(C1, A, Bt') ≈ C0
fill!(C1, NaN); @test Gaius.mul!(C1, At', Bt') ≈ C0
fill!(C2, NaN); @test Gaius.mul_serial!(C2, At', B) ≈ C0
fill!(C2, NaN); @test Gaius.mul_serial!(C2, A, Bt') ≈ C0
fill!(C2, NaN); @test Gaius.mul_serial!(C2, At', Bt') ≈ C0
end
end
for sz ∈ sz_values
n, k, m = shuffle([sz + rand(-5:5), sz + rand(-5:5), 10])
@testset "($n × $k) × ($k × $m) $(testset_name_suffix)" begin
C0 = zeros(n, m)
C1 = zeros(n, m)
C2 = zeros(n, m)
A = randn(n, k)
B = randn(k, m)
At = copy(A')
Bt = copy(B')
LinearAlgebra.mul!(C0, A, B)
Gaius.mul!(C1, A, B)
Gaius.mul_serial!(C2, A, B)
@test C0 ≈ C1
@test C0 ≈ C2
@test C1 ≈ C2
@test Gaius.mul_serial(A, B) ≈ C0
fill!(C1, NaN); @test Gaius.mul!(C1, At', B) ≈ C0
fill!(C1, NaN); @test Gaius.mul!(C1, A, Bt') ≈ C0
fill!(C1, NaN); @test Gaius.mul!(C1, At', Bt') ≈ C0
fill!(C2, NaN); @test Gaius.mul_serial!(C2, At', B) ≈ C0
fill!(C2, NaN); @test Gaius.mul_serial!(C2, A, Bt') ≈ C0
fill!(C2, NaN); @test Gaius.mul_serial!(C2, At', Bt') ≈ C0
end
end
end
@time @testset "Float32 Matrix-Matrix $(testset_name_suffix)" begin
for sz ∈ sz_values
n, k, m = (sz .+ rand(-5:5, 3))
@testset "($n × $k) × ($k × $m) $(testset_name_suffix)" begin
C0 = zeros(Float32, n, m)
C1 = zeros(Float32, n, m)
C2 = zeros(Float32, n, m)
A = randn(Float32, n, k)
B = randn(Float32, k, m)
At = copy(A')
Bt = copy(B')
LinearAlgebra.mul!(C0, A, B)
Gaius.mul!(C1, A, B)
Gaius.mul_serial!(C2, A, B)
@test C0 ≈ C1
@test C0 ≈ C2
@test C1 ≈ C2
@test Gaius.mul_serial(A, B) ≈ C0
fill!(C1, NaN32); @test Gaius.mul!(C1, At', B) ≈ C0
fill!(C1, NaN32); @test Gaius.mul!(C1, A, Bt') ≈ C0
fill!(C1, NaN32); @test Gaius.mul!(C1, At', Bt') ≈ C0
fill!(C2, NaN32); @test Gaius.mul_serial!(C2, At', B) ≈ C0
fill!(C2, NaN32); @test Gaius.mul_serial!(C2, A, Bt') ≈ C0
fill!(C2, NaN32); @test Gaius.mul_serial!(C2, At', Bt') ≈ C0
end
end
end
@time @testset "Int64 Matrix-Matrix $(testset_name_suffix)" begin
for sz ∈ sz_values
n, k, m = (sz .+ rand(-5:5, 3))
@testset "($n × $k) × ($k × $m) $(testset_name_suffix)" begin
C0 = zeros(Int64, n, m)
C1 = zeros(Int64, n, m)
C2 = zeros(Int64, n, m)
A = rand(Int64.(-100:100), n, k)
B = rand(Int64.(-100:100), k, m)
At = copy(A')
Bt = copy(B')
LinearAlgebra.mul!(C0, A, B)
Gaius.mul!(C1, A, B)
Gaius.mul_serial!(C2, A, B)
@test C0 == C1
@test C0 == C2
@test C1 == C2
@test Gaius.mul_serial(A, B) == C0
fill!(C1, typemax(Int64)); @test Gaius.mul!(C1, At', B) == C0
fill!(C1, typemax(Int64)); @test Gaius.mul!(C1, A, Bt') == C0
fill!(C1, typemax(Int64)); @test Gaius.mul!(C1, At', Bt') == C0
fill!(C2, typemax(Int64)); @test Gaius.mul_serial!(C2, At', B) == C0
fill!(C2, typemax(Int64)); @test Gaius.mul_serial!(C2, A, Bt') == C0
fill!(C2, typemax(Int64)); @test Gaius.mul_serial!(C2, At', Bt') == C0
@test Gaius.mul(A, B) == C0
@test Gaius.mul(At', B) == C0
@test Gaius.mul(A, Bt') == C0
@test Gaius.mul(At', Bt') == C0
end
end
end
@time @testset "Int32 Matrix-Matrix $(testset_name_suffix)" begin
for sz ∈ sz_values
n, k, m = (sz .+ rand(-5:5, 3))
@testset "($n × $k) × ($k × $m) $(testset_name_suffix)" begin
C0 = zeros(Int32, n, m)
C1 = zeros(Int32, n, m)
C2 = zeros(Int32, n, m)
A = rand(Int32.(-100:100), n, k)
B = rand(Int32.(-100:100), k, m)
At = copy(A')
Bt = copy(B')
LinearAlgebra.mul!(C0, A, B)
Gaius.mul!(C1, A, B)
Gaius.mul_serial!(C2, A, B)
@test C0 == C1
@test C0 == C2
@test C1 == C2
@test Gaius.mul_serial(A, B) == C0
fill!(C1, typemax(Int32)); @test Gaius.mul!(C1, At', B) == C0
fill!(C1, typemax(Int32)); @test Gaius.mul!(C1, A, Bt') == C0
fill!(C1, typemax(Int32)); @test Gaius.mul!(C1, At', Bt') == C0
fill!(C2, typemax(Int32)); @test Gaius.mul_serial!(C2, At', B) == C0
fill!(C2, typemax(Int32)); @test Gaius.mul_serial!(C2, A, Bt') == C0
fill!(C2, typemax(Int32)); @test Gaius.mul_serial!(C2, At', Bt') == C0
end
end
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 494 | @time @testset "block_operations" begin
multithreaded = Gaius.Multithreaded(0, Gaius.Singlethreaded(1))
@testset begin
A = [1 2; 3 4]
B = [5 6; 7 8]
C = Matrix{Int}(undef, 2, 2)
Gaius.block_covec_vec_mul!(multithreaded, C, A, B)
@test C == A * B
end
@testset begin
A = [1 2; 3 4]
B = [5, 6]
C = Vector{Int}(undef, 2)
Gaius.block_covec_vec_mul!(multithreaded, C, A, B)
@test C == A * B
end
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 2343 | @testset "init" begin
@testset "_print_num_threads_warning" begin
withenv("SUPPRESS_GAIUS_WARNING" => "false") do
@test_logs (:warn, "The system has 16 cores. However, Julia was started with 1 thread. We recommend starting Julia with at least 16 threads to take advantage of Gaius's multithreading algorithms. To suppress this warning, set the environment variable SUPPRESS_GAIUS_WARNING=true") match_mode=:any Gaius._print_num_threads_warning(16, 1)
end
end
@testset "_string_to_bool" begin
@test !Gaius._string_to_bool("")
@test !Gaius._string_to_bool("foobarbaz")
@test !Gaius._string_to_bool("false")
@test !Gaius._string_to_bool("0")
@test Gaius._string_to_bool("true")
@test Gaius._string_to_bool("1")
end
@testset "_is_suppress_warning" begin
withenv("SUPPRESS_GAIUS_WARNING" => nothing) do
@test !Gaius._is_suppress_warning()
end
withenv("SUPPRESS_GAIUS_WARNING" => "") do
@test !Gaius._is_suppress_warning()
end
withenv("SUPPRESS_GAIUS_WARNING" => "false") do
@test !Gaius._is_suppress_warning()
end
withenv("SUPPRESS_GAIUS_WARNING" => "0") do
@test !Gaius._is_suppress_warning()
end
withenv("SUPPRESS_GAIUS_WARNING" => "true") do
@test Gaius._is_suppress_warning()
end
withenv("SUPPRESS_GAIUS_WARNING" => "1") do
@test Gaius._is_suppress_warning()
end
end
@testset "_pluralize" begin
@test Gaius._pluralize("foo", "bar", 0) == "bar"
@test Gaius._pluralize("foo", "bar", 1) == "foo"
@test Gaius._pluralize("foo", "bar", 2) == "bar"
@test Gaius._pluralize("foo", "bar", 3) == "bar"
end
@testset "_pluralize_threads" begin
@test Gaius._pluralize_threads(0) == "0 threads"
@test Gaius._pluralize_threads(1) == "1 thread"
@test Gaius._pluralize_threads(2) == "2 threads"
@test Gaius._pluralize_threads(3) == "3 threads"
end
@testset "_pluralize_cores" begin
@test Gaius._pluralize_cores(0) == "0 cores"
@test Gaius._pluralize_cores(1) == "1 core"
@test Gaius._pluralize_cores(2) == "2 cores"
@test Gaius._pluralize_cores(3) == "3 cores"
end
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 1111 | @time @testset "kernels" begin
@testset begin
A = [1 2; 3 4]
B = [5 6; 7 8]
C1 = zeros(Int, 2, 2)
C2 = zeros(Int, 2, 2)
Gaius.add_gemm_kernel!(C1, A, B, Val(1))
LinearAlgebra.mul!(C2, A, B)
@test C1 == C2
end
@testset begin
A = [1 2; 3 4]
v = [5; 6]
u1 = zeros(Int, 2)
u2 = zeros(Int, 2)
Gaius.add_gemm_kernel!(u1, A, v)
LinearAlgebra.mul!(u2, A, v)
@test u1 == u2
end
@testset begin
v = adjoint([5; 6])
A = [1 2; 3 4]
u1 = adjoint(zeros(Int, 2))
u2 = adjoint(zeros(Int, 2))
Gaius.add_gemm_kernel!(u1, v, A)
LinearAlgebra.mul!(u2, v, A)
@test u1 == u2
end
@testset begin
A = [1 2; 3 4]
B = [5 6; 7 8]
C = zeros(Int, 2, 2)
Gaius.add_gemm_kernel!(C, A, B, Val(1))
@test C == A * B
end
@testset begin
A = [1 2; 3 4]
B = [5 6; 7 8]
C = zeros(Int, 2, 2)
Gaius.add_gemm_kernel!(C, A, B, Val(3))
@test C == 3 * A * B
end
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 132 | sz_values = [1]
n_values = [1, 9]
k_values = [1, 9]
m_values = [1, 9]
testset_name_suffix = "(coverage)"
include("_matmul.jl")
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 128 | sz_values = [1]
n_values = [1, 9]
k_values = [1, 9]
m_values = [1, 9]
testset_name_suffix = "(main)"
include("_matmul.jl")
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 158 | n_values_1 = [200]
n_values_2 = [200]
m_values_1 = [200]
m_values_2 = [200]
sz_values = [210]
testset_name_suffix = "(coverage)"
include("_public_mul.jl")
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 230 | n_values_1 = [10, 100, 500, 10000]
n_values_2 = [10, 100, 500, 2000]
m_values_1 = [10, 100, 10000]
m_values_2 = [10, 100, 2000]
sz_values = [10, 50, 100, 200, 400, 1000]
testset_name_suffix = "(main)"
include("_public_mul.jl")
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 591 | import Gaius
import BenchmarkTools
import InteractiveUtils
import LinearAlgebra
import Random
import StructArrays
import Test
import VectorizationBase
using Random: shuffle
using StructArrays: StructArray
using Test: @testset, @test, @test_logs, @test_throws
include("test_suite_preamble.jl")
@info("VectorizationBase.num_cores() is $(VectorizationBase.num_cores())")
include("block_operations.jl")
include("public_mul_coverage.jl")
include("init.jl")
include("kernels.jl")
include("matmul_coverage.jl")
if !coverage
include("public_mul_main.jl")
include("matmul_main.jl")
end
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | code | 285 | using InteractiveUtils: versioninfo
versioninfo()
@info("Running tests with $(Threads.nthreads()) threads")
function is_coverage()
return !iszero(Base.JLOptions().code_coverage)
end
const coverage = is_coverage()
@info("Code coverage is $(coverage ? "enabled" : "disabled")")
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 0.6.8 | 643b22c7e5461b89beee5a88bea666eddeae2585 | docs | 9196 | # Gaius.jl
*Because Caesar.jl was taken*
[![Continuous Integration][ci-img]][ci-url]
[![Continuous Integration (Julia nightly)][ci-julia-nightly-img]][ci-julia-nightly-url]
[![Code Coverage][codecov-img]][codecov-url]
[ci-url]: https://github.com/MasonProtter/Gaius.jl/actions?query=workflow%3ACI
[ci-julia-nightly-url]: https://github.com/MasonProtter/Gaius.jl/actions?query=workflow%3A%22CI+%28Julia+nightly%29%22
[codecov-url]: https://codecov.io/gh/MasonProtter/Gaius.jl
[ci-img]: https://github.com/MasonProtter/Gaius.jl/workflows/CI/badge.svg "Continuous Integration"
[ci-julia-nightly-img]: https://github.com/MasonProtter/Gaius.jl/workflows/CI%20(Julia%20nightly)/badge.svg "Continuous Integration (Julia nightly)"
[codecov-img]: https://codecov.io/gh/MasonProtter/Gaius.jl/branch/master/graph/badge.svg "Code Coverage"
Gaius.jl is a multi-threaded BLAS-like library using a divide-and-conquer
strategy to parallelism, and built on top of the **fantastic**
[LoopVectorization.jl](https://github.com/chriselrod/LoopVectorization.jl).
Gaius spawns threads using Julia's depth first parallel task runtime and so
Gaius's routines may be fearlessly nested inside multi-threaded Julia programs.
Gaius is *not* stable or well tested. Only use it if you're adventurous.
Note: Gaius is not actively maintained and I do not anticipate doing further
work on it. However, you may find it useful as a relatively simple playground
for learning about the implementation of linear algebra routines.
There are other, more promising projects that may result in a
scalable, multi-threaded pure Julia BLAS library such as:
1. [Tullio.jl](https://github.com/mcabbott/Tullio.jl)
2. [Octavian.jl](https://github.com/JuliaLinearAlgebra/Octavian.jl)
In general:
- Octavian is the most performant.
- Tullio is the most flexible.
## Quick Start
```julia
julia> using Gaius
julia> Gaius.mul!(C, A, B) # (multi-threaded) multiply A×B and store the result in C (overwriting the contents of C)
julia> Gaius.mul(A, B) # (multi-threaded) multiply A×B and return the result
julia> Gaius.mul_serial!(C, A, B) # (single-threaded) multiply A×B and store the result in C (overwriting the contents of C)
julia> Gaius.mul_serial(A, B) # (single-threaded) multiply A×B and return the result
```
Remember to start Julia with multiple threads with e.g. one of the following:
- `julia -t auto`
- `julia -t 4`
- Set the `JULIA_NUM_THREADS` environment variable to `4` **before** starting Julia
The functions in this list are part of the public API of Gaius:
- `Gaius.mul!`
- `Gaius.mul`
- `Gaius.mul_serial!`
- `Gaius.mul_serial`
All other functions are internal (private).
## Matrix Multiplication
Currently, fast, native matrix-multiplication is only implemented
between matrices of types `Matrix{<:Union{Float64, Float32, Int64,
Int32, Int16}}`, and `StructArray{Complex}`. Support for other other
commonly encountered numeric `struct` types such as `Rational` and
`Dual` numbers is planned.
### Using Gaius
<details>
<summary>Click to expand:</summary>
Gaius defines the public functions `Gaius.mul` and
`Gaius.mul!`. `Gaius.mul` is to be used like the regular `*`
operator between two matrices whereas `Gaius.mul!` takes in three
matrices `C, A, B` and stores `A*B` in `C` overwriting the contents of
`C`.
The functions `Gaius.mul` and `Gaius.mul!` use multithreading. If you
want to run the single-threaded variants, use `Gais.mul_serial` and
`Gaius.mul_serial!` respectively.
```julia
julia> using Gaius, BenchmarkTools, LinearAlgebra
julia> A, B, C = rand(104, 104), rand(104, 104), zeros(104, 104);
julia> @btime mul!($C, $A, $B); # from LinearAlgebra
68.529 μs (0 allocations: 0 bytes)
julia> @btime mul!($C, $A, $B); #from Gaius
31.220 μs (80 allocations: 10.20 KiB)
```
```julia
julia> using Gaius, BenchmarkTools
julia> A, B = rand(104, 104), rand(104, 104);
julia> @btime $A * $B;
68.949 μs (2 allocations: 84.58 KiB)
julia> @btime let * = Gaius.mul # Locally use Gaius.mul as * operator.
$A * $B
end;
32.950 μs (82 allocations: 94.78 KiB)
julia> versioninfo()
Julia Version 1.4.0-rc2.0
Commit b99ed72c95* (2020-02-24 16:51 UTC)
Platform Info:
OS: Linux (x86_64-pc-linux-gnu)
CPU: AMD Ryzen 5 2600 Six-Core Processor
WORD_SIZE: 64
LIBM: libopenlibm
LLVM: libLLVM-8.0.1 (ORCJIT, znver1)
Environment:
JULIA_NUM_THREADS = 6
```
Multi-threading in Gaius works by recursively splitting matrices
into sub-blocks to operate on. You can change the matrix sub-block
size by calling `mul!` with the `block_size` keyword argument. If left
unspecified, Gaius will use a (very rough) heuristic to choose a good
block size based on the size of the input matrices.
The size heuristics I use are likely not yet optimal for everyone's
machines.
</details>
### Complex Numbers
<details>
<summary>Click to expand:</summary>
Gaius supports the multiplication of matrices of complex numbers,
but they must first by converted explicity to structs of arrays using
StructArrays.jl (otherwise the multiplication will be done by OpenBLAS):
```julia
julia> using Gaius, StructArrays
julia> begin
n = 150
A = randn(ComplexF64, n, n)
B = randn(ComplexF64, n, n)
C = zeros(ComplexF64, n, n)
SA = StructArray(A)
SB = StructArray(B)
SC = StructArray(C)
@btime mul!($SC, $SA, $SB)
@btime mul!($C, $A, $B)
SC ≈ C
end
515.587 μs (80 allocations: 10.53 KiB)
546.481 μs (0 allocations: 0 bytes)
true
```
</details>
### Benchmarks
#### Floating Point Performance
<details>
<summary>Click to expand:</summary>
The following benchmarks were run on this
```julia
julia> versioninfo()
Julia Version 1.4.0-rc2.0
Commit b99ed72c95* (2020-02-24 16:51 UTC)
Platform Info:
OS: Linux (x86_64-pc-linux-gnu)
CPU: AMD Ryzen 5 2600 Six-Core Processor
WORD_SIZE: 64
LIBM: libopenlibm
LLVM: libLLVM-8.0.1 (ORCJIT, znver1)
Environment:
JULIA_NUM_THREADS = 6
```
and compared to [OpenBLAS](https://github.com/xianyi/OpenBLAS) running with
`6` threads (`BLAS.set_num_threads(6)`). I would be keenly interested in seeing
analogous benchmarks on a machine with an AVX512 instruction set and/or
[Intel's MKL](https://software.intel.com/en-us/mkl).


*Note that these are log-log plots.*
Gaius outperforms [OpenBLAS](https://github.com/xianyi/OpenBLAS) over a large
range of matrix sizes, but
does begin to appreciably fall behind around `800 x 800` matrices for
`Float64` and `650 x 650` matrices for `Float32`. I believe there is a
large amount of performance left on the table in Gaius and I look
forward to beating OpenBLAS for more matrix sizes.
</details>
#### Complex Floating Point Performance
<details>
<summary>Click to expand:</summary>
Here is Gaius operating on `Complex{Float64}` structs-of-arrays
competeing relatively evenly against OpenBLAS operating on
`Complex{Float64}` arrays-of-structs:

I think with some work, we can do much better.
</details>
#### Integer Performance
<details>
<summary>Click to expand:</summary>
These benchmarks compare Gaius (on the same machine as above) and
compare against Julia's generic matrix multiplication implementation
(OpenBLAS does not provide integer mat-mul) which is not
multi-threaded.


*Note that these are log-log plots.*
Benchmarks performed on a machine with the AVX512 instruction set show an
[even greater performance gain](https://github.com/chriselrod/LoopVectorization.jl).
If you find yourself in a high performance situation where you want to
multiply matrices of integers, I think this provides a compelling
use-case for Gaius since it will outperform it's competition at
*any* matrix size and for large matrices will benefit from
multi-threading.
</details>
## Other BLAS Routines
I have not yet worked on implementing other standard BLAS routines
with this strategy, but doing so should be relatively straightforward.
## Safety
*If you must break the law, do it to seize power; in all other cases observe it.*
-Gaius Julius Caesar
If you use only the functions `Gaius.mul!`, `Gaius.mul`,
`Gaius.mul_serial!`, and `Gaius.mul_serial`,
automatic array size-checking will occur before
the matrix multiplication begins. This can be turned off in
`mul!` by calling `Gaius.mul!(C, A, B; sizecheck=false)`, in
which case no sizechecks will occur on the arrays before the matrix
multiplication occurs and all sorts of bad, segfaulty things can
happen.
All other functions in this package are to be considered *internal*
and should not be expected to check for safety or obey the law. The
functions `Gaius.gemm_kernel!` and `Gaius.add_gemm_kernel!` may be of
utility, but be warned that they do not check array sizes.
| Gaius | https://github.com/MasonProtter/Gaius.jl.git |
|
[
"MIT"
] | 1.0.0 | 596e5adf3856e082d37f4a8ae8de8f56a3a3ce22 | code | 1430 | __precompile__(true)
"""
Support for Character Sets, Encodings, and Character Set Encodings
Copyright 2017-2018 Gandalf Software, Inc., Scott P. Jones
Licensed under MIT License, see LICENSE.md
"""
module CharSetEncodings
using ModuleInterfaceTools
@api extend! StrAPI
# Define symbols used for characters, codesets, codepoints
const cse_info =
((:Binary, UInt8), # really, no character set at all, not text
(:Text1, UInt8), # Unknown character set, 1 byte
(:ASCII, UInt8), # (7-bit subset of Unicode)
(:Latin, UInt8), # ISO-8859-1 (8-bit subset of Unicode)
(:_Latin, UInt8), # Latin subset of Unicode (0-0xff)
(:UTF8, UInt8, :UTF32), # Validated UTF-8
(:RawUTF8, UInt8, :UniPlus), # Unvalidated UTF-8
(:Text2, UInt16), # Unknown character set, 2 byte
(:UCS2, UInt16), # BMP (16-bit subset of Unicode)
(:_UCS2, UInt16), # UCS-2 Subset of Unicode (0-0xd7ff, 0xe000-0xffff)
(:UTF16, UInt16, :UTF32), # Validated UTF-16
(:RawUTF16, UInt16, :UniPlus), # Unvalidated UTF-16
(:Text4, UInt32), # Unknown character set, 4 byte
(:UTF32, UInt32), # corresponding to codepoints (0-0xd7ff, 0xe000-0x10fff)
(:_UTF32, UInt32)) # Full validated UTF-32
@api develop cse_info
include("charsets.jl")
include("encodings.jl")
include("cses.jl")
include("traits.jl")
@api freeze
end # module CharSetEncodings
| CharSetEncodings | https://github.com/JuliaString/CharSetEncodings.jl.git |
|
[
"MIT"
] | 1.0.0 | 596e5adf3856e082d37f4a8ae8de8f56a3a3ce22 | code | 1066 | # Character Sets
#
# Copyright 2017-2018 Gandalf Software, Inc., Scott P. Jones
# Licensed under MIT License, see LICENSE.md
@api public CharSet, UniPlusCharSet
@api develop charset_types
struct CharSet{CS} end
"""List of installed character sets"""
const charset_types = []
CharSet(s) = CharSet{Symbol(s)}()
# List of basic character sets
show(io::IO, ::Type{CharSet{S}}) where {S} = print(io, "CharSet{:$S}")
const UniPlusCharSet = CharSet{:UniPlus}
push!(charset_types, UniPlusCharSet)
for lst in cse_info
length(lst) > 2 && continue
nam = lst[1]
csnam = symstr(nam, "CharSet")
@eval const $csnam = CharSet{$(quotesym(nam))}
@eval show(io::IO, ::Type{$csnam}) = print(io, $(string(csnam)))
@eval push!(charset_types, $csnam)
@eval @api $(String(nam)[1] == '_' ? :develop : :public) $csnam
end
# Handle a few quirks
charset(::Type{<:AbstractChar}) = UTF32CharSet
charset(::Type{UInt8}) = BinaryCharSet # UInt8 instead of "BinaryChr"
charset(::Type{Char}) = UniPlusCharSet # Char instead of "UniPlusChr"
| CharSetEncodings | https://github.com/JuliaString/CharSetEncodings.jl.git |
|
[
"MIT"
] | 1.0.0 | 596e5adf3856e082d37f4a8ae8de8f56a3a3ce22 | code | 3775 | # Character Set Encoding support
#
# Copyright 2017-2018 Gandalf Software, Inc., Scott P. Jones
# Licensed under MIT License, see LICENSE.md
@api public CSE, "@cse"
@api public! basecse
@api develop cse_types
struct CSE{CS, ENC} end
"""List of installed character set encodings"""
const cse_types = []
CSE(cs, e) = CSE{CharSet(cs), Encoding(e)}()
macro cse(cs, e)
:(CSE{CharSet{$(quotesym(cs)), $(quotesym(e))}()})
end
const _CSE{U} = Union{CharSet{U}, Encoding{U}} where {U}
print(io::IO, ::S) where {S<:_CSE{U}} where {U} = print(io, U)
show(io::IO, ::Type{CSE{CS,E}}) where {S,T,CS<:CharSet{S},E<:Encoding{T}} =
print(io, "CSE{", string(S), ", ", string(T), "}")
print(io::IO, ::T) where {S,U,CS<:CharSet{S},E<:Encoding{U},T<:CSE{CS,E}} =
(show(io, T); print(io, "()"))
# Definition of built-in CSEs (Character Set Encodings)
codeunit(::Type{<:CSE}) = UInt8
basecse(::Type{C}) where {C<:CSE} = C
for lst in cse_info
nam, cu = lst
cse = symstr(nam, "CSE")
if length(lst) > 2
csnam = symstr(lst[3], "CharSet")
enc = cu === UInt8 ? :UTF8Encoding : :NativeUTF16
else
csnam = symstr(nam, "CharSet")
enc = cu === UInt8 ? :Native1Byte : cu === UInt16 ? :Native2Byte : :Native4Byte
end
@eval const $(symstr(nam, "CSE")) = CSE{$csnam, $enc}
@eval show(io::IO, ::Type{$cse}) = print(io, $(String(cse)))
cu === UInt8 || (@eval codeunit(::Type{$cse}) = $cu)
@eval push!(cse_types, $cse)
if String(nam)[1] == '_'
@eval basecse(::Type{$cse}) = $(symstr(String(nam)[2:end], "CSE"))
@eval @api develop $cse
else
@eval @api public $cse
end
end
# Various useful groups of character set types
# These should be done via traits
const Binary_CSEs = Union{Text1CSE, BinaryCSE}
const Latin_CSEs = Union{LatinCSE, _LatinCSE}
const UTF8_CSEs = Union{UTF8CSE, RawUTF8CSE}
const UCS2_CSEs = Union{UCS2CSE, _UCS2CSE}
const UTF32_CSEs = Union{UTF32CSE, _UTF32CSE}
const SubSet_CSEs = Union{_LatinCSE, _UCS2CSE, _UTF32CSE}
const Byte_CSEs = Union{ASCIICSE, Binary_CSEs, Latin_CSEs, UTF8_CSEs} # 8-bit code units
const Word_CSEs = Union{Text2CSE, UCS2CSE, _UCS2CSE, UTF16CSE} # 16-bit code units
const Quad_CSEs = Union{Text4CSE, UTF32CSE, _UTF32CSE} # 32-bit code units
@api develop Binary_CSEs, Latin_CSEs, UTF8_CSEs, UCS2_CSEs, UTF32_CSEs, SubSet_CSEs,
Byte_CSEs, Word_CSEs, Quad_CSEs
cse(::Type{<:AbstractString}) = RawUTF8CSE # allows invalid sequences
cse(::Type{<:SubString{T}}) where {T} = basecse(T)
cse(::T) where {T<:AbstractString} = cse(T)
basecse(::Type{T}) where {T<:AbstractString} = basecse(cse(T))
basecse(::T) where {T<:AbstractString} = basecse(cse(T))
# Get charset based on CSE
charset(::Type{<:CSE{CS}}) where {CS<:CharSet} = CS
charset(::Type{T}) where {T<:AbstractString} = charset(cse(T))
charset(::T) where {T<:AbstractString} = charset(cse(T))
# Get encoding based on CSE
encoding(::Type{<:CSE{CS,E}}) where {CS<:CharSet,E<:Encoding} = E
# Promotion rules for character set encodings
promote_rule(::Type{Text2CSE}, ::Type{Text1CSE}) = Text2CSE
promote_rule(::Type{Text4CSE}, ::Type{Text1CSE}) = Text4CSE
promote_rule(::Type{Text4CSE}, ::Type{Text2CSE}) = Text4CSE
promote_rule(::Type{T}, ::Type{ASCIICSE}) where {T<:CSE} = T
promote_rule(::Type{T}, ::Type{<:Latin_CSEs}
) where {T<:Union{UTF8CSE,UTF16CSE,UCS2_CSEs,UTF32_CSEs}} = T
promote_rule(::Type{T}, ::Type{_LatinCSE}) where {T<:Union{ASCIICSE,LatinCSE}} = LatinCSE
promote_rule(::Type{T}, ::Type{_UCS2CSE}) where {T<:Union{ASCIICSE,Latin_CSEs,UCS2CSE}} = UCS2CSE
promote_rule(::Type{T}, ::Type{_UTF32CSE}) where {T<:CSE} = UTF32CSE
promote_rule(::Type{T}, ::Type{UTF32CSE}) where {T<:UCS2_CSEs} = UTF32CSE
| CharSetEncodings | https://github.com/JuliaString/CharSetEncodings.jl.git |
|
[
"MIT"
] | 1.0.0 | 596e5adf3856e082d37f4a8ae8de8f56a3a3ce22 | code | 1451 | # Encoding support
#
# Copyright 2017-2018 Gandalf Software, Inc., Scott P. Jones
# Licensed under MIT License, see LICENSE.md
#
# Encodings inspired from collaboration with @nalimilan (Milan Bouchet-Valat) on
# [StringEncodings](https://github.com/nalimilan/StringEncodings.jl)
@api public Encoding, Native1Byte, UTF8Encoding
@api develop encoding_types
struct Encoding{Enc} end
"""List of installed encodings"""
const encoding_types = []
Encoding(s) = Encoding{Symbol(s)}()
const Native1Byte = Encoding{:Byte}
const UTF8Encoding = Encoding{:UTF8}
push!(encoding_types, Native1Byte, UTF8Encoding)
# Allow handling different endian encodings
for (n, l, b, s) in (("2Byte", :LE2, :BE2, "16-bit"),
("4Byte", :LE4, :BE4, "32-bit"),
("UTF16", :UTF16LE, :UTF16BE, "UTF-16"))
nat, swp = BIG_ENDIAN ? (b, l) : (l, b)
natnam = symstr("Native", n)
swpnam = symstr("Swapped", n)
@eval const $natnam = Encoding{$(quotesym("N", n))}
@eval const $swpnam = Encoding{$(quotesym("S", n))}
@eval const $nat = $natnam
@eval const $swp = $swpnam
@eval push!(encoding_types, $natnam, $swpnam)
@eval @api public $natnam, $swpnam
end
show(io::IO, ::Type{Encoding{S}}) where {S} = print(io, "Encoding{:", string(S), "}")
encoding(::Type{T}) where {T<:AbstractString} = encoding(cse(T)) # Default unless overridden
encoding(str::AbstractString) = encoding(cse(str))
| CharSetEncodings | https://github.com/JuliaString/CharSetEncodings.jl.git |
|
[
"MIT"
] | 1.0.0 | 596e5adf3856e082d37f4a8ae8de8f56a3a3ce22 | code | 3182 | # Copyright 2017-2018 Gandalf Software, Inc. (Scott Paul Jones)
# Licensed under MIT License, see LICENSE.md
EncodingStyle(::Type{<:Union{UTF8_CSEs,UTF16CSE}}) = MultiCodeUnitEncoding()
EncodingStyle(::Type{<:CSE}) = SingleCodeUnitEncoding()
EncodingStyle(v::AbstractString) = EncodingStyle(typeof(v))
EncodingStyle(::Type{T}) where {T<:AbstractString} = EncodingStyle(cse(T))
EncodingStyle(::Type{<:SubString{T}}) where {T<:AbstractString} = EncodingStyle(T)
################################################################################
CharSetStyle(::Type{<:CSE}) = CharSetUnicodePlus()
CharSetStyle(::Type{<:Union{Text1CSE, Text2CSE, Text4CSE}}) = CharSetUnknown()
CharSetStyle(::Type{BinaryCSE}) = CharSetBinary()
CharSetStyle(::Type{ASCIICSE}) = CharSetASCIICompat()
CharSetStyle(::Type{<:Latin_CSEs}) = CharSetISOCompat()
CharSetStyle(::Type{<:UCS2_CSEs}) = CharSetBMPCompat()
CharSetStyle(::Type{<:AbstractString}) = CharSetUnicodePlus()
CharSetStyle(::Type{<:AbstractChar}) = CharSetUnicode()
CharSetStyle(::Type{Char}) = CharSetUnicodePlus() # Encodes invalid characters also
CharSetStyle(::Type{UInt8}) = CharSetBinary()
CharSetStyle(::Type{UInt16}) = CharSetUnknown()
CharSetStyle(::Type{UInt32}) = CharSetUnknown()
CharSetStyle(::T) where {T<:AbstractString} = CharSetStyle(cse(T))
CharSetStyle(::T) where {T<:AbstractChar} = CharSetStyle(T)
################################################################################
CompareStyle(::Type{<:CSE}, ::Type{<:CSE}) = CodePointCompare()
CompareStyle(::Type{C}, ::Type{C}) where {C<:CSE} =
ByteCompare()
CompareStyle(::Type{C}, ::Type{C}) where {C<:Union{Word_CSEs,Quad_CSEs}} =
WordCompare()
# This is important because of invalid sequences
CompareStyle(::Type{C}, ::Type{C}) where {C<:RawUTF8CSE} =
CodePointCompare()
CompareStyle(::Type{UTF16CSE}, ::Type{UTF16CSE}) = UTF16Compare()
CompareStyle(::Type{UTF16CSE}, ::Type{<:UCS2_CSEs}) = UTF16Compare()
CompareStyle(::Type{<:UCS2_CSEs}, ::Type{UTF16CSE}) = UTF16Compare()
CompareStyle(::Type{ASCIICSE}, ::Type{<:Union{Binary_CSEs,Latin_CSEs,UTF8_CSEs}}) =
ByteCompare()
CompareStyle(::Type{ASCIICSE}, ::Type{<:Union{Word_CSEs,Quad_CSEs}}) =
WidenCompare()
CompareStyle(::Type{<:Latin_CSEs}, ::Type{<:Latin_CSEs}) =
ByteCompare()
CompareStyle(::Type{<:Latin_CSEs}, ::Type{UTF8_CSEs}) =
ASCIICompare()
CompareStyle(::Type{<:Latin_CSEs}, ::Type{<:Union{Word_CSEs,Quad_CSEs}}) =
WidenCompare()
CompareStyle(::Type{<:UCS2_CSEs}, ::Type{<:Union{ASCIICSE,Binary_CSEs,Latin_CSEs,Quad_CSEs}}) =
WidenCompare()
CompareStyle(::Type{<:UCS2_CSEs}, ::Type{<:UCS2_CSEs}) =
WordCompare()
CompareStyle(::Type{<:UTF32_CSEs},
::Type{<:Union{ASCIICSE,Binary_CSEs,Latin_CSEs,Text2CSE,UCS2_CSEs}}) =
WidenCompare()
CompareStyle(::Type{<:UTF32_CSEs}, ::Type{<:UTF32_CSEs}) =
WordCompare()
CompareStyle(::Type{S}, ::Type{T}) where {S<:AbstractString, T<:AbstractString} =
CompareStyle(cse(S), cse(T))
CompareStyle(::Type{T}, ::Type{T}) where {T<:AbstractString} = ByteCompare()
CompareStyle(A::AbstractString, B::AbstractString) = CompareStyle(typeof(A), typeof(B))
| CharSetEncodings | https://github.com/JuliaString/CharSetEncodings.jl.git |
|
[
"MIT"
] | 1.0.0 | 596e5adf3856e082d37f4a8ae8de8f56a3a3ce22 | code | 627 | # License is MIT: LICENSE.md
using ModuleInterfaceTools
@api test CharSetEncodings
@testset "CharSet" begin
for CS in charset_types
@test CS <: CharSet
nam = sprint(show, CS)
@test endswith(nam, "CharSet") || startswith(nam, "CharSet{:")
end
end
@testset "Encoding" begin
for E in encoding_types
@test E <: Encoding
end
end
@testset "Character Set Encodings" begin
for CS in cse_types
@test CS <: CSE
@test charset(CS) <: CharSet
@test encoding(CS) <: Encoding
end
end
@testset "show charsets" begin
for CS in charset_types
end
end
| CharSetEncodings | https://github.com/JuliaString/CharSetEncodings.jl.git |
|
[
"MIT"
] | 1.0.0 | 596e5adf3856e082d37f4a8ae8de8f56a3a3ce22 | docs | 5246 | # CharSetEncodings
| **Info** | **Windows** | **Linux & MacOS** | **Package Evaluator** | **CodeCov** | **Coveralls** |
|:------------------:|:------------------:|:---------------------:|:-----------------:|:---------------------:|:-----------------:|
| [![][license-img]][license-url] | [![][app-s-img]][app-s-url] | [![][travis-s-img]][travis-url] | [![][pkg-s-img]][pkg-url] | [![][codecov-img]][codecov-url] | [![][coverall-s-img]][coverall-s-url]
| [![][gitter-img]][gitter-url] | [![][app-m-img]][app-m-url] | [![][travis-m-img]][travis-url] | [![][pkg-m-img]][pkg-url] | [![][codecov-img]][codecov-url] | [![][coverall-m-img]][coverall-m-url]
[license-img]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat
[license-url]: LICENSE.md
[gitter-img]: https://badges.gitter.im/Join%20Chat.svg
[gitter-url]: https://gitter.im/JuliaString/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge
[travis-url]: https://travis-ci.org/JuliaString/CharSetEncodings.jl
[travis-s-img]: https://travis-ci.org/JuliaString/CharSetEncodings.jl.svg
[travis-m-img]: https://travis-ci.org/JuliaString/CharSetEncodings.jl.svg?branch=master
[app-s-url]: https://ci.appveyor.com/project/ScottPJones/charsetencodings-jl
[app-m-url]: https://ci.appveyor.com/project/ScottPJones/charsetencodings-jl/branch/master
[app-s-img]: https://ci.appveyor.com/api/projects/status/08ylxl46exltiemd?svg=true
[app-m-img]: https://ci.appveyor.com/api/projects/status/08ylxl46exltiemd/branch/master?svg=true
[pkg-url]: http://pkg.julialang.org/?pkg=CharSetEncodings
[pkg-s-img]: http://pkg.julialang.org/badges/CharSetEncodings_0.6.svg
[pkg-m-img]: http://pkg.julialang.org/badges/CharSetEncodings_0.7.svg
[codecov-url]: https://codecov.io/gh/JuliaString/CharSetEncodings.jl
[codecov-img]: https://codecov.io/gh/JuliaString/CharSetEncodings.jl/branch/master/graph/badge.svg
[coverall-s-url]: https://coveralls.io/github/JuliaString/CharSetEncodings.jl
[coverall-m-url]: https://coveralls.io/github/JuliaString/CharSetEncodings.jl?branch=master
[coverall-s-img]: https://coveralls.io/repos/github/JuliaString/CharSetEncodings.jl/badge.svg
[coverall-m-img]: https://coveralls.io/repos/github/JuliaString/CharSetEncodings.jl/badge.svg?branch=master
## Architecture
This provides the basic types and mode methods for dealing with character sets, encodings,
and character set encodings.
## Types
Currently, there are the following types:
* `CodeUnitTypes` a Union of the 3 codeunit types (UInt8, UInt16, UInt32) for convenience
* `CharSet` a struct type, which is parameterized by the name of the character set and the type needed to represent a code point
* `Encoding` a struct type, parameterized by the name of the encoding
## Built-in Character Sets / Character Set Encodings
* `Binary` For storing non-textual data as a sequence of bytes, 0-0xff
* `ASCII` ASCII (Unicode subset, 0-0x7f)
* `Latin` Latin-1 (ISO-8859-1) (Unicode subset, 0-0xff)
* `UCS2` UCS-2 (Unicode subset, 0-0xd7ff, 0xe000-0xffff, BMP only, no surrogates)
* `UTF32` UTF-32 (Full Unicode, 0-0xd7ff, 0xe000-0x10ffff)
* `UniPlus` Unvalidated Unicode (i.e. like `String`, can contain invalid codepoints)
* `Text1` Unknown 1-byte character set
* `Text2` Unknown 2-byte character set
* `Text4` Unknown 4-byte character set
## Built-in Encodings
* `UTF8Encoding`
* `Native1Byte`
* `Native2Byte`
* `Native4Byte`
* `NativeUTF16`
* `Swapped4Byte`
* `Swapped2Byte`
* `SwappedUTF16`
* `LE2`
* `BE2`
* `LE4`
* `BE4`
* `UTF16LE`
* `UTF16BE`
* `2Byte`
* `4Byte`
* `UTF16`
## Built-in CSEs
* `BinaryCSE`, `Text1CSE`, `ASCIICSE`, `LatinCSE`
* `Text2CSE`, `UCS2CSE`
* `Text4CSE`, `UTF32CSE`
* `UTF8CSE` `UTF32CharSet`, all valid, using `UTF8Encoding`,
conforming to the Unicode Organization's standard,
i.e. no long encodings, surrogates, or invalid bytes.
* `RawUTF8CSE` `UniPlusCharSet`, not validated, using `UTF8Encoding`,
may have invalid sequences, long encodings, encode surrogates and characters
up to `0x7fffffff`
* `UTF16CSE` `UTF32CharSet`, all valid, using `UTF16` Encoding (native order),
conforming to the Unicode standard, i.e. no out of order or isolated surrogates.
## Internal Unicode subset types
* `_LatinCSE` Indicates has at least 1 character > 0x7f, all <= 0xff
* `_UCS2CSE` Indicates has at least 1 character > 0xff, all <= 0xffff
* `_UTF32CSE` Indicates has at least 1 non-BMP character
## API
The `cse` function returns the character set encoding for a string type, string.
Returns `RawUTF8CSE` as a fallback for `AbstractString` (i.e. same as `String`)
The `charset` function returns the character set for a string type, string, character type, or character.
The `encoding` function returns the encoding for a type or string.
The `codeunit` function returns the code unit used for a character set encoding
The `cs"..."` string macro creates a CharSet type with that name
The `enc"..."` string macro creates an Encoding type with that name
The `@cse(cs, enc)` macro creates a character set encoding with the given character set and encoding
Also Exports the helpful constant `Bool` flags `BIG_ENDIAN` and `LITTLE_ENDIAN`
| CharSetEncodings | https://github.com/JuliaString/CharSetEncodings.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | code | 447 | using Documenter
push!(LOAD_PATH, "../../src")
using GenieAuthorisation
makedocs(
sitename = "GenieAuthorisation - User Authorisation for Genie",
format = Documenter.HTML(prettyurls = false),
pages = [
"Home" => "index.md",
"GenieAuthorisation API" => [
"GenieAuthorisation" => "API/genieauthorisation.md",
]
],
)
deploydocs(
repo = "github.com/GenieFramework/GenieAuthorisation.jl.git",
)
| GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | code | 313 | module CreateTableRoles
import SearchLight.Migrations: create_table, column, primary_key, add_index, drop_table
function up()
create_table(:roles) do
[
primary_key()
column(:name, :string, limit = 100)
]
end
add_index(:roles, :name)
end
function down()
drop_table(:roles)
end
end
| GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | code | 337 | module CreateTablePermissions
import SearchLight.Migrations: create_table, column, primary_key, add_index, drop_table
function up()
create_table(:permissions) do
[
primary_key()
column(:name, :string, limit = 100)
]
end
add_index(:permissions, :name)
end
function down()
drop_table(:permissions)
end
end
| GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | code | 391 | module CreateTableRolesUsers
import SearchLight.Migrations: create_table, column, primary_key, add_index, drop_table
function up()
create_table(:rolesusers) do
[
primary_key()
column(:roles_id, :int)
column(:users_id, :int)
]
end
add_index(:rolesusers, :roles_id)
add_index(:rolesusers, :users_id)
end
function down()
drop_table(:rolesusers)
end
end
| GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | code | 391 | module CreateTablePermissionsRoles
import SearchLight.Migrations: create_table, column, primary_key, add_index, drop_table
function up()
create_table(:permissionsroles) do
[
primary_key()
column(:permissions_id, :int)
column(:roles_id, :int)
]
end
add_index(:permissionsroles, :permissions_id)
end
function down()
drop_table(:permissionsroles)
end
end
| GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | code | 3079 | module GenieAuthorisation
using Reexport
using Genie
using SearchLight, SearchLight.Relationships
import GeniePlugins
@reexport using GenieAuthentication
export Role, Permission
export assign_role, assign_permission
export has_role, has_permission, @authorised!
struct UnexpectedTypeException <: Exception
expected_type::String
received_type::String
end
struct UndefinedPermissionException <: Exception
permission::String
end
Base.@kwdef mutable struct Role <: AbstractModel
id::DbId = DbId()
name::String = ""
end
Role(name::Union{String,Symbol}) = Role(name = string(name))
Base.@kwdef mutable struct Permission <: AbstractModel
id::DbId = DbId()
name::String = ""
end
Permission(name::Union{String,Symbol}) = Permission(name = string(name))
function assign_role(user::U, role::Role)::Bool where {U<:AbstractModel}
Relationship!(user, role)
true
end
function assign_permission(role::Role, permission::Permission) :: Bool
Relationship!(role, permission)
true
end
function has_role(user::U, role::Role)::Bool where {U<:AbstractModel}
isrelated(user, role)
end
function has_role(user::U, role::Union{String,Symbol})::Bool where {U<:AbstractModel}
has_role(user, findone(Role, name = string(role)))
end
function fetch_permission(permission::Union{Permission,String,Symbol}) :: Union{Permission,Nothing}
isa(permission, Permission) || (permission = findone(Permission, name = string(permission)))
permission
end
function has_permission(role::Role, permission::Union{Permission,String,Symbol})::Bool
permission = fetch_permission(permission)
permission === nothing && return false
isrelated(role, permission)
end
function has_permission(user::U, permission::Union{Permission,String,Symbol})::Bool where {U<:AbstractModel}
permission = fetch_permission(permission)
permission === nothing && return false
isrelated(user, permission, through = [Role])
end
function has_permission(u::Nothing, permission)::Bool
false
end
macro authorised!(permission, exception = Genie.Exceptions.NotFoundException("Page"))
:(has_permission($(esc( :( Main.UserApp.current_user() ) )), $(esc(permission))) || throw($exception))
end
"""
install(dest::String; force = false, debug = false) :: Nothing
Copies the plugin's files into the host Genie application.
"""
function install(dest::String; force = false, debug = false) :: Nothing
# automatically install the GenieAuthentication plugin -- however, do not force the install
GenieAuthentication.install(dest; force = false, debug = debug)
src = abspath(normpath(joinpath(pathof(@__MODULE__) |> dirname, "..", GeniePlugins.FILES_FOLDER)))
debug && @info "Preparing to install from $src into $dest"
debug && @info "Found these to install $(readdir(src))"
for f in readdir(src)
debug && @info "Processing $(joinpath(src, f))"
debug && @info "$(isdir(joinpath(src, f)))"
isdir(joinpath(src, f)) || continue
debug && "Installing from $(joinpath(src, f))"
GeniePlugins.install(joinpath(src, f), dest, force = force)
end
nothing
end
end
| GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | code | 109 | using GenieAuthorisation
using Test
@testset "GenieAuthorisation.jl" begin
# Write your tests here.
end
| GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | docs | 7932 | # GenieAuthorisation
Role Based Authorisation (RBA) plugin for `Genie.jl`
## Installation
The `GenieAuthorisation.jl` package is a role based authorisation plugin for `Genie.jl`, the highly productive Julia web framework.
As such, it requires installation within the environment of a `Genie.jl` MVC application, allowing the plugin to install
its files.
### Configuring authentication before using authorisation
`GenieAuthorisation.jl` works in tandem with `GenieAuthentication.jl`, the authentication plugin for `Genie.jl` apps.
In fact, `GenieAuthorisation.jl` adds an authorisation layer on top of the authentication features provided by `GenieAuthentication.jl`.
As such, first, please make sure that `GenieAuthentication.jl` is configured for your `Genie.jl` application, following the
instructions at: <https://github.com/GenieFramework/GenieAuthentication.jl>
With the `GenieAuthentication.jl` plugin installed, make sure you configure authenticated access to the areas you want to
further protect with role based authorisation. So the first step is to add user authentication to the app. Then refine access via
authorisation.
### Add the plugin
Now that your application supports user authentication, it's time to add user authorisation.
First, add the plugin (make sure you are in the environment of the `Genie.jl` app you want to protect with autorisation):
```julia
julia> ]
(MyGenieApp) pkg> add GenieAuthorisation
```
Once added, we can use its `install` function to add its files to the `Genie.jl` app (required only upon installation):
```julia
julia> using GenieAuthorisation
julia> GenieAuthorisation.install(@__DIR__)
```
The above command will set up the plugin's files within your `Genie.jl` app (will potentially add new views, controllers, models, migrations, initializers, etc).
## Usage
The bulk of the authorisation features are provided by the package itself together with a series of database migrations which
set up the database tables needed to configure the RBA system.
### Set up the database
The plugin needs DB support to store its configuration (roles, permissions and various relations).
You will find 4 new migration files within the `db/migrations/` folder. We need to run then, either by running all the migrations:
```julia
julia> using SearchLight
julia> SearchLight.Migration.all_up!!()
```
Or by individually running the 4 migrations:
```julia
julia> using SearchLight
julia> SearchLight.Migration.up("CreateTableRoles")
julia> SearchLight.Migration.up("CreateTablePermissions")
julia> SearchLight.Migration.up("CreateTableRolesUsers")
julia> SearchLight.Migration.up("CreateTablePermissionsRoles")
```
This will create all the necessary table.
### Users, roles, and permissions
A role based authorisation system implements access control through permissions. That is, certain features are accessible
only for users that have the necessary permission. For instance, this is how we require authorisation for a `user_admin` permission
at route level:
```julia
route("/admin/users") do; @authorised!("users_admin")
# code can be accessed only by users with the `users_admin` permission
end
```
Permissions, however, are not assigned directly to users, but to roles. As such, a role can have multiple permissions - like
for example an `admin` role would have all the possible permissions. Finally, the users are assigned roles - getting access
to the role's respective permissions. A role can have any number of permissions and a user can have any number of roles.
`GenieAuthorisation.jl` exposes an API which makes checking users permissions straightforward, without needing to handle
the actual roles. However, the roles make permission assignment manageable: we bundle permissions
into roles and then assign the roles to the users. This way, when we need to remove permissions from a user, we just
remove the role and eliminate the risk of failing to remove all the forbidden permissions.
#### Creating permissions and roles
Given that permissions and roles are stored in the database, we use `SearchLight.jl` to manage the data:
```julia
using GenieAuthorisation
# Create two roles, "user" and "admin"
for r in ["user", "admin"]
findone_or_create(Role, name = r) |> save!
end
# Create some permissions
for p in ["create", "read", "update", "delete"]
findone_or_create(Permission, name = p) |> save!
end
```
Now that the roles and the permissions are created, we need to assign permissions to roles:
```julia
using GenieAuthorisation
assign_permission(findone(Role, name = "admin"), findone(Permission, name = "create"))
assign_permission(findone(Role, name = "admin"), findone(Permission, name = "read"))
assign_permission(findone(Role, name = "admin"), findone(Permission, name = "update"))
assign_permission(findone(Role, name = "admin"), findone(Permission, name = "delete"))
assign_permission(findone(Role, name = "user"), findone(Permission, name = "read"))
```
We have assigned "create", "read", "update" and "delete" permissions to the `admin` role, and "read" permissions to the
`user` role.
Now we need to assign roles to our users -- for example making the user with the username `essenciary` an "admin":
```julia
using GenieAuthorisation, GenieAuthentication, Users
assign_role(findone(User, username = "essenciary"), findone(Role, name = "admin"))
```
---
**HEADS UP**
Users must be explicitly assigned roles in order to have any permissions.
Permissions are made available only through roles and this means that users without a role do not have any kind of permissions.
It makes sense to automate role assignment, for example by assigning a default basic role upon user registration.
---
### Autorising access
Once we have permissions, roles, and users, and we have defined the relationships between them, we can enforce user
authorisation within the app.
#### `@authorised!(<permission>)`
The `@authorised!` macro checks that the current user has the `<permission>` permission - if not, an exception is automatically
thrown, stopping the current thread of execution:
```julia
using GenieAuthorisation
route("/admin/users/delete/:user_id") do; @authorised!("delete")
# code can be accessed only by users with the `users_admin` permission
end
```
#### `has_permission(<user>, <permission>)
We can also use the `has_permission` function to check if a user has the necessary permissions. The function returns a
`boolean` allowing us to implement conditional logic based on the status of the authorisation:
```julia
<% if has_permission(current_user(), "update") || has_permission(current_user(), "delete") %>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown">User management</a>
<div class="dropdown-menu">
<% if has_permission(current_user(), "update") %>
<a class="dropdown-item" href="/admin/users/edit/:user_id">Edit user</a>
<% end %>
<% if has_permission(current_user(), "delete") %>
<a class="dropdown-item" href="/admin/users/delete/:user_id">Delete user</a>
<% end %>
</div>
</li>
<% end %>
```
### Deleting authorisation
Deleting authorisation is done by removing the relationships stored in the database, using the `SearchLight.jl` API.
For example, to remove a permission from a role:
```julia
using SearchLight, GenieAuthorisation
Relationship!(findone(Role, name = "admin"), findone(Permission, name = "delete")) |> delete
```
Or a role from a user:
```julia
using SearchLight, GenieAuthorisation, GenieAuthentication, Users
Relationship!(findone(User, username = "essenciary"), findone(Role, name = "admin")) |> delete
```
Finally, to remove roles or permissions, we delete the respective entities:
```julia
using SearchLight, GenieAuthorisation
# remove the `delete` permission
delete(findone(Permission, name = "delete"))
# remove the `admin` role
delete(findone(Role, name = "admin"))
```
| GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | docs | 53 | # GenieAuthorisation
User Authorisation for Genie.jl | GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 2.0.1 | 9822f4fedd372686c1b1fc26403c92fc2f4c4e83 | docs | 96 | ```@meta
CurrentModule = GenieAuthorisation
```
```@autodocs
Modules = [GenieAuthorisation]
``` | GenieAuthorisation | https://github.com/GenieFramework/GenieAuthorisation.jl.git |
|
[
"MIT"
] | 0.1.3 | da9adb5a5f7826e63999c55458ccf73ae2de44ac | code | 261 | using Documenter, CurlHTTP
makedocs(
sitename="CurlHTTP.jl Documentation",
format=Documenter.HTML(
prettyurls = false,
edit_link="main",
),
modules=[CurlHTTP],
)
deploydocs(
repo = "github.com/bluesmoon/CurlHTTP.jl.git",
)
| CurlHTTP | https://github.com/bluesmoon/CurlHTTP.jl.git |
|
[
"MIT"
] | 0.1.3 | da9adb5a5f7826e63999c55458ccf73ae2de44ac | code | 29972 | """
Wrapper around [`LibCURL`](https://github.com/JuliaWeb/LibCURL.jl) to make it more Julia like.
This module reexports `LibCURL` so everything available in `LibCURL` will be available when this module is used.
See https://curl.se/libcurl/c/libcurl-tutorial.html for a tutorial on using libcurl in C. The Julia interface should be similar.
# Examples
## GET a URL and read the response from the internal buffer
```julia
using CurlHTTP
curl = CurlEasy(
url="https://postman-echo.com/get?foo=bar",
method=CurlHTTP.GET,
verbose=true
)
res, http_status, errormessage = curl_execute(curl)
# curl.userdata[:databuffer] is a Vector{UInt8} containing the bytes of the response
responseBody = String(curl.userdata[:databuffer])
# curl.userdata[:responseHeaders] is a Vector{String} containing the response headers
responseHeaders = curl.userdata[:responseHeaders]
```
## POST to a URL and read the response with your own callback
```julia
using CurlHTTP
curl = CurlEasy(
url="https://postman-echo.com/post",
method=CurlHTTP.POST,
verbose=true
)
requestBody = "{\"testName\":\"test_writeCB\"}"
headers = ["Content-Type: application/json"]
databuffer = UInt8[]
res, http_status, errormessage = curl_execute(curl, requestBody, headers) do d
if isa(d, Array{UInt8})
append!(databuffer, d)
end
end
responseBody = String(databuffer)
```
## Multiple concurrent requests using CurlMulti
```julia
using CurlHTTP
curl = CurlMulti()
for i in 1:3
local easy = CurlEasy(
url="https://postman-echo.com/post?val=\$i",
method=CurlHTTP.POST,
verbose=true,
)
requestBody = "{\"testName\":\"test_multi_writeCB\",\"value\":\$i}"
headers = ["Content-Type: application/json", "X-App-Value: \$(i*5)"]
CurlHTTP.curl_setup_request_response(
easy,
requestBody,
headers
)
curl_multi_add_handle(curl, easy)
end
res = curl_execute(curl)
responses = [p.userdata for p in curl.pool] # userdata contains response data, status code and error message
```
"""
module CurlHTTP
using Reexport
using UUIDs
@reexport using LibCURL
export
curl_url_escape,
curl_add_headers,
curl_setup_request,
curl_execute,
curl_cleanup,
curl_perform,
curl_response_status,
curl_error_to_string,
CurlHandle,
CurlEasy,
CurlMulti
function __init__()
curl_global_init(CURL_GLOBAL_ALL)
end
"""
HTTP Methods recognized by `CurlHTTP`. Current values are:
* _GET_: Make a GET request
* _POST_: Upload data using POST
* _HEAD_: Make a HEAD request and specify no response body
* _DELETE_: Make a DELETE request
* _PUT_: Currently not supported
* _OPTIONS_: Make an OPTIONS request
"""
@enum HTTPMethod GET=1 POST=2 HEAD=3 DELETE=4 PUT=5 OPTIONS=6
"""
Internal markers for the data channel
"""
@enum ChannelMarkers EOF=-1
const CRLF = UInt8.(['\r', '\n'])
const VERBOSE_INFO = [CURLINFO_TEXT, CURLINFO_HEADER_IN, CURLINFO_HEADER_OUT, CURLINFO_SSL_DATA_IN, CURLINFO_SSL_DATA_OUT]
"""
Default user agent to use if not otherwise specified. This allows an application to set the user agent string
at __init__ time rather than at constructor time.
Use [`CurlHTTP.setDefaultUserAgent()`](@ref) to set it. Set it to `nothing` to unset it.
"""
DEFAULT_USER_AGENT = nothing
"""
Set the default user agent string to use for all requests. Set this to `nothing` to disable setting the user agent string.
"""
setDefaultUserAgent(ua::Union{AbstractString, Nothing}) = global DEFAULT_USER_AGENT = ua
"""
Abstract type representing all types of Curl Handles. Currently `CurlEasy` and `CurlMulti`.
"""
abstract type CurlHandle end
"""
Wrapper around a `curl_easy` handle. This is what we get from calling `curl_easy_init`.
Most `curl_easy_*` functions will work on a `CurlEasy` object without any other changes.
## Summary
`struct CurlEasy <:` [`CurlHandle`](@ref)
## Fields
`handle::Ptr`
: A C pointer to the curl_easy handle
`headers::Ptr`
: A C pointer to the list of headers passed on to curl. We hold onto this to make sure we can free allocated memory when required.
`uuid::UUID`
: A unique identifier for this curl handle. Used internally to identify a handle within a pool.
`userdata::Dict`
: A dictionary of user specified data. You may add anything you want to this and it will be passed along with the curl handle to all functions.
This dictionary will also be populated by several convenience functions to add the `:http_status`, `:errormessage`, and response header (`:databuffer`).
All data added by internal code will use `Symbol` keys.
## Constructors
`CurlEasy(curl::Ptr)`
: Create a `CurlEasy` wrapper around an existing `LibCURL` `curl` handle.
`CurlEasy(; url::String, method::`[`HTTPMethod`](@ref)`, verbose::Bool, certpath::String, keypath::String, cacertpath::String, useragent::String|Nothing)`
: Create a new `curl` object with default settings and wrap it. The default settings are:
* FOLLOWLOCATION
* SSL_VERIFYPEER
* SSL_VERIFYHOST
* SSL_VERSION (highest possible up to TLS 1.3)
* HTTP_VERSION (H2 over TLS or HTTP/1.1)
* TCP_FASTOPEN disabled
* TCP_KEEPALIVE
* ACCEPT_ENCODING best supported
* TRANSFER_ENCODING
* DNS_CACHE_TIMEOUT disabled
Additionally the following options are set based on passed in parameters:
* POST if `method` is POST
* HTTPGET if `method` is GET
* NOBODY if `method` is HEAD
* CUSTOMREQUEST if `method` is HEAD, DELETE, or OPTIONS
* VERBOSE if `verbose` is true
* SSLCERT if `certpath` is set
* SSLKEY if `certpath` and `keypath` are set
* CAINFO defaults to `LibCURL.cacert` but can be overridden with `cacertpath`
* URL if `url` is set
* USERAGENT if `useragent` is set to something other than `nothing`.
"""
mutable struct CurlEasy <: CurlHandle
handle::Ptr
headers::Ptr
uuid::UUID
userdata::Dict
CurlEasy(curl::Ptr) = finalizer(curl_cleanup, new(curl, C_NULL, UUIDs.uuid1(), Dict()))
function CurlEasy(;
url::AbstractString = "",
method::HTTPMethod = GET,
verbose::Bool = false,
certpath::AbstractString = "",
keypath::AbstractString = "",
cacertpath::AbstractString = "",
useragent::Union{AbstractString, Nothing} = DEFAULT_USER_AGENT
)
curl = curl_easy_init()
if method == GET
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1) # Use HTTP Get
elseif method == POST
curl_easy_setopt(curl, CURLOPT_POST, 1) # Use HTTP Post
elseif method == HEAD
curl_easy_setopt(curl, CURLOPT_NOBODY, 1) # Use HTTP Head
elseif method == DELETE
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1) # Use HTTP Delete
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE")
elseif method == OPTIONS
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1) # Use HTTP Options
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "OPTIONS")
else
throw(ArgumentError("Method `$method' is not currently supported"))
end
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1) # Follow HTTP redirects
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1) # Verify the peer's SSL cert
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2) # Verify the server's Common Name
curl_easy_setopt(curl, CURLOPT_SSLVERSION, 7<<16) # Try highest version up to TLS 1.3
curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, 4) # Use H2 over SSL or HTTP/1.1 otherwise
curl_easy_setopt(curl, CURLOPT_TCP_FASTOPEN, 0) # Do not use TCP Fastopen since it prevents connection reuse
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1) # Use TCP Keepalive
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "") # Use best supported encoding (compression) method. gzip or deflate
curl_easy_setopt(curl, CURLOPT_TRANSFER_ENCODING, 1) # Use transfer encoding
curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 0) # Do not cache DNS in curl
if !isnothing(useragent)
curl_easy_setopt(curl, CURLOPT_USERAGENT, useragent)
end
# Do we want verbose logging to stderr
curl_easy_setopt(curl, CURLOPT_VERBOSE, verbose ? 1 : 0)
# If config has a client cert, use it
if !isempty(certpath)
if !isfile(certpath)
throw(ArgumentError("Could not find the certpath `$certpath'"))
end
curl_easy_setopt(curl, CURLOPT_SSLCERT, certpath)
# Client certs will need cert private key
if !isempty(keypath)
if !isfile(keypath)
throw(ArgumentError("Could not find the keypath `$keypath'"))
end
curl_easy_setopt(curl, CURLOPT_SSLKEY, keypath)
end
end
# If config has a cacert (for self-signed servers), use it
if !isempty(cacertpath)
if !isfile(cacertpath)
throw(ArgumentError("Could not find the cacertpath `$cacertpath'"))
end
curl_easy_setopt(curl, CURLOPT_CAINFO, cacertpath)
else
curl_easy_setopt(curl, CURLOPT_CAINFO, LibCURL.cacert)
end
if !isempty(url)
curl_easy_setopt(curl, CURLOPT_URL, url)
end
return CurlEasy(curl)
end
end
"""
Wrapper around a `curl_multi` handle. This is what we get from calling `curl_multi_init`
## Summary
`struct CurlMulti <:` [`CurlHandle`](@ref)
## Fields
`handle::Ptr`
: A C pointer to the curl_multi handle
`pool::`[`CurlEasy`](@ref)`[]`
: An array of [`CurlEasy`](@ref) handles that are added to this `CurlMulti` handle. These can be added via the constructor or via a call to `curl_multi_add_handle`, and
may be removed via a call to `curl_multi_remove_handle`.
## Constructors
`CurlMulti()`
: Default constructor that calls `curl_multi_init` and sets up an empty pool
`CurlMulti(::`[`CurlEasy`](@ref)`[])`
: Constructor that accepts a Vector of [`CurlEasy`](@ref) objects, creates a `curl_multi` handle, and adds the easy handles to it.
"""
mutable struct CurlMulti <: CurlHandle
handle::Ptr
pool::Vector{CurlEasy}
CurlMulti() = finalizer(curl_cleanup, new(curl_multi_init(), CurlEasy[]))
function CurlMulti(pool::Vector{CurlEasy})
multi = CurlMulti()
for easy in pool
curl_multi_add_handle(multi.handle, easy.handle)
push!(multi.pool, easy)
end
multi
end
end
"""
Cleanup everything created by the [`CurlEasy`](@ref) constructor. See the [upstream docs](https://curl.se/libcurl/c/curl_easy_cleanup.html) for more details.
"""
LibCURL.curl_easy_cleanup(curl::CurlEasy) = (if curl.headers != C_NULL curl_slist_free_all(curl.headers); curl.headers = C_NULL; end; st=curl_easy_cleanup(curl.handle); curl.handle=C_NULL; st)
"""
Cleanup everything created by the [`CurlMulti`](@ref) constructor. See the [upstream docs](https://curl.se/libcurl/c/curl_multi_cleanup.html) for more details.
"""
LibCURL.curl_multi_cleanup(curl::CurlMulti) = (for easy in curl.pool curl_multi_remove_handle(curl.handle, easy.handle); curl_easy_cleanup(easy); end; empty!(curl.pool); curl_multi_cleanup(curl.handle))
"""
Perform a [`CurlEasy`](@ref) transfer synchronously. See the [upstream docs](https://curl.se/libcurl/c/curl_easy_perform.html) for more details.
"""
LibCURL.curl_easy_perform(curl::CurlEasy) = (res = curl_easy_perform(curl.handle); if !isnothing(get(curl.userdata, :data_channel, nothing)) put!(curl.userdata[:data_channel], EOF); end; res)
"""
Set options for the [`CurlEasy`](@ref) handle. See the [upstream docs](https://curl.se/libcurl/c/curl_easy_setopt.html) for all possible options, and links to documentation for each option.
"""
LibCURL.curl_easy_setopt(curl::CurlEasy, opt::Any, ptrval::Integer) = curl_easy_setopt(curl.handle, opt, ptrval)
LibCURL.curl_easy_setopt(curl::CurlEasy, opt::Any, ptrval::Array{T,N} where N) where T = curl_easy_setopt(curl.handle, opt, ptrval)
LibCURL.curl_easy_setopt(curl::CurlEasy, opt::Any, ptrval::Ptr) = curl_easy_setopt(curl.handle, opt, ptrval)
LibCURL.curl_easy_setopt(curl::CurlEasy, opt::Any, ptrval::AbstractString) = curl_easy_setopt(curl.handle, opt, ptrval)
LibCURL.curl_easy_setopt(curl::CurlEasy, opt::Any, param::Any) = curl_easy_setopt(curl.handle, opt, param)
"""
Clone a [`CurlEasy`](@ref) handle. See the [upstream docs](https://curl.se/libcurl/c/curl_easy_duphandle.html) for more details.
"""
LibCURL.curl_easy_duphandle(curl::CurlEasy) = CurlEasy(curl_easy_duphandle(curl.handle))
"""
URL escape a Julia string using a [`CurlEasy`](@ref) handle to make it safe for use as a URL.
See the [upstream docs](https://curl.se/libcurl/c/curl_easy_escape.html)
The return value is a Julia string with memory owned by Julia, so there's no risk of leaking memory.
"""
function LibCURL.curl_easy_escape(curl::CurlEasy, s, l)
s_esc = curl_easy_escape(curl.handle, s, l)
s_len = ccall(:strlen, Csize_t, (Ptr{Cvoid}, ), s_esc)
s_ret = Array{UInt8}(undef, s_len)
unsafe_copyto!(pointer(s_ret), s_esc, s_len)
curl_free(s_esc)
String(s_ret)
end
"""
curl_url_escape(::CurlEasy, ::String) → String
curl_url_escape(::String) → String
Use curl to do URL escaping
"""
curl_url_escape(curl::CurlEasy, s::AbstractString) = curl_easy_escape(curl, s, 0)
curl_url_escape(s::AbstractString) = curl_url_escape(CurlEasy(curl_easy_init()), s)
"""
Cleanup the [`CurlHandle`](@ref) automatically determining what needs to be done for `curl_easy` vs `curl_multi` handles.
In general, this will be called automatically when the [`CurlHandle`](@ref) gets garbage collected.
"""
curl_cleanup(curl::CurlEasy) = curl_easy_cleanup(curl)
curl_cleanup(curl::CurlMulti) = curl_multi_cleanup(curl)
"""
Perform all [`CurlEasy`](@ref) transfers attached to a [`CurlMulti`](@ref) handle asynchronously. See the [upstream docs](https://curl.se/libcurl/c/curl_multi_perform.html) for more details.
"""
LibCURL.curl_multi_perform(curl::CurlMulti, still_running::Ref{Cint}) = curl_multi_perform(curl.handle, still_running)
function LibCURL.curl_multi_perform(curl::CurlMulti)
still_running = Ref{Cint}(1)
numfds = Ref{Cint}()
while still_running[] > 0
mc = curl_multi_perform(curl, still_running)
if mc == CURLM_OK
mc = curl_multi_wait(curl.handle, C_NULL, 0, 1000, numfds)
end
if mc != CURLM_OK
# COV_EXCL_START
@error "curl_multi failed, code $(mc)."
return mc
# COV_EXCL_STOP
end
end
CURLM_OK
end
"""
Run either `curl_easy_perform` or `curl_multi_perform` depending on the type of handle passed in.
"""
curl_perform(curl::CurlEasy) = curl_easy_perform(curl)
curl_perform(curl::CurlMulti) = curl_multi_perform(curl)
"""
Adds a [`CurlEasy`](@ref) handle to the [`CurlMulti`](@ref) pool. See the [upstream docs](https://curl.se/libcurl/c/curl_multi_add_handle.html)
"""
function LibCURL.curl_multi_add_handle(multi::CurlMulti, easy::CurlEasy)
push!(multi.pool, easy)
curl_multi_add_handle(multi.handle, easy.handle)
end
"""
Remove a [`CurlEasy`](@ref) handle from the [`CurlMulti`](@ref) pool. See the [upstream docs](https://curl.se/libcurl/c/curl_multi_remove_handle.html).
Pass in either the [`CurlEasy`](@ref) handle or its `CurlHandle.uuid`.
"""
function LibCURL.curl_multi_remove_handle(multi::CurlMulti, easy::CurlEasy)
filter!(pool_entry -> pool_entry.uuid != easy.uuid, multi.pool)
curl_multi_remove_handle(multi.handle, easy.handle)
end
LibCURL.curl_multi_remove_handle(multi::CurlMulti, easy_uuid::AbstractString) = curl_multi_remove_handle(multi, Base.UUID(easy_uuid))
function LibCURL.curl_multi_remove_handle(multi::CurlMulti, easy_uuid::Base.UUID)
easy = findfirst(pool_entry -> pool_entry.uuid == easy_uuid, multi.pool)
if isnothing(easy)
return nothing
end
easy = multi.pool[easy]
curl_multi_remove_handle(multi, easy)
end
"""
Run common housekeeping tasks required by a curl callback function.
This function should be called from a curl WRITE or HEADER callback function. It does the following:
1. Calculate the number of bytes read
2. Copy bytes into a Vector{UInt8}
3. Convert any non-null userdata parameter to a julia type
It then returns a tuple of these three values.
"""
function curl_cb_preamble(curlbuf::Ptr{Cvoid}, s::Csize_t, n::Csize_t, p_ctxt::Ptr{Cvoid})
sz = s * n
data = Array{UInt8}(undef, sz)
ccall(:memcpy, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, UInt64), data, curlbuf, sz)
if p_ctxt == C_NULL
j_ctxt = nothing
else
j_ctxt = unsafe_pointer_to_objref(p_ctxt)
end
(sz, data, j_ctxt)
end
"""
Default write callback that puts the data stream as a `Vector{UInt8}` onto a `Channel` passed in via `curl_easy_setopt(CURLOPT_WRITEDATA)`.
This callback is called by curl when data is available to be read and is set up in [`curl_setup_request`](@ref)
"""
function curl_write_cb(curlbuf::Ptr{Cvoid}, s::Csize_t, n::Csize_t, p_ctxt::Ptr{Cvoid})::Csize_t
(sz, data, ch) = curl_cb_preamble(curlbuf, s, n, p_ctxt)
@debug "Body sending $sz bytes"
put!(ch, data)
sz::Csize_t
end
"""
Default header callback that puts the current header as a `crlf` terminate `String` onto a `Channel` passed in via `curl_easy_setopt(CURLOPT_HEADERDATA)`.
This callback is called by curl when header data is available to be read and is set up in [`curl_setup_request`](@ref)
"""
function curl_header_cb(curlbuf::Ptr{Cvoid}, s::Csize_t, n::Csize_t, p_ctxt::Ptr{Cvoid})::Csize_t
(sz, data, ch) = curl_cb_preamble(curlbuf, s, n, p_ctxt)
headerline = String(data)
@debug "Header sending $(sz) bytes"
put!(ch, headerline == "\r\n" ? EOF : headerline)
sz::Csize_t
end
"""
[Internal] curl debug callback to log informational text, header data, and SSL data transferred over the network.
This will only run if curl is configured in verbose mode.
"""
function curl_debug_cb(curl::Ptr{Cvoid}, type::Cint, curlbuf::Ptr{Cvoid}, sz::Csize_t, p_ctxt::Ptr{Cvoid})::Csize_t
if type ∉ VERBOSE_INFO
return Culong(0)
end
data = Array{UInt8}(undef, sz)
ccall(:memcpy, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, UInt64), data, curlbuf, sz)
@info String(data)
Culong(0)
end
function _create_default_buffer_handler(curl::CurlEasy, buffername::Symbol, buffertype::DataType=UInt8)
buffer = curl.userdata[buffername] = buffertype[]
if isbitstype(buffertype)
(mtd, expectedtype) = (append!, typeof(buffer))
else
(mtd, expectedtype) = (push!, buffertype)
end
return data -> if isa(data, expectedtype)
mtd(buffer, data)
else
@warn "$buffername got data of type $(typeof(data)) expected $(expectedtype)"
end
end
"""
Add a vector of headers to the curl object
"""
function curl_add_headers(curl::CurlEasy, headers::Vector{String}; append::Bool=false)
if !append && curl.headers != C_NULL
curl_slist_free_all(curl.headers)
curl.headers = C_NULL
end
for header in headers
curl.headers = curl_slist_append(curl.headers, header)
end
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl.headers)
return curl
end
"""
Prepare a [`CurlEasy`](@ref) object for making a request.
* Adds the `requestBody` and a corresponding `Content-Length`
* Adds headers
* If `data_channel` or `header_channel` are set, then sets up a default WRITE/HEADER callback that writes to that Channel
* If `url` is set, sets the request URL
"""
function curl_setup_request(
curl::CurlEasy,
requestBody::String,
headers::Vector{String} = String[];
data_channel::Union{Channel,Nothing} = nothing,
header_channel::Union{Channel,Nothing} = nothing,
url::AbstractString = ""
)
if !isempty(url)
curl_easy_setopt(curl, CURLOPT_URL, url)
end
curl_add_headers(curl, headers)
curl.userdata[:headers] = headers
if !isempty(requestBody)
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, ncodeunits(requestBody))
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, requestBody)
curl.userdata[:requestBody] = requestBody
curl_add_headers(curl, ["Content-Length: $(ncodeunits(requestBody))"]; append=true)
end
if !isnothing(data_channel)
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, @cfunction(curl_write_cb, Csize_t, (Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid})))
curl_easy_setopt(curl, CURLOPT_WRITEDATA, Base.unsafe_convert(Ptr{Cvoid}, Base.cconvert(Ptr{Cvoid}, Ref(data_channel))))
curl.userdata[:data_channel] = data_channel
end
if !isnothing(header_channel)
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, @cfunction(curl_header_cb, Csize_t, (Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid})))
curl_easy_setopt(curl, CURLOPT_HEADERDATA, Base.unsafe_convert(Ptr{Cvoid}, Base.cconvert(Ptr{Cvoid}, Ref(header_channel))))
curl.userdata[:header_channel] = header_channel
end
# Add a debug handler to log wire transfer data
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, @cfunction(curl_debug_cb, Csize_t, (Ptr{Cvoid}, Cint, Ptr{Cvoid}, Csize_t, Ptr{Cvoid})))
errorbuffer = Array{UInt8}(undef, CURL_ERROR_SIZE)
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorbuffer)
curl.userdata[:errorbuffer] = errorbuffer
return curl
end
"""
Setup a Channel for the default response handlers to write to.
"""
function setup_response_handler(data_handler::Function, uuid::UUID)
@debug "Creating channel for $uuid"
return Channel() do chnl
@debug "Starting channel handler for $uuid"
@debug "Going to read from channel for $uuid"
for d in chnl
if d == EOF
@debug "Removing channel for $uuid"
close(chnl)
break
else
@debug "Received $(length(d)) bytes"
data_handler(d)
end
end
@debug "Finished channel handler for $uuid"
end
end
setup_response_handler(::Nothing, ::Any) = nothing
"""
Setup the request object and response handlers in preparation to execute a request.
When using the [`CurlEasy`](@ref) interface, this method is called internally by [`curl_execute`](@ref), however when using the
[`CurlMulti`](@ref) interface, it is necessary to call this on every [`CurlEasy`](@ref) handle added to the [`CurlMulti`](@ref) handle.
This method allows you to set up your own response data and header handlers that receive streamed data. If you do
not pass in a handler, default handlers will be set up that write binary data as bytes (`Vector{UInt8}`) to
`curl.userdata[:databuffer]` and an array of String response headers (`Vector{String}`) to `curl.userdata[:responseHeaders]`.
## Arguments
`curl::`[`CurlEasy`](@ref)
: The [`CurlEasy`](@ref) handle to operate on
`requestBody::String`
: Any request body text that should be passed on to the server. Typically used for `POST` requests. Leave this as an empty
String to skip. This is passed as-is to `curl_setup_request`.
`headers::Vector{String} = String[]`
: Any request headers that should be passed on to the server as part of the request. Headers SHOULD be of the form `key: value`.
Consult [RFC 2616 section 4.2](https://datatracker.ietf.org/doc/html/rfc2616#section-4.2) for more details on HTTP request headers.
## Keyword Arguments
`data_handler::Union{Function, Nothing} = <default>`
: A function to handle any response Body data. This function should accept a single argument of type `Vector{UInt8}`. Its return value will be ignored.
If not specified, a default handler will be used. Set this explicitly to `nothing` to disable handling of HTTP response body data.
`data_handler::Union{Function, Nothing} = <default>`
: A function to handle any response Header data. This function should accept a single argument of type `String`. Its return value will be ignored.
If not specified, a default handler will be used. Set this explicitly to `nothing` to disable handling of HTTP response header data.
`url::AbstractString=""`
: The URL to use for this request. This permanently overrides the `url` passed in to the [`CurlEasy`](@ref) constructor. If not specified, then the previous value
of the [`CurlEasy`](@ref)'s url is reused.
## Returns
The [`CurlEasy`](@ref) object.
"""
function curl_setup_request_response(
curl::CurlEasy,
requestBody::String,
headers::Vector{String} = String[];
data_handler::Union{Function, Nothing} = _create_default_buffer_handler(curl, :databuffer),
header_handler::Union{Function, Nothing} = _create_default_buffer_handler(curl, :responseHeaders, String),
url::AbstractString = ""
)
data_channel = setup_response_handler(data_handler, curl.uuid)
header_channel = setup_response_handler(header_handler, curl.uuid)
curl_setup_request(
curl,
requestBody,
headers;
data_channel,
header_channel,
url
)
end
"""
curl_execute(::CurlMulti) → CURLMcode
Executes all pending [`CurlEasy`](@ref) attached to the [`CurlMulti`](@ref) handle and returns a `CURLMcode` indicating success or failure.
In most cases, this function should return `CURLM_OK` even if there were failures in individual transfers. Each [`CurlEasy`](@ref) handle
will have `userdata[:http_status]` set and `userdata[:errormessage]` will be set in case of an error.
This function will print errors or warnings to the Logger for unexpected states. File a bug if you see any of these.
"""
function curl_execute(curl::CurlMulti)
res = curl_perform(curl)
msgq = Ref{Cint}(1)
while msgq[] > 0
# Returns a Ptr{LibCURL.CURLMsg}
m = curl_multi_info_read(curl.handle, msgq)
if m == C_NULL
# COV_EXCL_START
if msgq[] > 0
@error "curl_multi_info_read returned NULL while $(msgq[]) messages still remain queued"
end
break
# COV_EXCL_STOP
end
# Convert from Ptr to LibCURL.CURLMsg
m_jl = unsafe_load(m)
if m_jl.msg == CURLMSG_DONE
local easy_h = m_jl.easy_handle
local easy = findfirst(x -> x.handle == easy_h, curl.pool)
if isnothing(easy)
# COV_EXCL_START
@error "Couldn't find handle $easy_h"
continue
# COV_EXCL_STOP
end
easy = curl.pool[easy]
if haskey(easy.userdata, :data_channel)
put!(easy.userdata[:data_channel], EOF)
end
easy.userdata[:http_status] = curl_response_status(easy)
if haskey(easy.userdata, :errorbuffer)
easy.userdata[:errormessage] = curl_error_to_string(easy.userdata[:errorbuffer])
end
else
@warn "curl_multi_info_read returned an unknown code: $(m_jl.msg)... ignoring. msgq=$(msgq[])"
end
end
res
end
"""
curl_execute(data_handler::Function, ::CurlEasy, ::String, ::Vector{String}; url::String) → (CURLCode, Int64, String)
curl_execute(::CurlEasy, ::String, Vector{String}; url::String, data_handler::Function, header_handler::Function) → (CURLCode, Int64, String)
Execute a [`CurlEasy`](@ref) handle optionally passing in a `requestBody` (for POSTs), any HTTP request headers, a request URL, and handlers for response
data and headers.
In its first form this method accepts the `data_handler` as the first argument allowing you to use `curl_execute(curl) do data ... end` to handle the data.
In this case, response headers are ignored.
In its second form, both data and header handlers are passed in as keyword arguments. If not specified, then default handlers are set up that write to
`userdata[:databuffer]` and `userdata[:responseHeaders]` respectively. You may explicitly set the handler to `nothing` to avoid handling data or headers.
This can have a small improvement in memory utilization.
"""
curl_execute(
data_handler::Function,
curl::CurlEasy,
requestBody::String="",
headers::Vector{String}=String[];
url::AbstractString=""
) = curl_execute(curl, requestBody, headers; data_handler, url, header_handler=nothing)
function curl_execute(
curl::CurlEasy,
requestBody::String="",
headers::Vector{String}=String[];
data_handler::Union{Function, Nothing} = _create_default_buffer_handler(curl, :databuffer),
header_handler::Union{Function, Nothing} = _create_default_buffer_handler(curl, :responseHeaders, String),
url::AbstractString=""
)
curl_setup_request_response(curl, requestBody, headers; data_handler, header_handler, url)
@debug "Starting curl_easy_perform"
res = curl_easy_perform(curl)
@debug "Finished curl_easy_perform"
http_status = curl_response_status(curl)
errormessage = curl_error_to_string(curl.userdata[:errorbuffer])
return (res, http_status, errormessage)
end
"""
curl_error_to_string(::Vector{UInt8}) → String
Convert curl's error message stored as a NULL terminated sequence of bytes into a Julia `String`
"""
function curl_error_to_string(errorbuffer::Vector{UInt8})
errorend = something(findfirst(==(UInt8(0)), errorbuffer), length(errorbuffer)+1)
return String(@view(errorbuffer[1:errorend-1]))
end
"""
curl_response_status(::CurlEasy) → Int64
Get the HTTP status code of the most recent response from the [`CurlEasy`](@ref) object.
"""
function curl_response_status(curl::CurlEasy)
http_code = Ref{Clong}()
curl_easy_getinfo(curl.handle, CURLINFO_RESPONSE_CODE, http_code)
return http_code[]
end
end # module
| CurlHTTP | https://github.com/bluesmoon/CurlHTTP.jl.git |
|
[
"MIT"
] | 0.1.3 | da9adb5a5f7826e63999c55458ccf73ae2de44ac | code | 10409 | using CurlHTTP, Test, JSON
gbVerbose = false
function test_GET()
curl = CurlEasy(
url="https://postman-echo.com/get?foo=bar&baz=zod",
method=CurlHTTP.GET,
verbose=gbVerbose
)
databuffer = UInt8[]
res, http_status, errormessage = curl_execute(curl, "", ["X-Custom-Header: ding"]) do d
if isa(d, Array{UInt8})
append!(databuffer, d)
end
end
@test CURLE_OK == res
@test 200 == http_status
data = JSON.parse(String(databuffer))
@test "https://postman-echo.com/get?foo=bar&baz=zod" == data["url"]
@test Dict("foo" => "bar", "baz" => "zod") == data["args"]
@test haskey(data["headers"], "x-custom-header")
@test data["headers"]["x-custom-header"] == "ding"
@test "" == errormessage
end
function test_GET_debug()
curl = CurlEasy(
url="https://postman-echo.com/get?foo=bar&baz=zod",
method=CurlHTTP.GET,
verbose=true
)
res, http_status, errormessage = curl_execute(curl)
@test CURLE_OK == res
@test 200 == http_status
databuffer = curl.userdata[:databuffer]
data = JSON.parse(String(databuffer))
@test "https://postman-echo.com/get?foo=bar&baz=zod" == data["url"]
@test Dict("foo" => "bar", "baz" => "zod") == data["args"]
@test "" == errormessage
responseHeaders = curl.userdata[:responseHeaders]
@test length(responseHeaders) > 1
end
function test_GET_reuse()
curl = CurlEasy(
url="https://postman-echo.com/get?foo=bar&baz=zod",
method=CurlHTTP.GET,
verbose=false
)
res, http_status, errormessage = curl_execute(curl, "", ["X-Custom-Header: ding1"])
@test CURLE_OK == res
@test 200 == http_status
@test "" == errormessage
databuffer = curl.userdata[:databuffer]
data = JSON.parse(String(databuffer))
@test "https://postman-echo.com/get?foo=bar&baz=zod" == data["url"]
@test Dict("foo" => "bar", "baz" => "zod") == data["args"]
@test haskey(data["headers"], "x-custom-header")
@test data["headers"]["x-custom-header"] == "ding1"
@test !haskey(data["headers"], "user-agent")
res, http_status, errormessage = curl_execute(curl, "", ["X-Custom-Header: ding2"]; url="https://postman-echo.com/get?foo=bear&baz=zeroed")
@test CURLE_OK == res
@test 200 == http_status
@test "" == errormessage
databuffer = curl.userdata[:databuffer]
data = JSON.parse(String(databuffer))
@test "https://postman-echo.com/get?foo=bear&baz=zeroed" == data["url"]
@test Dict("foo" => "bear", "baz" => "zeroed") == data["args"]
@test haskey(data["headers"], "x-custom-header")
@test data["headers"]["x-custom-header"] == "ding2"
end
function test_GET_useragent()
CurlHTTP.setDefaultUserAgent("CurlHTTP/0.1")
curl = CurlEasy(
url="https://postman-echo.com/get?foo=bar&baz=zod",
method=CurlHTTP.GET,
verbose=gbVerbose
)
res, http_status, errormessage = curl_execute(curl)
@test CURLE_OK == res
@test 200 == http_status
databuffer = curl.userdata[:databuffer]
data = JSON.parse(String(databuffer))
@test "https://postman-echo.com/get?foo=bar&baz=zod" == data["url"]
@test Dict("foo" => "bar", "baz" => "zod") == data["args"]
@test "CurlHTTP/0.1" == data["headers"]["user-agent"]
CurlHTTP.setDefaultUserAgent(nothing)
end
function test_DELETE()
curl = CurlEasy(
url="https://postman-echo.com/delete?foo=bar&baz=zod",
method=CurlHTTP.DELETE,
verbose=gbVerbose
)
databuffer = UInt8[]
res, http_status, errormessage = curl_execute(curl, "", ["X-Custom-Header: ding"]) do d
if isa(d, Array{UInt8})
append!(databuffer, d)
end
end
@test CURLE_OK == res
@test 200 == http_status
data = JSON.parse(String(databuffer))
@test "https://postman-echo.com/delete?foo=bar&baz=zod" == data["url"]
@test Dict("foo" => "bar", "baz" => "zod") == data["args"]
@test isnothing(data["json"])
@test haskey(data["headers"], "x-custom-header")
@test data["headers"]["x-custom-header"] == "ding"
@test "" == errormessage
end
function test_OPTIONS()
curl = CurlEasy(
url="https://postman-echo.com/get?foo=bar&baz=zod",
method=CurlHTTP.OPTIONS,
verbose=gbVerbose
)
databuffer = UInt8[]
res, http_status, errormessage = curl_execute(curl, "", ["X-Custom-Header: ding"]) do d
if isa(d, Array{UInt8})
append!(databuffer, d)
end
end
@test CURLE_OK == res
@test 200 == http_status
data = String(databuffer)
@test "GET,HEAD,PUT,POST,DELETE,PATCH" == data
@test "" == errormessage
end
function test_HEAD()
curl = CurlEasy(
url="https://postman-echo.com/get?foo=bar&baz=zod",
method=CurlHTTP.HEAD,
verbose=gbVerbose
)
databuffer = UInt8[]
res, http_status, errormessage = curl_execute(curl, "", ["X-Custom-Header: ding"]) do d
if isa(d, Array{UInt8})
append!(databuffer, d)
end
end
@test CURLE_OK == res
@test 200 == http_status
@test isempty(databuffer)
@test "" == errormessage
end
function test_PUT()
@test_throws ArgumentError("Method `PUT' is not currently supported") CurlEasy(method=CurlHTTP.PUT)
end
function test_POST()
curl = CurlEasy(
url="https://postman-echo.com/post",
method=CurlHTTP.POST,
verbose=gbVerbose
)
requestBody = """{"testName":"test_POST"}"""
errorbuffer = Array{UInt8}(undef, CURL_ERROR_SIZE)
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorbuffer)
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, length(requestBody))
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, requestBody)
curl_add_headers(curl, [
"Content-Type: application/json",
"Content-Length: $(length(requestBody))"
])
res = curl_perform(curl)
@test CURLE_OK == res
end
function test_writeCB()
curl = CurlEasy(
url="https://postman-echo.com/post",
method=CurlHTTP.POST,
verbose=gbVerbose,
useragent="CurlHTTP Test"
)
requestBody = """{"testName":"test_writeCB"}"""
headers = ["Content-Type: application/json",]
databuffer = UInt8[]
res, http_status, errormessage = curl_execute(curl, requestBody, headers) do d
if isa(d, Array{UInt8})
append!(databuffer, d)
end
end
@test CURLE_OK == res
@test 200 == http_status
@test 2 * length(requestBody) < length(databuffer) # We expect requestBody to be repeated twice in the response
data = JSON.parse(String(databuffer))
reqB = JSON.parse(requestBody)
@test reqB == data["data"] == data["json"]
@test "CurlHTTP Test" == data["headers"]["user-agent"]
@test "" == errormessage
end
function test_headerCB()
end
function test_multiPOST()
pool = CurlEasy[]
for i in 1:3
local curl = CurlEasy(
url="https://postman-echo.com/post?val=$i",
method=CurlHTTP.POST,
verbose=gbVerbose
)
local requestBody = """{"testName":"test_multiPOST","value":$i}"""
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, length(requestBody))
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, requestBody)
curl_add_headers(curl, [
"Content-Type: application/json",
"Content-Length: $(length(requestBody))"
])
push!(pool, curl)
end
curl = CurlMulti(pool)
res = curl_execute(curl)
http_statuses = [p.userdata[:http_status] for p in curl.pool]
@test CURLM_OK == res
@test 3 == length(http_statuses)
@test all(http_statuses .== 200)
end
function test_multi_writeCB()
curl = CurlMulti()
for i in 1:3
local easy = CurlEasy(
url="https://postman-echo.com/post?val=$i",
method=CurlHTTP.POST,
verbose=gbVerbose,
)
requestBody = """{"testName":"test_multi_writeCB","value":$i}"""
headers = ["Content-Type: application/json", "X-App-Value: $(i*5)"]
easy.userdata[:i] = i
CurlHTTP.curl_setup_request_response(
easy,
requestBody,
headers
)
curl_multi_add_handle(curl, easy)
end
res = curl_execute(curl)
responses = [p.userdata for p in curl.pool]
@test CURLM_OK == res
@test 3 == length(responses)
@testset "Response $(p.userdata[:i])" for p in curl.pool
r = p.userdata
@test haskey(r, :http_status)
@test r[:http_status] == 200
@test 2 * length(r[:requestBody]) < length(r[:databuffer])
data = JSON.parse(String(r[:databuffer]))
reqB = JSON.parse(r[:requestBody])
@test reqB == data["data"] == data["json"]
@test haskey(r, :errormessage)
@test "" == r[:errormessage]
@test CURLM_OK == curl_multi_remove_handle(curl, p.uuid)
end
@test nothing == curl_multi_remove_handle(curl, string(CurlHTTP.UUIDs.uuid4()))
end
function test_Certs()
@test_throws ArgumentError("Could not find the certpath `foobar'") CurlEasy(certpath="foobar")
@test_throws ArgumentError("Could not find the keypath `foobar'") CurlEasy(certpath=@__FILE__, keypath="foobar")
@test CurlEasy(certpath=@__FILE__, keypath=@__FILE__) isa CurlEasy
@test_throws ArgumentError("Could not find the cacertpath `foobar'") CurlEasy(cacertpath="foobar")
@test CurlEasy(cacertpath=LibCURL.cacert) isa CurlEasy
end
function test_UrlEscape()
@test "hello%20world%2C%20how%20are%20you%3F%20I%27m%20fine%21%20%23escape" == curl_url_escape("hello world, how are you? I'm fine! #escape")
end
@testset "Curl" begin
@testset "GET" begin
test_GET()
test_GET_debug()
test_GET_reuse()
test_GET_useragent()
end
@testset "HEAD" begin test_HEAD() end
@testset "HEAD" begin test_PUT() end
@testset "DELETE" begin test_DELETE() end
@testset "OPTIONS" begin test_OPTIONS() end
@testset "POST" begin test_POST() end
@testset "writeCB" begin test_writeCB() end
@testset "headerCB" begin test_headerCB() end
@testset "multiPOST" begin test_multiPOST() end
@testset "multi writeCB" begin test_multi_writeCB() end
@testset "Certs" begin test_Certs() end
@testset "URL Escape" begin test_UrlEscape() end
end
| CurlHTTP | https://github.com/bluesmoon/CurlHTTP.jl.git |
|
[
"MIT"
] | 0.1.3 | da9adb5a5f7826e63999c55458ccf73ae2de44ac | docs | 2836 | `CurlHTTP` is a wrapper around [LibCURL](https://github.com/JuliaWeb/LibCURL.jl) that provides a more Julia like interface to doing HTTP via `Curl`.
[](https://github.com/bluesmoon/CurlHTTP.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://coveralls.io/github/bluesmoon/CurlHTTP.jl?branch=)
[](https://bluesmoon.github.io/CurlHTTP.jl/)
In particular, this module implements the `CurlEasy` and `CurlMulti` interfaces for curl, and allows using Client TLS certificates.
This module reexports `LibCURL` so everything available in `LibCURL` will be available when this module is used.
See https://curl.se/libcurl/c/libcurl-tutorial.html for a tutorial on using libcurl in C. The Julia interface should be similar.
# Examples
## GET a URL and read the response from the internal buffer
```julia
using CurlHTTP
curl = CurlEasy(
url="https://postman-echo.com/get?foo=bar",
method=CurlHTTP.GET,
verbose=true
)
res, http_status, errormessage = curl_execute(curl)
# curl.userdata[:databuffer] is a Vector{UInt8} containing the bytes of the response
responseBody = String(curl.userdata[:databuffer])
# curl.userdata[:responseHeaders] is a Vector{String} containing the response headers
responseHeaders = curl.userdata[:responseHeaders]
```
## POST to a URL and read the response with your own callback
```julia
using CurlHTTP
curl = CurlEasy(
url="https://postman-echo.com/post",
method=CurlHTTP.POST,
verbose=true
)
requestBody = "{\"testName\":\"test_writeCB\"}"
headers = ["Content-Type: application/json"]
databuffer = UInt8[]
res, http_status, errormessage = curl_execute(curl, requestBody, headers) do d
if isa(d, Array{UInt8})
append!(databuffer, d)
end
end
responseBody = String(databuffer)
```
## Multiple concurrent requests using CurlMulti
```julia
using CurlHTTP
curl = CurlMulti()
for i in 1:3
local easy = CurlEasy(
url="https://postman-echo.com/post?val=$i",
method=CurlHTTP.POST,
verbose=true,
)
requestBody = "{\"testName\":\"test_multi_writeCB\",\"value\":$i}"
headers = ["Content-Type: application/json", "X-App-Value: $(i*5)"]
CurlHTTP.curl_setup_request_response(
easy,
requestBody,
headers
)
curl_multi_add_handle(curl, easy)
end
res = curl_execute(curl)
responses = [p.userdata for p in curl.pool] # userdata contains response data, status code and error message
```
| CurlHTTP | https://github.com/bluesmoon/CurlHTTP.jl.git |
|
[
"MIT"
] | 0.1.3 | da9adb5a5f7826e63999c55458ccf73ae2de44ac | docs | 648 | # CurlHTTP.jl Documentation
```@docs
CurlHTTP
```
## Globals
```@docs
CurlHTTP.DEFAULT_USER_AGENT
```
## Exported Types
```@docs
CurlHandle
CurlEasy
CurlMulti
```
## Internal Types
```@docs
CurlHTTP.HTTPMethod
CurlHTTP.ChannelMarkers
```
## Exported Methods
```@autodocs
Modules=[CurlHTTP]
Order=[:function]
Filter=f -> which(CurlHTTP, Symbol(f)) == CurlHTTP
Private=false
```
## Methods extended from `LibCURL`
```@autodocs
Modules=[CurlHTTP]
Order=[:function]
Filter=f -> which(CurlHTTP, Symbol(f)) == LibCURL
Private=false
```
## Internal Methods
```@autodocs
Modules=[CurlHTTP]
Order=[:function]
Public=false
```
## Index
```@index
```
| CurlHTTP | https://github.com/bluesmoon/CurlHTTP.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 1507 | # Source this script as e.g.
#
# include("PATH/TO/devrepl.jl")
#
# from *any* Julia REPL or run it as e.g.
#
# julia -i --banner=no PATH/TO/devrepl.jl
#
# from anywhere. This will change the current working directory and
# activate/initialize the correct Julia environment for you.
#
# You may also run this in vscode to initialize a development REPL
#
using Pkg
using Downloads: download
ENV["GKSwstype"] = 100
cd(@__DIR__)
Pkg.activate("test")
function _instantiate()
installorg_script = joinpath("..", "scripts", "installorg.jl")
if !isfile(installorg_script)
@warn "$(@__DIR__) should be inside the JuliaQuantumControl development environment. See https://github.com/JuliaQuantumControl/JuliaQuantumControl#readme"
installorg_script = download(
"https://raw.githubusercontent.com/JuliaQuantumControl/JuliaQuantumControl/master/scripts/installorg.jl",
)
end
if !isfile(joinpath("..", ".JuliaFormatter.toml"))
download(
"https://raw.githubusercontent.com/JuliaQuantumControl/JuliaQuantumControl/master/.JuliaFormatter.toml",
".JuliaFormatter.toml"
)
end
include(installorg_script)
eval(:(installorg()))
end
if !isfile(joinpath("test", "Manifest.toml"))
_instantiate()
end
include("test/init.jl")
# Disable link-checking in interactive REPL, since it is the slowest part
# of building the docs.
ENV["DOCUMENTER_CHECK_LINKS"] = "0"
if abspath(PROGRAM_FILE) == @__FILE__
help()
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 13756 | #! format: off
import QuantumControl
import Documenter
"""Return a list of symbols for the names directly defined in `pkg`.
This filters out re-exported names and sub-modules. By default, for `all=true`,
both public (exported) and private names are included. With `all=false`, the
list is filtered to include only exported names.
"""
function get_local_members(pkg; all=true)
return [
m for m in names(pkg, all=all) if !(
(startswith(String(m), "#")) || # compiler-generated names
(getfield(pkg, m) isa Union{Dict,Array,Set}) || # global variable
(m == Symbol(pkg)) || # the package itself
(m == :eval) || # compiler-injected "eval"
(m == :include) || # compiler-injected "include"
((getfield(pkg, m)) isa Module) || # sub-modules
(_parentmodule(getfield(pkg, m), pkg)) ≠ pkg # re-exported
)
]
end
function _parentmodule(m, pkg)
try
parentmodule(m)
catch
return pkg
end
end
"""Return a list of symbols for all the sub-modules of `pkg`.
"""
function get_submodules(pkg)
return [
m for m in names(pkg, all=true)
if (getfield(pkg, m) isa Module) && !(m == Symbol(pkg))
]
end
"""Return the canonical fully qualified name of an object (function, type).
Given e.g. a function object, it returns a string containing the canonical
fully qualified name of the original function definition.
"""
function canonical_name(obj)
mod = parentmodule(obj)
modpath = fullname(mod)
modname = join((String(sym) for sym in modpath), ".")
objname = String(nameof(obj))
return "$modname.$objname"
end
quantum_control_members = [
m for m in names(QuantumControl)
if (m ≠ :QuantumControl) && (m ∉ QuantumControl.DEPRECATED)
]
quantum_control_local_members = filter(
member -> member ∉ QuantumControl.DEPRECATED,
get_local_members(QuantumControl, all=false)
)
quantum_control_reexported_members = [
m for m in quantum_control_members if m ∉ quantum_control_local_members
]
quantum_control_sub_modules = get_submodules(QuantumControl)
subpackages = [
(:QuantumPropagators, "quantum_propagators.md"),
]
outfile = joinpath(@__DIR__, "src", "api", "quantum_control.md")
println("Generating API for QuantumControl in $outfile")
open(outfile, "w") do out
write(out, "```@meta\n")
write(out, "EditURL = \"../../generate_api.jl\"\n")
write(out, "```\n\n")
write(out, "# [QuantumControl Public API](@id QuantumControlAPI)\n\n")
write(out, """
This page summarizes the public API of the `QuantumControl` package. See
also the [Index](@ref API-Index) of *all* symbols.
QuantumControl exports the following symbols:
""")
for name ∈ quantum_control_local_members
obj = getfield(QuantumControl, name)
ref = canonical_name(obj)
println(out, "* [`$name`](@ref $ref)")
end
write(out, """
and re-exports the following symbols either from its own
[submodules](@ref public_submodules) or from
[`QuantumPropagators`](@ref QuantumPropagatorsPackage):
""")
for name ∈ quantum_control_reexported_members
obj = getfield(QuantumControl, name)
ref = canonical_name(obj)
println(out, "* [`$name`](@ref $ref)")
end
write(out, """
It also defines the following public, but unexported functions:
* [`QuantumControl.set_default_ad_framework`](@ref)
""")
write(out, """
### [Submodules](@id public_submodules)
Each of the following submodules defines their own public API. Note that
some of these submodules are re-exported from or extend submodules of
[`QuantumPropagators`](@ref QuantumPropagatorsPackage).
""")
for submod in quantum_control_sub_modules
write(out, "* [`QuantumControl.$(submod)`](@ref QuantumControl$(submod)API)\n")
end
for submod in quantum_control_sub_modules
write(out, "\n\n### [`QuantumControl.$submod`](@id QuantumControl$(submod)API)\n\n")
for name in names(getfield(QuantumControl, submod))
if name ≠ submod
obj = getfield(getfield(QuantumControl, submod), name)
ref = canonical_name(obj)
println(out, "* [`QuantumControl.$submod.$name`](@ref $ref)")
end
end
end
write(out, """
### Subpackages
`QuantumControl` contains the following sub-packages from the
[JuliaQuantumControl](https://github.com/JuliaQuantumControl)
organization:
""")
for (pkgname::Symbol, outfilename) in subpackages
local outfile = joinpath(@__DIR__, "src", "api", outfilename)
write(out, "* [`$pkgname`](@ref $(pkgname)Package)\n")
end
end
local_module_api_id(mod) = replace("$mod", "." => "") * "LocalAPI"
function write_module_api(out, mod, description="")
members = [
m for m in names(mod)
if !(
(String(Symbol(mod)) |> endswith(".$m")) ||
m == Symbol(mod)
)
]
public_members = get_local_members(mod, all=false)
all_local_members = get_local_members(mod, all=true)
documented_members = [
k.var for k in keys(Documenter.DocSystem.getmeta(mod))
]
documented_private_members = [
name for name in documented_members
if (name ∉ public_members) && (name ∈ all_local_members)
]
reexported_members = [
m for m in members
if m ∉ public_members
]
write(out, "\n\n## [`$mod`](@id $(local_module_api_id(mod)))\n\n")
if length(description) > 0
write(out, "\n\n")
write(out, description)
write(out, "\n\n")
end
if length(public_members) > 0
write(out, "\nPublic Symbols:\n\n")
for name ∈ public_members
println(out, "* [`$name`](@ref $mod.$name)")
end
write(out, "\n")
end
if length(reexported_members) > 0
write(out, "\nRe-exported Symbols:\n\n")
for name ∈ reexported_members
obj = getfield(mod, name)
ref = canonical_name(obj)
println(out, "* [`$name`](@ref $ref)")
end
write(out, "\n")
end
if length(documented_private_members) > 0
write(out, "\nPrivate Symbols:\n")
for name ∈ documented_private_members
println(out, "* [`$name`](@ref $mod.$name)")
end
write(out, "\n")
end
if length(public_members) > 0
write(out, "\n\n#### Public Symbols\n\n")
println(out, "```@docs")
for name ∈ public_members
println(out, "$mod.$name")
end
println(out, "```")
end
if length(documented_private_members) > 0
write(out, "\n\n#### Private Symbols\n\n")
println(out, "```@docs")
for name ∈ documented_private_members
println(out, "$mod.$name")
end
println(out, "```")
end
end
outfile = joinpath(@__DIR__, "src", "api", "reference.md")
println("Generating local reference for QuantumControl in $outfile")
open(outfile, "w") do out
write(out, "```@meta\n")
write(out, "EditURL = \"../../generate_api.jl\"\n")
write(out, "```\n\n")
write(out, raw"""
# API Reference
This page provides *all* docstrings locally defined in the `QuantumControl`
package for both private and public symbols. See also the summary of the
[public API](@ref QuantumControlAPI).
`QuantumControl` exposes local [exported](@ref quantumcontrol-local-symbols)
and [unexported](@ref quantumcontrol-local-unexported-symbols) local
symbols as well as re-exporting symbols and sub-modules from the
[QuantumPropagators](@ref QuantumPropagatorsPackage) subpackage and some
of its submodules.
The [`QuantumControl` submodules](@ref quantumcontrol-submodules) provide
additional public functionality. Note that some of the most commonly
used symbols from `QuantumControl`'s submodules may also be re-exported at
the top-level (such as [`@optimize_or_load`](@ref) from the
[`QuantumControl.Workflows`](@ref QuantumControlWorkflowsAPI) submodule).
""")
write(out, raw"""
## [Local Exported Symbols](@id quantumcontrol-local-symbols)
""")
println(out, "```@docs")
for name ∈ quantum_control_local_members
println(out, "QuantumControl.$name")
end
println(out, "```")
write(out, raw"""
## [Local Unexported Symbols](@id quantumcontrol-local-unexported-symbols)
```@docs
QuantumControl.set_default_ad_framework
QuantumControl.AbstractOptimizationResult
```
""")
write(out, raw"""
``\gdef\tgt{\text{tgt}}``
``\gdef\tr{\operatorname{tr}}``
``\gdef\Re{\operatorname{Re}}``
``\gdef\Im{\operatorname{Im}}``
## [List of Submodules](@id quantumcontrol-submodules)
`QuantumControl` has the following sub-modules:
""")
for name in quantum_control_sub_modules
write(out, "* [`QuantumControl.$name`](#$(local_module_api_id(getfield(QuantumControl, name))))\n")
end
for name in quantum_control_sub_modules
write_module_api(out, getfield(QuantumControl, name))
end
end
outfile = joinpath(@__DIR__, "src", "api", "quantum_control_index.md")
println("Generating index for QuantumControl in $outfile")
open(outfile, "w") do out
write(out, "```@meta\n")
write(out, "EditURL = \"../../generate_api.jl\"\n")
write(out, "```\n\n")
write(out, raw"""
# [API Index](@id API-Index)
```@index
```
""")
end
for (pkgname::Symbol, outfilename) in subpackages
local outfile = joinpath(@__DIR__, "src", "api", outfilename)
println("Generating API for $pkgname in $outfile")
open(outfile, "w") do out
pkg = getfield(QuantumControl, pkgname)
all_local_members = get_local_members(pkg)
public_members = get_local_members(pkg, all=false)
documented_members = [
k.var for k in keys(Documenter.DocSystem.getmeta(pkg))
]
documented_private_members = [
name for name in documented_members
if (name ∉ public_members) && (name ∈ all_local_members)
]
write(out, "```@meta\n")
write(out, "EditURL = \"../../generate_api.jl\"\n")
write(out, "```\n\n")
write(out, "\n\n# [$pkgname Package](@id $(pkgname)Package)\n\n")
write(out, "## Package Index\n\n")
write(out, raw"""
``\gdef\tgt{\text{tgt}}``
``\gdef\tr{\operatorname{tr}}``
``\gdef\Re{\operatorname{Re}}``
``\gdef\Im{\operatorname{Im}}``
""")
write(out, """
```@index
Pages = ["$outfilename"]
```
""")
write(out, "\n\n## [`$pkgname`](@id $(pkgname)API)\n\n")
if length(public_members) > 0
write(out, "\nPublic Symbols:\n\n")
for name in public_members
write(out, "* [`$name`](@ref $pkgname.$name)\n")
end
end
if length(documented_private_members) > 0
write(out, "\nPrivate Symbols:\n\n")
for name in documented_private_members
write(out, "* [`$name`](@ref $pkgname.$name)\n")
end
end
sub_modules = get_submodules(pkg)
if length(sub_modules) > 0
write(out, "\nSubmodules:\n\n")
for submodname in sub_modules
write(out, "* [`$pkgname.$submodname`](#$(pkgname)$(submodname)API)\n")
end
end
if length(public_members) + length(documented_private_members) > 0
write(out, "\n### Reference\n\n")
write(out, "\n```@docs\n")
for name in public_members
write(out, "$pkgname.$name\n")
end
for name in documented_private_members
write(out, "$pkgname.$name\n")
end
write(out, "```\n\n")
end
for submodname in sub_modules
submod = getfield(pkg, submodname)
all_local_members = get_local_members(submod)
public_members = get_local_members(submod, all=false)
documented_members = [
k.var for k in keys(Documenter.DocSystem.getmeta(submod))
]
documented_private_members = [
name for name in documented_members
if (name ∉ public_members) && (name ∈ all_local_members)
]
if length(public_members) + length(documented_private_members) > 0
write(out, "\n## [`$pkgname.$submodname`](@id $(pkgname)$(submodname)API)\n\n")
end
if length(public_members) > 0
write(out, "\nPublic:\n\n")
for name in public_members
write(out, "* [`$name`](@ref $pkgname.$submodname.$name)\n")
end
end
if length(documented_private_members) > 0
write(out, "\nPrivate:\n\n")
for name in documented_private_members
write(out, "* [`$name`](@ref $pkgname.$submodname.$name)\n")
end
end
if length(public_members) + length(documented_private_members) > 0
write(out, "\n### Reference\n\n")
write(out, "\n```@docs\n")
for name in public_members
write(out, "$pkgname.$submodname.$name\n")
end
for name in documented_private_members
write(out, "$pkgname.$submodname.$name\n")
end
write(out, "```\n\n")
end
end
end
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 4508 | using Pkg
using Documenter
using QuantumPropagators
using QuantumControl
using QuantumControl.Shapes
using QuantumControl.Functionals
using QuantumControl.Generators
using Krotov
using GRAPE
import OrdinaryDiffEq # ensure ODE extension is loaded
using Documenter.HTMLWriter: KaTeX
using DocumenterCitations
using DocumenterInterLinks
PROJECT_TOML = Pkg.TOML.parsefile(joinpath(@__DIR__, "..", "Project.toml"))
VERSION = PROJECT_TOML["version"]
NAME = PROJECT_TOML["name"]
AUTHORS = join(PROJECT_TOML["authors"], ", ") * " and contributors"
GITHUB = "https://github.com/JuliaQuantumControl/QuantumControl.jl"
DEV_OR_STABLE = "stable/"
if endswith(VERSION, "dev")
DEV_OR_STABLE = "dev/"
end
function org_inv(pkgname)
objects_inv =
joinpath(@__DIR__, "..", "..", "$pkgname.jl", "docs", "build", "objects.inv")
if isfile(objects_inv)
return ("https://juliaquantumcontrol.github.io/$pkgname.jl/dev/", objects_inv,)
else
return "https://juliaquantumcontrol.github.io/$pkgname.jl/$DEV_OR_STABLE"
end
end
links = InterLinks(
"Julia" => (
"https://docs.julialang.org/en/v1/",
"https://docs.julialang.org/en/v1/objects.inv",
joinpath(@__DIR__, "src", "inventories", "Julia.toml"),
),
"TimerOutputs" => (
"https://github.com/KristofferC/TimerOutputs.jl",
joinpath(@__DIR__, "src", "inventories", "TimerOutputs.toml")
),
"Examples" => "https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/$DEV_OR_STABLE",
"Krotov" => org_inv("Krotov"),
"GRAPE" => org_inv("GRAPE"),
"QuantumPropagators" => org_inv("QuantumPropagators"),
"QuantumGradientGenerators" => org_inv("QuantumGradientGenerators"),
"ComponentArrays" => (
"https://jonniedie.github.io/ComponentArrays.jl/stable/",
"https://jonniedie.github.io/ComponentArrays.jl/stable/objects.inv",
joinpath(@__DIR__, "src", "inventories", "ComponentArrays.toml")
),
"RecursiveArrayTools" => (
"https://docs.sciml.ai/RecursiveArrayTools/stable/",
"https://docs.sciml.ai/RecursiveArrayTools/stable/objects.inv",
joinpath(@__DIR__, "src", "inventories", "RecursiveArrayTools.toml")
),
)
println("Starting makedocs")
include("generate_api.jl")
bib = CitationBibliography(joinpath(@__DIR__, "src", "refs.bib"); style=:numeric)
warnonly = [:linkcheck,]
if get(ENV, "DOCUMENTER_WARN_ONLY", "0") == "1" # cf. test/init.jl
warnonly = true
end
makedocs(;
plugins=[bib, links],
authors=AUTHORS,
sitename="QuantumControl.jl",
# Link checking is disabled in REPL, see `devrepl.jl`.
linkcheck=(get(ENV, "DOCUMENTER_CHECK_LINKS", "1") != "0"),
warnonly,
doctest=false, # doctests run as part of test suite
format=Documenter.HTML(;
prettyurls=true,
canonical="https://juliaquantumcontrol.github.io/QuantumControl.jl",
assets=[
"assets/custom.css",
"assets/citations.css",
asset(
"https://juliaquantumcontrol.github.io/QuantumControl.jl/dev/assets/topbar/topbar.css"
),
asset(
"https://juliaquantumcontrol.github.io/QuantumControl.jl/dev/assets/topbar/topbar.js"
),
],
mathengine=KaTeX(
Dict(
:macros => Dict(
"\\Op" => "\\hat{#1}",
"\\ket" => "\\vert#1\\rangle",
"\\bra" => "\\langle#1\\vert",
"\\Im" => "\\operatorname{Im}",
"\\Re" => "\\operatorname{Re}",
),
),
),
footer="[$NAME.jl]($GITHUB) v$VERSION docs powered by [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl).",
size_threshold=1024 * 1024,
),
pages=[
"Home" => "index.md",
"Glossary" => "glossary.md",
"Overview" => "overview.md",
"Control Methods" => "methods.md",
"Howto" => "howto.md",
"Examples" => "examples/index.md",
"API" => [
"QuantumControl" => "api/quantum_control.md",
"Reference" => "api/reference.md",
"Subpackages" => ["QuantumPropagators" => "api/quantum_propagators.md",],
"Externals" => "api_externals.md",
"Index" => "api/quantum_control_index.md",
],
"References" => "references.md",
]
)
println("Finished makedocs")
deploydocs(; repo="github.com/JuliaQuantumControl/QuantumControl.jl")
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 3484 | module QuantumControlFiniteDifferencesExt
using LinearAlgebra
import FiniteDifferences
import QuantumControl.Functionals:
_default_chi_via, make_gate_chi, make_automatic_chi, make_automatic_grad_J_a
function make_automatic_chi(
J_T,
trajectories,
::Val{:FiniteDifferences};
via=_default_chi_via(trajectories)
)
# TODO: Benchmark if χ should be closure, see QuantumControlZygoteExt.jl
function fdm_chi_via_states(Ψ, trajectories)
function _J_T(Ψ...)
-J_T(Ψ, trajectories)
end
fdm = FiniteDifferences.central_fdm(5, 1)
χ = Vector{eltype(Ψ)}(undef, length(Ψ))
∇J = FiniteDifferences.grad(fdm, _J_T, Ψ...)
for (k, ∇Jₖ) ∈ enumerate(∇J)
χ[k] = 0.5 * ∇Jₖ # ½ corrects for gradient vs Wirtinger deriv
# axpby!(0.5, ∇Jₖ, false, χ[k])
end
return χ
end
function fdm_chi_via_tau(Ψ, trajectories; tau=nothing, τ=tau)
if isnothing(τ)
msg = "`chi` returned by `make_chi` with `via=:tau` requires keyword argument tau/τ"
throw(ArgumentError(msg))
end
function _J_T(τ...)
-J_T(Ψ, trajectories; tau=τ)
end
fdm = FiniteDifferences.central_fdm(5, 1)
χ = Vector{eltype(Ψ)}(undef, length(Ψ))
∇J = FiniteDifferences.grad(fdm, _J_T, τ...)
for (k, traj) ∈ enumerate(trajectories)
∂J╱∂τ̄ₖ = 0.5 * ∇J[k] # ½ corrects for gradient vs Wirtinger deriv
χ[k] = ∂J╱∂τ̄ₖ * traj.target_state
# axpby!(∂J╱∂τ̄ₖ, traj.target_state, false, χ[k])
end
return χ
end
if via ≡ :states
return fdm_chi_via_states
elseif via ≡ :tau
Ψ_tgt = [traj.target_state for traj in trajectories]
if any(isnothing.(Ψ_tgt))
error("`via=:tau` requires that all trajectories define a `target_state`")
end
τ_tgt = ones(ComplexF64, length(trajectories))
Ψ_undef = similar(Ψ_tgt)
if abs(J_T(Ψ_tgt, trajectories) - J_T(Ψ_undef, trajectories; tau=τ_tgt)) > 1e-12
msg = "`via=:tau` in `make_chi` requires that `J_T`=$(repr(J_T)) can be evaluated solely via `tau`"
error(msg)
end
return fdm_chi_via_tau
else
msg = "`via` must be either `:states` or `:tau`, not $(repr(via))"
throw(ArgumentError(msg))
end
end
function make_automatic_grad_J_a(J_a, tlist, ::Val{:FiniteDifferences})
function automatic_grad_J_a(pulsevals, tlist)
func = pulsevals -> J_a(pulsevals, tlist)
fdm = FiniteDifferences.central_fdm(5, 1)
∇J_a_fdm = FiniteDifferences.grad(fdm, func, pulsevals)[1]
return ∇J_a_fdm
end
return automatic_grad_J_a
end
function make_gate_chi(J_T_U, trajectories, ::Val{:FiniteDifferences}; kwargs...)
function fdm_gate_chi(Ψ, trajectories)
function _J_T(U)
-J_T_U(U; kwargs...)
end
N = length(trajectories)
χ = Vector{eltype(Ψ)}(undef, N)
# We assume that that the initial states of the trajectories are the
# logical basis states
U = [trajectories[i].initial_state ⋅ Ψ[j] for i = 1:N, j = 1:N]
fdm = FiniteDifferences.central_fdm(5, 1)
∇J = FiniteDifferences.grad(fdm, gate -> _J_T(gate), U)[1]
for k = 1:N
χ[k] = 0.5 * sum([∇J[i, k] * trajectories[i].initial_state for i = 1:N])
end
return χ
end
return fdm_gate_chi
end
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 3392 | module QuantumControlZygoteExt
using LinearAlgebra
import Zygote
import QuantumControl.Functionals:
_default_chi_via, make_gate_chi, make_automatic_chi, make_automatic_grad_J_a
function make_automatic_chi(
J_T,
trajectories,
::Val{:Zygote};
via=_default_chi_via(trajectories)
)
# TODO: At some point, for a large system, we could benchmark if there is
# any benefit to making χ a closure and using LinearAlgebra.axpby! to
# overwrite it in-place if all states are mutable.
function zygote_chi_via_states(Ψ, trajectories)
# The kwargs swallow any `tau` keyword argument
function _J_T(Ψ...)
-J_T(Ψ, trajectories)
end
χ = Vector{eltype(Ψ)}(undef, length(Ψ))
∇J = Zygote.gradient(_J_T, Ψ...)
for (k, ∇Jₖ) ∈ enumerate(∇J)
χ[k] = 0.5 * ∇Jₖ # ½ corrects for gradient vs Wirtinger deriv
# axpby!(0.5, ∇Jₖ, false, χ[k])
end
return χ
end
function zygote_chi_via_tau(Ψ, trajectories; tau=nothing, τ=tau)
if isnothing(τ)
msg = "`chi` returned by `make_chi` with `via=:tau` requires keyword argument tau/τ"
throw(ArgumentError(msg))
end
function _J_T(τ...)
-J_T(Ψ, trajectories; tau=τ)
end
χ = Vector{eltype(Ψ)}(undef, length(Ψ))
∇J = Zygote.gradient(_J_T, τ...)
for (k, traj) ∈ enumerate(trajectories)
∂J╱∂τ̄ₖ = 0.5 * ∇J[k] # ½ corrects for gradient vs Wirtinger deriv
χ[k] = ∂J╱∂τ̄ₖ * traj.target_state
# axpby!(∂J╱∂τ̄ₖ, traj.target_state, false, χ[k])
end
return χ
end
if via ≡ :states
return zygote_chi_via_states
elseif via ≡ :tau
Ψ_tgt = [traj.target_state for traj in trajectories]
if any(isnothing.(Ψ_tgt))
error("`via=:tau` requires that all trajectories define a `target_state`")
end
τ_tgt = ones(ComplexF64, length(trajectories))
Ψ_undef = similar(Ψ_tgt)
if abs(J_T(Ψ_tgt, trajectories) - J_T(Ψ_undef, trajectories; tau=τ_tgt)) > 1e-12
msg = "`via=:tau` in `make_chi` requires that `J_T`=$(repr(J_T)) can be evaluated solely via `tau`"
error(msg)
end
return zygote_chi_via_tau
else
msg = "`via` must be either `:states` or `:tau`, not $(repr(via))"
throw(ArgumentError(msg))
end
end
function make_automatic_grad_J_a(J_a, tlist, ::Val{:Zygote})
function automatic_grad_J_a(pulsevals, tlist)
func = pulsevals -> J_a(pulsevals, tlist)
∇J_a_zygote = Zygote.gradient(func, pulsevals)[1]
return ∇J_a_zygote
end
return automatic_grad_J_a
end
function make_gate_chi(J_T_U, trajectories, ::Val{:Zygote}; kwargs...)
function zygote_gate_chi(Ψ, trajectories)
function _J_T(U)
-J_T_U(U; kwargs...)
end
N = length(trajectories)
χ = Vector{eltype(Ψ)}(undef, N)
# We assume that that the initial states of the trajectories are the
# logical basis states
U = [trajectories[i].initial_state ⋅ Ψ[j] for i = 1:N, j = 1:N]
∇J = Zygote.gradient(gate -> _J_T(gate), U)[1]
for k = 1:N
χ[k] = 0.5 * sum([∇J[i, k] * trajectories[i].initial_state for i = 1:N])
end
return χ
end
return zygote_gate_chi
end
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 2604 | #! format: off
module QuantumControl
include("reexport.jl")
using QuantumPropagators
@reexport_members(QuantumPropagators)
module Generators
# we need `QuantumPropagators.Generators` to be available under a name that
# doesn't clash with `QuantumControl.Generators` in order for the
# `@reexport_members` macro to work correctly
using QuantumPropagators: Generators as QuantumPropagators_Generators
using QuantumPropagators.Generators
include("reexport.jl")
@reexport_members(QuantumPropagators_Generators)
end
module Controls
using QuantumPropagators: Controls as QuantumPropagators_Controls
using QuantumPropagators.Controls
include("reexport.jl")
@reexport_members(QuantumPropagators_Controls)
include("derivs.jl")
export get_control_deriv, get_control_derivs
end
module Shapes
using QuantumPropagators: Shapes as QuantumPropagators_Shapes
using QuantumPropagators.Shapes
include("reexport.jl")
@reexport_members(QuantumPropagators_Shapes)
end
module Storage
using QuantumPropagators: Storage as QuantumPropagators_Storage
using QuantumPropagators.Storage
include("reexport.jl")
@reexport_members(QuantumPropagators_Storage)
end
module Amplitudes
using QuantumPropagators: Amplitudes as QuantumPropagators_Amplitudes
using QuantumPropagators.Amplitudes
include("reexport.jl")
@reexport_members(QuantumPropagators_Amplitudes)
end
module Interfaces
using QuantumPropagators.Interfaces: check_state, check_operator, check_control, check_parameterized_function, check_parameterized, supports_inplace
export check_state, check_operator, check_control, check_parameterized_function, check_parameterized, supports_inplace
include("interfaces/amplitude.jl")
include("interfaces/generator.jl")
export check_generator, check_amplitude
end
include("pulse_parameterizations.jl") # submodule PulseParameterizations
include("functionals.jl") # submodule Functionals
include("print_versions.jl")
include("set_default_ad_framework.jl")
include("result.jl")
include("deprecate.jl")
include("atexit.jl")
include("conditionalthreads.jl")
include("trajectories.jl")
include("control_problem.jl")
include("propagate.jl")
include("callbacks.jl")
include("optimize.jl")
export ControlProblem, Trajectory, optimize, propagate_trajectory
export propagate_trajectories
include("workflows.jl") # submodule Workflows
using .Workflows: run_or_load, @optimize_or_load, save_optimization, load_optimization
export run_or_load, @optimize_or_load, save_optimization, load_optimization
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 2382 | using JLD2: jldopen
"""
Register a callback to dump a running optimization to disk on unexpected exit.
A long-running optimization routine may use
```julia
if !isnothing(atexit_filename)
set_atexit_save_optimization(
atexit_filename, result; msg_property=:message, msg="Abort: ATEXIT"
)
# ...
popfirst!(Base.atexit_hooks) # remove callback
end
```
to register a callback that writes the given `result` object to the given
`filename` in JLD2 format in the event that the program terminates
unexpectedly. The idea is to avoid data loss if the user presses `CTRL-C` in a
non-interactive program (`SIGINT`), or if the process receives a `SIGTERM` from
an HPC scheduler because the process has reached its allocated runtime limit.
Note that the callback cannot protect against data loss in all possible
scenarios, e.g., a `SIGKILL` will terminate the program without giving the
callback a chance to run (as will yanking the power cord).
As in the above example, the optimization routine should make
`set_atexit_save_optimization` conditional on an `atexit_filename` keyword
argument, which is what `QuantumControl.@optimize_or_load` will pass to the
optimization routine. The optimization routine must remove the callback from
`Base.atexit_hooks` when it exits normally. Note that in an interactive
context, `CTRL-C` will throw an `InterruptException`, but not cause a shutdown.
Optimization routines that want to prevent data loss in this situation should
handle the `InterruptException` and return `result`, in addition to using
`set_atexit_save_optimization`.
If `msg_property` is not `nothing`, the given `msg` string will be stored in
the corresponding property of the (mutable) `result` object before it is
written out.
The resulting JLD2 file is compatible with `QuantumControl.load_optimization`.
"""
function set_atexit_save_optimization(
filename,
result;
msg_property=:message,
msg="Abort: ATEXIT"
)
function dump_on_exit()
if !isnothing(msg_property)
setproperty!(result, msg_property, msg)
end
jldopen(filename, "w") do data
data["result"] = result
end
end
# the callback might not have very much time to run, so it's best to
# precompile and save a few seconds later on when it matters.
precompile(dump_on_exit, ())
atexit(dump_on_exit)
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 2678 | """
Construct a method-specific automatic callback for printing iter information.
```julia
print_iters = make_print_iters(Method; kwargs...)
```
constructs the automatic callback to be used by
`optimize(problem; method=Method, print_iters=true)` to print information after
each iteration. The keyword arguments are those used to instantiate `problem`
and those explicitly passed to [`optimize`](@ref).
Optimization methods should implement
`make_print_iters(::Val{:Method}; kwargs...)` where `:Method` is the name
of the module/package implementing the method.
"""
function make_print_iters(method::Module; kwargs...)
return make_print_iters(nameof(method); kwargs...)
end
function make_print_iters(method::Symbol; kwargs...)
# Optimization packages must implement
#
# make_print_iters(method::Val{name}; kwargs...)
#
return make_print_iters(Val(method); kwargs...)
end
# If a package does not implement make_print_iters, nothing will be printed
function make_print_iters(method::Val; kwargs...)
return nothing
end
"""Combine multiple `callback` functions.
```julia
chain_callbacks(funcs...)
```
combines `funcs` into a single Function that can be passes as `callback` to
[`ControlProblem`](@ref) or any `optimize`-function.
Each function in `func` must be a suitable `callback` by itself. This means
that it should receive the optimization workspace object as its first
positional parameter, then positional parameters specific to the optimization
method, and then an arbitrary number of data parameters. It must return either
`nothing` or a tuple of "info" objects (which will end up in the `records` field of
the optimization result).
When chaining callbacks, the `funcs` will be called in series, and the "info"
objects will be accumulated into a single result tuple. The combined results
from previous `funcs` will be given to the subsequent `funcs` as data
parameters. This allows for the callbacks in the chain to communicate.
The chain will return the final combined result tuple, or `nothing` if all
`funcs` return `nothing`.
!!! note
When calling [`optimize`](@ref), any `callback` that is a
tuple will be automatically processed with `chain_callbacks`. Thus,
`chain_callbacks` rarely has to be invoked manually.
"""
function chain_callbacks(funcs...)
function _callback(args...)
res = Tuple([])
for f in funcs
res_f = f(args..., res...)
if !isnothing(res_f)
res = (res..., res_f...)
end
end
if length(res) == 0
return nothing
else
return res
end
end
return _callback
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 1070 | using Base.Threads
using Base.Threads: threadid, threading_run
@static if Base.VERSION ≥ v"1.9-rc1"
using Base.Threads: threadpoolsize
end
"""Conditionally apply multi-threading to `for` loops.
This is a variation on `Base.Threads.@threads` that adds a run-time boolean
flag to enable or disable threading. It is intended for *internal use* in
packages building on `QuantumControl`.
Usage:
```julia
using QuantumControl: @threadsif
function optimize(trajectories; use_threads=true)
@threadsif use_threads for k = 1:length(trajectories)
# ...
end
end
```
"""
macro threadsif(cond, loop)
if !(isa(loop, Expr) && loop.head === :for)
throw(ArgumentError("@threadsif requires a `for` loop expression"))
end
if !(loop.args[1] isa Expr && loop.args[1].head === :(=))
throw(ArgumentError("nested outer loops are not currently supported by @threadsif"))
end
quote
if $(esc(cond))
$(Threads._threadsfor(loop.args[1], loop.args[2], :static))
else
$(esc(loop))
end
end
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 3256 | import QuantumPropagators.Controls: get_controls, get_parameters, substitute
"""A full control problem with multiple trajectories.
```julia
ControlProblem(
trajectories,
tlist;
kwargs...
)
```
The `trajectories` are a list of [`Trajectory`](@ref) instances,
each defining an initial state and a dynamical generator for the evolution of
that state. Usually, the trajectory will also include a target state (see
[`Trajectory`](@ref)) and possibly a weight. The `trajectories` may also be
given together with `tlist` as a mandatory keyword argument.
The `tlist` is the time grid on which the time evolution of the initial states
of each trajectory should be propagated. It may also be given as a (mandatory)
keyword argument.
The remaining `kwargs` are keyword arguments that are passed directly to the
optimal control method. These typically include e.g. the optimization
functional.
The control problem is solved by finding a set of controls that minimize an
optimization functional over all trajectories.
"""
struct ControlProblem
trajectories::Vector{<:Trajectory}
tlist::Vector{Float64}
kwargs::Dict{Symbol,Any}
function ControlProblem(trajectories, tlist; kwargs...)
kwargs_dict = Dict{Symbol,Any}(kwargs)
new(trajectories, tlist, kwargs_dict)
end
end
ControlProblem(trajectories; tlist, kwargs...) =
ControlProblem(trajectories, tlist; kwargs...)
ControlProblem(; trajectories, tlist, kwargs...) =
ControlProblem(trajectories, tlist; kwargs...)
function Base.summary(io::IO, problem::ControlProblem)
N = length(problem.trajectories)
nt = length(problem.tlist)
print(io, "ControlProblem with $N trajectories and $nt time steps")
end
function Base.show(io::IO, mime::MIME"text/plain", problem::ControlProblem)
println(io, summary(problem))
println(io, " trajectories:")
for traj in problem.trajectories
println(io, " ", summary(traj))
end
t = problem.tlist
if length(t) > 5
println(io, " tlist: [", t[begin], ", ", t[begin+1], " … ", t[end], "]")
else
print(io, " tlist: ")
show(io, t)
print(io, "\n")
end
if !isempty(problem.kwargs)
println(io, " kwargs:")
buffer = IOBuffer()
show(buffer, mime, problem.kwargs)
for line in split(String(take!(buffer)), "\n")[2:end]
println(io, " ", line)
end
end
end
function Base.copy(problem::ControlProblem)
return ControlProblem(problem.trajectories, problem.tlist; problem.kwargs...)
end
"""
```julia
controls = get_controls(problem)
```
extracts the controls from `problem.trajectories`.
"""
get_controls(problem::ControlProblem) = get_controls(problem.trajectories)
"""
```julia
parameters = get_parameters(problem)
```
extracts the `parameters` from `problem.trajectories`.
"""
get_parameters(problem::ControlProblem) = get_parameters(problem.trajectories)
"""
```julia
problem = substitute(problem::ControlProblem, replacements)
```
substitutes in `problem.trajectories`
"""
function substitute(problem::ControlProblem, replacements)
return ControlProblem(
substitute(problem.trajectories, replacements),
problem.tlist;
problem.kwargs...
)
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 685 | # COV_EXCL_START
OBJECTIVE_MSG = """
`Objective` has been renamed to `Trajectory`. This also affects related
parts of the API. for examples, `propagate_objectives` has been renamed to
`propagate_trajectories` and the `objectives` keyword argument in
`ControlProblem` is now as `trajectories` keyword or positional argument.
"""
DEPRECATED = [:Objective, :propagate_objectives]
function Objective(args...; kwargs...)
@error OBJECTIVE_MSG
return Trajectory(args...; kwargs...)
end
function propagate_objectives(args...; kwargs...)
@error OBJECTIVE_MSG
return propagate_trajectories(args...; kwargs...)
end
export Objective
export propagate_objectives
# COV_EXCL_STOP
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 3513 | using QuantumPropagators.Generators: Generator, Operator, _make_generator, evaluate
using QuantumPropagators.Amplitudes: LockedAmplitude, ShapedAmplitude
"""Get a vector of the derivatives of `generator` w.r.t. each control.
```julia
get_control_derivs(generator, controls)
```
return as vector containing the derivative of `generator` with respect to each
control in `controls`. The elements of the vector are either `nothing` if
`generator` does not depend on that particular control, or a function `μ(α)`
that evaluates the derivative for a particular value of the control, see
[`get_control_deriv`](@ref).
"""
function get_control_derivs(generator, controls)
controlderivs = []
for (i, control) in enumerate(controls)
push!(controlderivs, get_control_deriv(generator, control))
end
return [controlderivs...] # narrow eltype
end
get_control_derivs(operator::AbstractMatrix, controls) = [nothing for c ∈ controls]
get_control_derivs(operator::Operator, controls) = [nothing for c ∈ controls]
@doc raw"""
Get the derivative of the generator ``G`` w.r.t. the control ``ϵ(t)``.
```julia
μ = get_control_deriv(generator, control)
```
returns `nothing` if the `generator` (Hamiltonian or Liouvillian) does not
depend on `control`, or a generator
```math
μ = \frac{∂G}{∂ϵ(t)}
```
otherwise. For linear control terms, `μ` will be a static operator, e.g. an
`AbstractMatrix` or an [`Operator`](@ref). For non-linear controls, `μ` will be
time-dependent, e.g. a [`Generator`](@ref). In either case,
[`evaluate`](@ref) should be used to evaluate `μ` into a constant operator
for particular values of the controls and a particular point in time.
For constant generators, e.g. an [`Operator`](@ref), the result is always
`nothing`.
"""
function get_control_deriv(generator::Tuple, control)
return get_control_deriv(_make_generator(generator...), control)
end
function get_control_deriv(generator::Generator, control)
terms = []
drift_offset = length(generator.ops) - length(generator.amplitudes)
for (i, ampl) in enumerate(generator.amplitudes)
∂a╱∂ϵ = get_control_deriv(ampl, control)
if ∂a╱∂ϵ == 0.0
continue
elseif ∂a╱∂ϵ == 1.0
mu_op = generator.ops[i+drift_offset]
push!(terms, mu_op)
else
mu_op = generator.ops[i+drift_offset]
push!(terms, (mu_op, ∂a╱∂ϵ))
end
end
if length(terms) == 0
return nothing
else
return _make_generator(terms...)
end
end
@doc raw"""
```julia
a = get_control_deriv(ampl, control)
```
returns the derivative ``∂a_l(t)/∂ϵ_{l'}(t)`` of the given amplitude
``a_l(\{ϵ_{l''}(t)\}, t)`` with respect to the given control ``ϵ_{l'}(t)``. For
"trivial" amplitudes, where ``a_l(t) ≡ ϵ_l(t)``, the result with be either
`1.0` or `0.0` (depending on whether `ampl ≡ control`). For non-trivial
amplitudes, the result may be another amplitude that depends on the controls
and potentially on time, but can be evaluated to a constant with
[`evaluate`](@ref).
"""
get_control_deriv(ampl::Function, control) = (ampl ≡ control) ? 1.0 : 0.0
get_control_deriv(ampl::Vector, control) = (ampl ≡ control) ? 1.0 : 0.0
get_control_deriv(operator::AbstractMatrix, control) = nothing
get_control_deriv(operator::Operator, control) = nothing
# Amplitudes
get_control_deriv(ampl::LockedAmplitude, control) = 0.0
get_control_deriv(ampl::ShapedAmplitude, control) =
(control ≡ ampl.control) ? LockedAmplitude(ampl.shape) : 0.0
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 27294 | module Functionals
export J_T_ss, J_T_sm, J_T_re
export J_a_fluence
export gate_functional
export make_gate_chi
export make_grad_J_a, make_chi
using LinearAlgebra: axpy!, dot
# default for `via` argument of `make_chi`
function _default_chi_via(trajectories)
if any(isnothing(traj.target_state) for traj in trajectories)
return :states
else
return :tau
end
end
"""Overlaps of target states with propagates states
```julia
τ = taus(Ψ, trajectories)
```
calculates a vector of values ``τ_k = ⟨Ψ_k^{tgt}|Ψ_k⟩`` where ``|Ψ_k^{tgt}⟩``
is the `traj.target_state` of the ``k``'th element of `trajectories` and
``|Ψₖ⟩`` is the ``k``'th element of `Ψ`.
The definition of the τ values with ``Ψ_k^{tgt}`` on the left (overlap of
target states with propagated states, as opposed to overlap of propagated
states with target states) matches Refs. [PalaoPRA2003](@cite)
and [GoerzQ2022](@cite).
The function requires that each trajectory defines a target state.
See also [`taus!`](@ref) for an in-place version that includes well-defined
error handling for any trajectories whose `target_state` property is `nothing`.
"""
function taus(Ψ, trajectories)
# This function does not delegate to `taus!`, in order to make it
# compatible with automatic differentiation, which doesn't support
# mutation.
return [dot(traj.target_state, Ψₖ) for (traj, Ψₖ) in zip(trajectories, Ψ)]
end
"""Overlaps of target states with propagates states, calculated in-place.
```julia
taus!(τ, Ψ, trajectories; ignore_missing_target_state=false)
```
overwrites the complex vector `τ` with the results of
[`taus(Ψ, trajectories)`](@ref taus).
Throws an `ArgumentError` if any of trajectories have a `target_state` of
`nothing`. If `ignore_missing_target_state=true`, values in `τ` instead will
remain unchanged for any trajectories with a missing target state.
"""
function taus!(τ::Vector{ComplexF64}, Ψ, trajectories; ignore_missing_target_state=false)
for (k, (traj, Ψₖ)) in enumerate(zip(trajectories, Ψ))
if !isnothing(traj.target_state)
τ[k] = dot(traj.target_state, Ψₖ)
else
# With `ignore_missing_target_state=true`, we just skip the value.
# This makes `taus!` convenient for calculating τ values in
# Krotov/GRAPE if and only if the function is based on target
# states
if !ignore_missing_target_state
msg = "trajectory[$k] has no `target_state`. Cannot calculate τ = ⟨Ψ_tgt|Ψ⟩"
throw(ArgumentError(msg))
end
end
end
end
@doc raw"""Return a function that calculates ``|χ_k⟩ = -∂J_T/∂⟨Ψ_k|``.
```julia
chi = make_chi(
J_T,
trajectories;
mode=:any,
automatic=:default,
via=(any(isnothing(t.target_state) for t in trajectories) ? :states : :tau),
)
```
creates a function `chi(Ψ, trajectories; τ)` that returns
a vector of states `χ` with ``|χ_k⟩ = -∂J_T/∂⟨Ψ_k|``, where ``|Ψ_k⟩`` is the
k'th element of `Ψ`. These are the states used as the boundary condition for
the backward propagation propagation in Krotov's method and GRAPE. Each
``|χₖ⟩`` is defined as a matrix calculus
[Wirtinger derivative](https://www.ekinakyurek.me/complex-derivatives-wirtinger/),
```math
|χ_k(T)⟩ = -\frac{∂J_T}{∂⟨Ψ_k|} = -\frac{1}{2} ∇_{Ψ_k} J_T\,;\qquad
∇_{Ψ_k} J_T ≡ \frac{∂J_T}{\Re[Ψ_k]} + i \frac{∂J_T}{\Im[Ψ_k]}\,.
```
The function `J_T` must take a vector of states `Ψ` and a vector of
`trajectories` as positional parameters. If `via=:tau`, it must also a vector
`tau` as a keyword argument, see e.g. `J_T_sm`).
that contains the overlap of the states `Ψ` with the target states from the `trajectories`
The derivative can be calculated analytically of automatically (via automatic
differentiation) depending on the value of `mode`. For `mode=:any`, an analytic
derivative is returned if available, with a fallback to an automatic derivative.
If `mode=:analytic`, return an analytically known ``-∂J_T/∂⟨Ψ_k|``, e.g.,
* [`QuantumControl.Functionals.J_T_sm`](@ref) → [`QuantumControl.Functionals.chi_sm`](@ref),
* [`QuantumControl.Functionals.J_T_re`](@ref) → [`QuantumControl.Functionals.chi_re`](@ref),
* [`QuantumControl.Functionals.J_T_ss`](@ref) → [`QuantumControl.Functionals.chi_ss`](@ref).
and throw an error if no analytic derivative is known.
If `mode=:automatic`, return an automatic derivative (even if an analytic
derivative is known). The calculation of an automatic derivative (whether via
`mode=:any` or `mode=:automatic`) requires that a suitable framework (e.g.,
`Zygote` or `FiniteDifferences`) has been loaded. The loaded module must be
passed as `automatic` keyword argument. Alternatively, it can be registered as
a default value for `automatic` by calling
`QuantumControl.set_default_ad_framework`.
When evaluating ``|χ_k⟩`` automatically, if `via=:states` is given , ``|χ_k(T)⟩``
is calculated directly as defined above from the gradient with respect to
the states ``\{|Ψ_k(T)⟩\}``.
If `via=:tau` is given instead, the functional ``J_T`` is considered a function
of overlaps ``τ_k = ⟨Ψ_k^\tgt|Ψ_k(T)⟩``. This requires that all `trajectories`
define a `target_state` and that `J_T` calculates the value of the functional
solely based on the values of `tau` passed as a keyword argument. With only
the complex conjugate ``τ̄_k = ⟨Ψ_k(T)|Ψ_k^\tgt⟩`` having an explicit dependency
on ``⟨Ψ_k(T)|``, the chain rule in this case is
```math
|χ_k(T)⟩
= -\frac{∂J_T}{∂⟨Ψ_k|}
= -\left(
\frac{∂J_T}{∂τ̄_k}
\frac{∂τ̄_k}{∂⟨Ψ_k|}
\right)
= - \frac{1}{2} (∇_{τ_k} J_T) |Ψ_k^\tgt⟩\,.
```
Again, we have used the definition of the Wirtinger derivatives,
```math
\begin{align*}
\frac{∂J_T}{∂τ_k}
&≡ \frac{1}{2}\left(
\frac{∂ J_T}{∂ \Re[τ_k]}
- i \frac{∂ J_T}{∂ \Im[τ_k]}
\right)\,,\\
\frac{∂J_T}{∂τ̄_k}
&≡ \frac{1}{2}\left(
\frac{∂ J_T}{∂ \Re[τ_k]}
+ i \frac{∂ J_T}{∂ \Im[τ_k]}
\right)\,,
\end{align*}
```
and the definition of the Zygote gradient with respect to a complex scalar,
```math
∇_{τ_k} J_T = \left(
\frac{∂ J_T}{∂ \Re[τ_k]}
+ i \frac{∂ J_T}{∂ \Im[τ_k]}
\right)\,.
```
!!! tip
In order to extend `make_chi` with an analytic implementation for a new
`J_T` function, define a new method `make_analytic_chi` like so:
```julia
QuantumControl.Functionals.make_analytic_chi(::typeof(J_T_sm), trajectories) = chi_sm
```
which links `make_chi` for [`QuantumControl.Functionals.J_T_sm`](@ref)
to [`QuantumControl.Functionals.chi_sm`](@ref).
!!! warning
Zygote is notorious for being buggy (silently returning incorrect
gradients). Always test automatic derivatives against finite differences
and/or other automatic differentiation frameworks.
"""
function make_chi(
J_T,
trajectories;
mode=:any,
automatic=:default,
via=_default_chi_via(trajectories),
)
if mode == :any
try
chi = make_analytic_chi(J_T, trajectories)
@debug "make_chi for J_T=$(J_T) -> analytic"
# TODO: call chi to compile it and ensure required properties
return chi
catch exception
if exception isa MethodError
@info "make_chi for J_T=$(J_T): fallback to mode=:automatic"
try
chi = make_automatic_chi(J_T, trajectories, automatic; via)
# TODO: call chi to compile it and ensure required properties
return chi
catch exception
if exception isa MethodError
msg = "make_chi for J_T=$(J_T): no analytic gradient, and no automatic gradient with `automatic=$(repr(automatic))`."
error(msg)
else
rethrow()
end
end
else
rethrow()
end
end
elseif mode == :analytic
try
chi = make_analytic_chi(J_T, trajectories)
# TODO: call chi to compile it and ensure required properties
return chi
catch exception
if exception isa MethodError
msg = "make_chi for J_T=$(J_T): no analytic gradient. Implement `QuantumControl.Functionals.make_analytic_chi(::typeof(J_T), trajectories)`"
error(msg)
else
rethrow()
end
end
elseif mode == :automatic
try
chi = make_automatic_chi(J_T, trajectories, automatic; via)
# TODO: call chi to compile it and ensure required properties
return chi
catch exception
if exception isa MethodError
msg = "make_chi for J_T=$(J_T): no automatic gradient with `automatic=$(repr(automatic))`."
error(msg)
else
rethrow()
end
end
else
msg = "`mode=$(repr(mode))` must be one of :any, :analytic, :automatic"
throw(ArgumentError(msg))
end
end
# Generic placeholder
function make_analytic_chi end
# Module to Symbol-Val
function make_automatic_chi(J_T, trajectories, automatic::Module; via)
return make_automatic_chi(J_T, trajectories, Val(nameof(automatic)); via)
end
# Symbol to Symbol-Val
function make_automatic_chi(J_T, trajectories, automatic::Symbol; via)
return make_automatic_chi(J_T, trajectories, Val(automatic); via)
end
DEFAULT_AD_FRAMEWORK = :nothing
function make_automatic_chi(J_T, trajectories, ::Val{:default}; via)
if DEFAULT_AD_FRAMEWORK == :nothing
msg = "make_chi: no default `automatic`. You must run `QuantumControl.set_default_ad_framework` first, e.g. `import Zygote; QuantumControl.set_default_ad_framework(Zygote)`."
error(msg)
else
automatic = DEFAULT_AD_FRAMEWORK
chi = make_automatic_chi(J_T, trajectories, DEFAULT_AD_FRAMEWORK; via)
(string(automatic) == "default") && error("automatic fallback")
@info "make_chi for J_T=$(J_T): automatic with $automatic"
return chi
end
end
# There is a user-facing wrapper `QuantumControl.set_default_ad_framework`.
# See the documentation there.
function _set_default_ad_framework(mod::Module; quiet=false)
global DEFAULT_AD_FRAMEWORK
automatic = nameof(mod)
if !quiet
@info "QuantumControl: Setting $automatic as the default provider for automatic differentiation."
end
DEFAULT_AD_FRAMEWORK = automatic
return nothing
end
function _set_default_ad_framework(::Nothing; quiet=false)
global DEFAULT_AD_FRAMEWORK
if !quiet
@info "Unsetting the default provider for automatic differentiation."
end
DEFAULT_AD_FRAMEWORK = :nothing
return nothing
end
"""
Return a function to evaluate ``∂J_a/∂ϵ_{ln}`` for a pulse value running cost.
```julia
grad_J_a = make_grad_J_a(
J_a,
tlist;
mode=:any,
automatic=:default,
)
```
returns a function so that `∇J_a = grad_J_a(pulsevals, tlist)` sets
that retrurns a vector `∇J_a` containing the vectorized elements
``∂J_a/∂ϵ_{ln}``. The function `J_a` must have the interface `J_a(pulsevals,
tlist)`, see, e.g., [`J_a_fluence`](@ref).
The parameters `mode` and `automatic` are handled as in [`make_chi`](@ref),
where `mode` is one of `:any`, `:analytic`, `:automatic`, and `automatic` is
he loaded module of an automatic differentiation framework, where `:default`
refers to the framework set with `QuantumControl.set_default_ad_framework`.
!!! tip
In order to extend `make_grad_J_a` with an analytic implementation for a
new `J_a` function, define a new method `make_analytic_grad_J_a` like so:
```julia
make_analytic_grad_J_a(::typeof(J_a_fluence), tlist) = grad_J_a_fluence
```
which links `make_grad_J_a` for [`J_a_fluence`](@ref) to
[`grad_J_a_fluence`](@ref).
"""
function make_grad_J_a(J_a, tlist; mode=:any, automatic=:default)
if mode == :any
try
grad_J_a = make_analytic_grad_J_a(J_a, tlist)
@debug "make_grad_J_a for J_a=$(J_a) -> analytic"
return grad_J_a
catch exception
if exception isa MethodError
@info "make_grad_J_a for J_a=$(J_a): fallback to mode=:automatic"
try
grad_J_a = make_automatic_grad_J_a(J_a, tlist, automatic)
return grad_J_a
catch exception
if exception isa MethodError
msg = "make_grad_J_a for J_a=$(J_a): no analytic gradient, and no automatic gradient with `automatic=$(repr(automatic))`."
error(msg)
else
rethrow()
end
end
else
rethrow()
end
end
elseif mode == :analytic
try
return make_analytic_grad_J_a(J_a, tlist)
catch exception
if exception isa MethodError
msg = "make_grad_J_a for J_a=$(J_a): no analytic gradient. Implement `QuantumControl.Functionals.make_analytic_grad_J_a(::typeof(J_a), tlist)`"
error(msg)
else
rethrow()
end
end
elseif mode == :automatic
try
return make_automatic_grad_J_a(J_a, tlist, automatic)
catch exception
if exception isa MethodError
msg = "make_grad_J_a for J_a=$(J_a): no automatic gradient with `automatic=$(repr(automatic))`."
error(msg)
else
rethrow()
end
end
else
msg = "`mode=$(repr(mode))` must be one of :any, :analytic, :automatic"
throw(ArgumentError(msg))
end
end
function make_automatic_grad_J_a(J_a, tlist, ::Val{:default})
if DEFAULT_AD_FRAMEWORK == :nothing
msg = "make_automatic_grad_J_a: no default `automatic`. You must run `set_default_ad_framework` first, e.g. `import Zygote; QuantumControl.set_default_ad_framework(Zygote)`."
error(msg)
else
automatic = DEFAULT_AD_FRAMEWORK
grad_J_a = make_automatic_grad_J_a(J_a, tlist, DEFAULT_AD_FRAMEWORK)
@info "make_grad_J_a for J_a=$(J_a): automatic with $automatic"
return grad_J_a
end
end
# Generic placeholder
function make_analytic_grad_J_a end
# Module to Symbol-Val
function make_automatic_grad_J_a(J_a, tlist, automatic::Module)
return make_automatic_grad_J_a(J_a, tlist, Val(nameof(automatic)))
end
# Symbol to Symbol-Val
function make_automatic_grad_J_a(J_a, tlist, automatic::Symbol)
return make_automatic_grad_J_a(J_a, tlist, Val(automatic))
end
@doc raw"""
Average complex overlap of the target states with forward-propagated states.
```julia
f_tau(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)
```
calculates
```math
f_τ = \frac{1}{N} \sum_{k=1}^{N} w_k τ_k
```
with
```math
τ_k = ⟨Ψ_k^\tgt|Ψ_k(T)⟩
```
in Hilbert space, or
```math
τ_k = \tr[ρ̂_k^{\tgt\,\dagger} ρ̂_k(T)]
```
in Liouville space, where ``|Ψ_k⟩`` or ``ρ̂_k`` are the elements
of `Ψ`, and ``|Ψ_k^\tgt⟩`` or ``ρ̂_k^\tgt`` are the
target states from the `target_state` field of the `trajectories`. If `tau`/`τ`
is given as a keyword argument, it must contain the values `τ_k` according to
the above definition. Otherwise, the ``τ_k`` values will be calculated
internally, see [`taus`](@ref).
``N`` is the number of trajectories, and ``w_k`` is the `weight` attribute for
each trajectory. The weights are not automatically
normalized, they are assumed to have values such that the resulting ``f_τ``
lies in the unit circle of the complex plane. Usually, this means that the
weights should sum to ``N``.
# Reference
* [PalaoPRA2003](@cite) Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
"""
function f_tau(Ψ, trajectories; tau=nothing, τ=tau)
N = length(trajectories)
if τ === nothing
# If we did this in the function header, we'd redundandly call `taus`
# if the function was called with the keyword parameter τ
τ = taus(Ψ, trajectories)
end
f::ComplexF64 = 0
for (traj, τₖ) in zip(trajectories, τ)
w = traj.weight
f += w * τₖ
end
return f / N
end
@doc raw"""State-to-state phase-insensitive fidelity.
```julia
F_ss(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)
```
calculates
```math
F_{\text{ss}} = \frac{1}{N} \sum_{k=1}^{N} w_k |τ_k|^2 \quad\in [0, 1]
```
with ``N``, ``w_k`` and ``τ_k`` as in [`f_tau`](@ref).
# Reference
* [PalaoPRA2003](@cite) Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
"""
function F_ss(Ψ, trajectories; tau=nothing, τ=tau)
N = length(trajectories)
if τ === nothing
τ = taus(Ψ, trajectories)
end
f::Float64 = 0
for (traj, τₖ) in zip(trajectories, τ)
w = traj.weight
f += w * abs2(τₖ)
end
return f / N
end
@doc raw"""State-to-state phase-insensitive functional.
```julia
J_T_ss(Ψ, trajectories; tau=taus(Ψ, trajectories); τ=tau)
```
calculates
```math
J_{T,\text{ss}} = 1 - F_{\text{ss}} \in [0, 1].
```
All arguments are passed to [`F_ss`](@ref).
# Reference
* [PalaoPRA2003](@cite) Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
"""
function J_T_ss(Ψ, trajectories; tau=nothing, τ=tau)
return 1.0 - F_ss(Ψ, trajectories; τ=τ)
end
@doc raw"""Backward boundary states ``|χ⟩`` for functional [`J_T_ss`](@ref).
```julia
χ = chi_ss(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)
```
calculates the vector of states `χ` according to
```math
|χ_k⟩
= -\frac{∂ J_{T,\text{ss}}}{∂ ⟨Ψ_k(T)|}
= \frac{1}{N} w_k τ_k |Ψ^{\tgt}_k⟩\,,
```
with ``|Ψ^{\tgt}_k⟩``, ``τ_k`` and ``w_k`` as defined in [`f_tau`](@ref).
Note: this function can be obtained with `make_chi(J_T_ss, trajectories)`.
"""
function chi_ss(Ψ, trajectories; tau=nothing, τ=tau)
N = length(trajectories)
if τ === nothing
τ = taus(Ψ, trajectories)
end
χ = Vector{eltype(Ψ)}(undef, length(Ψ))
for (k, traj) in enumerate(trajectories)
w = traj.weight
Ψₖ_tgt = traj.target_state
χ[k] = (τ[k] * w) / N * Ψₖ_tgt
end
return χ
end
make_analytic_chi(::typeof(J_T_ss), trajectories) = chi_ss
# TODO: consider an in-place version of `chi_ss` if the states are mutable
@doc raw"""Square-modulus fidelity.
```julia
F_sm(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)
```
calculates
```math
F_{\text{sm}}
= |f_τ|^2
= \left\vert\frac{1}{N} \sum_{k=1}^{N} w_k τ_k\right\vert^2
= \frac{1}{N^2} \sum_{k=1}^{N} \sum_{j=1}^{N} w_k w_j τ̄_k τ_j
\quad\in [0, 1]\,,
```
with ``w_k`` the weight for the k'th trajectory and ``τ_k`` the overlap of the
k'th propagated state with the k'th target state, ``τ̄_k`` the complex conjugate
of ``τ_k``, and ``N`` the number of trajectories.
All arguments are passed to [`f_tau`](@ref) to evaluate ``f_τ``.
# Reference
* [PalaoPRA2003](@cite) Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
"""
function F_sm(Ψ, trajectories; tau=nothing, τ=tau)
return abs2(f_tau(Ψ, trajectories; τ=τ))
end
@doc raw"""Square-modulus functional.
```julia
J_T_sm(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)
```
calculates
```math
J_{T,\text{sm}} = 1 - F_{\text{sm}} \quad\in [0, 1].
```
All arguments are passed to [`f_tau`](@ref) while evaluating ``F_{\text{sm}}``
in [`F_sm`](@ref).
# Reference
* [PalaoPRA2003](@cite) Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
"""
function J_T_sm(Ψ, trajectories; tau=nothing, τ=tau)
return 1.0 - F_sm(Ψ, trajectories; τ=τ)
end
@doc raw"""Backward boundary states ``|χ⟩`` for functional [`J_T_sm`](@ref).
```julia
χ = chi_sm(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)
```
calculates the vector of states `χ` according to
```math
|χ_k⟩
= -\frac{\partial J_{T,\text{sm}}}{\partial ⟨Ψ_k(T)|}
= \frac{1}{N^2} w_k \sum_{j}^{N} w_j τ_j |Ψ_k^{\tgt}⟩
```
with ``|Ψ^{\tgt}_k⟩``, ``τ_j`` and ``w_k`` as defined in [`f_tau`](@ref).
Note: this function can be obtained with `make_chi(J_T_sm, trajectories)`.
"""
function chi_sm(Ψ, trajectories; tau=nothing, τ=tau)
N = length(trajectories)
if τ === nothing
τ = taus(Ψ, trajectories)
end
w = [traj.weight for traj in trajectories]
a = sum(w .* τ) / N^2
χ = Vector{eltype(Ψ)}(undef, length(Ψ))
for (k, traj) in enumerate(trajectories)
Ψₖ_tgt = traj.target_state
χ[k] = w[k] * a * Ψₖ_tgt
end
return χ
end
make_analytic_chi(::typeof(J_T_sm), trajectories) = chi_sm
# TODO: consider in-place version
@doc raw"""Real-part fidelity.
```julia
F_re(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)
```
calculates
```math
F_{\text{re}}
= \Re[f_{τ}]
= \Re\left[
\frac{1}{N} \sum_{k=1}^{N} w_k τ_k
\right]
\quad\in \begin{cases}
[-1, 1] & \text{in Hilbert space} \\
[0, 1] & \text{in Liouville space.}
\end{cases}
```
with ``w_k`` the weight for the k'th trajectory and ``τ_k`` the overlap of the
k'th propagated state with the k'th target state, and ``N`` the number of
trajectories.
All arguments are passed to [`f_tau`](@ref) to evaluate ``f_τ``.
# Reference
* [PalaoPRA2003](@cite) Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
"""
function F_re(Ψ, trajectories; tau=nothing, τ=tau)
return real(f_tau(Ψ, trajectories; τ=τ))
end
@doc raw"""Real-part functional.
```julia
J_T_re(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)
```
calculates
```math
J_{T,\text{re}} = 1 - F_{\text{re}} \quad\in \begin{cases}
[0, 2] & \text{in Hilbert space} \\
[0, 1] & \text{in Liouville space.}
\end{cases}
```
All arguments are passed to [`f_tau`](@ref) while evaluating ``F_{\text{re}}``
in [`F_re`](@ref).
# Reference
* [PalaoPRA2003](@cite) Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
"""
function J_T_re(Ψ, trajectories; tau=nothing, τ=tau)
return 1.0 - F_re(Ψ, trajectories; τ=τ)
end
@doc raw"""Backward boundary states ``|χ⟩`` for functional [`J_T_re`](@ref).
```julia
χ chi_re(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)
```
calculates the vector of states `χ` according to
```math
|χ_k⟩
= -\frac{∂ J_{T,\text{re}}}{∂ ⟨Ψ_k(T)|}
= \frac{1}{2N} w_k |Ψ^{\tgt}_k⟩
```
with ``|Ψ^{\tgt}_k⟩`` and ``w_k`` as defined in [`f_tau`](@ref).
Note: this function can be obtained with `make_chi(J_T_re, trajectories)`.
"""
function chi_re(Ψ, trajectories; tau=nothing, τ=tau)
N = length(trajectories)
if τ === nothing
τ = taus(Ψ, trajectories)
end
χ = Vector{eltype(Ψ)}(undef, length(Ψ))
for (k, traj) in enumerate(trajectories)
Ψₖ_tgt = traj.target_state
w = traj.weight
χ[k] = (w / (2N)) * Ψₖ_tgt
end
return χ
end
make_analytic_chi(::typeof(J_T_re), trajectories) = chi_re
# TODO: consider in-place version
"""Convert a functional from acting on a gate to acting on propagated states.
```
J_T = gate_functional(J_T_U; kwargs...)
```
constructs a functional `J_T` that meets the requirements for
for Krotov/GRAPE and [`make_chi`](@ref). That is, the output `J_T` takes
positional positional arguments `Ψ` and `trajectories`. The input functional
`J_T_U` is assumed to have the signature `J_T_U(U; kwargs...)` where `U` is a
matrix with elements ``U_{ij} = ⟨Ψ_i|Ψ_j⟩``, where ``|Ψ_i⟩`` is the
`initial_state` of the i'th `trajectories` (assumed to be the i'th canonical
basis state) and ``|Ψ_j⟩`` is the result of forward-propagating ``|Ψ_j⟩``. That
is, `U` is the projection of the time evolution operator into the subspace
defined by the basis in the `initial_states` of the `trajectories`.
# See also
* [`make_gate_chi`](@ref) — create a corresponding `chi` function that acts
more efficiently than the general [`make_chi`](@ref).
"""
function gate_functional(J_T_U; kwargs...)
function J_T(Ψ, trajectories)
N = length(trajectories)
U = [dot(trajectories[i].initial_state, Ψ[j]) for i = 1:N, j = 1:N]
return J_T_U(U; kwargs...)
end
return J_T
end
@doc raw"""
Return a function to evaluate ``|χ_k⟩ = -∂J_T(Û)/∂⟨Ψ_k|`` via the chain rule.
```julia
chi = make_gate_chi(J_T_U, trajectories; automatic=:default, kwargs...)
```
returns a function equivalent to
```julia
chi = make_chi(
gate_functional(J_T_U; kwargs...),
trajectories;
mode=:automatic,
automatic,
)
```
```math
\begin{split}
|χ_k⟩
&= -\frac{∂}{∂⟨Ψ_k|} J_T \\
&= - \frac{1}{2} \sum_i (∇_U J_T)_{ik} \frac{∂ U_{ik}}{∂⟨Ψ_k|} \\
&= - \frac{1}{2} \sum_i (∇_U J_T)_{ik} |Ψ_i⟩
\end{split}
```
where ``|Ψ_i⟩`` is the basis state stored as the `initial_state` of the i'th
trajectory, see [`gate_functional`](@ref).
The gradient ``∇_U J_T`` is obtained via automatic differentiation (AD). This
requires that an AD package has been loaded (e.g., `using Zygote`). This
package must either be passed as the `automatic` keyword argument, or the
package must be set as the default AD provider using
[`QuantumControl.set_default_ad_framework`](@ref).
Compared to the more general [`make_chi`](@ref) with `mode=:automatic`,
`make_gate_chi` will generally have a slightly smaller numerical overhead, as
it pushes the use of automatic differentiation down by one level.
"""
function make_gate_chi(J_T_U, trajectories; automatic=:default, kwargs...)
if automatic == :default
if DEFAULT_AD_FRAMEWORK == :nothing
msg = "make_gate_chi: no default `automatic`. You must run `set_default_ad_framework` first, e.g. `import Zygote; QuantumControl.set_default_ad_framework(Zygote)`."
error(msg)
else
automatic = DEFAULT_AD_FRAMEWORK
chi = make_gate_chi(J_T_U, trajectories, automatic; kwargs...)
@info "make_gate_chi for J_T_U=$(J_T_U): automatic with $automatic"
return chi
end
else
return make_gate_chi(J_T_U, trajectories, automatic; kwargs...)
end
end
function make_gate_chi(J_T_U, trajectories, automatic::Module; kwargs...)
return make_gate_chi(J_T_U, trajectories, Val(nameof(automatic)); kwargs...)
end
function make_gate_chi(J_T_U, trajectories, automatic::Symbol; kwargs...)
return make_gate_chi(J_T_U, trajectories, Val(automatic); kwargs...)
end
@doc raw"""Running cost for the pulse fluence.
```julia
J_a = J_a_fluence(pulsevals, tlist)
```
calculates
```math
J_a = \sum_l \int_0^T |ϵ_l(t)|^2 dt = \left(\sum_{nl} |ϵ_{nl}|^2 \right) dt
```
where ``ϵ_{nl}`` are the values in the (vectorized) `pulsevals`, `n` is the
index of the intervals of the time grid, and ``dt`` is the time step, taken
from the first time interval of `tlist` and assumed to be uniform.
"""
function J_a_fluence(pulsevals, tlist)
dt = tlist[begin+1] - tlist[begin]
return sum(abs2.(pulsevals)) * dt
end
"""Analytic derivative for [`J_a_fluence`](@ref).
```julia
∇J_a = grad_J_a_fluence(pulsevals, tlist)
```
returns the `∇J_a`, which contains the (vectorized) elements ``2 ϵ_{nl} dt``,
where ``ϵ_{nl}`` are the (vectorized) elements of `pulsevals` and ``dt`` is the
time step, taken from the first time interval of `tlist` and assumed to be
uniform.
"""
function grad_J_a_fluence(pulsevals, tlist)
dt = tlist[begin+1] - tlist[begin]
return (2 * dt) * pulsevals
end
make_analytic_grad_J_a(::typeof(J_a_fluence), tlist) = grad_J_a_fluence
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 4946 | using QuantumPropagators.Controls: substitute
using QuantumPropagators.Interfaces: check_state
# from callbacks.jl:
import .make_print_iters
# from check_generator.jl:
import .Interfaces: check_generator
"""Optimize a quantum control problem.
```julia
result = optimize(
problem;
method, # mandatory keyword argument
check=true,
callback=nothing,
print_iters=true,
kwargs...
)
```
optimizes towards a solution of given [`problem`](@ref ControlProblem) with
the given `method`, which should be a `Module` implementing the method, e.g.,
```julia
using Krotov
result = optimize(problem; method=Krotov)
```
If `check` is true (default), the `initial_state` and `generator` of each
trajectory is checked with [`check_state`](@ref) and [`check_generator`](@ref).
Any other keyword argument temporarily overrides the corresponding keyword
argument in [`problem`](@ref ControlProblem). These arguments are available to
the optimizer, see each optimization package's documentation for details.
The `callback` can be given as a function to be called after each iteration in
order to analyze the progress of the optimization or to modify the state of
the optimizer or the current controls. The signature of `callback` is
method-specific, but callbacks should receive a workspace objects as the first
parameter as the first argument, the iteration number as the second parameter,
and then additional method-specific parameters.
The `callback` function may return a tuple of values, and an optimization
method should store these values fore each iteration in a `records` field in
their `Result` object. The `callback` should be called once with an iteration
number of `0` before the first iteration. The `callback` can also be given as a
tuple of vector of functions, which are automatically combined via
[`chain_callbacks`](@ref).
If `print_iters` is `true` (default), an automatic `callback` is created via
the method-specific [`make_print_iters`](@ref) to print the progress of the
optimization after each iteration. This automatic callback runs after any
manually given `callback`.
All remaining keyword argument are method-specific.
To obtain the documentation for which options a particular method uses, run,
e.g.,
```julia
? optimize(problem, ::Val{:Krotov})
```
where `:Krotov` is the name of the module implementing the method. The above is
also the method signature that a `Module` wishing to implement a control method
must define.
The returned `result` object is specific to the optimization method, but should
be a subtype of [`QuantumControl.AbstractOptimizationResult`](@ref).
"""
function optimize(
problem::ControlProblem;
method::Union{Module,Symbol},
check=get(problem.kwargs, :check, true),
print_iters=get(problem.kwargs, :print_iters, true),
callback=get(problem.kwargs, :callback, nothing),
for_expval=true, # undocumented
for_pwc=true, # undocumented
for_time_continuous=false, # undocumented
for_parameterization=false, # undocumented
kwargs...
)
temp_kwargs = copy(problem.kwargs)
merge!(temp_kwargs, kwargs)
callbacks = Any[]
if !isnothing(callback)
if callback isa Union{Tuple,Vector}
@debug "Implicitly combining callback with chain_callbacks"
append!(callbacks, callback)
else
push!(callbacks, callback)
end
end
if print_iters
push!(callbacks, make_print_iters(method; temp_kwargs...))
end
if !isempty(callbacks)
if length(callbacks) > 1
temp_kwargs[:callback] = chain_callbacks(callbacks...)
else
temp_kwargs[:callback] = callbacks[1]
end
end
temp_problem = ControlProblem(;
trajectories=problem.trajectories,
tlist=problem.tlist,
temp_kwargs...
)
if check
# TODO: checks will have to be method-dependent, and then we may not
# need all the `for_...` keyword arguments
for (i, traj) in enumerate(problem.trajectories)
if !check_state(traj.initial_state)
error("The `initial_state` of trajectory $i is not valid")
end
if !check_generator(
traj.generator;
state=traj.initial_state,
tlist=problem.tlist,
for_expval,
for_pwc,
for_time_continuous,
for_parameterization,
)
error("The `generator` of trajectory $i is not valid")
end
end
end
return optimize(temp_problem, method)
end
optimize(problem::ControlProblem, method::Symbol) = optimize(problem, Val(method))
optimize(problem::ControlProblem, method::Module) = optimize(problem, Val(nameof(method)))
#
# Note: Methods *must* be defined in the various optimization packages as e.g.
#
# optimize(problem, method::Val{:krotov}) = optimize_krotov(problem)
#
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 962 | using Pkg
using UUIDs
"""
Print the versions of the packages constituting the `QuantumControl` framework.
```julia
QuantumControl.print_versions()
```
"""
function print_versions()
project_toml = Pkg.TOML.parsefile(joinpath(@__DIR__, "..", "Project.toml"))
version = project_toml["version"]
direct_deps = project_toml["deps"]
deps = Pkg.dependencies()
ignored = ["Pkg", "UUIDs", "IOCapture", "JLD2", "FileIO", "LinearAlgebra"]
pkg_names = [name for name in keys(direct_deps) if name ∉ ignored]
col_width = maximum([length(name) for name in pkg_names])
for name in reverse(pkg_names)
pkginfo = deps[UUIDs.UUID(direct_deps[name])]
if pkginfo.is_tracking_path
println("$(rpad(name, col_width)): $(pkginfo.version) ($(pkginfo.source))")
else
println("$(rpad(name, col_width)): $(pkginfo.version)")
end
end
println("$(rpad("QuantumControl", col_width)): $version")
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 7194 | # Extension of QuantumPropagators.propagate for trajectories
using Logging
import QuantumPropagators
using QuantumPropagators.Controls: substitute, get_controls
# from conditionalthreads.jl: @threadsif
"""Propagate a [`Trajectory`](@ref).
```julia
propagate_trajectory(
traj,
tlist;
initial_state=traj.initial_state,
kwargs...
)
```
propagates `initial_state` under the dynamics described by `traj.generator`. It
takes the same keyword arguments as [`QuantumPropagators.propagate`](@ref),
with default values from any property of `traj` with a `prop_` prefix
(`prop_method`, `prop_inplace`, `prop_callback`, …).
See [`init_prop_trajectory`](@ref) for details.
Note that `method` (a mandatory keyword argument in
[`QuantumPropagators.propagate`](@ref)) must be specified, either as a property
`prop_method` of the trajectory, or by passing a `method` keyword argument
explicitly.
"""
function propagate_trajectory(
traj,
tlist;
_prefixes=["prop_"],
initial_state=traj.initial_state,
kwargs...
)
propagator = init_prop_trajectory(traj, tlist; initial_state, kwargs...)
kwargs = Dict(kwargs...)
prop_kwargs = Dict{Symbol,Any}()
for name in (:storage, :observables, :show_progress, :callback)
for prefix in _prefixes
_traj_name = Symbol(prefix * string(name))
if hasproperty(traj, _traj_name)
prop_kwargs[name] = getproperty(traj, _traj_name)
end
end
if haskey(kwargs, name)
prop_kwargs[name] = kwargs[name]
end
end
@debug "propagate_trajectory: propagate(propagator, …) with kwargs=$(prop_kwargs)"
return QuantumPropagators.propagate(propagator; prop_kwargs...)
end
"""Initialize a propagator for a given [`Trajectory`](@ref).
```
propagator = init_prop_trajectory(
traj,
tlist;
initial_state=traj.initial_state,
kwargs...
)
```
initializes a [`Propagator`](@ref QuantumPropagators.AbstractPropagator) for
the propagation of the `initial_state` under the dynamics described by
`traj.generator`.
All keyword arguments are forwarded to [`QuantumPropagators.init_prop`](@ref),
with default values from any property of `traj` with a `prop_` prefix. That is,
the keyword arguments for the underlying [`QuantumPropagators.init_prop`](@ref)
are determined as follows:
* For any property of `traj` whose name starts with the prefix `prop_`, strip
the prefix and use that property as a keyword argument for `init_prop`. For
example, if `traj.prop_method` is defined, `method=traj.prop_method` will be
passed to `init_prop`. Similarly, `traj.prop_inplace` would be passed as
`inplace=traj.prop_inplace`, etc.
* Any explicitly keyword argument to `init_prop_trajectory` overrides the values
from the properties of `traj`.
Note that the propagation `method` in particular must be specified, as it is a
mandatory keyword argument in [`QuantumPropagators.propagate`](@ref)). Thus,
either `traj` must have a property `prop_method` of the trajectory, or `method`
must be given as an explicit keyword argument.
"""
function init_prop_trajectory(
traj::Trajectory,
tlist;
_prefixes=["prop_"],
_msg="Initializing propagator for trajectory",
_filter_kwargs=false,
_kwargs_dict::Dict{Symbol,Any}=Dict{Symbol,Any}(),
initial_state=traj.initial_state,
verbose=false,
kwargs...
)
#
# The private keyword arguments, `_prefixes`, `_msg`, `_filter_kwargs`,
# `_kwargs_dict` are for internal use when setting up optimal control
# workspace objects (see, e.g., Krotov.jl and GRAPE.jl)
#
# * `_prefixes`: which prefixes to translate into `init_prop` kwargs. For
# example, in Krotov/GRAPE, we have propagators both for the forward and
# backward propagation of each trajectory, and we allow prefixes
# "fw_prop_"/"bw_prop_" in addition to the standard "prop_" prefix.
# * `msg`: The message to show via @debug/@info. This could be customized
# to e.g. "Initializing fw-propagator for trajectory 1/N"
# * `_filter_kwargs`: Whether to filter `kwargs` to `_prefixes`. This
# allows to pass the keyword arguments from `optimize` directly to
# `init_prop_trajectory`. By convention, these use the same
# `prop`/`fw_prop`/`bw_prop` prefixes as the properties of `traj`.
# * `_kwargs_dict`: A dictionary Symbol => Any that collects the arguments
# for `init_prop`. This allows to keep a copy of those arguments,
# especially for arguments that cannot be obtained from the resulting
# propagator, like the propagation callback.
#
empty!(_kwargs_dict)
for prefix in _prefixes
for key in propertynames(traj)
if startswith(string(key), prefix)
_kwargs_dict[Symbol(string(key)[length(prefix)+1:end])] =
getproperty(traj, key)
end
end
end
if _filter_kwargs
for prefix in _prefixes
for (key, val) in kwargs
if startswith(string(key), prefix)
_kwargs_dict[Symbol(string(key)[length(prefix)+1:end])] = val
end
end
end
else
merge!(_kwargs_dict, kwargs)
end
level = verbose ? Logging.Info : Logging.Debug
@logmsg level _msg kwargs = _kwargs_dict
try
return init_prop(initial_state, traj.generator, tlist; verbose, _kwargs_dict...)
catch exception
msg = "Cannot initialize propagation for trajectory"
@error msg exception kwargs = _kwargs_dict
rethrow()
end
end
"""Propagate multiple trajectories in parallel.
```julia
result = propagate_trajectories(
trajectories, tlist; use_threads=true, kwargs...
)
```
runs [`propagate_trajectory`](@ref) for every trajectory in `trajectories`,
collects and returns a vector of results. The propagation happens in parallel
if `use_threads=true` (default). All keyword parameters are passed to
[`propagate_trajectory`](@ref), except that if `initial_state` is given, it
must be a vector of initial states, one for each trajectory. Likewise, to pass
pre-allocated storage arrays to `storage`, a vector of storage arrays must be
passed. A simple `storage=true` will still work to return a vector of storage
results.
"""
function propagate_trajectories(
trajectories,
tlist;
use_threads=true,
storage=nothing,
initial_state=[traj.initial_state for traj in trajectories],
kwargs...
)
result = Vector{Any}(undef, length(trajectories))
@threadsif use_threads for (k, traj) in collect(enumerate(trajectories))
if isnothing(storage) || (storage isa Bool)
result[k] = propagate_trajectory(
traj,
tlist;
storage=storage,
initial_state=initial_state[k],
kwargs...
)
else
result[k] = propagate_trajectory(
traj,
tlist;
storage=storage[k],
initial_state=initial_state[k],
kwargs...
)
end
end
return [result...] # chooses an automatic eltype
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 11367 | module PulseParameterizations
export SquareParameterization,
TanhParameterization,
TanhSqParameterization,
LogisticParameterization,
LogisticSqParameterization,
ParameterizedAmplitude
using QuantumPropagators.Controls: discretize_on_midpoints
using QuantumPropagators.Amplitudes: ControlAmplitude, ShapedAmplitude
import QuantumPropagators.Controls: evaluate, get_controls
import ..Controls: get_control_deriv
#! format: off
"""Specification for a "time-local" pulse parameterization.
The parameterization is given as a collection of three functions:
* ``a(ϵ(t))``
* ``ϵ(a(t))``
* ``∂a/∂ϵ`` as a function of ``ϵ(t)``.
"""
struct PulseParameterization
name::String
a_of_epsilon::Function
epsilon_of_a::Function
da_deps_derivative::Function
end
function Base.show(io::IO, p::PulseParameterization)
print(io, p.name)
end
"""Parameterization a(t) = ϵ²(t), enforcing pulse values ``a(t) ≥ 0``."""
SquareParameterization() = PulseParameterization(
"SquareParameterization()",
ϵ -> begin # a_of_epsilon
a = ϵ^2
end,
a -> begin # epsilon_of_a
a = max(a, 0.0)
ϵ = √a
end,
ϵ -> begin # da_deps_derivative
∂a╱∂ϵ = 2ϵ
end
)
"""Parameterization with a tanh function that enforces `a_min < a(t) < a_max`.
"""
function TanhParameterization(a_min, a_max)
Δ = a_max - a_min
Σ = a_max + a_min
aₚ = eps(1.0) # 2⋅10⁻¹⁶ (machine precision)
@assert a_max > a_min
PulseParameterization(
"TanhParameterization($a_min, $a_max)",
ϵ -> begin # a_of_epsilon
a = tanh(ϵ) * Δ / 2 + Σ / 2
end,
a -> begin # epsilon_of_a
a = clamp(2a / Δ - Σ / Δ, -1 + aₚ, 1 - aₚ)
ϵ = atanh(a) # -18.4 < ϵ < 18.4
end,
ϵ -> begin # da_deps_derivative
∂a╱∂ϵ = (Δ / 2) * sech(ϵ)^2
end
)
end
"""Parameterization with a tanh² function that enforces `0 ≤ a(t) < a_max`.
"""
function TanhSqParameterization(a_max)
aₚ = eps(1.0) # 2⋅10⁻¹⁶ (machine precision)
@assert a_max > 0
PulseParameterization(
"TanhSqParameterization($a_max)",
ϵ -> begin # a_of_epsilon
a = a_max * tanh(ϵ)^2
end,
a -> begin # epsilon_of_a
a = clamp(a / a_max, 0, 1 - aₚ)
ϵ = atanh(√a)
end,
ϵ -> begin # da_deps_derivative
∂a╱∂ϵ = 2a_max * tanh(ϵ) * sech(ϵ)^2
end
)
end
"""
Parameterization with a Logistic function that enforces `a_min < a(t) < a_max`.
"""
function LogisticParameterization(a_min, a_max; k=1.0)
Δ = a_max - a_min
a₀ = eps(0.0) # 5⋅10⁻³²⁴
@assert a_max > a_min
PulseParameterization(
"LogisticParameterization($a_max, $a_max; k=$k)",
ϵ -> begin # a_of_epsilon
a = Δ / (1 + exp(-k * ϵ)) + a_min
end,
a -> begin # epsilon_of_a
a′ = a - a_min
a = max(a′ / (Δ - a′), a₀)
ϵ = log(a) / k
end,
ϵ -> begin # da_deps_derivative
e⁻ᵏᵘ = exp(-k * ϵ)
∂a╱∂ϵ = Δ * k * e⁻ᵏᵘ / (1 + e⁻ᵏᵘ)^2
end
)
end
"""
Parameterization with a Logistic-Square function that enforces `0 ≤ a(t) < a_max`.
"""
function LogisticSqParameterization(a_max; k=1.0)
a₀ = eps(0.0) # 5⋅10⁻³²⁴
@assert a_max > 0
PulseParameterization(
"LogisticSqParameterization($a_max; k=$k)",
ϵ -> begin # a_of_epsilon
a = a_max * (2 / (1 + exp(-k * ϵ)) - 1)^2
end,
a -> begin # epsilon_of_a
ρ = clamp(a / a_max, 0.0, 1.0)
a = clamp((2 / (√ρ + 1)) - 1, a₀, 1.0)
ϵ = -log(a) / k
end,
ϵ -> begin # da_deps_derivative
eᵏᵘ = exp(k * ϵ)
∂a╱∂ϵ = 4k * a_max * eᵏᵘ * (eᵏᵘ - 1) / (eᵏᵘ + 1)^3
end
)
end
#! format: on
#### ParameterizedAmplitude ####################################################
"""An amplitude determined by a pulse parameterization.
That is, ``a(t) = a(ϵ(t))`` with a bijective mapping between the value of
``a(t)`` and ``ϵ(t)``, e.g. ``a(t) = ϵ^2(t)`` (a [`SquareParameterization`](@ref
SquareParameterization)). Optionally, the amplitude may be multiplied with an
additional shape function, cf. [`ShapedAmplitude`](@ref).
```julia
ampl = ParameterizedAmplitude(control; parameterization)
```
initializes ``a(t) = a(ϵ(t)`` where ``ϵ(t)`` is the `control`, and the mandatory
keyword argument `parameterization` is a [`PulseParameterization`](@ref
PulseParameterization). The `control` must either be a vector of values
discretized to the midpoints of a time grid, or a callable `control(t)`.
```julia
ampl = ParameterizedAmplitude(control; parameterization, shape=shape)
```
initializes ``a(t) = S(t) a(ϵ(t))`` where ``S(t)`` is the given `shape`. It
must be a vector if `control` is a vector, or a callable `shape(t)` if
`control` is a callable.
```julia
ampl = ParameterizedAmplitude(control, tlist; parameterization, shape=shape)
```
discretizes `control` and `shape` (if given) to the midpoints of `tlist` before
initialization.
```julia
ampl = ParameterizedAmplitude(
amplitude, tlist; parameterization, shape=shape, parameterize=true
)
```
initializes ``ã(t) = S(t) a(t)`` where ``a(t)`` is the input `amplitude`.
First, if `amplitude` is a callable `amplitude(t)`, it is discretized to the
midpoints of `tlist`. Then, a `control` ``ϵ(t)`` is calculated so that ``a(t) ≈
a(ϵ(t))``. Clippling may occur if the values in `amplitude` cannot represented
with the given `parameterization`. Lastly, `ParameterizedAmplitude(control;
parameterization, shape)` is initialized with the calculated `control`.
Note that the `tlist` keyword argument is required when `parameterize=true` is
given, even if `amplitude` is already a vector.
"""
abstract type ParameterizedAmplitude <: ControlAmplitude end
abstract type ShapedParameterizedAmplitude <: ParameterizedAmplitude end
function ParameterizedAmplitude(
control;
parameterization::PulseParameterization,
shape=nothing
)
if isnothing(shape)
if control isa Vector{Float64}
return ParameterizedPulseAmplitude(control, parameterization)
else
try
ϵ_t = control(0.0)
catch
error(
"A ParameterizedAmplitude control must either be a vector of values or a callable"
)
end
return ParameterizedContinuousAmplitude(control, parameterization)
end
else
if (control isa Vector{Float64}) && (shape isa Vector{Float64})
return ShapedParameterizedPulseAmplitude(control, shape, parameterization)
else
try
ϵ_t = control(0.0)
catch
error(
"A ParameterizedAmplitude control must either be a vector of values or a callable"
)
end
try
S_t = shape(0.0)
catch
error(
"A ParameterizedAmplitude shape must either be a vector of values or a callable"
)
end
return ShapedParameterizedContinuousAmplitude(control, shape, parameterization)
end
end
end
function ParameterizedAmplitude(
control,
tlist;
parameterization::PulseParameterization,
shape=nothing,
parameterize=false
)
control = discretize_on_midpoints(control, tlist)
if parameterize
control = parameterization.epsilon_of_a.(control)
end
if !isnothing(shape)
shape = discretize_on_midpoints(shape, tlist)
end
return ParameterizedAmplitude(control; parameterization, shape)
end
function Base.show(io::IO, ampl::ParameterizedAmplitude)
print(
io,
"ParameterizedAmplitude(::$(typeof(ampl.control)); parameterization=$(ampl.parameterization))"
)
end
function Base.show(io::IO, ampl::ShapedParameterizedAmplitude)
print(
io,
"ParameterizedAmplitude(::$(typeof(ampl.control)); parameterization=$(ampl.parameterization), shape::$(typeof(ampl.shape)))"
)
end
struct ParameterizedPulseAmplitude <: ParameterizedAmplitude
control::Vector{Float64}
parameterization::PulseParameterization
end
function Base.Array(ampl::ParameterizedPulseAmplitude)
return ampl.parameterization.a_of_epsilon.(ampl.control)
end
struct ParameterizedContinuousAmplitude <: ParameterizedAmplitude
control
parameterization::PulseParameterization
end
struct ShapedParameterizedPulseAmplitude <: ShapedParameterizedAmplitude
control::Vector{Float64}
shape::Vector{Float64}
parameterization::PulseParameterization
end
struct ShapedParameterizedContinuousAmplitude <: ShapedParameterizedAmplitude
control
shape
parameterization::PulseParameterization
end
function evaluate(ampl::ParameterizedAmplitude, args...; kwargs...)
ϵ = evaluate(ampl.control, args...; kwargs...)
return ampl.parameterization.a_of_epsilon(ϵ)
end
function evaluate(ampl::ShapedParameterizedAmplitude, args...; kwargs...)
ϵ = evaluate(ampl.control, args...; kwargs...)
S = evaluate(ampl.shape, args...; kwargs...)
return S * ampl.parameterization.a_of_epsilon(ϵ)
end
function Base.Array(ampl::ShapedParameterizedPulseAmplitude)
return ampl.shape .* ampl.parameterization.a_of_epsilon.(ampl.control)
end
function get_controls(ampl::ParameterizedAmplitude)
return (ampl.control,)
end
function get_control_deriv(ampl::ParameterizedAmplitude, control)
if control ≡ ampl.control
return ParameterizationDerivative(control, ampl.parameterization.da_deps_derivative)
else
return 0.0
end
end
function get_control_deriv(ampl::ShapedParameterizedPulseAmplitude, control)
if control ≡ ampl.control
return ShapedParameterizationPulseDerivative(
control,
ampl.parameterization.da_deps_derivative,
ampl.shape
)
else
return 0.0
end
end
function get_control_deriv(ampl::ShapedParameterizedContinuousAmplitude, control)
if control ≡ ampl.control
return ShapedParameterizationContinuousDerivative(
control,
ampl.parameterization.da_deps_derivative,
ampl.shape
)
else
return 0.0
end
end
struct ParameterizationDerivative <: ControlAmplitude
control
func
end
struct ShapedParameterizationPulseDerivative <: ControlAmplitude
control::Vector{Float64}
func
shape::Vector{Float64}
end
struct ShapedParameterizationContinuousDerivative <: ControlAmplitude
control
func
shape
end
function evaluate(deriv::ParameterizationDerivative, args...; vals_dict=IdDict())
ϵ = evaluate(deriv.control, args...; vals_dict)
return deriv.func(ϵ)
end
function evaluate(
deriv::ShapedParameterizationPulseDerivative,
tlist,
n;
vals_dict=IdDict()
)
ϵ = evaluate(deriv.control, tlist, n; vals_dict)
S = evaluate(deriv.shape, tlist, n; vals_dict)
return S * deriv.func(ϵ)
end
function evaluate(
deriv::ShapedParameterizationContinuousDerivative,
tlist,
n;
vals_dict=IdDict()
)
ϵ = evaluate(deriv.control, tlist, n; vals_dict)
S = evaluate(deriv.shape, tlist, n; vals_dict)
return S * deriv.func(ϵ)
end
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 757 | # I'm aware of Reexport.jl, but it doesn't work for QuantumControl.jl
#
# For one thing, `@reexport using QuantumPropagators` re-exports not just the
# members of `QuantumPropagators`, but also `QuantumControlPropagators` itself.
# Also, as far as I can tell `@reexport using QuantumPropagators.Shapes` does
# not work when it's inside a module also called `Shapes`, as we're doing.
#
# Besides, the macro below is pretty trivial
macro reexport_members(modname::Symbol)
mod = getfield(__module__, modname)
member_names = _exported_names(mod)
Expr(:export, member_names...)
end
function _exported_names(m::Module)
return filter!(
x -> (Base.isexported(m, x) && (x != nameof(m))),
names(m; all=true, imported=true)
)
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 3424 | """
Abstract type for the result object returned by [`optimize`](@ref). Any
optimization method implemented on top of `QuantumControl` should subtype
from `AbstractOptimizationResult`. This enables conversion between the results
of different methods, allowing one method to continue an optimization from
another method.
In order for this to work seamlessly, result objects should use a common set of
field names as much as a possible. When a result object requires fields that
cannot be provided by all other result objects, it should have default values
for these field, which can be defined in a custom `Base.convert` method, as,
e.g.,
```julia
function Base.convert(::Type{MyResult}, result::AbstractOptimizationResult)
defaults = Dict{Symbol,Any}(
:f_calls => 0,
:fg_calls => 0,
)
return convert(MyResult, result, defaults)
end
```
Where `f_calls` and `fg_calls` are fields of `MyResult` that are not present in
a given `result` of a different type. The three-argument `convert` is defined
internally for any `AbstractOptimizationResult`.
"""
abstract type AbstractOptimizationResult end
function Base.convert(
::Type{Dict{Symbol,Any}},
result::R
) where {R<:AbstractOptimizationResult}
return Dict{Symbol,Any}(field => getfield(result, field) for field in fieldnames(R))
end
struct MissingResultDataException{R} <: Exception
missing_fields::Vector{Symbol}
end
function Base.showerror(io::IO, err::MissingResultDataException{R}) where {R}
msg = "Missing data for fields $(err.missing_fields) to instantiate $R."
print(io, msg)
end
struct IncompatibleResultsException{R1,R2} <: Exception
missing_fields::Vector{Symbol}
end
function Base.showerror(io::IO, err::IncompatibleResultsException{R1,R2}) where {R1,R2}
msg = "$R2 cannot be converted to $R1: $R2 does not provide required fields $(err.missing_fields). $R1 may need a custom implementation of `Base.convert` that sets values for any field names not provided by all results."
print(io, msg)
end
function Base.convert(
::Type{R},
data::Dict{Symbol,<:Any},
defaults::Dict{Symbol,<:Any}=Dict{Symbol,Any}(),
) where {R<:AbstractOptimizationResult}
function _get(data, field, defaults)
# Can't use `get`, because that would try to evaluate the non-existing
# `defaults[field]` for `fields` that actually exist in `data`.
if haskey(data, field)
return data[field]
else
return defaults[field]
end
end
args = try
[_get(data, field, defaults) for field in fieldnames(R)]
catch exc
if exc isa KeyError
missing_fields = [
field for field in fieldnames(R) if
!(haskey(data, field) || haskey(defaults, field))
]
throw(MissingResultDataException{R}(missing_fields))
else
rethrow()
end
end
return R(args...)
end
function Base.convert(
::Type{R1},
result::R2,
defaults::Dict{Symbol,<:Any}=Dict{Symbol,Any}(),
) where {R1<:AbstractOptimizationResult,R2<:AbstractOptimizationResult}
data = convert(Dict{Symbol,Any}, result)
try
return convert(R1, data, defaults)
catch exc
if exc isa MissingResultDataException{R1}
throw(IncompatibleResultsException{R1,R2}(exc.missing_fields))
else
rethrow()
end
end
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 1261 | using .Functionals: _set_default_ad_framework
"""Set the default provider for automatic differentiation.
```julia
QuantumControl.set_default_ad_framework(mod; quiet=false)
```
registers the given module (package) as the default AD framework.
This determines the default setting for the `automatic` parameter in the
following functions:
* [`QuantumControl.Functionals.make_chi`](@ref)
* [`QuantumControl.Functionals.make_gate_chi`](@ref)
* [`QuantumControl.Functionals.make_grad_J_a`](@ref)
The given `mod` must be a supported AD framework, e.g.,
```julia
import Zygote
QuantumControl.set_default_ad_framework(Zygote)
```
Currently, there is built-in support for `Zygote` and `FiniteDifferences`.
For other packages to be used as the default AD framework, the appropriate
methods for `make_chi` etc. must be defined.
Unless `quiet=true`, calling `set_default_ad_framework` will show a message to
confirm the setting.
To unset the default AD framework, use
```julia
QuantumControl.set_default_ad_framework(nothing)
```
"""
function set_default_ad_framework(mod::Module; quiet=false)
return _set_default_ad_framework(mod; quiet)
end
function set_default_ad_framework(::Nothing; quiet=false)
return _set_default_ad_framework(nothing; quiet)
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 9330 | import Base
import QuantumPropagators
using Printf
using QuantumPropagators.Generators: Generator, Operator
using QuantumPropagators.Controls: _get_parameters
import QuantumPropagators.Controls: substitute, get_controls, get_parameters
"""Description of a state's time evolution.
```julia
Trajectory(
initial_state,
generator;
target_state=nothing,
weight=1.0,
kwargs...
)
```
describes the time evolution of the `initial_state` under a time-dependent
dynamical `generator` (e.g., a Hamiltonian or Liouvillian).
Trajectories are central to quantum control problems: an optimization
functional depends on the result of propagating one or more trajectories. For
example, when optimizing for a quantum gate, the optimization considers the
trajectories of all logical basis states.
In addition to the `initial_state` and `generator`, a `Trajectory` may
include data relevant to the propagation and to evaluating a particular
optimization functional. Most functionals have the notion of a "target state"
that the `initial_state` should evolve towards, which can be given as the
`target_state` keyword argument. In some functionals, different trajectories
enter with different weights [GoerzNJP2014](@cite), which can be given as a
`weight` keyword argument. Any other keyword arguments are also available to a
functional as properties of the `Trajectory` .
A `Trajectory` can also be instantiated using all keyword arguments.
# Properties
All keyword arguments used in the instantiation are available as properties of
the `Trajectory`. At a minimum, this includes `initial_state`, `generator`,
`target_state`, and `weight`.
By convention, properties with a `prop_` prefix, e.g., `prop_method`,
will be taken into account when propagating the trajectory. See
[`propagate_trajectory`](@ref) for details.
"""
struct Trajectory{ST,GT}
initial_state::ST
generator::GT
target_state::Union{Nothing,ST}
weight::Float64
kwargs::Dict{Symbol,Any}
function Trajectory(
initial_state::ST,
generator::GT;
target_state::Union{Nothing,ST}=nothing,
weight=1.0,
kwargs...
) where {ST,GT}
new{ST,GT}(initial_state, generator, target_state, weight, kwargs)
end
end
# All-keyword constructor
function Trajectory(; initial_state, generator, kwargs...)
Trajectory(initial_state, generator; kwargs...)
end
function _show_trajectory(io::IO, traj::Trajectory; multiline=false)
print(io, "Trajectory(")
multiline && print(io, ";")
print(io, multiline ? "\n initial_state=" : "", traj.initial_state)
print(io, multiline ? ",\n generator=" : ", ")
print(io, traj.generator)
has_kwargs = false
has_kwargs |= !isnothing(traj.target_state)
has_kwargs |= (traj.weight ≠ 1.0)
has_kwargs |= !isempty(getfield(traj, :kwargs))
sep = multiline ? ",\n " : "; "
if has_kwargs
if !isnothing(traj.target_state)
print(io, sep, "target_state=", traj.target_state)
sep = multiline ? ",\n " : ", "
end
if traj.weight != 1.0
print(io, sep, "weight=", traj.weight)
sep = multiline ? ",\n " : ", "
end
for (key, val) in getfield(traj, :kwargs)
print(io, sep, key, "=", val)
sep = multiline ? ",\n " : ", "
end
end
print(io, multiline ? "\n)" : ")")
end
function Base.show(io::IO, traj::Trajectory)
if get(io, :typeinfo, Any) <: Trajectory
# printing as part of a vector of trajectories
summary(io, traj)
else
_show_trajectory(io, traj)
end
end
function Base.summary(io::IO, traj::Trajectory)
print(
io,
"Trajectory with ",
summary(traj.initial_state),
" initial state, ",
summary(traj.generator)
)
if isnothing(traj.target_state)
print(io, ", no target state")
else
print(io, ", ", summary(traj.target_state), " target state")
end
if traj.weight != 1.0
print(io, ", weight=", traj.weight)
end
n_kwargs = length(getfield(traj, :kwargs))
if n_kwargs > 0
print(io, " and $n_kwargs extra kwargs")
end
end
function Base.show(io::IO, ::MIME"text/plain", traj::Trajectory)
# This could have been _show_trajectory(…, multiline=true), but the
# non-code representation with `summary` is more useful
println(io, typeof(traj))
println(io, " initial_state: $(summary(traj.initial_state))")
println(io, " generator: $(summary(traj.generator))")
println(io, " target_state: $(summary(traj.target_state))")
if traj.weight != 1.0
println(io, " weight: $(traj.weight)")
end
for (key, val) in getfield(traj, :kwargs)
println(io, " ", key, ": ", repr(val))
end
end
function Base.propertynames(traj::Trajectory, private::Bool=false)
return (
:initial_state,
:generator,
:target_state,
:weight,
keys(getfield(traj, :kwargs))...
)
end
function Base.setproperty!(traj::Trajectory, name::Symbol, value)
error("setproperty!: immutable struct of type Trajectory cannot be changed")
end
function Base.getproperty(traj::Trajectory, name::Symbol)
if name in (:initial_state, :generator, :target_state, :weight)
return getfield(traj, name)
else
kwargs = getfield(traj, :kwargs)
return get(kwargs, name) do
error("type Trajectory has no property $name")
end
end
end
"""
```julia
trajectory = substitute(trajectory::Trajectory, replacements)
trajectories = substitute(trajectories::Vector{<:Trajectory}, replacements)
```
recursively substitutes the `initial_state`, `generator`, and `target_state`.
"""
function substitute(traj::Trajectory, replacements)
initial_state = substitute(traj.initial_state, replacements)
ST = typeof(initial_state)
generator = substitute(traj.generator, replacements)
target_state::Union{Nothing,ST} = nothing
if !isnothing(traj.target_state)
target_state = substitute(traj.target_state, replacements)
end
weight = traj.weight
kwargs = getfield(traj, :kwargs)
return Trajectory(initial_state, generator; target_state, weight, kwargs...)
end
function substitute(trajs::Vector{<:Trajectory}, replacements)
return [substitute(traj, replacements) for traj ∈ trajs]
end
# adjoint for the nested-tuple dynamical generator (e.g. `(H0, (H1, ϵ))`)
function dynamical_generator_adjoint(G::Tuple)
result = []
for part in G
# `copy` materializes the `adjoint` view, so we don't end up with
# unnecessary `Adjoint{Matrix}` instead of Matrix, for example
if isa(part, Tuple)
push!(result, (copy(Base.adjoint(part[1])), part[2]))
else
push!(result, copy(Base.adjoint(part)))
end
end
return Tuple(result)
end
function dynamical_generator_adjoint(G::Generator)
ops = [dynamical_generator_adjoint(op) for op in G.ops]
return Generator(ops, G.amplitudes)
end
function dynamical_generator_adjoint(G::Operator)
ops = [dynamical_generator_adjoint(op) for op in G.ops]
coeffs = [Base.adjoint(c) for c in G.coeffs]
return Operator(ops, G.coeffs)
end
# fallback adjoint
dynamical_generator_adjoint(G) = copy(Base.adjoint(G))
"""Construct the adjoint of a [`Trajectory`](@ref).
```julia
adj_trajectory = adjoint(trajectory)
```
The adjoint trajectory contains the adjoint of
the dynamical generator `traj.generator`. All other fields contain a copy of
the original field value.
The primary purpose of this adjoint is to facilitate the backward propagation
under the adjoint generator that is central to gradient-based optimization
methods such as GRAPE and Krotov's method.
"""
function Base.adjoint(traj::Trajectory)
initial_state = traj.initial_state
generator = dynamical_generator_adjoint(traj.generator)
target_state = traj.target_state
weight = traj.weight
kwargs = getfield(traj, :kwargs)
Trajectory(initial_state, generator; target_state, weight, kwargs...)
end
"""
```julia
controls = get_controls(trajectories)
```
extracts the controls from a list of [trajectories](@ref Trajectory) (i.e.,
from each trajectory's `generator`). Controls that occur multiple times in the
different trajectories will occur only once in the result.
"""
function get_controls(trajectories::Vector{<:Trajectory})
controls = []
seen_control = IdDict{Any,Bool}()
for traj in trajectories
traj_controls = get_controls(traj.generator)
for control in traj_controls
if !haskey(seen_control, control)
push!(controls, control)
seen_control[control] = true
end
end
end
return Tuple(controls)
end
"""
```julia
parameters = get_parameters(trajectories)
```
collects and combines get parameter arrays from all the generators in
[`trajectories`](@ref Trajectory). Note that this allows any custom generator
type to define a custom `get_parameters` method to override the default of
obtaining the parameters recursively from the controls inside the generator.
"""
function get_parameters(trajectories::Vector{<:Trajectory})
return _get_parameters(trajectories; via=(trajs -> [traj.generator for traj in trajs]))
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 13989 | module Workflows
import ..optimize
import ..set_atexit_save_optimization
export run_or_load, @optimize_or_load, save_optimization, load_optimization
using FileIO: FileIO, File, DataFormat
using JLD2: JLD2
using IOCapture
_is_jld2_filename(file) = (file isa String && endswith(file, ".jld2"))
"""
Run some code and write the result to file, or load from the file if it exists.
```julia
data = run_or_load(
file;
save=(endswith(file, ".jld2") ? JLD2.save_object : FileIO.save),
load=(endswith(file, ".jld2") ? JLD2.load_object : FileIO.load),
force=false,
verbose=true,
kwargs...
) do
data = Dict() # ... # something that can be saved to / loaded from file
return data
end
```
runs the code in the block and stores `data` in the given `file`.
If `file` already exists, skip running the code and instead return the data
in `file`.
If `force` is `True`, run the code whether or not `file` exists,
potentially overwriting it.
With `verbose=true`, information about the status of `file` will be shown
as `@info`.
The `data` returned by the code block must be compatible with the format of
`file` and the `save`/`load` functions. When using `JLD2.save_object` and
`JLD2.load_object`, almost any data can be written, so this should be
particularly safe. More generally, when using `FileIO.save` and `FileIO.load`,
see the [FileIO registry](https://juliaio.github.io/FileIO.jl/stable/registry/)
for details. A common examples would be a
[`DataFrame`](https://dataframes.juliadata.org/stable/) being written to a
`.csv` file.
# See also
* [`@optimize_or_load`](@ref) — for wrapping around [`optimize`](@ref)
* [`DrWatson.@produce_or_load`](https://juliadynamics.github.io/DrWatson.jl/stable/save/#DrWatson.@produce_or_load)
— a similar but more opinionated function with automatic naming
"""
function run_or_load(
f::Function,
file;
save::Function=(_is_jld2_filename(file) ? JLD2.save_object : FileIO.save),
load::Function=(_is_jld2_filename(file) ? JLD2.load_object : FileIO.load),
force=false,
verbose=true,
_else=nothing, # undocumented function to run on data if loaded
kwargs...
)
# Using `JLD2.save_object` instead of `FileIO.save` is more flexible:
# `FileIO.save` would require a Dict{String, Any}, whereas `save_object`
# can save pretty much anything.
if file isa AbstractString
filename = file
else
filename = FileIO.filename(file)
end
if force || !isfile(filename)
if verbose
if force && isfile(filename)
@info "Overwriting $(relpath(filename)) (force=true)"
else # if !isfile(filename)
@info "File $(relpath(filename)) does not exist. Creating it now."
end
end
dir, _ = splitdir(filename)
# We want to make sure we can create the output dir *before* we run `f`
mkpath(dir)
data = f()
try
save(file, data; kwargs...)
catch exc
# This "emergency fallback" is undocumented on purpose: it's just
# to be nice and try to preserve the results of long-running
# calculations, but nothing is guaranteed and nobody should rely on
# it.
if exc isa CapturedException
# `showerror` directly for a CapturedException includes the
# backtrace, which we don't want.
exc = exc.ex
end
exc_msg = sprint(showerror, exc)
@error "Error saving data: $exc_msg"
tmp = "$(tempname(; cleanup=false)).jld2"
try
JLD2.save_object(tmp, data)
catch exc_inner
exc_msg = sprint(showerror, exc_inner)
error("Unable to recover by writing data to $tmp: $exc_msg")
end
# Julia < 1.8 doesn't have `else` for `try`
error("""
Recover data with:
using JLD2: load_object
data = load_object($(repr(tmp)))
""")
end
return load(file)
else
data = load(file)
verbose && @info "Loading data from $(relpath(filename))"
if !isnothing(_else)
_else(data)
end
return data
end
end
mutable struct FirstLastBuffer
first::Vector{UInt8}
last::Vector{UInt8}
N::Int64
written::Int64
end
function FirstLastBuffer(N=1024)
first = Vector{UInt8}(undef, N)
last = Vector{UInt8}(undef, N)
FirstLastBuffer(first, last, N, 0)
end
function Base.write(buffer::FirstLastBuffer, data)
for byte in data
if buffer.written < buffer.N
i = buffer.written + 1
buffer.first[i] = byte
else
i = mod((buffer.written - buffer.N), buffer.N) + 1
buffer.last[i] = byte
end
buffer.written += 1
end
end
function Base.take!(buffer::FirstLastBuffer)
N = buffer.N
if buffer.written <= N
result = buffer.first[1:buffer.written]
else
written_last = buffer.written - N
last = view(buffer.last, 1:min(written_last, N))
if written_last <= N
sep = Vector{UInt8}[]
length_result = buffer.written
shift = 0
else
sep = Vector{UInt8}("…\n…")
length_result = 2 * N + length(sep)
shift = -mod(buffer.written - buffer.N, buffer.N)
end
result = Vector{UInt8}(undef, length_result)
result[1:N] .= buffer.first
result[N+1:N+length(sep)] .= sep
result[N+length(sep)+1:end] .= circshift(last, shift)
end
buffer.written = 0
return result
end
function _redirect_to_file(f, logfile)
open(logfile, "w") do io
redirect_stdout(io) do
redirect_stderr(io) do
return f()
end
end
end
end
function _print_loaded_output(data)
if haskey(data, "output")
for line in split(data["output"], "\n")
if !startswith(line, "…")
println(line)
end
end
end
end
# See @optimize_or_load for documentation –
# Only the macro version should be public!
function optimize_or_load(
_filter,
file,
problem;
method,
force=false,
verbose=get(problem.kwargs, :verbose, false),
metadata::Union{Nothing,Dict}=nothing,
logfile=nothing,
kwargs...
)
# _filter is only for attaching metadata to the result
save = FileIO.save
load = FileIO.load
JLD2_fmt = FileIO.DataFormat{:JLD2}
if file isa AbstractString
atexit_filename = file
else
atexit_filename = FileIO.filename(file)
end
data = run_or_load(
File{JLD2_fmt}(file);
save,
load,
force,
verbose,
_else=_print_loaded_output
) do
color = get(stdout, :color, false)
if haskey(ENV, "JULIA_CAPTURE_COLOR")
# Undocumented feature. Literate.jl doesn't work well with captured
# color. When doing an optimization in a Literate example, it's
# best to evaluate it with JULIA_CAPTURE_COLOR=0
color = (ENV["JULIA_CAPTURE_COLOR"] != "0")
end
if isnothing(logfile)
c = IOCapture.capture(
passthrough=true,
capture_buffer=FirstLastBuffer(),
color=color,
) do
optimize(problem; method, verbose, atexit_filename, kwargs...)
end
result = c.value
output = c.output
else
result = _redirect_to_file(logfile) do
optimize(problem; method, verbose, atexit_filename, kwargs...)
end
output = ""
end
data = Dict{String,Any}("result" => result, "output" => output)
if !isnothing(_filter)
data = _filter(data)
end
if !isnothing(metadata)
for (k, v) in metadata
# This should convert pretty much any key to a string
data[String(Symbol(k))] = v
end
end
return data
end
return data["result"]
end
optimize_or_load(file, problem; kwargs...) =
optimize_or_load(nothing, file, problem; kwargs...)
# Given a list of macro arguments, push all keyword parameters to the end.
#
# A macro will receive keyword arguments after ";" as either the first or
# second argument (depending on whether the macro is invoked together with
# `do`). The `reorder_macro_kw_params` function reorders the arguments to put
# the keyword arguments at the end or the argument list, as if they had been
# separated from the positional arguments by a comma instead of a semicolon.
#
# # Example
#
# With
#
# ```
# macro mymacro(exs...)
# @show exs
# exs = reorder_macro_kw_params(exs)
# @show exs
# end
# ```
#
# the `exs` in e.g. `@mymacro(1, 2; a=3, b)` will end up as
#
# ```
# (1, 2, :($(Expr(:kw, :a, 3))), :($(Expr(:kw, :b, :b))))
# ```
#
# instead of the original
#
# ```
# (:($(Expr(:parameters, :($(Expr(:kw, :a, 3))), :b))), 1, 2)
# ```
function reorder_macro_kw_params(exs)
exs = Any[exs...]
i = findfirst([(ex isa Expr && ex.head == :parameters) for ex in exs])
if !isnothing(i)
extra_kw_def = exs[i].args
for ex in extra_kw_def
push!(exs, ex isa Symbol ? Expr(:kw, ex, ex) : ex)
end
deleteat!(exs, i)
end
return Tuple(exs)
end
"""
Run [`optimize`](@ref) and store the result, or load the result if it exists.
```julia
result = @optimize_or_load(
file,
problem;
method,
force=false,
verbose=true,
metadata=nothing,
logfile=nothing,
kwargs...
)
```
runs `result = optimize(problem; method, kwargs...)` and stores
`result` in `file` in the JLD2 format. Note that the `method` keyword argument
is mandatory.
In addition to the `result`, the data in the output `file`
can also contain metadata. By default, this is "script" with the file
name and line number of where `@optimize_or_load` was called, as well as data
from the dict `metadata` mapping arbitrary (string) keys to values.
Lastly, the data contains truncated captured output (up to 1kB of both the
beginning and end of the output) from the optimization.
If `logfile` is given as the path to a file, both `stdout` and `stderr` from
`optimize` are redirected into the given file.
If `file` already exists (and `force=false`), load the `result` from that file
instead of running the optimization, and print any (truncated) captured output.
All other `kwargs` are passed directly to [`optimize`](@ref).
For methods that support this, `@optimize_or_load` will set up a callback to
dump the optimization result to `file` in case of an unexpected program
shutdown, see [`set_atexit_save_optimization`](@ref).
## Related Functions
* [`run_or_load`](@ref) — a function for more general long-running
calculations.
* [`load_optimization`](@ref): Function to load a file produced by
`@optimize_or_load`
"""
macro optimize_or_load(exs...)
exs = reorder_macro_kw_params(exs)
exs = Any[exs...]
_isa_kw = arg -> (arg isa Expr && (arg.head == :kw || arg.head == :(=)))
if (length(exs) < 2) || _isa_kw(exs[1]) || _isa_kw(exs[2])
@show exs
error(
"@optimize_or_load macro must receive `file` and `problem` as positional arguments"
)
end
if (length(exs) > 2) && !_isa_kw(exs[3])
@show exs
error(
"@optimize_or_load macro only takes two positional arguments (`file` and `problem`)"
)
end
file = popfirst!(exs)
problem = popfirst!(exs)
s = QuoteNode(__source__) # source file and line number of calling line
return quote
optimize_or_load($(esc(file)), $(esc(problem)); $(esc.(exs)...)) do data # _filter
data["script"] = relpath(_sourcename($(esc(s))), $(esc(file)))
return data
end
end
end
_sourcename(s) = string(s)
_sourcename(s::LineNumberNode) = string(s.file) * "#" * string(s.line)
"""Write an optimization result to file.
```julia
save_optimization(file, result; metadata=nothing)
```
writes the result obtained from a call to `optimize` to the given `file` in
JLD2 format. If given, `metadata` is a dict of additional data that will be
stored with the result. The `metadata` dict should use strings as keys.
# See also
* [`load_optimization`](@ref): Function to load a file produced by
[`@optimize_or_load`](@ref) or [`save_optimization`](@ref)
* [`@optimize_or_load`](@ref): Run [`optimize`](@ref) and
[`save_optimization`](@ref) in one go.
"""
function save_optimization(file, result; metadata=nothing)
JLD2_fmt = FileIO.DataFormat{:JLD2}
data = Dict{String,Any}("result" => result)
if !isnothing(metadata)
for (k, v) in metadata
# This should convert pretty much any key to a string
data[String(Symbol(k))] = v
end
end
FileIO.save(File{JLD2_fmt}(file), data)
end
"""Load a previously stored optimization.
```julia
result = load_optimization(file; verbose=false, kwargs...)
```
recovers a `result` previously stored by [`@optimize_or_load`](@ref) or
[`save_optimization`](@ref).
```julia
result, metadata = load_optimization(file; return_metadata=true, kwargs...)
```
also obtains a metadata dict, see [`@optimize_or_load`](@ref). This dict maps
string keys to values.
Calling `load_optimization` with `verbose=true` will `@info` the
metadata after loading the file
"""
function load_optimization(file; return_metadata=false, verbose=false, kwargs...)
data = FileIO.load(file)
result = data["result"]
metadata = filter(kv -> (kv[1] != "result"), data)
if verbose
msg = "Loaded optimization result from $(relpath(file))"
@info msg metadata
end
if return_metadata
return result, metadata
else
return result
end
end
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 3783 | using QuantumPropagators
using QuantumPropagators.Controls: get_controls, evaluate
using QuantumPropagators.Interfaces: catch_abbreviated_backtrace
using ..Controls: get_control_deriv
"""
Check an amplitude in a [`Generator`](@ref) in the context of optimal control.
```
@test check_amplitude(
ampl; tlist, for_gradient_optimization=true, quiet=false
)
```
verifies that the given `ampl` is a valid element in the list of `amplitudes`
of a [`Generator`](@ref) object. This checks all the conditions of
[`QuantumPropagators.Interfaces.check_amplitude`](@ref). In addition, the
following conditions must be met.
If `for_gradient_optimization`:
* The function [`get_control_deriv(ampl, control)`](@ref get_control_deriv)
must be defined
* If `ampl` does not depend on `control`, [`get_control_deriv(ampl,
control)`](@ref get_control_deriv) must return `0.0`
* If `ampl` depends on `control`,
[`u = get_control_deriv(ampl, control)`](@ref get_control_deriv) must return
an object `u` so that `evaluate(u, tlist, n)` returns a Number. In most
cases, `u` itself will be a Number. For more unusual amplitudes, e.g., an
amplitude with a non-linear dependency on the controls, `u` may be
another amplitude. The controls in `u` (as obtained by
[`QuantumPropagators.Controls.get_controls`](@ref)) must be a subset of the
controls in `ampl`.
The function returns `true` for a valid amplitude and `false` for an invalid
amplitude. Unless `quiet=true`, it will log an error to indicate which of the
conditions failed.
"""
function check_amplitude(
ampl;
tlist,
for_gradient_optimization=true,
quiet=false,
_message_prefix="" # for recursive calling
)
px = _message_prefix
success =
QuantumPropagators.Interfaces.check_amplitude(ampl; tlist, quiet, _message_prefix)
success || (return false)
if for_gradient_optimization
controls = get_controls(ampl) # guaranteed to work if success still true
dummy_control_aSQeB(t) = rand()
for (j, control) in enumerate(controls)
try
deriv = get_control_deriv(ampl, control)
val = evaluate(deriv, tlist, 1)
if !(val isa Number)
quiet ||
@error "$(px)get_control_deriv(ampl, control) for control $j must return an object that evaluates to a Number, not $(typeof(val))"
success = false
end
deriv_controls = Set(objectid(c) for c in get_controls(deriv))
if deriv_controls ⊈ Set(objectid.(controls))
quiet ||
@error "$(px)get_control_deriv(ampl, control) for control $j must return an object `u` so that `get_controls(u)` is a subset of `get_controls(ampl)`"
success = false
end
catch exc
quiet || @error(
"$(px)get_control_deriv(ampl, control) must be defined for control $j.",
exception = (exc, catch_abbreviated_backtrace())
)
success = false
end
end
@assert dummy_control_aSQeB ∉ controls
try
deriv = get_control_deriv(ampl, dummy_control_aSQeB)
if deriv ≠ 0.0
quiet ||
@error "$(px)get_control_deriv(ampl, control) must return 0.0 if it does not depend on `control`, not $(repr(deriv))"
success = false
end
catch exc
quiet || @error(
"$(px)get_control_deriv(ampl, control) must be defined.",
exception = (exc, catch_abbreviated_backtrace())
)
success = false
end
end
return success
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 6583 | using QuantumPropagators
using QuantumPropagators.Generators: Generator
using QuantumPropagators.Controls: get_controls
using QuantumPropagators.Interfaces: catch_abbreviated_backtrace
using ..Controls: get_control_derivs, get_control_deriv
"""Check the dynamical `generator` in the context of optimal control.
```
@test check_generator(
generator; state, tlist,
for_expval=true, for_pwc=true, for_time_continuous=false,
for_parameterization=false, for_gradient_optimization=true,
atol=1e-15, quiet=false
)
```
verifies the given `generator`. This checks all the conditions of
[`QuantumPropagators.Interfaces.check_generator`](@ref). In addition, the
following conditions must be met.
If `for_gradient_optimization`:
* [`get_control_derivs(generator, controls)`](@ref get_control_derivs) must be
defined and return a vector containing the result of
[`get_control_deriv(generator, control)`](@ref get_control_deriv) for every
`control` in `controls`.
* [`get_control_deriv(generator, control)`](@ref get_control_deriv) must return
an object that passes the less restrictive
[`QuantumPropagators.Interfaces.check_generator`](@ref) if `control` is in
`get_controls(generator)`. The controls in the derivative (if any) must be a
subset of the controls in `generator.`
* [`get_control_deriv(generator, control)`](@ref get_control_deriv) must return
`nothing` if `control` is not in
[`get_controls(generator)`](@ref get_controls)
* If `generator` is a [`Generator`](@ref) instance, every `ampl` in
`generator.amplitudes` must pass [`check_amplitude(ampl; tlist)`](@ref
check_amplitude).
The function returns `true` for a valid generator and `false` for an invalid
generator. Unless `quiet=true`, it will log an error to indicate which of the
conditions failed.
"""
function check_generator(
generator;
state,
tlist,
for_expval=true,
for_pwc=true,
for_time_continuous=false,
for_parameterization=false,
for_gradient_optimization=true,
atol=1e-15,
quiet=false,
_message_prefix="" # for recursive calling
)
px = _message_prefix
success = QuantumPropagators.Interfaces.check_generator(
generator;
state,
tlist,
for_expval,
for_pwc,
for_time_continuous,
for_parameterization,
atol,
quiet,
_message_prefix,
_check_amplitudes=false # amplitudes are checked separately
)
success || (return false)
if for_gradient_optimization
try
controls = get_controls(generator)
control_derivs = get_control_derivs(generator, controls)
if !(control_derivs isa Vector)
quiet ||
@error "$(px)`get_control_derivs(generator, controls)` must return a Vector"
success = false
end
if length(control_derivs) ≠ length(controls)
quiet ||
@error "$(px)`get_control_derivs(generator, controls)` must return a derivative for every `control` in `controls`"
success = false
end
# In general, we can't check for equality between
# `get_control_deriv` and `get_control_deriv`, because `==` may not
# be implemented to compare arbitrary generators by value
catch exc
quiet || @error(
"$(px)`get_control_derivs(generator, controls)` must be defined.",
exception = (exc, catch_abbreviated_backtrace())
)
success = false
end
try
controls = get_controls(generator)
for (i, control) in enumerate(controls)
deriv = get_control_deriv(generator, control)
valid_deriv = check_generator(
deriv;
state,
tlist,
for_expval,
atol,
quiet,
_message_prefix="On `deriv = get_control_deriv(generator, control)` of type $(typeof(deriv)) for control $i: ",
for_gradient_optimization=false
)
if !valid_deriv
quiet ||
@error "$(px)the result of `get_control_deriv(generator, control)` for control $i is not a valid generator"
success = false
else
deriv_controls = Set(objectid(c) for c in get_controls(deriv))
if deriv_controls ⊈ Set(objectid.(controls))
quiet ||
@error "$(px)get_control_deriv(generator, control) for control $i must return an object `D` so that `get_controls(D)` is a subset of `get_controls(generator)`"
success = false
end
end
end
catch exc
quiet || @error(
"$(px)`get_control_deriv(generator, control)` must be defined.",
exception = (exc, catch_abbreviated_backtrace())
)
success = false
end
try
controls = get_controls(generator)
dummy_control_CYRmE(t) = rand()
@assert dummy_control_CYRmE ∉ controls
deriv = get_control_deriv(generator, dummy_control_CYRmE)
if deriv ≢ nothing
quiet ||
@error "$(px)`get_control_deriv(generator, control)` must return `nothing` if `control` is not in `get_controls(generator)`, not $(repr(deriv))"
success = false
end
catch exc
quiet || @error(
"$(px)`get_control_deriv(generator, control)` must return `nothing` if `control` is not in `get_controls(generator)`.",
exception = (exc, catch_abbreviated_backtrace())
)
success = false
end
if generator isa Generator
for (i, ampl) in enumerate(generator.amplitudes)
valid_ampl = check_amplitude(
ampl;
tlist,
for_gradient_optimization,
quiet,
_message_prefix="On ampl $i ($(typeof(ampl))) in `generator`: "
)
if !valid_ampl
quiet ||
@error "$(px)amplitude $i in `generator` does not pass `check_amplitude`"
success = false
end
end
end
end
return success
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 2139 | """
clean([distclean=false])
Clean up build/doc/testing artifacts. Restore to clean checkout state
(distclean)
"""
function clean(; distclean=false, _exit=true)
_glob(folder, ending) =
[name for name in readdir(folder; join=true) if (name |> endswith(ending))]
_glob_star(folder; except=[]) = [
joinpath(folder, name) for
name in readdir(folder) if !(name |> startswith(".") || name ∈ except)
]
_exists(name) = isfile(name) || isdir(name)
_push!(lst, name) = _exists(name) && push!(lst, name)
ROOT = dirname(@__DIR__)
###########################################################################
CLEAN = String[]
for folder in ["", "src", "test"]
append!(CLEAN, _glob(joinpath(ROOT, folder), ".cov"))
end
append!(
CLEAN,
_glob_star(joinpath(ROOT, "docs", "src", "examples"), except=["index.md"])
)
append!(CLEAN, _glob(joinpath(ROOT, "docs", "src", "api"), ".md"))
_push!(CLEAN, joinpath(ROOT, "coverage"))
_push!(CLEAN, joinpath(ROOT, "docs", "build"))
append!(CLEAN, _glob(ROOT, ".info"))
append!(CLEAN, _glob(joinpath(ROOT, ".coverage"), ".info"))
###########################################################################
###########################################################################
DISTCLEAN = String[]
for folder in ["", "docs", "test"]
_push!(DISTCLEAN, joinpath(joinpath(ROOT, folder), "Manifest.toml"))
end
_push!(DISTCLEAN, joinpath(ROOT, "docs", "Project.toml"))
_push!(DISTCLEAN, joinpath(ROOT, "docs", "src", "examples", ".ipynb_checkpoints"))
_push!(DISTCLEAN, joinpath(ROOT, ".JuliaFormatter.toml"))
###########################################################################
for name in CLEAN
@info "rm $name"
rm(name, force=true, recursive=true)
end
if distclean
for name in DISTCLEAN
@info "rm $name"
rm(name, force=true, recursive=true)
end
if _exit
@info "Exiting"
exit(0)
end
end
end
distclean() = clean(distclean=true)
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 1408 | # init file for "make devrepl"
using Revise
using Plots
unicodeplots()
using JuliaFormatter
using QuantumControlTestUtils: test, show_coverage, generate_coverage_html
using LiveServer: LiveServer, serve, servedocs as _servedocs
include(joinpath(@__DIR__, "clean.jl"))
function servedocs(; kwargs...)
clean() # otherwise, we get an infinite loop
ENV["DOCUMENTER_WARN_ONLY"] = "1"
_servedocs(; skip_dirs=["docs/src/api"], kwargs...)
end
REPL_MESSAGE = """
*******************************************************************************
DEVELOPMENT REPL
Revise, JuliaFormatter, LiveServer, Plots with unicode backend are active.
* `help()` – Show this message
* `include("test/runtests.jl")` – Run the entire test suite
* `test()` – Run the entire test suite in a subprocess with coverage
* `show_coverage()` – Print a tabular overview of coverage data
* `generate_coverage_html()` – Generate an HTML coverage report
* `include("docs/make.jl")` – Generate the documentation
* `format(".")` – Apply code formatting to all files
* `servedocs([port=8000, verbose=false])` –
Build and serve the documentation. Automatically recompile and redisplay on
changes
* `clean()` – Clean up build/doc/testing artifacts
* `distclean()` – Restore to a clean checkout state
*******************************************************************************
"""
"""Show help"""
help() = println(REPL_MESSAGE)
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 3053 | using QuantumControl
using QuantumPropagators
using IOCapture
using Test
using SafeTestsets
@testset "QuantumControl versions" begin
captured = IOCapture.capture(passthrough=true) do
QuantumControl.print_versions()
end
qp_exports = QuantumControl._exported_names(QuantumPropagators)
@test :propagate ∈ qp_exports
@test :QuantumControl ∉ qp_exports
end
# Note: comment outer @testset to stop after first @safetestset failure
@time @testset verbose = true "QuantumControl" begin
println("* Propagation (test_propagation.jl):")
@time @safetestset "Propagation" begin
include("test_propagation.jl")
end
println("* Derivatives (test_derives.jl):")
@time @safetestset "Derivatives" begin
include("test_derivs.jl")
end
println("\n* Parameterization (test_parameterization.jl):")
@time @safetestset "Parameterization" begin
include("test_parameterization.jl")
end
println("\n* Functionals (test_functionals.jl):")
@time @safetestset "Functionals" begin
include("test_functionals.jl")
end
println("* Callbacks (test_callbacks.jl):")
@time @safetestset "Callbacks" begin
include("test_callbacks.jl")
end
println("* Optimize-kwargs (test_optimize_kwargs.jl):")
@time @safetestset "Optimize-kwargs" begin
include("test_optimize_kwargs.jl")
end
println("* Dummy Optimization (test_dummy_optimization.jl):")
@time @safetestset "Dummy Optimization" begin
include("test_dummy_optimization.jl")
end
println("* Atexit dumps (test_atexit.jl):")
@time @safetestset "Atexit dumps" begin
include("test_atexit.jl")
end
println("* Trajectories (test_trajectories.jl):")
@time @safetestset "Trajectories" begin
include("test_trajectories.jl")
end
println("* Adjoint Trajectories (test_adjoint_trajectory.jl):")
@time @safetestset "Adjoint Trajectories" begin
include("test_adjoint_trajectory.jl")
end
println("* Control problems (test_control_problems.jl):")
@time @safetestset "Control problems" begin
include("test_control_problems.jl")
end
println("\n* Run-or-load (test_run_or_load.jl):")
@time @safetestset "Run-or-load" begin
include("test_run_or_load.jl")
end
println("\n* Optimize-or-load (test_optimize_or_load.jl):")
@time @safetestset "Optimize-or-load" begin
include("test_optimize_or_load.jl")
end
println("\n* Pulse Parameterizations (test_pulse_parameterizations.jl):")
@time @safetestset "Pulse Parameterizations" begin
include("test_pulse_parameterizations.jl")
end
println("\n* Result Conversion (test_result_conversion.jl):")
@time @safetestset "Result Conversion" begin
include("test_result_conversion.jl")
end
println("* Invalid interfaces (test_invalid_interfaces.jl):")
@time @safetestset "Invalid interfaces" begin
include("test_invalid_interfaces.jl")
end
print("\n")
end;
nothing
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 2792 | using Test
using LinearAlgebra
using QuantumControl: Trajectory
using QuantumControlTestUtils.DummyOptimization: dummy_control_problem
@testset "Sparse trajectory adjoint" begin
traj = dummy_control_problem().trajectories[1]
adj = adjoint(traj)
@test norm(adj.initial_state - traj.initial_state) ≈ 0
@test norm(adj.target_state - traj.target_state) ≈ 0
@test norm(adj.generator[1] - traj.generator[1]') ≈ 0
@test norm(adj.generator[2][1] - traj.generator[2][1]') ≈ 0
@test adj.generator[2][2] == traj.generator[2][2]
end
@testset "Dense trajectory adjoint" begin
traj = dummy_control_problem(density=1.0).trajectories[1]
adj = adjoint(traj)
@test norm(adj.initial_state - traj.initial_state) ≈ 0
@test norm(adj.target_state - traj.target_state) ≈ 0
@test norm(adj.generator[1] - traj.generator[1]') ≈ 0
@test norm(adj.generator[1] - traj.generator[1]) ≈ 0
@test norm(adj.generator[2][1] - traj.generator[2][1]') ≈ 0
@test adj.generator[2][2] == traj.generator[2][2]
end
@testset "Non-Hermitian trajectory adjoint" begin
traj = dummy_control_problem(sparsity=1.0, hermitian=false).trajectories[1]
adj = adjoint(traj)
@test norm(adj.initial_state - traj.initial_state) ≈ 0
@test norm(adj.target_state - traj.target_state) ≈ 0
@test norm(adj.generator[1] - traj.generator[1]') ≈ 0
@test norm(adj.generator[1] - traj.generator[1]) > 0
@test norm(adj.generator[2][1] - traj.generator[2][1]') ≈ 0
@test norm(adj.generator[2][1] - traj.generator[2][1]) > 0
@test adj.generator[2][2] == traj.generator[2][2]
end
@testset "weighted trajectory adjoint" begin
traj0 = dummy_control_problem().trajectories[1]
traj = Trajectory(
initial_state=traj0.initial_state,
generator=traj0.generator,
target_state=traj0.target_state,
weight=0.2
)
adj = adjoint(traj)
@test adj.weight == traj.weight
end
@testset "custom trajectory adjoint" begin
traj0 = dummy_control_problem(hermitian=false).trajectories[1]
traj = Trajectory(
initial_state=traj0.initial_state,
generator=traj0.generator,
gate="CNOT",
weight=0.5,
coeff=1im
)
@test propertynames(traj) ==
(:initial_state, :generator, :target_state, :weight, :coeff, :gate)
kwargs = getfield(traj, :kwargs)
@test :coeff ∈ keys(kwargs)
@test isnothing(traj.target_state)
@test traj.gate == "CNOT"
@test traj.coeff == 1im
adj = adjoint(traj)
@test norm(adj.initial_state - traj.initial_state) ≈ 0
@test norm(adj.generator[1] - traj.generator[1]') ≈ 0
@test norm(adj.generator[1] - traj.generator[1]) > 0
@test adj.gate == "CNOT"
@test adj.weight == 0.5
@test adj.coeff == 1im
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 659 | using Test
using QuantumControl: set_atexit_save_optimization
using QuantumControl: load_optimization
mutable struct Result
msg::String
end
@testset "Test set_atexit_save_optimization" begin
result = Result("Started")
filename = tempname()
n_atexit_hooks = length(Base.atexit_hooks)
set_atexit_save_optimization(filename, result; msg_property=:msg)
@test length(Base.atexit_hooks) == n_atexit_hooks + 1
@test !isfile(filename)
Base.atexit_hooks[1]()
@test isfile(filename)
result_recovered = load_optimization(filename)
@test result_recovered.msg == "Abort: ATEXIT"
popfirst!(Base.atexit_hooks)
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 593 | using Test
using QuantumControl: chain_callbacks
@testset "chain_callbacks" begin
function hook1(wrk, a1, a2, args...)
return (1,)
end
function hook2(wrk, a1, a2, args...)
return (2,)
end
function hook3(wrk, a1, a2, args...)
@test length(args) == 2
return (3.1, 3.2)
end
function hook4(wrk, a1, a2, args...)
return nothing
end
chained = chain_callbacks(hook1, hook2, hook3, hook4)
res = chained(nothing, 0, 0)
@test res == (1, 2, 3.1, 3.2)
@test res[1] isa Int64
@test res[3] isa Float64
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 2911 | using Test
using QuantumPropagators: Cheby
using QuantumPropagators.Controls: substitute, get_controls
using QuantumControl: Trajectory, ControlProblem
using QuantumControlTestUtils.RandomObjects: random_state_vector, random_dynamic_generator
using StableRNGs
@testset "ControlProblem instantiation" begin
rng = StableRNG(3143161816)
N = 10
Ψ0 = random_state_vector(N; rng)
Ψ1 = random_state_vector(N; rng)
Ψ0_tgt = random_state_vector(N; rng)
Ψ1_tgt = random_state_vector(N; rng)
tlist = collect(range(0, 5; length=101))
H = random_dynamic_generator(N, tlist)
problem = ControlProblem(
[
Trajectory(Ψ0, H; target_state=Ψ0_tgt, weight=0.3),
Trajectory(Ψ1, H; target_state=Ψ1_tgt, weight=0.7),
],
tlist,
J_T=(Ψ -> 1.0),
prop_method=Cheby,
iter_stop=10,
)
@test length(problem.trajectories) == 2
@test length(get_controls(problem)) == 1
@test length(problem.kwargs) == 3
@test endswith(
summary(problem),
"ControlProblem with 2 trajectories and 101 time steps"
)
repl_repr = repr("text/plain", problem; context=(:limit => true))
@test contains(repl_repr, "ControlProblem with 2 trajectories and 101 time steps")
@test contains(
repl_repr,
"Trajectory with 10-element Vector{ComplexF64} initial state, Generator with 2 ops and 1 amplitudes, 10-element Vector{ComplexF64} target state, weight=0.3"
)
@test contains(
repl_repr,
"Trajectory with 10-element Vector{ComplexF64} initial state, Generator with 2 ops and 1 amplitudes, 10-element Vector{ComplexF64} target state, weight=0.7"
)
@test contains(repl_repr, ":J_T => ")
@test contains(repl_repr, "tlist: [0.0, 0.05 … 5.0]")
@test contains(repl_repr, ":iter_stop => 10")
@test contains(repl_repr, r":prop_method => .*.Cheby")
problem = ControlProblem([Trajectory(Ψ0, H; target_state=Ψ0_tgt)], [0.0, 0.1])
repl_repr = repr("text/plain", problem; context=(:limit => true))
@test contains(repl_repr, "tlist: [0.0, 0.1]")
end
@testset "ControlProblem substitution" begin
rng = StableRNG(3143161816)
N = 10
Ψ0 = random_state_vector(N; rng)
Ψ1 = random_state_vector(N; rng)
Ψ0_tgt = random_state_vector(N; rng)
Ψ1_tgt = random_state_vector(N; rng)
tlist = collect(range(0, 5; length=101))
ϵ1(t) = 0.0
ϵ2(t) = 1.0
H = random_dynamic_generator(N, tlist; amplitudes=[ϵ1])
problem = ControlProblem(
[
Trajectory(Ψ0, H; target_state=Ψ0_tgt, weight=0.3),
Trajectory(Ψ1, H; target_state=Ψ1_tgt, weight=0.7),
],
tlist,
J_T=(Ψ -> 1.0),
prop_method=Cheby,
iter_stop=10,
)
@test get_controls(problem) == (ϵ1,)
problem2 = substitute(problem, IdDict(ϵ1 => ϵ2))
@test get_controls(problem2) == (ϵ2,)
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 4614 | using Test
using LinearAlgebra
using QuantumControl.Controls: get_control_deriv, get_control_derivs
using QuantumPropagators.Generators
using QuantumPropagators.Controls
using QuantumPropagators: Generator, Operator
using QuantumControlTestUtils.RandomObjects: random_matrix, random_state_vector
using QuantumControl.Interfaces: check_generator, check_amplitude
using QuantumPropagators.Amplitudes: LockedAmplitude, ShapedAmplitude
import QuantumPropagators
import QuantumControl
_AT(::Generator{OT,AT}) where {OT,AT} = AT
struct MySquareAmpl
control::Function
end
struct MyScaledAmpl
c::Number
control::Function
end
function QuantumControl.Controls.get_control_deriv(a::MySquareAmpl, control)
if control ≡ a.control
return MyScaledAmpl(2.0, control)
else
return 0.0
end
end
QuantumPropagators.Controls.get_controls(a::MySquareAmpl) = (a.control,)
QuantumPropagators.Controls.get_controls(a::MyScaledAmpl) = (a.control,)
function QuantumPropagators.Controls.evaluate(a::MySquareAmpl, args...; kwargs...)
v = evaluate(a.control, args...; kwargs...)
return v^2
end
function QuantumPropagators.Controls.evaluate(a::MyScaledAmpl, args...; vals_dict=IdDict())
return a.c * evaluate(a.control, args...; vals_dict)
end
@testset "Standard get_control_derivs" begin
H₀ = random_matrix(5; hermitian=true)
H₁ = random_matrix(5; hermitian=true)
H₂ = random_matrix(5; hermitian=true)
ϵ₁ = t -> 1.0
ϵ₂ = t -> 1.0
H = (H₀, (H₁, ϵ₁), (H₂, ϵ₂))
@test get_control_deriv(ϵ₁, ϵ₁) == 1.0
@test get_control_deriv(ϵ₁, ϵ₂) == 0.0
derivs = get_control_derivs(H₀, (ϵ₁, ϵ₂))
@test all(isnothing.(derivs))
derivs = get_control_derivs(H, (ϵ₁, ϵ₂))
@test derivs[1] isa Matrix{ComplexF64}
@test derivs[2] isa Matrix{ComplexF64}
@test norm(derivs[1] - H₁) < 1e-14
@test norm(derivs[2] - H₂) < 1e-14
for deriv in derivs
O = evaluate(deriv; vals_dict=IdDict(ϵ₁ => 1.1, ϵ₂ => 2.0))
@test O ≡ deriv
end
@test isnothing(get_control_deriv(H, t -> 3.0))
Ψ = random_state_vector(5)
tlist = collect(range(0, 10; length=101))
@test check_generator(H; state=Ψ, tlist, for_gradient_optimization=true)
end
@testset "Nonlinear get_control_derivs" begin
H₀ = random_matrix(5; hermitian=true)
H₁ = random_matrix(5; hermitian=true)
H₂ = random_matrix(5; hermitian=true)
ϵ₁ = t -> 1.0
ϵ₂ = t -> 1.0
H = (H₀, (H₁, MySquareAmpl(ϵ₁)), (H₂, MySquareAmpl(ϵ₂)))
derivs = get_control_derivs(H, (ϵ₁, ϵ₂))
@test derivs[1] isa Generator
@test derivs[2] isa Generator
@test derivs[1].ops[1] ≡ H₁
@test _AT(derivs[1]) ≡ MyScaledAmpl
O₁ = evaluate(derivs[1]; vals_dict=IdDict(ϵ₁ => 1.1, ϵ₂ => 2.0))
@test O₁ isa Operator
@test length(O₁.ops) == length(O₁.coeffs) == 1
@test O₁.ops[1] ≡ H₁
@test O₁.coeffs[1] ≈ (2 * 1.1)
O₂ = evaluate(derivs[2]; vals_dict=IdDict(ϵ₁ => 1.1, ϵ₂ => 2.0))
@test O₂ isa Operator
@test length(O₂.ops) == length(O₂.coeffs) == 1
@test O₂.ops[1] ≡ H₂
@test O₂.coeffs[1] ≈ (2 * 2.0)
@test isnothing(get_control_deriv(H, t -> 3.0))
Ψ = random_state_vector(5)
tlist = collect(range(0, 10; length=101))
@test check_amplitude(H[2][2]; tlist)
@test check_amplitude(H[3][2]; tlist)
@test check_generator(H; state=Ψ, tlist, for_gradient_optimization=true)
end
@testset "LockedAmplitude get_control_derivs" begin
shape(t) = 1.0
tlist = [0.0, 0.5, 1.0]
ampl1 = LockedAmplitude(shape)
ampl2 = LockedAmplitude(shape, tlist)
@test get_control_deriv(ampl1, t -> 0.0) == 0.0
@test get_control_deriv(ampl1, shape) == 0.0
@test get_control_deriv(ampl2, t -> 0.0) == 0.0
@test get_control_deriv(ampl2, shape) == 0.0
end
@testset "ShapedAmplitude get_control_derivs" begin
shape(t) = 1.0
control(t) = 0.5
tlist = [0.0, 0.5, 1.0]
ampl1 = ShapedAmplitude(control; shape)
ampl2 = ShapedAmplitude(control, tlist; shape)
@test get_control_deriv(ampl1, t -> 0.0) == 0.0
@test get_control_deriv(ampl1, shape) == 0.0
@test get_control_deriv(ampl1, control) == LockedAmplitude(shape)
@test get_control_deriv(ampl2, t -> 0.0) == 0.0
@test get_control_deriv(ampl2, shape) == 0.0
control2 = get_controls(ampl2)[1]
@test control2 ≢ control # should have been discretized
@test ampl2.shape ≢ shape # should have been discretized
@test control2 isa Vector{Float64}
@test ampl2.shape isa Vector{Float64}
@test get_control_deriv(ampl2, control2) == LockedAmplitude(ampl2.shape)
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 656 | using Test
using QuantumControl: optimize
using QuantumControl.Controls: get_controls, substitute
using QuantumControlTestUtils.DummyOptimization: dummy_control_problem
@testset "dummy optimization" begin
println("")
problem = dummy_control_problem(n_trajectories=4, n_controls=3)
result = optimize(problem; method=:dummymethod)
@test result.converged
H = problem.trajectories[1].generator
H_opt = substitute(
H,
Dict(
ϵ => ϵ_opt for
(ϵ, ϵ_opt) in zip(get_controls(problem), result.optimized_controls)
)
)
@test get_controls(H_opt)[2] ≡ result.optimized_controls[2]
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 14364 | using Test
using LinearAlgebra
using QuantumControl: QuantumControl, Trajectory
using QuantumControl.Functionals:
J_T_sm,
J_T_re,
J_T_ss,
J_a_fluence,
grad_J_a_fluence,
make_grad_J_a,
make_chi,
chi_re,
chi_sm,
chi_ss,
gate_functional,
make_gate_chi
using QuantumControlTestUtils.RandomObjects: random_state_vector
using QuantumControlTestUtils.DummyOptimization: dummy_control_problem
using TwoQubitWeylChamber: D_PE, gate_concurrence, unitarity
using StableRNGs: StableRNG
using Zygote
using GRAPE: GrapeWrk
using FiniteDifferences
using IOCapture
const 𝕚 = 1im
const ⊗ = kron
N_HILBERT = 10
N = 4
L = 2
N_T = 50
RNG = StableRNG(4290326946)
PROBLEM = dummy_control_problem(;
N=N_HILBERT,
n_trajectories=N,
n_controls=L,
n_steps=N_T,
rng=RNG,
J_T=J_T_sm,
)
@testset "make-chi" begin
# Test that the routine returned by `make_chi` gives the same result
# as the Zygote chi
trajectories = PROBLEM.trajectories
χ1 = [similar(traj.initial_state) for traj in trajectories]
χ2 = [similar(traj.initial_state) for traj in trajectories]
χ3 = [similar(traj.initial_state) for traj in trajectories]
χ4 = [similar(traj.initial_state) for traj in trajectories]
χ5 = [similar(traj.initial_state) for traj in trajectories]
χ6 = [similar(traj.initial_state) for traj in trajectories]
χ7 = [similar(traj.initial_state) for traj in trajectories]
χ8 = [similar(traj.initial_state) for traj in trajectories]
Ψ = [random_state_vector(N_HILBERT; rng=RNG) for k = 1:N]
τ = [traj.target_state ⋅ Ψ[k] for (k, traj) in enumerate(trajectories)]
for functional in (J_T_sm, J_T_re, J_T_ss)
#!format: off
chi_analytical = make_chi(functional, trajectories; mode=:analytic)
chi_auto = make_chi(functional, trajectories)
chi_zyg = make_chi(functional, trajectories; mode=:automatic, automatic=Zygote)
chi_zyg_states = make_chi(functional, trajectories; mode=:automatic, automatic=Zygote, via=:states)
chi_zyg_tau = make_chi(functional, trajectories; mode=:automatic, automatic=Zygote, via=:tau)
chi_fdm = make_chi(functional, trajectories; mode=:automatic, automatic=FiniteDifferences)
chi_fdm_states = make_chi(functional, trajectories; mode=:automatic, automatic=FiniteDifferences, via=:states)
chi_fdm_tau = make_chi(functional, trajectories; mode=:automatic, automatic=FiniteDifferences, via=:tau)
#!format: on
χ1 = chi_analytical(Ψ, trajectories; τ)
χ2 = chi_auto(Ψ, trajectories; τ)
χ3 = chi_zyg(Ψ, trajectories; τ)
χ4 = chi_zyg_states(Ψ, trajectories)
χ5 = chi_zyg_tau(Ψ, trajectories; τ)
χ6 = chi_fdm(Ψ, trajectories; τ)
χ7 = chi_fdm_states(Ψ, trajectories)
χ8 = chi_fdm_tau(Ψ, trajectories; τ)
@test maximum(norm.(χ1 .- χ2)) < 1e-12
@test maximum(norm.(χ1 .- χ3)) < 1e-12
@test maximum(norm.(χ1 .- χ4)) < 1e-12
@test maximum(norm.(χ1 .- χ5)) < 1e-12
@test maximum(norm.(χ1 .- χ6)) < 1e-12
@test maximum(norm.(χ1 .- χ7)) < 1e-12
@test maximum(norm.(χ1 .- χ8)) < 1e-12
end
end
@testset "make-grad-J_a" begin
tlist = PROBLEM.tlist
wrk = GrapeWrk(PROBLEM)
pulsevals = wrk.pulsevals
J_a_val = J_a_fluence(pulsevals, tlist)
@test J_a_val > 0.0
G1 = grad_J_a_fluence(pulsevals, tlist)
grad_J_a_zygote = make_grad_J_a(J_a_fluence, tlist; mode=:automatic, automatic=Zygote)
@test grad_J_a_zygote ≢ grad_J_a_fluence
G2 = grad_J_a_zygote(pulsevals, tlist)
grad_J_a_fdm =
make_grad_J_a(J_a_fluence, tlist; mode=:automatic, automatic=FiniteDifferences)
@test grad_J_a_fdm ≢ grad_J_a_fluence
@test grad_J_a_fdm ≢ grad_J_a_zygote
G3 = grad_J_a_fdm(pulsevals, tlist)
@test 0.0 ≤ norm(G2 - G1) < 1e-12 # zygote can be exact
@test 0.0 < norm(G3 - G1) < 1e-12 # fdm should not be exact
@test 0.0 < norm(G3 - G2) < 1e-10
end
@testset "J_T without analytic derivative" begin
QuantumControl.set_default_ad_framework(nothing; quiet=true)
J_T(ϕ, trajectories; tau=nothing, τ=tau) = 1.0
trajectories = PROBLEM.trajectories
capture = IOCapture.capture(rethrow=Union{}) do
make_chi(J_T, trajectories)
end
@test contains(capture.output, "fallback to mode=:automatic")
@test capture.value isa ErrorException
if capture.value isa ErrorException
@test contains(capture.value.msg, "no default `automatic`")
end
QuantumControl.set_default_ad_framework(Zygote; quiet=true)
capture = IOCapture.capture() do
make_chi(J_T, trajectories)
end
@test capture.value isa Function
@test contains(capture.output, "fallback to mode=:automatic")
@test contains(capture.output, "automatic with Zygote")
capture = IOCapture.capture(rethrow=Union{}) do
make_chi(J_T, trajectories; mode=:analytic)
end
@test capture.value isa ErrorException
if capture.value isa ErrorException
@test contains(capture.value.msg, "no analytic gradient")
end
QuantumControl.set_default_ad_framework(nothing; quiet=true)
end
@testset "J_a without analytic derivative" begin
QuantumControl.set_default_ad_framework(nothing; quiet=true)
J_a(pulsvals, tlist) = 0.0
tlist = [0.0, 1.0]
capture = IOCapture.capture(rethrow=Union{}) do
make_grad_J_a(J_a, tlist)
end
@test contains(capture.output, "fallback to mode=:automatic")
@test capture.value isa ErrorException
if capture.value isa ErrorException
@test contains(capture.value.msg, "no default `automatic`")
end
QuantumControl.set_default_ad_framework(Zygote; quiet=true)
capture = IOCapture.capture() do
make_grad_J_a(J_a, tlist)
end
@test capture.value isa Function
@test contains(capture.output, "fallback to mode=:automatic")
@test contains(capture.output, "automatic with Zygote")
capture = IOCapture.capture(rethrow=Union{}) do
make_grad_J_a(J_a, tlist; mode=:analytic)
end
@test capture.value isa ErrorException
if capture.value isa ErrorException
@test contains(capture.value.msg, "no analytic gradient")
end
QuantumControl.set_default_ad_framework(nothing; quiet=true)
end
module UnsupportedADFramework end
@testset "Unsupported AD Framework (J_T)" begin
QuantumControl.set_default_ad_framework(UnsupportedADFramework; quiet=true)
@test QuantumControl.Functionals.DEFAULT_AD_FRAMEWORK == :UnsupportedADFramework
J_T(ϕ, trajectories; tau=nothing, τ=tau) = 1.0
trajectories = PROBLEM.trajectories
capture = IOCapture.capture(rethrow=Union{}, passthrough=false) do
make_chi(J_T, trajectories)
end
@test contains(capture.output, "fallback to mode=:automatic")
@test capture.value isa ErrorException
if capture.value isa ErrorException
msg = "no analytic gradient, and no automatic gradient"
@test contains(capture.value.msg, msg)
end
capture = IOCapture.capture(rethrow=Union{}, passthrough=false) do
make_chi(J_T, trajectories; automatic=UnsupportedADFramework)
end
@test contains(capture.output, "fallback to mode=:automatic")
@test capture.value isa ErrorException
if capture.value isa ErrorException
msg = "no analytic gradient, and no automatic gradient"
@test contains(capture.value.msg, msg)
end
capture = IOCapture.capture(rethrow=Union{}, passthrough=false) do
make_chi(J_T, trajectories; mode=:automatic, automatic=UnsupportedADFramework)
end
@test capture.value isa ErrorException
if capture.value isa ErrorException
msg = ": no automatic gradient"
@test contains(capture.value.msg, msg)
end
QuantumControl.set_default_ad_framework(nothing; quiet=true)
@test QuantumControl.Functionals.DEFAULT_AD_FRAMEWORK == :nothing
end
@testset "Unsupported AD Framework (J_a)" begin
QuantumControl.set_default_ad_framework(UnsupportedADFramework; quiet=true)
@test QuantumControl.Functionals.DEFAULT_AD_FRAMEWORK == :UnsupportedADFramework
J_a(pulsvals, tlist) = 0.0
tlist = [0.0, 1.0]
capture = IOCapture.capture(rethrow=Union{}, passthrough=false) do
make_grad_J_a(J_a, tlist)
end
@test contains(capture.output, "fallback to mode=:automatic")
@test capture.value isa ErrorException
if capture.value isa ErrorException
msg = "no analytic gradient, and no automatic gradient"
@test contains(capture.value.msg, msg)
end
capture = IOCapture.capture(rethrow=Union{}, passthrough=false) do
make_grad_J_a(J_a, tlist; automatic=UnsupportedADFramework)
end
@test contains(capture.output, "fallback to mode=:automatic")
@test capture.value isa ErrorException
if capture.value isa ErrorException
msg = "no analytic gradient, and no automatic gradient"
@test contains(capture.value.msg, msg)
end
capture = IOCapture.capture(rethrow=Union{}, passthrough=false) do
make_grad_J_a(J_a, tlist; mode=:automatic, automatic=UnsupportedADFramework)
end
@test capture.value isa ErrorException
if capture.value isa ErrorException
msg = ": no automatic gradient"
@test contains(capture.value.msg, msg)
end
QuantumControl.set_default_ad_framework(nothing; quiet=true)
@test QuantumControl.Functionals.DEFAULT_AD_FRAMEWORK == :nothing
end
@testset "invalid functional" begin
QuantumControl.set_default_ad_framework(Zygote; quiet=true)
J_T(ϕ, trajectories) = 1.0 # no τ keyword argument
trajectories = PROBLEM.trajectories
@test_throws ErrorException begin
IOCapture.capture() do
make_chi(J_T, trajectories)
end
end
function J_T_xxx(ϕ, trajectories; tau=nothing, τ=tau)
throw(DomainError("XXX"))
end
@test_throws DomainError begin
IOCapture.capture() do
make_chi(J_T_xxx, trajectories)
end
end
@test_throws DomainError begin
IOCapture.capture() do
make_chi(J_T_xxx, trajectories; mode=:automatic)
end
end
function J_a_xxx(pulsevals, tlist)
throw(DomainError("XXX"))
end
tlist = [0.0, 1.0]
capture = IOCapture.capture() do
make_grad_J_a(J_a_xxx, tlist)
end
grad_J_a = capture.value
@test_throws DomainError begin
grad_J_a(1, tlist)
end
QuantumControl.set_default_ad_framework(nothing; quiet=true)
end
@testset "functionals-tau-no-tau" begin
# Test that the various chi routines give the same result whether they are
# called with ϕ states or with τ values
trajectories = PROBLEM.trajectories
Ψ = [random_state_vector(N_HILBERT; rng=RNG) for k = 1:N]
τ = [traj.target_state ⋅ Ψ[k] for (k, traj) in enumerate(trajectories)]
@test J_T_re(Ψ, trajectories) ≈ J_T_re(nothing, trajectories; τ)
χ1 = chi_re(Ψ, trajectories)
χ2 = chi_re(Ψ, trajectories; τ)
@test maximum(norm.(χ1 .- χ2)) < 1e-12
@test J_T_sm(Ψ, trajectories) ≈ J_T_sm(nothing, trajectories; τ)
χ1 = chi_sm(Ψ, trajectories)
χ2 = chi_sm(Ψ, trajectories; τ)
@test maximum(norm.(χ1 .- χ2)) < 1e-12
@test J_T_ss(Ψ, trajectories) ≈ J_T_ss(nothing, trajectories; τ)
χ1 = chi_ss(Ψ, trajectories)
χ2 = chi_ss(Ψ, trajectories; τ)
@test maximum(norm.(χ1 .- χ2)) < 1e-12
end
@testset "gate functional" begin
CPHASE_lossy = [
0.99 0 0 0
0 0.99 0 0
0 0 0.99 0
0 0 0 0.99𝕚
]
function ket(i::Int64; N=N)
Ψ = zeros(ComplexF64, N)
Ψ[i+1] = 1
return Ψ
end
function ket(indices::Int64...; N=N)
Ψ = ket(indices[1]; N=N)
for i in indices[2:end]
Ψ = Ψ ⊗ ket(i; N=N)
end
return Ψ
end
function ket(label::AbstractString; N=N)
indices = [parse(Int64, digit) for digit in label]
return ket(indices...; N=N)
end
basis = [ket("00"), ket("01"), ket("10"), ket("11")]
J_T_C(U; w=0.5) = w * (1 - gate_concurrence(U)) + (1 - w) * (1 - unitarity(U))
@test 0.6 < gate_concurrence(CPHASE_lossy) < 0.8
@test 0.97 < unitarity(CPHASE_lossy) < 0.99
@test 0.1 < J_T_C(CPHASE_lossy) < 0.2
J_T = gate_functional(J_T_C)
Ψ = transpose(CPHASE_lossy) * basis
trajectories = [Trajectory(Ψ, nothing) for Ψ ∈ basis]
@test J_T(Ψ, trajectories) ≈ J_T_C(CPHASE_lossy)
chi_J_T = make_chi(J_T, trajectories; mode=:automatic, automatic=Zygote)
χ = chi_J_T(Ψ, trajectories)
J_T2 = gate_functional(J_T_C; w=0.1)
@test (J_T2(Ψ, trajectories) - J_T_C(CPHASE_lossy)) < -0.1
chi_J_T2 = make_chi(J_T2, trajectories; mode=:automatic, automatic=Zygote)
χ2 = chi_J_T2(Ψ, trajectories)
QuantumControl.set_default_ad_framework(nothing; quiet=true)
capture = IOCapture.capture(rethrow=Union{}, passthrough=true) do
make_gate_chi(J_T_C, trajectories)
end
@test capture.value isa ErrorException
if capture.value isa ErrorException
@test contains(capture.value.msg, "no default `automatic`")
end
QuantumControl.set_default_ad_framework(Zygote; quiet=true)
capture = IOCapture.capture() do
make_gate_chi(J_T_C, trajectories)
end
@test contains(capture.output, "automatic with Zygote")
chi_J_T_C_zyg = capture.value
χ_zyg = chi_J_T_C_zyg(Ψ, trajectories)
QuantumControl.set_default_ad_framework(FiniteDifferences; quiet=true)
capture = IOCapture.capture() do
make_gate_chi(J_T_C, trajectories)
end
@test contains(capture.output, "automatic with FiniteDifferences")
chi_J_T_C_fdm = capture.value
χ_fdm = chi_J_T_C_fdm(Ψ, trajectories)
@test maximum(norm.(χ_zyg .- χ)) < 1e-12
@test maximum(norm.(χ_zyg .- χ_fdm)) < 1e-12
QuantumControl.set_default_ad_framework(nothing; quiet=true)
chi_J_T_C_zyg2 = make_gate_chi(J_T_C, trajectories; automatic=Zygote, w=0.1)
χ_zyg2 = chi_J_T_C_zyg2(Ψ, trajectories)
chi_J_T_C_fdm2 = make_gate_chi(J_T_C, trajectories; automatic=FiniteDifferences, w=0.1)
χ_fdm2 = chi_J_T_C_fdm2(Ψ, trajectories)
@test maximum(norm.(χ_zyg2 .- χ2)) < 1e-12
@test maximum(norm.(χ_zyg2 .- χ_fdm2)) < 1e-12
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 5002 | using Test
using Logging: with_logger
using LinearAlgebra: I
using QuantumPropagators
using QuantumControl: hamiltonian
using QuantumControlTestUtils.RandomObjects: random_matrix, random_state_vector
using QuantumControl.Interfaces: check_generator, check_amplitude
using IOCapture
import QuantumControl.Controls:
get_control_deriv,
get_controls,
evaluate,
evaluate!,
substitute,
discretize_on_midpoints
struct InvalidGenerator
control
end
# Define the methods required for propagation, but not the methods required
# for gradients
get_controls(G::InvalidGenerator) = (G.control,)
evaluate(G::InvalidGenerator, args...; kwargs...) = I(4)
evaluate!(op, G, args...; kwargs...) = op
substitute(G::InvalidGenerator, args...) = G
struct InvalidAmplitude
control
end
get_controls(a::InvalidAmplitude) = (a.control,)
substitute(a::InvalidAmplitude, args...) = a
evaluate(a::InvalidAmplitude, args...; kwargs...) = evaluate(a.control, args...; kwargs...)
struct InvalidAmplitudeNonPreserving
control
end
function InvalidAmplitudeNonPreserving(control, tlist)
pulse = discretize_on_midpoints(control, tlist)
InvalidAmplitudeNonPreserving(pulse)
end
get_controls(a::InvalidAmplitudeNonPreserving) = (a.control,)
substitute(a::InvalidAmplitudeNonPreserving, args...) = a
evaluate(a::InvalidAmplitudeNonPreserving, args...; kwargs...) =
evaluate(a.control, args...; kwargs...)
function get_control_deriv(a::InvalidAmplitudeNonPreserving, control)
if control ≡ a.control
if a.control isa Function
return InvalidAmplitudeNonPreserving(t -> a.control(t))
else
return InvalidAmplitudeNonPreserving(copy(a.control))
end
# The `copy` above is the "non-preserving" problematic behavior
else
return 0.0
end
end
struct InvalidAmplitudeWrongDeriv
control
end
get_controls(a::InvalidAmplitudeWrongDeriv) = (a.control,)
substitute(a::InvalidAmplitudeWrongDeriv, args...) = a
evaluate(a::InvalidAmplitudeWrongDeriv, args...; kwargs...) =
evaluate(a.control, args...; kwargs...)
get_control_deriv(::InvalidAmplitudeWrongDeriv, control) = nothing
@testset "Invalid generator" begin
state = ComplexF64[1, 0, 0, 0]
tlist = collect(range(0, 10, length=101))
generator = InvalidGenerator(t -> 1.0)
@test QuantumPropagators.Interfaces.check_generator(generator; state, tlist)
captured = IOCapture.capture(rethrow=Union{}, passthrough=false) do
check_generator(generator; state, tlist)
end
@test captured.value ≡ false
@test contains(
captured.output,
"`get_control_derivs(generator, controls)` must be defined"
)
@test contains(
captured.output,
"`get_control_deriv(generator, control)` must return `nothing` if `control` is not in `get_controls(generator)`"
)
H₀ = random_matrix(4; hermitian=true)
H₁ = random_matrix(4; hermitian=true)
ampl = InvalidAmplitudeNonPreserving(t -> 1.0)
generator = hamiltonian(H₀, (H₁, ampl))
captured = IOCapture.capture(rethrow=Union{}, passthrough=false) do
check_generator(generator; state, tlist)
end
@test captured.value ≡ false
@test contains(
captured.output,
"must return an object `D` so that `get_controls(D)` is a subset of `get_controls(generator)`"
)
end
@testset "Invalid amplitudes" begin
N = 5
state = random_state_vector(N)
tlist = collect(range(0, 10, length=101))
H₀ = random_matrix(5; hermitian=true)
H₁ = random_matrix(5; hermitian=true)
ampl = InvalidAmplitude(t -> 1.0)
@test QuantumPropagators.Interfaces.check_amplitude(ampl; tlist)
H = hamiltonian(H₀, (H₁, ampl))
@test QuantumPropagators.Interfaces.check_generator(H; state, tlist)
captured = IOCapture.capture(rethrow=Union{}, passthrough=false) do
check_generator(H; state, tlist)
end
@test captured.value ≡ false
@test contains(captured.output, "get_control_deriv(ampl, control) must be defined")
ampl = InvalidAmplitudeWrongDeriv(t -> 1.0)
captured = IOCapture.capture(rethrow=Union{}, passthrough=false) do
check_amplitude(ampl; tlist)
end
@test contains(
captured.output,
"get_control_deriv(ampl, control) for control 1 must return an object that evaluates to a Number"
)
@test contains(
captured.output,
"get_control_deriv(ampl, control) must return 0.0 if it does not depend on `control`"
)
ampl = InvalidAmplitudeNonPreserving(t -> 1.0, tlist)
deriv = get_control_deriv(ampl, ampl.control)
@test get_controls(ampl)[1] ≢ get_controls(deriv)[1] # This is the "bug"
captured = IOCapture.capture(rethrow=Union{}, passthrough=false) do
check_amplitude(ampl; tlist)
end
@test contains(
captured.output,
"must return an object `u` so that `get_controls(u)` is a subset of `get_controls(ampl)`"
)
@test captured.value ≡ false
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 1130 | using Test
import QuantumControl
using QuantumControl: ControlProblem, Trajectory
@testset "optimize-kwargs" begin
# test that we can call optimize with kwargs that override the kwargs of
# the `problem` without permanently changing `problem`
struct Result
iter_stop::Int
flag::Bool
end
function optimize_kwargstest(problem)
return Result(problem.kwargs[:iter_stop], problem.kwargs[:flag])
end
QuantumControl.optimize(problem, method::Val{:kwargstest}) =
optimize_kwargstest(problem)
problem = ControlProblem(
[Trajectory(nothing, nothing)],
pulse_options=Dict(),
tlist=[0.0, 10.0],
iter_stop=2,
flag=false
)
res = QuantumControl.optimize(problem; method=:kwargstest, check=false)
@test res.iter_stop == 2
@test !res.flag
res2 = QuantumControl.optimize(
problem;
method=:kwargstest,
iter_stop=10,
flag=true,
check=false
)
@test res2.iter_stop == 10
@test res2.flag
@test problem.kwargs[:iter_stop] == 2
@test !problem.kwargs[:flag]
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 4045 | using Test
using IOCapture
using QuantumControl: @optimize_or_load, load_optimization, save_optimization, optimize
using QuantumControlTestUtils.DummyOptimization:
dummy_control_problem, DummyOptimizationResult
@testset "metadata" begin
problem = dummy_control_problem()
outdir = mktempdir()
outfile = joinpath(outdir, "optimization_with_metadata.jld2")
captured = IOCapture.capture(passthrough=false) do
result = @optimize_or_load(
outfile,
problem;
method=:dummymethod,
metadata=Dict("testset" => "metadata", "method" => :dummymethod,)
)
end
result = captured.value
@test result.converged
@test isfile(outfile)
result_load, metadata = load_optimization(outfile; return_metadata=true)
@test result_load isa DummyOptimizationResult
@test result_load.message == "Reached maximum number of iterations"
@test metadata["testset"] == "metadata"
@test metadata["method"] == :dummymethod
outfile2 = joinpath(outdir, "optimization_with_metadata2.jld2")
save_optimization(outfile2, result_load; metadata)
@test isfile(outfile2)
result_load2, metadata2 = load_optimization(outfile2; return_metadata=true)
@test result_load2 isa DummyOptimizationResult
@test result_load2.message == "Reached maximum number of iterations"
@test metadata2["testset"] == "metadata"
@test metadata2["method"] == :dummymethod
end
@testset "continue_from" begin
problem = dummy_control_problem()
outdir = mktempdir()
outfile = joinpath(outdir, "optimization_stage1.jld2")
println("")
captured = IOCapture.capture(passthrough=false, color=true) do
@optimize_or_load(outfile, problem; iter_stop=5, method=:dummymethod)
end
result = captured.value
@test result.converged
result1 = load_optimization(outfile)
captured = IOCapture.capture(passthrough=false, color=true) do
optimize(problem; method=:dummymethod, iter_stop=15, continue_from=result1)
end
result2 = captured.value
@test result2.iter == 15
end
@testset "captured output" begin
problem = dummy_control_problem(verbose=true)
outdir = mktempdir()
outfile = joinpath(outdir, "optimization_with_output.jld2")
captured = IOCapture.capture(passthrough=false) do
result = @optimize_or_load(outfile, problem; iter_stop=300, method=:dummymethod,)
end
@test contains(captured.output, "\n 200\t7.")
captured = IOCapture.capture(passthrough=false) do
result = @optimize_or_load(outfile, problem; iter_stop=300, method=:dummymethod,)
end
@test contains(captured.output, "Info: Loading data")
@test !contains(captured.output, "\n 200\t7.")
@test contains(captured.output, "\n 6…")
end
@testset "optimization logfile" begin
problem = dummy_control_problem(verbose=true)
outdir = mktempdir()
outfile = joinpath(outdir, "optimization_with_logfile.jld2")
logfile = joinpath(outdir, "oct.log")
captured = IOCapture.capture(passthrough=false) do
result = @optimize_or_load(
outfile,
problem;
iter_stop=300,
method=:dummymethod,
logfile,
)
end
@test !contains(captured.output, "# iter\tJ_T\n")
@test isfile(logfile)
if isfile(logfile)
logfile_text = read(logfile, String)
@test startswith(logfile_text, "# iter\tJ_T\n")
@test contains(logfile_text, "\n 200\t7.") # not truncated
end
captured = IOCapture.capture(passthrough=false) do
result = @optimize_or_load(
outfile,
problem;
iter_stop=300,
method=:dummymethod,
logfile,
)
end
@test !contains(captured.output, "# iter\tJ_T\n")
@test isfile(logfile)
if isfile(logfile)
logfile_text = read(logfile, String)
@test startswith(logfile_text, "# iter\tJ_T\n")
@test contains(logfile_text, "\n 200\t7.") # not truncated
end
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 6645 | using ComponentArrays
using RecursiveArrayTools # to ensure extension is loaded
using UnPack: @unpack
using QuantumPropagators: hamiltonian
using QuantumPropagators.Controls: ParameterizedFunction, get_parameters
using QuantumControl: ControlProblem, Trajectory
using Test
struct GaussianControl <: ParameterizedFunction
parameters::ComponentVector{Float64,Vector{Float64},Tuple{Axis{(A=1, t₀=2, σ=3)}}}
GaussianControl(; kwargs...) = new(ComponentVector(; kwargs...))
end
function (control::GaussianControl)(t)
@unpack A, t₀, σ = control.parameters
return A * exp(-(t - t₀)^2 / (2 * σ^2))
end
const 𝕚 = 1im
function total_enantiomer_ham(parameters; sign, a, independent_parameters=false, kwargs...)
μ = (sign == "-" ? -1 : 1)
H₁Re = μ * ComplexF64[0 1 0; 1 0 0; 0 0 0]
H₁Im = μ * ComplexF64[0 𝕚 0; -𝕚 0 0; 0 0 0]
H₂Re = μ * ComplexF64[0 0 0; 0 0 1; 0 1 0]
H₂Im = μ * ComplexF64[0 0 0; 0 0 𝕚; 0 -𝕚 0]
H₃Re = μ * ComplexF64[0 0 1; 0 0 0; 1 0 0]
H₃Im = μ * ComplexF64[0 0 𝕚; 0 0 0; -𝕚 0 0]
if independent_parameters
# This doesn't make sense physically, but it's a good way to test
# collecting multiple parameter arrays
return hamiltonian(
(H₁Re, TEH_field1Re(copy(parameters), a)),
(H₁Im, TEH_field1Im(copy(parameters), a)),
(H₂Re, TEH_field2Re(copy(parameters), a)),
(H₂Im, TEH_field2Im(copy(parameters), a)),
(H₃Re, TEH_field3Re(copy(parameters), a)),
(H₃Im, TEH_field3Im(copy(parameters), a));
kwargs...
)
else
return hamiltonian(
(H₁Re, TEH_field1Re(parameters, a)),
(H₁Im, TEH_field1Im(parameters, a)),
(H₂Re, TEH_field2Re(parameters, a)),
(H₂Im, TEH_field2Im(parameters, a)),
(H₃Re, TEH_field3Re(parameters, a)),
(H₃Im, TEH_field3Im(parameters, a));
kwargs...
)
end
end
struct TEH_field1Re <: ParameterizedFunction
parameters::ComponentVector{
Float64,
Vector{Float64},
Tuple{Axis{(ΔT₁=1, ΔT₂=2, ΔT₃=3, ϕ₁=4, ϕ₂=5, ϕ₃=6, E₀₁=7, E₀₂=8, E₀₃=9)}}
}
a::Float64
end
function (E::TEH_field1Re)(t)
@unpack E₀₁, ΔT₁, ϕ₁ = E.parameters
_tanhfield(t; E₀=E₀₁, t₁=0.0, t₂=ΔT₁, a=E.a) * cos(ϕ₁)
end
struct TEH_field2Re <: ParameterizedFunction
parameters::ComponentVector{
Float64,
Vector{Float64},
Tuple{Axis{(ΔT₁=1, ΔT₂=2, ΔT₃=3, ϕ₁=4, ϕ₂=5, ϕ₃=6, E₀₁=7, E₀₂=8, E₀₃=9)}}
}
a::Float64
end
function (E::TEH_field2Re)(t)
@unpack E₀₂, ΔT₁, ΔT₂, ϕ₂ = E.parameters
_tanhfield(t; E₀=E₀₂, t₁=ΔT₁, t₂=(ΔT₁ + ΔT₂), a=E.a) * cos(ϕ₂)
end
struct TEH_field3Re <: ParameterizedFunction
parameters::ComponentVector{
Float64,
Vector{Float64},
Tuple{Axis{(ΔT₁=1, ΔT₂=2, ΔT₃=3, ϕ₁=4, ϕ₂=5, ϕ₃=6, E₀₁=7, E₀₂=8, E₀₃=9)}}
}
a::Float64
end
function (E::TEH_field3Re)(t)
@unpack E₀₃, ΔT₁, ΔT₂, ΔT₃, ϕ₃ = E.parameters
_tanhfield(t; E₀=E₀₃, t₁=(ΔT₁ + ΔT₂), t₂=(ΔT₁ + ΔT₂ + ΔT₃), a=E.a) * cos(ϕ₃)
end
struct TEH_field1Im <: ParameterizedFunction
parameters::ComponentVector{
Float64,
Vector{Float64},
Tuple{Axis{(ΔT₁=1, ΔT₂=2, ΔT₃=3, ϕ₁=4, ϕ₂=5, ϕ₃=6, E₀₁=7, E₀₂=8, E₀₃=9)}}
}
a::Float64
end
function (E::TEH_field1Im)(t)
@unpack E₀₁, ΔT₁, ϕ₁ = E.parameters
_tanhfield(t; E₀=E₀₁, t₁=0.0, t₂=ΔT₁, a=E.a) * sin(ϕ₁)
end
struct TEH_field2Im <: ParameterizedFunction
parameters::ComponentVector{
Float64,
Vector{Float64},
Tuple{Axis{(ΔT₁=1, ΔT₂=2, ΔT₃=3, ϕ₁=4, ϕ₂=5, ϕ₃=6, E₀₁=7, E₀₂=8, E₀₃=9)}}
}
a::Float64
end
function (E::TEH_field2Im)(t)
@unpack E₀₂, ΔT₁, ΔT₂, ϕ₂ = E.parameters
_tanhfield(t; E₀=E₀₂, t₁=ΔT₁, t₂=(ΔT₁ + ΔT₂), a=E.a) * sin(ϕ₂)
end
struct TEH_field3Im <: ParameterizedFunction
parameters::ComponentVector{
Float64,
Vector{Float64},
Tuple{Axis{(ΔT₁=1, ΔT₂=2, ΔT₃=3, ϕ₁=4, ϕ₂=5, ϕ₃=6, E₀₁=7, E₀₂=8, E₀₃=9)}}
}
a::Float64
end
function (E::TEH_field3Im)(t)
@unpack E₀₃, ΔT₁, ΔT₂, ΔT₃, ϕ₃ = E.parameters
_tanhfield(t; E₀=E₀₃, t₁=(ΔT₁ + ΔT₂), t₂=(ΔT₁ + ΔT₂ + ΔT₃), a=E.a) * sin(ϕ₃)
end
_tanhfield(t; E₀, t₁, t₂, a) = (E₀ / 2) * (tanh(a * (t - t₁)) - tanh(a * (t - t₂)));
_ENANTIOMER_PARAMETERS = ComponentVector(
ΔT₁=0.3,
ΔT₂=0.4,
ΔT₃=0.3,
ϕ₁=0.0,
ϕ₂=0.0,
ϕ₃=0.0,
E₀₁=4.5,
E₀₂=4.0,
E₀₃=5.0
)
@testset "enantiomer problem - dependent parameters" begin
H₊ = total_enantiomer_ham(_ENANTIOMER_PARAMETERS; sign="+", a=100)
H₋ = total_enantiomer_ham(_ENANTIOMER_PARAMETERS; sign="-", a=100)
tlist = [0.0, 0.5, 1.0]
Ψ₀ = ComplexF64[1, 0, 0]
Ψ₊tgt = ComplexF64[1, 0, 0]
Ψ₋tgt = ComplexF64[0, 0, 1]
problem = ControlProblem(
[Trajectory(Ψ₀, H₊; target_state=Ψ₊tgt), Trajectory(Ψ₀, H₋; target_state=Ψ₋tgt)],
tlist;
)
p = get_parameters(problem)
@test p isa AbstractVector
@test eltype(p) == Float64
@test length(p) == 9
@test p === _ENANTIOMER_PARAMETERS
end
@testset "enantiomer problem - partially independent parameters" begin
H₊ = total_enantiomer_ham(copy(_ENANTIOMER_PARAMETERS); sign="+", a=100)
H₋ = total_enantiomer_ham(copy(_ENANTIOMER_PARAMETERS); sign="-", a=100)
tlist = [0.0, 0.5, 1.0]
Ψ₀ = ComplexF64[1, 0, 0]
Ψ₊tgt = ComplexF64[1, 0, 0]
Ψ₋tgt = ComplexF64[0, 0, 1]
problem = ControlProblem(
[Trajectory(Ψ₀, H₊; target_state=Ψ₊tgt), Trajectory(Ψ₀, H₋; target_state=Ψ₋tgt)],
tlist;
)
p = get_parameters(problem)
@test p isa AbstractVector
@test eltype(p) == Float64
@test length(p) == 18
@test p[2] == 0.4
@test length(p.x) == 2
@test length(p.x[1]) == 9
end
@testset "enantiomer problem - fully independent parameters" begin
H₊ = total_enantiomer_ham(
copy(_ENANTIOMER_PARAMETERS);
independent_parameters=true,
sign="+",
a=100
)
H₋ = total_enantiomer_ham(
copy(_ENANTIOMER_PARAMETERS);
independent_parameters=true,
sign="-",
a=100
)
tlist = [0.0, 0.5, 1.0]
Ψ₀ = ComplexF64[1, 0, 0]
Ψ₊tgt = ComplexF64[1, 0, 0]
Ψ₋tgt = ComplexF64[0, 0, 1]
problem = ControlProblem(
[Trajectory(Ψ₀, H₊; target_state=Ψ₊tgt), Trajectory(Ψ₀, H₋; target_state=Ψ₋tgt)],
tlist;
)
p = get_parameters(problem)
@test p isa AbstractVector
@test eltype(p) == Float64
@test length(p) == 108
@test p[2] == 0.4
@test length(p.x) == 2
@test length(p.x[1]) == 54
@test length(p.x[1].x) == 6
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 1285 | using Test
using QuantumPropagators: ExpProp
using QuantumPropagators.Shapes: flattop
using QuantumControl: Trajectory, propagate
using UnicodePlots
@testset "propagate TLS" begin
# from the first Krotov.jl example
SHOWPLOT = false
#! format: off
σ̂_z = ComplexF64[1 0; 0 -1];
σ̂_x = ComplexF64[0 1; 1 0];
#! format: on
ϵ(t) = 0.2 * flattop(t, T=5, t_rise=0.3, func=:blackman)
function hamiltonian(Ω=1.0, ϵ=ϵ)
Ĥ₀ = -0.5 * Ω * σ̂_z
Ĥ₁ = σ̂_x
return (Ĥ₀, (Ĥ₁, ϵ))
end
function ket(label)
#! format: off
result = Dict(
"0" => Vector{ComplexF64}([1, 0]),
"1" => Vector{ComplexF64}([0, 1]),
)
#! format: on
return result[string(label)]
end
H = hamiltonian()
traj = Trajectory(ket(0), H, target_state=ket(1))
tlist = collect(range(0, 5, length=500))
states =
propagate(traj.initial_state, traj.generator, tlist, storage=true, method=ExpProp)
pops = abs.(states) .^ 2
pop0 = pops[1, :]
SHOWPLOT && println(lineplot(tlist, pop0, ylim=[0, 1], title="0 population"))
@test length(pop0) == length(tlist)
@test pop0[1] ≈ 1.0
@test abs(pop0[end] - 0.95146) < 1e-4
@test minimum(pop0) < 0.9
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 6639 | using Test
using LinearAlgebra
using QuantumControl: QuantumControl, ControlProblem, hamiltonian, optimize, Trajectory
using QuantumControlTestUtils.RandomObjects: random_matrix
using QuantumControl.Controls: substitute
using QuantumControl.Shapes: flattop
using QuantumPropagators: ExpProp
using QuantumControl.PulseParameterizations:
ParameterizedAmplitude,
SquareParameterization,
TanhParameterization,
TanhSqParameterization,
LogisticParameterization,
LogisticSqParameterization
using QuantumControl.Controls: get_controls, evaluate, discretize
using Krotov
using IOCapture
@testset "Instantiate ParameterizedAmplitude" begin
# See https://github.com/orgs/JuliaQuantumControl/discussions/42
# https://github.com/JuliaQuantumControl/QuantumControl.jl/issues/43
N = 10
H0 = random_matrix(N; hermitian=true)
H1 = random_matrix(N; hermitian=true)
H2 = random_matrix(N; hermitian=true)
ϵ(t) = 0.5
a = ParameterizedAmplitude(ϵ; parameterization=SquareParameterization())
@test get_controls(a) == (ϵ,)
H = hamiltonian(H0, (H1, ϵ), (H2, a); check=false)
@test get_controls(H) == (ϵ,)
@test norm(Array(evaluate(H, 0.0)) - (H0 + 0.5 * H1 + 0.5^2 * H2)) < 1e-12
end
@testset "Positive parameterizations" begin
# See figure at
# https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/stable/tutorials/krotov_pulse_parameterization/#Positive-(Bounded)-Controls
u_vals = collect(range(-3, 3, length=101))
ϵ_vals = collect(range(0, 1, length=101))
ϵ_max = 1.0
ϵ_tanhsq = TanhSqParameterization(ϵ_max).a_of_epsilon.(u_vals)
@test minimum(ϵ_tanhsq) ≈ 0.0
@test 0.95 < maximum(ϵ_tanhsq) <= 1.0
ϵ_logsq1 = LogisticSqParameterization(ϵ_max).a_of_epsilon.(u_vals)
@test minimum(ϵ_logsq1) ≈ 0.0
@test 0.81 < maximum(ϵ_logsq1) <= 0.83
ϵ_logsq4 = LogisticSqParameterization(ϵ_max, k=4.0).a_of_epsilon.(u_vals)
@test minimum(ϵ_logsq4) ≈ 0.0
@test 0.95 < maximum(ϵ_logsq4) <= 1.0
ϵ_sq = SquareParameterization().a_of_epsilon.(u_vals)
@test minimum(ϵ_sq) ≈ 0.0
@test maximum(ϵ_sq) ≈ 9.0
u_tanhsq = TanhSqParameterization(ϵ_max).epsilon_of_a.(ϵ_vals)
@test u_tanhsq[begin] ≈ 0.0
@test maximum(u_tanhsq) ≈ u_tanhsq[end]
@test 18.0 < maximum(u_tanhsq) <= 19.0
u_logsq1 = LogisticSqParameterization(ϵ_max).epsilon_of_a.(ϵ_vals)
@test u_logsq1[begin] ≈ 0.0
@test maximum(u_logsq1) ≈ u_logsq1[end]
@test 740.0 < maximum(u_logsq1) <= 750.0
u_logsq4 = LogisticSqParameterization(ϵ_max, k=4.0).epsilon_of_a.(ϵ_vals)
@test u_logsq4[begin] ≈ 0.0
@test maximum(u_logsq4) ≈ u_logsq4[end]
@test 180.0 < maximum(u_logsq4) <= 190.0
u_sq = SquareParameterization().epsilon_of_a.(ϵ_vals)
@test u_sq[begin] ≈ 0.0
@test maximum(u_sq) ≈ u_sq[end]
@test maximum(u_sq) ≈ 1.0
d_tanhsq = TanhSqParameterization(ϵ_max).da_deps_derivative.(u_vals)
@test maximum(d_tanhsq) ≈ -minimum(d_tanhsq)
@test 0.7 < maximum(d_tanhsq) < 0.8
d_logsq1 = LogisticSqParameterization(ϵ_max).da_deps_derivative.(u_vals)
@test maximum(d_logsq1) ≈ -minimum(d_logsq1)
@test 0.35 < maximum(d_logsq1) < 0.40
d_logsq4 = LogisticSqParameterization(ϵ_max, k=4.0).da_deps_derivative.(u_vals)
@test maximum(d_logsq4) ≈ -minimum(d_logsq4)
@test 1.5 < maximum(d_logsq4) < 1.6
end
@testset "Symmetric parameterizations" begin
# See figure at
# https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/stable/tutorials/krotov_pulse_parameterization/#Symmetric-Bounded-Controls
u_vals = collect(range(-3, 3, length=101))
ϵ_vals = collect(range(-1, 1, length=101))
ϵ_min = -1.0
ϵ_max = 1.0
ϵ_tanh = TanhParameterization(ϵ_min, ϵ_max).a_of_epsilon.(u_vals)
@test minimum(ϵ_tanh) ≈ -maximum(ϵ_tanh)
@test 0.99 <= maximum(ϵ_tanh) <= 1.0
ϵ_log1 = LogisticParameterization(ϵ_min, ϵ_max).a_of_epsilon.(u_vals)
@test minimum(ϵ_log1) ≈ -maximum(ϵ_log1)
@test 0.90 <= maximum(ϵ_log1) <= 0.91
ϵ_log4 = LogisticParameterization(ϵ_min, ϵ_max, k=4.0).a_of_epsilon.(u_vals)
@test minimum(ϵ_log4) ≈ -maximum(ϵ_log4)
@test 0.999 <= maximum(ϵ_log4) <= 1.0
u_tanh = TanhParameterization(ϵ_min, ϵ_max).epsilon_of_a.(ϵ_vals)
@test minimum(u_tanh) ≈ -maximum(u_tanh)
@test 18.0 <= maximum(u_tanh) <= 19.0
# These diverge to Inf for the maximum:
u_log1 = LogisticParameterization(ϵ_min, ϵ_max).epsilon_of_a.(ϵ_vals)
u_log4 = LogisticParameterization(ϵ_min, ϵ_max, k=4.0).epsilon_of_a.(ϵ_vals)
d_tanh = TanhParameterization(ϵ_min, ϵ_max).da_deps_derivative.(u_vals)
@test 0.009 < minimum(d_tanh) < 0.010
@test maximum(d_tanh) ≈ 1.0
d_log1 = LogisticParameterization(ϵ_min, ϵ_max).da_deps_derivative.(u_vals)
@test 0.08 < minimum(d_log1) < 0.10
@test maximum(d_log1) ≈ 0.5
d_log4 = LogisticParameterization(ϵ_min, ϵ_max, k=4.0).da_deps_derivative.(u_vals)
@test 4e-5 < minimum(d_log4) < 6e-5
@test maximum(d_log4) ≈ 2.0
end
@testset "Parameterized optimization" begin
ϵ(t) = 0.2 * flattop(t, T=5, t_rise=0.3, func=:blackman)
function tls_hamiltonian(; Ω=1.0, ampl=ϵ)
σ̂_z = ComplexF64[
1 0
0 -1
]
σ̂_x = ComplexF64[
0 1
1 0
]
Ĥ₀ = -0.5 * Ω * σ̂_z
Ĥ₁ = σ̂_x
return hamiltonian(Ĥ₀, (Ĥ₁, ampl))
end
function ket(label)
result = Dict("0" => Vector{ComplexF64}([1, 0]), "1" => Vector{ComplexF64}([0, 1]),)
return result[string(label)]
end
H = tls_hamiltonian()
tlist = collect(range(0, 5, length=500))
trajectories = [Trajectory(ket(0), H; target_state=ket(1))]
a = ParameterizedAmplitude(
ϵ,
tlist;
parameterization=TanhParameterization(-0.5, 0.5),
parameterize=true
)
problem_tanh = ControlProblem(
trajectories=substitute(trajectories, IdDict(ϵ => a)),
prop_method=ExpProp,
lambda_a=1,
update_shape=(t -> flattop(t, T=5, t_rise=0.3, func=:blackman)),
tlist=tlist,
iter_stop=30,
J_T=QuantumControl.Functionals.J_T_ss,
)
captured = IOCapture.capture(passthrough=false) do
optimize(problem_tanh; method=Krotov, rethrow_exceptions=true)
end
opt_result_tanh = captured.value
@test opt_result_tanh.iter == 30
@test 0.15 < opt_result_tanh.J_T < 0.16
opt_ampl =
Array(substitute(a, IdDict(a.control => opt_result_tanh.optimized_controls[1])))
@test -0.5 < minimum(opt_ampl) < -0.4
@test 0.4 < maximum(opt_ampl) < 0.5
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 2445 | using Test
using IOCapture
using QuantumControl:
AbstractOptimizationResult, MissingResultDataException, IncompatibleResultsException
struct _TestOptimizationResult1 <: AbstractOptimizationResult
iter_start::Int64
iter_stop::Int64
end
struct _TestOptimizationResult2 <: AbstractOptimizationResult
iter_start::Int64
J_T::Float64
J_T_prev::Float64
end
struct _TestOptimizationResult3 <: AbstractOptimizationResult
iter_start::Int64
iter_stop::Int64
end
@testset "Dict conversion" begin
R = _TestOptimizationResult1(0, 100)
data = convert(Dict{Symbol,Any}, R)
@test data isa Dict{Symbol,Any}
@test Set(keys(data)) == Set((:iter_stop, :iter_start))
@test data[:iter_start] == 0
@test data[:iter_stop] == 100
@test _TestOptimizationResult1(0, 100) ≠ _TestOptimizationResult1(0, 50)
_R = convert(_TestOptimizationResult1, data)
@test _R == R
captured = IOCapture.capture(; passthrough=false, rethrow=Union{}) do
convert(_TestOptimizationResult2, data)
end
@test captured.value isa MissingResultDataException
msg = begin
io = IOBuffer()
showerror(io, captured.value)
String(take!(io))
end
@test startswith(msg, "Missing data for fields [:J_T, :J_T_prev]")
@test contains(msg, "_TestOptimizationResult2")
end
@testset "Result conversion" begin
R = _TestOptimizationResult1(0, 100)
_R = convert(_TestOptimizationResult1, R)
@test _R == R
_R = convert(_TestOptimizationResult3, R)
@test _R isa _TestOptimizationResult3
@test convert(Dict{Symbol,Any}, _R) == convert(Dict{Symbol,Any}, R)
captured = IOCapture.capture(; passthrough=false, rethrow=Union{}) do
convert(_TestOptimizationResult2, R)
end
@test captured.value isa IncompatibleResultsException
msg = begin
io = IOBuffer()
showerror(io, captured.value)
String(take!(io))
end
@test contains(msg, "does not provide required fields [:J_T, :J_T_prev]")
R2 = _TestOptimizationResult2(0, 0.1, 0.4)
captured = IOCapture.capture(; passthrough=false, rethrow=Union{}) do
convert(_TestOptimizationResult1, R2)
end
@test captured.value isa IncompatibleResultsException
msg = begin
io = IOBuffer()
showerror(io, captured.value)
String(take!(io))
end
@test contains(msg, "does not provide required fields [:iter_stop]")
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 1493 | using Test
using DataFrames
using CSV
using Logging
using IOCapture
using JLD2: load_object
using QuantumControlTestUtils: QuantumTestLogger
using QuantumControl: run_or_load
load_csv(f) = DataFrame(CSV.File(f))
@testset "run_or_load to csv" begin
mktempdir() do folder
file = joinpath(folder, "data", "out.csv")
run_or_load(file; load=load_csv, force=true, verbose=false) do
DataFrame(a=rand(100), b=rand(100))
end
df = load_csv(file)
@test names(df) == ["a", "b"]
end
end
@testset "run_or_load invalid" begin
mktempdir() do folder
file = joinpath(folder, "data", "out.csv")
captured = IOCapture.capture(passthrough=false, rethrow=Union{}) do
run_or_load(file; load=load_csv, force=true, verbose=false) do
# A tuple of vectors is not something that can be written
# to a csv file
return rand(100), rand(100)
end
end
@test captured.value isa ErrorException
if captured.value isa ErrorException
err = captured.value
@test occursin("Recover", err.msg)
rx = r"load_object\(\"(.*)\"\)"
m = match(rx, err.msg)
recovery_file = m.captures[1]
data = load_object(recovery_file)
rm(recovery_file)
@test length(data) == 2
end
@test occursin("Can't write this data to a CSV file", captured.output)
end
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | code | 4682 | using Test
using QuantumControl: Trajectory, propagate_trajectory
using QuantumPropagators: Cheby, ExpProp
using QuantumPropagators.Controls: substitute, get_controls
using QuantumControlTestUtils.RandomObjects: random_state_vector, random_dynamic_generator
using StableRNGs
using LinearAlgebra: norm
using IOCapture
using TestingUtilities: @Test # better for string comparison
@testset "Trajectory instantiation" begin
rng = StableRNG(3143161815)
N = 10
Ψ₀ = random_state_vector(N; rng)
Ψtgt = random_state_vector(N; rng)
tlist = [0.0, 1.0]
H = random_dynamic_generator(N, tlist)
traj = Trajectory(Ψ₀, H)
@test startswith(repr(traj), "Trajectory(ComplexF64[")
repl_repr = repr("text/plain", traj; context=(:limit => true))
@test contains(repl_repr, "initial_state: 10-element Vector{ComplexF64}")
@test contains(repl_repr, "generator: Generator with 2 ops and 1 amplitudes")
@test contains(repl_repr, "target_state: Nothing")
@test summary(traj) ==
"Trajectory with 10-element Vector{ComplexF64} initial state, Generator with 2 ops and 1 amplitudes, no target state"
# with target state
traj = Trajectory(Ψ₀, H; target_state=Ψtgt)
@test startswith(repr(traj), "Trajectory(ComplexF64[")
repl_repr = repr("text/plain", traj; context=(:limit => true))
@test contains(repl_repr, "target_state: 10-element Vector{ComplexF64}")
@test summary(traj) ==
"Trajectory with 10-element Vector{ComplexF64} initial state, Generator with 2 ops and 1 amplitudes, 10-element Vector{ComplexF64} target state"
# with weight
traj = Trajectory(Ψ₀, H; weight=0.3)
@test startswith(repr(traj), "Trajectory(ComplexF64[")
repl_repr = repr("text/plain", traj; context=(:limit => true))
@test contains(repl_repr, "weight: 0.3")
@test summary(traj) ==
"Trajectory with 10-element Vector{ComplexF64} initial state, Generator with 2 ops and 1 amplitudes, no target state, weight=0.3"
# with extra data
traj = Trajectory(
Ψ₀,
H;
weight=0.3,
note="Note",
prop_inplace=false,
prop_method=Cheby,
prop_specrange_method=:manual
)
@test startswith(repr(traj), "Trajectory(ComplexF64[")
repl_repr = repr("text/plain", traj; context=(:limit => true))
@test contains(repl_repr, r"prop_method: .*.Cheby")
@test contains(repl_repr, "note: \"Note\"")
@test contains(repl_repr, "prop_specrange_method: :manual")
@test contains(repl_repr, "prop_inplace: false")
@test summary(traj) ==
"Trajectory with 10-element Vector{ComplexF64} initial state, Generator with 2 ops and 1 amplitudes, no target state, weight=0.3 and 4 extra kwargs"
vec = [traj, traj]
repl_repr = repr("text/plain", vec; context=(:limit => true))
@test contains(repl_repr, "2-element Vector")
@test contains(repl_repr, "Trajectory with 10-element Vector{ComplexF64} initial state")
end
@testset "Trajectory substitution" begin
rng = StableRNG(3143161815)
N = 10
Ψ₀ = random_state_vector(N; rng)
Ψtgt = random_state_vector(N; rng)
tlist = [0.0, 1.0]
ϵ1(t) = 0.0
ϵ2(t) = 1.0
H = random_dynamic_generator(N, tlist; amplitudes=[ϵ1])
traj = Trajectory(Ψ₀, H)
@test get_controls([traj]) == (ϵ1,)
traj2 = substitute(traj, IdDict(ϵ1 => ϵ2))
@test get_controls([traj2]) == (ϵ2,)
trajs = [traj, traj2]
@test get_controls(trajs) == (ϵ1, ϵ2)
trajs2 = substitute(trajs, IdDict(ϵ1 => ϵ2))
@test get_controls(trajs2) == (ϵ2,)
end
@testset "Trajectory propagation" begin
rng = StableRNG(3143161815)
N = 10
Ψ₀ = random_state_vector(N; rng)
Ψtgt = random_state_vector(N; rng)
tlist = [0.0, 0.5, 1.0]
H = random_dynamic_generator(N, tlist)
traj = Trajectory(Ψ₀, H)
captured = IOCapture.capture(rethrow=Union{}) do
propagate_trajectory(traj, tlist)
end
@test captured.value isa UndefKeywordError
@test contains(captured.output, "Cannot initialize propagation for trajectory")
@test contains(captured.output, "keyword argument `method` not assigned")
Ψout = propagate_trajectory(traj, tlist, method=Cheby)
@test Ψout isa Vector{ComplexF64}
@test abs(1.0 - norm(Ψout)) < 1e-12
traj = Trajectory(Ψ₀, H; prop_method=Cheby)
captured = IOCapture.capture(rethrow=Union{}, passthrough=false) do
propagate_trajectory(traj, tlist; verbose=true)
end
Ψout2 = captured.value
@test norm(Ψout2 - Ψout) < 1e-12
@test contains(captured.output, "Info: Initializing propagator for trajectory")
@test contains(captured.output, r":method => .*.Cheby")
end
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | docs | 2383 | # QuantumControl.jl
[](https://juliahub.com/ui/Packages/General/QuantumControl)
[](https://juliaquantumcontrol.github.io/QuantumControl.jl/)
[](https://juliaquantumcontrol.github.io/QuantumControl.jl/dev)
[](https://github.com/JuliaQuantumControl/QuantumControl.jl/actions)
[](https://codecov.io/gh/JuliaQuantumControl/QuantumControl.jl)
A Julia Framework for Quantum Dynamics and Control.
The [`QuantumControl`][QuantumControl] package is a high-level interface for the [packages][] in the [JuliaQuantumControl][] organization and provides a coherent [API](https://juliaquantumcontrol.github.io/QuantumControl.jl/dev/api/quantum_control/#QuantumControlAPI) for solving quantum control problems. See the [organization README](https://github.com/JuliaQuantumControl#readme) for details.
## Documentation
The [full documentation](https://juliaquantumcontrol.github.io/QuantumControl.jl/) is available at <https://juliaquantumcontrol.github.io/QuantumControl.jl/>.
Support is also available in the `#quantumcontrol` channel in the [Julia Slack](https://julialang.org/slack/).
## Installation
The [`QuantumControl.jl`][QuantumControl] package can be installed via the [standard Pkg manager](https://docs.julialang.org/en/v1/stdlib/Pkg/):
~~~
pkg> add QuantumControl
~~~
You will also want to install the [`QuantumPropagators` package][QuantumPropagators]
~~~
pkg> add QuantumPropagator
~~~
to access a suitable dynamic solver for your problem (e.g. `using QuantumPropagators: Cheby`); as well as at least one package for a specific optimization method you are planning to use:
~~~
pkg> add Krotov
pkg> add GRAPE
~~~
See the [list of packages][packages] of the [JuliaQuantumControl][] organization.
[JuliaQuantumControl]: https://github.com/JuliaQuantumControl
[QuantumControl]: https://github.com/JuliaQuantumControl/QuantumControl.jl
[QuantumPropagators]: https://github.com/JuliaQuantumControl/QuantumPropagators.jl
[packages]: https://github.com/JuliaQuantumControl#packages
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | docs | 43 | ```@autodocs
Modules = [Krotov, GRAPE]
```
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | docs | 8485 | # Glossary
In the context of the JuliaQuantumControl ecosystem, we apply the following nomenclature.
----
##### Generator
Dynamical generator (Hamiltonian / Liouvillian) for the time evolution of a state, i.e., the right-hand-side of the equation of motion (up to a factor of ``i``) such that ``|Ψ(t+dt)⟩ = e^{-i Ĥ dt} |Ψ(t)⟩`` in the infinitesimal limit. We use the symbols ``G``, ``Ĥ``, or ``L``, depending on the context (general, Hamiltonian, Liouvillian).
Examples for supported forms a Hamiltonian are the following, from the most general case to simplest and most common case of linear controls,
```@raw html
<img src="../assets/controlhams.svg" width="80%"/>
```
In Eq. (G1), ``Ĥ_0`` is the [Drift Term](@ref) (which may be zero) and each term under the sum over ``l`` is a [Control Term](@ref). Each control term is a Hamiltonian that depends on a set of [control functions](#Control-Function) (or simply "controls"). The controls are the functions directly tunable via optimal control.
The control term may also contain an explicit time dependence outside of the controls. This most general form (G1) is supported only via custom user-implemented generator objects, see the documentation of the [QuantumPropagators package](https://juliaquantumcontrol.github.io/QuantumPropagators.jl/stable/).
More commonly, each control term is separable into the [Control Amplitude](@ref) ``a_l(t)`` and the [Control Operator](@ref) ``Ĥ_l``, as in Eq. (G2). This is the most general form supported by the built-in [`Generator`](@ref) object, which can be initialized via the [`hamiltonian`](@ref) or [`liouvillian`](@ref) functions. The control amplitude ``a_l(t)`` depends in turn on one ore more function ``\{ϵ_{l'}(t)\}``, where each ``ϵ_{l'}(t)`` is as [Control Function](@ref). It may also contain an explicit time dependence.
In the most common case, ``a_l ≡ ϵ_l``, as in Eq. (G3). The control may further depend on a set of [Control Parameters](@ref), ``ϵ_l(t) = ϵ_l({u_n})``.
In an open quantum system, the structure of Eqs. (G1–G3) is the same, but with Liouvillian (super-)operators acting on density matrices instead of Hamiltonians acting on state vectors. See [`liouvillian`](@ref) with `convention=:TDSE`.
----
##### Operator
A static, non-time-dependent object that can be multiplied to a state. An operator can be obtained from a time-dependent [Generator](@ref) by plugging in values for the controls and potentially any explicit time dependence. For example, an [`Operator`](@ref) is obtained from a [`Generator`](@ref) via [`QuantumControl.Controls.evaluate`](@ref).
----
##### Drift Term
A term in the dynamical generator that does not depend on any controls.
----
##### Control Term
A term in the dynamical generator that depends on one or more controls.
----
##### Control Function
(aka "**Control**") A function ``ϵ_l(t)`` in the [Generator](@ref) that is directly tuned by an optimal control method, either as [Pulse](@ref) values or via [Control Parameters](@ref).
----
##### Control Field
A function that corresponds directly to some kind of *physical* drive (laser amplitude, microwave pulse, etc.). The term can be ambiguous in that it usually corresponds to the [Control Amplitude](@ref) ``a(t)``, but depending on how the control problem is formulated, it can also correspond to the [Control Function](@ref) ``ϵ(t)``
----
##### Control Operator
(aka "control Hamiltonian/Liouvillian"). The operator ``Ĥ_l`` in Eqs. (G2, G3). This is a *static* operator which forms the [Control Term](@ref) together with a [Control Amplitude](@ref). The control generator is not a well-defined concept in the most general case of non-separable controls terms, Eq. (G1).
----
##### Control Amplitude
The time-dependent coefficient ``a_l(t)`` for the [Control Operator](@ref) in Eq. (G2). A control amplitude may depend on on or more control functions, as well as have an explicit time dependency. Some conceptual examples for control amplitudes and how they may depend on a [Control Function](@ref) are the following:
* Non-linear coupling of a control field to the operator, e.g., the quadratic coupling of the laser field to a Stark shift operator
* [Pulse Parameterization](@ref) as a way to enforce bounds on a [Control Field](@ref)
* Transfer functions, e.g., to model the response of an electronic device to the optimal control field ``ϵ(t)``.
* Noise in the amplitude of the control function
* Non-controllable aspects of the control amplitude, e.g. a "guided" control amplitude ``a_l(t) = R(t) + ϵ_l(t)`` or a non-controllable envelope ``S(t)`` in ``a_l(t) = S(t) ϵ(t)`` that ensures switch-on- and switch-off in a CRAB pulse `ϵ(t)`.
In [Qiskit Dynamics](https://qiskit.org/documentation/dynamics/index.html), the "control amplitude" is called ["Signal"](https://qiskit.org/documentation/dynamics/apidocs/signals.html), see [Connecting Qiskit Pulse with Qiskit Dynamics](https://qiskit.org/documentation/dynamics/tutorials/qiskit_pulse.html), where a Qiskit "pulse" corresponds roughly to our [Control Function](@ref).
----
##### Control Parameters
Non-time-dependent parameters that a [Control Function](@ref) depends on, ``ϵ(t) = ϵ(\{u_n\}, t)``. One common parameterization of a control field is as a [Pulse](@ref), where the control parameters are the amplitude of the field at discrete points of a time grid. Parameterization as a "pulse" is implicit in Krotov's method and standard GRAPE.
More generally, the control parameters could also be spectral coefficients (CRAB) or simple parameters for an analytic pulse shape (e.g., position, width, and amplitude of a Gaussian shape). All optimal control methods find optimized control fields by varying the control parameters.
----
##### Pulse
(aka "control pulse") A control field discretized to a time grid, usually on the midpoints of the time grid, in a piecewise-constant approximation. Stored as a vector of floating point values. The parameterization of a control field as a "pulse" is implicit for Krotov's method and standard GRAPE. One might think of these methods to optimize the control fields *directly*, but a conceptually cleaner understanding is to think of the discretized "pulse" as a vector of control parameters for the time-continuous control field.
----
##### Pulse Parameterization
A special case of a [Control Amplitude](@ref) where ``a(t) = a(ϵ(t))`` at every point in time. The purpose of this is to constrain the amplitude of the control amplitude ``a(t)``. See e.g. [`QuantumControl.PulseParameterizations.SquareParameterization`](@ref), where ``a(t) = ϵ^2(t)`` to ensure that ``a(t)`` is positive. Since Krotov's method inherently has no constraints on the optimized control fields, pulse parameterization is a method of imposing constraints on the amplitude in this context.
----
##### Control Derivative
The derivative of the dynamical [Generator](@ref) with respect to the control ``ϵ(t)``. In the case of linear controls terms in Eq. (G3), the control derivative is the [Control Operator](@ref) coupling to ``ϵ(t)``. In general, however, for non-linear control terms, the control derivatives still depends on the control fields and is thus time dependent. We commonly use the symbol ``μ`` for the control derivative (reminiscent of the dipole operator)
----
##### Parameter Derivative
The derivative of a control with respect to a single control parameter. The derivative of the dynamical [Generator](@ref) with respect to that control parameter is then the product of the [Control Derivative](@ref) and the parameter derivative.
----
##### Gradient
The derivative of the optimization functional with respect to *all* [Control Parameters](@ref), i.e. the vector of all parameter derivatives.
----
!!! note
The above nomenclature does not consistently extend throughout the quantum control literature: the terms "control"/"control term"/"control Hamiltonian", and "control"/"control field"/"control function"/"control pulse"/"pulse" are generally somewhat ambiguous. In particular, the distinction between "control field" and "pulse" (as a parameterization of the control field in terms of amplitudes on a time grid) here is somewhat artifcial and borrowed from the [Krotov Python package](https://qucontrol.github.io/krotov). However, the terminology defined in this glossary is consistently applied within the `JuliaQuantumControl` organization, both in the documentation and in the names of members and methods.
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | docs | 4251 | # QuantumControl.jl
```@eval
using Markdown
using Pkg
VERSION = Pkg.dependencies()[Base.UUID("8a270532-f23f-47a8-83a9-b33d10cad486")].version
github_badge = "[](https://github.com/JuliaQuantumControl/QuantumControl.jl)"
version_badge = ""
Markdown.parse("$github_badge $version_badge")
```
[QuantumControl.jl](https://github.com/JuliaQuantumControl/QuantumControl.jl) is a [Julia framework for quantum dynamics and control](https://github.com/JuliaQuantumControl).
Quantum optimal control [BrumerShapiro2003,BrifNJP2010,Shapiro2012,KochJPCM2016,SolaAAMOP2018,MorzhinRMS2019,Wilhelm2003.10132,KochEPJQT2022](@cite) attempts to steer a quantum system in some desired way by finding optimal control parameters or control fields inside the system Hamiltonian or Liouvillian. Typical control tasks are the preparation of a specific quantum state or the realization of a logical gate in a quantum computer (["pulse level control"](https://arxiv.org/abs/2004.06755)). Thus, quantum control theory is a critical part of realizing quantum technologies at the lowest level. Numerical methods of *open-loop* quantum control (methods that do not involve measurement feedback from a physical quantum device) such as [Krotov's method](https://github.com/JuliaQuantumControl/Krotov.jl) [Krotov1996,SomloiCP1993,BartanaJCP1997,PalaoPRA2003,ReichJCP2012,GoerzSPP2019](@cite) and [GRAPE](https://github.com/JuliaQuantumControl/GRAPE.jl) [KhanejaJMR2005,FouquieresJMR2011](@cite) address the control problem by [simulating the dynamics of the system](https://github.com/JuliaQuantumControl/QuantumPropagators.jl) and then iteratively improving the value of a functional that encodes the desired outcome.
##### Functional
Mathematically, the control problem is the minimization of a functional of the form
```math
J(\{ϵ_l(t)\})
= J_T(\{|Ψ_k(T)⟩\})
+ λ_a \, \underbrace{∑_l \int_{0}^{T} g_a(ϵ_l(t)) \, dt}_{=J_a(\{ϵ_l(t)\})}
+ λ_b \, \underbrace{∑_k \int_{0}^{T} g_b(|Ψ_k(t)⟩) \, dt}_{=J_b(\{|Ψ_k(t)⟩\})}\,,
```
where ``\{ϵ_l(t)\}`` is a set of [control functions](@ref "Control Function") defined between the initial time ``t=0`` and the final time ``t=T``, and ``\{|Ψ_k(t)⟩\}`` is a set of ["trajectories"](@ref QuantumControl.Trajectory) evolving from a set of initial states ``\{|\Psi_k(t=0)⟩\}`` under the controls ``\{ϵ_l(t)\}``. The full functional consists of the final-time functional ``J_T``, a control-dependent running cost ``J_a`` weighted by ``λ_a``, and sometimes a state-dependent running cost ``J_b`` weighted by ``λ_b``. The states can be Hilbert space vectors or density matrices, and the equation of motion is implicit, typically the Schrödinger or Liouville equation.
The `QuantumControl.jl` package provides a single coherent [API](@ref QuantumControlAPI) for solving the quantum control problem with the [packages](https://github.com/JuliaQuantumControl#packages) in the [JuliaQuantumControl](https://github.com/JuliaQuantumControl) organization. Different [optimization methods](@ref "Control Methods") target specific variants of the above functional.
## Getting Started
* See the [installation instructions](https://github.com/JuliaQuantumControl/QuantumControl.jl#installation) on Github.
* Look at a [simple example for a state-to-state transition with GRAPE](@extref Examples :doc:`examples/simple_state_to_state/index`) to get a feeling for how the `QuantumControl` package is intended to be used, or look at the larger list of [Examples](@extref Examples :doc:`index`).
* Read the [Glossary](@ref) and [Overview](@ref) to understand the philosophy of the framework.
## Contents
```@contents
Pages = [
"glossary.md",
"overview.md",
"methods.md",
"howto.md",
]
Depth = 2
```
### Examples
```@contents
Pages = [
"examples/index.md",
]
```
### API
```@contents
Pages = [
"api/quantum_control.md",
]
Depth = 1
```
#### Sub-Packages
```@contents
Pages = [
"api/quantum_propagators.md",
]
Depth = 1
```
### History
See the [Releases](https://github.com/JuliaQuantumControl/QuantumControl.jl/releases) on Github.
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | docs | 1176 | # Control Methods
All optimizations in the `QuantumControl` package are done by calling `QuantumControl.optimize`, or preferably the high-level wrapper [`@optimize_or_load`](@ref). The actual control methods are implemented in separate packages. The module implementing a particular method should be passed to `optimize` as the `method` keyword argument.
```@docs; canonical=false
optimize(::ControlProblem; method=:any)
```
The following methods of optimal control are implemented by packages in the [JuliaQuantumControl organization](https://github.com/JuliaQuantumControl):
```@contents
Pages = ["methods.md"]
Depth = 2:2
```
## Krotov's Method
See the [documentation](@extref Krotov :doc:`index`) of the [`Krotov` package](https://github.com/JuliaQuantumControl/Krotov.jl) for more details.
```@docs; canonical=false
optimize(::ControlProblem, ::Val{:Krotov})
```
## GRAPE
The Gradient Ascent Pulse Engineering (GRAPE) method is implemented in the [`GRAPE` package](https://github.com/JuliaQuantumControl/GRAPE.jl). See the [`GRAPE` documentation](@extref GRAPE :doc:`index`) for details.
```@docs; canonical=false
optimize(::ControlProblem, ::Val{:GRAPE})
```
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | docs | 7892 | # Overview
This page describes the API of the `QuantumControl` package by outlining the general procedure for defining and solving quantum control problems. See the [API](@ref) for a detailed reference.
## Setting up control problems
Quantum control problems are described by instantiating [`ControlProblem`](@ref). Remember that a quantum control problem aims to find control parameters in the dynamical generators ([Hamiltonians](@ref hamiltonian), [Liouvillians](@ref liouvillian)) of a quantum system to steer the dynamics of the system in some desired way. The dynamics of system are probed by one or more quantum states, each with its particular dynamical generator, which we encode as a [`Trajectory`](@ref) object.
To determine how well the system dynamics meet the desired behavior, a [`Trajectory`](@ref) can have additional properties that are taken into account in the [optimization functional](@ref "Functional"). Most commonly, this is represented by a `target_state` property of the [`Trajectory`](@ref). The objective is fulfilled when the control parameters are chosen such that the initial state of each [`Trajectory`](@ref) evolves into the target state, on the time grid given as `tlist` in the [`ControlProblem`](@ref).
A control problem with a single such trajectory already encodes the common state-to-state problem, e.g., to initialize a system into an entangled state, or to control a chemical reaction. However, there are many control problems that require *simultaneously* solving more than one trajectory. For example, finding the control parameters that implement a two-qubit quantum gate ``Ô`` on a quantum computer naturally translates to four simultaneous trajectories, one for each two-qubit basis state: ``|00⟩ → Ô |00⟩``, ``|01⟩ → Ô |01⟩``, ``|10⟩ → Ô |10⟩``, ``|00⟩ → Ô |11⟩``. By virtue of the linearity of Hilbert space, finding a simultaneous solution to these four trajectories means the *any* state ``|Ψ⟩`` will then evolve as ``|Ψ⟩ → Ô |Ψ⟩``.
Some optimal control frameworks treat the optimization of quantum gates by numerically evolving the gate itself, ``Û(t=0) = I → Ô(t=T)``. This is perfectly compatible with our framework: we can have a single trajectory for an initial "state" ``Û`` with a target "state" ``Ô``. However, this approach does not scale well numerically when the logical subspace of the two-qubit gate is embedded in a significantly larger physical Hilbert space: ``Û`` is quadratically larger than ``|Ψ⟩``. Moreover, the various methods implemented in the `QuantumControl` package are inherently *parallel* with respect to multiple trajectories. This is why we emphasize the formulation of the control problem in terms of multiple simultaneous trajectories.
Sometimes, some of the trajectories may be more important than others. In this case, the [`Trajectory`](@ref) can be instantiated with a `weight` attribute. There are also situations where the notion of a "target state" is not meaningful. Coming back to the example of two-qubit quantum gates, one may wish to maximize the entangling power of the quantum gate, without requiring a *specific* gate. We extract the information about the entangling power of the dynamical generator by tracking the time evolution of a set of states (the Bell basis, as it happens), but there is no meaningful notion of a "target state". In this example, an [`Trajectory`](@ref) may be instantiated without the `target_state` attribute, i.e., containing only the `initial_state` and the `generator`. These are the minimal required attributes for any optimization.
Mathematically, the control problem is solved by minimizing a functional that is calculated from the time-propagated trajectory states. By convention, this functional is passed as a keyword argument `J_T` when instantiating the [`ControlProblem`](@ref). Standard functionals are defined in [the `QuantumControl.Functionals` module](@ref QuantumControlFunctionalsAPI). Depending on the control method, there can be additional options. See the documentation of the various methods implementing [`optimize`](@ref) for the options required or supported by the different solvers. All of these options can be passed as keyword arguments when instantiating the [`ControlProblem`](@ref)[^1], or they can be passed later to [`optimize`](@ref)/[`@optimize_or_load`](@ref).
[^1]: The solvers that ship with `QuantumControl` ignore options they do not know about. So when setting up a [`ControlProblem`](@ref) it is safe to pass a superset of options for different optimization methods.
## Controls and control parameters
The controls that the `QuantumControl` package optimizes are implicit in the dynamical generator ([`hamiltonian`](@ref), [`liouvillian`](@ref)) of the [`Trajectories`](@ref Trajectory) in the [`ControlProblem`](@ref).
The [`QuantumControl.Controls.get_controls`](@ref) method extracts the controls from the trajectories. Each control is typically time-dependent, e.g., a function ``ϵ(t)`` or a vector of pulse values on a time grid. For each control, [`QuantumControl.Controls.discretize`](@ref) and [`QuantumControl.Controls.discretize_on_midpoints`](@ref) discretizes the control to an existing time grid. For controls that are implemented through some custom type, these methods must be defined to enable piecewise-constant time propagation or an optimization that assumes piecewise-constant control (most notably, Krotov's method). See [`QuantumControl.Interfaces.check_control`](@ref) for the full interface required of a control.
See also the [section on Dynamical Generators in the `QuantumPropagators` documentation](https://juliaquantumcontrol.github.io/QuantumPropagators.jl/stable/generators/) and [`QuantumControl.Interfaces.check_generator`](@ref) for details on how generators and controls relate.
## Time propagation
The `QuantumControl` package uses (and includes) [`QuantumPropagators.jl`](https://github.com/JuliaQuantumControl/QuantumPropagators.jl) as the numerical back-end for simulating the time evolution of all quantum states. The main high-level function provided from that package is [`propagate`](@ref), which simulates the dynamics of a quantum state over an entire time grid. In the context of a [`ControlProblem`](@ref) consisting of one or more [`Trajectory`](@ref), there is also a [`propagate_trajectory`](@ref) function that provides a more convenient interface, automatically using the initial state and the dynamical generator from the trajectory.
A very typical overall workflow is to set up the control problem, then propagate the trajectories with the guess control to see how the system behaves, run the optimization, and then propagate the trajectories again with the optimized controls, to verify the success of the optimization. For plugging in the optimized controls, [`QuantumControl.Controls.substitute`](@ref) can be used.
## Optimization
The most direct way to solve a [`ControlProblem`](@ref) is with the [`optimize`](@ref) routine. It has a mandatory `method` argument that then delegates the optimization to the appropriate sub-package implementing that method.
However, if the optimization takes more than a few minutes to complete, you should use [`@optimize_or_load`](@ref) instead of just [`optimize`](@ref). This routine runs the optimization and then writes the result to file. When called again, it will then simply load the result instead of rerunning the optimization. The [`@optimize_or_load`](@ref) also embeds some metadata in the output file, including (by default) the commit hash of the project repository containing the script that called [`@optimize_or_load`](@ref) and the filename of the script and line number where the call was made.
The output file written by [`@optimize_or_load`](@ref) can be read via the [`load_optimization`](@ref) function. This can recover both the optimization result and the metadata.
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | docs | 35 | # References
```@bibliography
```
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
|
[
"MIT"
] | 0.11.1 | bf2b978e6a3fcba1a01e741411e0d389c6617c64 | docs | 1257 | # [Examples](@id examples-list)
## Krotov-specific examples
* [Optimization of a State-to-State Transfer in a Two-Level-System](https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/stable/examples/simple_state_to_state/#Optimization-of-a-State-to-State-Transfer-in-a-Two-Level-System)
* [Optimization of a Dissipative Quantum Gate](https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/stable/examples/rho_3states/#Optimization-of-a-Dissipative-Quantum-Gate)
* [Pulse Parameterization](https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/stable/tutorials/krotov_pulse_parameterization/)
* [Optimization for a perfect entangler](https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/stable/examples/perfect_entanglers/#Optimizing-for-a-general-perfect-entangler)
## GRAPE-specific examples
* [Optimization of a State-to-State Transfer in a Two-Level-System](https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/stable/examples/simple_state_to_state/#Optimization-of-a-State-to-State-Transfer-in-a-Two-Level-System)
* [Optimization for a perfect entangler](https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/stable/examples/perfect_entanglers/#Optimizing-for-a-general-perfect-entangler)
| QuantumControl | https://github.com/JuliaQuantumControl/QuantumControl.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.