licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 1.1.0 | 258274c47afd63fe67dade9c3f12244b086288e8 | docs | 4752 | # Glossary
This is a summary of the type of objects you will be studying.
- **`Sublat`**: a sublattice, representing a number of identical sites within the unit cell of a bounded or unbounded lattice. Each site has a position in an `E`-dimensional space (`E` is called the embedding dimension). All sites in a given `Sublat` will be able to hold the same number of orbitals, and they can be thought of as identical atoms. Each `Sublat` in a `Lattice` can be given a unique name, by default `:A`, `:B`, etc.
- **`Lattice`**: a collection of `Sublat`s plus a collection of `L` Bravais vectors that define the periodicity of the lattice. A bounded lattice has `L=0`, and no Bravais vectors. A `Lattice` with `L > 0` can be understood as a periodic (unbounded) collection of unit cells, each containing a set of sites, each of which belongs to a different sublattice.
- **`SiteSelector`**: a rule that defines a subset of sites in a `Lattice` (not necessarily restricted to a single unit cell)
- `HopSelector`: a rule that defines a subset of site pairs in a `Lattice` (not necessarily restricted to the same unit cell)
- **`LatticeSlice`**: a *finite* subset of sites in a `Lattice`, defined by their cell index (an `L`-dimensional integer vector, usually denoted by `n` or `cell`) and their site index within the unit cell (an integer). A `LatticeSlice` an be constructed by combining a `Lattice` and a (bounded) `SiteSelector`.
- **`AbstractModel`**: either a `TightBindingModel` or a `ParametricModel`
- **`TightBindingModel`**: a set of `HoppingTerm`s and `OnsiteTerm`s
- **`OnsiteTerm`**: a rule that, applied to a single site, produces a scalar or a (square) matrix that represents the intra-site Hamiltonian elements (single or multi-orbital)
- **`HoppingTerm`**: a rule that, applied to a pair of sites, produces a scalar or a matrix that represents the inter-site Hamiltonian elements (single or multi-orbital)
- **`ParametricModel`**: a set of `ParametricOnsiteTerm`s and `ParametricHoppingTerm`s
- **`ParametricOnsiteTerm`**: an `OnsiteTerm` that depends on a set of free parameters that can be adjusted, and that may or may not have a default value
- **`ParametricHoppingTerm`**: a `HoppingTerm` that depends on parameters, like `ParametricOnsiteTerm` above
- **`AbstractHamiltonian`**: either a `Hamiltonian` or a `ParametricHamiltonian`
- **`Hamiltonian`**: a `Lattice` combined with a `TightBindingModel`.
It also includes a specification of the number of orbitals in each `Sublat` in the `Lattice`. A `Hamiltonian` represents a tight-binding Hamiltonian sharing the same periodicity as the `Lattice` (it is translationally invariant under Bravais vector shifts).
- `ParametricHamiltonian`: like the above, but using a `ParametricModel`, which makes it dependent on a set of free parameters that can be efficiently adjusted.
An `h::AbstractHamiltonian` can be used to produce a Bloch matrix `h(ϕ; params...)` of the same size as the number of orbitals per unit cell, where `ϕ = [ϕᵢ...]` are Bloch phases and `params` are values for the free parameters, if any.
- **`Spectrum`**: the set of eigenpairs (eigenvalues and corresponding eigenvectors) of a Bloch matrix. It can be computed with a number of `EigenSolvers`.
- **`Bandstructure`**: a collection of spectra, evaluated over a discrete mesh (typically a discretization of the Brillouin zone), that is connected to its mesh neighbors into a linearly-interpolated approximation of the `AbstractHamiltonian`'s bandstructure.
- **`SelfEnergy`**: an operator `Σ(ω)` defined to act on a `LatticeSlice` of an `AbstractHamiltonian` that depends on energy `ω`.
- **`OpenHamiltonian`**: an `AbstractHamiltonian` combined with a set of `SelfEnergies`
- **`GreenFunction`**: an `OpenHamiltonian` combined with an `AbstractGreenSolver`, which is an algorithm that can in general compute the retarded or advanced Green function at any energy between any subset of sites of the underlying lattice.
- **`GreenSlice`**: a `GreenFunction` evaluated on a specific set of sites, but at an unspecified energy
- **`GreenSolution`**: a `GreenFunction` evaluated at a specific energy, but on an unspecified set of sites
- **`OrbitalSliceArray`**: an `AbstractArray` that can be indexed with a `SiteSelector`, in addition to the usual scalar indexing. Particular cases are `OrbitalSliceMatrix` and `OrbitalSliceVector`. This is the most common type obtained from `GreenFunction`s and observables obtained from them.
- **Observables**: Supported observables, obtained from Green functions using various algorithms, include **local density of states**, **density matrices**, **current densities**, **transmission probabilities**, **conductance** and **Josephson currents**
| Quantica | https://github.com/pablosanjose/Quantica.jl.git |
|
[
"MIT"
] | 1.1.0 | 258274c47afd63fe67dade9c3f12244b086288e8 | docs | 18495 | # GreenFunctions
Up to now we have seen how to define Lattices, Models, Hamiltonians and Bandstructures. Most problems require the computation of different physical observables for these objects, e.g. the local density of states or various transport coefficients. We reduce this general problem to the computation of the retarded Green function
``G^r_{ij}(\omega) = \langle i|(\omega-H-\Sigma(\omega))^{-1}|j\rangle``
where `i, j` are orbitals, `H` is the (possibly infinite) Hamiltonian matrix, and `Σ(ω)` is the self-energy coming from any coupling to other systems (typically described by their own `AbstractHamiltonian`).
We split the problem of computing `Gʳᵢⱼ(ω)` of a given `h::AbstractHamiltonian` into four steps:
1. Attach self-energies to `h` using the command `oh = attach(h, args...)`. This produces a new object `oh::OpenHamiltonian` with a number of `Contacts`, numbered `1` to `N`
2. Use `g = greenfunction(oh, solver)` to build a `g::GreenFunction` representing `Gʳ` (at arbitrary `ω` and `i,j`), where `oh::OpenHamiltonian` and `solver::AbstractGreenSolver` (see `GreenSolvers` below for available solvers)
3. Evaluate `gω = g(ω; params...)` at fixed energy `ω` and model parameters, which produces a `gω::GreenSolution`
4. Slice `gω[sᵢ, sⱼ]` or `gω[sᵢ] == gω[sᵢ, sᵢ]` to obtain `Gʳᵢⱼ(ω)` as a flat matrix, where `sᵢ, sⱼ` are either site selectors over sites spanning orbitals `i,j`, integers denoting contacts, `1` to `N`, or `:` denoting all contacts merged together.
!!! tip "GreenSlice vs. GreenSolution"
The two last steps can be interchanged, by first obtaining a `gs::GreenSlice` with `gs = g[sᵢ, sⱼ]` and then obtaining the `Gʳᵢⱼ(ω)` matrix with `gs(ω; params...)`.
## A simple example
Here is a simple example of the Green function of a 1D lead with two sites per unit cell, a boundary at `cell = 0`, and with no attached self-energies for simplicity
```
julia> hlead = LP.square() |> supercell((1,0), region = r -> 0 <= r[2] < 2) |> hopping(1);
julia> glead = greenfunction(hlead, GreenSolvers.Schur(boundary = 0))
GreenFunction{Float64,2,1}: Green function of a Hamiltonian{Float64,2,1}
Solver : AppliedSchurGreenSolver
Contacts : 0
Contact solvers : ()
Contact sizes : ()
Hamiltonian{Float64,2,1}: Hamiltonian on a 1D Lattice in 2D space
Bloch harmonics : 3
Harmonic size : 2 × 2
Orbitals : [1]
Element type : scalar (ComplexF64)
Onsites : 0
Hoppings : 6
Coordination : 3.0
julia> gω = glead(0.2) # we first fix energy to ω = 0.2
GreenSolution{Float64,2,1}: Green function at arbitrary positions, but at a fixed energy
julia> gω[cells = 1:2] # we now ask for the Green function between orbitals in the first two unit cells to the righht of the boundary
4×4 Matrix{ComplexF64}:
0.1-0.858258im -0.5-0.0582576im -0.48-0.113394im -0.2+0.846606im
-0.5-0.0582576im 0.1-0.858258im -0.2+0.846606im -0.48-0.113394im
-0.48-0.113394im -0.2+0.846606im 0.104-0.869285im 0.44+0.282715im
-0.2+0.846606im -0.48-0.113394im 0.44+0.282715im 0.104-0.869285im
```
Note that the result is a 4 x 4 matrix, because there are 2 orbitals (one per site) in each of the two unit cells. Note also that the `GreenSolvers.Schur` used here allows us to compute the Green function between distant cells with little overhead
```julia
julia> @time gω[cells = 1:2];
0.000067 seconds (70 allocations: 6.844 KiB)
julia> @time gω[cells = (SA[10], SA[100000])];
0.000098 seconds (229 allocations: 26.891 KiB)
```
## GreenSolvers
The currently implemented `GreenSolvers` (abbreviated as `GS`) are the following
- `GS.SparseLU()`
For bounded (`L=0`) AbstractHamiltonians. Default for `L=0`.
Uses a sparse `LU` factorization to compute the inverse of `⟨i|ω - H - Σ(ω)|j⟩`, where `Σ(ω)` is the self-energy from the contacts.
- `GS.Spectrum(; spectrum_kw...)`
For bounded (`L=0`) Hamiltonians. This solver does not accept ParametricHamiltonians. Convert to Hamiltonian with `h(; params...)` first.
Uses a diagonalization of `H`, obtained with `spectrum(H; spectrum_kw...)`, to compute the `G⁰ᵢⱼ` using the Lehmann representation `∑ₖ⟨i|ϕₖ⟩⟨ϕₖ|j⟩/(ω - ϵₖ)`. Any eigensolver supported by `spectrum` can be used here. If there are contacts, it dresses `G⁰` using a T-matrix approach, `G = G⁰ + G⁰TG⁰`.
- `GS.KPM(order = 100, bandrange = missing, kernel = I)`
For bounded (`L=0`) Hamiltonians, and restricted to sites belonging to contacts (see the section on Contacts).
It precomputes the Chebyshev momenta, and incorporates the contact self energy with a T-matrix approach.
- `GS.Schur(boundary = Inf)`
For 1D (`L=1`) AbstractHamiltonians with only nearest-cell coupling. Default for `L=1`.
Uses a deflating Generalized Schur (QZ) factorization of the generalized eigenvalue problem to compute the unit-cell self energies.
The Dyson equation then yields the Green function between arbitrary unit cells, which is further dressed using a T-matrix approach if the lead has any attached self-energy.
- `GS.Bands(bandsargs...; boundary = missing, bandskw...)`
For unbounded (`L>0`) Hamiltonians.
It precomputes a bandstructure `b = bands(h, bandsargs...; kw..., split = false)` and then uses analytic expressions for the contribution of each subband simplex to the `GreenSolution`. If `boundary = dir => cell_pos`, it takes into account the reflections on an infinite boundary perpendicular to Bravais vector number `dir`, so that all sites with cell index `c[dir] <= cell_pos` are removed. Contacts are incorporated using a T-matrix approach.
To retrieve the bands from a `g::GreenFunction` that used the `GS.Bands` solver, we may use `bands(g)`.
## Attaching Contacts
A self energy `Σ(ω)` acting of a finite set of sites of `h` (i.e. on a `LatticeSlice` of `lat = lattice(h)`) can be incorporated using the `attach` command. This defines a new Contact in `h`. The general syntax is `oh = attach(h, args...; sites...)`, where the `sites` directives define the Contact `LatticeSlice` (`lat[siteselector(; sites...)]`), and `args` can take a number of forms.
The supported `attach` forms are the following
- **Generic self-energy**
`attach(h, gs::GreenSlice, coupling::AbstractModel; sites...)`
This is the generic form of `attach`, which couples some sites `i` of a `g::Greenfunction` (defined by the slice `gs = g[i]`), to `sites` of `h` using a `coupling` model. This results in a self-energy `Σ(ω) = V´⋅gs(ω)⋅V` on `h` `sites`, where `V` and `V´` are couplings matrices given by `coupling`.
- **Dummy self-energy**
`attach(h, nothing; sites...)`
This form merely defines a new contact on the specified `sites`, but adds no actual self-energy to it. It is meant as a way to refer to some sites of interest using the `g[i::Integer]` slicing syntax for `GreenFunction`s, where `i` is the contact index.
- **Model self-energy**
`attach(h, model::AbstractModel; sites...)`
This form defines a self-energy `Σᵢⱼ(ω)` in terms of `model`, which must be composed purely of parametric terms (`@onsite` and `@hopping`) that have `ω` as first argument, as in e.g. `@onsite((ω, r) -> Σᵢᵢ(ω, r))` or `@hopping((ω, r, dr) -> Σᵢⱼ(ω, r, dr))`. This is a modellistic approach, wherein the self-energy is not computed from the properties of another `AbstractHamiltonian`, but rather has an arbitrary form defined by the user.
- **Matched lead self-energy**
`attach(h, glead::GreenFunction; reverse = false, transform = identity, sites...)`
Here `glead` is a GreenFunction of a 1D lead, possibly with a boundary.
With this syntax `sites` must select a number of sites in `h` whose position match (after applying `transform` to them and modulo an arbitrary displacement) the sites in the unit cell of `glead`. Then, the coupling between these and the first unit cell of `glead` on the positive side of the boundary will be the same as between `glead` unitcells, i.e. `V = hlead[(1,)]`, where `hlead = hamiltonian(glead)`.
If `reverse == true`, the lead is reversed before being attached, so that h is coupled through `V = hlead[(-1,)]` to the first unitcell on the negative side of the boundary. If there is no boundary, the `cell = 0` unitcell of the `glead` is used.
- **Generic lead self-energy**
`attach(h, glead::GreenFunction, model::AbstractModel; reverse = false, transform = identity, sites...)`
The same as above, but without any restriction on `sites`. The coupling between these and the first unit cell of `glead` (transformed by `transform`) is constructed using `model::TightbindingModel`. The "first unit cell" is defined as above.
## A more advanced example
Let us define the classical example of a multiterminal mesoscopic junction. We choose a square lattice, and a circular central region of radius `10`, with four leads of width `5` coupled to it at right angles.
We first define a single lead `Greenfunction` and the central Hamiltonian
```julia
julia> glead = LP.square() |> onsite(4) - hopping(1) |> supercell((1, 0), region = r -> abs(r[2]) <= 5/2) |> greenfunction(GS.Schur(boundary = 0));
julia> hcentral = LP.square() |> onsite(4) - hopping(1) |> supercell(region = RP.circle(10) | RP.rectangle((22, 5)) | RP.rectangle((5, 22)));
```
The two rectangles overlayed on the circle above create the stubs where the leads will be attached:
```@raw html
<img src="../../assets/central.png" alt="Central region with stubs" width="250" class="center"/>
```
We now attach `glead` four times using the `Matched lead` syntax
```julia
julia> Rot = r -> SA[0 -1; 1 0] * r; # 90º rotation function
julia> g = hcentral |>
attach(glead, region = r -> r[1] == 11) |>
attach(glead, region = r -> r[1] == -11, reverse = true) |>
attach(glead, region = r -> r[2] == 11, transform = Rot) |>
attach(glead, region = r -> r[2] == -11, reverse = true, transform = Rot) |>
greenfunction
GreenFunction{Float64,2,0}: Green function of a Hamiltonian{Float64,2,0}
Solver : AppliedSparseLUGreenSolver
Contacts : 4
Contact solvers : (SelfEnergySchurSolver, SelfEnergySchurSolver, SelfEnergySchurSolver, SelfEnergySchurSolver)
Contact sizes : (5, 5, 5, 5)
Hamiltonian{Float64,2,0}: Hamiltonian on a 0D Lattice in 2D space
Bloch harmonics : 1
Harmonic size : 353 × 353
Orbitals : [1]
Element type : scalar (ComplexF64)
Onsites : 0
Hoppings : 1320
Coordination : 3.73938
julia> qplot(g, children = (; selector = siteselector(; cells = 1:5), sitecolor = :blue))
```
```@raw html
<img src="../../assets/multiterminal.png" alt="Multiterminal system" width="300" class="center"/>
```
Note that since we did not specify the `solver` in `greenfunction`, the `L=0` default `GS.SparseLU()` was taken.
We can also visualize `glead`, which is defined on a 1D lattice with a boundary. Boundary cells are shown by default in red
!!! tip "The GreenFunction <-> AbstractHamiltonian relation"
Its important un appreciate that a `g::GreenFunction` represents the retarded Green function between sites in a given `AbstractHamiltonian`, but not on sites of the coupled `AbstractHamiltonians` of its attached self-energies. Therefore, `gcentral` above cannot yield observables in the leads (blue sites above), only on the red sites. To obtain observables in a given lead, its `GreenFunction` must be constructed, with an attached self-energy coming from the central region plus the other three leads.
## Slicing and evaluation
As explained above, a `g::GreenFunction` represents a Green function of an `OpenHamiltonian` (i.e. `AbstractHamiltonian` with zero or more self-energies), but it does so for any energy `ω` or lattice sites.
- To specify `ω` (plus any parameters `params` in the underlying `AbstractHamiltonian`) we use the syntax `g(ω; params...)`, which yields an `gω::GreenSolution`
- To specify source (`sⱼ`) and drain (`sᵢ`) sites we use the syntax `g[sᵢ, sⱼ]` or `g[sᵢ] == g[sᵢ,sᵢ]`, which yields a `gs::GreenSlice`. `sᵢ` and `sⱼ` can be `SiteSelectors(; sites...)`, or an integer denoting a specific contact (i.e. sites with an attached self-energy) or `:` denoting all contacts merged together.
- If we specify both of the above we get the Green function between the orbitals of the specified sites at the specified energy, in the form of an `OrbitalSliceMatrix`, which is a special `AbstractMatrix` that knows about the orbitals in the lattice over which its matrix elements are defined.
Let us see this in action using the example from the previous section
```julia
julia> g[1, 3]
GreenSlice{Float64,2,0}: Green function at arbitrary energy, but at a fixed lattice positions
julia> g(0.2)
GreenSolution{Float64,2,0}: Green function at arbitrary positions, but at a fixed energy
julia> g(0.2)[1, 3]
5×5 OrbitalSliceMatrix{Matrix{ComplexF64}}:
-2.56906+0.000123273im -4.28767+0.00020578im -4.88512+0.000234514im -4.28534+0.00020578im -2.5664+0.000123273im
-4.28767+0.00020578im -7.15613+0.00034351im -8.15346+0.000391475im -7.15257+0.00034351im -4.2836+0.000205781im
-4.88512+0.000234514im -8.15346+0.000391475im -9.29002+0.000446138im -8.14982+0.000391476im -4.88095+0.000234514im
-4.28534+0.00020578im -7.15257+0.00034351im -8.14982+0.000391476im -7.14974+0.000343511im -4.28211+0.000205781im
-2.5664+0.000123273im -4.2836+0.000205781im -4.88095+0.000234514im -4.28211+0.000205781im -2.56469+0.000123273im
julia> g(0.2)[siteselector(region = RP.circle(1, (0.5, 0))), 3]
2×5 OrbitalSliceMatrix{Matrix{ComplexF64}}:
0.0749214+3.15744e-8im 0.124325+5.27948e-8im 0.141366+6.01987e-8im 0.124325+5.27948e-8im 0.0749214+3.15744e-8im
-0.374862+2.15287e-5im -0.625946+3.5938e-5im -0.712983+4.09561e-5im -0.624747+3.59379e-5im -0.37348+2.15285e-5im
```
!!! tip "Fixing parameters"
In the same way we can fix all parameters of a `h::ParametricHamiltonian` with `h´=h(;params...)` (which produces a `h´::Hamiltonian` without any parametric dependencies), we can similarly fix all parameters in a `g::GreenFunction` (or `g::GreenSlice`) with `g(; params...)`, which produces a new `GreenFunction` (or `GreenSlice`). Note that, like in the case of `h`, this fixes *all* parameters. Any parameter that is not specify will be fixed to its default value.
### Diagonal slices
There is a special form of slicing that requests just the diagonal of a given `g[sᵢ] == g[sᵢ,sᵢ]`. It uses the syntax `g[diagonal(sᵢ)]`. Let us see it in action in a multiorbital example in 2D
```julia
julia> g = HP.graphene(a0 = 1, t0 = 1, orbitals = 2) |> greenfunction
GreenFunction{Float64,2,2}: Green function of a Hamiltonian{Float64,2,2}
Solver : AppliedBandsGreenSolver
Contacts : 0
Contact solvers : ()
Contact sizes : ()
Hamiltonian{Float64,2,2}: Hamiltonian on a 2D Lattice in 2D space
Bloch harmonics : 5
Harmonic size : 2 × 2
Orbitals : [2, 2]
Element type : 2 × 2 blocks (ComplexF64)
Onsites : 0
Hoppings : 6
Coordination : 3.0
julia> g(0.5)[diagonal(cells = (0, 0))]
4-element OrbitalSliceVector{Vector{ComplexF64}}:
-0.3497363468480622 - 0.3118358260294266im
-0.3497363468271048 - 0.31183582602942655im
-0.3497363468402952 - 0.31183582602942667im
-0.34973634686125243 - 0.3118358260294267im
```
Note that we get an `OrbitalSliceVector`, which is equal to the diagonal `diag(g(0.5)[cells = (0, 0)])`. Like the `g` `OrbitalSliceMatrix`, this vector is resolved in orbitals, of which there are two per site and four per unit cell in this case. Using `diagonal(sᵢ; kernel = K)` we can collect all the orbitals of different sites, and compute `tr(g[site, site] * K)` for a given matrix `K`. This is useful to obtain spectral densities. In the above example, and interpreting the two orbitals per site as the electron spin, we could obtain the spin density along the `x` axis, say, using `σx = SA[0 1; 1 0]` as `kernel`,
```julia
julia> g(0.5)[diagonal(cells = (0, 0), kernel = SA[0 1; 1 0])]
2-element OrbitalSliceVector{Vector{ComplexF64}}:
4.26186044627701e-12 - 2.2846013280115095e-17im
-4.261861877528737e-12 + 1.9177925470610777e-17im
```
which is zero in this spin-degenerate case
!!! tip "Slicing `OrbitalSliceArray`s"
An `v::OrbitalSliceVector` and `m::OrbitalSliceMatrix` are both `a::OrbitalSliceArray`, and wrap conventional arrays, with e.g. conventional `axes`. They also provide, however, `orbaxes(a)`, which are a tuple of `OrbitalSliceGrouped`. These are `LatticeSlice`s that represent orbitals grouped by sites. They allow an interesting additional functionality. You can index `v[sitelector(...)]` or `m[rowsiteselector, colsiteselector]` to obtain a new `OrbitalSliceArray` of the selected rows and cols. The full machinery of `siteselector` applies. One can also use a lower-level `v[sites(cell_index, site_indices)]` to obtain an unwrapped `AbstractArray`, without building new `orbaxes`. See `OrbitalSliceArray` for further details.
## Visualizing a Green function
We can use `qplot` to visualize a `GreenSolution` in space. Here we define a bounded square lattice with an interesting shape, and attach a model self-energy to the right. Then we compute the Green function from each orbital in the contact to any other site in the lattice, and compute the norm over contact sites. The resulting vector is used as a shader for the color and radius of sites when plotting the system
```julia
julia> h = LP.square() |> onsite(4) - hopping(1) |> supercell(region = r -> norm(r) < 40*(1+0.2*cos(5*atan(r[2],r[1]))));
julia> g = h |> attach(@onsite(ω -> -im), region = r -> r[1] ≈ 47) |> greenfunction;
julia> gx1 = sum(abs2, g(0.1)[siteselector(), 1], dims = 2);
julia> qplot(h, hide = :hops, sitecolor = (i, r) -> gx1[i], siteradius = (i, r) -> gx1[i], minmaxsiteradius = (0, 2), sitecolormap = :balance)
```
```@raw html
<img src="../../assets/star_shape.png" alt="Green function from a contact on the right" width="400" class="center"/>
```
!!! warning "Caveat for multiorbital systems"
Since, currently, `g(ω)[sᵢ, sⱼ]` yields a `Matrix` over orbitals (instead of over sites), the above example requires single-orbital sites to work. In the future we will probably introduce a way to slice a `GreenSolution` over sites, similar to the way `diagonal` works. For the moment, one can use observables like `ldos` for visualization (see next section), which are all site-based by default.
| Quantica | https://github.com/pablosanjose/Quantica.jl.git |
|
[
"MIT"
] | 1.1.0 | 258274c47afd63fe67dade9c3f12244b086288e8 | docs | 14602 | # Hamiltonians
We build a Hamiltonian by combining a `Lattice` and a `TightbindingModel`, optionally specifying also the number of orbitals on each sublattice if there is more than one. A spinful graphene model (two orbitals per site in both sublattices) with nearest neighbor hopping `t0 = 2.7` would be written as
```julia
julia> lat = LP.honeycomb(); model = hopping(2.7*I);
julia> h = hamiltonian(lat, model; orbitals = 2)
Hamiltonian{Float64,2,2}: Hamiltonian on a 2D Lattice in 2D space
Bloch harmonics : 5
Harmonic size : 2 × 2
Orbitals : [2, 2]
Element type : 2 × 2 blocks (ComplexF64)
Onsites : 0
Hoppings : 6
Coordination : 3.0
```
A crucial thing to remember when defining multi-orbital Hamiltonians as the above is that `onsite` and `hopping` amplitudes need to be matrices of the correct size. The symbol `I` in Julia represents the identity matrix of any size, which is convenient to define a spin-preserving hopping in the case above. An alternative would be to use `model = hopping(2.7*SA[1 0; 0 1])`.
!!! tip "Models with different number of orbitals per sublattice"
Non-homogeneous multiorbital models are more advanced but are fully supported in Quantica.jl. Just use `orbitals = (n₁, n₂,...)` to have `nᵢ` orbitals in sublattice `i`, and make sure your model is consistent with that. As in the case of the `dim` keyword in `lattice`, you can also use `Val(nᵢ)` for marginally faster construction.
Similarly to `LatticePreset`s, we also have `HamiltonianPresets`, also aliased as `HP`. Currently, we have only `HP.graphene(...)` and `HP.twisted_bilayer_graphene(...)`, but we expect to extend this library in the future (see the docstring of `HP`).
## A more elaborate example: the Kane-Mele model
The Kane-Mele model for graphene describes intrinsic spin-orbit coupling (SOC), in the form of an imaginary second-nearest-neighbor hopping between same-sublattice sites, with a sign that alternates depending on hop direction `dr`. A possible implementation in Quantica.jl would be
```julia
SOC(dr) = 0.05 * ifelse(iseven(round(Int, atan(dr[2], dr[1])/(pi/3))), im, -im)
model =
hopping(1, range = neighbors(1)) +
hopping((r, dr) -> SOC(dr); sublats = :A => :A, range = neighbors(2)) +
hopping((r, dr) -> -SOC(dr); sublats = :B => :B, range = neighbors(2))
h = LatticePresets.honeycomb() |> model
qplot(h)
```
```@raw html
<img src="../../assets/latticeKM.png" alt="Kane-Mele lattice" width="350" class="center"/>
```
Interactive tooltips in the visualization of `h` are enabled by default (use keyword `inspector = false` to disable them). They allows to navigate each `onsite` and `hopping` amplitude graphically. Note that sites connected to the unit cell of `h` by some hopping are included, but are rendered with partial transparency by default.
## ParametricHamiltonians
If we use a `ParametricModel` instead of a simple `TightBindingModel` we will obtain a `ParametricHamiltonian` instead of a simple `Hamiltonian`, both of which are subtypes of the `AbstractHamiltonian` type
```julia
julia> model_param = @hopping((; t = 2.7) -> t*I);
julia> h_param = hamiltonian(lat, model_param; orbitals = 2)
ParametricHamiltonian{Float64,2,2}: Parametric Hamiltonian on a 2D Lattice in 2D space
Bloch harmonics : 5
Harmonic size : 2 × 2
Orbitals : [2, 2]
Element type : 2 × 2 blocks (ComplexF64)
Onsites : 0
Hoppings : 6
Coordination : 3.0
Parameters : [:t]
```
We can also apply `Modifier`s by passing them as extra arguments to `hamiltonian`, which results again in a `ParametricHamiltonian` with the parametric modifiers applied
```julia
julia> peierls! = @hopping!((t, r, dr; Bz = 0) -> t * cis(-Bz/2 * SA[-r[2], r[1]]' * dr));
julia> h_param_mod = hamiltonian(lat, model_param, peierls!; orbitals = 2)
ParametricHamiltonian{Float64,2,2}: Parametric Hamiltonian on a 2D Lattice in 2D space
Bloch harmonics : 5
Harmonic size : 2 × 2
Orbitals : [2, 2]
Element type : 2 × 2 blocks (ComplexF64)
Onsites : 0
Hoppings : 6
Coordination : 3.0
Parameters : [:Bz, :t]
```
Note that `SA[-r[2], r[1]]` above is a 2D `SVector`, because since the embedding dimension is `E = 2`, both `r` and `dr` are also 2D `SVector`s.
We can also apply modifiers to an already constructed `AbstractHamiltonian`. The following is equivalent to the above
```julia
julia> h_param_mod = hamiltonian(h_param, peierls!);
```
!!! warning "Modifiers do not commute"
We can add as many modifiers as we need by passing them as extra arguments to `hamiltonian`, and they will be applied sequentially, one by one. Beware, however, that modifiers do not necessarily commute, in the sense that the result will in general depend on their order.
We can obtain a plain `Hamiltonian` from a `ParametricHamiltonian` by applying specific values to its parameters. To do so, simply use the call syntax with parameters as keyword arguments
```julia
julia> h_param_mod(Bz = 0.1, t = 1)
Hamiltonian{Float64,2,2}: Hamiltonian on a 2D Lattice in 2D space
Bloch harmonics : 5
Harmonic size : 2 × 2
Orbitals : [2, 2]
Element type : 2 × 2 blocks (ComplexF64)
Onsites : 0
Hoppings : 6
Coordination : 3.0
```
!!! tip "Syntax `lat |> model` and `h |> modifier"
The common cases `lat |> hamiltonian(model)` (or `hamiltonian(lat, model)`) and `h |> hamiltonian(modifier)` (or `hamiltonian(h, modifier)`) can be also written as `lat |> model` and `h |> modifier`, respectively. Hence `hamiltonian(lat, model, modifier)` may be written as `lat |> model |> modifier`. This form however does not allow to specify the number of orbitals per sublattice (it will be one, the default).
## Obtaining actual matrices
For an L-dimensional `h::AbstractHamiltonian` (i.e. defined on a Lattice with `L` Bravais vectors), the Hamiltonian matrix between any unit cell with cell index `n` and another unit cell at `n+dn` (here known as a Hamiltonian "harmonic") is given by `h[dn]`
```julia
julia> h[(1,0)]
4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 4 stored entries:
⋅ ⋅ 2.7+0.0im 0.0+0.0im
⋅ ⋅ 0.0+0.0im 2.7+0.0im
⋅ ⋅ ⋅ ⋅
⋅ ⋅ ⋅ ⋅
julia> h[(0,0)]
4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 8 stored entries:
⋅ ⋅ 2.7+0.0im 0.0+0.0im
⋅ ⋅ 0.0+0.0im 2.7+0.0im
2.7+0.0im 0.0+0.0im ⋅ ⋅
0.0+0.0im 2.7+0.0im ⋅ ⋅
```
!!! tip "Cell distance indices"
We can use `Tuple`s or `SVector`s for cell distance indices `dn`. An empty `Tuple` `dn = ()` will always return the main intra-unitcell harmonic: `h[()] = h[(0,0...)] = h[SA[0,0...]]`.
!!! note "Bounded Hamiltonians"
If the Hamiltonian has a bounded lattice (i.e. it has `L=0` Bravais vectors), we will simply use an empty tuple to obtain its matrix `h[()]`. This is not in conflict with the above syntax.
Note that if `h` is a `ParametricHamiltonian`, such as `h_param` above, we will get zeros in place of the unspecified parametric terms, unless we actually first specify the values of the parameters
```julia
julia> h_param[(0,0)] # Parameter t is not specified -> it is not applied
4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 8 stored entries:
⋅ ⋅ 0.0+0.0im 0.0+0.0im
⋅ ⋅ 0.0+0.0im 0.0+0.0im
0.0+0.0im 0.0+0.0im ⋅ ⋅
0.0+0.0im 0.0+0.0im ⋅ ⋅
julia> h_param(t=2)[(0,0)]
4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 8 stored entries:
⋅ ⋅ 2.0+0.0im 0.0+0.0im
⋅ ⋅ 0.0+0.0im 2.0+0.0im
2.0+0.0im 0.0+0.0im ⋅ ⋅
0.0+0.0im 2.0+0.0im ⋅ ⋅
```
!!! note "ParametricHamiltonian harmonics"
The above behavior for unspecified parameters is not set in stone and may change in future versions. Another option would be to apply their default values (which may, however, not exist).
We are usually not interested in the harmonics `h[dn]` themselves, but rather in the Bloch matrix of a Hamiltonian
``H(\phi) = \sum_{dn} H_{dn} \exp(-i \phi * dn)``
where ``H_{dn}`` are the Hamiltonian harmonics, ``\phi = (\phi_1, \phi_2...) = (k\cdot A_1, k\cdot A_2...)`` are the Bloch phases, ``k`` is the Bloch wavevector and ``A_i`` are the Bravais vectors.
We obtain the Bloch matrix using the syntax `h(ϕ; params...)`
```julia
julia> h((0,0))
4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 8 stored entries:
⋅ ⋅ 8.1+0.0im 0.0+0.0im
⋅ ⋅ 0.0+0.0im 8.1+0.0im
8.1+0.0im 0.0+0.0im ⋅ ⋅
0.0+0.0im 8.1+0.0im ⋅ ⋅
julia> h_param_mod((0.2, 0.3); B = 0.1)
4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 8 stored entries:
⋅ ⋅ 7.92559-1.33431im 0.0+0.0im
⋅ ⋅ 0.0+0.0im 7.92559-1.33431im
7.92559+1.33431im 0.0+0.0im ⋅ ⋅
0.0+0.0im 7.92559+1.33431im ⋅ ⋅
```
Note that unspecified parameters take their default values when using the call syntax (as per the standard Julia convention). Any unspecified parameter that does not have a default value will produce an `UndefKeywordError` error.
## Transforming Hamiltonians
Like with lattices, we can transform an `h::AbstractHamiltonians` using `supercell`, `reverse`, `transform` and `translate`. All these except `supercell` operate only on the underlying `lattice(h)` of `h`, leaving the hoppings and onsite elements unchanged. Meanwhile, `supercell` acts on `lattice(h)` but also copies the hoppings and onsites of `h` onto the new sites, preserving the periodicity of the original `h`.
Additionally, we can also use `torus`, which makes the `h` lattice periodic along some (or all) of its Bravais vectors, while leaving the rest unbounded.
```julia
julia> torus(HP.graphene(), (0, :))
Hamiltonian{Float64,2,1}: Hamiltonian on a 1D Lattice in 2D space
Bloch harmonics : 3
Harmonic size : 2 × 2
Orbitals : [1, 1]
Element type : scalar (ComplexF64)
Onsites : 0
Hoppings : 4
Coordination : 2.0
```
The `phases` argument of `torus(h, phases)` is a `Tuple` of real numbers and/or colons (`:`), of length equal to the lattice dimension of `h`. Each real number `ϕᵢ` corresponds to a Bravais vector along which the transformed lattice will become periodic, picking up a phase `exp(iϕᵢ)` in the new hoppings, while each colon leaves the lattice unbounded along the corresponding Bravais vector. In a way `torus` is dual to `supercell`, in that it applies a different boundary condition to the lattice along the eliminated Bravais vectors, periodic instead of open, as in the case of `supercell`. The phases `ϕᵢ` are also connected to Bloch phases, in the sense that e.g. `torus(h, (ϕ₁, :))(ϕ₂) == h(ϕ₁, ϕ₂)`
!!! warning "Caveat of the Bloch-torus duality"
The relation `torus(h, phases)(()) = h(phases)` is quite general. However, in some cases with position-dependent models, this may not hold. This may happen when some of the new hoppings added by `torus` are already present in `h`, as in cases with hoppings at ranges equal or larger than half the size of the unit cell.
It's important to understand that, when transforming an `h::AbstractHamiltonian`, the model used to build `h` is not re-evaluated. Hoppings and onsite energies are merely copied so as to preserve the periodicity of the original `h`. As a consequence, these two constructions give different Hamiltonians
```julia
julia> h1 = LP.linear() |> supercell(4) |> hamiltonian(onsite(r -> r[1]));
julia> h2 = LP.linear() |> hamiltonian(onsite(r -> r[1])) |> supercell(4);
```
In the case of `h1` the `onsite` model is applied to the 4-site unitcell. Since each site has a different position, each gets a different onsite energy.
```julia
julia> h1[()]
4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 4 stored entries:
0.0+0.0im ⋅ ⋅ ⋅
⋅ 1.0+0.0im ⋅ ⋅
⋅ ⋅ 2.0+0.0im ⋅
⋅ ⋅ ⋅ 3.0+0.0im
```
In contrast `h2` first gets the `onsite` model applied with a 1-site unitcell at position `r = SA[0]`, so all sites in the lattice get onsite energy zero. Only then it is expanded with `supercell`, which generates a 4-site unitcell with zero onsite energy on all its sites
```julia
julia> h2[()]
4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 4 stored entries:
0.0+0.0im ⋅ ⋅ ⋅
⋅ 0.0+0.0im ⋅ ⋅
⋅ ⋅ 0.0+0.0im ⋅
⋅ ⋅ ⋅ 0.0+0.0im
```
As a consequence, `h` and `supercell(h)` represent exactly the same system, with the same observables, but with a different choice of unitcell.
These two different behaviors make sense in different situations, so it is important to be aware of the order dependence of transformations. Similar considerations apply to `transform`, `translate` and `torus` when models are position dependent.
## Combining Hamiltonians
Multiple `h::AbstractHamiltonian`s (or multiple `l::Lattice`s) can be combined into one with `combine`.
```julia
julia> h1 = LP.linear(dim = 2) |> hopping(1); h2 = LP.linear(dim = 2, names = :B) |> hopping(1) |> translate(SA[0,1]) |> @onsite!((o; p=1) -> o+p);
julia> combine(h1, h2; coupling = hopping(2))
ParametricHamiltonian{Float64,2,1}: Parametric Hamiltonian on a 1D Lattice in 2D space
Bloch harmonics : 3
Harmonic size : 2 × 2
Orbitals : [1, 1]
Element type : scalar (ComplexF64)
Onsites : 0
Hoppings : 6
Coordination : 3.0
Parameters : [:p]
```
The `coupling` keyword, available when combining `h::AbstractHamiltonian`s, is a hopping model that is applied between each `h`. It can be constrained as usual with `hopselector`s and also be parametric. If either `coupling` or any of the combined `h` is parametric, the result of `combine` will be a `ParametricHamiltonian`, or a `Hamiltonian` otherwise.
The combined objects must satisfy some conditions:
- They must have the same Bravais vectors (modulo reorderings), which will be the inherited by the combined result.
- They must have the same position type (the `T` in `AbstractHamiltonian{T}` and `Lattice{T}`)
- They must have no repeated sublattice names among them (unless the combined object is non-parametric)
| Quantica | https://github.com/pablosanjose/Quantica.jl.git |
|
[
"MIT"
] | 1.1.0 | 258274c47afd63fe67dade9c3f12244b086288e8 | docs | 15447 | # Lattices
## Constructing a Lattice from scratch
Consider a lattice like graphene's. It has two sublattices, A and B, forming a 2D honeycomb pattern in space. The position of site A and B inside the unitcell are `[0, -a0/(2√3)]` and `[0, a0/(2√3)]`, respectively. The Bravais vectors are `A₁, A₂ = a0 * [± cos(π/3), sin(π/3)]`. If we set the lattice constant to `a0 = √3` (so the carbon-carbon distance is 1), one way to build this lattice in Quantica.jl would be
```julia
julia> A₁, A₂ = √3 .* (cos(π/3), sin(π/3)),
√3 .* (-cos(π/3), sin(π/3));
julia> sA, sB = sublat((0, -1/2), name = :A),
sublat((0, 1/2), name = :B);
julia> lattice(sA, sB, bravais = (A₁, A₂))
Lattice{Float64,2,2} : 2D lattice in 2D space
Bravais vectors : [[0.866025, 1.5], [-0.866025, 1.5]]
Sublattices : 2
Names : (:A, :B)
Sites : (1, 1) --> 2 total per unit cell
```
!!! tip "Tuple, SVector and SMatrix"
Note that we have used `Tuple`s, such as `(0, 1/2)` instead of `Vector`s, like `[0, 1/2]`. In Julia small-length `Tuple`s are much more efficient as containers than `Vector`s, since their length is known and fixed at compile time. Static vectors (`SVector`) and matrices (`SMatrix`) are also available to Quantica, which are just as efficient as `Tuple`s, and they also implement linear algebra operations. They may be entered as e.g. `SA[0, 1/2]` and `SA[1 0; 0 1]`, respectively. For efficiency, always use `Tuple`, `SVector` and `SMatrix` in Quantica.jl where possible.
If we don't plan to address the two sublattices individually, we could also fuse them into one, like
```julia
julia> lat = lattice(sublat((0, 1/2), (0, -1/2)), bravais = (A₁, A₂))
Lattice{Float64,2,2} : 2D lattice in 2D space
Bravais vectors : [[0.866025, 1.5], [-0.866025, 1.5]]
Sublattices : 1
Names : (:A,)
Sites : (2,) --> 2 total per unit cell
```
This lattice has type `Lattice{T,E,L}`, with `T = Float64` the numeric type of position coordinates, `E = 2` the dimension of embedding space, and `L = 2` the number of Bravais vectors (i.e. the lattice dimension). Both `T` and `E`, and even the `Sublat` names can be overridden when creating a lattice. One can also provide the Bravais vectors as a matrix, with each `Aᵢ` as a column.
```julia
julia> Amat = √3 * SA[-cos(π/3) cos(π/3); sin(π/3) sin(π/3)];
julia> lat´ = lattice(sA, sB, bravais = Amat, type = Float32, dim = 3, names = (:C, :D))
Lattice{Float32,3,2} : 2D lattice in 3D space
Bravais vectors : Vector{Float32}[[-0.866025, 1.5, 0.0], [0.866025, 1.5, 0.0]]
Sublattices : 2
Names : (:C, :D)
Sites : (1, 1) --> 2 total per unit cell
```
!!! tip "Advanced: `dim = Val(E)` vs. `dim = E`"
For the `dim` keyword above we can alternatively use `dim = Val(3)`, which is slightly more efficient, because the value is encoded as a type. This is a "Julia thing" (related to the concept of type stability), and can be ignored upon a first contact with Quantica.jl.
One can also *convert* an existing lattice like the above to have a different type, embedding dimension, Bravais vectors and `Sublat` names with `lattice(lat; kw...)`. For example
```julia
julia> lat´´ = lattice(lat´, type = Float16, dim = 2, names = (:Boron, :Nitrogen))
Lattice{Float16,2,2} : 2D lattice in 2D space
Bravais vectors : Vector{Float16}[[-0.866, 1.5], [0.866, 1.5]]
Sublattices : 2
Names : (:Boron, :Nitrogen)
Sites : (1, 1) --> 2 total per unit cell
```
A list of site positions in a lattice `lat` can be obtained with `sites(lat)`, or `sites(lat, sublat)` to restrict to a specific sublattice
```julia
julia> sites(lat´´)
2-element Vector{SVector{2, Float16}}:
[0.0, -0.5]
[0.0, 0.5]
julia> sites(lat´´, :Nitrogen)
1-element view(::Vector{SVector{2, Float16}}, 2:2) with eltype SVector{2, Float16}:
[0.0, 0.5]
```
Similarly, the Bravais matrix of a `lat` can be obtained with `bravais_matrix(lat)`.
## Lattice presets
Quantica.jl provides a range of presets. A preset is a pre-built object of some type. In particular we have Lattice presets, defined in the submodule `LatticePresets` (also called `LP` for convenience), that include a number of classical lattices in different dimensions:
- `LP.linear`: linear 1D lattice
- `LP.square`: square 2D lattice
- `LP.honeycomb`: honeycomb 2D lattice
- `LP.cubic`: cubic 3D lattice
- `LP.bcc`: body-centered cubic 3D lattice
- `LP.fcc`: face-centered cubic 3D lattice
To obtain a lattice from a preset one simply calls it, e.g. `LP.honecyomb(; kw...)`. One can modify any of these `LatticePresets` by passing a `bravais`, `type`, `dim` or `names` keyword. One can also use a new keyword `a0` for the lattice constant (`a0 = 1` by default). The lattice `lat´´` above can thus be also obtained with
```julia
julia> lat´´ = LP.honeycomb(a0 = √3, type = Float16, names = (:Boron, :Nitrogen))
Lattice{Float16,2,2} : 2D lattice in 2D space
Bravais vectors : Vector{Float16}[[0.866, 1.5], [-0.866, 1.5]]
Sublattices : 2
Names : (:Boron, :Nitrogen)
Sites : (1, 1) --> 2 total per unit cell
```
!!! tip "Quantica's Presets library"
Quantica comes with four submodules that provide different kinds of presets: `LatticePresets` (`LP`), `HamiltonianPresets` (`HP`), `RegionPresets` (`RP`) and `ExternalPresets` (`EP`). `LP` provides a collection of standard lattices, `HP` some premade model Hamiltonians such as `HP.graphene` or `HP.twisted_bilayer_graphene`, `RP` some geometric regions such as `RP.circle` or `RP.cuboid`, and `EP` some importers of externally produced objects such as `EP.wannier90` to import Wannier90 files (see `Advanced` for details on the latter). This library of presets is expected to grow with time. The docstring for the submodule or the preset function can be queried for a description of the available options.
## Visualization
To produce an interactive visualization of `Lattice`s or other Quantica.jl object you need to load GLMakie.jl, CairoMakie.jl or some other plotting backend from the Makie repository (i.e. do `using GLMakie`, see also Installation). Then, a number of new plotting functions will become available. The main one is `qplot`. A `Lattice` is represented, by default, as the sites in a unitcell plus the Bravais vectors.
```julia
julia> using GLMakie
julia> lat = LP.honeycomb()
julia> qplot(lat, hide = nothing)
```
```@raw html
<img src="../../assets/honeycomb_lat.png" alt="Honeycomb lattice" width="250" class="center"/>
```
`qplot` accepts a large number of keywords to customize your plot. In the case of lattice, most of these are passed over to the function `plotlattice`, specific to `Lattices` and `Hamiltonians`. In the case above, `hide = nothing` means "don't hide any element of the plot". See the `qplot` and `plotlattice` docstrings for details.
!!! tip "GLMakie.jl vs CairoMakie.jl"
GLMakie.jl is optimized for interactive GPU-accelerated, rasterized plots. If you need to export to PDF for publications or display plots inside a Jupyter notebook, use CairoMakie.jl instead, which in general renders non-interactive, but vector-based plots.
!!! tip "User-defined defaults for `qplot`"
The command `qplotdefaults(; axis, figure)` can be used to define the default value of `figure` and `axis` keyword arguments of `qplot`. Example: to fix the size of all subsequent plots, do `qplotdefaults(; figure = (size = (1000, 1000),))`.
## [SiteSelectors](@id siteselectors)
A central concept in Quantica.jl is that of a "selector". There are two types of selectors, `SiteSelector`s and `HopSelectors`. `SiteSelector`s are a set of directives or rules that define a subset of its sites. `SiteSelector` rules are defined through three keywords:
- `region`: a boolean function of allowed site positions `r`.
- `sublats`: allowed sublattices of selected sites
- `cells`: allowed cell indices of selected sites
Similarly, `HopSelector`s can be used to select a number of site pairs, and will be used later to define hoppings in tight-binding models (see further below).
As an example, let us define a `SiteSelector` that picks all sites belonging to the `:B` sublattice of a given lattice within a circle of radius `10`
```julia
julia> s = siteselector(region = r -> norm(r) <= 10, sublats = :B)
SiteSelector: a rule that defines a finite collection of sites in a lattice
Region : Function
Sublattices : B
Cells : any
```
Note that this selector is defined independently of the lattice. To apply it to a lattice `lat` we do `lat[s]`, which results in a `LatticeSlice` (i.e. a finite portion, or slice, of `lat`)
```julia
julia> lat = LP.honeycomb(); lat[s]
LatticeSlice{Float64,2,2} : collection of subcells for a 2D lattice in 2D space
Cells : 363
Cell range : ([-11, -11], [11, 11])
Total sites : 363
```
The `Cell range` above are the corners of a bounding box *in cell-index space* that contains all unit cell indices with at least one selected site.
Let's plot it
```julia
julia> qplot(lat[s], hide = ())
```
```@raw html
<img src="../../assets/latslice.png" alt="A LatticeSlice" width="400" class="center"/>
```
!!! tip "qplot selector"
The above `qplot(lat[s])` can also be written as `qplot(lat, selector = s)`, which will be useful when plotting `AbstractHamiltonians`.
!!! tip "Sites of a LatticeSlice"
Collect the site positions of a `LatticeSlice` into a vector with `collect(sites(ls))`. If you do `sites(ls)` instead, you will get a lazy generator that can be used to iterate efficiently among site positions without allocating them in memory.
Apart from `region` and `sublats` we can also restrict the unitcells by their cell index. For example, to select all sites in unit cells within the above bounding box we can do
```julia
julia> s´ = siteselector(cells = CartesianIndices((-11:11, -11:11)))
SiteSelector: a rule that defines a finite collection of sites in a lattice
Region : any
Sublattices : any
Cells : CartesianIndices((-11:11, -11:11))
julia> lat[s´]
LatticeSlice{Float64,2,2} : collection of subcells for a 2D lattice in 2D space
Cells : 529
Cell range : ([-11, -11], [11, 11])
Total sites : 1058
```
We can often omit constructing the `SiteSelector` altogether by using the keywords directly
```julia
julia> ls = lat[cells = n -> 0 <= n[1] <= 2 && abs(n[2]) < 3, sublats = :A]
LatticeSlice{Float64,2,2} : collection of subcells for a 2D lattice in 2D space
Cells : 15
Cell range : ([0, -2], [2, 2])
Total sites : 15
```
Selectors are very expressive and powerful. Do check `siteselector` and `hopselector` docstrings for more details.
## Transforming lattices
We can transform lattices using `supercell`, `reverse`, `transform`, `translate`.
As a periodic structure, the choice of the unitcell in an unbounded lattice is, to an extent, arbitrary. Given a lattice `lat` we can obtain another with a unit cell 3 times larger with `supercell(lat, 3)`
```julia
julia> lat = supercell(LP.honeycomb(), 3)
Lattice{Float64,2,2} : 2D lattice in 2D space
Bravais vectors : [[1.5, 2.598076], [-1.5, 2.598076]]
Sublattices : 2
Names : (:A, :B)
Sites : (9, 9) --> 18 total per unit cell
```
More generally, given a lattice `lat` with Bravais matrix `Amat = bravais_matrix(lat)`, we can obtain a larger one with Bravais matrix `Amat´ = Amat * S`, where `S` is a square matrix of integers. In the example above, `S = SA[3 0; 0 3]`. The columns of `S` represent the coordinates of the new Bravais vectors in the basis of the old Bravais vectors. A more general example with e.g. `S = SA[3 1; -1 2]` can be written either in terms of `S` or of its columns
```julia
julia> supercell(lat, SA[3 1; -1 2]) == supercell(lat, (3, -1), (1, 2))
true
```
We can also use `supercell` to reduce the number of Bravais vectors, and hence the lattice dimensionality. To construct a new lattice with a single Bravais vector `A₁´ = 3A₁ - A₂`, just omit the second one
```julia
julia> supercell(lat, (3, -1))
Lattice{Float64,2,1} : 1D lattice in 2D space
Bravais vectors : [[6.0, 5.196152]]
Sublattices : 2
Names : (:A, :B)
Sites : (27, 27) --> 54 total per unit cell
```
Its important to note that the lattice will be bounded along directions different from the specified Bravais vectors. With the syntax above, the new unitcell will be minimal. We may however define how many sites to include in the new unitcell by adding a `SiteSelector` directive to be applied in the non-periodic directions. For example, to create a 10 * a0 wide, honeycomb nanoribbon we can do
```julia
julia> lat = supercell(LP.honeycomb(), (1,-1), region = r -> -5 <= r[2] <= 5)
Lattice{Float64,2,1} : 1D lattice in 2D space
Bravais vectors : [[1.0, 0.0]]
Sublattices : 2
Names : (:A, :B)
Sites : (12, 12) --> 24 total per unit cell
julia> qplot(lat[cells = -7:7])
```
```@raw html
<img src="../../assets/nanoribbon_lat.png" alt="Honeycomb nanoribbon" width="350" class="center"/>
```
!!! tip "No need to build selectors explicitly"
Note that we we didn't build a `siteselector(region = ...)` object to pass it to `supercell`. Instead, as shown above, we passed the corresponding keywords directly to `supercell`, which then takes care to build the selector internally.
To simply reverse the direction of the Bravais vectors of a lattice, while leaving the site positions unchanged, use `reverse` (or `reverse!` to do it in-place)
```julia
julia> reverse(LP.square())
Lattice{Float64,2,2} : 2D lattice in 2D space
Bravais vectors : [[-1.0, -0.0], [-0.0, -1.0]]
Sublattices : 1
Names : (:A,)
Sites : (1,) --> 1 total per unit cell
```
To transform a lattice, so that site positions `r` become `f(r)` use `transform`
```julia
julia> f(r) = SA[0 1; 1 0] * r
f (generic function with 1 method)
julia> rotated_honeycomb = transform(LP.honeycomb(a0 = √3), f)
Lattice{Float64,2,2} : 2D lattice in 2D space
Bravais vectors : [[1.5, 0.866025], [1.5, -0.866025]]
Sublattices : 2
Names : (:A, :B)
Sites : (1, 1) --> 2 total per unit cell
julia> sites(rotated_honeycomb)
2-element Vector{SVector{2, Float64}}:
[-0.5, 0.0]
[0.5, 0.0]
```
To translate a lattice by a displacement vector `δr` use `translate`
```julia
julia> δr = SA[0, 1];
julia> sites(translate(rotated_honeycomb, δr))
2-element Vector{SVector{2, Float64}}:
[-0.5, 1.0]
[0.5, 1.0]
```
## Currying: chaining transformations with the `|>` operator
Many functions in Quantica.jl have a "curried" version that allows them to be chained together using the pipe operator `|>`.
!!! note "Definition of currying"
The curried version of a function `f(x1, x2...)` is `f´ = x1 -> f(x2...)`, so that the curried form of `f(x1, x2...)` is `x2 |> f´(x2...)`, or `f´(x2...)(x1)`. This gives the first argument `x1` a privileged role. Users of object-oriented languages such as Python may find this use of the `|>` operator somewhat similar to the way the dot operator works there (i.e. `x1.f(x2...)`).
The last example above can then be written as
```julia
julia> LP.honeycomb(a0 = √3) |> transform(f) |> translate(δr) |> sites
2-element Vector{SVector{2, Float64}}:
[-0.5, 1.0]
[0.5, 1.0]
```
This type of curried syntax is natural in Quantica, and will be used extensively in this tutorial.
| Quantica | https://github.com/pablosanjose/Quantica.jl.git |
|
[
"MIT"
] | 1.1.0 | 258274c47afd63fe67dade9c3f12244b086288e8 | docs | 9623 | # Models
We now will show how to build a generic single-particle tight-binding model, with generic Hamiltonian
``H = \sum_{i\alpha j\beta} c_{i\alpha}^\dagger V_{\alpha\beta}(r_i, r_j)c_{j\alpha}``
Here, `α,β` are orbital indices in each site, `i,j` are site indices, and `rᵢ, rⱼ` are site positions. In Quantica.jl we would write the above model as
```julia
julia> model = onsite(r -> V(r, r)) + hopping((r, dr) -> V(r-dr/2, r+dr/2))
TightbindingModel: model with 2 terms
OnsiteTerm{Function}:
Region : any
Sublattices : any
Cells : any
Coefficient : 1
HoppingTerm{Function}:
Region : any
Sublattice pairs : any
Cell distances : any
Hopping range : Neighbors(1)
Reverse hops : false
Coefficient : 1
```
where `V(rᵢ, rⱼ)` is a function that returns a matrix (ideally an `SMatrix`) ``V_{\alpha\beta}(r_i, r_j)`` of the required orbital dimensionality.
Note that when writing models we distinguish between onsite (`rᵢ=rⱼ`) and hopping (`rᵢ≠rⱼ`) terms. For the former, `r` is the site position. For the latter we use a bond-center and bond-distance `(r, dr)` parametrization of `V`, so that `r₁, r₂ = r ∓ dr/2`
If the onsite and hopping amplitudes do not depend on position, we can simply use constants
```julia
julia> model = onsite(1) - 2*hopping(1)
TightbindingModel: model with 2 terms
OnsiteTerm{Int64}:
Region : any
Sublattices : any
Cells : any
Coefficient : 1
HoppingTerm{Int64}:
Region : any
Sublattice pairs : any
Cell distances : any
Hopping range : Neighbors(1)
Reverse hops : false
Coefficient : -2
```
!!! tip "Model term algebra"
Note that we can combine model terms as in the above example by summing and subtracting them, and using constant coefficients.
## HopSelectors
By default `onsite` terms apply to any site in a Lattice, and `hopping` terms apply to any pair of sites within nearest-neighbor distance (see the `Hopping range: Neighbors(1)` above).
We can change this default by specifying a `SiteSelector` or `HopSelector` for each term. `SiteSelector`s where [already introduced](@ref siteselectors) to create `LatticeSlices`. `HopSelectors` are very similar, but support slightly different keywords:
- `region`: to restrict according to bond center `r` and bond vector `dr`
- `sublats`: to restrict source and target sublattices
- `dcells`: to restrict the distance in cell index
- `range`: to restrict the distance in real space
As an example, a `HopSelector` that selects any two sites at a distance between `1.0` and the second-nearest neighbor distance, with the first belonging to sublattice `:B` and the second to sublattice `:A`, and their bond center inside a unit circle
```julia
julia> hs = hopselector(range = (1.0, neighbors(2)), sublats = :B => :A, region = (r, dr) -> norm(r) < 1)
HopSelector: a rule that defines a finite collection of hops between sites in a lattice
Region : Function
Sublattice pairs : :B => :A
Cell distances : any
Hopping range : (1.0, Neighbors(2))
Reverse hops : false
```
We can now use this `HopSelector` to restrict the hoppings in a model, just as `SiteSelector`s can be used to restrict onsite terms
```julia
julia> model = plusadjoint(hopping(1, hs)) - 2*onsite(1, sublats = :B)
TightbindingModel: model with 3 terms
HoppingTerm{Int64}:
Region : Function
Sublattice pairs : :B => :A
Cell distances : any
Hopping range : (1.0, Neighbors(2))
Reverse hops : false
Coefficient : 1
HoppingTerm{Int64}:
Region : Function
Sublattice pairs : :B => :A
Cell distances : any
Hopping range : (1.0, Neighbors(2))
Reverse hops : true
Coefficient : 1
OnsiteTerm{Int64}:
Region : any
Sublattices : B
Cells : any
Coefficient : 1
```
Note that we can pass the `Selector` itself as a second argument to `hopping` and `onsite`, or alternatively use selector keywords directly as in the `onsite` above.
!!! tip "plusadjoint function"
The convenience function `plusadjoint(term) = term + term'` adds the Hermitian conjugate of its argument (`term'`), equivalent to the `+ h.c.` notation often used in the literature.
!!! note "Index-agnostic modeling"
The Quantica.jl approach to defining tight-binding models does not rely explicitly on site indices (`i,j` above), since these are arbitrary, and may even be beyond the control of the user (for example after using `supercell`). Instead, we rely on physical properties of sites, such as position, distance or sublattice.
## Parametric Models
The models introduced above are non-parametric, in the sense that they encode fixed, numerical Hamiltonian matrix elements. In many problems, it is commonplace to have models that depend on a number of free parameters that will need to be adjusted during a calculation. For example, one may need to compute the phase diagram of a system as a function of a spin-orbit coupling or an applied magnetic field. For these cases, we have `ParametricModel`s.
Parametric models are defined with
- `@onsite((; params...) -> ...; sites...)`
- `@onsite((r; params...) -> ...; sites...)`
- `@hopping((; params...) -> ...; hops...)`
- `@hopping((r, dr; params...) -> ...; hops...)`
where the `params` keyword arguments define the free parameters, together with (optional) default values. Here is an example of a hopping model with a Peierls phase in the symmetric gauge, with the magnetic field `Bz` and the zero-field hopping `t` as free parameters
```julia
julia> model_perierls = @hopping((r, dr; Bz = 0, t = 1) -> t * cis(-im * Bz/2 * SA[-r[2], r[1], 0]' * dr))
ParametricModel: model with 1 term
ParametricHoppingTerm{ParametricFunction{2}}
Region : any
Sublattice pairs : any
Cell distances : any
Hopping range : Neighbors(1)
Reverse hops : false
Coefficient : 1
Argument type : spatial
Parameters : [:Bz, :t]
```
One can linearly combine parametric and non-parametric models freely, omit parameter default values, and use any of the functional argument forms described for `onsite` and `hopping` (although not the constant argument form):
```julia
julia> model´ = 2 * (onsite(1) - 2 * @hopping((; t) -> t))
ParametricModel: model with 2 terms
ParametricHoppingTerm{ParametricFunction{0}}
Region : any
Sublattice pairs : any
Cell distances : any
Hopping range : Neighbors(1)
Reverse hops : false
Coefficient : -4
Argument type : spatial
Parameters : [:t]
OnsiteTerm{Int64}:
Region : any
Sublattices : any
Cells : any
Coefficient : 2
```
!!! tip "Non-spatial parametric models with -->"
The `->` in the above parametric models `@onsite` and `@hopping`, but also in the modifiers below, can be changed to `-->`. This indicates that the function arguments are no longer treated as site or link positions `r` and `dr`, but as objects `i, j` representing destination and source sites. This allows to address sites directly instead of through their spatial location. See the Mean Field section for further details.
## Modifiers
There is a third model-related functionality known as `OnsiteModifier`s and `HoppingModifier`s. Given a model that defines a set of onsite and hopping amplitudes on a subset of sites and hops, one can define a parameter-dependent modification of a subset of said amplitudes. This is a useful way to introduce a new parameter dependence on an already defined model. Modifiers are built with
- `@onsite!((o; params...) -> new_onsite; sites...)`
- `@onsite!((o, r; params...) -> new_onsite; sites...)`
- `@hopping((t; params...) -> new_hopping; hops...)`
- `@hopping((t, r, dr; params...) -> new_hopping; hops...)`
where the first argument `o` and `t` is the unmodified value of the onsite or hopping amplitude, respectively. Here `sites` and `hops` are once more keyword arguments to restrict the modification with a `SiteSelector` or `HopSelector`.
For example, the following `HoppingModifier` inserts a Peierls phase on all the hopping in a given model
```julia
julia> model_perierls! = @hopping!((t, r, dr; B = 0) -> t * cis(-Bz/2 * SA[-r[2], r[1], 0]' * dr))
HoppingModifier{ParametricFunction{3}}:
Region : any
Sublattice pairs : any
Cell distances : any
Hopping range : Inf
Reverse hops : false
Argument type : spatial
Parameters : [:B]
```
The difference with `model_perierls` is that `model_perierls!` will never add any new hoppings. It will only modify previously existing hoppings in a model. Modifiers are not models themselves, and cannot be summed to other models. They are instead meant to be applied sequentially after applying a model.
In the next section we show how models and modifiers can be used in practice to construct Hamiltonians.
!!! note "Mind the `;`"
While syntax like `onsite(2, sublats = :B)` and `onsite(2; sublats = :B)` are equivalent in Julia, due to the way keyword arguments are parsed, the same is not true for macro calls like `@onsite`, `@onsite!`, `@hopping` and `@hopping!`. These macros just emulate the function call syntax. But to work you must currently always use the `;` separator for keywords. Hence, something like `@onsite((; p) -> p; sublats = :B)` works, but `@onsite((; p) -> p, sublats = :B)` does not.
| Quantica | https://github.com/pablosanjose/Quantica.jl.git |
|
[
"MIT"
] | 1.1.0 | 258274c47afd63fe67dade9c3f12244b086288e8 | docs | 18203 | # Observables
We are almost at our destination now. We have defined a `Lattice`, a `Model` for our system, we applied the `Model` to the `Lattice` to obtain a `Hamiltonian` or a `ParametricHamiltonian`, and finally, after possibly attaching some contacts to outside reservoirs and specifying a `GreenSolver`, we obtained a `GreenFunction`. It is now time to use the `GreenFunction` to obtain some observables of interest.
Currently, we have the following observables built into Quantica.jl (with more to come in the future)
- `ldos`: computes the local density of states at specific energy and sites
- `densitymatrix`: computes the density matrix at thermal equilibrium on specific sites.
- `current`: computes the local current density along specific directions, and at specific energy and sites
- `transmission`: computes the total transmission between contacts
- `conductance`: computes the differential conductance `dIᵢ/dVⱼ` between contacts `i` and `j`
- `josephson`: computes the supercurrent and the current-phase relation through a given contact in a superconducting system
See the corresponding docstrings for full usage instructions. Here we will present some basic examples
## Local density of states (LDOS)
Let us compute the LDOS in a cavity like in the previous section. Instead of computing the Green function between a contact to an arbitrary point, we can construct an object `d = ldos(g(ω))` without any contacts. By using a small imaginary part in `ω`, we broaden the discrete spectrum, and obtain a finite LDOS. Then, we can pass `d` directly as a site shader to `qplot`
```julia
julia> h = LP.square() |> onsite(4) - hopping(1) |> supercell(region = r -> norm(r) < 40*(1+0.2*cos(5*atan(r[2],r[1]))));
julia> g = h |> greenfunction;
julia> d = ldos(g(0.1 + 0.001im))
LocalSpectralDensitySolution{Float64} : local density of states at fixed energy and arbitrary location
kernel : LinearAlgebra.UniformScaling{Bool}(true)
julia> qplot(h, hide = :hops, sitecolor = d, siteradius = d, minmaxsiteradius = (0, 2), sitecolormap = :balance)
```
```@raw html
<img src="../../assets/star_shape_ldos.png" alt="LDOS" width="400" class="center"/>
```
Note that `d[sites...]` produces a vector with the LDOS at sites defined by `siteselector(; sites...)` (`d[]` is the ldos over all sites). We can also define a `kernel` to be traced over orbitals to obtain the spectral density of site-local observables (see `diagonal` slicing in the preceding section).
## Density matrix
We can also compute the convolution of the density of states with the Fermi distribution `f(ω)=1/(exp((ω-μ)/kBT) + 1)`, which yields the density matrix in thermal equilibrium, at a given temperature `kBT` and chemical potential `μ`. This is computed with `ρ = densitymatrix(gs, (ωmin, ωmax))`. Here `gs = g[sites...]` is a `GreenSlice`, and `(ωmin, ωmax)` are integration bounds (they should span the full bandwidth of the system). Then, `ρ(µ, kBT = 0; params...)` will yield a matrix over the selected `sites` for a set of model `params`.
```julia
julia> ρ = densitymatrix(g[region = RP.circle(1)], (-0.1, 8.1))
DensityMatrix: density matrix on specified sites using solver of type DensityMatrixIntegratorSolver
julia> @time ρ(4)
6.150548 seconds (57.84 k allocations: 5.670 GiB, 1.12% gc time)
5×5 OrbitalSliceMatrix{Matrix{ComplexF64}}:
0.5+0.0im -7.34893e-10-3.94035e-15im 0.204478+1.9366e-14im -7.34889e-10-1.44892e-15im -5.70089e-10+5.48867e-15im
-7.34893e-10+3.94035e-15im 0.5+0.0im 0.200693-2.6646e-14im -5.70089e-10-1.95251e-15im -7.34891e-10-2.13804e-15im
0.204478-1.9366e-14im 0.200693+2.6646e-14im 0.5+0.0im 0.200693+3.55692e-14im 0.204779-4.27255e-14im
-7.34889e-10+1.44892e-15im -5.70089e-10+1.95251e-15im 0.200693-3.55692e-14im 0.5+0.0im -7.34885e-10-3.49861e-15im
-5.70089e-10-5.48867e-15im -7.34891e-10+2.13804e-15im 0.204779+4.27255e-14im -7.34885e-10+3.49861e-15im 0.5+0.0im
```
Note that the diagonal is `0.5`, indicating half-filling.
The default algorithm used here is slow, as it relies on numerical integration in the complex plane. Some GreenSolvers have more efficient implementations. If they exist, they can be accessed by omitting the `(ωmin, ωmax)` argument. For example, using `GS.Spectrum`:
```julia
julia> @time g = h |> greenfunction(GS.Spectrum());
37.638522 seconds (105 allocations: 2.744 GiB, 0.79% gc time)
julia> ρ = densitymatrix(g[region = RP.circle(1)])
DensityMatrix: density matrix on specified sites with solver of type DensityMatrixSpectrumSolver
julia> @time ρ(4)
0.001659 seconds (9 allocations: 430.906 KiB)
5×5 OrbitalSliceMatrix{Matrix{ComplexF64}}:
0.5+0.0im -2.21437e-15+0.0im 0.204478+0.0im 2.67668e-15+0.0im 3.49438e-16+0.0im
-2.21437e-15+0.0im 0.5+0.0im 0.200693+0.0im -1.40057e-15+0.0im -2.92995e-15+0.0im
0.204478+0.0im 0.200693+0.0im 0.5+0.0im 0.200693+0.0im 0.204779+0.0im
2.67668e-15+0.0im -1.40057e-15+0.0im 0.200693+0.0im 0.5+0.0im 1.81626e-15+0.0im
3.49438e-16+0.0im -2.92995e-15+0.0im 0.204779+0.0im 1.81626e-15+0.0im 0.5+0.0im
```
Note, however, that the computation of `g` is much slower in this case, due to the need of a full diagonalization. A better algorithm choice in this case is `GS.KPM`. It requires, however, that we define the region for the density matrix beforehand, as a `nothing` contact.
```julia
julia> @time g = h |> attach(nothing, region = RP.circle(1)) |> greenfunction(GS.KPM(order = 10000, bandrange = (0,8)));
Computing moments: 100%|█████████████████████████████████████████████████████████████████████████████████| Time: 0:00:01
2.065083 seconds (31.29 k allocations: 11.763 MiB)
julia> ρ = densitymatrix(g[1])
DensityMatrix: density matrix on specified sites with solver of type DensityMatrixKPMSolver
julia> @time ρ(4)
0.006580 seconds (3 allocations: 1.156 KiB)
5×5 OrbitalSliceMatrix{Matrix{ComplexF64}}:
0.5+0.0im 2.15097e-17+0.0im 0.20456+0.0im 2.15097e-17+0.0im 3.9251e-17+0.0im
2.15097e-17+0.0im 0.5+0.0im 0.200631+0.0im 1.05873e-16+0.0im 1.70531e-18+0.0im
0.20456+0.0im 0.200631+0.0im 0.5+0.0im 0.200631+0.0im 0.20482+0.0im
2.15097e-17+0.0im 1.05873e-16+0.0im 0.200631+0.0im 0.5+0.0im 1.70531e-18+0.0im
3.9251e-17+0.0im 1.70531e-18+0.0im 0.20482+0.0im 1.70531e-18+0.0im 0.5+0.0im
```
## Current
A similar computation can be done to obtain the current density, using `J = current(g(ω), direction = missing)`. This time `J[sᵢ, sⱼ]` yields a sparse matrix of current densities along a given direction for each hopping (or the current norm if `direction = missing`). Passing `J` as a hopping shader yields the equilibrium current in a system. In the above example we can add a magnetic flux to make this current finite
```julia
julia> h = LP.square() |> supercell(region = r -> norm(r) < 40*(1+0.2*cos(5*atan(r[2],r[1])))) |> onsite(4) - @hopping((r, dr; B = 0.1) -> cis(B * dr[1] * r[2]));
julia> g = h |> greenfunction;
julia> J = current(g(0.1; B = 0.01))
CurrentDensitySolution{Float64} : current density at a fixed energy and arbitrary location
charge : LinearAlgebra.UniformScaling{Int64}(-1)
direction : missing
julia> qplot(h, siteradius = 0.08, sitecolor = :black, siteoutline = 0, hopradius = J, hopcolor = J, minmaxhopradius = (0, 2), hopcolormap = :balance, hopdarken = 0)
```
```@raw html
<img src="../../assets/star_shape_current.png" alt="Current density with magnetic flux" width="400" class="center"/>
```
!!! note "Remember to construct supercell before applying position-dependent fields"
Note that we built the supercell before applying the model with the magnetic flux. Not doing so would make the gauge field be repeated in each unit cell when expanding the supercell. This was mentioned in the section on Hamiltonians, and is a common mistake when modeling systems with position dependent fields.
## Transmission
The transmission `Tᵢⱼ` from contact `j` to contact `i` can be computed using `transmission`. This function accepts a `GreenSlice` between the contact. Let us recover the four-terminal setup of the preceding section, but let's make it bigger this time
```julia
julia> hcentral = LP.square() |> hopping(-1) |> supercell(region = RP.circle(100) | RP.rectangle((202, 50)) | RP.rectangle((50, 202)))
julia> glead = LP.square() |> hopping(-1) |> supercell((1, 0), region = r -> abs(r[2]) <= 50/2) |> greenfunction(GS.Schur(boundary = 0));
julia> Rot = r -> SA[0 -1; 1 0] * r; # 90º rotation function
julia> g = hcentral |>
attach(glead, region = r -> r[1] == 101) |>
attach(glead, region = r -> r[1] == -101, reverse = true) |>
attach(glead, region = r -> r[2] == 101, transform = Rot) |>
attach(glead, region = r -> r[2] == -101, reverse = true, transform = Rot) |>
greenfunction;
julia> gx1 = abs2.(g(-3.96)[siteselector(), 1]);
julia> qplot(hcentral, hide = :hops, siteoutline = 1, sitecolor = gx1, siteradius = gx1, minmaxsiteradius = (0, 2), sitecolormap = :balance)
```
```@raw html
<img src="../../assets/four_terminal_g_big.png" alt="Green function from right lead" width="400" class="center"/>
```
!!! tip "Matrix and vector shaders"
In the above example `gx1` is a matrix with one row per orbital in `hcentral`. The color and radii of each site is obtained from the sum of each row. If `gx1` were a vector, the color/radius of site `i` would be taken as `gx1[i]`. See `plotlattice` for more details and other shader types.
It's apparent from the plot that the transmission from right to left (`T₂₁` here) at this energy of `0.04` is larger than from right to top (`T₃₁`). Is this true in general? Let us compute the two transmissions as a function of energy. To show the progress of the calculation we can use a monitor package, such as `ProgressMeter`
```julia
julia> using ProgressMeter
julia> T₂₁ = transmission(g[2,1]); T₃₁ = transmission(g[3,1]); ωs = subdiv(-4, 4, 201);
julia> T₂₁ω = @showprogress [T₂₁(ω) for ω in ωs]; T₃₁ω = @showprogress [T₃₁(ω) for ω in ωs];
Progress: 100%|██████████████████████████████████████████████████████████████| Time: 0:01:02
Progress: 100%|██████████████████████████████████████████████████████████████| Time: 0:01:00
julia> f = Figure(); a = Axis(f[1,1], xlabel = "ω/t", ylabel = "T(ω)"); lines!(a, ωs, T₂₁ω, label = L"T_{2,1}"); lines!(a, ωs, T₃₁ω, label = L"T_{3,1}"); axislegend("Transmission", position = :lt); f
```
```@raw html
<img src="../../assets/four_terminal_T.png" alt="Total transmission from right contact" width="400" class="center"/>
```
So we indeed find that the 90-degree transmission `T₃₁` is indeed larger than the forward transmission `T₂₁` for all energies. The rapid oscillations are due to mesoscopic fluctuations.
!!! note "Total transmission vs transmission probability"
Note that `transmission` gives the total transmission, which is the sum of the transmission probability from each orbital in the source contact to any other orbital in the drain contact. As such it is not normalized to 1, but to the number of source orbitals. It also gives the local conductance from a given contact in units of $$e^2/h$$ according to the Landauer formula, $$G_j = e^2/h \sum_i T_{ij}(eV)$$.
## Conductance
Local and non-local differential conductance $$G_{ij} = dI_i/dV_j$$ can be computed with `G = conductance(g[i,j])`. Calling `G(ω)` returns the conductance at bias $$eV = \omega$$ in units of $$e^2/h$$. Let's look at the local differential conductance into the right contact in the previous example
```julia
julia> G₁₁ = conductance(g[1,1])
Conductance{Float64}: Zero-temperature conductance dIᵢ/dVⱼ from contacts i,j, in units of e^2/h
Current contact : 1
Bias contact : 1
julia> ωs = subdiv(-4, 4, 201); Gω = @showprogress [G₁₁(ω) for ω in ωs];
Progress: 100%|██████████████████████████████████████████████████████████████| Time: 0:01:01
julia> f = Figure(); a = Axis(f[1,1], xlabel = "eV/t", ylabel = "G [e²/h]"); lines!(a, ωs, Gω); f
```
```@raw html
<img src="../../assets/four_terminal_cond.png" alt="Local conductance from right contact" width="400" class="center"/>
```
!!! warning "Sign of non-local conductance"
If you compute a non-local conductance such as `conductance(g[2,1])(ω)` in this example you will note it is negative. This is actually expected. It means that the current flowing **into** the system through the right contact when you **increase** the bias in a different contact is negative, because the current is actually flowing out into the right reservoir.
The conductance can also be computed for hybrid (normal-superconducting) systems. To do so,
one first needs to write the model in the Nambu representation, i.e. with particle and hole
orbitals on each site (first particles, then holes). In the above examples amounts to
switching `hopping(-1)` to `hamiltonian(onsite(Δ*σx) - hopping(σz), orbitals = 2)`, with `σx
= SA[0 1; 1 0]`, `σz = SA[1 0; 0 -1]` and `Δ` the pairing amplitude. Then we must specify
`G₁₁ = conductance(g[1,1], nambu = true)` to take into account Andreev reflections. The
above example with left, bottom and top leads superconducting (with `Δ=0.3`) yields the
following conductance `G₁₁` in the right (normal) lead (we leave the implementation as an
exercise for the reader).
```@raw html
<img src="../../assets/four_terminal_nambu.png" alt="Local conductance from right contact, with other contacts superconducting" width="400" class="center"/>
```
Note that within the gap Andreev reflection leads to an enhancement of conductance, since
the contacts are transparent
## Josephson
The above example showcases normal-superconductor (NS) conductance, which is a Fermi-surface
process in response to an electric bias on the normal contacts. In contrast,
supercorconductor-superconductor junctions, also known as Josephson junctions, can exhibit
supercurrents carried by the full Fermi sea even without a bias. Usually, this supercurrent
flows in response to a phase bias between the superconductors, where by phase we mean the
complex phase of the `Δ` order parameter.
We can compute the supercurrent or the full current-phase relation of a Josephson junction
with the command `josephson(gs::GreenSlice, ωmax)`, where `gs = g[contact_id]` and `ωmax` is
the full bandwidth of the system (i.e. the maximum energy, in absolute value, spanned by the
Fermi sea). This latter quantity can be an estimate or even an upper bound, as it is just
used to know up to which energy we should integrate the supercurrent. Let us see an example.
```julia
julia> σz = SA[1 0; 0 -1];
julia> central_region = RP.circle(50) & !RP.circle(40) | RP.rectangle((4, 10), (-50, 0)) | RP.rectangle((4, 10), (50, 0));
julia> h = LP.square() |> hamiltonian(hopping(-σz), orbitals = 2) |> supercell(region = central_region)
julia> Σ(ω, Δ) = SA[-ω Δ; conj(Δ) -ω]/sqrt(1-abs2(Δ))
julia> g = h |>
attach(@onsite((ω; Δ = 0.2) -> Σ(ω, Δ)); region = r -> r[1] < -51) |>
attach(@onsite((ω; Δ = 0.2, phase = 0) -> Σ(ω, Δ*cis(phase))); region = r -> r[1] > 51) |>
greenfunction
GreenFunction{Float64,2,0}: Green function of a Hamiltonian{Float64,2,0}
Solver : AppliedSparseLUGreenSolver
Contacts : 2
Contact solvers : (SelfEnergyModelSolver, SelfEnergyModelSolver)
Contact sizes : (11, 11)
Hamiltonian{Float64,2,0}: Hamiltonian on a 0D Lattice in 2D space
Bloch harmonics : 1
Harmonic size : 2884 × 2884
Orbitals : [2]
Element type : 2 × 2 blocks (ComplexF64)
Onsites : 0
Hoppings : 10800
Coordination : 3.7448
julia> J = josephson(g[1], 4.1)
Integrator: Complex-plane integrator
Integration path : (-4.1 + 1.4901161193847656e-8im, -2.05 + 2.050000014901161im, 0.0 + 1.4901161193847656e-8im)
Integration options : (atol = 1.0e-7,)
Integrand: :
JosephsonDensity{Float64} : Equilibrium (dc) Josephson current observable before integration over energy
kBT : 0.0
Contact : 1
Number of phase shifts : 0
julia> qplot(g, children = (; sitecolor = :blue))
```
```@raw html
<img src="../../assets/josephson_lat.png" alt="Josephson junction" width="400" class="center"/>
```
In this case we have chosen to introduce the superconducting leads with a model self-energy,
corresponding to a BCS bulk, but any other self-energy form could be used. We have introduced the phase difference (`phase`) as a model parameter. We can now evaluate the zero-temperature Josephson current simply with
```julia
julia> J(phase = 0)
-1.974396994480587e-16
julia> J(phase = 0.2)
0.004617597139699372
```
Note that finite temperatures can be taken using the `kBT` keyword argument for `josephson`, see docstring for details.
One is often interested in the critical current, which is the maximum of the Josephson current over all phase differences. Quantica.jl can compute the integral over a collection of phase differences simultaneously, which is more efficient that computing them one by one. This is done with
```julia
julia> φs = subdiv(0, pi, 11); J = josephson(g[1], 4.1; phases = φs)
Integration path : (-4.1 + 1.4901161193847656e-8im, -2.05 + 2.050000014901161im, 0.0 + 1.4901161193847656e-8im)
Integration options : (atol = 1.0e-7,)
Integrand: :
JosephsonDensity{Float64} : Equilibrium (dc) Josephson current observable before integration over energy
kBT : 0.0
Contact : 1
Number of phase shifts : 11
julia> Iφ = J()
11-element Vector{Float64}:
1.868862401627357e-14
0.007231421775452674
0.014242855188877
0.02081870760779799
0.026752065104401878
0.031847203848574666
0.0359131410974842
0.03871895510547465
0.039762442694035505
0.03680096751905469
2.7677727119798235e-14
julia> f = Figure(); a = Axis(f[1,1], xlabel = "φ", ylabel = "I [e/h]"); lines!(a, φs, Iφ); scatter!(a, φs, Iφ); f
```
```@raw html
<img src="../../assets/josephson_CPR.png" alt="Josephson junction current-phase relation" width="400" class="center"/>
```
| Quantica | https://github.com/pablosanjose/Quantica.jl.git |
|
[
"MIT"
] | 1.1.0 | 258274c47afd63fe67dade9c3f12244b086288e8 | docs | 1188 | # Tutorial
Welcome to the Quantica.jl tutorial!
Here you will learn how to use Quantica.jl to build and compute properties of tight-binding models. This includes
- Defining general **Lattices** in arbitrary dimensions
- Defining generic tight-binding **Models** with arbitrary parameter dependences
- Building **Hamiltonians** of mono- or multiorbital systems by combining Lattices and Models
- Computing **Bandstructures** of Hamiltonians
- Computing **GreenFunctions** of Hamiltonians or OpenHamiltonians (i.e. Hamiltonians with attached self-energies from other Hamiltonians, such as leads).
- Computing **Observables** from Green functions, such as spectral densities, current densities, local and nonlocal conductances, Josephson currents, critical currents, transmission probabilities, etc.
Check the menu on the left for shortcuts to the relevant sections.
!!! tip "Check the docstrings"
Full usage instructions on all Quantica.jl functions can be found [here](@ref api) or within the Julia REPL by querying their docstrings. For example, to obtain details on the `hamiltonian` function or on the available `LatticePresets`, just type `?hamiltonian` or `?LatticePresets`.
| Quantica | https://github.com/pablosanjose/Quantica.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 867 | using Cassette
using Documenter
makedocs(;
modules = [Cassette],
authors = "Jarrett Revels",
sitename = "Cassette",
format = Documenter.HTML(;
prettyurls = get(ENV, "CI", "false") == "true",
ansicolor = true,
),
pages = Any[
"Introduction" => "index.md",
"Disclaimers" => "disclaimers.md",
"Why Cassette?" => "whycassette.md",
"The Overdubbing Mechanism" => "overdub.md",
"Contextual Dispatch" => "contextualdispatch.md",
"Contextual Compiler Pass Injection" => "contextualpass.md",
"Contextual Tagging of Values" => "contextualtagging.md",
"Cassette API Documentation" => "api.md",
"Related Work" => "relatedwork.md",
],
strict = false,
)
deploydocs(; repo = "github.com/JuliaLabs/Cassette.jl",
push_preview = true,
)
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 240 | module Cassette
using Core: CodeInfo, SlotNumber, SSAValue, Typeof
include("context.jl")
include("pass.jl")
include("tagging.jl")
include("overdub.jl")
include("deprecations.jl")
const NO_PASS = @pass (_, r) -> r.code_info
end # module
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 17522 | ##################
# `AbstractPass` #
##################
abstract type AbstractPass end
#########
# `Tag` #
#########
# this @pure annotation has official vtjnash approval :p
Base.@pure _pure_objectid(x) = objectid(x)
abstract type AbstractContextName end
struct Tag{N<:AbstractContextName,X,E#=<:Union{Nothing,Tag}=#} end
Tag(::Type{N}, ::Type{X}) where {N,X} = Tag(N, X, Nothing)
Tag(::Type{N}, ::Type{X}, ::Type{E}) where {N,X,E} = Tag{N,_pure_objectid(X),E}()
#################
# `BindingMeta` #
#################
# We define these here because we need them to define `Context`,
# but most code that works with these types is in src/tagged.jl
mutable struct BindingMeta
data::Any
BindingMeta() = new()
end
const BindingMetaDict = Dict{Symbol,BindingMeta}
const BindingMetaDictCache = IdDict{Module,BindingMetaDict}
#############
# `Context` #
#############
struct DisableHooks end
"""
```
Context{N<:Cassette.AbstractContextName,
M<:Any,
P<:Cassette.AbstractPass,
T<:Union{Nothing,Cassette.Tag},
B<:Union{Nothing,Cassette.BindingMetaDictCache},
H<:Union{Nothing,Cassette.DisableHooks}}
```
A type representing a Cassette execution context. This type is normally interacted with
through type aliases constructed via `Cassette.@context`:
```
julia> Cassette.@context MyCtx
Cassette.Context{nametype(MyCtx),M,P,T,B,H} where H<:Union{Nothing,DisableHooks}
where B<:Union{Nothing,IdDict{Module,Dict{Symbol,BindingMeta}}}
where P<:AbstractPass
where T<:Union{Nothing,Tag}
where M
```
# Constructors
Given a context type alias named e.g. `MyCtx`, an instance of the type can be constructed via:
```
MyCtx(; metadata = nothing, pass = Cassette.NoPass())
```
To construct a new context instance using an existing context instance as a template, see
the `similarcontext` function.
To enable contextual tagging for a given context instance, see the [`enabletagging`](@ref) function.
# Fields
- `name::N<:Cassette.AbstractContextName`: a parameter used to disambiguate different
contexts for overloading purposes (e.g. distinguishes `MyCtx` from other `Context` type
aliases).
- `metadata::M<:Any`: trace-local metadata as provided to the context constructor
- `tag::T<:Union{Nothing,Tag}`: the tag object that is attached to values when they are
tagged w.r.t. the context instance
- `pass::P<:Cassette.AbstractPass`: the Cassette pass that will be applied to all method
bodies encountered during contextual execution (see the [`@pass`](@ref) macro for details).
- `bindingscache::B<:Union{Nothing,BindingMetaDictCache}}`: storage for metadata associated
with tagged module bindings
- `hooktoggle::H<:Union{Nothing,DisableHooks}`: configuration toggle for disabling
the `overdub` pass's `prehook`/`posthook` injection (see [`disablehooks`](@ref)
for details)
"""
struct Context{N<:AbstractContextName,
M<:Any,
T<:Union{Nothing,Tag},
P<:AbstractPass,
B<:Union{Nothing,BindingMetaDictCache},
H<:Union{Nothing,DisableHooks}}
name::N
metadata::M
tag::T
pass::P
bindingscache::B
hooktoggle::H
end
const ContextUntagged{N<:AbstractContextName} = Context{N,<:Any,Nothing}
const ContextTagged{T<:Tag,N<:AbstractContextName} = Context{N,<:Any,T}
const ContextWithPass{P<:AbstractPass,N<:AbstractContextName} = Context{N,<:Any,<:Union{Nothing,Tag},P}
const ContextWithHookToggle{H<:Union{Nothing,DisableHooks},N<:AbstractContextName} = Context{N,<:Any,<:Union{Nothing,Tag},<:AbstractPass,<:Union{Nothing,BindingMetaDictCache},H}
function Context(name::AbstractContextName; metadata = nothing, pass::AbstractPass = NO_PASS)
return Context(name, metadata, nothing, pass, nothing, nothing)
end
"""
```
similarcontext(context::Context;
metadata = context.metadata,
pass = context.pass)
```
Return a copy of the given `context`, where the copy's `metadata` and/or `pass`
fields are replaced with those provided via the corresponding keyword arguments.
"""
function similarcontext(context::Context;
metadata = context.metadata,
pass = context.pass)
return Context(context.name, metadata, context.tag, pass,
context.bindingscache, context.hooktoggle)
end
"""
```
disablehooks(context::Cassette.Context)
```
Return of copy of the given `context` with `prehook`/`posthook` injection
disabled for the context. Disabling hook injection can reduce IR bloat in
scenarios where these hooks are not being utilized.
"""
function disablehooks(context::Context)
return Context(context.name, context.metadata, context.tag, context.pass,
context.bindingscache, DisableHooks())
end
"""
```
enabletagging(context::Cassette.Context, f)
```
Return a copy of the given `context` with the tagging system enabled for the contextual
execution of `f`.
Cassette uses the type of `f` to generate the `tag` field of the returned instance.
Note that it is generally unsafe to use the returned instance to contextually execute
functions other than `f`. Specifically, in cases of nested contextual execution where
both inner and outer contexts employ the tagging system, improper application of the
tagged system could cause (for example) separate contexts to erroneously interfere with
each other's metadata propagation.
See also: [`hastagging`](@ref)
"""
function enabletagging(context::Context, f)
return Context(context.name, context.metadata,
Tag(typeof(context.name), typeof(f)),
context.pass, BindingMetaDictCache(), context.hooktoggle)
end
"""
```
hastagging(::Type{<:Cassette.Context})
```
Returns `true` if the given type indicates that the contextual tagging system is enabled
for context instances of the type, returns `false` otherwise.
# Example
```
julia> Cassette.@context MyCtx;
julia> ctx = MyCtx();
julia> Cassette.hastagging(typeof(ctx))
false
julia> ctx = Cassette.enabletagging(ctx, sum);
julia> Cassette.hastagging(typeof(ctx))
true
```
See also: [`enabletagging`](@ref)
"""
hastagging(::Type{<:ContextTagged}) = true
hastagging(::Type{<:ContextUntagged}) = false
hashooks(::Type{<:ContextWithHookToggle{Nothing}}) = true
hashooks(::Type{<:ContextWithHookToggle{DisableHooks}}) = false
tagtype(::C) where {C<:Context} = tagtype(C)
tagtype(::Type{<:ContextTagged{T}}) where {T} = T
nametype(::Type{<:Context{N}}) where {N} = N
passtype(::Type{<:ContextWithPass{P}}) where {P} = P
############
# @context #
############
"""
```
Cassette.@context Ctx
```
Define a new Cassette context type with the name `Ctx`. In reality, `Ctx` is simply a type
alias for `Cassette.Context{Cassette.nametype(Ctx)}`.
Note that `Cassette.overdub` is automatically overloaded w.r.t. `Ctx` to define several
primitives by default. A full list of these default primitives can be obtained by running:
```
methods(Cassette.overdub, (Ctx, Vararg{Any}))
```
Note also that many of the default primitives' signatures only match when contextual tagging
is enabled.
See also: [`Context`](@ref)
"""
macro context(_Ctx)
@assert isa(_Ctx, Symbol) "context name must be a Symbol"
# These are not necessarily hygienic, but allow for `@context C` to be
# repeatedly declared (as a no-op for redundant declarations) without
# error, similarly to repeated `struct` declarations.
CtxName = esc(Symbol("##$(_Ctx)#Name"))
CtxTagged = esc(Symbol("##$(_Ctx)#Tagged"))
Ctx = esc(_Ctx)
N, M, T, P, H = esc(:N), esc(:M), esc(:T), esc(:P), esc(:H)
return quote
struct $CtxName <: AbstractContextName end
const $Ctx{$M,$T<:Union{Nothing,Tag}} = Context{$CtxName,$M,$T}
const $CtxTagged = ContextTagged{$T,$CtxName} where {$T<:Tag}
$Ctx(; kwargs...) = Context($CtxName(); kwargs...)
@inline Cassette.overdub(::C, ::Typeof(Tag), ::Type{N}, ::Type{X}) where {C<:$Ctx,N,X} = Tag(N, X, tagtype(C))
@inline Cassette.overdub(ctx::$Ctx, ::typeof(Core._apply), f, args...) = Core._apply(overdub, (ctx, f), args...)
if VERSION >= v"1.4.0-DEV.304"
@inline function Cassette.overdub(ctx::$Ctx, ::typeof(Core._apply_iterate), iter, f, args...)
# XXX: Overdubbing the iterate function breaks things
# overdubbed_iter = (args...) -> Core._apply(overdub, (ctx, iter), args...)
Core._apply_iterate(iter, overdub, (ctx, f), args...)
end
end
# TODO: There are certain non-`Core.Builtin` functions which the compiler often
# relies upon constant propagation/tfuncs to infer, instead of specializing on
# them, such as `isdispatchtuple`. Such functions should generally be contextual
# primitives by default for the sake of performance, and we should add more of
# them here as we encounter them.
@inline Cassette.overdub(ctx::$Ctx, f::Typeof(Base.isdispatchtuple), T::Type) = fallback(ctx, f, T)
@inline Cassette.overdub(ctx::$Ctx, f::Typeof(Base.eltype), T::Type) = fallback(ctx, f, T)
@inline Cassette.overdub(ctx::$Ctx, f::Typeof(Base.convert), T::Type, t::Tuple) = fallback(ctx, f, T, t)
@inline Cassette.overdub(ctx::$Ctx{<:Any,Nothing}, f::Typeof(Core.kwfunc), x) = fallback(ctx, f, x)
@inline Cassette.overdub(ctx::$Ctx{<:Any,Nothing}, f::Typeof(Base.getproperty), x::Any, s::Symbol) = fallback(ctx, f, x, s)
@inline Cassette.overdub(ctx::$Ctx, f::Typeof(Base.throw), exception) = fallback(ctx, f, exception)
# the below primitives are only active when the tagging system is enabled (`typeof(ctx) <: CtxTagged`)
@inline Cassette.overdub(ctx::C, f::Typeof(tag), value, ::C, metadata) where {C<:$CtxTagged} = fallback(ctx, f, value, ctx, metadata)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Array{T,N}), undef::UndefInitializer, args...) where {T,N} = tagged_new_array(ctx, Array{T,N}, undef, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Core.Module), args...) = tagged_new_module(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Core.tuple), args...) = tagged_new_tuple(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Base.nameof), args...) = tagged_nameof(ctx, m)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Core.getfield), args...) = tagged_getfield(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Core.setfield!), args...) = tagged_setfield!(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Core.arrayref), args...) = tagged_arrayref(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Core.arrayset), args...) = tagged_arrayset(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Base._growbeg!), args...) = tagged_growbeg!(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Base._growend!), args...) = tagged_growend!(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Base._growat!), args...) = tagged_growat!(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Base._deletebeg!), args...) = tagged_deletebeg!(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Base._deleteend!), args...) = tagged_deleteend!(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Base._deleteat!), args...) = tagged_deleteat!(ctx, args...)
@inline Cassette.overdub(ctx::$CtxTagged, ::Typeof(Core.typeassert), args...) = tagged_typeassert(ctx, args...)
@inline function Cassette.overdub(ctx::$CtxTagged, f::Core.IntrinsicFunction, args...)
if f === Base.sitofp
return tagged_sitofp(ctx, args...)
elseif f === Base.sle_int
return tagged_sle_int(ctx, args...)
else # TODO: add more cases
return fallback(ctx, f, args...)
end
end
$Ctx
end
end
###############################
# contextual dispatch methods #
###############################
"""
```
prehook(context::Context, f, args...)
```
Overload this Cassette method w.r.t. a given context in order to define a new contextual
prehook for that context.
To understand when/how this method is called, see the documentation for [`overdub`](@ref).
Invoking `prehook` is a no-op by default (it immediately returns `nothing`).
See also: [`overdub`](@ref), [`posthook`](@ref), [`recurse`](@ref), [`fallback`](@ref)
# Examples
Simple trace logging:
```
julia> Cassette.@context PrintCtx;
julia> Cassette.prehook(::PrintCtx, f, args...) = println(f, args)
julia> Cassette.overdub(PrintCtx(), /, 1, 2)
float(1,)
AbstractFloat(1,)
Float64(1,)
sitofp(Float64, 1)
float(2,)
AbstractFloat(2,)
Float64(2,)
sitofp(Float64, 2)
/(1.0, 2.0)
div_float(1.0, 2.0)
0.5
```
Counting the number of method invocations with one or more arguments of a given type:
```
julia> mutable struct Count{T}
count::Int
end
julia> Cassette.@context CountCtx;
julia> Cassette.prehook(ctx::CountCtx{Count{T}}, f, arg::T, args::T...) where {T} = (ctx.metadata.count += 1)
# count the number of calls of the form `f(::Float64, ::Float64...)`
julia> ctx = CountCtx(metadata = Count{Float64}(0));
julia> Cassette.overdub(ctx, /, 1, 2)
0.5
julia> ctx.metadata.count
2
```
"""
@inline prehook(::Context, ::Vararg{Any}) = nothing
"""
```
posthook(context::Context, output, f, args...)
```
Overload this Cassette method w.r.t. a given context in order to define a new contextual
posthook for that context.
To understand when/how this method is called, see the documentation for [`overdub`](@ref).
Invoking `posthook` is a no-op by default (it immediately returns `nothing`).
See also: [`overdub`](@ref), [`prehook`](@ref), [`recurse`](@ref), [`fallback`](@ref)
# Examples
Simple trace logging:
```
julia> Cassette.@context PrintCtx;
julia> Cassette.posthook(::PrintCtx, output, f, args...) = println(output, " = ", f, args)
julia> Cassette.overdub(PrintCtx(), /, 1, 2)
1.0 = sitofp(Float64, 1)
1.0 = Float64(1,)
1.0 = AbstractFloat(1,)
1.0 = float(1,)
2.0 = sitofp(Float64, 2)
2.0 = Float64(2,)
2.0 = AbstractFloat(2,)
2.0 = float(2,)
0.5 = div_float(1.0, 2.0)
0.5 = /(1.0, 2.0)
0.5
```
Accumulate the sum of all numeric scalar outputs encountered in the trace:
```
julia> mutable struct Accum
x::Number
end
julia> Cassette.@context AccumCtx;
julia> Cassette.posthook(ctx::AccumCtx{Accum}, out::Number, f, args...) = (ctx.metadata.x += out)
julia> ctx = AccumCtx(metadata = Accum(0));
julia> Cassette.overdub(ctx, /, 1, 2)
0.5
julia> ctx.metadata.x
13.0
```
"""
@inline posthook(::Context, ::Vararg{Any}) = nothing
"""
```
fallback(context::Context, f, args...)
```
Overload this Cassette method w.r.t. a given context in order to define a new contextual
execution fallback for that context.
To understand when/how this method is called, see the documentation for [`overdub`](@ref) and
[`canrecurse`](@ref).
By default, invoking `fallback(context, f, args...)` will simply call `f(args...)` (with all
arguments automatically untagged, if `hastagging(typeof(context))`).
See also: [`canrecurse`](@ref), [`overdub`](@ref), [`recurse`](@ref), [`prehook`](@ref), [`posthook`](@ref)
"""
@inline fallback(ctx::Context, args...) = call(ctx, args...)
@inline call(::ContextUntagged, f, args...) = f(args...)
@inline call(context::ContextTagged, f, args...) = untag(f, context)(ntuple(i -> untag(args[i], context), Val(nfields(args)))...)
# TODO: This is currently needed to force the compiler to specialize on the type arguments
# to `Core.apply_type`. In the future, it would be best for Julia's compiler to better handle
# varargs calls to such functions with type arguments, or at least provide a better way to
# force specialization on the type arguments.
@inline call(::ContextUntagged, f::typeof(Core.apply_type), ::Type{A}, ::Type{B}) where {A,B} = f(A, B)
@inline call(::ContextTagged, f::typeof(Core.apply_type), ::Type{A}, ::Type{B}) where {A,B} = f(A, B)
"""
```
canrecurse(context::Context, f, args...)
```
Return `true` if `f(args...)` has a lowered IR representation that Cassette can overdub,
return `false` otherwise.
Alternatively, but equivalently:
Return `false` if `recurse(context, f, args...)` directly translates to
`fallback(context, f, args...)`, return `true` otherwise.
Note that unlike `overdub`, `fallback`, etc., this function is not intended to be overloaded.
See also: [`overdub`](@ref), [`fallback`](@ref), [`recurse`](@ref)
"""
@inline canrecurse(ctx::Context, f, @nospecialize(args...)) = !(isa(untag(f, ctx), Core.Builtin) || _iscompilerfunc(untag(f, ctx)))
@inline canrecurse(ctx::Context, ::typeof(Core._apply), f, @nospecialize(args...)) = Core._apply(canrecurse, (ctx, f), args...)
@static if isdefined(Core, :_apply_iterate)
@inline canrecurse(ctx::Context, ::typeof(Core._apply_iterate), iterate, f, @nospecialize(args...)) = Core._apply_iterate(iterate, canrecurse, (ctx, f), args...)
end
@inline canrecurse(ctx::Context, ::typeof(Core.invoke), f, @nospecialize(_), @nospecialize(args...)) = canrecurse(ctx, f, args...)
_iscompilerfunc(::F) where {F} = Core.Compiler.typename(F).module === Core.Compiler
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 982 | Sorry_OverdubInstead_Is_Deprecated() = error("Usage of `OverdubInstead` should be replaced by `Cassette.recurse`; see `Cassette.recurse` for details.")
Base.@deprecate_binding(OverdubInstead, Sorry_OverdubInstead_Is_Deprecated, false,
string("; the `overdub` <--> `execute` cycle has been removed from Cassette, and",
" usage of `OverdubInstead` has been replaced with `Cassette.recurse`;",
" see `Cassette.recurse` for details."))
struct Sorry_Execute_Is_Deprecated end
Base.@deprecate_binding(execute, Sorry_Execute_Is_Deprecated, false,
string("; the `overdub` <--> `execute` cycle has been removed from Cassette. In",
" most cases, `execute` calls can now be replaced with `overdub`; in",
" general, however, users may need to do some extra refactoring to",
" properly migrate to the new overdubbing model. Feel free to open a",
" Cassette issue for help with migration."))
Base.@deprecate(canoverdub(args...), canrecurse(args...))
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 37277 | ##############
# Reflection #
##############
"""
Cassette.Reflection
A struct representing the information retrieved via `Cassette.reflect`.
A `Reflection` is essentially just a convenient bundle of information about a
specific method invocation.
# Fields
- `signature`: the invocation signature (in `Tuple{...}` type form) for the invoked method.
- `method`: the `Method` object associated with the invoked method.
- `static_params`: a `Vector` representing the invoked method's static parameter list.
- `code_info`: the `CodeInfo` object associated with the invoked method.
"""
mutable struct Reflection
signature::DataType
method::Method
static_params::Vector{Any}
code_info::CodeInfo
end
@static if VERSION < v"1.1.0-DEV.762"
copy_code_info(code_info) = Core.Compiler.copy_code_info(code_info)
else
copy_code_info(code_info) = copy(code_info)
end
@static if VERSION ≥ v"1.8.0-DEV.369"
# https://github.com/JuliaLang/julia/pull/41920
specialize_method(method, metharg, methsp, world, preexisting) = Core.Compiler.specialize_method(method, metharg, methsp; preexisting)
elseif VERSION < v"1.2.0-DEV.573"
specialize_method(method, metharg, methsp, world, preexisting) = Core.Compiler.code_for_method(method, metharg, methsp, world, preexisting)
else
specialize_method(method, metharg, methsp, world, preexisting) = Core.Compiler.specialize_method(method, metharg, methsp, preexisting)
end
function overdubbed_iterate(ctx, iterate)
(args...) -> overdub(ctx, iterate, args...)
end
# in order to get better stacktraces, we insert a fake LineNumberNode and change the code
# locs, so that Julia thinks the method we overdubbed here was a separate method that simply
# got inlined
function verbose_lineinfo!(ci::CodeInfo, @nospecialize(sig::Type{<:Tuple}))
linetable, codelocs = ci.linetable, ci.codelocs
# we actually want to see the whole signature, not just the function name as is
# usually the case if a method is inlined
sig = Symbol(sprint(Base.show_tuple_as_call, :overdub, sig))
linfo = nothing
for _linfo in linetable
if _linfo.inlined_at == 0
@static if fieldtype(Core.LineInfoNode, :inlined_at) === Int32
linfo = Core.LineInfoNode(getfield(_linfo, 1), sig, _linfo.file, _linfo.line, Int32(1))
elseif fieldcount(Core.LineInfoNode) == 5
linfo = Core.LineInfoNode(getfield(_linfo, 1), sig, _linfo.file, _linfo.line, 1)
else
linfo = Core.LineInfoNode(sig, _linfo.file, _linfo.line, 1)
end
break
end
end
# @assert linfo !== nothing
linfo === nothing && return ci
push!(linetable, linfo)
for i in 1:length(codelocs)
if codelocs[i] <= 1
codelocs[i] = length(linetable)
end
end
return ci
end
if VERSION >= v"1.2"
get_world_counter() = Base.get_world_counter()
else
get_world_counter() = typemax(UInt64)
end
# Return `Reflection` for signature `sigtypes` and `world`, if possible. Otherwise, return `nothing`.
function reflect(@nospecialize(sigtypes::Tuple), world::UInt = get_world_counter())
if length(sigtypes) > 2 && sigtypes[1] === typeof(invoke)
@assert sigtypes[3] <: Type{<:Tuple}
sigtypes = (sigtypes[2], sigtypes[3].parameters[1].parameters...)
end
# This works around a subtyping bug. Basically, callers can deconstruct upstream
# `UnionAll` types in such a way that results in a type with free type variables, in
# which case subtyping can just break.
#
# God help you if you try to use a type parameter here (e.g. `::Type{S} where S<:Tuple`)
# instead of this nutty workaround, because the compiler can just rewrite `S` into
# whatever it thinks is "type equal" to the actual provided value. In other words, if
# `S` is defined as e.g. `f(::Type{S}) where S`, and you call `f(T)`, you should NOT
# assume that `S === T`. If you did, SHAME ON YOU. It doesn't matter that such an
# assumption holds true for essentially all other kinds of values. I haven't counted in
# a while, but I'm pretty sure I have ~40+ hellish years of Julia experience, and this
# still catches me every time. Who even uses this crazy language?
S = Tuple{map(s -> Core.Compiler.has_free_typevars(s) ? typeof(s.parameters[1]) : s, sigtypes)...}
(S.parameters[1]::DataType).name.module === Core.Compiler && return nothing
_methods = Base._methods_by_ftype(S, -1, world)
method_index = 0
for i in 1:length(_methods)
if _methods[i][1] === S
method_index = i
break
end
end
method_index === 0 && return nothing
type_signature, raw_static_params, method = _methods[method_index]
method_instance = specialize_method(method, type_signature, raw_static_params, world, false)
method_instance === nothing && return nothing
method_signature = method.sig
static_params = Any[raw_static_params...]
@static if VERSION >= v"1.10.0-DEV.873"
code_info = Core.Compiler.retrieve_code_info(method_instance, world)
else
code_info = Core.Compiler.retrieve_code_info(method_instance)
end
isa(code_info, CodeInfo) || return nothing
code_info = copy_code_info(code_info)
verbose_lineinfo!(code_info, S)
@static if VERSION >= v"1.3.0-DEV.379"
edges = Core.MethodInstance[method_instance]
# if the reflected CI has already edges on it,
# we can safely ignore them since the new CI will
# depend on the MI of the old one.
code_info.edges = edges
end
return Reflection(S, method, static_params, code_info)
end
###########
# overdub #
###########
"""
Cassette.OVERDUB_CONTEXT_NAME
The variable name bound to `overdub`'s `Context` argument in its `@generated`
method definition.
This binding can be used to manually reference/destructure `overdub` arguments
within `Expr` thunks emitted by user-provided passes.
See also: [`OVERDUB_ARGUMENTS_NAME`](@ref), [`@pass`](@ref), [`overdub`](@ref)
"""
const OVERDUB_CONTEXT_NAME = gensym("overdub_context")
"""
Cassette.OVERDUB_ARGUMENTS_NAME
The variable name bound to `overdub`'s tuple of non-`Context` arguments in its
`@generated` method definition.
This binding can be used to manually reference/destructure `overdub` arguments
within `Expr` thunks emitted by user-provided passes.
See also: [`OVERDUB_CONTEXT_NAME`](@ref), [`@pass`](@ref), [`overdub`](@ref)
"""
const OVERDUB_ARGUMENTS_NAME = gensym("overdub_arguments")
@static if VERSION ≥ v"1.9.0-DEV.1598"
iskwftype(@nospecialize(t::Type)) = t === typeof(Core.kwcall)
else
function iskwftype(::Type{F}) where F
name = string(F.name.name)
return @static if VERSION >= v"1.4"
startswith(name, "#") && endswith(name, "##kw")
else
startswith(name, "#kw##")
end
end
end
# The `overdub` pass has four intertwined tasks:
# 1. Apply the user-provided pass, if one is given
# 2. Munge the reflection-generated IR into a valid form for returning from
# `overdub_generator` (i.e. add new argument slots, substitute static
# parameters, destructure overdub arguments into underlying method slots, etc.)
# 3. Perform the statement replacement central to the overdubbing pass (see `overdub` docstring)
# 4. If tagging is enabled, do the necessary IR transforms for the metadata tagging system
function overdub_pass!(reflection::Reflection,
context_type::DataType,
is_invoke::Bool = false)
signature = reflection.signature
method = reflection.method
static_params = reflection.static_params
code_info = reflection.code_info
# TODO: This `iskwfunc` is part of a hack that `overdub_pass!` implements in order to fix
# JuliaLabs/Cassette.jl#48. The assumptions made by this hack are quite fragile, so we
# should eventually get Base to expose a standard/documented API for this. Here, we see
# this hack's first assumption: that `Core.kwfunc(f)` is going to return a function whose
# type name has a prefix and suffix.
# More assumptions for this hack will be commented on as we go.
iskwfunc = iskwftype(signature.parameters[1])
istaggingenabled = hastagging(context_type)
#=== execute user-provided pass (is a no-op by default) ===#
if !iskwfunc
# passtype is defined in the wrong world-age so we need to run it in the newest
# ideally we would add a edge from that function to the generated thunk, but
# alas that would require us, to trace all dynamic function calls. Here be dragons.
code_info = Core._apply_pure(passtype(context_type), (context_type, reflection))
isa(code_info, Expr) && return code_info
end
#=== munge the code into a valid form for `overdub_generator` ===#
# NOTE: The slotflags set by this pass are set according to what makes sense based on the
# compiler's actual `@code_lowered` output in practice, since this real-world output does
# not seem to match Julia's developer documentation.
# construct new slotnames/slotflags for added slots
code_info.slotnames = Any[:overdub, OVERDUB_CONTEXT_NAME, OVERDUB_ARGUMENTS_NAME, code_info.slotnames...]
code_info.slotflags = UInt8[0x00, 0x00, 0x00, code_info.slotflags...]
n_prepended_slots = 3
overdub_ctx_slot = SlotNumber(2)
overdub_args_slot = SlotNumber(3)
# For the sake of convenience, the rest of this pass will translate `code_info`'s fields
# into these overdubbed equivalents instead of updating `code_info` in-place. Then, at
# the end of the pass, we'll reset `code_info` fields accordingly.
overdubbed_code = Any[]
overdubbed_codelocs = Int32[]
# destructure the generated argument slots into the overdubbed method's argument slots.
n_actual_args = fieldcount(signature)
n_method_args = Int(method.nargs)
offset = 1
for i in 1:n_method_args
if is_invoke && (i == 1 || i == 2)
# With an invoke call, we have: 1 is invoke, 2 is f, 3 is Tuple{}, 4... is args.
# In the first loop iteration, we should skip invoke and process f.
# In the second loop iteration, we should skip the Tuple type and process args[1].
offset += 1
end
slot = i + n_prepended_slots
actual_argument = Expr(:call, GlobalRef(Core, :getfield), overdub_args_slot, offset)
push!(overdubbed_code, :($(SlotNumber(slot)) = $actual_argument))
push!(overdubbed_codelocs, code_info.codelocs[1])
code_info.slotflags[slot] |= 0x02 # ensure this slotflag has the "assigned" bit set
offset += 1
end
# If `method` is a varargs method, we have to restructure the original method call's
# trailing arguments into a tuple and assign that tuple to the expected argument slot.
if method.isva
if !isempty(overdubbed_code)
# remove the final slot reassignment leftover from the previous destructuring
pop!(overdubbed_code)
pop!(overdubbed_codelocs)
end
if hastagging(context_type)
trailing_arguments = Expr(:call, GlobalRef(Cassette, :_tagged_new_tuple_unsafe), overdub_ctx_slot)
else
trailing_arguments = Expr(:call, GlobalRef(Core, :tuple))
end
for i in n_method_args:n_actual_args
push!(overdubbed_code, Expr(:call, GlobalRef(Core, :getfield), overdub_args_slot, offset - 1))
push!(overdubbed_codelocs, code_info.codelocs[1])
push!(trailing_arguments.args, SSAValue(length(overdubbed_code)))
offset += 1
end
push!(overdubbed_code, Expr(:(=), SlotNumber(n_method_args + n_prepended_slots), trailing_arguments))
push!(overdubbed_codelocs, code_info.codelocs[1])
end
#=== finish initialization of `overdubbed_code`/`overdubbed_codelocs` ===#
# substitute static parameters, offset slot numbers by number of added slots, and
# offset statement indices by the number of additional statements
Base.Meta.partially_inline!(code_info.code, Any[], method.sig, static_params,
n_prepended_slots, length(overdubbed_code), :propagate)
original_code_start_index = length(overdubbed_code) + 1
append!(overdubbed_code, code_info.code)
append!(overdubbed_codelocs, code_info.codelocs)
#=== perform tagged module transformation if tagging is enabled ===#
if istaggingenabled && !iskwfunc
# find `GlobalRef`s in IR and set up tagged module replacements
modules = Any[]
original_code_region = view(overdubbed_code, original_code_start_index:length(overdubbed_code))
replace_match!(x -> isa(x, GlobalRef), original_code_region) do x
x.mod === Core && in(x.name, (:tuple, :_apply)) && return x
m = GlobalRef(parentmodule(x.mod), nameof(x.mod))
i = findfirst(isequal(m), modules)
if isa(i, Nothing)
push!(modules, m)
i = length(modules)
end
return Expr(:replaceglobalref, original_code_start_index + i - 1, x)
end
for i in 1:length(modules)
modules[i] = Expr(:call, Expr(:nooverdub, GlobalRef(Cassette, :fetch_tagged_module)), overdub_ctx_slot, modules[i])
end
# insert `fetch_tagged_module`s at the `original_code_start_index`
insert_statements!(overdubbed_code, overdubbed_codelocs,
(x, i) -> i == original_code_start_index ? length(modules) + 1 : nothing,
(x, i) -> [modules..., x])
# append `tagged_globalref_set_meta!` to `GlobalRef() = ...` statements
insert_statements!(overdubbed_code, overdubbed_codelocs,
(x, i) -> begin
if (i > original_code_start_index &&
Base.Meta.isexpr(x, :(=)) &&
Base.Meta.isexpr(x.args[1], :replaceglobalref))
return 3
end
return nothing
end,
(x, i) -> begin
lhs, rhs = x.args
tagmodssa = SSAValue(lhs.args[1])
globalref = lhs.args[2]
name = QuoteNode(globalref.name)
return [
rhs,
Expr(:(=), globalref, Expr(:call, Expr(:nooverdub, GlobalRef(Cassette, :untag)), SSAValue(i), overdub_ctx_slot)),
Expr(:call, Expr(:nooverdub, GlobalRef(Cassette, :tagged_globalref_set_meta!)), overdub_ctx_slot, tagmodssa, name, SSAValue(i))
]
end)
# replace `GlobalRef`-loads with `Cassette.tagged_globalref`
original_code_start_index += length(modules)
insert_statements!(overdubbed_code, overdubbed_codelocs,
(x, i) -> begin
i >= original_code_start_index || return nothing
stmt = Base.Meta.isexpr(x, :(=)) ? x.args[2] : x
Base.Meta.isexpr(stmt, :replaceglobalref) && return 1
if isa(stmt, Expr)
count = 0
for arg in stmt.args
if Base.Meta.isexpr(arg, :replaceglobalref)
count += 1
end
end
count > 0 && return count + 1
end
return nothing
end,
(x, i) -> begin
items = Any[]
stmt = Base.Meta.isexpr(x, :(=)) ? x.args[2] : x
if Base.Meta.isexpr(stmt, :replaceglobalref)
tagmodssa = SSAValue(stmt.args[1])
globalref = stmt.args[2]
name = QuoteNode(globalref.name)
result = Expr(:call, Expr(:nooverdub, GlobalRef(Cassette, :tagged_globalref)), overdub_ctx_slot, tagmodssa, name, globalref)
elseif isa(stmt, Expr)
result = Expr(stmt.head)
for arg in stmt.args
if Base.Meta.isexpr(arg, :replaceglobalref)
tagmodssa = SSAValue(arg.args[1])
globalref = arg.args[2]
name = QuoteNode(globalref.name)
push!(result.args, SSAValue(i + length(items)))
push!(items, Expr(:call, Expr(:nooverdub, GlobalRef(Cassette, :tagged_globalref)), overdub_ctx_slot, tagmodssa, name, globalref))
else
push!(result.args, arg)
end
end
end
if Base.Meta.isexpr(x, :(=))
result = Expr(:(=), x.args[1], result)
end
push!(items, result)
return items
end)
end
#=== untag all `foreigncall` SSAValue/SlotNumber arguments if tagging is enabled ===#
if istaggingenabled && !iskwfunc
insert_statements!(overdubbed_code, overdubbed_codelocs,
(x, i) -> begin
stmt = Base.Meta.isexpr(x, :(=)) ? x.args[2] : x
if Base.Meta.isexpr(stmt, :foreigncall)
count = 0
for arg in stmt.args
if isa(arg, SSAValue) || isa(arg, SlotNumber)
count += 1
end
end
count > 0 && return count + 1
end
return nothing
end,
(x, i) -> begin
items = Any[]
stmt = Base.Meta.isexpr(x, :(=)) ? x.args[2] : x
result = Expr(:foreigncall)
for arg in stmt.args
if isa(arg, SSAValue) || isa(arg, SlotNumber)
push!(result.args, SSAValue(i + length(items)))
push!(items, Expr(:call, Expr(:nooverdub, GlobalRef(Cassette, :untag)), arg, overdub_ctx_slot))
else
push!(result.args, arg)
end
end
if Base.Meta.isexpr(x, :(=))
result = Expr(:(=), x.args[1], result)
end
push!(items, result)
return items
end)
end
#=== untag `gotoifnot` conditionals if tagging is enabled ===#
if istaggingenabled && !iskwfunc
@static if isdefined(Core, :GotoIfNot)
insert_statements!(overdubbed_code, overdubbed_codelocs,
(x, i) -> isa(x, Core.GotoIfNot) ? 2 : nothing,
(x, i) -> [
Expr(:call, Expr(:nooverdub, GlobalRef(Cassette, :untag)), x.cond, overdub_ctx_slot),
Core.GotoIfNot(SSAValue(i), x.dest)
])
else
insert_statements!(overdubbed_code, overdubbed_codelocs,
(x, i) -> Base.Meta.isexpr(x, :gotoifnot) ? 2 : nothing,
(x, i) -> [
Expr(:call, Expr(:nooverdub, GlobalRef(Cassette, :untag)), x.args[1], overdub_ctx_slot),
Expr(:gotoifnot, SSAValue(i), x.args[2])
])
end
end
#=== replace `Expr(:new, ...)`/`Expr(:splatnew, ...)` with ===#
#=== `Expr(:call, :tagged_new)`/`Expr(:call, :tagged_splatnew)` if tagging is enabled ===#
if istaggingenabled && !iskwfunc
replace_match!(x -> Base.Meta.isexpr(x, :new) || Base.Meta.isexpr(x, :splatnew), overdubbed_code) do x
tagged_version = x.head == :new ? :tagged_new : :tagged_splatnew
return Expr(:call, Expr(:nooverdub, GlobalRef(Cassette, tagged_version)), overdub_ctx_slot, x.args...)
end
end
#=== replace `Expr(:call, ...)` with `Expr(:call, :overdub, ...)` calls ===#
if iskwfunc
# Another assumption of this `iskwfunc` hack is that the second to last statement in
# the lowered IR for `Core.kwfunc(f)` is the call to the "underlying" non-kwargs form
# of `f`. Thus, we `recurse` that call instead of replacing it with `call`.
for i in 1:length(overdubbed_code)
stmt = overdubbed_code[i]
replacewith = i === (length(overdubbed_code) - 1) ? :recurse : :call
if Base.Meta.isexpr(stmt, :(=))
replacein = stmt.args
replaceat = 2
else
replacein = overdubbed_code
replaceat = i
end
stmt = replacein[replaceat]
if Base.Meta.isexpr(stmt, :call)
replacein[replaceat] = Expr(:call, GlobalRef(Cassette, replacewith), overdub_ctx_slot, stmt.args...)
end
end
else
arehooksenabled = hashooks(context_type)
stmtcount = (x, i) -> begin
i >= original_code_start_index || return nothing
isassign = Base.Meta.isexpr(x, :(=))
stmt = isassign ? x.args[2] : x
if Base.Meta.isexpr(stmt, :call) && !(Base.Meta.isexpr(stmt.args[1], :nooverdub))
isapplycall = is_ir_element(stmt.args[1], GlobalRef(Core, :_apply), overdubbed_code)
isapplyiteratecall = is_ir_element(stmt.args[1], GlobalRef(Core, :_apply_iterate), overdubbed_code)
if isapplycall
if arehooksenabled
return 7
else
return 2 + isassign
end
elseif isapplyiteratecall
if arehooksenabled
return 8
else
return 3 + isassign
end
elseif arehooksenabled
return 4
else
return 1 + isassign
end
end
return nothing
end
newstmts = (x, i) -> begin
callstmt = Base.Meta.isexpr(x, :(=)) ? x.args[2] : x
isapplycall = is_ir_element(callstmt.args[1], GlobalRef(Core, :_apply), overdubbed_code)
isapplyiteratecall = is_ir_element(callstmt.args[1], GlobalRef(Core, :_apply_iterate), overdubbed_code)
if isapplycall
if arehooksenabled
callf = callstmt.args[2]
callargs = callstmt.args[3:end]
stmts = Any[
Expr(:call, GlobalRef(Core, :tuple), overdub_ctx_slot),
Expr(:call, GlobalRef(Core, :tuple), callf),
Expr(:call, GlobalRef(Core, :_apply), GlobalRef(Cassette, :prehook), SSAValue(i), SSAValue(i + 1), callargs...),
Expr(:call, GlobalRef(Core, :_apply), GlobalRef(Cassette, :overdub), SSAValue(i), SSAValue(i + 1), callargs...),
Expr(:call, GlobalRef(Core, :tuple), SSAValue(i + 3)),
Expr(:call, GlobalRef(Core, :_apply), GlobalRef(Cassette, :posthook), SSAValue(i), SSAValue(i + 4), SSAValue(i + 1), callargs...),
Base.Meta.isexpr(x, :(=)) ? Expr(:(=), x.args[1], SSAValue(i + 3)) : SSAValue(i + 3)
]
else
callf = callstmt.args[2]
callargs = callstmt.args[3:end]
stmts = Any[
Expr(:call, GlobalRef(Core, :tuple), overdub_ctx_slot, callf),
Expr(:call, GlobalRef(Core, :_apply), GlobalRef(Cassette, :overdub), SSAValue(i), callargs...),
]
Base.Meta.isexpr(x, :(=)) && push!(stmts, Expr(:(=), x.args[1], SSAValue(i + 1)))
end
elseif isapplyiteratecall
if arehooksenabled
iterf = callstmt.args[2]
callf = callstmt.args[3]
callargs = callstmt.args[4:end]
stmts = Any[
Expr(:call, GlobalRef(Core, :tuple), overdub_ctx_slot),
Expr(:call, GlobalRef(Core, :tuple), callf),
# XXX: Overdubbing the iterate function breaks things
nothing, # Expr(:call, GlobalRef(Cassette, :overdubbed_iterate), SSAValue(i), iterf),
Expr(:call, GlobalRef(Core, :_apply), GlobalRef(Cassette, :prehook), SSAValue(i), SSAValue(i + 1), callargs...),
Expr(:call, GlobalRef(Core, :_apply_iterate), iterf, GlobalRef(Cassette, :overdub), SSAValue(i), SSAValue(i+1), callargs...),
Expr(:call, GlobalRef(Core, :tuple), SSAValue(i + 4)),
Expr(:call, GlobalRef(Core, :_apply), GlobalRef(Cassette, :posthook), SSAValue(i), SSAValue(i + 5), SSAValue(i + 1), callargs...),
Base.Meta.isexpr(x, :(=)) ? Expr(:(=), x.args[1], SSAValue(i + 4)) : SSAValue(i + 4)
]
else
iterf = callstmt.args[2]
callf = callstmt.args[3]
callargs = callstmt.args[4:end]
stmts = Any[
# XXX: Overdubbing the iterate function breaks things
nothing, # Expr(:call, GlobalRef(Cassette, :overdubbed_iterate), overdub_ctx_slot, iterf),
Expr(:call, GlobalRef(Core, :tuple), overdub_ctx_slot, callf),
Expr(:call, GlobalRef(Core, :_apply_iterate), iterf, GlobalRef(Cassette, :overdub), SSAValue(i+1), callargs...),
]
Base.Meta.isexpr(x, :(=)) && push!(stmts, Expr(:(=), x.args[1], SSAValue(i+2)))
end
elseif arehooksenabled
stmts = Any[
Expr(:call, GlobalRef(Cassette, :prehook), overdub_ctx_slot, callstmt.args...),
Expr(:call, GlobalRef(Cassette, :overdub), overdub_ctx_slot, callstmt.args...),
Expr(:call, GlobalRef(Cassette, :posthook), overdub_ctx_slot, SSAValue(i + 1), callstmt.args...),
Base.Meta.isexpr(x, :(=)) ? Expr(:(=), x.args[1], SSAValue(i + 1)) : SSAValue(i + 1)
]
else
stmts = Any[
Expr(:call, GlobalRef(Cassette, :overdub), overdub_ctx_slot, callstmt.args...),
]
Base.Meta.isexpr(x, :(=)) && push!(stmts, Expr(:(=), x.args[1], SSAValue(i)))
end
return stmts
end
insert_statements!(overdubbed_code, overdubbed_codelocs, stmtcount, newstmts)
end
#=== unwrap all `Expr(:nooverdub)`s ===#
replace_match!(x -> x.args[1], x -> Base.Meta.isexpr(x, :nooverdub), overdubbed_code)
#=== replace all `Expr(:contextslot)`s ===#
replace_match!(x -> overdub_ctx_slot, x -> Base.Meta.isexpr(x, :contextslot), overdubbed_code)
#=== set `code_info`/`reflection` fields accordingly ===#
if code_info.method_for_inference_limit_heuristics === nothing
code_info.method_for_inference_limit_heuristics = method
end
code_info.code = overdubbed_code
code_info.codelocs = overdubbed_codelocs
code_info.ssavaluetypes = length(overdubbed_code)
code_info.ssaflags = [0x00 for _ in 1:length(overdubbed_code)] # XXX we need to copy flags that are set for the original code
reflection.code_info = code_info
return reflection
end
@eval _overdub_fallback($OVERDUB_CONTEXT_NAME, $OVERDUB_ARGUMENTS_NAME...) = fallback($OVERDUB_CONTEXT_NAME, $OVERDUB_ARGUMENTS_NAME...)
const OVERDUB_FALLBACK = begin
code_info = reflect((typeof(_overdub_fallback), Any, Vararg{Any})).code_info
code_info.inlineable = true
code_info
end
# `args` is `(typeof(original_function), map(typeof, original_args_tuple)...)`
function __overdub_generator__(world::UInt, source, self, context_type, args)
if nfields(args) > 0
is_builtin = args[1] <: Core.Builtin
is_invoke = args[1] === typeof(Core.invoke)
if !is_builtin || is_invoke
try
untagged_args = ntuple(i->untagtype(args[i], context_type), nfields(args))
reflection = reflect(untagged_args, world)
if isa(reflection, Reflection)
result = overdub_pass!(reflection, context_type, is_invoke)
isa(result, Expr) && return result
return reflection.code_info
end
catch err
errmsg = "ERROR COMPILING $args IN CONTEXT $(context_type): \n" #* sprint(showerror, err)
errmsg *= "\n" .* repr("text/plain", stacktrace(catch_backtrace()))
return quote
error($errmsg)
end
end
end
end
return copy_code_info(OVERDUB_FALLBACK)
end
function __overdub_generator__(self, context_type, args)
if nfields(args) > 0
is_builtin = args[1] <: Core.Builtin
is_invoke = args[1] === typeof(Core.invoke)
if !is_builtin || is_invoke
try
untagged_args = ntuple(i->untagtype(args[i], context_type), nfields(args))
reflection = reflect(untagged_args)
if isa(reflection, Reflection)
result = overdub_pass!(reflection, context_type, is_invoke)
isa(result, Expr) && return result
return reflection.code_info
end
catch err
errmsg = "ERROR COMPILING $args IN CONTEXT $(context_type): \n" * sprint(showerror, err)
errmsg *= "\n" .* repr("text/plain", stacktrace(catch_backtrace()))
return quote
error($errmsg)
end
end
end
end
return copy_code_info(OVERDUB_FALLBACK)
end
function overdub end
function recurse end
@inline recurse(ctx::Context, ::typeof(Core._apply), f, args...) = Core._apply(recurse, (ctx, f), args...)
if VERSION >= v"1.4.0-DEV.304"
@inline function Cassette.recurse(ctx::Context, ::typeof(Core._apply_iterate), iter, f, args...)
# XXX: Overdubbing the iterate function breaks things
# overdubbed_iter = (args...) -> Cassette.recurse(ctx, iter, args...)
Core._apply_iterate(iter, recurse, (ctx, f), args...)
end
end
let line = @__LINE__, file = @__FILE__
@static if VERSION >= v"1.10.0-DEV.873"
@eval (@__MODULE__) begin
function $Cassette.overdub($OVERDUB_CONTEXT_NAME::$Cassette.Context, $OVERDUB_ARGUMENTS_NAME...)
$(Expr(:meta, :generated_only))
$(Expr(:meta, :generated, __overdub_generator__))
end
function $Cassette.recurse($OVERDUB_CONTEXT_NAME::$Cassette.Context, $OVERDUB_ARGUMENTS_NAME...)
$(Expr(:meta, :generated_only))
$(Expr(:meta, :generated, __overdub_generator__))
end
end
else
@eval (@__MODULE__) begin
function $Cassette.overdub($OVERDUB_CONTEXT_NAME::$Cassette.Context, $OVERDUB_ARGUMENTS_NAME...)
$(Expr(:meta, :generated_only))
$(Expr(:meta,
:generated,
Expr(:new,
Core.GeneratedFunctionStub,
:__overdub_generator__,
Any[:overdub, OVERDUB_CONTEXT_NAME, OVERDUB_ARGUMENTS_NAME],
Any[],
line,
QuoteNode(Symbol(file)),
true)))
end
function $Cassette.recurse($OVERDUB_CONTEXT_NAME::$Cassette.Context, $OVERDUB_ARGUMENTS_NAME...)
$(Expr(:meta, :generated_only))
$(Expr(:meta,
:generated,
Expr(:new,
Core.GeneratedFunctionStub,
:__overdub_generator__,
Any[:recurse, OVERDUB_CONTEXT_NAME, OVERDUB_ARGUMENTS_NAME],
Any[],
line,
QuoteNode(Symbol(file)),
true)))
end
end
end
end
@doc """
```
overdub(context::Context, f, args...)
```
Execute `f(args...)` overdubbed with respect to `context`.
More specifically, execute `f(args...)`, but with every internal method invocation `g(x...)`
replaced by statements similar to the following:
```
begin
prehook(context, g, x...)
overdub(context, g, x...) # %n
posthook(context, %n, g, x...)
%n
end
```
Otherwise, if Cassette cannot retrieve lowered IR for the method body of `f(args...)`,
then `fallback(context, f, args...)` will be called instead. Cassette's [`canrecurse`](@ref)
function is a useful utility for checking if this will occur.
If the injected `prehook`/`posthook` statements are not needed for your use
case, you can disable their injection via the [`disablehooks`](@ref) function.
Additionally, for every method body encountered in the execution trace, apply the compiler pass
associated with `context` if one exists. Note that this user-provided pass is performed on
the method IR before method invocations are transformed into the form specified above. See
the [`@pass`](@ref) macro for further details.
If `Cassette.hastagging(typeof(context))`, then a number of additional passes are run in
order to accomodate tagged value propagation:
- `Expr(:new)` is replaced with a call to `Cassette.tagged_new`
- `Expr(:splatnew)` is replaced with a call to `Cassette.tagged_splatnew`
- conditional values passed to `Expr(:gotoifnot)` are untagged
- arguments to `Expr(:foreigncall)` are untagged
- load/stores to external module bindings are intercepted by the tagging system
The default definition of `overdub` is to recursively enter the given function
and continue overdubbing, but one can interrupt/redirect this recursion by
overloading `overdub` w.r.t. a given context and/or method signature to define
new contextual execution primitives. For example:
```
julia> using Cassette
julia> Cassette.@context Ctx;
julia> Cassette.overdub(::Ctx, ::typeof(sin), x) = cos(x)
julia> Cassette.overdub(Ctx(), x -> sin(x) + cos(x), 1) == 2 * cos(1)
true
```
See also: [`recurse`](@ref), [`prehook`](@ref), [`posthook`](@ref)
"""
overdub
@doc """
```
recurse(context::Context, f, args...)
```
Execute `f(args...)` overdubbed with respect to `context`.
This method performs exactly the same transformation as the default
[`overdub`](@ref) transformation, but is not meant to be overloaded. Thus, one
can call `recurse` to "continue" recursively overdubbing a function when calling
`overdub` directly on that function might've dispatched to a contextual
primitive.
To illustrate why `recurse` might be useful, consider the following example
which utilizes `recurse` as part of a Cassette-based memoization implementation
for the classic Fibonacci function:
```
using Cassette: Cassette, @context, overdub, recurse
fib(x) = x < 3 ? 1 : fib(x - 2) + fib(x - 1)
fibtest(n) = fib(2 * n) + n
@context MemoizeCtx
function Cassette.overdub(ctx::MemoizeCtx, ::typeof(fib), x)
result = get(ctx.metadata, x, 0)
if result === 0
result = recurse(ctx, fib, x)
ctx.metadata[x] = result
end
return result
end
```
See Cassette's Contextual Dispatch documentation for more details and examples.
"""
recurse
"""
```
Cassette.@overdub(ctx, expression)
```
A convenience macro for executing `expression` within the context `ctx`. This
macro roughly expands to `Cassette.recurse(ctx, () -> expression)`.
See also: [`overdub`](@ref), [`recurse`](@ref)
"""
macro overdub(ctx, expr)
return :(recurse($(esc(ctx)), () -> $(esc(expr))))
end
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 7251 | #########
# @pass #
#########
"""
```
Cassette.@pass transform
```
Return a Cassette pass that can be provided to the `Context` constructor's `pass` keyword
argument in order to apply `transform` to the lowered IR representations of all methods
invoked during contextual execution.
`transform` must be a Julia object that is callable with the following signature:
```
transform(::Type{<:Context}, ::Cassette.Reflection)::Union{Expr,CodeInfo}
```
If `isa(transform(...), Expr)`, then the returned `Expr` will be emitted immediately
without any additional processing. Otherwise, if `isa(transform(...), CodeInfo)`, then
the returned `CodeInfo` will undergo the rest of Cassette's overdubbing transformation
before being emitted from the `overdub` generator.
Two special `Expr` heads are available to Cassette pass authors that are not normally valid
in Julia IR. `Expr`s with these heads can be used to interact with the downstream built-in
Cassette passes that consume them.
- `:nooverdub`: Wrap an `Expr` with this head value around the first argument in an
`Expr(:call)` to tell downstream built-in Cassette passes not to overdub that call. For
example, `Expr(:call, Expr(:nooverdub, GlobalRef(MyModule, :myfunc)), args...)`.
- `:contextslot`: Cassette will replace any `Expr(:contextslot)` with the actual `SlotNumber`
corresponding to the context object associated with the execution trace. For example, one
could construct an IR element that accesses the context's `metadata` field by emitting:
`Expr(:call, Expr(:nooverdub, GlobalRef(Core, :getfield)), Expr(:contextslot), QuoteNode(:metadata))`
Cassette provides a few IR-munging utility functions of interest to pass authors; for details,
see [`insert_statements!`](@ref), [`replace_match!`](@ref), and [`is_ir_element`](@ref).
Note that the `@pass` macro expands to an `eval` call and thus should only be called at
top-level. Furthermore, to avoid world-age issues, `transform` should not be overloaded after
it has been registered with `@pass`.
Note also that `transform` should be "relatively pure." More specifically, Julia's compiler
has license to apply `transform` multiple times, even if only compiling a single method
invocation once. Thus, it is required that `transform` always return a generally "equivalent"
`CodeInfo` for a given context, method body, and signature. If your `transform`
implementation is not naturally "pure" in this sense, then it is still possible to guarantee
this property by memoizing your implementation (i.e. maintaining a cache of previously
computed IR results, instead of recomputing results every time).
See also: [`Context`](@ref), [`overdub`](@ref)
"""
macro pass(transform)
Pass = gensym("PassType")
line = Expr(:quote, __source__.line)
file = Expr(:quote, __source__.file)
return esc(quote
struct $Pass <: $Cassette.AbstractPass end
(::Type{$Pass})(ctxtype, reflection) = $transform(ctxtype, reflection)
$Pass()
end)
end
#############
# utilities #
#############
"""
```
replace_match!(replace, ismatch, x)
```
Return `x` with all subelements `y` replaced with `replace(y)` if `ismatch(y)`. If
`!ismatch(y)`, but `y` is of type `Expr`, `Array`, or `SubArray`, then replace `y`
in `x` with `replace_match!(replace, ismatch, y)`.
Generally, `x` should be of type `Expr`, `Array`, or `SubArray`.
Note that this function modifies `x` (and potentially its subelements) in-place.
See also: [`insert_statements!`](@ref), [`is_ir_element`](@ref)
"""
function replace_match!(replace, ismatch, x)
if ismatch(x)
return replace(x)
elseif isa(x, Array) || isa(x, SubArray)
for i in eachindex(x)
x[i] = replace_match!(replace, ismatch, x[i])
end
elseif isa(x, Expr)
replace_match!(replace, ismatch, x.args)
end
return x
end
"""
```
insert_statements!(code::Vector, codelocs::Vector, stmtcount, newstmts)
```
For every statement `stmt` at position `i` in `code` for which `stmtcount(stmt, i)` returns
an `Int`, remove `stmt`, and in its place, insert the statements returned by
`newstmts(stmt, i)`. If `stmtcount(stmt, i)` returns `nothing`, leave `stmt` alone.
For every insertion, all downstream `SSAValue`s, label indices, etc. are incremented
appropriately according to number of inserted statements.
Proper usage of this function dictates that following properties hold true:
- `code` is expected to be a valid value for the `code` field of a `CodeInfo` object.
- `codelocs` is expected to be a valid value for the `codelocs` field of a `CodeInfo` object.
- `newstmts(stmt, i)` should return a `Vector` of valid IR statements.
- `stmtcount` and `newstmts` must obey `stmtcount(stmt, i) == length(newstmts(stmt, i))` if
`isa(stmtcount(stmt, i), Int)`.
To gain a mental model for this function's behavior, consider the following scenario. Let's
say our `code` object contains several statements:
```
code = Any[oldstmt1, oldstmt2, oldstmt3, oldstmt4, oldstmt5, oldstmt6]
codelocs = Int[1, 2, 3, 4, 5, 6]
```
Let's also say that for our `stmtcount` returns `2` for `stmtcount(oldstmt2, 2)`, returns `3`
for `stmtcount(oldstmt5, 5)`, and returns `nothing` for all other inputs. From this setup, we
can think of `code`/`codelocs` being modified in the following manner:
```
newstmts2 = newstmts(oldstmt2, 2)
newstmts5 = newstmts(oldstmt5, 5)
code = Any[oldstmt1,
newstmts2[1], newstmts2[2],
oldstmt3, oldstmt4,
newstmts5[1], newstmts5[2], newstmts5[3],
oldstmt6]
codelocs = Int[1, 2, 2, 3, 4, 5, 5, 5, 6]
```
See also: [`replace_match!`](@ref), [`is_ir_element`](@ref)
"""
function insert_statements!(code, codelocs, stmtcount, newstmts)
ssachangemap = fill(0, length(code))
labelchangemap = fill(0, length(code))
worklist = Tuple{Int,Int}[]
for i in 1:length(code)
stmt = code[i]
nstmts = stmtcount(stmt, i)
if nstmts !== nothing
addedstmts = nstmts - 1
push!(worklist, (i, addedstmts))
ssachangemap[i] = addedstmts
if i < length(code)
labelchangemap[i + 1] = addedstmts
end
end
end
Core.Compiler.renumber_ir_elements!(code, ssachangemap, labelchangemap)
for (i, addedstmts) in worklist
i += ssachangemap[i] - addedstmts # correct the index for accumulated offsets
stmts = newstmts(code[i], i)
@assert length(stmts) == (addedstmts + 1)
code[i] = stmts[end]
for j in 1:(length(stmts) - 1) # insert in reverse to maintain the provided ordering
insert!(code, i, stmts[end - j])
insert!(codelocs, i, codelocs[i])
end
end
end
"""
```
is_ir_element(x, y, code::Vector)
```
Return `true` if `x === y` or if `x` is an `SSAValue` such that
`is_ir_element(code[x.id], y, code)` is `true`.
See also: [`replace_match!`](@ref), [`insert_statements!`](@ref)
"""
function is_ir_element(x, y, code::Vector)
result = false
while true # break by default
if x === y #
result = true
break
elseif isa(x, SSAValue)
x = code[x.id]
else
break
end
end
return result
end
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 28262 | ##################
# `FieldStorage` #
##################
abstract type FieldStorage{D} end
#=== `Mutable` ===#
mutable struct Mutable{D} <: FieldStorage{D}
data::D
Mutable{D}() where D = new{D}()
Mutable{D}(data) where D = new{D}(data)
end
load(x::Mutable) = x.data
store!(x::Mutable, y) = (x.data = y)
#=== `Immutable` ===#
struct Immutable{D} <: FieldStorage{D}
data::D
Immutable{D}(data) where D = new{D}(data)
end
load(x::Immutable) = x.data
store!(x::Immutable, y) = error("cannot mutate immutable field")
##########
# `Meta` #
##########
struct NoMetaData end
struct NoMetaMeta end
_metadataconvert(T, x::NoMetaData) = x
_metadataconvert(T, x) = convert(T, x)
_metametaconvert(T, x::NoMetaMeta) = x
_metametaconvert(T, x) = convert(T, x)
struct Meta{D,M#=<:Union{Tuple,NamedTuple,Array,ModuleMeta}=#}
data::Union{D,NoMetaData}
meta::Union{M,NoMetaMeta}
Meta(data::D, meta::M) where {D,M} = Meta{D,M}(data, meta)
Meta{D,M}(data, meta) where {D,M} = new{D,M}(_metadataconvert(D, data), _metametaconvert(M, meta))
end
const NOMETA = Meta(NoMetaData(), NoMetaMeta())
# These defined to allow conversion of `Meta{NoMetaData,NoMetaMeta}`
# into whatever metatype is expected by a container.
Base.convert(::Type{M}, meta::M) where {M<:Meta} = meta
function Base.convert(::Type{Meta{D,M}}, meta::Meta) where {D,M}
metadata = _metadataconvert(D, meta.data)
metameta = _metametaconvert(M, meta.meta)
return Meta{D,M}(metadata, metameta)
end
################
# `ModuleMeta` #
################
# note that `BindingMeta` was defined earlier in src/context.jl
struct ModuleMeta{D,M}
name::Meta{D,M}
bindings::BindingMetaDict
end
Base.convert(::Type{M}, meta::M) where {M<:ModuleMeta} = meta
function Base.convert(::Type{ModuleMeta{D,M}}, meta::ModuleMeta) where {D,M}
return ModuleMeta(convert(Meta{D,M}, meta.name), meta.bindings)
end
# TODO: For fast methods (~ns), this fetch can cost drastically more than the primal method
# invocation. We easily have the module at compile time, but we don't have access to the
# actual context object (just the type). This `@pure` is vtjnash-approved. It should allow
# the compiler to optimize away the fetch once we have support for it, e.g. loop invariant
# code motion.
Base.@pure @noinline function fetch_tagged_module(context::Context, m::Module)
return Tagged(context, m, Meta(NoMetaData(), fetch_modulemeta(context, m)))
end
Base.@pure @noinline function fetch_modulemeta(context::Context, m::Module)
if haskey(context.bindingscache, m)
bindings = context.bindingscache[m]
else
bindings = Cassette.BindingMetaDict()
context.bindingscache[m] = bindings
end
return ModuleMeta(NOMETA, bindings::BindingMetaDict)
end
Base.@pure @noinline function _fetch_bindingmeta!(context::Context,
m::Module,
bindings::BindingMetaDict,
name::Symbol)
return get!(bindings, name) do
bindingmeta = BindingMeta()
# If `!(isdefined(m, name))`, there must be a context-observable assigment to
# the primal binding before we can access it again. This is okay because a) it's
# obvious that the primal program can't access bindings without defining them,
# and b) we already don't allow non-context-observable assignments that could
# invalidate the context's metadata.
if isdefined(m, name)
bindingmeta.data = initmeta(context, getfield(m, name), NoMetaData())
end
return bindingmeta
end
end
function fetch_bindingmeta!(context::Context,
m::Module,
bindings::BindingMetaDict,
name::Symbol,
primal)
M = metatype(typeof(context), typeof(primal))
return convert(M, _fetch_bindingmeta!(context, m, bindings, name).data)::M
end
############################
# `metatype` specification #
############################
#=
The optimal metatype specification for a given non-leaftype is the union of the metatypes of
its subtypes, and thus can be implemented as:
```
function metatype(::Type{C}, ::Type{T}) where {C,T}
if isconcretetype(T)
return Meta{metadatatype(C, T),metametatype(C, T)}
else
return Union{map(X -> metatype(C, X), subtypes(T))...}
end
end
```
However, this is an expensive implementation of this operation. Thus, our actual `metatype`
implementation returns a still-correct, but extremely pessimistic metatype with the
benefit that metatype computation is very fast. If, in the future, `metatype` is
parameterized on world age, then we can call `subtypes` at compile time, and compute a more
optimally bounded metatype.
=#
function metatype(::Type{C}, ::Type{T}) where {C<:Context,T}
if isconcretetype(T) || T <: Type
return Meta{metadatatype(C, T),metametatype(C, T)}
end
return Meta
end
function _fieldtypes_for_metatype(T::Type)
ftypes = Any[]
for i in 1:fieldcount(T)
# TODO improve recursion detection; this only spots 1-degree cycles right now
ftype = fieldtype(T, i)
ftype = ftype === T ? Any : ftype
push!(ftypes, ftype)
end
return ftypes
end
doesnotneedmetatype(::Type{T}) where {T} = isbitstype(T)
doesnotneedmetatype(::Type{Symbol}) = true
doesnotneedmetatype(::Type{<:Type}) = true
doesnotneedmeta(x) = isbits(x)
doesnotneedmeta(::Symbol) = true
doesnotneedmeta(::Type) = true
#=== metadatatype ===#
"""
```
metadatatype(::Type{<:Context}, ::Type{T})
```
Overload this Cassette method w.r.t. a given context to define the type of metadata that
can be tagged to values of type `T` within that context.
By default, this method is set such that associating metadata with any tagged value is
disallowed.
Cassette uses `metadatatype` to statically compute a context-specific metadata type hiearchy
for all tagged values within overdubbed programs. To gain a mental model for this mechanism,
consider a simple struct definition as follows:
```
struct Foo
x::Int
y::Complex{Int}
end
```
Now, Cassette can use `metadatatype` to determine type constraints for metadata structures
associated with tagged values of type `Foo`. In psuedo-Julia-code, these metadata structures
might look something like the following for `Foo`:
```
struct IntMeta
data::metadatatype(Ctx, Int)
meta::Cassette.NoMetaMeta
end
struct ComplexIntMeta
data::metadatatype(Ctx, Complex{Int})
meta::NamedTuple{(:re,:im),Tuple{IntMeta,IntMeta}}
end
struct FooMeta
data::metadatatype(Ctx, Foo)
meta::NamedTuple{(:x,:y),Tuple{IntMeta,ComplexIntMeta}
end
```
# Examples
```
julia> Cassette.@context Ctx;
# any value of type `Number` can now be tagged with metadata of type `Number`
julia> Cassette.metadatatype(::Type{<:Ctx}, ::Type{<:Number}) = Number
# any value of type `T<:Number` can now be tagged with metadata of type `T`
julia> Cassette.metadatatype(::Type{<:Ctx}, ::Type{T}) where {T<:Number} = T
# any value of type `T<:Number` can now be tagged with metadata of type `promote_type(T, M)`
# where `M` is the type of the trace-local metadata associated with the context
julia> Cassette.metadatatype(::Type{<:Ctx{M}}, ::Type{T}) where {M<:Number,T<:Number} = promote_type(T, M)
```
"""
metadatatype(::Type{<:Context}, ::DataType) = NoMetaData
#=== metametatype ===#
@static if isdefined(Base, :ismutabletype)
using Base: ismutabletype
else
function ismutabletype(@nospecialize(t::Type))
t = Base.unwrap_unionall(t)
return isa(t, DataType) && t.mutable
end
end
@generated function metametatype(::Type{C}, ::Type{T}) where {C<:Context,T}
if T <: Type || fieldcount(T) == 0
body = :(NoMetaMeta)
elseif !(isconcretetype(T))
body = :(error("cannot call metametatype on non-concrete type ", $T))
else
F = ismutabletype(T) ? :Mutable : :Immutable
ftypes = [:($F{metatype(C, $S)}) for S in _fieldtypes_for_metatype(T)]
tuplemetatype = :(Tuple{$(ftypes...)})
if T <: Tuple
body = tuplemetatype
else
fnames = Expr(:tuple, map(Base.Meta.quot, fieldnames(T))...)
body = :(NamedTuple{$fnames,$tuplemetatype})
end
end
return quote
$body
end
end
@generated function metametatype(::Type{C}, ::Type{T}) where {C<:Context,T<:Array}
return :(Array{metatype(C, $(eltype(T))),$(ndims(T))})
end
function metametatype(::Type{C}, ::Type{Module}) where {C<:Context}
return ModuleMeta{metadatatype(C, Symbol), metametatype(C, Symbol)}
end
#=== initmetameta ===#
function _metametaexpr(::Type{C}, ::Type{V}, metaexprs::Vector) where {C,V}
if V <: Type || fieldcount(V) == 0 || (all(x == :NOMETA for x in metaexprs) && doesnotneedmetatype(V))
return :(NoMetaMeta())
else
F = ismutabletype(V) ? :Mutable : :Immutable
metatypes = [:(metatype(C, $S)) for S in _fieldtypes_for_metatype(V)]
metaconverts = [:(convert($(metatypes[i]), $(metaexprs[i]))) for i in 1:fieldcount(V)]
metametafields = [:($F{$(metatypes[i])}($(metaconverts[i]))) for i in 1:fieldcount(V)]
if !(V <: Tuple)
fnames = fieldnames(V)
for i in 1:fieldcount(V)
metametafields[i] = :($(fnames[i]) = $(metametafields[i]))
end
end
return Expr(:tuple, metametafields...)
end
end
initmetameta(context::Context, value::Module) = fetch_modulemeta(context, value)
function initmetameta(context::C, value::Array{V}) where {C<:Context,V}
M = metatype(C, V)
if M <: typeof(NOMETA)
return NoMetaMeta()
else
return fill!(similar(value, M), NOMETA)
end
end
@generated function initmetameta(context::C, value::V) where {C<:Context,V}
return quote
$(_metametaexpr(C, V, [:NOMETA for i in 1:fieldcount(V)]))
end
end
#=== initmeta ===#
function initmeta(context::C, value::V, metadata::D) where {C<:Context,V,D}
return Meta{metadatatype(C, V),metametatype(C, V)}(metadata, initmetameta(context, value))
end
############
# `Tagged` #
############
struct Tagged{T<:Tag,V,D,M,C<:ContextTagged}
context::C
value::V
meta::Meta{D,M}
function Tagged(context::C, value::V, meta::Meta) where {T<:Tag,V,C<:ContextTagged{T}}
D = metadatatype(C, V)
M = metametatype(C, V)
return new{T,V,D,M,C}(context, value, convert(Meta{D,M}, meta))
end
end
#=== `Tagged` API ===#
"""
```
tag(value, context::Context, metadata = Cassette.NoMetaData())
```
Return `value` tagged w.r.t. `context`, optionally associating `metadata` with the returned
`Tagged` instance.
Any provided `metadata` must obey the type constraints determined by Cassette's
[`metadatatype`](@ref) method.
Note that `hastagging(typeof(context))` must be `true` for a value to be tagged w.r.t. to
`context`.
See also: [`untag`](@ref), [`enabletagging`](@ref), [`hastagging`](@ref)
"""
function tag(value, context::Context, metadata = NoMetaData())
return Tagged(context, value, initmeta(context, value, metadata))
end
function tag(value, context::ContextUntagged, metadata = NoMetaData())
error("cannot `tag` a value w.r.t. a `context` if `!hastagging(typeof(context))`")
end
"""
```
untag(x, context::Context)
```
Return `x` untagged w.r.t. `context` if `istagged(x, context)`, otherwise return
`x` directly.
In other words, `untag(tag(x, context), context) === x` is always `true`.
If `!istagged(x, context)`, then `untag(x, context) === x` is `true`.
See also: [`tag`](@ref), [`istagged`](@ref)
"""
untag(x, context::Context) = untag(x, context.tag)
untag(x::Tagged{T}, tag::T) where {T<:Tag} = x.value
untag(x, ::Union{Tag,Nothing}) = x
"""
```
untagtype(::Type{T}, ::Type{C<:Context})
```
Return `typeof(untag(::T, ::C))`.
In other words, `untagtype(typeof(tag(x, context)), typeof(context)) === typeof(x)` is always
`true`.
If `!istaggedtype(T, C)`, then `untagtype(T, C) === T` is `true`.
"""
untagtype(X::Type, ::Type{C}) where {C<:Context} = untagtype(X, tagtype(C))
untagtype(::Type{<:Tagged{T,V}}, ::Type{T}) where {T<:Tag,V} = V
untagtype(X::Type, ::Type{<:Union{Tag,Nothing}}) = X
"""
```
metadata(x, context::Context)
```
Return the `metadata` attached to `x` if `hasmetadata(x, context)`, otherwise return
`Cassette.NoMetaData()`.
In other words, `metadata(tag(x, context, m), context) === m` is always `true`.
If `!hasmetadata(x, context)`, then `metadata(x, context) === Cassette.NoMetaData()` is
`true`.
"""
metadata(x, context::Context) = metadata(x, context.tag)
metadata(x::Tagged{T}, tag::T) where {T<:Tag} = x.meta.data
metadata(::Any, ::Union{Tag,Nothing}) = NoMetaData()
metameta(x, context::Context) = metameta(x, context.tag)
metameta(x::Tagged{T}, tag::T) where {T<:Tag} = x.meta.meta
metameta(::Any, ::Union{Tag,Nothing}) = NoMetaMeta()
"""
```
istagged(x, context::Context)
```
Return `true` if `x` is tagged w.r.t. `context`, return `false` otherwise.
In other words, `istagged(tag(x, context), context)` is always `true`.
See also: [`tag`](@ref), [`istaggedtype`](@ref)
"""
istagged(x, context::Context) = istagged(x, context.tag)
istagged(x::Tagged{T}, tag::T) where {T<:Tag} = true
istagged(::Any, ::Union{Tag,Nothing}) = false
"""
```
istaggedtype(::Type{T}, ::Type{C<:Context})
```
Return `typeof(istagged(::T, ::C))`.
In other words, `istaggedtype(typeof(tag(x, context)), typeof(context))` is always `true`.
See also: [`tag`](@ref), [`istagged`](@ref)
"""
istaggedtype(X::Type, ::Type{C}) where {C<:Context} = istaggedtype(X, tagtype(C))
istaggedtype(::Type{<:Tagged{T}}, ::Type{T}) where {T<:Tag} = true
istaggedtype(::DataType, ::Type{<:Union{Tag,Nothing}}) = false
"""
```
hasmetadata(x, context::Context)
```
Return `true` if `!isa(metadata(x, context), Cassette.NoMetaData)`, return `false` otherwise.
In other words, `hasmetadata(tag(x, context, m), context)` is always `true` and
`hasmetadata(tag(x, context), context)` is always `false`.
See also: [`metadata`](@ref)
"""
hasmetadata(x, context::Context) = hasmetadata(x, context.tag)
hasmetadata(x, tag::Union{Tag,Nothing}) = !isa(metadata(x, tag), NoMetaData)
hasmetameta(x, context::Context) = hasmetameta(x, context.tag)
hasmetameta(x, tag::Union{Tag,Nothing}) = !isa(metameta(x, tag), NoMetaMeta)
#########################
# Core._apply iteration #
#########################
destructstate(ctx::ContextTagged{T}, state::Tagged{T,<:Tuple}) where {T} = (tagged_getfield(ctx, state, 1), tagged_getfield(ctx, state, 2))
destructstate(ctx, state) = untag(state, ctx)
Base.iterate(t::Tagged) = destructstate(t.context, overdub(t.context, iterate, t))
Base.iterate(t::Tagged, state) = destructstate(t.context, overdub(t.context, iterate, t, state))
##################################
# `tagged_new`/`tagged_splatnew` #
##################################
@generated function tagged_new(context::C, ::Type{T}, args...) where {C<:Context,T}
argmetaexprs = Any[]
for i in 1:fieldcount(T)
if i <= nfields(args) && istaggedtype(args[i], C)
push!(argmetaexprs, :(args[$i].meta))
else
push!(argmetaexprs, :NOMETA)
end
end
untagged_args = [:(untag(args[$i], context)) for i in 1:nfields(args)]
newexpr = (T <: Tuple) ? Expr(:tuple, untagged_args...) : Expr(:new, T, untagged_args...)
onlytypeargs = true
for arg in args
if !(arg <: Type)
onlytypeargs = false
break
end
end
if (all(x == :NOMETA for x in argmetaexprs) && doesnotneedmetatype(T)) || onlytypeargs
return newexpr
else
metametaexpr = _metametaexpr(C, T, argmetaexprs)
return quote
M = metatype(C, T)
return Tagged(context, $newexpr, Meta(NoMetaData(), $metametaexpr))
end
end
end
@inline tagged_splatnew(context::Context, T::Type, args) = tagged_new(context, T, args...)
@generated function tagged_new_array(context::C, ::Type{T}, args...) where {C<:Context,T<:Array}
untagged_args = [:(untag(args[$i], context)) for i in 1:nfields(args)]
return quote
return tag($(T)($(untagged_args...)), context)
end
end
@generated function tagged_new_module(context::C, args...) where {C<:Context}
if istaggedtype(args[1], C)
return_expr = quote
Tagged(context, tagged_module.value,
Meta(NoMetaData(),
ModuleMeta(args[1].meta, tagged_module.meta.meta.bindings)))
end
else
return_expr = :(tagged_module)
end
return quote
new_module = Module(args...)
tagged_module = fetch_tagged_module(context, new_module)
return $return_expr
end
end
@generated function tagged_new_tuple(context::C, args...) where {C<:Context}
T = Tuple{[untagtype(args[i], C) for i in 1:nfields(args)]...}
return quote
tagged_new(context, $T, args...)
end
end
# like `tagged_new_tuple`, but will not necessarily tag non-`doesnotneedmeta` elements of `args`
@generated function _tagged_new_tuple_unsafe(context::C, args...) where {C<:Context}
if all(!istaggedtype(arg, C) for arg in args)
return quote
Core.tuple(args...)
end
else
return quote
tagged_new_tuple(context, args...)
end
end
end
##################################
# `tagged_*` intrisic primitives #
##################################
_untag_all(context::Context, a) = untag(a, context)
_untag_all(context::Context, a, b) = (untag(a, context), untag(b, context))
_untag_all(context::Context, a, b, c) = (untag(a, context), untag(b, context), untag(c, context))
_untag_all(context::Context, a, b, c, rest...) = (untag(a, context), untag(b, context), untag(c, context), _untag_all(context, rest...)...)
#=== tagged_nameof ===#
tagged_nameof(context::Context, x) = nameof(untag(x, context))
function tagged_nameof(context::ContextTagged{T}, x::Tagged{T,Module}) where {T}
name_value = nameof(x.value)
name_meta = hasmetameta(x, context) ? x.meta.meta.name : NOMETA
return Tagged(context, name_value, name_meta)
end
#=== tagged_globalref ===#
@inline function tagged_globalref(context::ContextTagged{T},
m::Tagged{T},
name,
primal) where {T}
if hasmetameta(m, context) && !istagged(primal, context)
return _tagged_globalref(context, m, name, primal)
else
return primal
end
end
# assume that `context` === `primal` TODO is this assumption valid?
@inline function tagged_globalref(context::ContextTagged{T},
m::Tagged{T},
name,
primal::ContextTagged{T}) where {T}
return primal
end
@inline function _tagged_globalref(context::ContextTagged{T},
m::Tagged{T},
name,
primal) where {T}
untagged_name = untag(name, context)
if isconst(m.value, untagged_name) && doesnotneedmeta(primal)
# It's very important that this fast path exists and is taken with no runtime
# overhead; this is the path that will be taken by, for example, access of simple
# named function bindings.
return primal
else
meta = fetch_bindingmeta!(context, m.value, m.meta.meta.bindings, untagged_name, primal)
return Tagged(context, primal, meta)
end
end
#=== tagged_globalref_set_meta! ===#
@inline function tagged_globalref_set_meta!(context::ContextTagged{T}, m::Tagged{T}, name::Symbol, primal) where {T}
bindingmeta = _fetch_bindingmeta!(context, m.value, m.meta.meta.bindings, name)
bindingmeta.data = istagged(primal, context) ? primal.meta : NOMETA
return nothing
end
#=== tagged_getfield ===#
tagged_getfield(context::Context, x, name) = tagged_getfield(context, x, name, false)
tagged_getfield(context::ContextTagged{T}, x, name, boundscheck) where {T} = getfield(x, untag(name, context), untag(boundscheck, context))
function tagged_getfield(context::ContextTagged{T}, x::Tagged{T}, name, boundscheck) where {T}
untagged_boundscheck = untag(boundscheck, context)
untagged_name = untag(name, context)
x_value = untag(x, context)
y_value = getfield(x_value, untagged_name, untagged_boundscheck)
if isa(x_value, Module)
return tagged_globalref(context, x, untagged_name, getfield(x_value, untagged_name))
elseif hasmetameta(x, context)
y_meta = load(getfield(x.meta.meta, untagged_name, untagged_boundscheck))
doesnotneedmeta(y_value) && y_meta === NOMETA && return y_value
return Tagged(context, y_value, y_meta)
elseif doesnotneedmeta(y_value)
return y_value
else
return Tagged(context, y_value, NOMETA)
end
end
#=== tagged_setfield! ===#
tagged_setfield!(context::ContextTagged{T}, x, name, y) where {T} = setfield!(x, untag(name, context), y)
function tagged_setfield!(context::ContextTagged{T}, x::Tagged{T}, name, y) where {T}
untagged_name = untag(name, context)
y_value = untag(y, context)
y_meta = istagged(y, context) ? y.meta : NOMETA
setfield!(x.value, untagged_name, y_value)
if hasmetameta(x, context)
store!(getfield(x.meta.meta, untagged_name), y_meta)
end
return y
end
#=== tagged_arrayref ===#
function tagged_arrayref(context::ContextTagged{T}, boundscheck, x, inds...) where {T}
return Core.arrayref(untag(boundscheck, context), x, _untag_all(context, inds...)...)
end
function tagged_arrayref(context::ContextTagged{T}, boundscheck, x::Tagged{T}, inds...) where {T}
untagged_boundscheck = untag(boundscheck, context)
untagged_inds = _untag_all(context, inds...)
y_value = Core.arrayref(untagged_boundscheck, untag(x, context), untagged_inds...)
if hasmetameta(x, context)
y_meta = Core.arrayref(untagged_boundscheck, x.meta.meta, untagged_inds...)
else
y_meta = NOMETA
end
return Tagged(context, y_value, y_meta)
end
#=== tagged_arrayset ===#
function tagged_arrayset(context::ContextTagged{T}, boundscheck, x, y, inds...) where {T}
return Core.arrayset(untag(boundscheck, context), x, y, _untag_all(context, inds...)...)
end
function tagged_arrayset(context::ContextTagged{T}, boundscheck, x::Tagged{T}, y, inds...) where {T}
untagged_boundscheck = untag(boundscheck, context)
untagged_inds = _untag_all(context, inds...)
y_value = untag(y, context)
y_meta = istagged(y, context) ? y.meta : NOMETA
Core.arrayset(untagged_boundscheck, untag(x, context), y_value, untagged_inds...)
if hasmetameta(x, context)
Core.arrayset(untagged_boundscheck, x.meta.meta, convert(eltype(x.meta.meta), y_meta), untagged_inds...)
end
return x
end
#=== tagged_growbeg! ===#
tagged_growbeg!(context::ContextTagged{T}, x, delta) where {T} = Base._growbeg!(x, untag(delta, context))
function tagged_growbeg!(context::ContextTagged{T}, x::Tagged{T}, delta) where {T}
delta_untagged = untag(delta, context)
Base._growbeg!(x.value, delta_untagged)
if hasmetameta(x, context)
Base._growbeg!(x.meta.meta, delta_untagged)
x.meta.meta[1:delta_untagged] .= Ref(NOMETA)
end
return nothing
end
#=== tagged_growend! ===#
tagged_growend!(context::ContextTagged{T}, x, delta) where {T} = Base._growend!(x, untag(delta, context))
function tagged_growend!(context::ContextTagged{T}, x::Tagged{T}, delta) where {T}
delta_untagged = untag(delta, context)
Base._growend!(x.value, delta_untagged)
if hasmetameta(x, context)
old_length = length(x.meta.meta)
Base._growend!(x.meta.meta, delta_untagged)
x.meta.meta[(old_length + 1):(old_length + delta_untagged)] .= Ref(NOMETA)
end
return nothing
end
#=== tagged_growat! ===#
function tagged_growat!(context::ContextTagged{T}, x, i, delta) where {T}
return Base._growat!(x, untag(i, context), untag(delta, context))
end
function tagged_growat!(context::ContextTagged{T}, x::Tagged{T}, i, delta) where {T}
i_untagged = untag(i, context)
delta_untagged = untag(delta, context)
Base._growat!(x.value, i_untagged, delta_untagged)
if hasmetameta(x, context)
Base._growat!(x.meta.meta, i_untagged, delta_untagged)
x.meta.meta[i_untagged:(i_untagged + delta_untagged - 1)] .= Ref(NOMETA)
end
return nothing
end
#=== tagged_deletebeg! ===#
tagged_deletebeg!(context::ContextTagged{T}, x, delta) where {T} = Base._deletebeg!(x, untag(delta, context))
function tagged_deletebeg!(context::ContextTagged{T}, x::Tagged{T}, delta) where {T}
delta_untagged = untag(delta, context)
Base._deletebeg!(x.value, delta_untagged)
hasmetameta(x, context) && Base._deletebeg!(x.meta.meta, delta_untagged)
return nothing
end
#=== tagged_deleteend! ===#
tagged_deleteend!(context::ContextTagged{T}, x, delta) where {T} = Base._deleteend!(x, untag(delta, context))
function tagged_deleteend!(context::ContextTagged{T}, x::Tagged{T}, delta) where {T}
delta_untagged = untag(delta, context)
Base._deleteend!(x.value, delta_untagged)
hasmetameta(x, context) && Base._deleteend!(x.meta.meta, delta_untagged)
return nothing
end
#=== tagged_deleteat! ===#
function tagged_deleteat!(context::ContextTagged{T}, x, i, delta) where {T}
return Base._deleteat!(x, untag(i, context), untag(delta, context))
end
function tagged_deleteat!(context::ContextTagged{T}, x::Tagged{T}, i, delta) where {T}
i_untagged = untag(i, context)
delta_untagged = untag(delta, context)
Base._deleteat!(x.value, i_untagged, delta_untagged)
hasmetameta(x, context) && Base._deleteat!(x.meta.meta, i_untagged, delta_untagged)
return nothing
end
#=== tagged_typeassert ===#
function tagged_typeassert(context::ContextTagged{T}, x, typ) where {T}
return Core.typeassert(x, untag(typ, context))
end
function tagged_typeassert(context::ContextTagged{T}, x::Tagged{T}, typ) where {T}
untagged_result = Core.typeassert(untag(x, context), untag(typ, context))
return Tagged(context, untagged_result, x.meta)
end
#=== tagged_sitofp ===#
function tagged_sitofp(context::ContextTagged{T}, F, x) where {T}
return Base.sitofp(untag(F, context), x)
end
function tagged_sitofp(context::ContextTagged{T}, F, x::Tagged{T}) where {T}
return Tagged(context, Base.sitofp(untag(F, context), x.value), x.meta)
end
#=== tagged_sle_int ===#
tagged_sle_int(context::Context, x, y) = Base.sle_int(untag(x, context), untag(y, context))
###################
# Pretty Printing #
###################
Base.show(io::IO, meta::Union{NoMetaMeta,NoMetaData}) = print(io, "_")
function Base.show(io::IO, meta::Meta)
if isa(meta.data, NoMetaData) && isa(meta.meta, NoMetaMeta)
print(io, "_")
else
if isa(meta.meta, NamedTuple)
tmp = IOBuffer()
write(tmp, "(")
i = 1
for (k, v) in pairs(meta.meta)
print(tmp, k, " = ", load(v))
if i == length(meta.meta)
print(tmp, ")")
else
print(tmp, ", ")
i += 1
end
end
metametastr = String(take!(tmp))
elseif isa(meta.meta, Tuple)
tmp = IOBuffer()
write(tmp, "(")
i = 1
for v in meta.meta
print(tmp, load(v))
if i == length(meta.meta)
print(tmp, ")")
else
print(tmp, ", ")
i += 1
end
end
metametastr = String(take!(tmp))
else
metametastr = sprint(show, meta.meta)
end
print(io, "Meta(", meta.data, ", ", metametastr, ")")
end
end
Base.show(io::IO, x::Tagged) = print(io, "Tagged(", x.context.tag, ", ", x.value, ", ", x.meta, ")")
Base.show(io::IO, ::Tag{N,X,E}) where {N,X,E} = print(io, "Tag{", N, ",", X, ",", E, "}()")
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 15956 | #############################################################################################
print(" running BazCtx test...")
before_time = time()
@context BazCtx
struct Baz
x::Int
y::Float64
z::String
end
baz_identity(x::Int) = Baz(x, float(x), "$x").x
Cassette.metadatatype(::Type{<:BazCtx}, ::Type{<:Number}) = Float64
x, n = rand(Int), rand()
ctx = enabletagging(BazCtx(), baz_identity)
result = overdub(ctx, baz_identity, tag(x, ctx, n))
@test untag(result, ctx) === x
@test untagtype(typeof(result), typeof(ctx)) === typeof(x)
@test istagged(result, ctx)
@test istaggedtype(typeof(result), typeof(ctx))
@test metadata(result, ctx) === n
@test metameta(result, ctx) === Cassette.NoMetaMeta()
@test hasmetadata(result, ctx)
@test !hasmetameta(result, ctx)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running FooBarCtx test...")
before_time = time()
struct Bar{X,Y,Z}
x::X
y::Y
z::Z
end
mutable struct Foo
a::Bar{Int}
b
end
function foo_bar_identity(x)
bar = Bar(x, x + 1, x + 2)
foo = Foo(bar, "ha")
foo.b = bar
foo.a = Bar(4,5,6)
foo2 = Foo(foo.a, foo.b)
foo2.a = foo2.b
array = Float64[]
push!(array, foo2.a.x)
return [array[1]][1]
end
@context FooBarCtx
Cassette.metadatatype(::Type{<:FooBarCtx}, ::Type{T}) where T<:Number = T
x, n = 1, 2
ctx = enabletagging(FooBarCtx(), foo_bar_identity)
result = overdub(ctx, foo_bar_identity, tag(x, ctx, n))
@test untag(result, ctx) === float(x)
@test untagtype(typeof(result), typeof(ctx)) === Float64
@test istagged(result, ctx)
@test istaggedtype(typeof(result), typeof(ctx))
@test metadata(result, ctx) === float(n)
@test metameta(result, ctx) === Cassette.NoMetaMeta()
@test hasmetadata(result, ctx)
@test !hasmetameta(result, ctx)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running TaggedTupleCtx test...")
before_time = time()
@context TaggedTupleCtx
Cassette.metadatatype(::Type{<:TaggedTupleCtx}, ::DataType) = Float64
x = rand()
ctx = enabletagging(TaggedTupleCtx(), 1)
result = overdub(ctx, x -> (x, [x], 1), x)
@test untag(result, ctx) == (x, [x], 1)
@test untagtype(typeof(result), typeof(ctx)) === typeof((x, [x], 1))
@test istagged(result, ctx)
@test istaggedtype(typeof(result), typeof(ctx))
@test metadata(result, ctx) === Cassette.NoMetaData()
@test isa(metameta(result, ctx), Tuple{
Cassette.Immutable{Cassette.Meta{Float64,Cassette.NoMetaMeta}},
Cassette.Immutable{Cassette.Meta{Float64,Array{Cassette.Meta{Float64,Cassette.NoMetaMeta},1}}},
Cassette.Immutable{Cassette.Meta{Float64,Cassette.NoMetaMeta}}
})
@test !hasmetadata(result, ctx)
@test hasmetameta(result, ctx)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running ApplyCtx test...")
before_time = time()
@context ApplyCtx
x = rand()
@static if isdefined(Core, :_apply_iterate)
applytest(x) = Core._apply_iterate(iterate, hypot, (x,), (1, x), 1, x, (1, 2))
else
applytest(x) = Core._apply(hypot, (x,), (1, x), 1, x, (1, 2))
end
ctx = enabletagging(ApplyCtx(), 1)
@test overdub(ctx, applytest, tag(x, ctx)) === applytest(x)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running VATupleCtx test...")
before_time = time()
@context VATupleCtx
x = rand(5)
ctx = enabletagging(VATupleCtx(), 1)
result = overdub(ctx, broadcast, sin, x)
@test untag(result, ctx) == sin.(x)
@test untagtype(typeof(result), typeof(ctx)) === typeof(sin.(x))
@test istagged(result, ctx)
@test istaggedtype(typeof(result), typeof(ctx))
@test metadata(result, ctx) === Cassette.NoMetaData()
@test metameta(result, ctx) === Cassette.NoMetaMeta()
@test !hasmetadata(result, ctx)
@test !hasmetameta(result, ctx)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running BroadcastCtx test...")
before_time = time()
@context BroadcastCtx
v, m = rand(5), rand(5)
ctx = enabletagging(BroadcastCtx(), 1)
Cassette.metadatatype(::Type{<:BroadcastCtx}, ::Type{T}) where {T<:Number} = T
result = overdub(ctx, broadcast, (v, m) -> tag(v, ctx, m), v, m)
@test untag(result, ctx) == v
@test untagtype(typeof(result), typeof(ctx)) === typeof(v)
@test istagged(result, ctx)
@test istaggedtype(typeof(result), typeof(ctx))
@test metadata(result, ctx) === Cassette.NoMetaData()
@test m == map(metameta(result, ctx)) do x
@test x.meta === Cassette.NoMetaMeta()
return x.data
end
@test !hasmetadata(result, ctx)
@test hasmetameta(result, ctx)
result = @overdub(ctx, ((v, m) -> tag(v, ctx, m)).(v, m[1]))
@test untag(result, ctx) == v
@test untagtype(typeof(result), typeof(ctx)) === typeof(v)
@test istagged(result, ctx)
@test istaggedtype(typeof(result), typeof(ctx))
@test metadata(result, ctx) === Cassette.NoMetaData()
foreach(metameta(result, ctx)) do x
@test x.meta === Cassette.NoMetaMeta()
@test x.data === m[1]
end
@test !hasmetadata(result, ctx)
@test hasmetameta(result, ctx)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running BroadcastCtx2 test...")
before_time = time()
@context BroadcastCtx2
Cassette.metadatatype(::Type{<:BroadcastCtx2{Int}}, ::Type{T}) where {T<:Number} = Vector{T}
Cassette.metadatatype(::Type{<:BroadcastCtx2{Val{N}}}, ::Type{T}) where {N,T<:Number} = NTuple{N,T}
v, m = rand(5), rand(5)
ctx = enabletagging(BroadcastCtx2(metadata=10), 1)
result = overdub(ctx, broadcast, (v, m) -> tag(v, ctx, m), v, [m])
@test untag(result, ctx) == v
@test untagtype(typeof(result), typeof(ctx)) === typeof(v)
@test istagged(result, ctx)
@test istaggedtype(typeof(result), typeof(ctx))
@test metadata(result, ctx) === Cassette.NoMetaData()
@test all(e -> e == m, map(metameta(result, ctx)) do x
@test x.meta === Cassette.NoMetaMeta()
return x.data
end)
@test !hasmetadata(result, ctx)
@test hasmetameta(result, ctx)
v, m = rand(5), (1.0,2.0,3.0)
ctx = enabletagging(BroadcastCtx2(metadata=Val(3)), 1)
result = overdub(ctx, broadcast, (v, m) -> tag(v, ctx, m), v, [m])
@test untag(result, ctx) == v
@test untagtype(typeof(result), typeof(ctx)) === typeof(v)
@test istagged(result, ctx)
@test istaggedtype(typeof(result), typeof(ctx))
@test metadata(result, ctx) === Cassette.NoMetaData()
foreach(metameta(result, ctx)) do x
@test x.meta === Cassette.NoMetaMeta()
@test x.data === m
end
@test !hasmetadata(result, ctx)
@test hasmetameta(result, ctx)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running MetaTypeCtx test...")
before_time = time()
@context MetaTypeCtx
@test Cassette.metatype(typeof(MetaTypeCtx()), DataType) === Cassette.Meta{Cassette.NoMetaData,Cassette.NoMetaMeta}
ctx = enabletagging(MetaTypeCtx(), 1)
@test overdub(ctx, T -> (T,T), Float64) === (Float64, Float64)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running TagConditionalCtx test...")
before_time = time()
@context TagConditionalCtx
ctx = enabletagging(TagConditionalCtx(), 1)
@test overdub(ctx, x -> x ? 1 : 2, tag(true, ctx)) === 1
function condtest(b)
i = 1
while i > b
i -= 1
end
if b end
return i
end
@test overdub(ctx, condtest, tag(false, ctx)) === 0
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running KwargCtx test...")
before_time = time()
@context KwargCtx
ctx = enabletagging(KwargCtx(), 1)
kwargtest(x; y = 1) = x + y
@test overdub(ctx, _y -> kwargtest(3; y = _y), tag(2, ctx)) === 5
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running RecurTagCtx test...")
before_time = time()
@context RecurTagCtx
mutable struct RecurType
r::RecurType
RecurType() = new()
end
ctx = enabletagging(RecurTagCtx(), 1)
x = tag(RecurType(), ctx)
@overdub(ctx, x.r = RecurType())
@test istagged(x, ctx)
@test !hasmetadata(x, ctx)
@test hasmetameta(x, ctx)
@test isa(metameta(x, ctx), NamedTuple{(:r,),Tuple{Cassette.Mutable{Cassette.Meta}}})
@test isdefined(untag(x, ctx), :r)
@test !(isdefined(untag(x, ctx).r, :r))
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running CrazyPropCtx test...")
before_time = time()
@context CrazyPropCtx
module CrazyPropModule
const CONST_BINDING = Float64[]
global GLOBAL_BINDING = 0.0
struct Foo
vector::Vector{Float64}
end
mutable struct FooContainer
foo::Foo
end
mutable struct PlusFunc
x::Float64
end
(f::PlusFunc)(x) = f.x + x
const PLUSFUNC = PlusFunc(0.0)
# implements a very convoluted `sum(x) * sum(y)`
function crazy_sum_mul(x::Vector{Float64}, y::Vector{Float64})
@assert length(x) === length(y)
fooc = FooContainer(Foo(x))
tmp = y
# this loop sets:
# `const_binding == x`
# `global_binding == prod(y)`
for i in 1:length(y)
if iseven(i) # `fooc.foo.vector === y && tmp === x`
v = fooc.foo.vector[i]
push!(CONST_BINDING, tmp[i])
global GLOBAL_BINDING = PLUSFUNC(v)
PLUSFUNC.x = GLOBAL_BINDING
fooc.foo = Foo(x)
tmp = y
else # `fooc.foo.vector === x && tmp === y`
v = fooc.foo.vector[i]
push!(CONST_BINDING, v)
global GLOBAL_BINDING = PLUSFUNC(tmp[i])
PLUSFUNC.x = GLOBAL_BINDING
fooc.foo = Foo(y)
tmp = x
end
end
# accumulate result
z = sum(CONST_BINDING) * GLOBAL_BINDING
# reset global state
empty!(CONST_BINDING)
PLUSFUNC.x = 0.0
global GLOBAL_BINDING = 0.0
return z
end
end
x, y = rand(100), rand(100)
primal_result = CrazyPropModule.crazy_sum_mul(x, y)
@test isapprox(primal_result, sum(x) * sum(y))
Cassette.metadatatype(::Type{<:CrazyPropCtx}, ::Type{T}) where T<:Number = T
function Cassette.overdub(ctx::CrazyPropCtx, ::typeof(*), x, y)
z = untag(x, ctx) * untag(y, ctx)
if hasmetadata(x, ctx) && hasmetadata(y, ctx)
return tag(z, ctx, metadata(x, ctx) * metadata(y, ctx))
elseif hasmetadata(x, ctx)
return tag(z, ctx, metadata(x, ctx))
elseif hasmetadata(y, ctx)
return tag(z, ctx, metadata(y, ctx))
else
return z
end
end
function Cassette.overdub(ctx::CrazyPropCtx, ::typeof(+), x, y)
z = untag(x, ctx) + untag(y, ctx)
if hasmetadata(x, ctx) && hasmetadata(y, ctx)
return tag(z, ctx, metadata(x, ctx) + metadata(y, ctx))
elseif hasmetadata(x, ctx)
return tag(z, ctx, metadata(x, ctx))
elseif hasmetadata(y, ctx)
return tag(z, ctx, metadata(y, ctx))
else
return z
end
end
ctx = enabletagging(CrazyPropCtx(), CrazyPropModule.crazy_sum_mul)
xm, ym = rand(100), rand(100)
tx = overdub(ctx, broadcast, (v, m) -> tag(v, ctx, m), x, xm)
ty = overdub(ctx, broadcast, (v, m) -> tag(v, ctx, m), y, ym)
tagged_result = overdub(ctx, CrazyPropModule.crazy_sum_mul, tx, ty)
@test isapprox(untag(tagged_result, ctx), primal_result)
@test isapprox(metadata(tagged_result, ctx), CrazyPropModule.crazy_sum_mul(xm, ym))
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running DiffCtx test...")
before_time = time()
@context DiffCtx
const DiffCtxWithTag{T} = DiffCtx{Nothing,T}
Cassette.metadatatype(::Type{<:DiffCtx}, ::Type{T}) where {T<:Real} = T
tangent(x, context) = hasmetadata(x, context) ? metadata(x, context) : zero(untag(x, context))
function D(f, x)
ctx = enabletagging(DiffCtx(), f)
result = overdub(ctx, f, tag(x, ctx, oftype(x, 1.0)))
return tangent(result, ctx)
end
function Cassette.overdub(ctx::DiffCtxWithTag{T}, ::typeof(sin), x::Tagged{T,<:Real}) where {T}
vx, dx = untag(x, ctx), tangent(x, ctx)
return tag(sin(vx), ctx, cos(vx) * dx)
end
function Cassette.overdub(ctx::DiffCtxWithTag{T}, ::typeof(cos), x::Tagged{T,<:Real}) where {T}
vx, dx = untag(x, ctx), tangent(x, ctx)
return tag(cos(vx), ctx, -sin(vx) * dx)
end
function Cassette.overdub(ctx::DiffCtxWithTag{T}, ::typeof(*), x::Tagged{T,<:Real}, y::Tagged{T,<:Real}) where {T}
vx, dx = untag(x, ctx), tangent(x, ctx)
vy, dy = untag(y, ctx), tangent(y, ctx)
return tag(vx * vy, ctx, vy * dx + vx * dy)
end
function Cassette.overdub(ctx::DiffCtxWithTag{T}, ::typeof(*), x::Tagged{T,<:Real}, y::Real) where {T}
vx, dx = untag(x, ctx), tangent(x, ctx)
return tag(vx * y, ctx, y * dx)
end
function Cassette.overdub(ctx::DiffCtxWithTag{T}, ::typeof(*), x::Real, y::Tagged{T,<:Real}) where {T}
vy, dy = untag(y, ctx), tangent(y, ctx)
return tag(x * vy, ctx, x * dy)
end
function Cassette.overdub(ctx::DiffCtxWithTag{T}, ::typeof(+), x::Tagged{T,<:Real}, y::Tagged{T,<:Real}) where {T}
vx, dx = untag(x, ctx), tangent(x, ctx)
vy, dy = untag(y, ctx), tangent(y, ctx)
return tag(vx + vy, ctx, dx + dy)
end
function Cassette.overdub(ctx::DiffCtxWithTag{T}, ::typeof(+), x::Tagged{T,<:Real}, y::Real) where {T}
vx, dx = untag(x, ctx), tangent(x, ctx)
return tag(vx + y, ctx, dx)
end
function Cassette.overdub(ctx::DiffCtxWithTag{T}, ::typeof(+), x::Real, y::Tagged{T,<:Real}) where {T}
vy, dy = untag(y, ctx), tangent(y, ctx)
return tag(x + vy, ctx, dy)
end
Cassette.overdub(ctx::DiffCtx, ::typeof(sin), x::Real) = sin(x)
Cassette.overdub(ctx::DiffCtx, ::typeof(cos), x::Real) = cos(x)
Cassette.overdub(ctx::DiffCtx, ::typeof(*), x::Real, y::Real) = x * y
Cassette.overdub(ctx::DiffCtx, ::typeof(+), x::Real, y::Real) = x + y
Cassette.overdub(ctx::DiffCtx, ::typeof(*), x, y, z) = Cassette.overdub(ctx, *, Cassette.overdub(ctx, *, x, y), z)
Cassette.overdub(ctx::DiffCtx, ::typeof(+), x, y, z) = Cassette.overdub(ctx, +, Cassette.overdub(ctx, +, x, y), z)
@test D(sin, 1) === cos(1)
@test D(x -> D(sin, x), 1) === -sin(1)
@test D(x -> sin(x) * cos(x), 1) === cos(1)^2 - sin(1)^2
@test D(x -> x * D(y -> x * y, 1), 2) === 4
@test D(x -> x * D(y -> x * y, 2), 1) === 2
@test D(x -> x * D(y -> 5*x*y, 3), 2) === 20
@test D(x -> x * foo_bar_identity(x), 1) === 2.0
x = rand()
@test D(x -> (x + 2) * (3 + x), x) === 2x + 5
@test D(x -> CrazyPropModule.crazy_sum_mul([x], [x]), x) === (x + x)
@test D(x -> CrazyPropModule.crazy_sum_mul([x, 2], [3, x]), x) === 2x + 5
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running ArrayIndexCtx test...")
before_time = time()
@context ArrayIndexCtx
matrixliteral(x) = Int[x x; x x]
Cassette.metadatatype(::Type{<:ArrayIndexCtx}, ::Type{Int}) = String
ctx = enabletagging(ArrayIndexCtx(), matrixliteral)
result = overdub(ctx, matrixliteral, tag(1, ctx, "hi"))
@test untag(result, ctx) == matrixliteral(1)
@test metameta(result, ctx) == fill(Cassette.Meta("hi", Cassette.NoMetaMeta()), 2, 2)
println("done (took ", time() - before_time, " seconds)")
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 26213 | #############################################################################################
print(" running RosCtx test...")
before_time = time()
@context RosCtx
function rosenbrock(x::Vector{Float64})
a = 1.0
b = 100.0
result = 0.0
for i in 1:length(x)-1
result += (a - x[i])^2 + b*(x[i+1] - x[i]^2)^2
end
return result
end
x = rand(2)
if VERSION < v"1.9"
@inferred (overdub(RosCtx(), rosenbrock, x))
end
messages = String[]
Cassette.prehook(::RosCtx, f, args...) = push!(messages, string("calling ", f, args))
@test overdub(RosCtx(), rosenbrock, x) == rosenbrock(x)
@test length(messages) > 50
Cassette.prehook(ctx::RosCtx, f, args...) = push!(ctx.metadata, string("calling ", f, args))
messages2 = String[]
@test overdub(RosCtx(metadata=messages2), rosenbrock, x) == rosenbrock(x)
@test messages == messages2
Cassette.prehook(::RosCtx, f, args...) = nothing
Cassette.prehook(ctx::RosCtx, f, args::Number...) = push!(ctx.metadata, args)
argslog = Any[]
@test @overdub(RosCtx(metadata=argslog), rosenbrock(x)) == rosenbrock(x)
for args in argslog
@test all(x -> isa(x, Number), args)
end
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running HookCtx test...")
before_time = time()
@context HookCtx
Cassette.prehook(ctx::HookCtx, f, args...) = push!(ctx.metadata[1], (f, args))
Cassette.posthook(ctx::HookCtx, out, f, args...) = push!(ctx.metadata[2], (out, f, args))
pres, posts = Any[], Any[]
ctx = HookCtx(metadata=(pres, posts))
x1, x2, x3 = rand(Int), rand(Int), rand(Int)
@overdub(ctx, x1 + x2 * x3)
@test pres == [(*, (x2, x3)),
(Base.mul_int, (x2, x3)),
(+, (x1, x2*x3)),
(Base.add_int, (x1, x2*x3))]
@test posts == [(Base.mul_int(x2, x3), Base.mul_int, (x2, x3)),
(*(x2, x3), *, (x2, x3)),
(Base.add_int(x1, x2*x3), Base.add_int, (x1, x2*x3)),
(+(x1, x2*x3), +, (x1, x2*x3))]
empty!(pres)
empty!(posts)
Cassette.overdub(::HookCtx, ::typeof(+), args...) = +(args...)
@overdub(ctx, x1 + x2 * x3)
@test pres == [(*, (x2, x3)),
(Base.mul_int, (x2, x3)),
(+, (x1, x2*x3))]
@test posts == [(Base.mul_int(x2, x3), Base.mul_int, (x2, x3)),
(*(x2, x3), *, (x2, x3)),
(+(x1, x2*x3), +, (x1, x2*x3))]
empty!(pres)
empty!(posts)
@overdub(ctx, Core._apply(+, (x1, x2), (x2 * x3, x3)))
if !(v"1.9" <= VERSION < v"1.10")
@test pres == [(tuple, (x1, x2)),
(*, (x2, x3)),
(Base.mul_int, (x2, x3)),
(tuple, (x2*x3, x3)),
(+, (x1, x2, x2*x3, x3))]
@test posts == [((x1, x2), tuple, (x1, x2)),
(Base.mul_int(x2, x3), Base.mul_int, (x2, x3)),
(*(x2, x3), *, (x2, x3)),
((x2*x3, x3), tuple, (x2*x3, x3)),
(+(x1, x2, x2*x3, x3), +, (x1, x2, x2*x3, x3))]
else
@test pres == [(tuple, (x1, x2)),
(*, (x2, x3)),
(Base.mul_int, (x2, x3)),
(tuple, (x2*x3, x3)),
(Core._apply, (+, (x1, x2), (x2*x3, x3)))]
@test posts == [((x1, x2), tuple, (x1, x2)),
(Base.mul_int(x2, x3), Base.mul_int, (x2, x3)),
(*(x2, x3), *, (x2, x3)),
((x2*x3, x3), tuple, (x2*x3, x3)),
(+(x1, x2, x2*x3, x3), Core._apply, (+, (x1, x2), (x2*x3, x3)))]
end
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running SinCtx test...")
before_time = time()
@context SinCtx
x = rand()
sin_plus_cos(x) = sin(x) + cos(x)
@test @overdub(SinCtx(), sin_plus_cos(x)) === sin_plus_cos(x)
Cassette.overdub(::SinCtx, ::typeof(sin), x) = cos(x)
@test @overdub(SinCtx(), sin_plus_cos(x)) === (2 * cos(x))
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running FoldCtx test...")
before_time = time()
@context FoldCtx
x = 2
foldmul(x, args...) = Core._apply(Base.afoldl, (*, x), args...)
@test @overdub(FoldCtx(), foldmul(x)) === foldmul(x)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running CountCtx test...")
before_time = time()
@context CountCtx
count1 = Ref(0)
Cassette.prehook(ctx::CountCtx, f, args::Number...) = (ctx.metadata[] += 1)
@overdub(CountCtx(metadata=count1), sin(1))
Cassette.prehook(ctx::CountCtx, f, args::Number...) = (ctx.metadata[] += 2)
count2 = Ref(0)
@overdub(CountCtx(metadata=count2), sin(1))
@test (2 * count1[]) === count2[]
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running CountCtx2 test...")
before_time = time()
@context CountCtx2
mutable struct Count{T}
count::Int
end
function Cassette.prehook(ctx::CountCtx2{Count{T}}, f, arg::T, args::T...) where {T}
ctx.metadata.count += 1
end
mapstr(x) = map(string, x)
c = Count{Union{String,Int}}(0)
@test @overdub(CountCtx2(metadata=c), mapstr(1:10)) == mapstr(1:10)
@test c.count > 1000
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running SqrCtx test...")
before_time = time()
@context SqrCtx
square_closure(x) = (y -> y * x)(x)
x = rand()
@test square_closure(x) == @overdub(SqrCtx(), square_closure(x))
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running CompCtx test...")
before_time = time()
@context CompCtx
comprehension1(x) = [i for i in x]
comprehension2(f, x, y) = [f(x, i) for i in y]
f, x, y = hypot, rand(), rand(2)
@test comprehension1(x) == @overdub(CompCtx(), comprehension1(x))
@test comprehension1(y) == @overdub(CompCtx(), comprehension1(y))
@test comprehension2(f, x, y) == @overdub(CompCtx(), comprehension2(f, x, y))
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running PassCtx test...")
before_time = time()
@context PassCtx
sig_collection = DataType[]
mypass = @pass (ctx, ref) -> begin
# TODO: check !in(sig, sig_collection) first to mimic a caching technique that will be used in practice
push!(sig_collection, ref.signature)
return ref.code_info
end
@overdub(PassCtx(pass=mypass), sum(rand(3)))
@test !isempty(sig_collection) && all(T -> T <: Tuple, sig_collection)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running PassFallbackCtx test...")
before_time = time()
@context PassFallbackCtx
fallbackpass = @pass (ctx, ref) -> begin
if ref.signature <: Tuple{typeof(sin),Any}
return :(cos($(Cassette.OVERDUB_ARGUMENTS_NAME)[2]))
end
return ref.code_info
end
x = rand(30)
sin_kernel(i) = i > 0.5 ? sin(i) : i
y = @inferred(overdub(PassFallbackCtx(pass=fallbackpass), sum, sin_kernel, x))
@test sum(i -> i > 0.5 ? cos(i) : i, x) === y
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running WorldCtx test...")
before_time = time()
@context WorldCtx
worldtest = 0
oldctx = WorldCtx()
overdub(oldctx, sin, 1)
Cassette.prehook(::WorldCtx, args...) = (global worldtest += 1)
overdub(WorldCtx(), sin, 1)
@test worldtest > 100
tmp = worldtest
overdub(oldctx, sin, 1)
@test tmp < worldtest
tmp = worldtest
Cassette.prehook(::WorldCtx, args...) = nothing
overdub(WorldCtx(), sin, 1)
@test tmp === worldtest
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running TraceCtx test...")
before_time = time()
x, y, z = rand(3)
trtest(x, y, z) = x*y + y*z
trkwtest(x; _y = 1.0, _z = 2.0) = trtest(x, _y, _z)
@context TraceCtx
function Cassette.overdub(ctx::TraceCtx, args...)
subtrace = Any[]
push!(ctx.metadata, args => subtrace)
if canrecurse(ctx, args...)
newctx = similarcontext(ctx, metadata = subtrace)
return recurse(newctx, args...)
else
return fallback(ctx, args...)
end
end
trace = Any[]
@test @overdub(TraceCtx(metadata = trace), trtest(x, y, z)) == trtest(x, y, z)
@test trace == Any[
(trtest,x,y,z) => Any[
(*,x,y) => Any[(Base.mul_float,x,y)=>Any[]]
(*,y,z) => Any[(Base.mul_float,y,z)=>Any[]]
(+,x*y,y*z) => Any[(Base.add_float,x*y,y*z)=>Any[]]
]
]
# JuliaLabs/Cassette.jl#48
@context HookTraceCtx
mutable struct HookTrace
current::Vector{Any}
stack::Vector{Any}
HookTrace() = new(Any[], Any[])
end
tracekw = Any[]
@overdub(TraceCtx(metadata = tracekw), trkwtest(x, _y = y, _z = z)) == trtest(x, y, z)
subtracekw = first(Iterators.filter(t -> t[1] === (Core.kwfunc(trkwtest), (_y = y, _z = z), trkwtest, x), tracekw))[2]
@test subtracekw == trace
function enter!(t::HookTrace, args...)
pair = args => Any[]
push!(t.current, pair)
push!(t.stack, t.current)
t.current = pair.second
return nothing
end
function exit!(t::HookTrace)
t.current = pop!(t.stack)
return nothing
end
Cassette.prehook(ctx::HookTraceCtx, args...) = enter!(ctx.metadata, args...)
Cassette.posthook(ctx::HookTraceCtx, args...) = exit!(ctx.metadata)
htrace = HookTrace()
@overdub(HookTraceCtx(metadata = htrace), trtest(x, y, z))
@test htrace.current == trace
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running NestedReflectCtx test...")
before_time = time()
@context NestedReflectCtx
r_pre = Cassette.reflect((typeof(sin), Int))
r_post = Cassette.reflect((typeof(overdub), typeof(NestedReflectCtx()), typeof(sin), Int))
@test isa(r_pre, Cassette.Reflection) && isa(r_post, Cassette.Reflection)
Cassette.overdub_pass!(r_pre, typeof(NestedReflectCtx()))
@test r_pre.code_info.code == r_post.code_info.code
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running GemvCtx test...")
before_time = time()
# issue #51
@context GemvCtx
α, β = 1.0, 2.0
A, X, Y = rand(Float64, 10, 10), rand(Float64, 10), rand(Float64, 10)
Y_copy = copy(Y)
Y_out = overdub(GemvCtx(), LinearAlgebra.BLAS.gemv!, 'T', α, A, X, β, Y)
Y_copy_out = LinearAlgebra.BLAS.gemv!('T', α, A, X, β, Y_copy)
@test Y_out == Y_copy_out
@test Y_out === Y
@test Y_copy_out === Y_copy
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running InferCtx test...")
before_time = time()
@context InferCtx
dispatchtupletest(::Type{T}) where {T} = Base.isdispatchtuple(Tuple{T}) ? T : Any
relu(x) = max(zero(x), x)
relulayer(W, x, b) = relu.(W*x .+ b)
kwargtest(foobar; foo = 1, bar = 2) = nothing
@inferred(overdub(InferCtx(), typejoin, Float32, Float32, Float32))
@inferred(overdub(InferCtx(), dispatchtupletest, Float32))
@inferred(overdub(InferCtx(), (a, b) -> Core.apply_type(a, b), AbstractVector, Int))
@inferred(overdub(InferCtx(), eltype, rand(1)))
@inferred(overdub(InferCtx(), *, rand(1, 1), rand(1, 1)))
@inferred(overdub(InferCtx(), *, rand(Float32, 1, 1), rand(Float32, 1, 1)))
if VERSION <= v"1.3"
@inferred(overdub(InferCtx(), *, rand(Float32, 1, 1), rand(Float32, 1)))
@inferred(overdub(InferCtx(), relulayer, rand(Float64, 1, 1), rand(Float32, 1), rand(Float32, 1)))
@inferred(overdub(InferCtx(), rand, Float32, 1))
else
# test depends on constant propagation
@test_throws Exception @inferred(overdub(InferCtx(), *, rand(Float32, 1, 1), rand(Float32, 1)))
# test depends on M*v which is the test above
@test_throws Exception @inferred(overdub(InferCtx(), relulayer, rand(Float64, 1, 1), rand(Float32, 1), rand(Float32, 1)))
if VERSION < v"1.7"
@test_throws Exception @inferred(overdub(InferCtx(), rand, Float32, 1))
else
@inferred(overdub(InferCtx(), rand, Float32, 1))
end
end
if VERSION < v"1.9"
@inferred(overdub(InferCtx(), broadcast, +, rand(1), rand(1)))
end
@inferred(overdub(InferCtx(), () -> kwargtest(42; foo = 1, bar = 2)))
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running InModuleCtx test...")
before_time = time()
module DefineStuffInModule
using Cassette
Cassette.@context InModuleCtx
x = 0
incrpass = Cassette.@pass (ctx, ref) -> (global x += 1; ref.code_info)
f(x) = Cassette.overdub(InModuleCtx(pass = incrpass), sin, x)
end
@test DefineStuffInModule.f(1) === sin(1)
@test DefineStuffInModule.x > 0
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running InvokeCtx test...")
before_time = time()
invoked(x::Int) = x + x
invoked(x::Number) = x^2
invoker(x) = invoke(invoked, Tuple{Number}, x)
@context InvokeCtx
Cassette.prehook(ctx::InvokeCtx, f, args...) = push!(ctx.metadata, f)
ctx = InvokeCtx(metadata=Any[])
@test overdub(ctx, invoker, 3) === 9
# This is kind of fragile and may break for unrelated reasons - the main thing
# we're testing here is that we properly trace through the `invoke` call.
if VERSION < v"1.9"
@test ctx.metadata == Any[Core.apply_type, Core.invoke, Core.apply_type,
Val{2}, Core.apply_type, Base.literal_pow, *,
Base.mul_int]
end
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running Invoke2Ctx test...")
before_time = time()
# issue #89
invoked2(x::Int) = x + x
invoked2(x::Number, y=4) = x^2 + y
invoker2(x) = invoke(invoked2, Tuple{Number}, x)
@context Invoke2Ctx
Cassette.prehook(ctx::Invoke2Ctx, f, args...) = push!(ctx.metadata, f)
ctx = Invoke2Ctx(metadata=Any[])
@test overdub(ctx, invoker2, 3) === invoker2(3) === 13
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
# taken from https://stackoverflow.com/questions/52050262/how-to-do-memoization-or-memoisation-in-julia-1-0/52062639#52062639
print(" running MemoizeCtx test...")
before_time = time()
fib(x) = x < 3 ? 1 : fib(x - 2) + fib(x - 1)
fibtest(n) = fib(2 * n) + n
@context MemoizeCtx
function Cassette.overdub(ctx::MemoizeCtx, ::typeof(fib), x)
result = get(ctx.metadata, x, 0)
result === 0 && return recurse(ctx, fib, x)
return result
end
Cassette.posthook(ctx::MemoizeCtx, fibx, ::typeof(fib), x) = (ctx.metadata[x] = fibx)
ctx = MemoizeCtx(metadata = Dict{Int,Int}())
n = 10
result = Cassette.overdub(ctx, fibtest, n)
@test result == fibtest(n)
@test length(ctx.metadata) == 2 * n
@test all(fib(k) == v for (k, v) in ctx.metadata)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
# ref https://github.com/JuliaLabs/Cassette.jl/issues/73
if VERSION >= v"1.1-"
print(" running NoOpCtx test...")
before_time = time()
@context NoOpCtx
function loop73(x, n)
r = x / x
while n > 0
r *= sin(x)
n -= 1
end
return r
end
f73(x, n) = overdub(NoOpCtx(), loop73, x, n)
ff73(x, n) = overdub(NoOpCtx(), f73, x, n)
fff73(x, n) = overdub(NoOpCtx(), ff73, x, n)
f73(2, 50) # warm up
ff73(2, 50) # warm up
fff73(2, 50) # warm up
if VERSION < v"1.4"
@test @allocated(f73(2, 50)) == 0
@test @allocated(ff73(2, 50)) == 0
else
@test_broken @allocated(f73(2, 50)) == 0
@test_broken @allocated(ff73(2, 50)) == 0
end
@test_broken @allocated(fff73(2, 50)) == 0
println("done (took ", time() - before_time, " seconds)")
end
#############################################################################################
print(" running DisableHooksCtx test...")
before_time = time()
@context DisableHooksCtx
Cassette.prehook(ctx::DisableHooksCtx, args...) = ctx.metadata[1] += 1
Cassette.posthook(ctx::DisableHooksCtx, args...) = ctx.metadata[2] += 1
ctx = disablehooks(DisableHooksCtx(metadata = [0, 0]))
@test overdub(ctx, sin, 1.0) == sin(1.0)
@test all(ctx.metadata .== 0)
@test overdub(ctx, overdub, ctx, sin, 1.0) == sin(1.0)
@test all(ctx.metadata .== 0)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running SliceCtx test...")
before_time = time()
using Core: CodeInfo, SlotNumber, SSAValue
@context SliceCtx
function Cassette.overdub(ctx::SliceCtx, f, callback, args...)
if canrecurse(ctx, f, args...)
_ctx = similarcontext(ctx, metadata = callback)
return recurse(_ctx, f, args...) # return result, callback
else
return fallback(ctx, f, args...), callback
end
end
const global_test_cache = Any[]
push_to_global_test_cache!(x) = push!(global_test_cache, x)
function Cassette.overdub(ctx::SliceCtx, ::typeof(push_to_global_test_cache!), callback, x)
return nothing, () -> (callback(); push_to_global_test_cache!(x))
end
function sliceprintln(::Type{<:SliceCtx}, reflection::Cassette.Reflection)
ir = reflection.code_info
callbackslotname = gensym("callback")
push!(ir.slotnames, callbackslotname)
push!(ir.slotflags, 0x00)
callbackslot = SlotNumber(length(ir.slotnames))
getmetadata = Expr(:call, Expr(:nooverdub, GlobalRef(Core, :getfield)), Expr(:contextslot), QuoteNode(:metadata))
# insert the initial `callbackslot` assignment into the IR.
Cassette.insert_statements!(ir.code, ir.codelocs,
(stmt, i) -> i == 1 ? 2 : nothing,
(stmt, i) -> [Expr(:(=), callbackslot, getmetadata), stmt])
# replace all calls of the form `f(args...)` with `f(callback, args...)`, taking care to
# properly handle Core._apply calls and destructure the returned `(result, callback)`
# into the appropriate statements
Cassette.insert_statements!(ir.code, ir.codelocs,
(stmt, i) -> begin
i > 1 || return nothing # don't slice the callback assignment
stmt = Base.Meta.isexpr(stmt, :(=)) ? stmt.args[2] : stmt
if Base.Meta.isexpr(stmt, :call)
isapply = Cassette.is_ir_element(stmt.args[1], GlobalRef(Core, :_apply), ir.code) ||
Cassette.is_ir_element(stmt.args[1], GlobalRef(Core, :_apply_iterate), ir.code)
return 3 + isapply
end
return nothing
end,
(stmt, i) -> begin
items = Any[]
callstmt = Base.Meta.isexpr(stmt, :(=)) ? stmt.args[2] : stmt
callssa = SSAValue(i)
if Cassette.is_ir_element(callstmt.args[1], GlobalRef(Core, :_apply), ir.code)
push!(items, Expr(:call, Expr(:nooverdub, GlobalRef(Core, :tuple)), callbackslot))
push!(items, Expr(:call, callstmt.args[1], callstmt.args[2], SSAValue(i), callstmt.args[3:end]...))
callssa = SSAValue(i + 1)
elseif Cassette.is_ir_element(callstmt.args[1], GlobalRef(Core, :_apply_iterate), ir.code)
push!(items, Expr(:call, Expr(:nooverdub, GlobalRef(Core, :tuple)), callbackslot))
push!(items, Expr(:call, callstmt.args[1], callstmt.args[2], callstmt.args[3], SSAValue(i), callstmt.args[4:end]...))
callssa = SSAValue(i + 1)
else
push!(items, Expr(:call, callstmt.args[1], callbackslot, callstmt.args[2:end]...))
end
push!(items, Expr(:(=), callbackslot, Expr(:call, Expr(:nooverdub, GlobalRef(Core, :getfield)), callssa, 2)))
result = Expr(:call, Expr(:nooverdub, GlobalRef(Core, :getfield)), callssa, 1)
if Base.Meta.isexpr(stmt, :(=))
result = Expr(:(=), stmt.args[1], result)
end
push!(items, result)
return items
end)
# replace return statements of the form `return x` with `return (x, callback)`
@static if isdefined(Core, :ReturnNode)
Cassette.insert_statements!(ir.code, ir.codelocs,
(stmt, i) -> isa(stmt, Core.ReturnNode) ? 2 : nothing,
(stmt, i) -> begin
return [
Expr(:call, Expr(:nooverdub, GlobalRef(Core, :tuple)), stmt.val, callbackslot),
Core.ReturnNode(SSAValue(i))
]
end)
else
Cassette.insert_statements!(ir.code, ir.codelocs,
(stmt, i) -> Base.Meta.isexpr(stmt, :return) ? 2 : nothing,
(stmt, i) -> begin
return [
Expr(:call, Expr(:nooverdub, GlobalRef(Core, :tuple)), stmt.args[1], callbackslot),
Expr(:return, SSAValue(i))
]
end)
end
return ir
end
const sliceprintlnpass = Cassette.@pass sliceprintln
a = rand(3)
b = rand(3)
function add(a, b)
push_to_global_test_cache!(a)
push_to_global_test_cache!(b)
c = a + b
push_to_global_test_cache!(c)
return c
end
ctx = SliceCtx(pass=sliceprintlnpass, metadata = () -> nothing)
result, callback = Cassette.recurse(ctx, add, a, b)
@test result == a + b
@test isempty(global_test_cache)
callback()
@test global_test_cache == [a, b, result]
println("done (took ", time() - before_time, " seconds)")
# Test overdubbing of a call overload invoke
using LinearAlgebra
struct Dense{F,S,T}
W::S
b::T
σ::F
end
Dense(W, b) = Dense(W, b, identity)
function (a::Dense)(x::AbstractArray)
W, b, σ = a.W, a.b, a.σ
σ.(W*x .+ b)
end
function (a::Dense{<:Any,W})(x::AbstractArray{T}) where {T <: Union{Float32,Float64}, W <: AbstractArray{T}}
invoke(a, Tuple{AbstractArray}, x)
end
function (a::Dense{<:Any,W})(x::AbstractArray{<:Real}) where {T <: Union{Float32,Float64}, W <: AbstractArray{T}}
a(T.(x))
end
Cassette.@context CtxCallOverload;
let d = Dense(3,3)
data = rand(3)
Cassette.overdub(CtxCallOverload(), d, data)
end
#############################################################################################
print(" running OverdubOverdubCtx test...")
before_time = time()
# Fixed in PR #148
Cassette.@context OverdubOverdubCtx
overdub_overdub_me() = 2
Cassette.overdub(OverdubOverdubCtx(), Cassette.overdub, OverdubOverdubCtx(), overdub_overdub_me)
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running NukeCtx test...")
before_time = time()
@Cassette.context NukeContext
struct Silo; end
Base.iterate(x::Silo) = (println("Launching Nukes"); error("What's the point?"))
function Cassette.overdub(ctx::NukeContext, ::typeof(iterate), x::Silo)
nothing
end
@test Cassette.overdub(NukeContext(), iterate, Silo()) === nothing
launch(s::Silo) = (s...,)
# if VERSION >= v"1.4.0-DEV.304"
# @test Cassette.overdub(NukeContext(), launch, Silo()) === ()
# else
@test_broken Cassette.overdub(NukeContext(), launch, Silo()) === ()
# end
if VERSION >= v"1.4.0-DEV.304"
Cassette.@context ApplyIterateCtx;
const instructions = []
function Cassette.prehook(ctx::ApplyIterateCtx,
op::Any,
a::T1, b::T2) where {T1, T2}
push!(instructions, (op, T1, T2))
end
Cassette.overdub(ApplyIterateCtx(), ()->pi*2.0)
@test instructions[end] === (Core.Intrinsics.mul_float, Float64, Float64)
end
println("done (took ", time() - before_time, " seconds)")
#############################################################################################
print(" running NaNCtx test...")
before_time = time()
Cassette.@context NaNCtx;
Cassette.posthook(::NaNCtx, out::Number, f, args...) = isnan(out) ? error("$f$args returned $out") : nothing
checked(f, x...) = Cassette.overdub(NaNCtx(), f, x...)
@test_throws ErrorException checked() do
(() -> 0 / 0)()
end
bt = try
checked() do
(() -> 0 / 0)()
end
catch
Base.catch_backtrace()
end
s = sprint(Base.show_backtrace, bt)
@test occursin("/(::Float64, ::Float64)", s)
@test occursin("/(::$Int, ::$Int)", s)
# TODO
# if VERSION >= https://github.com/JuliaLang/julia/pull/40106
# @test occursin(r"\(::var\"#\d+#\d+\"\)\(\)", s)
# else
# @test_broken occursin(r"\(::var\"#\d+#\d+\"\)\(\)", s)
# end
println("done (took ", time() - before_time, " seconds)")
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 778 | using Pkg
using Test
testcode = raw"""
module MyPkg
using Cassette
Cassette.@context Ctx
const mypass = Cassette.@pass (ctx, ref) -> ref.code_info
end # module
"""
mktempdir() do dir
# for debugging use:
# let dir = mktempdir()
# @show dir
cd(dir) do
Pkg.generate("MyPkg")
open(joinpath("MyPkg", "src", "MyPkg.jl"), "w") do io
write(io, testcode)
end
Pkg.activate("MyPkg")
Pkg.develop(PackageSpec(path=joinpath(@__DIR__, ".."))) # add Cassette
run(pipeline(`$(Base.julia_cmd()) --project=./MyPkg -e "using MyPkg"`, stderr="errs.log"))
errs = read("errs.log", String)
@testset "Precompilation" begin
@test !occursin("WARNING: Method definition overdub", errs)
end
end
end
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 757 | using Test, Cassette, LinearAlgebra
using Cassette: @context, @pass, @overdub, overdub, recurse, hasmetadata,
metadata, hasmetameta, metameta, untag, tag, enabletagging,
untagtype, istagged, istaggedtype, Tagged, fallback, canrecurse,
similarcontext, disablehooks, iskwftype
println("running unit tests")
@time @testset "unit tests" begin include("unittests.jl") end
println("running misc. tests (w/o tagging)")
@time @testset "misc. tests (w/o tagging)" begin include("misctests.jl") end
println("running misc. tests (w/ tagging)")
@time @testset "misc. tests (w/ tagging)" begin include("misctaggingtests.jl") end
# note should always be last
println("running precompile test")
include("precompile.jl")
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | code | 2332 | # TODO: this file is pretty sparse...
using InteractiveUtils: subtypes
using Core.Compiler: SSAValue, Const, GotoNode
function const_bool_retval(f, sig)
ctyped = code_typed(f, sig)[1].first
retval = ctyped.code[end]
retval = isa(retval, GotoNode) ? ctyped.code[retval.label] : retval
@static if isdefined(Core, :ReturnNode)
retval = isa(retval, Core.ReturnNode) ? retval.val : retval
else
retval = Meta.isexpr(retval, :return) ? retval.args[1] : retval
end
retval = isa(retval, SSAValue) ? ctyped.ssavaluetypes[retval.id] : retval
retval = isa(retval, Const) ? retval.val : retval
isa(retval, Bool) && return retval
error("did not infer constant boolean return value for ", f, sig)
end
@context canrecurseTestCtx
ctx = canrecurseTestCtx()
# Test that the result value of `canrecurse` is inferred exactly for `T <: Core.Builtin`.
# Note that these aren't necessarily valid full call signatures, this is just
# testing that Cassette's `canrecurse` implementation has an inferrable
# short-circuiting `Core.Builtin` check.
for T in subtypes(Core.Builtin)
if !(T <: typeof(Core._apply))
@test !const_bool_retval(canrecurse, (typeof(ctx), T))
@test !const_bool_retval(canrecurse, (typeof(ctx), typeof(Core._apply), T))
@test !const_bool_retval(canrecurse, (typeof(ctx), typeof(Core.invoke), T))
end
end
@test canrecurse(ctx, hypot, 1, 2)
@test canrecurse(ctx, Core.invoke, hypot, Tuple{Int,Int}, 1, 2)
@test canrecurse(ctx, Core._apply, hypot, (1, 2))
@test canrecurse(ctx, Core._apply, Core.invoke, (hypot, Tuple{Int,Int}, 1, 2))
@static if isdefined(Core, :_apply_iterate)
@test canrecurse(ctx, Core._apply_iterate, Base.iterate, hypot, (1, 2))
@test canrecurse(ctx, Core._apply_iterate, Base.iterate, Core.invoke, (hypot, Tuple{Int,Int}, 1, 2))
end
###########
# Declaring a `@context` with the same name twice, should be a No-Op, not an error
# Code below will throw an error if this is not true
@context FooBar
@context FooBar
# Test keyword function detection
kwtest_1(; x) = x # Normal function
const kwtest_2 = (; x) -> x # Anonymous function
const kwtest_3 = let; (; x) -> x end # Closure
for n in 1:3
F = typeof(getfield(Main, Symbol(:kwtest_, n)))
@test iskwftype(Core.kwftype(F))
@test !iskwftype(F)
end
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 2927 | <p align="center">
<img width="350px" src="https://raw.githubusercontent.com/JuliaLabs/Cassette.jl/master/docs/img/cassette-logo.png"/>
</p>
[](https://zenodo.org/badge/latestdoi/86752121)
[](https://julia.mit.edu/Cassette.jl/stable/)
[](https://julia.mit.edu/Cassette.jl/dev/)
[](https://github.com/JuliaLabs/Cassette.jl/actions?query=workflow%3ACI)
[/badge.svg)](https://github.com/JuliaLabs/Cassette.jl/actions?query=workflow%3A%22CI+%28Julia+nightly%29%22)
[](https://codecov.io/gh/JuliaLabs/Cassette.jl)
## Overview
Cassette lets you easily extend the Julia language by directly injecting the Julia compiler with new, context-specific behaviors.
More technically, Cassette is a Julia package that provides a mechanism for dynamically injecting code transformation passes into Julia’s just-in-time (JIT) compilation cycle, enabling post hoc analysis and modification of "Cassette-unaware" Julia programs without requiring manual source annotation or refactoring of the target code.
Cassette's API is built upon the notion of user-definable execution contexts, which are represented as normal Julia types. Using Cassette, any normal Julia function can be invoked within an execution context via a process called "overdubbing". Cassette provides users with multiple ways to define the execution of code overdubbed with their context type. For example, Cassette's lowest level interface allows users to implement arbitrary `CodeInfo` transformations via normal Julia functions, and easily apply these transformations to overdubbed method bodies at compile-time. Cassette also provides a higher-level "contextual dispatch" interface that allows users to safely and quickly overload existing Julia methods with context-specific behaviors without ever needing to handle Julia’s IR directly.
On top of contextual pass injection and contextual dispatch, Cassette implements a system for "tagging" values with respect to a context, optionally attaching metadata to these tagged values (e.g. the value's derivative). Cassette can then automatically propagate these tagged values throughout target programs, even in the presence of structural and/or dispatch type constraints.
Downstream applications for Cassette include dynamic code analysis (e.g. profiling, rr-style debugging, etc.), JIT compilation to new hardware/software backends, automatic differentiation, interval constraint programming, automatic parallelization/rescheduling, automatic memoization, lightweight multistage programming, graph extraction, and more.
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 693 | # Cassette API Documentation
```@meta
CurrentModule = Cassette
```
```@docs
Cassette.Context
Cassette.similarcontext
Cassette.disablehooks
Cassette.enabletagging
Cassette.hastagging
Cassette.@context
```
```@docs
Cassette.overdub
Cassette.@overdub
Cassette.recurse
Cassette.prehook
Cassette.posthook
Cassette.fallback
Cassette.canrecurse
```
```@docs
Cassette.@pass
Cassette.replace_match!
Cassette.insert_statements!
Cassette.is_ir_element
Cassette.OVERDUB_CONTEXT_NAME
Cassette.OVERDUB_ARGUMENTS_NAME
Cassette.Reflection
```
```@docs
Cassette.tag
Cassette.untag
Cassette.untagtype
Cassette.metadata
Cassette.metadatatype
Cassette.hasmetadata
Cassette.istagged
Cassette.istaggedtype
```
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 8606 | # Contextual Dispatch
```@meta
CurrentModule = Cassette
```
In [the previous section](overdub.md), we saw how, within a given execution
trace, Cassette's `overdub` mechanism transforms every method invocation of the
form `f(args...)` into statements similar to the following:
```julia
begin
Cassette.prehook(context, f, args...)
%n = Cassette.overdub(context, f, args...)
Cassette.posthook(context, %n, f, args...)
%n
end
```
This transformation yields several extra points of overloadability in the form
of various Cassette methods, such as [`prehook`](@ref), [`posthook`](@ref), and
even [`overdub`](@ref) itself. Together, these methods form Cassette's
"contextual dispatch" interface, so-named because it enables an extra context
parameter to participate in what would normally be a simple dispatch to the
underlying method call.
In this section of the documentation, we'll go over these functions in a bit more detail.
To begin, let's define a simple contextual prehook by overloading the [`prehook`](@ref)
method w.r.t. to a dummy context:
```julia
julia> using Cassette
julia> Cassette.@context Ctx;
# this prehook implements simple trace logging for overdubbed functions
julia> Cassette.prehook(::Ctx, f, args...) = println(f, args)
julia> Cassette.overdub(Ctx(), /, 1, 2)
float(1,)
AbstractFloat(1,)
Float64(1,)
sitofp(Float64, 1)
float(2,)
AbstractFloat(2,)
Float64(2,)
sitofp(Float64, 2)
/(1.0, 2.0)
div_float(1.0, 2.0)
0.5
```
Cool beans!
Actually, there's a subtlety about `overdub` here that we should address before
moving on. Why wasn't the first line in the trace log `/(1, 2)`? If the answer
isn't obvious, recall the definition of `overdub` from the previous section. With
that definition in mind, it makes sense that `/(1, 2)` is not printed in the
above example, since `prehook(Ctx(), /, 1, 2)` is not actually ever called in
the above example. If this still seems confusing, compare the output from the
above example with the output generated via `overdub(Ctx(), () -> 1/2)`.
Moving on, let's make our `prehook` slightly more complicated for pedagogy's sake.
This time around, we'll only print calls whose first argument matches a
specific type. A nice configurable way to do this is as follows:
```julia
# reset our prehook fallback for `Ctx` to a no-op
julia> Cassette.prehook(::Ctx, f, args...) = nothing
# parameterize our prehook on the type of metadata stored in our context instance
julia> Cassette.prehook(::Ctx{Val{T}}, f, arg::T, rest...) where {T} = println(f, (arg, rest...))
# construct our context instance with metadata to configure the prehook
julia> Cassette.overdub(Ctx(metadata=Val(Int)), /, 1, 2)
float(1,)
AbstractFloat(1,)
Float64(1,)
float(2,)
AbstractFloat(2,)
Float64(2,)
0.5
julia> Cassette.overdub(Ctx(metadata=Val(DataType)), /, 1, 2)
sitofp(Float64, 1)
sitofp(Float64, 2)
0.5
```
Also of note is `prehook`'s long-lost cousin [`posthook`](@ref), with which `prehook` shares
many similarities. In fact, these functions are so similar that we won't be spending too much
time on `posthook` individually. The key difference between `prehook` and `posthook` is that
`posthook` runs *after* the overdubbed invocation is executed, such that it has access to the
output of the overdubbed invocation.
For example, here we use `posthook` and `prehook` together to accumulate a trace that
preserves nesting information:
```julia
using Cassette
Cassette.@context TraceCtx
mutable struct Trace
current::Vector{Any}
stack::Vector{Any}
Trace() = new(Any[], Any[])
end
function enter!(t::Trace, args...)
pair = args => Any[]
push!(t.current, pair)
push!(t.stack, t.current)
t.current = pair.second
return nothing
end
function exit!(t::Trace)
t.current = pop!(t.stack)
return nothing
end
Cassette.prehook(ctx::TraceCtx, args...) = enter!(ctx.metadata, args...)
Cassette.posthook(ctx::TraceCtx, args...) = exit!(ctx.metadata)
trace = Trace()
x, y, z = rand(3)
f(x, y, z) = x*y + y*z
Cassette.overdub(TraceCtx(metadata = trace), () -> f(x, y, z))
# returns `true`
trace.current == Any[
(f,x,y,z) => Any[
(*,x,y) => Any[(Base.mul_float,x,y)=>Any[]]
(*,y,z) => Any[(Base.mul_float,y,z)=>Any[]]
(+,x*y,y*z) => Any[(Base.add_float,x*y,y*z)=>Any[]]
]
]
```
Next, let's tackle the meatiest part of the contextual dispatch interface: contextual
primitives. A method invocation of the form `f(args...)` within a given context `Ctx`
is a primitive w.r.t. `Ctx` if `overdub(Ctx(), f, args...)` does not recursively
overdub the function calls comprising the invoked method's implementation.
There are two cases where `overdub(Ctx(), f, args...)` does not correspond to
recursively overdubbing `f`'s implementation:
1. `f(args...)` might be a built-in with no overdubbable Julia implementation (e.g. `getfield`), in which case `overdub(Ctx(), f, args...)` immediately redirects to `Cassette.fallback(Ctx(), f, args...)`.
2. `overdub` can be overloaded by the user such that `overdub(::Ctx, ::typeof(f), ...)` dispatches to a context-specific primitive definition.
If this definition isn't exactly intuitive, never fear - the concept of a
contextual primitive is more easily understood via examples. The simplest
example is to define a context that simply redirects all method call of a
specific type (let's say `sin(x)`) to a different method call of a specific
type (let's say `cos(x)`). This can be expressed as follows:
```julia
using Cassette, Test
Cassette.@context SinToCosCtx
# Override the default recursive `overdub` implementation for `sin(x)`.
# Note that there's no tricks here; this is just a normal Julia method
# overload using the normal multiple dispatch semantics.
Cassette.overdub(::SinToCosCtx, ::typeof(sin), x) = cos(x)
x = rand(10)
y = Cassette.overdub(SinToCosCtx(), sum, i -> cos(i) + sin(i), x)
@test y == sum(i -> 2 * cos(i), x)
```
Pretty nifty!
Here's a more motivating example. Below, we define a context that allows us to
memoize the computation of Fibonacci numbers (many thanks to the illustrious
Simon Byrne, [the original author of this example](https://stackoverflow.com/questions/52050262/how-to-do-memoization-or-memoisation-in-julia-1-0/52062639#52062639)):
```julia
using Cassette: Cassette, @context, overdub, recurse
fib(x) = x < 3 ? 1 : fib(x - 2) + fib(x - 1)
fibtest(n) = fib(2 * n) + n
@context MemoizeCtx
function Cassette.overdub(ctx::MemoizeCtx, ::typeof(fib), x)
result = get(ctx.metadata, x, 0)
if result === 0
result = recurse(ctx, fib, x)
ctx.metadata[x] = result
end
return result
end
```
Note that this example uses Cassette's [`recurse`](@ref) function. This function is
exactly equivalent to Cassette's default `overdub` implementation, but is not
meant to be overloaded by users, thus allowing one to recursively overdub
"through" invocations that might otherwise be contextual primitives.
We can do some toy performance tests to see that we get the expected speedup using this implementation (skipping the warm-up calls used to compile both functions):
```julia
julia> ctx = MemoizeCtx(metadata = Dict{Int,Int}());
julia> @time Cassette.overdub(ctx, fibtest, 20)
0.000011 seconds (8 allocations: 1.547 KiB)
102334175
julia> @time Cassette.overdub(ctx, fibtest, 20)
0.000006 seconds (5 allocations: 176 bytes)
102334175
julia> @time fibtest(20)
0.276069 seconds (5 allocations: 176 bytes)
102334175
```
!!! note
A bunch of reasonable default contextual primitives are generated automatically
upon context definition. It is possible, of course, to simply override these
defaults if necessary. For more details, see [`@context`](@ref).
Finally, to get a sense of the interaction between `recurse` and `overdub`, let's
reimplement our previous nested tracing example using recursion instead of maintaining
a stack:
```julia
using Cassette
Cassette.@context TraceCtx
function Cassette.overdub(ctx::TraceCtx, args...)
subtrace = Any[]
push!(ctx.metadata, args => subtrace)
if Cassette.canrecurse(ctx, args...)
newctx = Cassette.similarcontext(ctx, metadata = subtrace)
return Cassette.recurse(newctx, args...)
else
return Cassette.fallback(ctx, args...)
end
end
trace = Any[]
x, y, z = rand(3)
f(x, y, z) = x*y + y*z
Cassette.overdub(TraceCtx(metadata = trace), f, x, y, z)
# returns `true`
trace == Any[
(f,x,y,z) => Any[
(*,x,y) => Any[(Base.mul_float,x,y)=>Any[]]
(*,y,z) => Any[(Base.mul_float,y,z)=>Any[]]
(+,x*y,y*z) => Any[(Base.add_float,x*y,y*z)=>Any[]]
]
]
```
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 12162 | # Contextual Compiler Pass Injection
```@meta
CurrentModule = Cassette
```
In the previous section on [Cassette's overdubbing mechanism](overdub.md), we explored how
Cassette can automatically transform methods' lowered representation to insert a bunch of
statements around method calls encountered while overdubbing. In [the section that followed](contextualdispatch.md),
we discussed the result of this IR transformation: Cassette's contextual dispatch interface,
a suite of normal Julia methods that can be easily overloaded to perform the kinds of method
replacement and instrumentation that would otherwise require manually implemented compiler
passes.
Some use cases, however, require the ability to access and/or alter properties of the
execution trace that just can't be reached via simple method overloading, like control
flow or the surrounding scope of a method call. In these cases, you probably *do* want to
manually implement a compiler pass!
To facilitate these use cases, Cassette allows users to write and inject their own arbitrary
post-lowering, pre-inference compiler passes as part of the overdubbing process. This feature
of Cassette is called "contextual pass injection". As we did in the preceding sections,
we'll be using the classic "trial-by-fire" technique to better understand this feature.
Note that the following example was originally inspired by [JuliaLabs/Cassette.jl#66](https://github.com/JuliaLabs/Cassette.jl/issues/66).
Let's say you wanted to use Cassette to ["slice" various separable
subcomputations out from an overall computation](https://en.wikipedia.org/wiki/Program_slicing).
For a specific example, let's say you wanted to implement a tool that takes a
Julia function and strips out calls to `println` encountered in the trace. When
this function returns, we also want to return a callback that executes all the
`println` calls that we stripped out. How would you implement this with
Cassette?
Well, it's not too hard to achieve this via the contextual dispatch interface:
```julia
using Cassette
Cassette.@context Ctx
mutable struct Callback
f::Any
end
function Cassette.overdub(ctx::Ctx, ::typeof(println), args...)
previous = ctx.metadata.f
ctx.metadata.f = () -> (previous(); println(args...))
return nothing
end
```
We can check our implementation using the following test case:
```julia
julia> begin
a = rand(3)
b = rand(3)
function add(a, b)
println("I'm about to add $a + $b")
c = a + b
println("c = $c")
return c
end
add(a, b)
end
I'm about to add [0.457465, 0.62078, 0.954555] + [0.0791336, 0.744041, 0.976194]
c = [0.536599, 1.36482, 1.93075]
3-element Array{Float64,1}:
0.5365985032259399
1.3648210555868863
1.9307494378914405
julia> ctx = Ctx(metadata = Callback(() -> nothing));
julia> c = Cassette.overdub(ctx, add, a, b)
3-element Array{Float64,1}:
0.5365985032259399
1.3648210555868863
1.9307494378914405
julia> ctx.metadata.f()
I'm about to add [0.457465, 0.62078, 0.954555] + [0.0791336, 0.744041, 0.976194]
c = [0.536599, 1.36482, 1.93075]
```
This is pretty cool, but also a bit limited. First of all, what if we want to move more than
just `println` invocations into our callback, e.g. what if we want to slice the construction
of `println`'s arguments as well? Another potential issue is that this implementation
requires an explicit `Any` barrier, preventing the compiler from inferring callback
construction (note, however, that this does not prevent inferring *invocation* of the
callback). This is possibly desirable in some cases, since you're being easier on the
compiler, but what if you really wanted to expose Julia's type inference to callback
construction?
To resolve issues like these, we'll need to dig deeper than contextual dispatch and implement an
actual compiler pass. First, let's go over a high-level description of the pass we'll implement.
Essentially, we want this method:
```julia
function add(a, b)
println("I'm about to add $a + $b")
c = a + b
println("c = $c")
return c
end
```
...to become something akin to the following when overdubbed:
```julia
function overdub(ctx::Ctx, add, a, b)
_callback_ = ctx.metadata
_, _callback_ = overdub(ctx, println, _callback_, "I'm about to add $a + $b")
c, _callback_ = overdub(ctx, +, _callback_, a, b)
_, _callback_ = overdub(ctx, println, _callback_, "c = $c")
return c, _callback_
end
```
Note that I reduced a lot of the contextual dispatch boilerplate, such that the above is
essentially pseudocode.
Here, we can overload `Ctx`'s `overdub` method with the following definitions:
```julia
function Cassette.overdub(ctx::SliceCtx, f, callback, args...)
if Cassette.canrecurse(ctx, f, args...)
_ctx = Cassette.similarcontext(ctx, metadata = callback)
return Cassette.recurse(_ctx, f, args...) # return result, callback
else
return Cassette.fallback(ctx, f, args...), callback
end
end
function Cassette.overdub(ctx::SliceCtx, ::typeof(println), callback, args...)
return nothing, () -> (callback(); println(args...))
end
```
This, then, essentially accumulates the same closure we were accumulating before, but does so in a
way where...
- ...in theory, there is no longer any barrier to the inference of the closure construction.
- ...the pass itself determines the "capture region" manually, such that one could just alter it
to do e.g. linear dependence analysis to capture `println` argument construction code an arbitrary
number of degrees out from the actual `println` invocation.
Next, let's list the steps our compiler pass will actually need to perform in order to actually
accomplish the above:
- At the beginning of each method body, insert something like `_callback_ = context.metadata`
- Change every method invocation of the form `f(args...)` to `f(_callback_, args...)`.
- Change every return statement of the form `return x` to `return (x, _callback_)`
- Ensure the output of every method invocation is properly destructured into the original assignment slot/SSAValue and the `_callback_` slot.
Okay! Now that we have a high-level description of our pass, let's look at the code that implements
it. **I highly recommend reading the documentation for [`@pass`](@ref) and
[`insert_statements!`](@ref) before trying to understand this code**.
```julia
using Cassette
using Core: CodeInfo, SlotNumber, SSAValue, ReturnNode
Cassette.@context SliceCtx
function Cassette.overdub(ctx::SliceCtx, f, callback, args...)
if Cassette.canrecurse(ctx, f, args...)
_ctx = Cassette.similarcontext(ctx, metadata = callback)
return Cassette.recurse(_ctx, f, args...) # return result, callback
else
return Cassette.fallback(ctx, f, args...), callback
end
end
function Cassette.overdub(ctx::SliceCtx, ::typeof(println), callback, args...)
return nothing, () -> (callback(); println(args...))
end
function sliceprintln(::Type{<:SliceCtx}, reflection::Cassette.Reflection)
ir = reflection.code_info
callbackslotname = gensym("callback")
push!(ir.slotnames, callbackslotname)
push!(ir.slotflags, 0x00)
callbackslot = SlotNumber(length(ir.slotnames))
getmetadata = Expr(:call, Expr(:nooverdub, GlobalRef(Core, :getfield)), Expr(:contextslot), QuoteNode(:metadata))
# insert the initial `callbackslot` assignment into the IR.
Cassette.insert_statements!(ir.code, ir.codelocs,
(stmt, i) -> i == 1 ? 2 : nothing,
(stmt, i) -> [Expr(:(=), callbackslot, getmetadata), stmt])
# replace all calls of the form `f(args...)` with `f(callback, args...)`, taking care to
# properly handle Core._apply calls and destructure the returned `(result, callback)`
# into the appropriate statements
Cassette.insert_statements!(ir.code, ir.codelocs,
(stmt, i) -> begin
i > 1 || return nothing # don't slice the callback assignment
stmt = Base.Meta.isexpr(stmt, :(=)) ? stmt.args[2] : stmt
if Base.Meta.isexpr(stmt, :call)
isapply = Cassette.is_ir_element(stmt.args[1], GlobalRef(Core, :_apply_iterate), ir.code)
return 3 + isapply
end
return nothing
end,
(stmt, i) -> begin
items = Any[]
callstmt = Base.Meta.isexpr(stmt, :(=)) ? stmt.args[2] : stmt
callssa = SSAValue(i)
if Cassette.is_ir_element(callstmt.args[1], GlobalRef(Core, :_apply_iterate), ir.code)
push!(items, Expr(:call, Expr(:nooverdub, GlobalRef(Core, :tuple)), callbackslot))
push!(items, Expr(:call, callstmt.args[1:3]..., SSAValue(i), callstmt.args[4:end]...))
callssa = SSAValue(i + 1)
else
push!(items, Expr(:call, callstmt.args[1], callbackslot, callstmt.args[2:end]...))
end
push!(items, Expr(:(=), callbackslot, Expr(:call, Expr(:nooverdub, GlobalRef(Core, :getfield)), callssa, 2)))
result = Expr(:call, Expr(:nooverdub, GlobalRef(Core, :getfield)), callssa, 1)
if Base.Meta.isexpr(stmt, :(=))
result = Expr(:(=), stmt.args[1], result)
end
push!(items, result)
return items
end)
# replace return statements of the form `return x` with `return (x, callback)`
Cassette.insert_statements!(ir.code, ir.codelocs,
(stmt, i) -> isa(stmt, ReturnNode) ? 2 : nothing,
(stmt, i) -> begin
return [
Expr(:call, Expr(:nooverdub, GlobalRef(Core, :tuple)), stmt.val, callbackslot),
ReturnNode(SSAValue(i)),
]
end)
return ir
end
const sliceprintlnpass = Cassette.@pass sliceprintln
```
Here's how to invoke this new implementation on the above test case:
```julia
julia> begin
a = rand(3)
b = rand(3)
function add(a, b)
println("I'm about to add $a + $b")
c = a + b
println("c = $c")
return c
end
add(a, b)
end
I'm about to add [0.67915246284728, 0.2756120072191095, 0.11756215681978621] + [0.36694497827600103, 0.8528773638511087, 0.5911748231895997]
c = [1.046097441123281, 1.1284893710702182, 0.7087369800093859]
3-element Vector{Float64}:
1.046097441123281
1.1284893710702182
0.7087369800093859
julia> ctx = SliceCtx(pass=sliceprintlnpass, metadata = () -> nothing);
julia> result, callback = Cassette.@overdub(ctx, add(a, b))
([1.046097441123281, 1.1284893710702182, 0.7087369800093859], var"#2#3"{var"#2#3"{var"#16#17", Tuple{String}}, Tuple{String}}(var"#2#3"{var"#16#17", Tuple{String}}(var"#16#17"(), ("I'm about to add [0.67915246284728, 0.2756120072191095, 0.11756215681978621] + [0.36694497827600103, 0.8528773638511087, 0.5911748231895997]",)), ("c = [1.046097441123281, 1.1284893710702182, 0.7087369800093859]",)))
julia> callback()
I'm about to add [0.67915246284728, 0.2756120072191095, 0.11756215681978621] + [0.36694497827600103, 0.8528773638511087, 0.5911748231895997]
c = [1.046097441123281, 1.1284893710702182, 0.7087369800093859]
```
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 27 | Documentation Coming Soon!
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 2227 | # Disclaimers (Don't Say I Didn't Warn You)
Cassette can be a powerful tool for extending the Julia language, but it functions equally
well as a loaded foot-gun. Here are some things one should know before using Cassette:
- **Cassette, its API, and its documentation targets Julia package developers and/or those
interested in doing compiler research using Julia.** Cassette users are expected to have
a working understanding of Julia's compiler, type system and metaprogramming facilities.
- **Practical usage of Cassette will quite likely reveal both performance and correctness
bugs caused by either Cassette or Julia itself** (especially in this early stage of
development). This is especially likely when doing nested overdubbing, or composing
multiple Cassette contexts. Please file issues on the Cassette and/or Julia issue
tracker where appropriate.
- **The performance of Cassette's implementation of the contextual tagging system heavily
depends on compiler improvements planned for the Julia `1.x` release cycle.** In theory,
given these compiler improvements, the contextual tagging system could achieve
performance comparable to alternatives (e.g. ForwardDiff's dual number implementation),
but for now, the contextual tagging system is quite slow and allocation-heavy.
- Cassette enables interaction with many parts of the Julia compiler, a lot of which are
undocumented or sparsely documented. **It is extremely easy to accidentally implement a
pass that breaks internal compiler assumptions in some subtle way.** If (and when) you
run into these scenarios, it would be helpful to open an issue on the Julia issue tracker
proposing better documentation (or even a stable API) for a specific part of the
compiler.
- Due to limitations of Julia's current world-age mechanism, **Cassette exhibits a similar
recompilation problem to the famous
[JuliaLang/julia#265](https://github.com/JuliaLang/julia/issues/265)** (see
[JuliaLabs/Cassette.jl#6](https://github.com/JuliaLabs/Cassette.jl/issues/6) for details). In
order to resolve this issue, an update to Julia's world-age mechanism is planned for the
Julia `1.x` release cycle.
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 466 | # Introduction
Hello! Welcome to Cassette's documentation.
For an initial overview of Cassette, please see the
[README](https://github.com/JuliaLabs/Cassette.jl). Otherwise, feel free to peruse available
documentation via the sidebar.
It is recommended that all Cassette users read the documentation in its entirety. It is
**highly** recommended that all Cassette users *at least* read the
[Disclaimers](disclaimers.md) section before attempting to use Cassette.
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 5952 | # The Overdubbing Mechanism
```@meta
CurrentModule = Cassette
```
The central mechanism that drives Cassette usage is called the "overdubbing" mechanism.
A naive usage of this mechanism looks like this:
```julia
julia> using Cassette
julia> Cassette.@context Ctx;
julia> Cassette.overdub(Ctx(), /, 1, 2)
0.5
```
Okay - what did we actually just do here? From the output, it seems like we just computed
`1/2`...and indeed, we did! In reality, however, Cassette was doing a lot of work behind the
scenes during this seemingly simple calculation. Let's drill down further into this example
to see what's actually going on.
First, we define a new [`Context`](@ref) type alias called `Ctx` via the [`@context`](@ref)
macro. In practical usage, one normally defines one or more contexts specific to one's
application of Cassette. Here, we just made a dummy one for illustrative purposes. Contexts
are relatively simple to construct and understand, and are of central importance to Cassette's
operation. I recommend skimming the [`Context`](@ref) docstring before moving forward.
Next, we "overdubbed" a call to `1/2` w.r.t. `Ctx()` using the [`overdub`](@ref) function. To
get a sense of what that means, let's look at the lowered IR for the original call:
```julia
julia> @code_lowered 1/2
CodeInfo(
59 1 ─ %1 = (Base.float)(x)
│ %2 = (Base.float)(y)
│ %3 = %1 / %2
└── return %3
)
```
And now let's look at lowered IR for the call to `overdub(Ctx(), /, 1, 2)`
```julia
julia> @code_lowered Cassette.overdub(Ctx(), /, 1, 2)
CodeInfo(
59 1 ─ #self# = (Core.getfield)(##overdub_arguments#361, 1) │
│ x = (Core.getfield)(##overdub_arguments#361, 2) │
│ y = (Core.getfield)(##overdub_arguments#361, 3) │
│ (Cassette.prehook)(##overdub_context#360, Base.float, x) │
│ %5 = (Cassette.overdub)(##overdub_context#360, Base.float, x) │
│ (Cassette.posthook)(##overdub_context#360, %5, Base.float, x) │
│ %7 = %5 │
│ (Cassette.prehook)(##overdub_context#360, Base.float, y) │
│ %9 = (Cassette.overdub)(##overdub_context#360, Base.float, y) │
│ (Cassette.posthook)(##overdub_context#360, %9, Base.float, y) │
│ %11 = %9 │
│ (Cassette.prehook)(##overdub_context#360, Base.:/, %7, %11) │
│ %13 = (Cassette.overdub)(##overdub_context#360, Base.:/, %7, %11) │
│ (Cassette.posthook)(##overdub_context#360, %13, Base.:/, %7, %11) │
│ %15 = %13 │
└── return %15 │
)
```
There's obviously a lot more going on here than in the lowered IR for `1/2`, but if you
squint, you might notice that the overdubbed IR is actually the original IR with a special
transformation applied to it. Specifically, the overdubbed IR is the lowered IR for the given
function call with all internal method invocations of the form `f(args...)` replaced by
statements similar to the following:
```julia
begin
Cassette.prehook(context, f, args...)
%n = Cassette.overdub(context, f, args...)
Cassette.posthook(context, %n, f, args...)
%n
end
```
It is here that we experience our first bit of overdubbing magic: for every method call
in the overdubbed trace, we obtain several extra points of overloadability that we didn't
have before! In the [following section on contextual dispatch](contextualdispatch.md), we'll
explore how [`prehook`](@ref), [`posthook`](@ref), and even [`overdub`](@ref) itself can be
overloaded to add new contextual behaviors to overdubbed programs.
In the meantime, we should clarify how `overdub` is achieving this feat. Let's start by
examining a "pseudo-implementation" of `overdub`:
```julia
@generated function overdub(context::C, args...) where C<:Context
reflection = Cassette.reflect(args)
if isa(reflection, Cassette.Reflection)
Cassette.overdub_pass!(reflection, C)
return reflection.code_info
else
return :(Cassette.fallback(context, args...))
end
end
```
As you can see, `overdub` is a `@generated` function, and thus returns a method body
computed from the run-time types of its inputs. To actually compute this method body,
`overdub` is doing something quite special.
First, via `Cassette.reflect`, `overdub` asks Julia's compiler to provide it with a bunch of
information about the original method call as specified by `args`. The result of this query
is `reflection`, which is a [`Cassette.Reflection`](@ref) object if the compiler found lowered IR for
`args` and `nothing` otherwise (e.g. if `args` specifies a built-in call like `getfield`
whose implementation is not, itself, Julia code). For the former case, we execute a pass over
the `reflection` and the lowered IR stored within (`Cassette.overdub_pass!`) to perform the
previously presented transformation, returning the new lowered IR as a `CodeInfo` object.
Otherwise, if `reflection` is not a `Reflection` object, then no lowered IR is available, so
we simply call the context's [`fallback`](@ref) method (which, by default, simply calls the
provided function).
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 1304 | # Related Work
Cassette draws inspiration from a bunch of different work (in no particular order):
- Aspect-Oriented Programming: [https://en.wikipedia.org/wiki/Aspect-oriented_programming](https://en.wikipedia.org/wiki/Aspect-oriented_programming)
- XRay for LLVM: [https://ai.google/research/pubs/pub45287](https://ai.google/research/pubs/pub45287)
- Multimethods for C++: [http://www.stroustrup.com/multimethods.pdf](http://www.stroustrup.com/multimethods.pdf)
- Map-Closure for Scheme: [http://www.bcl.hamilton.ie/~qobi/map-closure/](http://www.bcl.hamilton.ie/~qobi/map-closure/)
- Stalingrad Compiler for VLAD: [https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1368&context=ecetr](https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1368&context=ecetr)
- Compiling to Categories for Haskell: [http://conal.net/papers/compiling-to-categories/](http://conal.net/papers/compiling-to-categories/)
- The Checker Framework for Java: [https://checkerframework.org/](https://checkerframework.org/)
- Context-Oriented Programming (this is not strictly what Cassette implements, despite the naming similarities): [http://www.jot.fm/issues/issue_2008_03/article4/](http://www.jot.fm/issues/issue_2008_03/article4/)
- Jameson Nash's Brain: [https://github.com/vtjnash](https://github.com/vtjnash)
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 0.3.13 | 0970356c3bb9113309c74c27c87083cf9c73880a | docs | 2665 | # Why Cassette?
Due to its multiple dispatch, method overloading and metaprogramming capabilities, Julia has turned out to be a great language for implementing various forms of "nonstandard execution", enabling generically-written Julia programs to be executed with new features simply by passing new types through the code. Of course, many other languages allow this kind of polymorphism, but Julia is unique in its ability to facilitate these kinds of techniques with surprising elegance and performance. These key advantages have attracted thriving, state-of-the-art Julia implementations of numerical computing tools in regimes such as mathematical optimization and parallel programming.
Over time, however, these amazing Julia tools have run up against the boundaries of purely overloading-based approaches to nonstandard execution. Cassette is an attempt to push these boundaries by giving Julia package developers the ability to fundamentally extend the language for their own purposes.
Here are some specific limitations that might be overcome by using Cassette:
- Overloading-based approaches to nonstandard execution are ultimately thwarted by dispatch and/or structural type constraints in non-generic target programs.
- Proper usage of overloading-based nonstandard execution tools require proper genericity criteria, i.e. answering "what weird subset of Julia do I really support?". These criteria are often difficult to correctly define and test against for both experienced developers and end-users.
- Not all relevant Julia language mechanisms are fully exposed/interceptable via method overloading (e.g. control flow, literals, bindings). Additionally, many different compiler passes require access to a wider scope of information than is locally available at individual method callsites (e.g. graph-based transformations).
- It is often difficult to fully resolve the kinds of ambiguities that naturally result from the composition of several multiple-dispatch-based tools. Brute-force solutions end up generating an excessive number of methods and are often either code-load-order dependent or incomplete (or even both). Julia's promotion mechanism resolves this problem when the involved types are efficiently convertible to one another, but this is not often the case in practice (e.g. subtypes of `AbstractArray`).
# No, why the *name* "Cassette"?
Cassette was originally motivated by the need for better language-level support for automatic differentiation, where the data structure used to accumulate program traces is often called a "tape" (since, of course, program traces really *were* stored on magnetic tapes back in the day).
| Cassette | https://github.com/JuliaLabs/Cassette.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1418 | ## header to provide surface and context
using Cairo
using Colors
c = CairoRGBSurface(256,256)
cr = CairoContext(c)
save(cr)
z = Array{RGB24}(undef, 2, 2)
c1 = convert(RGB24,colorant"grey20")
c2 = convert(RGB24,colorant"grey80")
z[1,1] = c1
z[1,2] = c2
z[2,1] = c2
z[2,2] = c1
img = CairoImageSurface(z)
pattern = CairoPattern(img)
pattern_set_extend(pattern, Cairo.EXTEND_REPEAT)
pattern_set_filter(pattern, Cairo.FILTER_BILINEAR)
m = CairoMatrix(1/8.0,0,0,1/8.0,0,0)
set_matrix(pattern, m)
set_source(cr, pattern)
paint(cr)
restore(cr)
save(cr)
# 5 uses of set_source
# color
save(cr)
rectangle(cr,16,32,224,32)
set_source(cr, colorant"red4")
fill(cr)
restore(cr)
# color with alpha
save(cr)
rectangle(cr,16,72,224,32)
set_source(cr, alphacolor(colorant"blue",0.5))
fill(cr)
restore(cr)
# image from surface
save(cr)
rectangle(cr,16,112,224,32)
clip(cr)
new_path(cr)
s = read_from_png("data/mulberry.png")
set_source(cr,s)
paint_with_alpha(cr,0.6)
restore(cr)
# image from context (from surface)
save(cr)
rectangle(cr,16,152,224,32)
clip(cr)
new_path(cr)
set_source(cr,creategc(s))
paint(cr)
restore(cr)
# image for surface with offset
save(cr)
rectangle(cr,16,192,224,32)
clip(cr)
set_source(cr,s,0.0,40.0)
paint(cr)
restore(cr)
## mark picture with current date
restore(cr)
move_to(cr,0.0,12.0)
set_source_rgb(cr, 0,0,0)
show_text(cr,Libc.strftime(time()))
write_to_png(c,"sample_alpha_paint.png")
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 910 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
## original example, following here
xc = 128.0;
yc = 128.0;
radius = 100.0;
angle1 = 45.0 * (pi/180.0); # angles are specified
angle2 = 180.0 * (pi/180.0); # in radians
set_line_width(cr, 10.0);
arc(cr, xc, yc, radius, angle1, angle2);
stroke(cr);
# draw helping lines
set_source_rgba(cr, 1, 0.2, 0.2, 0.6);
set_line_width(cr, 6.0);
arc(cr, xc, yc, 10.0, 0, 2*pi);
fill(cr);
arc(cr, xc, yc, radius, angle1, angle1);
line_to(cr, xc, yc);
arc(cr, xc, yc, radius, angle2, angle2);
line_to(cr, xc, yc);
stroke(cr);
## mark picture with current date
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_arc.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 927 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
## original example, following here
xc = 128.0;
yc = 128.0;
radius = 100.0;
angle1 = 45.0 * (pi/180.0); # angles are specified
angle2 = 180.0 * (pi/180.0); # in radians
set_line_width(cr, 10.0);
arc_negative(cr, xc, yc, radius, angle1, angle2);
stroke(cr);
# draw helping lines
set_source_rgba(cr, 1, 0.2, 0.2, 0.6);
set_line_width(cr, 6.0);
arc(cr, xc, yc, 10.0, 0, 2*pi);
fill(cr);
arc(cr, xc, yc, radius, angle1, angle1);
line_to(cr, xc, yc);
arc(cr, xc, yc, radius, angle2, angle2);
line_to(cr, xc, yc);
stroke(cr);
## mark picture with current date
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_arc_negative.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 756 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
arc(cr, 128.0, 128.0, 76.8, 0, 2 * pi);
clip(cr);
new_path(cr); # current path is not consumed by cairo_clip()
rectangle(cr, 0, 0, 256, 256);
fill(cr);
set_source_rgb(cr, 0, 1, 0);
move_to(cr, 0, 0);
line_to(cr, 256, 256);
move_to(cr, 256, 0);
line_to(cr, 0, 256);
set_line_width(cr, 10.0);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_clip.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 775 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
arc(cr, 128.0, 128.0, 76.8, 0, 2*pi);
clip(cr);
new_path(cr); # path not consumed by clip
image = read_from_png("data/mulberry.png"); # should be create_from_png
w = image.width;
h = image.height;
scale(cr, 256.0/w, 256.0/h);
set_source_surface(cr, image, 0, 0);
paint(cr);
#cairo_surface_destroy not used here
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_clip_image.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1744 | using Cairo
function common_header()
## header to provide surface and context
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
return c,cr
end
function write_out_picture(filename::AbstractString,c::CairoSurface)
## mark picture with current date
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
##
write_to_png(c,filename);
nothing
end
function example_copy_path(cr)
save(cr);
# single (large) character set with text_path+stroke
select_font_face(cr, "Sans", Cairo.FONT_SLANT_NORMAL,
Cairo.FONT_WEIGHT_BOLD);
set_font_size(cr, 100.0);
translate(cr, 10.0, 100.0);
text_path(cr, "J");
stroke_preserve(cr);
# copied and converted
opath = Cairo.convert_cairo_path_data(Cairo.copy_path(cr));
restore(cr);
l = 2 # something like a line counter
# loop over all entries and just print out command and available points
for x in opath
if x.element_type == Cairo.CAIRO_PATH_MOVE_TO
s0 = "moveto"
elseif x.element_type == Cairo.CAIRO_PATH_LINE_TO
s0 = "lineto"
elseif x.element_type == Cairo.CAIRO_PATH_CURVE_TO
s0 = "curveto"
elseif x.element_type == Cairo.CAIRO_PATH_CLOSE_PATH
s0 = "closepath"
end
s1 = repr(x.points)
move_to(cr,100.0,14.0*l)
l += 1
show_text(cr,s0*s1)
end
nothing
end
c,cr = common_header();
save(cr);
example_copy_path(cr);
restore(cr);
write_out_picture("sample_copy_path.png",c);
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1803 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256)
cr = CairoContext(c)
save(cr)
set_source_rgb(cr,0.8,0.8,0.8) # light gray
rectangle(cr,0.0,0.0,256.0,256.0) # background
fill(cr)
restore(cr)
save(cr)
## original example, following here
move_to(cr, 16.0, 32.0)
curve_to(cr, 16.0, 16.0, 16.0, 16.0, 32.0, 16.0)
opath = Cairo.convert_cairo_path_data(Cairo.copy_path(cr))
dx,dy,ex,ey = path_extents(cr)
fpath = Cairo.convert_cairo_path_data(Cairo.copy_path_flat(cr))
stroke(cr)
restore(cr)
l = 2 # something like a line counter
# loop over all entries and just print out command and available points
for x in opath
if x.element_type == Cairo.CAIRO_PATH_MOVE_TO
s0 = "moveto"
elseif x.element_type == Cairo.CAIRO_PATH_LINE_TO
s0 = "lineto"
elseif x.element_type == Cairo.CAIRO_PATH_CURVE_TO
s0 = "curveto"
elseif x.element_type == Cairo.CAIRO_PATH_CLOSE_PATH
s0 = "closepath"
end
s1 = repr(x.points)
move_to(cr,10.0,16.0+(14.0*l))
global l += 1
show_text(cr,s0*s1)
end
l = 2 # something like a line counter
# loop over all entries and just print out command and available points
for x in fpath
if x.element_type == Cairo.CAIRO_PATH_MOVE_TO
s0 = "moveto"
elseif x.element_type == Cairo.CAIRO_PATH_LINE_TO
s0 = "lineto"
elseif x.element_type == Cairo.CAIRO_PATH_CURVE_TO
s0 = "curveto"
elseif x.element_type == Cairo.CAIRO_PATH_CLOSE_PATH
s0 = "closepath"
end
s1 = repr(x.points)
move_to(cr,10.0,50.0+(14.0*l))
global l += 1
show_text(cr,s0*s1)
end
## mark picture with current date
restore(cr)
move_to(cr,0.0,12.0)
set_source_rgb(cr, 0,0,0)
show_text(cr,Libc.strftime(time()))
write_to_png(c,"sample_copy_path_flat.png")
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1214 | using Cairo
function common_header()
## header to provide surface and context
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
return c,cr
end
function write_out_picture(filename::AbstractString,c::CairoSurface)
## mark picture with current date
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
##
write_to_png(c,filename);
nothing
end
function example_current_point(cr)
save(cr);
x=25.6; y=128.0;
x1=102.4; y1=30.4;
x2=123.6; y2=45.6;
x3=130.4; y3=128.0;
move_to(cr, x, y);
curve_to(cr, x1, y1, x2, y2, x3, y3);
if has_current_point(cr)
x,y = get_current_point(cr);
save(cr)
move_to(cr,x,y)
set_source_rgb(cr, 0,0,1.0);
show_text(cr,"current point")
restore(cr)
end
set_line_width(cr, 10.0);
stroke(cr);
restore(cr);
save(cr);
nothing
end
c,cr = common_header();
save(cr);
example_current_point(cr);
restore(cr);
write_out_picture("sample_current_point.png",c);
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 2583 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
# custom shape wrapped in a function
function shape_curve_rectangle(cr::CairoContext,x0::Real,y0::Real,
rect_width::Real, rect_height::Real, radius::Real)
save(cr);
x1=x0+rect_width;
y1=y0+rect_height;
if (rect_width == 0 || rect_height == 0)
return;
end
if (rect_width/2 < radius)
if (rect_height/2 < radius)
move_to(cr, x0, (y0 + y1)/2);
curve_to(cr, x0 ,y0, x0, y0, (x0 + x1)/2, y0);
curve_to(cr, x1, y0, x1, y0, x1, (y0 + y1)/2);
curve_to(cr, x1, y1, x1, y1, (x1 + x0)/2, y1);
curve_to(cr, x0, y1, x0, y1, x0, (y0 + y1)/2);
else
move_to(cr, x0, y0 + radius);
curve_to(cr, x0 ,y0, x0, y0, (x0 + x1)/2, y0);
curve_to(cr, x1, y0, x1, y0, x1, y0 + radius);
line_to(cr, x1 , y1 - radius);
curve_to(cr, x1, y1, x1, y1, (x1 + x0)/2, y1);
curve_to(cr, x0, y1, x0, y1, x0, y1- radius);
end
else
if (rect_height/2 < radius)
move_to(cr, x0, (y0 + y1)/2);
curve_to(cr, x0 , y0, x0 , y0, x0 + radius, y0);
line_to(cr, x1 - radius, y0);
curve_to(cr, x1, y0, x1, y0, x1, (y0 + y1)/2);
curve_to(cr, x1, y1, x1, y1, x1 - radius, y1);
line_to(cr, x0 + radius, y1);
curve_to(cr, x0, y1, x0, y1, x0, (y0 + y1)/2);
else
move_to(cr, x0, y0 + radius);
curve_to(cr, x0 , y0, x0 , y0, x0 + radius, y0);
line_to(cr, x1 - radius, y0);
curve_to(cr, x1, y0, x1, y0, x1, y0 + radius);
line_to(cr, x1 , y1 - radius);
curve_to(cr, x1, y1, x1, y1, x1 - radius, y1);
line_to(cr, x0 + radius, y1);
curve_to(cr, x0, y1, x0, y1, x0, y1- radius);
end
end
close_path(cr);
set_source_rgb(cr, 0.5, 0.5, 1);
fill_preserve(cr);
set_source_rgba(cr, 0.5, 0, 0, 0.5);
set_line_width(cr, 10.0);
stroke(cr);
restore(cr);
return;
end
shape_curve_rectangle(cr,25.6,25.6,204.8,204.8,102.4);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_curve_rectangle.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 784 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
x=25.6; y=128.0;
x1=102.4; y1=230.4;
x2=153.6; y2=25.6;
x3=230.4; y3=128.0;
move_to(cr, x, y);
curve_to(cr, x1, y1, x2, y2, x3, y3);
set_line_width(cr, 10.0);
stroke(cr);
set_source_rgba(cr, 1, 0.2, 0.2, 0.6);
set_line_width(cr, 6.0);
move_to(cr,x,y); line_to(cr,x1,y1);
move_to(cr,x2,y2); line_to(cr,x3,y3);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_curve_to.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 849 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
dashes = [50.0, # ink
10.0, # skip
10.0, # ink
10.0 # skip
];
#ndash = length(dashes); not implemented as ndash on set_dash
offset = -50.0;
set_dash(cr, dashes, offset);
set_line_width(cr, 10.0);
move_to(cr, 128.0, 25.6);
line_to(cr, 230.4, 230.4);
rel_line_to(cr, -102.4, 0.0);
curve_to(cr, 51.2, 230.4, 51.2, 128.0, 128.0, 128.0);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_dash.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 864 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
move_to(cr, 128.0, 25.6);
line_to(cr, 230.4, 230.4);
rel_line_to(cr, -102.4, 0.0);
curve_to(cr, 51.2, 230.4, 51.2, 128.0, 128.0, 128.0);
close_path(cr);
move_to(cr, 64.0, 25.6);
rel_line_to(cr, 51.2, 51.2);
rel_line_to(cr, -51.2, 51.2);
rel_line_to(cr, -51.2, -51.2);
close_path(cr);
set_line_width(cr, 10.0);
set_source_rgb(cr, 0, 0, 1);
fill_preserve(cr);
set_source_rgb(cr, 0, 0, 0);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_fill_and_stroke2.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1094 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
set_line_width(cr, 6);
rectangle(cr, 12, 12, 232, 70);
new_sub_path(cr); arc(cr, 64, 64, 40, 0, 2*pi);
new_sub_path(cr); arc_negative(cr, 192, 64, 40, 0, -2*pi);
set_fill_type(cr, Cairo.CAIRO_FILL_RULE_EVEN_ODD); # should be set_fill_rule
set_source_rgb(cr, 0, 0.7, 0); fill_preserve(cr);
set_source_rgb(cr, 0, 0, 0); stroke(cr);
translate(cr, 0, 128);
rectangle(cr, 12, 12, 232, 70);
new_sub_path(cr); arc(cr, 64, 64, 40, 0, 2*pi);
new_sub_path(cr); arc_negative(cr, 192, 64, 40, 0, -2*pi);
set_fill_type(cr, Cairo.CAIRO_FILL_RULE_WINDING);
set_source_rgb(cr, 0, 0, 0.9); fill_preserve(cr);
set_source_rgb(cr, 0, 0, 0); stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_fill_style.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 987 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
pat = pattern_create_linear(0.0, 0.0, 0.0, 256.0);
pattern_add_color_stop_rgb(pat, 1, 0, 0, 0); # alpha=1
pattern_add_color_stop_rgb(pat, 0, 1, 1, 1);
rectangle(cr, 0, 0, 256, 256);
set_source(cr, pat);
fill(cr);
destroy(pat);
pat = pattern_create_radial(115.2, 102.4, 25.6,
102.4, 102.4, 128.0);
pattern_add_color_stop_rgba(pat, 0, 1, 1, 1, 1); # explicit alpha=1
pattern_add_color_stop_rgba(pat, 1, 0, 0, 0, 1);
set_source(cr, pat);
arc(cr, 128.0, 128.0, 76.8, 0, 2 * pi);
fill(cr);
destroy(pat);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_gradient.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 722 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
image = read_from_png("data/mulberry.png");
w = image.width;
h = image.height;
translate(cr, 128.0, 128.0);
rotate(cr, 45* pi/180);
scale(cr, 256.0/w, 256.0/h);
translate(cr, -0.5*w, -0.5*h);
set_source_surface(cr, image, 0, 0);
paint(cr);
#surface_destroy (image);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_image.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 900 | ## header to provide surface and context
using Cairo
using Graphics
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
# put image top left
s = read_from_png("data/mulberry.png");
Cairo.image(cr,s,0,0,128,128)
# copy inplace, so to apply copy as source, need coordinate translate
c1 = copy(cr)
save(cr)
translate(cr,128,0)
rectangle(cr,0,0,256,256)
set_source_surface(cr,c1.surface)
paint(cr)
restore(cr)
# copy centered part
c2 = copy(cr,Graphics.BoundingBox(64,192,0,128))
save(cr)
rectangle(cr,0,0,256,256)
set_source_surface(cr,c2.surface,64,128)
paint(cr)
restore(cr)
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_image_copy.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 950 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
image = read_from_png("data/mulberry.png");
w = image.width;
h = image.height;
pattern = CairoPattern(image);
pattern_set_extend(pattern, Cairo.EXTEND_REPEAT);
translate(cr, 128.0, 128.0);
rotate(cr, pi / 4);
scale(cr, 1 / sqrt(2), 1 / sqrt(2));
translate(cr, -128.0, -128.0);
m = CairoMatrix(w/256.0 * 5.0,0,0,h/256.0 * 5.0,0,0);
#matrix_init_scale (&matrix, w/256.0 * 5.0, h/256.0 * 5.0);
set_matrix(pattern, m);
set_source(cr, pattern);
rectangle(cr, 0, 0, 256.0, 256.0);
fill(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_imagepattern.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1656 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
# example, following here
inline_png2 = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00d\x00\x00\x00d\x08\x02\x00\x00\x00\xff\x80\x02\x03\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x01=IDATx\x9c\xed\xdc\xc1i\x85@\x14@\xd1IH!\x96bi\x96f)\x96\x92E@!\x01\x7f\xeeF\xfdp\xce\xca\x9d\xc3\xe5\xb9{\xce\xc7\xb2,\x83\xff\xf9\xbc\xfb\x00\xefD\xac@\xac@\xac@\xac@\xac@\xac@\xac@\xac\xe0\xeb\xee\x03\xfc\xb1\xaec]\xc7\x18c\x9e\xc7<\xdf{\x96_LV V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V\xf0j[\xf9gq\xf8J\xdbv<\\\xff\xf6\xd3\xfd\xe8\xe7\xc5\xdam\xdb\x11\xee2\xa7\xb1|\x86\xc1\xab\xc9\xba~m\x7f\x1f\xa8i\x1a\xd3t\xf5\xdbO=/\xd6\xba\x1e\xb1\xfca\xf1\xbe\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\xc4\n\x9ew\x1f\xfc\xf3\xae\x81\xdf\x99\xac@\xac@\xac@\xac@\xac@\xac@\xac@\xac@\xac\xe0\x1b\xaf\xef\x1c\xd4\x17\xfe\xcaX\x00\x00\x00\x00IEND\xaeB`\x82"
png_stream = IOBuffer();
write(png_stream,inline_png2);
seekstart(png_stream);
imagesurface = read_from_png(png_stream);
set_source_surface(cr, imagesurface, 0, 0);
paint(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_imagestream.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 2032 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, taken from cairo/test/pattern-mesh.c
function draw(cr, width::Int, height::Int)
PAT_WIDTH = 170
PAT_HEIGHT = 170
SIZE = PAT_WIDTH
PAD = 2
WIDTH = (PAD + SIZE + PAD)
HEIGHT = WIDTH
pattern = CairoPatternMesh();
#cairo_test_paint_checkered (cr); ?
translate(cr, PAD, PAD);
translate(cr, 10, 10);
mesh_pattern_begin_patch(pattern);
mesh_pattern_move_to(pattern, 0, 0);
mesh_pattern_curve_to(pattern, 30, -30, 60, 30, 100, 0);
mesh_pattern_curve_to(pattern, 60, 30, 130, 60, 100, 100);
mesh_pattern_curve_to(pattern, 60, 70, 30, 130, 0, 100);
mesh_pattern_curve_to(pattern, 30, 70, -30, 30, 0, 0);
mesh_pattern_set_corner_color_rgb(pattern, 0, 1, 0, 0);
mesh_pattern_set_corner_color_rgb(pattern, 1, 0, 1, 0);
mesh_pattern_set_corner_color_rgb(pattern, 2, 0, 0, 1);
mesh_pattern_set_corner_color_rgb(pattern, 3, 1, 1, 0);
mesh_pattern_end_patch(pattern);
mesh_pattern_begin_patch(pattern);
mesh_pattern_move_to(pattern, 50, 50);
mesh_pattern_curve_to(pattern, 80, 20, 110, 80, 150, 50);
mesh_pattern_curve_to(pattern, 110, 80, 180, 110, 150, 150);
mesh_pattern_curve_to(pattern, 110, 120, 80, 180, 50, 150);
mesh_pattern_curve_to(pattern, 80, 120, 20, 80, 50, 50);
mesh_pattern_set_corner_color_rgba(pattern, 0, 1, 0, 0, 0.3);
mesh_pattern_set_corner_color_rgb(pattern, 1, 0, 1, 0);
mesh_pattern_set_corner_color_rgba(pattern, 2, 0, 0, 1, 0.3);
mesh_pattern_set_corner_color_rgb(pattern, 3, 1, 1, 0);
mesh_pattern_end_patch(pattern);
set_source(cr, pattern);
paint(cr);
#pattern_destroy (pattern);
end
draw(cr,170,170);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_meshpattern.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 710 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
move_to(cr, 50.0, 75.0);
line_to(cr, 200.0, 75.0);
move_to(cr, 50.0, 125.0);
line_to(cr, 200.0, 125.0);
move_to(cr, 50.0, 175.0);
line_to(cr, 200.0, 175.0);
set_line_width(cr, 30.0);
set_line_cap(cr, Cairo.CAIRO_LINE_CAP_ROUND);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_multi_segment_caps.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 2153 | ## header to provide surface and context
using Cairo
c = CairoARGBSurface(512,512);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,512.0,512.0); # background
fill(cr);
restore(cr);
save(cr);
function operator_demo(operator_index)
c = CairoARGBSurface(126,98);
cr = CairoContext(c);
operators = [
(Cairo.OPERATOR_CLEAR,"OPERATOR_CLEAR"),
(Cairo.OPERATOR_SOURCE,"OPERATOR_SOURCE"),
(Cairo.OPERATOR_OVER,"OPERATOR_OVER"),
(Cairo.OPERATOR_IN,"OPERATOR_IN"),
(Cairo.OPERATOR_OUT,"OPERATOR_OUT"),
(Cairo.OPERATOR_ATOP,"OPERATOR_ATOP"),
(Cairo.OPERATOR_DEST,"OPERATOR_DEST"),
(Cairo.OPERATOR_DEST_OVER,"OPERATOR_DEST_OVER"),
(Cairo.OPERATOR_DEST_IN,"OPERATOR_DEST_IN"),
(Cairo.OPERATOR_DEST_OUT,"OPERATOR_DEST_OUT"),
(Cairo.OPERATOR_DEST_ATOP,"OPERATOR_DEST_ATOP"),
(Cairo.OPERATOR_XOR,"OPERATOR_XOR"),
(Cairo.OPERATOR_ADD,"OPERATOR_ADD"),
(Cairo.OPERATOR_SATURATE,"OPERATOR_SATURATE"),
(Cairo.OPERATOR_MULTIPLY,"OPERATOR_MULTIPLY"),
(Cairo.OPERATOR_SCREEN,"OPERATOR_SCREEN"),
(Cairo.OPERATOR_OVERLAY,"OPERATOR_OVERLAY"),
(Cairo.OPERATOR_DARKEN,"OPERATOR_DARKEN"),
(Cairo.OPERATOR_LIGHTEN,"OPERATOR_LIGHTEN")]
save(cr)
set_source_rgb(cr, 0.9, 0.9, 0.9)
paint(cr);
save(cr)
scale(cr,6,6)
rectangle(cr, 0, 5, 12, 9)
set_source_rgba(cr, 0.7, 0, 0, 0.8)
fill(cr)
set_operator(cr, operators[operator_index][1])
rectangle(cr, 4, 2, 12, 9)
set_source_rgba(cr, 0, 0, 0.9, 0.4)
fill(cr)
local_operator = get_operator(cr)
restore(cr)
move_to(cr,0,10)
set_source_rgb(cr, 0,0,0)
show_text(cr,operators[local_operator+1][2])
restore(cr)
c
end
for k=1:19
save(cr)
translate(cr,6+(128*mod(k-1,4)),24+(100*div(k-1,4)))
set_source(cr,operator_demo(k))
paint(cr)
restore(cr)
end
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_operators.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 961 | ## header to provide surface and context
using Cairo
using Printf
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
set_font_face(cr, "Sans 16")
text(cr,16.0,40.0,"Hamburgefons")
text(cr,16.0,72.0,"sp⁰¹²³,min⁻²,αΑβΒφϕΦγΓ")
text(cr,16.0,104.0,"Text<b>Bold</b><i>Italic</i><sup>super-2</sup>",markup=true)
text(cr,40.0,224.0,"Es geht <span foreground=\"white\" background=\"blue\">aufwärts</span> !",markup=true,angle=30.0)
#using textwidth and height
set_font_face(cr, "Sans 12")
a = "A"
aheight = textheight(cr,a)
awidth = textwidth(cr,a)
atext = @sprintf("%s wd=%2.2f,ht=%2.2f",a,awidth,aheight)
text(cr,16.0,240.0,atext,markup=true)
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_pango_text.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 838 | ## header to provide surface and context
using Cairo
using Printf
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
set_font_face(cr, "Sans 16")
text(cr,40.0,40.0,"E<span foreground=\"white\" background=\"blue\">F</span>",markup=true)
text(cr,40.0,60.0,"EGDC")
text(cr,40.0,90.0,"<span foreground=\"white\" background=\"red\">E</span>FGH",markup=true)
text(cr,40.0,110.0,"EGDC",markup=true)
text(cr,40.0,140.0,"G<span foreground=\"white\" background=\"green4\">E</span>FJ",markup=true)
text(cr,40.0,160.0,"EGDC")
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_pango_text1.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 994 | ## header to provide surface and context
using Cairo
c = CairoARGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgba(cr,0.0,0.0,0.0,0.0); # transparent black
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
s1 = CairoRecordingSurface()
c1 = CairoContext(s1)
## original example, following here
move_to(c1, 128.0, 25.6);
line_to(c1, 230.4, 230.4);
rel_line_to(c1, -102.4, 0.0);
curve_to(c1, 51.2, 230.4, 51.2, 128.0, 128.0, 128.0);
close_path(c1);
move_to(c1, 64.0, 25.6);
rel_line_to(c1, 51.2, 51.2);
rel_line_to(c1, -51.2, 51.2);
rel_line_to(c1, -51.2, -51.2);
close_path(c1);
set_line_width(c1, 10.0);
set_source_rgb(c1, 0, 0, 1);
fill_preserve(c1);
set_source_rgb(c1, 0, 0, 0);
stroke(c1);
## now using the recorded painting
set_source(cr, s1, 0.0, 0.0)
paint(cr)
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_record0.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1131 | ## header to provide surface and context
using Cairo
c = CairoARGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgba(cr,0.0,0.0,0.0,0.0); # transparent black
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## paint the following to a Recording Surface
s1 = CairoRecordingSurface()
c1 = CairoContext(s1)
move_to(c1, 128.0, 25.6);
line_to(c1, 230.4, 230.4);
rel_line_to(c1, -102.4, 0.0);
curve_to(c1, 51.2, 230.4, 51.2, 128.0, 128.0, 128.0);
close_path(c1);
move_to(c1, 64.0, 25.6);
rel_line_to(c1, 51.2, 51.2);
rel_line_to(c1, -51.2, 51.2);
rel_line_to(c1, -51.2, -51.2);
close_path(c1);
set_line_width(c1, 10.0);
set_source_rgb(c1, 0, 0, 1);
fill_preserve(c1);
set_source_rgb(c1, 0, 0, 0);
stroke(c1);
## play back on transform coord
scale(cr,0.5,0.5)
set_source(cr, s1, 128.0, 128.0)
paint(cr)
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_record1.png");
## write to script
#s2 = Cairo.CairoScript("cairo-record1.cs")
#Cairo.script_from_recording_surface(s2,s1)
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1263 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
# a custom shape that could be wrapped in a function */
x = 25.6; # parameters like cairo_rectangle */
y = 25.6;
xw = 204.8;
yw = 204.8;
aspect = 1.0; # aspect ratio */
corner_radius = yw / 10.0; #* and corner curvature radius */
radius = corner_radius / aspect;
degrees = pi / 180.0;
new_sub_path(cr);
arc(cr, x + xw - radius, y + radius, radius, -90 * degrees, 0 * degrees);
arc(cr, x + xw - radius, y + yw - radius, radius, 0 * degrees, 90 * degrees);
arc(cr, x + radius, y + yw - radius, radius, 90 * degrees, 180 * degrees);
arc(cr, x + radius, y + radius, radius, 180 * degrees, 270 * degrees);
close_path(cr);
set_source_rgb(cr, 0.5, 0.5, 1);
fill_preserve(cr);
set_source_rgba(cr, 0.5, 0, 0, 0.5);
set_line_width(cr, 10.0);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_rounded_rectangle.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1170 | ## header to provide surface and context
using Cairo
c = CairoARGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.5,0.5,0.5);
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## paint the following to a Recording Surface
s1 = CairoRecordingSurface()
c1 = CairoContext(s1)
move_to(c1, 128.0, 25.6);
line_to(c1, 230.4, 230.4);
rel_line_to(c1, -102.4, 0.0);
curve_to(c1, 51.2, 230.4, 51.2, 128.0, 128.0, 128.0);
close_path(c1);
move_to(c1, 64.0, 25.6);
rel_line_to(c1, 51.2, 51.2);
rel_line_to(c1, -51.2, 51.2);
rel_line_to(c1, -51.2, -51.2);
close_path(c1);
set_line_width(c1, 10.0);
set_source_rgb(c1, 0, 0, 1);
fill_preserve(c1);
set_source_rgb(c1, 0, 0, 0);
stroke(c1);
## write to script
io = IOBuffer()
s2 = Cairo.CairoScript(io)
Cairo.script_from_recording_surface(s2,s1);
destroy(s2)
seek(io,0)
r = String(read(io))
r1 = split(r,"\n")
t1 = 24.0
for x in r1
move_to(cr,0.0,t1)
show_text(cr,x)
global t1 += 12.0
end
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_script0.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 785 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## api example, use set_line_type
dashes_by_name = [
"solid",
"dot",
"dotdashed",
"longdashed",
"dash",
"dotdotdashed",
"dotdotdotdashed"]
set_line_width(cr, 3.0);
for k=1:7
save(cr)
set_line_type(cr, dashes_by_name[k])
move_to(cr,16.0,16.0+(k*32.0))
line_to(cr,240.0,16.0+(k*32.0))
stroke(cr)
restore(cr)
end
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_set_dash.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1079 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
set_line_width(cr, 30.0);
set_line_cap(cr, Cairo.CAIRO_LINE_CAP_BUTT); # default
move_to(cr, 64.0, 50.0); line_to(cr, 64.0, 200.0);
stroke(cr);
set_line_cap(cr, Cairo.CAIRO_LINE_CAP_ROUND);
move_to(cr, 128.0, 50.0); line_to(cr, 128.0, 200.0);
stroke(cr);
set_line_cap(cr, Cairo.CAIRO_LINE_CAP_SQUARE);
move_to(cr, 192.0, 50.0); line_to(cr, 192.0, 200.0);
stroke(cr);
# draw helping lines
set_source_rgb(cr, 1, 0.2, 0.2);
set_line_width(cr, 2.56);
move_to(cr, 64.0, 50.0); line_to(cr, 64.0, 200.0);
move_to(cr, 128.0, 50.0); line_to(cr, 128.0, 200.0);
move_to(cr, 192.0, 50.0); line_to(cr, 192.0, 200.0);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_set_line_cap.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 937 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
set_line_width(cr, 40.96);
move_to(cr, 76.8, 84.48);
rel_line_to(cr, 51.2, -51.2);
rel_line_to(cr, 51.2, 51.2);
set_line_join(cr, Cairo.CAIRO_LINE_JOIN_MITER); # default
stroke(cr);
move_to(cr, 76.8, 161.28);
rel_line_to(cr, 51.2, -51.2);
rel_line_to(cr, 51.2, 51.2);
set_line_join(cr, Cairo.CAIRO_LINE_JOIN_BEVEL);
stroke(cr);
move_to(cr, 76.8, 238.08);
rel_line_to(cr, 51.2, -51.2);
rel_line_to(cr, 51.2, 51.2);
set_line_join(cr, Cairo.CAIRO_LINE_JOIN_ROUND);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_set_line_join.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 955 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
select_font_face(cr, "Sans", Cairo.FONT_SLANT_NORMAL,
Cairo.FONT_WEIGHT_BOLD);
set_font_size(cr, 90.0);
move_to(cr, 10.0, 135.0);
show_text(cr, "Hello");
move_to(cr, 70.0, 165.0);
text_path(cr, "void");
set_source_rgb(cr, 0.5, 0.5, 1);
fill_preserve(cr);
set_source_rgb(cr, 0, 0, 0);
set_line_width(cr, 2.56);
stroke(cr);
# draw helping lines
set_source_rgba(cr, 1, 0.2, 0.2, 0.6);
arc(cr, 10.0, 135.0, 5.12, 0, 2*pi);
close_path(cr);
arc(cr, 70.0, 165.0, 5.12, 0, 2*pi);
fill(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_text.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1167 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
select_font_face(cr, "Sans", Cairo.FONT_SLANT_NORMAL,
Cairo.FONT_WEIGHT_NORMAL);
set_font_size(cr, 52.0);
extents = text_extents(cr, "cairo");
#
# typedef struct {
# double x_bearing;
# double y_bearing;
# double width;
# double height;
# double x_advance;
# double y_advance;
# } cairo_text_extents_t;
x = 128.0-(extents[3]/2 + extents[1]);
y = 128.0-(extents[4]/2 + extents[2]);
move_to(cr, x, y);
show_text(cr, "cairo");
# draw helping lines
set_source_rgba(cr, 1, 0.2, 0.2, 0.6);
set_line_width(cr, 6.0);
arc(cr, x, y, 10.0, 0, 2*pi);
fill(cr);
move_to(cr, 128.0, 0);
rel_line_to(cr, 0, 256);
move_to(cr, 0, 128.0);
rel_line_to(cr, 256, 0);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_text_align_center.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1134 | ## header to provide surface and context
using Cairo
c = CairoRGBSurface(256,256);
cr = CairoContext(c);
save(cr);
set_source_rgb(cr,0.8,0.8,0.8); # light gray
rectangle(cr,0.0,0.0,256.0,256.0); # background
fill(cr);
restore(cr);
save(cr);
## original example, following here
select_font_face(cr, "Sans", Cairo.FONT_SLANT_NORMAL,
Cairo.FONT_WEIGHT_NORMAL);
set_font_size(cr, 100.0);
extents = text_extents(cr, "cairo");
#
# typedef struct {
# double x_bearing;
# double y_bearing;
# double width;
# double height;
# double x_advance;
# double y_advance;
# } cairo_text_extents_t;
x = 25.0;
y = 150.0;
move_to(cr, x, y);
show_text(cr, "cairo");
# draw helping lines
set_source_rgba(cr, 1, 0.2, 0.2, 0.6);
set_line_width(cr, 6.0);
arc(cr, x, y, 10.0, 0, 2*pi);
fill(cr);
move_to(cr, x,y);
rel_line_to(cr, 0, -extents[4]);
rel_line_to(cr, extents[3], 0);
rel_line_to(cr, extents[1], -extents[2]);
stroke(cr);
## mark picture with current date
restore(cr);
move_to(cr,0.0,12.0);
set_source_rgb(cr, 0,0,0);
show_text(cr,Libc.strftime(time()));
write_to_png(c,"sample_text_extents.png");
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 50004 | module Cairo
import Base.Sys
# For libcairo
using Cairo_jll
# For libpangocairo
using Pango_jll
# For libgobject
using Glib_jll
# Deprecate old library variables
Base.@deprecate_binding _jl_libcairo Cairo.libcairo false
Base.@deprecate_binding _jl_libgobject Cairo.libgobject false
Base.@deprecate_binding _jl_libpango Cairo.libpango false
Base.@deprecate_binding _jl_libpangocairo Cairo.libpango false
using Colors
import Graphics
using Graphics: BoundingBox, GraphicsContext, GraphicsDevice
import Graphics: arc, clip, clip_preserve, close_path, creategc, device_to_user!, device_to_user_distance!, fill_preserve, height, line_to, move_to, new_path, new_sub_path, paint, rectangle, rel_line_to, rel_move_to, reset_clip, restore, rotate, save, scale, set_dash, set_line_width, set_source, set_source_rgb, set_source_rgba, stroke, stroke_preserve, stroke_transformed, stroke_transformed_preserve, textwidth, translate, user_to_device!, user_to_device_distance!, width, circle, reset_transform
import Base: copy, fill
libcairo_version = VersionNumber(unsafe_string(
ccall((:cairo_version_string,Cairo.libcairo),Cstring,()) ))
libpango_version = VersionNumber(unsafe_string(
ccall((:pango_version_string,Cairo.libpango),Cstring,()) ))
if !Sys.iswindows()
libpangocairo_version = VersionNumber(unsafe_string(
ccall((:pango_version_string,Cairo.libpangocairo),Cstring,()) ))
libgobject_version = VersionNumber(
unsafe_load(cglobal((:glib_major_version, Cairo.libgobject), Cuint)),
unsafe_load(cglobal((:glib_minor_version, Cairo.libgobject), Cuint)),
unsafe_load(cglobal((:glib_micro_version, Cairo.libgobject), Cuint)))
end
import Base.show
include("constants.jl")
export
# drawing surface and context types
CairoSurface, CairoContext, CairoPattern,
# surface constructors
CairoRGBSurface, CairoPDFSurface, CairoEPSSurface, CairoXlibSurface,
CairoARGBSurface, CairoSVGSurface, CairoImageSurface, CairoQuartzSurface,
CairoWin32Surface, CairoScriptSurface, CairoRecordingSurface,
CairoPSSurface, surface_create_similar,
# surface and context management
finish, destroy, status, get_source,
creategc, save, restore, show_page, copy_page, width, height,
# pattern
pattern_create_radial, pattern_create_linear,
pattern_add_color_stop_rgb, pattern_add_color_stop_rgba,
pattern_set_filter, pattern_set_extend, pattern_get_surface,
# mesh patterns (version > 1.12)
CairoPatternMesh,
mesh_pattern_begin_patch, mesh_pattern_end_patch,
mesh_pattern_move_to, mesh_pattern_line_to,
mesh_pattern_curve_to,
mesh_pattern_set_corner_color_rgb,
mesh_pattern_set_corner_color_rgba,
# drawing attribute manipulation
set_antialias, get_antialias,
set_fill_type, set_line_width, set_dash,
set_source_rgb, set_source_rgba, set_source_surface, set_line_type,
set_line_cap, set_line_join,
set_operator, get_operator, set_source,
CairoMatrix,
# coordinate systems
reset_transform, rotate, scale, translate, user_to_device!,
device_to_user!, user_to_device_distance!, device_to_user_distance!,
get_matrix, set_matrix,
# clipping
clip, clip_preserve, reset_clip,
# fill, stroke, path, and shape commands
fill, fill_preserve, new_path, new_sub_path, close_path, paint, paint_with_alpha, stroke,
stroke_preserve, stroke_transformed, stroke_transformed_preserve,
move_to, line_to, rel_line_to, rel_move_to,
rectangle, circle, arc, arc_negative,
curve_to, rel_curve_to,
path_extents,
# path copy
copy_path, copy_path_flat, convert_cairo_path_data,
# other path operations
get_current_point, has_current_point,
# text
text,
update_layout, show_layout, get_layout_size, layout_text,
set_text, set_latex,
set_font_face, set_font_size, select_font_face,
textwidth, textheight, text_extents,
TeXLexer, tex2pango, show_text, text_path,
set_font_matrix, get_font_matrix,
# images
write_to_png, image, read_from_png,
# push+pop group
push_group, pop_group
## head docstring following
"
Surfaces, the canvas you are painting on
CairoSurface, CairoRGBSurface, CairoPDFSurface, CairoEPSSurface,
CairoXlibSurface, CairoARGBSurface, CairoSVGSurface,
CairoImageSurface, CairoQuartzSurface,
CairoWin32Surface, CairoScriptSurface, CairoRecordingSurface,
CairoPSSurface,
Context, the handle to coordinate transformation, paint+Color
CairoContext, finish, destroy, status, get_source,
creategc, save, restore, show_page, copy_page, width, height
Path creation API
new_path, new_sub_path, close_path,
move_to, line_to, rel_line_to, rel_move_to,
rectangle, circle, arc, arc_negative,
curve_to, rel_curve_to,
path_extents,
Stroking and painting API
fill, fill_preserve, paint, paint_with_alpha, stroke,
stroke_preserve, stroke_transformed, stroke_transformed_preserve
CairoContext, finish, destroy, status, get_source,
creategc, save, restore, show_page, copy_page, width, height
"
Cairo
function write_to_stream_callback(s::IO, buf::Ptr{UInt8}, len::UInt32)
n = unsafe_write(s,buf,len)
Int32((n == len) ? 0 : 11)
end
get_stream_callback(::Type{T}) where T = @cfunction write_to_stream_callback Int32 (Ref{T}, Ptr{UInt8}, UInt32)
function read_from_stream_callback(s::IO, buf::Ptr{UInt8}, len::UInt32)
# wrap the provided buf into a julia Array
b1 = unsafe_wrap(Array,buf,len)
# read from stream
nb = readbytes!(s,b1,len)
# provide a return status
(nb == len) ? STATUS_SUCCESS : STATUS_READ_ERROR
end
get_readstream_callback(::Type{T}) where T = @cfunction read_from_stream_callback Int32 (Ref{T}, Ptr{UInt8}, UInt32)
abstract type CairoSurface{T<:Union{UInt32,RGB24,ARGB32}} <: GraphicsDevice end
# All CairoSurfaces have to implement at least the fields and types of CairoSurfaceBase
function Base.getproperty(surface::CairoSurface, fieldname::Symbol)
if fieldname === :ptr
return getfield(surface, :ptr)::Ptr{Nothing}
elseif fieldname === :width
return getfield(surface, :width)::Float64
elseif fieldname === :height
return getfield(surface, :height)::Float64
end
return getfield(surface, fieldname)
end
mutable struct CairoSurfaceBase{T<:Union{UInt32,RGB24,ARGB32}} <: CairoSurface{T}
ptr::Ptr{Nothing}
width::Float64
height::Float64
function CairoSurface{T}(ptr::Ptr{Nothing}, w, h) where {T}
self = new{T}(ptr, w, h)
finalizer(destroy, self)
self
end
function CairoSurface{T}(ptr::Ptr{Nothing}) where {T}
ccall(
(:cairo_surface_reference,libcairo),
Ptr{Nothing}, (Ptr{Nothing}, ), ptr)
self = new{T}(ptr)
finalizer(destroy, self)
self
end
end
mutable struct CairoSurfaceImage{T<:Union{UInt32,RGB24,ARGB32}} <: CairoSurface{T}
ptr::Ptr{Nothing}
width::Float64
height::Float64
data::Matrix{T}
function CairoSurface{T}(ptr::Ptr{Nothing}, w, h, data::Matrix{T}) where {T}
self = new{T}(ptr, w, h, data)
finalizer(destroy, self)
self
end
end
mutable struct CairoSurfaceIOStream{T<:Union{UInt32,RGB24,ARGB32}} <: CairoSurface{T}
ptr::Ptr{Nothing}
width::Float64
height::Float64
stream::IO
function CairoSurface{T}(ptr::Ptr{Nothing}, w, h, stream::IO) where {T}
self = new{T}(ptr, w, h, stream)
finalizer(destroy, self)
self
end
end
function get_stream_ptr(surf::T) where {T<:CairoSurfaceIOStream}
GC.@preserve surf begin
return unsafe_load(Ptr{Ptr{Nothing}}(pointer_from_objref(surf) + fieldoffset(T, 4)))
end
end
CairoSurface(ptr, w, h) = CairoSurface{UInt32}(ptr, w, h)
CairoSurface(ptr, w, h, data) = CairoSurface{eltype(data)}(ptr, w, h, data)
CairoSurface(ptr, w, h, stream::IO) = CairoSurface{UInt32}(ptr, w, h, stream)
CairoSurface(ptr) = CairoSurface{UInt32}(ptr)
width(surface::CairoSurface) = surface.width
height(surface::CairoSurface) = surface.height
function destroy(surface::CairoSurface)
if surface.ptr == C_NULL
return
end
ccall((:cairo_surface_destroy,libcairo), Nothing, (Ptr{Nothing},), surface.ptr)
surface.ptr = C_NULL
nothing
end
# function resize(surface::CairoSurface, w, h)
# if OS_NAME == :Linux
# CairoXlibSurfaceSetSize(surface.ptr, w, h)
# elseif OS_NAME == :Darwin
# elseif OS_NAME == :Windows
# else
# error("Unsupported operating system")
# end
# surface.width = w
# surface.height = h
# end
for name in (:finish,:flush,:mark_dirty)
@eval begin
$name(surface::CairoSurface) =
ccall(($(string("cairo_surface_",name)),libcairo),
Nothing, (Ptr{Nothing},), surface.ptr)
end
end
function image_surface_get_data(surface::CairoSurface{T}) where {T}
return ccall(
(:cairo_image_surface_get_data, libcairo),
Ptr{T}, (Ptr{Nothing},), surface.ptr)
end
function status(surface::CairoSurface)
ccall((:cairo_surface_status,libcairo),
Int32, (Ptr{Nothing},), surface.ptr)
end
function CairoImageSurface(w::Real, h::Real, format::Integer)
ptr = ccall((:cairo_image_surface_create,libcairo),
Ptr{Nothing}, (Int32,Int32,Int32), format, w, h)
CairoSurface(ptr, w, h)
end
CairoRGBSurface(w::Real, h::Real) = CairoImageSurface(w, h, FORMAT_RGB24)
CairoARGBSurface(w::Real, h::Real) = CairoImageSurface(w, h, FORMAT_ARGB32)
CairoARGBSurface(img) = CairoImageSurface(img, FORMAT_ARGB32)
CairoRGBSurface(img) = CairoImageSurface(img, FORMAT_RGB24)
function CairoImageSurface(img::Array{UInt32,2}, format::Integer; flipxy::Bool = true)
if flipxy
img = permutedims(img, (2,1))
end
w,h = size(img)
stride = format_stride_for_width(format, w)
@assert stride == 4w
ptr = ccall((:cairo_image_surface_create_for_data,libcairo),
Ptr{Nothing}, (Ptr{Nothing},Int32,Int32,Int32,Int32),
img, format, w, h, stride)
CairoSurface(ptr, w, h, img)
end
function CairoImageSurface(img::Matrix{T}) where {T<:Union{RGB24,ARGB32}}
w,h = size(img)
stride = format_stride_for_width(format(T), w)
@assert stride == 4w
ptr = ccall((:cairo_image_surface_create_for_data,libcairo),
Ptr{Nothing}, (Ptr{Nothing},Int32,Int32,Int32,Int32),
img, format(T), w, h, stride)
CairoSurface(ptr, w, h, img)
end
format(::Type{RGB24}) = FORMAT_RGB24
format(::Type{ARGB32}) = FORMAT_ARGB32
format(surf::CairoSurface{T}) where {T<:Union{RGB24,ARGB32}} = T
## PDF ##
function CairoPDFSurface(stream::T, w::Real, h::Real) where {T<:IO}
callback = get_stream_callback(T)
surf = CairoSurface(C_NULL, w, h, stream)
GC.@preserve surf begin
surf.ptr = ccall((:cairo_pdf_surface_create_for_stream,libcairo), Ptr{Nothing},
(Ptr{Nothing}, Ptr{Nothing}, Float64, Float64), callback,
get_stream_ptr(surf), w, h)
end
return surf
end
function CairoPDFSurface(filename::AbstractString, w_pts::Real, h_pts::Real)
ptr = ccall((:cairo_pdf_surface_create,libcairo), Ptr{Nothing},
(Ptr{UInt8},Float64,Float64), String(filename), w_pts, h_pts)
CairoSurface(ptr, w_pts, h_pts)
end
## EPS ##
function CairoEPSSurface(stream::T, w::Real, h::Real) where {T<:IO}
callback = get_stream_callback(T)
surf = CairoSurface(C_NULL, w, h, stream)
GC.@preserve surf begin
surf.ptr = ccall((:cairo_ps_surface_create_for_stream,libcairo), Ptr{Nothing},
(Ptr{Nothing}, Ptr{Nothing}, Float64, Float64),
callback, get_stream_ptr(surf), w, h)
ccall((:cairo_ps_surface_set_eps,libcairo), Nothing,
(Ptr{Nothing},Int32), surf.ptr, 1)
end
return surf
end
function CairoEPSSurface(filename::AbstractString, w_pts::Real, h_pts::Real)
ptr = ccall((:cairo_ps_surface_create,libcairo), Ptr{Nothing},
(Ptr{UInt8},Float64,Float64), String(filename), w_pts, h_pts)
ccall((:cairo_ps_surface_set_eps,libcairo), Nothing,
(Ptr{Nothing},Int32), ptr, 1)
CairoSurface(ptr, w_pts, h_pts)
end
## PS ##
function CairoPSSurface(stream::T, w::Real, h::Real) where {T<:IO}
callback = get_stream_callback(T)
surf = CairoSurface(C_NULL, w, h, stream)
GC.@preserve surf begin
surf.ptr = ccall((:cairo_ps_surface_create_for_stream,libcairo), Ptr{Nothing},
(Ptr{Nothing}, Ptr{Nothing}, Float64, Float64),
callback, get_stream_ptr(surf), w, h)
ccall((:cairo_ps_surface_set_eps,libcairo), Nothing,
(Ptr{Nothing},Int32), surf.ptr, 0)
end
return surf
end
function CairoPSSurface(filename::AbstractString, w_pts::Real, h_pts::Real)
ptr = ccall((:cairo_ps_surface_create,libcairo), Ptr{Nothing},
(Ptr{UInt8},Float64,Float64), String(filename), w_pts, h_pts)
ccall((:cairo_ps_surface_set_eps,libcairo), Nothing,
(Ptr{Nothing},Int32), ptr, 0)
CairoSurface(ptr, w_pts, h_pts)
end
## Xlib ##
function CairoXlibSurface(display, drawable, visual, w, h)
ptr = ccall((:cairo_xlib_surface_create,libcairo), Ptr{Nothing},
(Ptr{Nothing}, Int, Ptr{Nothing}, Int32, Int32),
display, drawable, visual, w, h)
CairoSurface(ptr, w, h)
end
CairoXlibSurfaceSetSize(surface, w, h) =
ccall((:cairo_xlib_surface_set_size,libcairo), Nothing,
(Ptr{Nothing}, Int32, Int32),
surface, w, h)
## Quartz ##
function CairoQuartzSurface(context, w, h)
ptr = ccall((:cairo_quartz_surface_create_for_cg_context,libcairo),
Ptr{Nothing}, (Ptr{Nothing}, UInt32, UInt32), context, w, h)
CairoSurface(ptr, w, h)
end
## Win32 ##
function CairoWin32Surface(hdc,w,h)
ptr = ccall((:cairo_win32_surface_create, libcairo),
Ptr{Nothing}, (Ptr{Nothing},), hdc)
CairoSurface(ptr,w,h)
end
## SVG ##
function CairoSVGSurface(stream::T, w::Real, h::Real) where {T<:IO}
callback = get_stream_callback(T)
surf = CairoSurface(C_NULL, w, h, stream)
GC.@preserve surf begin
surf.ptr = ccall((:cairo_svg_surface_create_for_stream,libcairo), Ptr{Nothing},
(Ptr{Nothing}, Ptr{Nothing}, Float64, Float64), callback,
get_stream_ptr(surf), w, h)
end
return surf
end
function CairoSVGSurface(filename::AbstractString, w::Real, h::Real)
ptr = ccall((:cairo_svg_surface_create,libcairo), Ptr{Nothing},
(Ptr{UInt8},Float64,Float64), String(filename), w, h)
CairoSurface(ptr, w, h)
end
## PNG ##
function read_from_png(filename::AbstractString)
ptr = ccall((:cairo_image_surface_create_from_png,libcairo),
Ptr{Nothing}, (Ptr{UInt8},), String(filename))
w = ccall((:cairo_image_surface_get_width,libcairo),
Int32, (Ptr{Nothing},), ptr)
h = ccall((:cairo_image_surface_get_height,libcairo),
Int32, (Ptr{Nothing},), ptr)
CairoSurface(ptr, w, h)
end
function write_to_png(surface::CairoSurface, stream::T) where {T<:IO}
callback = get_stream_callback(T)
ccall((:cairo_surface_write_to_png_stream,libcairo), status_t,
(Ptr{UInt8},Ptr{Nothing},Any), surface.ptr, callback, stream)
end
function write_to_png(surface::CairoSurface, filename::AbstractString)
ccall((:cairo_surface_write_to_png,libcairo), status_t,
(Ptr{UInt8},Ptr{UInt8}), surface.ptr, String(filename))
end
show(io::IO, ::MIME"image/png", surface::CairoSurface) =
write_to_png(surface, io)
function read_from_png(stream::T) where {T<:IO}
callback = get_readstream_callback(T)
ptr = ccall((:cairo_image_surface_create_from_png_stream, Cairo.libcairo),
Ptr{Nothing}, (Ptr{Nothing},Ref{IO}), callback, stream)
w = ccall((:cairo_image_surface_get_width,Cairo.libcairo),
Int32, (Ptr{Nothing},), ptr)
h = ccall((:cairo_image_surface_get_height,Cairo.libcairo),
Int32, (Ptr{Nothing},), ptr)
Cairo.CairoSurface(ptr, w, h)
end
## Generic ##
function surface_create_similar(s::CairoSurface, w = width(s), h = height(s))
ptr = ccall((:cairo_surface_create_similar,libcairo), Ptr{Nothing},
(Ptr{Nothing}, Int32, Int32, Int32),
s.ptr, CONTENT_COLOR_ALPHA, w, h)
CairoSurface(ptr, w, h)
end
# Utilities
function format_stride_for_width(format::Integer, width::Integer)
ccall((:cairo_format_stride_for_width,libcairo), Int32,
(Int32,Int32), format, width)
end
## Scripting (only target IO stream)
mutable struct CairoScript <: GraphicsDevice
ptr::Ptr{Nothing}
stream::IO
function CairoScript(stream::T) where {T<:IO}
callback = get_stream_callback(T)
self = new(C_NULL, stream)
GC.@preserve self begin
self.ptr = ccall((:cairo_script_create_for_stream,libcairo), Ptr{Nothing},
(Ptr{Nothing}, Ptr{Nothing}), callback, get_stream_ptr(self))
end
finalizer(destroy, self)
self
end
end
function get_stream_ptr(s::T) where {T<:CairoScript}
GC.@preserve s begin
return unsafe_load(Ptr{Ptr{Nothing}}(pointer_from_objref(s) + fieldoffset(T, 2)))
end
end
function destroy(s::CairoScript)
if s.ptr == C_NULL
return
end
ccall((:cairo_device_destroy,libcairo), Nothing, (Ptr{Nothing},), s.ptr)
s.ptr = C_NULL
nothing
end
function CairoScriptSurface(stream::IO, w::Real, h::Real)
s = CairoScript(stream)
ptr = ccall((:cairo_script_surface_create,libcairo), Ptr{Nothing},
(Ptr{Nothing},Int32,Float64,Float64),s.ptr ,CONTENT_COLOR_ALPHA, w, h)
CairoSurface(ptr, w, h, stream)
end
function CairoScriptSurface(stream::IO, sc::CairoSurface)
s = CairoScript(stream)
ptr = ccall((:cairo_script_surface_create_for_target,libcairo), Ptr{Nothing},
(Ptr{Nothing},Ptr{Nothing}),s.ptr, sc.ptr)
CairoSurface(ptr, sc.width, sc.height)
end
mutable struct CairoRectangle
x0::Float64
y0::Float64
x1::Float64
y1::Float64
end
CairoRectangle() = CairoRectangle(0.0, 0.0, 0.0, 0.0)
function CairoRecordingSurface(content::Int32,extents::CairoRectangle)
ptr = ccall((:cairo_recording_surface_create,libcairo), Ptr{Nothing},
(Int32,Ptr{Nothing}),content, Ref(extents))
CairoSurface(ptr)
end
function CairoRecordingSurface(content::Int32)
ptr = ccall((:cairo_recording_surface_create,libcairo), Ptr{Nothing},
(Int32,Ptr{Nothing}),content, C_NULL)
CairoSurface(ptr)
end
CairoRecordingSurface() = CairoRecordingSurface(CONTENT_COLOR_ALPHA)
function script_from_recording_surface(s::CairoScript,r::CairoSurface)
ccall((:cairo_script_from_recording_surface,libcairo), Int32,
(Ptr{Nothing},Ptr{Nothing}),s.ptr, r.ptr)
end
# -----------------------------------------------------------------------------
mutable struct CairoContext <: GraphicsContext
ptr::Ptr{Nothing}
surface::CairoSurface
layout::Ptr{Nothing} # cache PangoLayout
function CairoContext(surface::CairoSurface)
ptr = ccall((:cairo_create,libcairo),
Ptr{Nothing}, (Ptr{Nothing},), surface.ptr)
layout = ccall((:pango_cairo_create_layout,libpangocairo),
Ptr{Nothing}, (Ptr{Nothing},), ptr)
self = new(ptr, surface, layout)
finalizer(destroy, self)
self
end
function CairoContext(ptr::Ptr{Nothing})
ccall((:cairo_reference,libcairo),
Ptr{Nothing}, (Ptr{Nothing},), ptr)
surface_p = ccall((:cairo_get_target,libcairo),
Ptr{Nothing}, (Ptr{Nothing},), ptr)
surface = CairoSurface(surface_p)
layout = ccall((:pango_cairo_create_layout,libpangocairo),
Ptr{Nothing}, (Ptr{Nothing},), ptr)
self = new(ptr,surface,layout)
finalizer(destroy, self)
self
end
end
creategc(s::CairoSurface) = CairoContext(s)
function destroy(ctx::CairoContext)
if ctx.ptr == C_NULL
return
end
ccall((:g_object_unref,libgobject), Nothing, (Ptr{Nothing},), ctx.layout)
_destroy(ctx)
ctx.ptr = C_NULL
nothing
end
width(ctx::CairoContext) = width(ctx.surface)
height(ctx::CairoContext) = height(ctx.surface)
function copy(ctx::CairoContext)
surf = surface_create_similar(ctx.surface)
c = creategc(surf)
set_source_surface(c, ctx.surface)
paint(c)
set_matrix(c, get_matrix(ctx))
c
end
# Copy a rectangular region
function copy(ctx::CairoContext, bb::BoundingBox)
w = width(bb)
h = height(bb)
surf = surface_create_similar(ctx.surface, ceil(Int,w), ceil(Int,h))
c = creategc(surf)
set_source_surface(c, ctx.surface, -bb.xmin, -bb.ymin)
rectangle(c, 0, 0, w, h)
fill(c)
set_matrix(c, get_matrix(ctx))
c
end
for (NAME, FUNCTION) in Any[(:_destroy, :cairo_destroy),
(:save, :cairo_save),
(:restore, :cairo_restore),
(:show_page, :cairo_show_page),
(:copy_page, :cairo_copy_page),
(:clip, :cairo_clip),
(:clip_preserve, :cairo_clip_preserve),
(:reset_clip, :cairo_reset_clip),
(:reset_transform, :cairo_identity_matrix),
(:fill, :cairo_fill),
(:fill_preserve, :cairo_fill_preserve),
(:new_path, :cairo_new_path),
(:new_sub_path, :cairo_new_sub_path),
(:close_path, :cairo_close_path),
(:paint, :cairo_paint),
(:stroke_transformed, :cairo_stroke),
(:stroke_transformed_preserve, :cairo_stroke_preserve)]
@eval begin
$NAME(ctx::CairoContext) =
ccall(($(Expr(:quote,FUNCTION)),libcairo),
Nothing, (Ptr{Nothing},), ctx.ptr)
end
end
function stroke(ctx::CairoContext)
save(ctx)
# use uniform scale for stroking
reset_transform(ctx)
ccall((:cairo_stroke, libcairo), Nothing, (Ptr{Nothing},), ctx.ptr)
restore(ctx)
end
function stroke_preserve(ctx::CairoContext)
save(ctx)
reset_transform(ctx)
ccall((:cairo_stroke_preserve, libcairo), Nothing, (Ptr{Nothing},), ctx.ptr)
restore(ctx)
end
function paint_with_alpha(ctx::CairoContext, a)
ccall((:cairo_paint_with_alpha, libcairo),
Nothing, (Ptr{Nothing}, Float64), ctx.ptr, a)
end
function get_operator(ctx::CairoContext)
Int(ccall((:cairo_get_operator,libcairo), Int32, (Ptr{Nothing},), ctx.ptr))
end
for (NAME, FUNCTION) in Any[(:set_fill_type, :cairo_set_fill_rule),
(:set_operator, :cairo_set_operator),
(:set_line_cap, :cairo_set_line_cap),
(:set_line_join, :cairo_set_line_join)]
@eval begin
$NAME(ctx::CairoContext, i0::Integer) =
ccall(($(Expr(:quote,FUNCTION)),libcairo),
Nothing, (Ptr{Nothing},Int32), ctx.ptr, i0)
end
end
for (NAME, FUNCTION) in Any[(:set_line_width, :cairo_set_line_width),
(:rotate, :cairo_rotate),
(:set_font_size, :cairo_set_font_size)]
@eval begin
$NAME(ctx::CairoContext, d0::Real) =
ccall(($(Expr(:quote,FUNCTION)),libcairo),
Nothing, (Ptr{Nothing},Float64), ctx.ptr, d0)
end
end
for (NAME, FUNCTION) in Any[(:line_to, :cairo_line_to),
(:move_to, :cairo_move_to),
(:rel_line_to, :cairo_rel_line_to),
(:rel_move_to, :cairo_rel_move_to),
(:scale, :cairo_scale),
(:translate, :cairo_translate)]
@eval begin
$NAME(ctx::CairoContext, d0::Real, d1::Real) =
ccall(($(Expr(:quote,FUNCTION)),libcairo),
Nothing, (Ptr{Nothing},Float64,Float64), ctx.ptr, d0, d1)
end
end
for (NAME, FUNCTION) in Any[(:curve_to, :cairo_curve_to),
(:rel_curve_to, :cairo_rel_curve_to)]
@eval begin
$NAME(ctx::CairoContext, d0::Real, d1::Real, d2::Real, d3::Real, d4::Real, d5::Real) =
ccall(($(Expr(:quote,FUNCTION)),libcairo),
Nothing, (Ptr{Nothing},Float64,Float64,Float64,Float64,Float64,Float64), ctx.ptr, d0, d1, d2, d3, d4, d5)
end
end
for (NAME, FUNCTION) in Any[(:arc, :cairo_arc),
(:arc_negative, :cairo_arc_negative)]
@eval begin
$NAME(ctx::CairoContext, xc::Real, yc::Real, radius::Real, angle1::Real, angle2::Real) =
ccall(($(Expr(:quote,FUNCTION)),libcairo),
Nothing, (Ptr{Nothing},Float64,Float64,Float64,Float64,Float64),
ctx.ptr, xc, yc, radius, angle1, angle2)
end
end
set_source_rgb(ctx::CairoContext, r::Real, g::Real, b::Real) =
ccall((:cairo_set_source_rgb,libcairo),
Nothing, (Ptr{Nothing},Float64,Float64,Float64), ctx.ptr, r, g, b)
set_source_rgba(ctx::CairoContext, r::Real, g::Real, b::Real, a::Real) =
ccall((:cairo_set_source_rgba,libcairo), Nothing,
(Ptr{Nothing},Float64,Float64,Float64,Float64),
ctx.ptr, r, g, b, a)
function set_source(ctx::CairoContext, c::Color)
rgb = convert(RGB, c)
set_source_rgb(ctx, rgb.r, rgb.g, rgb.b)
end
function set_source(ctx::CairoContext, ac::TransparentColor)
rgba = convert(RGBA, ac)
set_source_rgba(ctx, rgba.r, rgba.g, rgba.b, rgba.alpha)
end
set_source(dest::CairoContext, src::CairoContext) = set_source_surface(dest, src.surface)
set_source(dest::CairoContext, src::CairoSurface) = set_source_surface(dest, src)
rectangle(ctx::CairoContext, x::Real, y::Real, w::Real, h::Real) =
ccall((:cairo_rectangle,libcairo), Nothing,
(Ptr{Nothing},Float64,Float64,Float64,Float64),
ctx.ptr, x, y, w, h)
function set_dash(ctx::CairoContext, dashes::Vector{Float64}, offset::Real = 0.0)
ccall((:cairo_set_dash,libcairo), Nothing,
(Ptr{Nothing},Ptr{Float64},Int32,Float64), ctx.ptr, dashes, length(dashes), offset)
end
function set_source_surface(ctx::CairoContext, s::CairoSurface, x::Real = 0.0, y::Real = 0.0)
ccall((:cairo_set_source_surface,libcairo), Nothing,
(Ptr{Nothing},Ptr{Nothing},Float64,Float64), ctx.ptr, s.ptr, x, y)
end
function set_source(ctx::CairoContext, s::CairoSurface, x::Real, y::Real)
set_source_surface(ctx, s, x, y)
end
# cairo_path data and functions
mutable struct CairoPath_t
status::Cairo.status_t
data::Ptr{Float64}
num_data::UInt32
end
mutable struct CairoPath <: GraphicsDevice
ptr::Ptr{CairoPath_t}
function CairoPath(ptr::Ptr{Nothing})
self = new(ptr)
finalizer(destroy, self)
self
end
end
# Abstract, contains type (moveto,lineto,curveto,closepath) and points
mutable struct CairoPathEntry
element_type::UInt32
points::Array{Float64,1}
end
function destroy(path::CairoPath)
if path.ptr == C_NULL
return
end
ccall((:cairo_path_destroy,libcairo), Nothing, (Ptr{Nothing},), path.ptr)
path.ptr = C_NULL
nothing
end
function copy_path(ctx::CairoContext)
ptr = ccall((:cairo_copy_path, libcairo),
Ptr{Nothing}, (Ptr{Nothing},),ctx.ptr)
path = CairoPath(ptr)
finalizer(destroy, path)
path
end
function copy_path_flat(ctx::CairoContext)
ptr = ccall((:cairo_copy_path_flat, libcairo),
Ptr{Nothing}, (Ptr{Nothing},),ctx.ptr)
path = CairoPath(ptr)
finalizer(destroy, path)
path
end
function convert_cairo_path_data(p::CairoPath)
c = unsafe_load(p.ptr)
# The original data (pointed by c.data) is an array of Unions. We
# define here by Float64 (most data is) and reinterpret in the header.
path_data = CairoPathEntry[]
@static if VERSION >= v"0.7"
c_data = unsafe_wrap(Array, c.data, (Int(c.num_data*2), 1), own=false)
else
c_data = unsafe_wrap(Array, c.data, (Int(c.num_data*2), 1), false)
end
data_index = 1
while data_index <= ((c.num_data)*2)
# read header (reinterpret a Float64 to UInt64 and split to UInt32 x 2)
element_length = reinterpret(UInt64,c_data[data_index]) >> 32
element_type = reinterpret(UInt64,c_data[data_index]) & 0xffffffff
# copy points x,y
points = Vector{Float64}(undef, (element_length - 1) * 2)
for i=1:(element_length-1)*2
points[i] = c_data[data_index+i+1]
end
g = CairoPathEntry(element_type,points)
push!(path_data,g)
# goto next element
data_index += (element_length*2)
end
path_data
end
# other path operations
function get_current_point(ctx::CairoContext)
x = Ref{Cdouble}(0)
y = Ref{Cdouble}(0)
ccall((:cairo_get_current_point, libcairo),
Nothing, (Ptr{Nothing},Ref{Cdouble},Ref{Cdouble}),ctx.ptr,x,y)
x[],y[]
end
function has_current_point(ctx::CairoContext)
Bool(ccall((:cairo_has_current_point, libcairo),
Cint, (Ptr{Nothing},),ctx.ptr))
end
# user<->device coordinate translation
for (fname,cname) in ((:user_to_device!,:cairo_user_to_device),
(:device_to_user!,:cairo_device_to_user),
(:user_to_device_distance!,:cairo_user_to_device_distance),
(:device_to_user_distance!,:cairo_device_to_user_distance))
@eval begin
function ($fname)(ctx::CairoContext, p::Vector{Float64})
ccall(($(Expr(:quote,cname)),libcairo),
Nothing, (Ptr{Nothing}, Ptr{Float64}, Ptr{Float64}),
ctx.ptr, Ref(p,1), Ref(p,2))
p
end
end
end
function image(ctx::CairoContext, s::CairoSurface, x, y, w, h)
rectangle(ctx, x, y, w, h)
save(ctx)
translate(ctx, x, y)
scale(ctx, w/s.width, h/s.height)
set_source_surface(ctx, s, 0, 0)
if abs(w) > s.width && abs(h) > s.height
# use NEAREST filter when stretching an image
# it's usually better to see pixels than a blurry mess when viewing
# a small image
p = get_source(ctx)
pattern_set_filter(p, FILTER_NEAREST)
end
fill(ctx)
restore(ctx)
end
image(ctx::CairoContext, img::Array{UInt32,2}, x, y, w, h) =
image(ctx, CairoRGBSurface(img), x, y, w, h)
function push_group(ctx::CairoContext)
if ctx.ptr == C_NULL
return
end
ccall((:cairo_push_group, libcairo), Nothing, (Ptr{Nothing},),ctx.ptr)
nothing
end
function pop_group(ctx::CairoContext)
if ctx.ptr == C_NULL
return
end
ptr = ccall((:cairo_pop_group, libcairo), Ptr{Nothing}, (Ptr{Nothing},),ctx.ptr)
pattern = CairoPattern(ptr)
finalizer(destroy, pattern)
pattern
end
# -----------------------------------------------------------------------------
mutable struct CairoPattern
ptr::Ptr{Nothing}
end
function CairoPattern(s::CairoSurface)
ptr = ccall((:cairo_pattern_create_for_surface, libcairo),
Ptr{Nothing}, (Ptr{Nothing},), s.ptr)
# Ideally we'd check the status, but at least for certain releases of the library
# the return value seems not to be set properly (random values are returned)
# status = ccall((:cairo_pattern_status, libcairo),
# Cint, (Ptr{Nothing},), s.ptr)
# if status != 0
# error("Error creating Cairo pattern: ", bytestring(
# ccall((:cairo_status_to_string, libcairo),
# Ptr{UInt8}, (Cint,), status)))
# end
pattern = CairoPattern(ptr)
finalizer(destroy, pattern)
pattern
end
set_source(dest::CairoContext, src::CairoPattern) =
ccall((:cairo_set_source, libcairo),
Nothing, (Ptr{Nothing}, Ptr{Nothing}), dest.ptr, src.ptr)
function get_source(ctx::CairoContext)
CairoPattern(ccall((:cairo_get_source,libcairo),
Ptr{Nothing}, (Ptr{Nothing},), ctx.ptr))
end
function pattern_set_filter(p::CairoPattern, f)
ccall((:cairo_pattern_set_filter,libcairo), Nothing,
(Ptr{Nothing},Int32), p.ptr, f)
end
function pattern_set_extend(p::CairoPattern, val)
ccall((:cairo_pattern_set_extend,libcairo), Nothing,
(Ptr{Nothing},Int32), p.ptr, val)
end
function pattern_create_radial(cx0::Real, cy0::Real, radius0::Real, cx1::Real, cy1::Real, radius1::Real)
ptr = ccall((:cairo_pattern_create_radial, libcairo),
Ptr{Nothing}, (Float64,Float64,Float64,Float64,Float64,Float64),cx0,cy0,radius0,cx1,cy1,radius1)
pattern = CairoPattern(ptr)
finalizer(destroy, pattern)
pattern
end
function pattern_create_linear(x0::Real, y0::Real, x1::Real, y1::Real)
ptr = ccall((:cairo_pattern_create_linear, libcairo),
Ptr{Nothing}, (Float64,Float64,Float64,Float64),x0,y0,x1,y1)
pattern = CairoPattern(ptr)
finalizer(destroy, pattern)
pattern
end
function pattern_add_color_stop_rgb(pat::CairoPattern, offset::Real, red::Real, green::Real, blue::Real)
ccall((:cairo_pattern_add_color_stop_rgb, libcairo),
Nothing, (Ptr{Nothing},Float64,Float64,Float64,Float64),pat.ptr,offset,red,green,blue)
end
function pattern_add_color_stop_rgba(pat::CairoPattern, offset::Real, red::Real, green::Real, blue::Real, alpha::Real)
ccall((:cairo_pattern_add_color_stop_rgba, libcairo),
Nothing, (Ptr{Nothing},Float64,Float64,Float64,Float64,Float64),pat.ptr,offset,red,green,blue,alpha)
end
function pattern_get_surface(pat::CairoPattern)
ptrref = Ref{Ptr{Nothing}}()
status = ccall((:cairo_pattern_get_surface, libcairo), Cint,
(Ptr{Nothing}, Ref{Ptr{Nothing}}), pat.ptr, ptrref)
if status == STATUS_PATTERN_TYPE_MISMATCH
error("Cannot get surface from a non-surface pattern.")
end
ptr = ptrref.x
ccall((:cairo_surface_reference, libcairo), Ptr{Nothing}, (Ptr{Nothing},), ptr)
typ = ccall((:cairo_surface_get_type, libcairo), Cint, (Ptr{Nothing},), ptr)
w = 0.0
h = 0.0
if typ == CAIRO_SURFACE_TYPE_IMAGE
w = ccall((:cairo_image_surface_get_width, libcairo),
Int32, (Ptr{Nothing},), ptr)
h = ccall((:cairo_image_surface_get_height, libcairo),
Int32, (Ptr{Nothing},), ptr)
end
return CairoSurface(ptr, w, h)
end
function destroy(pat::CairoPattern)
if pat.ptr == C_NULL
return
end
ccall((:cairo_pattern_destroy,libcairo), Nothing, (Ptr{Nothing},), pat.ptr)
pat.ptr = C_NULL
nothing
end
# mesh pattern
# create mesh pattern
function CairoPatternMesh()
ptr = ccall((:cairo_pattern_create_mesh, libcairo),
Ptr{Nothing}, ())
pattern = CairoPattern(ptr)
#status = ccall((:cairo_pattern_status, libcairo),
# Cint, (Ptr{Nothing},), pattern.ptr)
#if status != 0
# error("Error creating Cairo pattern: ", bytestring(
# ccall((:cairo_status_to_string, libcairo),
# Ptr{Uint8}, (Cint,), status)))
#end
finalizer(destroy, pattern)
pattern
end
#for (NAME, FUNCTION) in Any[(:set_line_width, :cairo_set_line_width),
# (:rotate, :cairo_rotate),
# (:set_font_size, :cairo_set_font_size)]
# @eval begin
# $NAME(ctx::CairoContext, d0::Real) =
# ccall(($(Expr(:quote,FUNCTION)),libcairo),
# Nothing, (Ptr{Nothing},Float64), ctx.ptr, d0)
# end
#end
for (NAME, FUNCTION) in Any[(:mesh_pattern_begin_patch, :cairo_mesh_pattern_begin_patch),
(:mesh_pattern_end_patch, :cairo_mesh_pattern_end_patch)]
@eval begin
$NAME(pattern::CairoPattern) =
ccall(($(Expr(:quote,FUNCTION)),libcairo),
Nothing, (Ptr{Nothing},), pattern.ptr)
end
end
for (NAME, FUNCTION) in Any[(:mesh_pattern_line_to, :cairo_mesh_pattern_line_to),
(:mesh_pattern_move_to, :cairo_mesh_pattern_move_to)]
@eval begin
$NAME(pattern::CairoPattern, d0::Real, d1::Real) =
ccall(($(Expr(:quote,FUNCTION)),libcairo),
Nothing, (Ptr{Nothing},Float64,Float64), pattern.ptr, d0, d1)
end
end
for (NAME, FUNCTION) in Any[(:mesh_pattern_curve_to, :cairo_mesh_pattern_curve_to)]
@eval begin
$NAME(pattern::CairoPattern, d0::Real, d1::Real, d2::Real, d3::Real, d4::Real, d5::Real) =
ccall(($(Expr(:quote,FUNCTION)),libcairo),
Nothing, (Ptr{Nothing},Float64,Float64,Float64,Float64,Float64,Float64), pattern.ptr, d0, d1, d2, d3, d4, d5)
end
end
function mesh_pattern_set_corner_color_rgb(pat::CairoPattern, corner_num::Real, red::Real, green::Real, blue::Real)
ccall((:cairo_mesh_pattern_set_corner_color_rgb, libcairo),
Nothing, (Ptr{Nothing},Int32,Float64,Float64,Float64),pat.ptr,corner_num,red,green,blue)
end
function mesh_pattern_set_corner_color_rgba(pat::CairoPattern, corner_num::Real, red::Real, green::Real, blue::Real, alpha::Real)
ccall((:cairo_mesh_pattern_set_corner_color_rgba, libcairo),
Nothing, (Ptr{Nothing},Int32,Float64,Float64,Float64,Float64),pat.ptr,corner_num,red,green,blue,alpha)
end
# ----
set_antialias(ctx::CairoContext, a) =
ccall((:cairo_set_antialias,libcairo), Nothing,
(Ptr{Nothing},Cint), ctx.ptr, a)
get_antialias(ctx::CairoContext) =
ccall((:cairo_get_antialias,libcairo), Cint,
(Ptr{Nothing},), ctx.ptr)
# -----------------------------------------------------------------------------
struct CairoMatrix
xx::Float64
yx::Float64
xy::Float64
yy::Float64
x0::Float64
y0::Float64
end
CairoMatrix() = CairoMatrix(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
function get_matrix(ctx::CairoContext)
m = [CairoMatrix()]
ccall((:cairo_get_matrix, libcairo), Nothing, (Ptr{Nothing}, Ptr{Nothing}), ctx.ptr, m)
m[1]
end
function set_matrix(ctx::CairoContext, m::CairoMatrix)
ccall((:cairo_set_matrix, libcairo), Nothing, (Ptr{Nothing}, Ptr{Nothing}), ctx.ptr, [m])
end
function set_matrix(p::CairoPattern, m::CairoMatrix)
ccall((:cairo_pattern_set_matrix, libcairo), Nothing, (Ptr{Nothing}, Ptr{Nothing}), p.ptr, [m])
end
# -----------------------------------------------------------------------------
function get_font_matrix(ctx::CairoContext)
m = [CairoMatrix()]
ccall((:cairo_get_font_matrix, libcairo), Nothing, (Ptr{Nothing}, Ptr{Nothing}), ctx.ptr, m)
m[1]
end
function set_font_matrix(ctx::CairoContext, m::CairoMatrix)
ccall((:cairo_set_font_matrix, libcairo), Nothing, (Ptr{Nothing}, Ptr{Nothing}), ctx.ptr, [m])
end
# -----------------------------------------------------------------------------
function set_line_type(ctx::CairoContext, nick::AbstractString)
if nick == "solid"
dash = Float64[]
elseif nick == "dotted" || nick == "dot"
dash = [1.,3.]
elseif nick == "dotdashed"
dash = [1.,3.,4.,4.]
elseif nick == "longdashed"
dash = [6.,6.]
elseif nick == "shortdashed" || nick == "dash" || nick == "dashed"
dash = [4.,4.]
elseif nick == "dotdotdashed"
dash = [1.,3.,1.,3.,4.,4.]
elseif nick == "dotdotdotdashed"
dash = [1.,3.,1.,3.,1.,3.,4.,4.]
else
error("unknown line type ", nick)
end
set_dash(ctx, dash)
end
# -----------------------------------------------------------------------------
# text commands
function set_font_face(ctx::CairoContext, str::AbstractString)
fontdesc = ccall((:pango_font_description_from_string,libpango),
Ptr{Nothing}, (Ptr{UInt8},), String(str))
ccall((:pango_layout_set_font_description,libpango), Nothing,
(Ptr{Nothing},Ptr{Nothing}), ctx.layout, fontdesc)
ccall((:pango_font_description_free,libpango), Nothing,
(Ptr{Nothing},), fontdesc)
end
function set_text(ctx::CairoContext, text::AbstractString, markup::Bool = false)
if markup
ccall((:pango_layout_set_markup,libpango), Nothing,
(Ptr{Nothing},Ptr{UInt8},Int32), ctx.layout, String(text), -1)
else
# clear attributes (from previous set markups)
ccall((:pango_layout_set_attributes,libpango), Nothing,
(Ptr{Nothing},Ptr{Nothing}), ctx.layout, C_NULL)
ccall((:pango_layout_set_text,libpango), Nothing,
(Ptr{Nothing},Ptr{UInt8},Int32), ctx.layout, String(text), -1)
end
text
end
function get_layout_size(ctx::CairoContext)
w = Vector{Int32}(undef, 2)
ccall((:pango_layout_get_pixel_size,libpango), Nothing,
(Ptr{Nothing},Ptr{Int32},Ptr{Int32}), ctx.layout, Ref(w,1), Ref(w,2))
w
end
function update_layout(ctx::CairoContext)
ccall((:pango_cairo_update_layout,libpangocairo), Nothing,
(Ptr{Nothing},Ptr{Nothing}), ctx.ptr, ctx.layout)
end
function show_layout(ctx::CairoContext)
ccall((:pango_cairo_show_layout,libpangocairo), Nothing,
(Ptr{Nothing},Ptr{Nothing}), ctx.ptr, ctx.layout)
end
text_extents(ctx::CairoContext,value::AbstractString) =
text_extents!(ctx,value, Matrix{Float64}(undef, 6, 1))
function text_extents!(ctx::CairoContext,value::AbstractString,extents)
ccall((:cairo_text_extents, libcairo),
Nothing, (Ptr{Nothing}, Ptr{UInt8}, Ptr{Float64}),
ctx.ptr, String(value), extents)
extents
end
function path_extents(ctx::CairoContext)
dx1 = Cdouble[0]
dx2 = Cdouble[0]
dy1 = Cdouble[0]
dy2 = Cdouble[0]
ccall((:cairo_path_extents, libcairo),
Nothing, (Ptr{Nothing}, Ptr{Cdouble}, Ptr{Cdouble},
Ptr{Cdouble}, Ptr{Cdouble}),
ctx.ptr, dx1, dy1, dx2, dy2)
return(dx1[1],dy1[1],dx2[1],dy2[1])
end
function show_text(ctx::CairoContext,value::AbstractString)
ccall((:cairo_show_text, libcairo),
Nothing, (Ptr{Nothing}, Ptr{UInt8}),
ctx.ptr, String(value))
end
function text_path(ctx::CairoContext,value::AbstractString)
ccall((:cairo_text_path, libcairo),
Nothing, (Ptr{Nothing}, Ptr{UInt8}),
ctx.ptr, String(value))
end
function select_font_face(ctx::CairoContext,family::AbstractString,slant,weight)
ccall((:cairo_select_font_face, libcairo),
Nothing, (Ptr{Nothing}, Ptr{UInt8},
font_slant_t, font_weight_t),
ctx.ptr, String(family),
slant, weight)
end
function align2offset(a::AbstractString)
if a == "center" return 0.5
elseif a == "left" return 0.0
elseif a == "right" return 1.0
elseif a == "top" return 0.0
elseif a == "bottom" return 1.0
end
@assert false
end
function text(ctx::CairoContext, x::Real, y::Real, str::AbstractString;
halign::AbstractString = "left", valign::AbstractString = "bottom", angle::Real = 0, markup::Bool=false)
move_to(ctx, x, y)
save(ctx)
reset_transform(ctx)
rotate(ctx, -angle*pi/180.)
set_text(ctx, str, markup)
update_layout(ctx)
extents = get_layout_size(ctx)
dxrel = -align2offset(halign)
dyrel = align2offset(valign)
rel_move_to(ctx, dxrel*extents[1], -dyrel*extents[2])
show_layout(ctx)
restore(ctx)
w, h = Graphics.device_to_user(ctx, extents[1], extents[2])
BoundingBox(x+dxrel*w, x+(dxrel+1)*w, y-dyrel*h, y+(1-dyrel)*h)
end
function textwidth(ctx::CairoContext, str::AbstractString, markup::Bool = false)
set_text(ctx, str, markup)
extents = get_layout_size(ctx)
extents[1]
end
function textheight(ctx::CairoContext, str::AbstractString, markup::Bool = false)
set_text(ctx, str, markup)
extents = get_layout_size(ctx)
extents[2]
end
set_latex(ctx::CairoContext, str::AbstractString, fontsize::Real) = set_text(ctx, tex2pango(str, fontsize), true)
mutable struct TeXLexer
str::String
len::Int
pos::Int
token_stack::Array{String,1}
function TeXLexer(str::AbstractString)
s = String(str)
new(s, lastindex(s), 1, String[])
end
end
function get_token(self::TeXLexer)
if self.pos > self.len
return nothing
end
if length(self.token_stack) > 0
return pop!(self.token_stack)
end
str = self.str[self.pos:end]
re_control_sequence = r"^\\[a-zA-Z]+[ ]?|^\\[^a-zA-Z][ ]?"
m = match(re_control_sequence, str)
if m !== nothing
token = m.match
self.pos = self.pos + sizeof(token)
# consume trailing space
if length(token) > 2 && token[end] == ' '
token = token[1:end-1]
end
else
@static if VERSION >= v"0.7"
token, self.pos = iterate(self.str, self.pos)
else
token, self.pos = next(self.str, self.pos)
end
token = string(token)
end
return token
end
function put_token(self::TeXLexer, token)
push!(self.token_stack, token)
end
function peek(self::TeXLexer)
token = get_token(self)
put_token(self, token)
return token
end
function map_text_token(token::AbstractString)
if haskey(_text_token_dict, token)
return _text_token_dict[token]
else
return get(_common_token_dict, token, token)
end
end
function map_math_token(token::AbstractString)
if haskey(_math_token_dict, token)
return _math_token_dict[token]
else
return get(_common_token_dict, token, token)
end
end
function math_group(lexer::TeXLexer)
output = ""
bracketmode = false
while true
token = get_token(lexer)
if token == nothing
break
end
if token == "{"
bracketmode = true
elseif token == "}"
break
else
output = string(output, map_math_token(token))
if !bracketmode
break
end
end
end
return output
end
#font_code = [ "\\f0", "\\f1", "\\f2", "\\f3" ]
function tex2pango(str::AbstractString, fontsize::Real)
output = ""
mathmode = true
font_stack = Any[]
font = 1
script_size = fontsize/1.618034
lexer = TeXLexer(str)
while true
token = get_token(lexer)
if token == nothing
break
end
more_output = ""
if token == "\$"
# mathmode = !mathmode
more_output = "\$"
elseif token == "{"
push!(font_stack, font)
elseif token == "}"
old_font = pop!(font_stack)
if old_font != font
font = old_font
# more_output = font_code[font]
end
elseif token == "\\rm"
font = 1
# more_output = font_code[font]
elseif token == "\\it"
font = 2
# more_output = font_code[font]
elseif token == "\\bf"
font = 3
# more_output = font_code[font]
elseif !mathmode
more_output = map_text_token(token)
elseif token == "_"
more_output = string("<sub><span font=\"$script_size\">", math_group(lexer), "</span></sub>")
#if peek(lexer) == "^"
# more_output = string("\\mk", more_output, "\\rt")
#end
elseif token == "^"
more_output = string("<sup><span font=\"$script_size\">", math_group(lexer), "</span></sup>")
#if peek(lexer) == "_"
# more_output = string("\\mk", more_output, "\\rt")
#end
else
more_output = map_math_token(token)
end
output = string(output, more_output)
end
return output
end
@deprecate text(ctx::CairoContext,x::Real,y::Real,str::AbstractString,fontsize::Real,halign::AbstractString,valign,angle) text(ctx,x,y,set_latex(ctx,str,fontsize),halign=halign,valign=valign,angle=angle,markup=true)
@deprecate layout_text(ctx::CairoContext, str::AbstractString, fontsize::Real) set_latex(ctx, str, fontsize)
@deprecate textwidth(ctx::CairoContext, str::AbstractString, fontsize::Real) textwidth(ctx, tex2pango(str, fontsize), true)
@deprecate textheight(ctx::CairoContext, str::AbstractString, fontsize::Real) textheight(ctx, tex2pango(str, fontsize), true)
@deprecate cairo_write_to_ios_callback(s::Ptr{Nothing}, buf::Ptr{UInt8}, len::UInt32) write_to_ios_callback(s, buf, len)
@deprecate cairo_write_to_stream_callback(s::IO, buf::Ptr{UInt8}, len::UInt32) write_to_stream_callback(s, buf, len)
@deprecate text_extents(ctx::CairoContext,value::AbstractString,extents) text_extents!(ctx,value,extents)
if Base.VERSION >= v"1.4.2"
ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
@assert precompile(Tuple{typeof(CairoImageSurface),Matrix{UInt32},Int32}) # time: 0.03191977
@assert precompile(Tuple{typeof(copy),CairoContext}) # time: 0.02283907
@assert precompile(Tuple{typeof(image),CairoContext,CairoSurfaceImage{UInt32},Int,Int,Float64,Float64}) # time: 0.002372729
@assert precompile(Tuple{typeof(image),CairoContext,CairoSurfaceImage{UInt32},Float64,Float64,Float64,Float64})
@assert precompile(Tuple{typeof(surface_create_similar),CairoSurfaceBase{UInt32}}) # time: 0.001453267
@assert precompile(Tuple{typeof(user_to_device!),CairoContext,Vector{Float64}}) # time: 0.001948533
@assert precompile(Tuple{typeof(device_to_user!),CairoContext,Vector{Float64}}) # time: 0.001546066
@assert precompile(Tuple{typeof(destroy),CairoSurfaceImage{UInt32}}) # time: 0.001699678
@assert precompile(Tuple{typeof(destroy),CairoContext}) # time: 0.001185085
@assert precompile(Tuple{Type{CairoContext},CairoSurfaceBase{UInt32}}) # time: 0.001118005
end
end # module
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 15201 | ## Cairo Constants ##
# deprecated exports---do not add more!
export CAIRO_FORMAT_ARGB32,
CAIRO_FORMAT_RGB24,
CAIRO_FORMAT_A8,
CAIRO_FORMAT_A1,
CAIRO_FORMAT_RGB16_565,
CAIRO_CONTENT_COLOR,
CAIRO_CONTENT_ALPHA,
CAIRO_CONTENT_COLOR_ALPHA,
CAIRO_FILTER_FAST,
CAIRO_FILTER_GOOD,
CAIRO_FILTER_BEST,
CAIRO_FILTER_NEAREST,
CAIRO_FILTER_BILINEAR,
CAIRO_FILTER_GAUSSIAN
const format_t = Int32
const FORMAT_INVALID = Int32(-1)
const FORMAT_ARGB32 = Int32(0)
const FORMAT_RGB24 = Int32(1)
const FORMAT_A8 = Int32(2)
const FORMAT_A1 = Int32(3)
const FORMAT_RGB16_565 = Int32(4)
const FORMAT_RGB30 = Int32(5)
const status_t = Int32
const STATUS_SUCCESS = Int32(0)
const STATUS_NO_MEMORY = Int32(1)
const STATUS_INVALID_RESTORE = Int32(2)
const STATUS_INVALID_POP_GROUP = Int32(3)
const STATUS_NO_CURRENT_POINT = Int32(4)
const STATUS_INVALID_MATRIX = Int32(5)
const STATUS_INVALID_STATUS = Int32(6)
const STATUS_NULL_POINTER = Int32(7)
const STATUS_INVALID_STRING = Int32(8)
const STATUS_INVALID_PATH_DATA = Int32(9)
const STATUS_READ_ERROR = Int32(10)
const STATUS_WRITE_ERROR = Int32(11)
const STATUS_SURFACE_FINISHED = Int32(12)
const STATUS_SURFACE_TYPE_MISMATCH = Int32(13)
const STATUS_PATTERN_TYPE_MISMATCH = Int32(14)
const STATUS_INVALID_CONTENT = Int32(15)
const STATUS_INVALID_FORMAT = Int32(16)
const STATUS_INVALID_VISUAL = Int32(17)
const STATUS_FILE_NOT_FOUND = Int32(17)
const STATUS_INVALID_DASH = Int32(18)
const STATUS_INVALID_DSC_COMMENT = Int32(19)
const STATUS_INVALID_INDEX = Int32(20)
const STATUS_CLIP_NOT_REPRESENTABLE = Int32(21)
const STATUS_TEMP_FILE_ERROR = Int32(22)
const STATUS_INVALID_STRIDE = Int32(23)
const STATUS_FONT_TYPE_MISMATCH = Int32(24)
const STATUS_USER_FONT_IMMUTABLE = Int32(25)
const STATUS_USER_FONT_ERROR = Int32(26)
const STATUS_NEGATIVE_COUNT = Int32(27)
const STATUS_INVALID_CLUSTERS = Int32(28)
const STATUS_INVALID_SLANT = Int32(29)
const STATUS_INVALID_WEIGHT = Int32(30)
const STATUS_INVALID_SIZE = Int32(31)
const STATUS_USER_FONT_NOT_IMPLEMENTED = Int32(32)
const STATUS_DEVICE_TYPE_MISMATCH = Int32(33)
const STATUS_DEVICE_ERROR = Int32(34)
const STATUS_INVALID_MESH_CONSTRUCTION = Int32(35)
const STATUS_DEVICE_FINISHED = Int32(36)
const STATUS_LAST_STATUS = Int32(37)
const surface_t = Int32
const CAIRO_SURFACE_TYPE_IMAGE = Int32(0)
const CAIRO_SURFACE_TYPE_PDF, = Int32(1)
const CAIRO_SURFACE_TYPE_PS, = Int32(2)
const CAIRO_SURFACE_TYPE_XLIB, = Int32(3)
const CAIRO_SURFACE_TYPE_XCB, = Int32(4)
const CAIRO_SURFACE_TYPE_GLITZ, = Int32(5)
const CAIRO_SURFACE_TYPE_QUARTZ, = Int32(6)
const CAIRO_SURFACE_TYPE_WIN32, = Int32(7)
const CAIRO_SURFACE_TYPE_BEOS, = Int32(8)
const CAIRO_SURFACE_TYPE_DIRECTFB, = Int32(9)
const CAIRO_SURFACE_TYPE_SVG, = Int32(10)
const CAIRO_SURFACE_TYPE_OS2, = Int32(11)
const CAIRO_SURFACE_TYPE_WIN32_PRINTING, = Int32(12)
const CAIRO_SURFACE_TYPE_QUARTZ_IMAGE, = Int32(13)
const CAIRO_SURFACE_TYPE_SCRIPT, = Int32(14)
const CAIRO_SURFACE_TYPE_QT, = Int32(15)
const CAIRO_SURFACE_TYPE_RECORDING, = Int32(16)
const CAIRO_SURFACE_TYPE_VG, = Int32(17)
const CAIRO_SURFACE_TYPE_GL, = Int32(18)
const CAIRO_SURFACE_TYPE_DRM, = Int32(19)
const CAIRO_SURFACE_TYPE_TEE, = Int32(20)
const CAIRO_SURFACE_TYPE_XML, = Int32(21)
const CAIRO_SURFACE_TYPE_SKIA, = Int32(22)
const CAIRO_SURFACE_TYPE_SUBSURFACE, = Int32(23)
const CAIRO_SURFACE_TYPE_COGL = Int32(24)
const font_slant_t = Int32
const FONT_SLANT_NORMAL = Int32(0)
const FONT_SLANT_ITALIC = Int32(1)
const FONT_SLANT_OBLIQUE = Int32(2)
const font_weight_t = Int32
const FONT_WEIGHT_NORMAL = Int32(0)
const FONT_WEIGHT_BOLD = Int32(1)
const CONTENT_COLOR = Int32(0x1000)
const CONTENT_ALPHA = Int32(0x2000)
const CONTENT_COLOR_ALPHA = Int32(0x3000)
const FILTER_FAST = 0
const FILTER_GOOD = 1
const FILTER_BEST = 2
const FILTER_NEAREST = 3
const FILTER_BILINEAR = 4
const FILTER_GAUSSIAN = 5
const EXTEND_NONE = 0
const EXTEND_REPEAT = 1
const EXTEND_REFLECT = 2
const EXTEND_PAD = 3
const ANTIALIAS_DEFAULT = 0
const ANTIALIAS_NONE = 1
const ANTIALIAS_GRAY = 2
const ANTIALIAS_SUBPIXEL = 3
# next 3 are not available on all Cairo installations (only since 1.12)
const ANTIALIAS_FAST = 4
const ANTIALIAS_GOOD = 5
const ANTIALIAS_BEST = 6
const OPERATOR_CLEAR = 0
const OPERATOR_SOURCE = 1
const OPERATOR_OVER = 2
const OPERATOR_IN = 3
const OPERATOR_OUT = 4
const OPERATOR_ATOP = 5
const OPERATOR_DEST = 6
const OPERATOR_DEST_OVER = 7
const OPERATOR_DEST_IN = 8
const OPERATOR_DEST_OUT = 9
const OPERATOR_DEST_ATOP = 10
const OPERATOR_XOR = 11
const OPERATOR_ADD = 12
const OPERATOR_SATURATE = 13
const OPERATOR_MULTIPLY = 14
const OPERATOR_SCREEN = 15
const OPERATOR_OVERLAY = 16
const OPERATOR_DARKEN = 17
const OPERATOR_LIGHTEN = 18
## LaTex Token Dicts ##
const _common_token_dict = Dict(
"\\{" => "{",
"\\}" => "}",
"\\_" => "_",
"\\^" => "^",
"\\-" => "-",
## ignore stray brackets
"{" => "",
"}" => ""
)
const _text_token_dict = Dict(
## non-math symbols (p438)
"\\S" => "\ua7",
"\\P" => "\ub6",
"\\dag" => "\u2020",
"\\ddag" => "\u2021"
)
const _math_token_dict = Dict(
"-" => "\u2212", # minus sign
## spacing
"\\quad" => "\u2003", # 1 em
"\\qquad" => "\u2003\u2003", # 2 em
"\\," => "\u2006", # 3/18 em
"\\>" => "\u2005", # 4/18 em
"\\;" => "\u2004", # 5/18 em
## lowercase greek
"\\alpha" => "\u03b1",
"\\beta" => "\u03b2",
"\\gamma" => "\u03b3",
"\\delta" => "\u03b4",
"\\epsilon" => "\u03b5",
"\\varepsilon" => "\u03f5",
"\\zeta" => "\u03b6",
"\\eta" => "\u03b7",
"\\theta" => "\u03b8",
"\\vartheta" => "\u03d1",
"\\iota" => "\u03b9",
"\\kappa" => "\u03ba",
"\\lambda" => "\u03bb",
"\\mu" => "\u03bc",
"\\nu" => "\u03bd",
"\\xi" => "\u03be",
"\\omicron" => "\u03bf",
"\\pi" => "\u03c0",
"\\varpi" => "\u03d6",
"\\rho" => "\u03c1",
"\\varrho" => "\u03f1",
"\\sigma" => "\u03c3",
"\\varsigma" => "\u03c2",
"\\tau" => "\u03c4",
"\\upsilon" => "\u03c5",
"\\phi" => "\u03d5",
"\\varphi" => "\u03c6",
"\\chi" => "\u03c7",
"\\psi" => "\u03c8",
"\\omega" => "\u03c9",
## uppercase greek
"\\Alpha" => "\u0391",
"\\Beta" => "\u0392",
"\\Gamma" => "\u0393",
"\\Delta" => "\u0394",
"\\Epsilon" => "\u0395",
"\\Zeta" => "\u0396",
"\\Eta" => "\u0397",
"\\Theta" => "\u0398",
"\\Iota" => "\u0399",
"\\Kappa" => "\u039a",
"\\Lambda" => "\u039b",
"\\Mu" => "\u039c",
"\\Nu" => "\u039d",
"\\Xi" => "\u039e",
"\\Pi" => "\u03a0",
"\\Rho" => "\u03a1",
"\\Sigma" => "\u03a3",
"\\Tau" => "\u03a4",
"\\Upsilon" => "\u03a5",
"\\Phi" => "\u03a6",
"\\Chi" => "\u03a7",
"\\Psi" => "\u03a8",
"\\Omega" => "\u03a9",
## miscellaneous
"\\aleph" => "\u2135",
"\\hbar" => "\u210f",
"\\ell" => "\u2113",
"\\wp" => "\u2118",
"\\Re" => "\u211c",
"\\Im" => "\u2111",
"\\partial" => "\u2202",
"\\infty" => "\u221e",
"\\prime" => "\u2032",
"\\emptyset" => "\u2205",
"\\nabla" => "\u2206",
"\\surd" => "\u221a",
"\\top" => "\u22a4",
"\\bot" => "\u22a5",
"\\|" => "\u2225",
"\\angle" => "\u2220",
"\\triangle" => "\u25b3", # == \bigtriangleup
"\\backslash" => "\u2216",
"\\forall" => "\u2200",
"\\exists" => "\u2203",
"\\neg" => "\uac",
"\\flat" => "\u266d",
"\\natural" => "\u266e",
"\\sharp" => "\u266f",
"\\clubsuit" => "\u2663",
"\\diamondsuit" => "\u2662",
"\\heartsuit" => "\u2661",
"\\spadesuit" => "\u2660",
## large operators
"\\sum" => "\u2211",
"\\prod" => "\u220f",
"\\coprod" => "\u2210",
"\\int" => "\u222b",
"\\oint" => "\u222e",
"\\bigcap" => "\u22c2",
"\\bigcup" => "\u22c3",
"\\bigscup" => "\u2a06",
"\\bigvee" => "\u22c1",
"\\bigwedge" => "\u22c0",
"\\bigodot" => "\u2a00",
"\\bigotimes" => "\u2a02",
"\\bigoplus" => "\u2a01",
"\\biguplus" => "\u2a04",
## binary operations
"\\pm" => "\ub1",
"\\mp" => "\u2213",
"\\setminus" => "\u2216",
"\\cdot" => "\u22c5",
"\\times" => "\ud7",
"\\ast" => "\u2217",
"\\star" => "\u22c6",
"\\diamond" => "\u22c4",
"\\circ" => "\u2218",
"\\bullet" => "\u2219",
"\\div" => "\uf7",
"\\cap" => "\u2229",
"\\cup" => "\u222a",
"\\uplus" => "\u228c", # 228e?
"\\sqcap" => "\u2293",
"\\sqcup" => "\u2294",
"\\triangleleft" => "\u22b2",
"\\triangleright" => "\u22b3",
"\\wr" => "\u2240",
"\\bigcirc" => "\u25cb",
"\\bigtriangleup" => "\u25b3", # == \triangle
"\\bigtriangledown" => "\u25bd",
"\\vee" => "\u2228",
"\\wedge" => "\u2227",
"\\oplus" => "\u2295",
"\\ominus" => "\u2296",
"\\otimes" => "\u2297",
"\\oslash" => "\u2298",
"\\odot" => "\u2299",
"\\dagger" => "\u2020",
"\\ddagger" => "\u2021",
"\\amalg" => "\u2210",
## relations
"\\leq" => "\u2264",
"\\prec" => "\u227a",
"\\preceq" => "\u227c",
"\\ll" => "\u226a",
"\\subset" => "\u2282",
"\\subseteq" => "\u2286",
"\\sqsubseteq" => "\u2291",
"\\in" => "\u2208",
"\\vdash" => "\u22a2",
"\\smile" => "\u2323",
"\\frown" => "\u2322",
"\\geq" => "\u2265",
"\\succ" => "\u227b",
"\\succeq" => "\u227d",
"\\gg" => "\u226b",
"\\supset" => "\u2283",
"\\supseteq" => "\u2287",
"\\sqsupseteq" => "\u2292",
"\\ni" => "\u220b",
"\\dashv" => "\u22a3",
"\\mid" => "\u2223",
"\\parallel" => "\u2225",
"\\equiv" => "\u2261",
"\\sim" => "\u223c",
"\\simeq" => "\u2243",
"\\asymp" => "\u224d",
"\\approx" => "\u2248",
"\\cong" => "\u2245",
"\\bowtie" => "\u22c8",
"\\propto" => "\u221d",
"\\models" => "\u22a7", # 22a8?
"\\doteq" => "\u2250",
"\\perp" => "\u27c2",
## arrows
"\\leftarrow" => "\u2190",
"\\Leftarrow" => "\u21d0",
"\\rightarrow" => "\u2192",
"\\Rightarrow" => "\u21d2",
"\\leftrightarrow" => "\u2194",
"\\Leftrightarrow" => "\u21d4",
"\\mapsto" => "\u21a6",
"\\hookleftarrow" => "\u21a9",
"\\leftharpoonup" => "\u21bc",
"\\leftharpoondown" => "\u21bd",
"\\rightleftharpoons" => "\u21cc",
"\\longleftarrow" => "\u27f5",
"\\Longleftarrow" => "\u27f8",
"\\longrightarrow" => "\u27f6",
"\\Longrightarrow" => "\u27f9",
"\\longleftrightarrow" => "\u27f7",
"\\Longleftrightarrow" => "\u27fa",
"\\hookrightarrow" => "\u21aa",
"\\rightharpoonup" => "\u21c0",
"\\rightharpoondown" => "\u21c1",
"\\uparrow" => "\u2191",
"\\Uparrow" => "\u21d1",
"\\downarrow" => "\u2193",
"\\Downarrow" => "\u21d3",
"\\updownarrow" => "\u2195",
"\\Updownarrow" => "\u21d5",
"\\nearrow" => "\u2197",
"\\searrow" => "\u2198",
"\\swarrow" => "\u2199",
"\\nwarrow" => "\u2196",
## openings
# "\\lbrack" => "[",
# "\\lbrace" => "{",
"\\langle" => "\u27e8",
"\\lfloor" => "\u230a",
"\\lceil" => "\u2308",
## closings
# "\\rbrack" => "]",
# "\\rbrace" => "}",
"\\rangle" => "\u27e9",
"\\rfloor" => "\u230b",
"\\rceil" => "\u2309",
## alternate names
"\\ne" => "\u2260",
"\\neq" => "\u2260",
"\\le" => "\u2264",
"\\ge" => "\u2265",
"\\to" => "\u2192",
"\\gets" => "\u2192",
"\\owns" => "\u220b",
"\\land" => "\u2227",
"\\lor" => "\u2228",
"\\lnot" => "\uac",
"\\vert" => "\u2223",
"\\Vert" => "\u2225",
## extensions
"\\deg" => "\ub0",
"\\degr" => "\ub0",
"\\degree" => "\ub0",
"\\degrees" => "\ub0",
"\\arcdeg" => "\ub0",
"\\arcmin" => "\u2032",
"\\arcsec" => "\u2033"
)
const CAIRO_FILL_RULE_WINDING = Int32(0);
const CAIRO_FILL_RULE_EVEN_ODD = Int32(1);
const CAIRO_LINE_CAP_BUTT = Int32(0);
const CAIRO_LINE_CAP_ROUND = Int32(1);
const CAIRO_LINE_CAP_SQUARE = Int32(2);
const CAIRO_LINE_JOIN_MITER = Int32(0);
const CAIRO_LINE_JOIN_ROUND = Int32(1);
const CAIRO_LINE_JOIN_BEVEL = Int32(2);
#typedef enum _cairo_path_data_type {
# CAIRO_PATH_MOVE_TO,
# CAIRO_PATH_LINE_TO,
# CAIRO_PATH_CURVE_TO,
# CAIRO_PATH_CLOSE_PATH
#} cairo_path_data_type_t;
const CAIRO_PATH_MOVE_TO = Int32(0);
const CAIRO_PATH_LINE_TO = Int32(1);
const CAIRO_PATH_CURVE_TO = Int32(2);
const CAIRO_PATH_CLOSE_PATH = Int32(3);
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 9875 | using Cairo
using Colors
import Base.Sys
import Base.show
using Test
# Test that an the CairoSurface holds a reference to the passed IOBuffer
@testset "IOBuffer Rooting " begin
CairoSVGSurface(IOBuffer(), 200, 110)
GC.gc()
GC.gc()
end
# Image Surface
@testset "Image Surface " begin
surf = CairoImageSurface(100, 200, Cairo.FORMAT_ARGB32)
@test @inferred(width(surf)) == 100
@test @inferred(height(surf)) == 200
abstractsurf = Ref{CairoSurface}(surf)
getwidth(r) = width(r[])
getheight(r) = height(r[])
@test @inferred(getwidth(abstractsurf)) == 100
@test @inferred(getheight(abstractsurf)) == 200
ctx = CairoContext(surf)
@test @inferred(width(ctx)) == 100
@test @inferred(height(ctx)) == 200
surf = CairoImageSurface(fill(RGB24(0), 10, 10))
@test Cairo.format(surf) == RGB24
io = IOBuffer()
show(io, MIME("image/png"), surf)
seek(io,0)
str_data = Vector{UInt8}(read(io))
@test length(str_data) > 8 && str_data[1:8] == [0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a]
surf = CairoImageSurface(fill(ARGB32(0), 10, 10))
@test Cairo.format(surf) == ARGB32
end
@testset "Conversions " begin
include("shape_functions.jl")
include("test_stream.jl")
function test_pattern_get_surface()
# test getting a surface from a surface pattern
surf = CairoImageSurface(100, 200, Cairo.FORMAT_ARGB32)
ctx = CairoContext(surf)
Cairo.push_group(ctx)
pattern = Cairo.pop_group(ctx)
group_surf = Cairo.pattern_get_surface(pattern)
@test group_surf.width == 100
@test group_surf.height == 200
# test that surfaces can't be gotten from non-surface patterns
pattern = Cairo.pattern_create_linear(0, 0, 100, 200)
@test_throws ErrorException Cairo.pattern_get_surface(pattern)
end
test_pattern_get_surface()
# Test creating a CairoContext from a cairo_t pointer
surf = CairoImageSurface(fill(ARGB32(0), 10, 10))
ctx_ptr = ccall((:cairo_create, Cairo.libcairo),Ptr{Nothing}, (Ptr{Nothing}, ), surf.ptr)
ctx = CairoContext(ctx_ptr)
ccall((:cairo_destroy,Cairo.libcairo),Nothing, (Ptr{Nothing}, ), ctx_ptr)
@test isa(ctx, CairoContext)
end
@testset "TexLexer " begin
include("tex.jl")
end
# Run all the samples -> success, if output file exits
@testset "Samples " begin
samples_dir_path = joinpath(dirname(dirname(@__FILE__)), "samples")
samples_files = filter(str->endswith(str,".jl"), readdir(samples_dir_path))
# filter known >= 1.12 -> sample_meshpattern.jl
if Cairo.libcairo_version < v"1.12.0"
files_to_exclude = ["sample_meshpattern.jl","sample_record0.jl","sample_record1.jl","sample_script0.jl"]
samples_files = setdiff(samples_files, files_to_exclude)
end
@testset "sample: $test_file_name" for test_file_name in samples_files
# Run each sample script in a separate module to avoid pollution
s = Symbol(test_file_name)
mod = @eval(Main, module $s end)
@eval mod include($(joinpath(samples_dir_path, test_file_name)))
output_png_name = replace(test_file_name,".jl" => ".png")
@test isfile(output_png_name)
rm(output_png_name)
end
end
# Run some painting, check the colored pixels by counting them
@testset "Bitmap Painting" begin
include("test_painting.jl")
# fill all
z = zeros(UInt32,512,512);
surf = CairoImageSurface(z, Cairo.FORMAT_ARGB32)
# fills a 512x512 pixel area with blue,0.5 by using a hilbert curve of
# dimension 64 (scaled by 8 -> 512) and a linewidth of 8
hdraw(surf,64,8,8)
d = simple_hist(surf.data)
@test length(d) == 1
@test collect(keys(d))[1] == 0x80000080
# fill 1/4 (upper quarter)
z = zeros(UInt32,512,512);
surf = CairoImageSurface(z, Cairo.FORMAT_ARGB32)
# fills a 256x256 pixel area with blue,0.5 by using a hilbert curve of
# dimension 32 (scaled by 8 -> 256) and a linewidth of 8
hdraw(surf,32,8,8)
d = simple_hist(surf.data)
@test length(d) == 2
@test d[0x80000080] == 256*256
# fill ~1/2 full,
z = zeros(UInt32,512,512);
surf = CairoImageSurface(z, Cairo.FORMAT_ARGB32)
# fills a 512x512 pixel area with blue,0.5 by using a hilbert curve of
# dimension 64 (scaled by 8 -> 512) and a linewidth of 4 -> 1/4 of pixels -16
hdraw(surf,64,8,4)
d = simple_hist(surf.data)
@test length(d) == 2
@test d[0x80000080] == ((512*256)-16)
end
# vector surfaces
@testset "Vector Surfaces" begin
output_file_name = "a.svg"
surf = CairoSVGSurface(output_file_name,512,512)
hdraw(surf,64,8,4)
finish(surf)
@test isfile(output_file_name)
rm(output_file_name)
io = IOBuffer()
surf = CairoSVGSurface(io,512,512)
hdraw(surf,64,8,4)
finish(surf)
seek(io,0)
str_data = Vector{UInt8}(read(io))
@test length(str_data) > 31000 && str_data[1:13] == [0x3c,0x3f,0x78,0x6d,0x6c,0x20,0x76,0x65,0x72,0x73,0x69,0x6f,0x6e]
output_file_name = "a.pdf"
surf = CairoPDFSurface(output_file_name,512,512)
hdraw(surf,64,8,4)
finish(surf)
@test isfile(output_file_name)
rm(output_file_name)
io = IOBuffer()
surf = CairoPDFSurface(io,512,512)
hdraw(surf,64,8,4)
finish(surf)
seek(io,0)
str_data = Vector{UInt8}(read(io))
@test length(str_data) > 3000 && str_data[1:7] == [0x25,0x50,0x44,0x46,0x2d,0x31,0x2e]
output_file_name = "a.eps"
surf = CairoEPSSurface(output_file_name,512,512)
hdraw(surf,64,8,4)
finish(surf)
@test isfile(output_file_name)
rm(output_file_name)
io = IOBuffer()
surf = CairoEPSSurface(io,512,512)
hdraw(surf,64,8,4)
finish(surf)
seek(io,0)
str_data = Vector{UInt8}(read(io))
@test length(str_data) > 3000 && str_data[1:10] == [0x25,0x21,0x50,0x53,0x2d,0x41,0x64,0x6f,0x62,0x65]
output_file_name = "a.ps"
surf = CairoPSSurface(output_file_name,512,512)
hdraw(surf,64,8,4)
finish(surf)
@test isfile(output_file_name)
rm(output_file_name)
io = IOBuffer()
surf = CairoPSSurface(io,512,512)
hdraw(surf,64,8,4)
finish(surf)
seek(io,0)
str_data = Vector{UInt8}(read(io))
@test length(str_data) > 3000 && str_data[1:10] == [0x25,0x21,0x50,0x53,0x2d,0x41,0x64,0x6f,0x62,0x65]
if Cairo.libcairo_version >= v"1.12.0"
# just write to surface and test for content
io = IOBuffer()
surf = CairoScriptSurface(io,512,512)
hdraw(surf,64,8,4)
finish(surf)
seek(io,0)
str_data = Vector{UInt8}(read(io))
@test length(str_data) > 3000 && str_data[1:10] == [0x25,0x21,0x43,0x61,0x69,0x72,0x6f,0x53,0x63,0x72]
# create_for_target
z = zeros(UInt32,512,512);
surf = CairoImageSurface(z, Cairo.FORMAT_ARGB32)
io = IOBuffer()
scsurf = CairoScriptSurface(io,surf)
hdraw(scsurf,64,8,8)
finish(surf)
destroy(scsurf)
seek(io,0)
str_data = Vector{UInt8}(read(io))
@test length(str_data) > 3000 && str_data[1:10] == [0x25,0x21,0x43,0x61,0x69,0x72,0x6f,0x53,0x63,0x72]
d = simple_hist(surf.data)
@test length(d) == 1
@test collect(keys(d))[1] == 0x80000080
end
end
# pixel/bitmap surfaces
@testset "Bitmap Surfaces" begin
z = zeros(UInt32,512,512)
surf = CairoImageSurface(z, Cairo.FORMAT_ARGB32)
hilbert_colored(surf)
d1 = matrix_read(surf)
d = simple_hist(d1)
@test length(d) == 513 # 512 colors and empty background
surf = CairoARGBSurface(z)
hilbert_colored(surf)
d1 = matrix_read(surf)
d = simple_hist(d1)
@test length(d) == 513
surf = CairoRGBSurface(z)
hilbert_colored(surf)
d1 = matrix_read(surf)
d = simple_hist(d1)
@test length(d) == 512 # black is included
# width: 5, height: 3; Test-Image
mat = [ 0x80800000 0x00000000 0x00000000
0x80800000 0x00000000 0x00000000
0x80800000 0x33000033 0x33000033
0x80800000 0x33000033 0x33000033
0xff00ff00 0xff00ff00 0x00000000 ]
surf = CairoImageSurface(mat, Cairo.FORMAT_ARGB32; flipxy=false)
data_arr = unsafe_wrap(Array, Cairo.image_surface_get_data(surf), (5, 3))
@test (mat == data_arr) && (mat == surf.data)
end
@testset "Assert/Status " begin
z = zeros(UInt32,512,512);
surf = CairoImageSurface(z, Cairo.FORMAT_ARGB32)
@test Cairo.status(surf) == 0
pa = surf.ptr
surf.ptr = C_NULL
@test destroy(surf) == nothing
surf.ptr = pa
cr = Cairo.CairoContext(surf)
pa = cr.ptr
cr.ptr = C_NULL
@test destroy(cr) == nothing
@test push_group(cr) == nothing
@test pop_group(cr) == nothing
@test_throws AssertionError Cairo.align2offset("to")
@test_throws ErrorException Cairo.set_line_type(cr,"nondef")
end
@testset "reset_transform" begin
using Graphics
z = zeros(UInt32,512,512);
surf = CairoImageSurface(z, Cairo.FORMAT_ARGB32)
@test Cairo.status(surf) == 0
pa = surf.ptr
surf.ptr = C_NULL
@test destroy(surf) == nothing
surf.ptr = pa
cr = Cairo.CairoContext(surf)
m1 = CairoMatrix(1, 0, 0, 1, 0, 0)
m2 = CairoMatrix(1.0,2.0,2.0,1.0,0.,0.)
m = get_matrix(cr)
@test m == m1
set_matrix(cr, m2)
@test get_matrix(cr) == m2
Graphics.reset_transform(cr)
@test get_matrix(cr) == m1
@test destroy(cr) == nothing
end
@testset "font_matrix" begin
z = zeros(UInt32,512,512);
surf = CairoImageSurface(z, Cairo.FORMAT_ARGB32)
pa = surf.ptr
surf.ptr = C_NULL
surf.ptr = pa
cr = Cairo.CairoContext(surf)
m = CairoMatrix(1.0,2.0,2.0,1.0,0.,0.)
set_font_matrix(cr, m)
@test m == get_font_matrix(cr)
@test destroy(cr) == nothing
end
nothing
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 8936 | using Cairo
using Random
# shape functions,
function randpos(n,w::Real,h::Real)
@static if VERSION >= v"0.7"
Random.seed!(141413)
else
srand(141413)
end
px = rand(n)*w
py = rand(n)*h
return (px,py)
end
function clear_bg(c::CairoContext,w::Real,h::Real)
save(c)
set_source_rgb(c,1.0,1.0,1.0)
rectangle(c, 0,0,w,h)
paint(c)
restore(c)
end
# ddotsx: fill random dots with different methods, disc only (no ring)
function ddots1(cr::CairoContext, rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
new_path(cr)
for i=1:n
move_to(cr,px[i],py[i])
rel_move_to(cr,radius,0)
arc(cr, px[i], py[i], radius, 0, 2*pi)
end
close_path(cr)
set_source_rgb(cr, 0, 0, 1.0)
fill(cr)
end
function ddots2(cr::CairoContext, rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
for i=1:n
new_path(cr)
move_to(cr,px[i],py[i])
rel_move_to(cr,radius,0)
arc(cr, px[i], py[i], radius, 0, 2*pi)
close_path(cr)
set_source_rgb(cr, 0, 0, 1.0)
fill(cr)
end
end
function ddots3(cr::CairoContext, rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
new_path(cr)
set_source_rgb(cr, 0, 0, 1.0)
set_line_cap(cr,Cairo.CAIRO_LINE_CAP_ROUND)
set_line_width(cr,radius*2.0)
for i=1:n
move_to(cr,px[i],py[i])
rel_line_to(cr,0,0)
stroke(cr)
end
close_path(cr)
end
function ddots4(cr::CairoContext,
rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
cc = radius + 1
rectangle(cr,0,0,2*cc,2*cc)
clip(cr)
push_group(cr)
arc(cr,radius,radius,radius,0,2*pi)
set_source_rgb(cr,0,0,1.0)
fill(cr)
p = pop_group(cr)
reset_clip(cr)
for i=1:n
save(cr)
translate(cr,px[i]-cc,py[i]-cc)
set_source(cr,p)
paint(cr)
restore(cr)
end
end
function ddots5(cr::CairoContext,
rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
cc = radius + 1
s1 = Cairo.CairoARGBSurface(cc*2,cc*2)
c1 = Cairo.CairoContext(s1)
rectangle(c1,0,0,2*cc,2*cc)
set_source_rgba(c1,0,0,0,0)
paint(c1)
new_path(c1)
arc(c1,radius,radius,radius,0,2*pi)
set_source_rgb(c1,0,0,1.0)
fill(c1)
p = Cairo.CairoPattern(s1)
for i=1:n
save(cr)
translate(cr,px[i]-cc,py[i]-cc)
set_source(cr,p)
paint(cr)
restore(cr)
end
end
# rdotsx: fill random dots with different methods
function rdots1(cr::CairoContext, rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
new_path(cr)
for i=1:n
move_to(cr,px[i],py[i])
rel_move_to(cr,radius,0)
arc(cr, px[i], py[i], radius, 0, 2*pi)
end
close_path(cr)
set_source_rgb(cr, 0, 0, 1.0)
fill_preserve(cr)
set_line_width(cr,1.0)
set_source_rgb(cr, 0, 0, 0)
stroke(cr)
end
function rdots2(cr::CairoContext, rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
for i=1:n
new_path(cr)
move_to(cr,px[i],py[i])
rel_move_to(cr,radius,0)
arc(cr, px[i], py[i], radius, 0, 2*pi)
close_path(cr)
set_source_rgb(cr, 0, 0, 1.0)
fill_preserve(cr)
set_line_width(cr,1.0)
set_source_rgb(cr, 0, 0, 0)
stroke(cr)
end
end
function rdots3(cr::CairoContext, rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
new_path(cr)
set_line_cap(cr,Cairo.CAIRO_LINE_CAP_ROUND)
set_source_rgb(cr, 0, 0, 0)
set_line_width(cr,radius*2 + 2.0)
for i=1:n
move_to(cr,px[i],py[i])
rel_line_to(cr,0,0)
stroke(cr)
end
set_source_rgb(cr, 0, 0, 1.0)
set_line_width(cr,radius*2)
for i=1:n
move_to(cr,px[i],py[i])
rel_line_to(cr,0,0)
stroke(cr)
end
end
function rdots4(cr::CairoContext,
rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
cc = radius + 3.0
rectangle(cr,0,0,2*cc,2*cc)
clip(cr)
push_group(cr)
arc(cr,radius,radius,radius,0,2*pi)
set_source_rgb(cr,0,0,1.0)
fill_preserve(cr)
set_source_rgb(cr,0,0,0)
set_line_width(cr,1.0)
stroke(cr)
p = pop_group(cr)
reset_clip(cr)
for i=1:n
save(cr)
translate(cr,px[i]-cc,py[i]-cc)
set_source(cr,p)
paint(cr)
restore(cr)
end
end
function rdots5(cr::CairoContext,
rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
cc = radius + 3.0
s1 = Cairo.CairoARGBSurface(cc*2,cc*2)
c1 = Cairo.CairoContext(s1)
rectangle(c1,0,0,2*cc,2*cc)
set_source_rgba(c1,0,0,0,0)
paint(c1)
new_path(c1)
arc(c1,radius+1,radius+1,radius,0,2*pi)
set_source_rgb(c1,0,0,1.0)
fill_preserve(c1)
set_source_rgb(c1,0,0,0)
set_line_width(c1,1.0)
stroke(c1)
p = Cairo.CairoPattern(s1)
for i=1:n
save(cr)
translate(cr,px[i]-cc,py[i]-cc)
set_source(cr,p)
paint(cr)
restore(cr)
end
end
# alpha transparency using paint_with_alpha
function rdots6(cr::CairoContext,
rect_width::Real, rect_height::Real, radius::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
cc = radius + 3.0
s1 = Cairo.CairoARGBSurface(cc*2,cc*2)
c1 = Cairo.CairoContext(s1)
rectangle(c1,0,0,2*cc,2*cc)
set_source_rgba(c1,0,0,0,0)
paint_with_alpha(c1, 0.5)
new_path(c1)
arc(c1,radius+1,radius+1,radius,0,2*pi)
set_source_rgb(c1,0,0,1.0)
fill_preserve(c1)
set_source_rgb(c1,0,0,0)
set_line_width(c1,1.0)
stroke(c1)
p = Cairo.CairoPattern(s1)
for i=1:n
save(cr)
translate(cr,px[i]-cc,py[i]-cc)
set_source(cr,p)
paint_with_alpha(cr, 1 - i/n)
restore(cr)
end
end
# lines0, random x,y lines
function lines0(cr::CairoContext, rect_width::Real, rect_height::Real, width::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
new_path(cr)
set_source_rgb(cr, 0, 0, 1.0)
set_line_width(cr,width)
new_path(cr)
move_to(cr,px[1],py[1])
for i=2:n
line_to(cr,px[i],py[i])
end
stroke(cr)
end
# lines1, x sorted, line a plot
function lines1(cr::CairoContext, rect_width::Real, rect_height::Real, width::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
px = sort(px)
set_source_rgb(cr, 0, 0, 1.0)
set_line_width(cr,width)
new_path(cr)
move_to(cr,px[1],py[1])
for i=2:n
line_to(cr,px[i],py[i])
end
stroke(cr)
end
# lines2, x sorted, independent lines per coord
function lines2(cr::CairoContext, rect_width::Real, rect_height::Real, width::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
px = sort(px)
set_source_rgb(cr, 0, 0, 1.0)
set_line_width(cr,width)
new_path(cr)
for i=1:n-1
move_to(cr,px[i],py[i])
line_to(cr,px[i+1],py[i+1])
stroke(cr)
end
end
# lines3, x sorted, in clusters of 100
function lines3(cr::CairoContext, rect_width::Real, rect_height::Real, width::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
px = sort(px)
set_source_rgb(cr, 0, 0, 1.0)
set_line_width(cr,width)
new_path(cr)
for c = 1:100:n
move_to(cr,px[c],py[c])
for i=c:min(c+100,n)
line_to(cr,px[i],py[i])
end
stroke(cr)
end
end
# lines4, x sorted, in clusters of 1000
function lines4(cr::CairoContext, rect_width::Real, rect_height::Real, width::Real, n::Int)
clear_bg(cr,rect_width,rect_height)
px,py = randpos(n,rect_width,rect_height)
px = sort(px)
set_source_rgb(cr, 0, 0, 1.0)
set_line_width(cr,width)
new_path(cr)
for c = 1:1000:n
move_to(cr,px[c],py[c])
for i=c:min(c+1000,n)
line_to(cr,px[i],py[i])
end
stroke(cr)
end
end
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 2833 | # some collection of some painting plus support functions
"""
function ngray(base::Int,digits::Int,value::Int)
Convert a value to a graycode with the given base and digits
"""
function ngray(base::Int,digits::Int,value::Int)
baseN = zeros(Int,digits)
gray = zeros(Int,1,digits)
for i=1:digits
baseN[i] = value % base
value = div(value,base)
end
shift = 0
for i=digits:-1:1
gray[i] = (baseN[i] + shift) % base
shift = shift + base - gray[i]
end
gray
end
"""
function hilbert_curve(c,x,y,lg,i1,i2)
recursive hilbert curve (2D), appends pairs of x,y to c, lg = dimension/length
"""
function hilbert_curve(c,x,y,lg,i1,i2)
if lg == 1
append!(c,[x,y])
else
lg = lg / 2;
hilbert_curve(c,x+i1*lg,y+i1*lg,lg,i1,1-i2);
hilbert_curve(c,x+i2*lg,y+(1-i2)*lg,lg,i1,i2);
hilbert_curve(c,x+(1-i1)*lg,y+(1-i1)*lg,lg,i1,i2);
hilbert_curve(c,x+(1-i2)*lg,y+i2*lg,lg,1-i1,i2);
end
end
function hilbert_colored(surf)
zscale = 8;
n1 = 8;
cr = CairoContext(surf)
c = Float64[]
hilbert_curve(c,0,0,64,0,0)
move_to(cr,0,0)
translate(cr,zscale/2,zscale/2)
scale(cr,zscale,zscale)
set_line_width(cr,zscale/2)
set_line_cap(cr,Cairo.CAIRO_LINE_CAP_SQUARE)
for k in zip(collect(1:2:(length(c)-2)),1:(length(1:2:(length(c)-2))))
move_to(cr,c[k[1]],c[k[1]+1])
line_to(cr,c[k[1]+2],c[k[1]+3])
c1 = ngray(n1,3,k[2])
set_source_rgb(cr,c1[1]/float(n1-1),c1[2]/float(n1-1),c1[3]/float(n1-1))
stroke(cr)
end
end
""" function hdraw(s,dim,zscale,linewidth)
draws a hilbert curve with dimension dim (power of 2) and scales the drawing with
zscale.
"""
function hdraw(s,dim,zscale,linewidth)
cr = CairoContext(s)
set_source_rgba(cr,0.0,0.0,1.0,0.5)
set_line_width(cr,linewidth)
set_line_cap(cr,Cairo.CAIRO_LINE_CAP_SQUARE)
translate(cr,zscale/2,zscale/2)
save(cr)
c = Float64[]
hilbert_curve(c,0,0,dim,0,0)
scale(cr,zscale,zscale)
move_to(cr,0,0)
for k=1:div(length(c),2)
line_to(cr,c[(k*2)-1],c[(k*2)])
end
stroke(cr)
restore(cr)
end
"""
function simple_hist(data)
simple histogram by population count in a Dict
"""
function simple_hist(data)
# poor man's hist -> pop count in Dict
pc = Dict()
for d in data
if d in keys(pc)
pc[d] += 1
else
pc[d] = 1
end
end
pc
end
"""
function matrix_read(surface)
paint the input surface into a matrix image of the same size to access
the pixels.
"""
function matrix_read(surface)
w = Int(surface.width)
h = Int(surface.height)
z = zeros(UInt32,w,h)
surf = CairoImageSurface(z, Cairo.FORMAT_ARGB32)
cr = CairoContext(surf)
set_source_surface(cr,surface,0,0)
paint(cr)
surf.data
end
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 1991 | using Cairo
include("shape_functions.jl")
function test_all(;tmax = 2.0, save_flag = false)
print("cairo version: ",Cairo.libcairo_version,"\n");
size_surface = [512];#,512,1024]; #three sizes of a surface
paint_width = [0.5,1.0,3.0,5.0];
shapes = [ddots1, ddots2, ddots3, ddots4, ddots5,
rdots1, rdots2, rdots3, rdots4, rdots5, rdots6,
lines0, lines1, lines2, lines3, lines4];
n_elements = [100,300,1000,3000,10000,30000,100000];
n_tests = length(size_surface) * length(paint_width) * length(shapes);
test_data = zeros(n_tests+1,3 + length(n_elements));
test_data[1,3+(1:length(n_elements))] = n_elements;
i = 1;
if save_flag && !isdir("test_results")
mkdir("test_results")
end
for s_size in size_surface
s = Cairo.CairoARGBSurface(s_size,s_size);
c = Cairo.CairoContext(s);
print("Surface Size: ",s_size,"\n")
for w in paint_width
print("Paint Width: ",w,"\n")
for m_index in 1:length(shapes)
test_data[i,1] = s_size;
test_data[i,2] = w;
test_data[i,3] = m_index;
m = shapes[m_index];
for n_index in 1:length(n_elements)
n = n_elements[n_index];
t = @elapsed(m(c,s_size,s_size,w,n));
print(m," ",@sprintf("%6d",n)," elapsed time: ",@sprintf("%f seconds",t),"\n");
test_data[i+1,3+n_index] = t;
if save_flag
write_to_png(s,@sprintf("test_results/test_speed_%2.1f_%02d_%02d.png",w,m_index,n_index));
end
if t > tmax && n_index < length(n_elements)
println("Remaining tests in this sequence skipped")
break
end
end
print("\n")
i += 1;
end
end
end
end
test_all()
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 762 | # So that this test can be run independently
using Cairo
using Base64
include("shape_functions.jl")
@testset "Test that writing images to a Julia IO object works" begin
c = CairoRGBSurface(256,256)
cr = CairoContext(c)
ddots4(cr,256,246,1.0,3000)
buf = IOBuffer()
pipe = Base64EncodePipe(buf)
write_to_png(c,pipe)
close(pipe)
# Catch short writes
str = String(take!(buf))
str_data = codeunits(str)
@test length(str_data) > 200
end
@testset "Test that writing images to a temp file works" begin
c = CairoRGBSurface(256,256)
cr = CairoContext(c)
ddots4(cr,256,246,1.0,3000)
fn = tempname()*".png"
@test write_to_png(c,fn) == Cairo.STATUS_SUCCESS
@test isfile(fn)
rm(fn) # clean up
end
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | code | 154 | using Cairo: tex2pango
using Test
fsize = 1.618034
@test tex2pango("ƒ_{Nyquist} [\\mu K]",fsize) == "ƒ<sub><span font=\"1.0\">Nyquist</span></sub> [μK]"
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | docs | 676 | [](https://github.com/JuliaGraphics/Cairo.jl/actions?query=workflow%3ACI)
[](https://codecov.io/gh/JuliaGraphics/Cairo.jl)
## Bindings to the Cairo graphics library ##
Adaptation to [Cairo](https://www.cairographics.org/), a 2D graphics library with support for multiple output devices.
Some of the functions implemented by this wrapper may be documented in [Graphics.jl](https://juliagraphics.github.io/Graphics.jl/stable/).
There is an extensive set of [examples](samples/Samples.md).
| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"MIT"
] | 1.1.0 | 7b6ad8c35f4bc3bca8eb78127c8b99719506a5fb | docs | 7806 | ## Sample programs #
This is roughly a copy of the sample code listed at [cairographics.org/samples](http://www.cairographics.org/samples/).
These examples are C code and assume that you've already set up a Cairo surface and Cairo Context.
This (samples) directory contains ports of these examples to julia, additionally creating the Surface and Context, adding a time-stamp to the image, and saving the result to a .png file.
### arc #
Example of using the arc path operator [sample_arc.jl](sample_arc.jl).
Note: The path creation starts without current point, otherwise there would be a linesegment first, before starting of the arc.

### arc_negative #
Example of using the arc_negative path operator [sample_arc_negative.jl](sample_arc_negative.jl).

### clip #
A clip path, a circle is defined, then the drawing is done [sample_clip.jl](sample_clip.jl).

### clip image #
Like the previous, but now inserting a picture by reading a .png to an Image Surface. Note: the function is called read_from_png and creates an Image Surface; while in pure C cairo this would be a call of cairo_image_surface_create_from_png [sample_clip_image.jl](sample_clip_image.jl).

### curve rectangle #
Example of more complex path construction, here a rectangle constructed be four bezier segments. Note: Different as in the original example, this here now puts the path construction and stroke and fill operations into a function with coordinates and corner radius as arguments [sample_curve_rectangle.jl](sample_curve_rectangle.jl).

### curve to #
Example of using the curve to path operator, which adds a cubic Bézier spline to the current path [sample_curve_to.jl](sample_curve_to.jl).

### dash #
Example of using a dash line pattern for stroking a path. Note: the julia set_dash uses the length of the dash array to set the ndash internally [sample_dash.jl](sample_dash.jl).

### fill and stroke 2 #
Example of creating a path of non connected areas and fill - while preserving the path - and stroke [sample_fill_and_stroke2.jl](sample_fill_and_stroke2.jl).

### fill style #
Exmaple of using the different fill rules. The same path is filled and stroked [sample_fill_style.jl](sample_fill_style.jl). Note: the julia function is called set_fill_type while the pure C cairo is called with set_fill_rule.

### gradient #
Example of gradients - both linear and radiant - as definition and used for filling [sample_gradient.jl](sample_gradient.jl).

### image #
Example of painting with a Image Surface as source [sample_image.jl](sample_image.jl).

### image pattern #
Example of painting with a Image Surface as pattern [sample_imagepattern.jl](sample_imagepattern.jl).

### multi segment caps #
Example of stroking a path with non connected segments [sample_multi_segment_caps.jl](sample_multi_segment_caps.jl).

### rounded rectangle #
Example of more path operators, custom shape could be wrapped in a function [sample_rounded_rectangle.jl](sample_rounded_rectangle.jl).

### set line caps
Examples of the line cap settings [sample_set_line_cap.jl](sample_set_line_cap.jl).

### set line join
Examples of the line join settings [sample_set_line_join.jl](sample_set_line_join.jl).

### text
Example of setting text, one with text_show, second with text_path extending the current path and fill and stroke the outline [sample_text.jl](sample_text.jl).

### text align center
Example of getting the text extents, then centering the text around 128.0,128.0 [sample_text_align_center.jl](sample_text_align_center.jl).

### text extents
Example of getting the text extents, plotting the dimension [sample_text_extents.jl](sample_text_extents.jl).

### copy path
Example of getting the path to a single character via text_path, copy_path and convert to an Array of CairoPathEntry [sample_copy_path.jl](sample_copy_path.jl).

### image (from stream)
Example of painting with a Image Surface as source that was created by reading from a stream. The example reads the png data from an inline string [sample_imagestream.jl](sample_imagestream.jl).

## More Samples for Testing
The following examples have been created to have more coverage in testing (all samples_X are executed).
### alpha paint
Example to use set_source with different input (for multiple dispatch). For better viewing the background is not plain gray anymore, but has structure
[sample_alpha_paint.jl](sample_alpha_paint.jl).

### image copy
Example to use copy(Image). You need to take care about coordinate transformation, as the copy is inplace [sample_image_copy.jl](sample_image_copy.jl).

### operators
Example to use the defined operators for set_operator with two filled rectangles [sample_operators.jl](sample_operators.jl).

### set dash
Example to use the set line type function (input to set_dash) [sample_set_dash.jl](sample_set_dash.jl).

### copy path flat
[sample_copy_path_flat.jl](sample_copy_path_flat.jl).

### pango text
Example of a few (but not all) pango text formating options [sample_pango_text.jl](sample_pango_text.jl).

### mesh pattern
Example of creating and using a mesh pattern [sample_meshpattern.jl](sample_meshpattern.jl).
Mesh patterns are tensor-product patch meshes (type 7 shadings in PDF), read more in [http://www.cairographics.org/manual/cairo-cairo-pattern-t.html#cairo-pattern-create-mesh] or [http://www.w3.org/TR/SVG2/pservers.html#MeshGradients].

### Recording and Scripting Surfaces
Example of using Recording surface, simple copy, then scaled and offset.


Example of writing to script, put script text into frame. [sample_record0.jl](sample_record0.jl), [sample_record1.jl](sample_record1.jl)

### current point
Example of using current point [sample_current_point.jl](sample_current_point.jl)

| Cairo | https://github.com/JuliaGraphics/Cairo.jl.git |
|
[
"Apache-2.0"
] | 0.2.0 | b7f634d8f61ac906ad75954ba95ab174cb939d5a | code | 434 | module FCSFiles
using FileIO
using AxisArrays
const axes = Base.axes
include("type.jl")
include("utils.jl")
include("parse.jl")
export FlowSample
function load(f::File{format"FCS"})
open(f) do io
offsets = parse_header(io)
text_mappings = parse_text(io, offsets[1], offsets[2])
verify_text(text_mappings)
return parse_data(io, offsets[3], offsets[4], text_mappings)
end
end
end # module
| FCSFiles | https://github.com/tlnagy/FCSFiles.jl.git |
|
[
"Apache-2.0"
] | 0.2.0 | b7f634d8f61ac906ad75954ba95ab174cb939d5a | code | 3667 | function parse_header(io)
seekstart(io)
rawversion = Array{UInt8}(undef, 6)
read!(io, rawversion)
version = String(rawversion)
if "$version" != "FCS3.0" && version != "FCS3.1"
@warn "$version files are not guaranteed to work"
end
seek(io, 10)
# start, end positions of TEXT, DATA, and ANALYSIS sections
offsets = Array{Int64}(undef, 6)
for i in 1:6
# offsets are encoded as ASCII strings
raw_str = Array{UInt8}(undef, 8)
read!(io, raw_str)
offsets_str = String(raw_str)
# the last two numbers are for the analysis segment
# the analysis segment is facultative, although the bytes should
# always be there
# (FCS 3.1 ref at https://isac-net.org/page/Data-Standards)
# some cytometers (BD Accuri) do not put the last two bytes
# putting "0" bytes in their files is what other cytometers do
# see github discussion:
# https://github.com/tlnagy/FCSFiles.jl/pull/13#discussion_r985251676
if isempty(lstrip(offsets_str)) && i>4
offsets_str="0"
end
offsets[i] = parse(Int, strip(join(offsets_str)))
end
# DATA offsets are larger than 99,999,999bytes
if offsets[3] == 0 && offsets[4] == 0
text_mappings = parse_text(io, offsets[1], offsets[2])
offsets[3] = parse(Int64, text_mappings["\$BEGINDATA"])
offsets[4] = parse(Int64, text_mappings["\$ENDDATA"])
end
return offsets
end
function parse_text(io, start_text::Int, end_text::Int)
seek(io, start_text)
# TODO: Check for supplemental TEXT file
raw_btext = Array{UInt8}(undef, end_text - start_text + 1)
read!(io, raw_btext)
raw_text = String(raw_btext)
# initialize iterator, save&skip the delimiter
delimiter, state = iterate(raw_text)
# container for the results
text_mappings = Dict{String, String}()
while iterate(raw_text, state) !== nothing
# grab key and ignore escaped delimiters
key, state = grab_word(raw_text, state, delimiter)
# grab value and ignore escaped delimiters
value, state = grab_word(raw_text, state, delimiter)
# FCS keywords are case insensitive so force everything to uppercase
text_mappings[uppercase(key)] = value
end
text_mappings
end
function parse_data(io,
start_data::Int,
end_data::Int,
text_mappings::Dict{String, String})
seek(io, start_data)
# data type in FCS3.1 can be I (integer), F (float32), A (Ascii)
if text_mappings["\$DATATYPE"] == "I"
dtype = Int32
elseif text_mappings["\$DATATYPE"] == "F"
dtype = Float32
else
error("Only float and integer data types are implemented for now, the required .fcs file is using another number encoding.")
end
flat_data = Array{dtype}(undef, (end_data - start_data + 1) ÷ 4)
read!(io, flat_data)
endian_func = get_endian_func(text_mappings)
map!(endian_func, flat_data, flat_data)
n_params = parse(Int, text_mappings["\$PAR"])
# data should be in multiples of `n_params` for list mode
(mod(length(flat_data), n_params) != 0) && error("FCS file is corrupt. DATA and TEXT sections don't match.")
datamatrix = Matrix{dtype}(undef, n_params, length(flat_data) ÷ n_params)
rows = Vector{String}(undef, n_params)
for i in 1:n_params
rows[i] = text_mappings["\$P$(i)N"]
datamatrix[i, :] = flat_data[i:n_params:end]
end
data = AxisArray(datamatrix, Axis{:param}(rows), Axis{:event}(1:size(datamatrix, 2)))
FlowSample(data, text_mappings)
end
| FCSFiles | https://github.com/tlnagy/FCSFiles.jl.git |
|
[
"Apache-2.0"
] | 0.2.0 | b7f634d8f61ac906ad75954ba95ab174cb939d5a | code | 3227 | struct FlowSample{T<:Number, I<:AbstractVector{Int}}
data::AxisArray{T, 2, Matrix{T}, Tuple{Axis{:param, Vector{String}}, Axis{:event, I}}}
params::Dict{String, String}
end
const opt_params = [
("Machine", "\$CYT"),
("Begin Time", "\$BTIM"),
("End Time", "\$ETIM"),
("Date", "\$DATE"),
("File", "\$FIL"),
("Volume run", "\$VOL")
]
function Base.show(io::IO, f::FlowSample)
spacing = " "^4
print(io, typeof(f))
for pair in opt_params
if haskey(f.params, pair[2])
print(io, "\n", spacing, "$(pair[1]): $(f.params[pair[2]])")
end
end
print(io, "\n", spacing, "Axes:")
n_params = parse(Int, f.params["\$PAR"])
for i in 1:n_params
print(io, "\n", spacing, spacing, "$(f.params["\$P$(i)N"])")
if haskey(f.params, "\$P$(i)S")
print(io, " ($(f.params["\$P$(i)N"]))")
end
end
end
"""
Looks for `s` in the `params` dict.
`s` is searched for both as a FCS standard keyword then as a user-defined keyword, with precendence given to the standard keywords. E.g. `param_lookup(flowrun, "par")` will look for both `"\$PAR"` and `"PAR"` but return `"\$PAR"` if it exists, otherwise `"PAR"`.
In accordance with the FCS3.0 standard, the search is cas insensitive.
If no match is found, `nothing` is returned.
"""
function param_lookup(f::FlowSample, s::AbstractString)
s = uppercase(s)
params = getfield(f, :params)
result = get(params, startswith(s, "\$") ? s : "\$" * s, nothing)
return result === nothing ? get(params, s, nothing) : result
end
function Base.getproperty(f::FlowSample, s::Symbol)
if s == :params
Base.depwarn("`flowrun.params` is deprecated and will be removed in a future release. Parameters can be accessed like any other member variable. E.g. `flowrun.par` or `flowrun.PAR`.", "flowrun.params")
elseif s == :data
Base.depwarn("`flowrun.data` is deprecated and will be removed in a future release. The data can be indexed, e.g. `flowrun[\"SSC-A\"]` or can be obtained as a matrix with `Array(flowrun)`.", "flowrun.data")
end
value = param_lookup(f, String(s))
if value === nothing
getfield(f, s)
else
value
end
end
function Base.propertynames(f::FlowSample, private::Bool=false)
makesym(x) = Symbol.(lowercase(first(match(r"^\$?(.+)", x).captures)))
names = makesym.(keys(getfield(f, :params)))
if private
append!(names, fieldnames(FlowSample))
end
names
end
Base.size(f::FlowSample) = size(getfield(f, :data))
Base.size(f::FlowSample, dim::Int) = size(f)[dim]
Base.length(f::FlowSample) = size(f, 1)
Base.keys(f::FlowSample) = getfield(f, :data).axes[1]
Base.haskey(f::FlowSample, x) = x in keys(f)
Base.values(f::FlowSample) = [getfield(f, :data)[key] for key in keys(f)]
Base.axes(f::FlowSample, args...) = AxisArrays.axes(getfield(f, :data), args...)
Base.getindex(f::FlowSample, args...) = getindex(getfield(f, :data), args...)
Base.iterate(iter::FlowSample) = iterate(getfield(iter, :data))
Base.iterate(iter::FlowSample, state) = iterate(getfield(iter, :data), state)
Base.Array(f::FlowSample) = Array(getfield(f, :data))
AxisArrays.axisnames(f::FlowSample) = axisnames(getfield(f, :data))
| FCSFiles | https://github.com/tlnagy/FCSFiles.jl.git |
|
[
"Apache-2.0"
] | 0.2.0 | b7f634d8f61ac906ad75954ba95ab174cb939d5a | code | 3433 | # These are keywords present in the TEXT section that are guaranteed by the spec
const required_keywords = [
"\$BEGINANALYSIS", # Byte-offset to the beginning of the ANALYSIS segment.
"\$BEGINDATA", # Byte-offset to the beginning of the DATA segment.
"\$BEGINSTEXT", # Byte-offset to the beginning of a supplemental TEXT segment.
"\$BYTEORD", # Byte order for data acquisition computer.
"\$DATATYPE", # Type of data in DATA segment (ASCII, integer, floating point).
"\$ENDANALYSIS", # Byte-offset to the last byte of the ANALYSIS segment.
"\$ENDDATA", # Byte-offset to the last byte of the DATA segment.
"\$ENDSTEXT", # Byte-offset to the last byte of a supplemental TEXT segment.
"\$MODE", # Data mode (list mode - preferred, histogram - deprecated).
"\$NEXTDATA", # Byte offset to next data set in the file.
"\$PAR", # Number of parameters in an event.
"\$PnB", # Number of bits reserved for parameter number n.
"\$PnE", # Amplification type for parameter n.
"\$PnN", # Short name for parameter n.
"\$PnR", # Range for parameter number n.
"\$TOT" # Total number of events in the data set.
]
"""
grab_word(iter, state, delimiter) -> word, state
Grabs the next word from the iterator `iter`. Takes care to handle escaped
delimiters specified by `delimiter`. Returns a string containing the word
and the state of the iterator.
"""
function grab_word(iter, state, delimiter::Char)
word = Char[]
prev = ' '
iter_result = iterate(iter, state)
while iter_result !== nothing
i, state = iter_result
# only add character if the current and previous are both
# delimiters (i.e. escaped) or neither are
if !xor((prev == delimiter), (i == delimiter))
push!(word, i)
prev = i
else
break
end
iter_result = iterate(iter, state)
end
join(word), state
end
"""
verify_text(text_mappings) -> Void
Checks that all required keywords are present in the text_mapping dictionary
returned by `parse_text`
"""
function verify_text(text_mappings::Dict{String, String})
# get all parameterized keywords $P1N, $P2N, etc
is_param = [occursin("n", keyword) for keyword in required_keywords]
# verify that all non-parameterized keywords are present in the mapping
for non_param in required_keywords[.~is_param]
if !haskey(text_mappings, non_param)
error("FCS file is corrupted. It is missing required keyword $non_param in its TEXT section")
end
end
# TODO: Add support for modes other than list
(text_mappings["\$MODE"] != "L") && error("Non list mode FCS files are not supported yet")
n_params = parse(Int, text_mappings["\$PAR"])
for params in required_keywords[is_param]
for i in 1:n_params
if !haskey(text_mappings, replace(params, "n"=>i))
error("FCS file is corrupted. It is missing required keyword $non_param in its TEXT section")
end
end
end
end
function get_endian_func(text_mappings::Dict{String, String})
byte_order = text_mappings["\$BYTEORD"]
if byte_order == "1,2,3,4" # least significant byte first
return ltoh
elseif byte_order == "4,3,2,1" # most significant byte first
return ntoh
else
error("FCS file is malformed. '$(byte_order)' is not a valid byte order.")
end
end
| FCSFiles | https://github.com/tlnagy/FCSFiles.jl.git |
|
[
"Apache-2.0"
] | 0.2.0 | b7f634d8f61ac906ad75954ba95ab174cb939d5a | code | 8259 | using FCSFiles
using FileIO
using Test
project_root = dirname(dirname(@__FILE__))
testdata_dir = joinpath(project_root, "test", "fcsexamples")
if !isdir(testdata_dir)
run(`git -C $(joinpath(project_root, "test")) clone https://github.com/tlnagy/fcsexamples.git --branch main --depth 1`)
else
run(`git -C $testdata_dir fetch`)
# for reproducibility we should use hard reset
run(`git -C $testdata_dir reset --hard origin/main`)
run(`git -C $testdata_dir pull`)
end
@testset "FCSFiles test suite" begin
# test the loading of a large FCS file
@testset "Loading of large FCS file" begin
# load the large file
flowrun = load(joinpath(testdata_dir, "Day 3.fcs"))
@test length(flowrun) == 50
@test length(getfield(flowrun, :params)) == 268
end
@testset "FlowSample size and length" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
@test size(flowrun) == (14, 100000)
@test length(flowrun) == 14
end
@testset "FlowSample keys and haskey" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
expected = [
"G710-A", "FSC-H", "V545-A", "FSC-A", "G560-A", "Time",
"SSC-A", "B515-A", "G610-A", "Event #", "R780-A",
"G780-A", "V450-A", "G660-A",
]
flowrun = load(fn)
for channel in expected
@test haskey(flowrun, channel)
end
@test all(x in keys(flowrun) for x in expected)
end
# AxisArray already has tests, here we are just checking that
# relevant methods get forwarded to their AxisArray implementation
@testset "Channel access using String" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
for key in keys(flowrun)
@test flowrun[key] == getfield(flowrun, :data)[key]
end
end
@testset "Multiple channel access using String" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
channels = keys(flowrun)
for (keyA, keyB) in zip(channels[1:end-1], channels[2:end])
@test flowrun[[keyA, keyB]] == getfield(flowrun, :data)[[keyA, keyB]]
end
end
@testset "Integer sample indexing as second dimension" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
idx = rand(1:size(flowrun, 2))
@test getfield(flowrun, :data)[:, idx] == flowrun[:, idx]
@test getfield(flowrun, :data)[:, begin] == flowrun[:, begin]
@test getfield(flowrun, :data)[:, end] == flowrun[:, end]
rng = range(sort(rand(1:size(flowrun, 2), 2))..., step=1)
@test getfield(flowrun, :data)[:, rng] == flowrun[:, rng]
end
@testset "Mixed indexing with String and Integer" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
idx = rand(1:size(flowrun, 2))
@test getfield(flowrun, :data)["SSC-A", idx] == flowrun["SSC-A", idx]
@test getfield(flowrun, :data)[["SSC-A", "FSC-A"], idx] == flowrun[["SSC-A", "FSC-A"], idx]
rng = range(sort(rand(1:size(flowrun, 2), 2))..., step=1)
@test getfield(flowrun, :data)["SSC-A", rng] == flowrun["SSC-A", rng]
@test getfield(flowrun, :data)[["SSC-A", "FSC-A"], rng] == flowrun[["SSC-A", "FSC-A"], rng]
end
@testset "Logical indexing in second dimension" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
idxs = rand(Bool, size(flowrun, 2))
@test getfield(flowrun, :data)["SSC-A", idxs] == flowrun["SSC-A", idxs]
end
@testset "Convert to Matrix" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
@test Array(getfield(flowrun, :data)) == Array(flowrun)
end
@testset "Regression for reading FCS files" begin
# should catch if changes to the parsing of the file introduce errors
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
checkpoints = [
("SSC-A", 33),
("G610-A", 703),
("Event #", 382),
("FSC-A", 15),
("Time", 1),
("V450-A", 9938)
]
expected = [585.006f0, 993.2587f0, 3810.0f0, 131008.0f0, 0.0f0, 472.9652f0]
for (checkpoint, value) in zip(checkpoints, expected)
@test flowrun[checkpoint[1]][checkpoint[2]] == value
end
end
@testset "Iterating FlowSample" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
i = 1
pass = true
for x in flowrun
pass = pass && x == flowrun[i]
i = i + 1
end
@test pass
end
@testset "Loading float-encoded file" begin
flowrun = load(joinpath(testdata_dir, "Applied Biosystems - Attune.fcs"))
@test length(flowrun["SSC-A"]) == 22188
@test flowrun["FSC-A"][2] == 244982.11f0
end
@testset "Loading Accuri file" begin
flowrun = load(joinpath(testdata_dir, "Accuri - C6.fcs"))
@test length(flowrun["SSC-A"]) == 63273
@test flowrun["SSC-A"][2] == 370971
end
@testset "params throws deprecation warning" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
msg = "`flowrun.params` is deprecated and will be removed in a future release. Parameters can be accessed like any other member variable. E.g. `flowrun.par` or `flowrun.PAR`."
@test_logs (:warn, msg) flowrun.params
end
@testset "data throws deprecation warning" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
msg = "`flowrun.data` is deprecated and will be removed in a future release. The data can be indexed, e.g. `flowrun[\"SSC-A\"]` or can be obtained as a matrix with `Array(flowrun)`."
@test_logs (:warn, msg) flowrun.data
end
@testset "`param_lookup` for different versions of the param" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
pass = true
for (key, value) in getfield(flowrun, :params)
# exact name
pass = pass && value == FCSFiles.param_lookup(flowrun, key)
# with no $
var = first(match(r"^\$?(.+)", key).captures)
pass = pass && value == FCSFiles.param_lookup(flowrun, var)
# in lowercase
pass = pass && value == FCSFiles.param_lookup(flowrun, lowercase(key))
# in lowercase with no $
pass = pass && value == FCSFiles.param_lookup(flowrun, lowercase(var))
end
@test pass
end
@testset "param access through `Base.getproperty`" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
pass = true
for (key, value) in getfield(flowrun, :params)
# bare usage
pass = pass && value == getproperty(flowrun, Symbol(key))
# with no $
var = first(match(r"^\$?(.+)", key).captures)
pass = pass && value == getproperty(flowrun, Symbol(var))
# in lowercase
pass = pass && value == getproperty(flowrun, Symbol(lowercase(key)))
# in lowercase with no $
pass = pass && value == getproperty(flowrun, Symbol(lowercase(var)))
end
@test pass
@static if VERSION < v"1.8"
@test_throws ErrorException flowrun.notthere
else
@test_throws "no field notthere" flowrun.notthere
end
end
@testset "property names give the names of the parameters" begin
fn = joinpath(testdata_dir, "BD-FACS-Aria-II.fcs")
flowrun = load(fn)
pass = true
for key in keys(getfield(flowrun, :params))
var = Symbol(lowercase(first(match(r"^\$?(.+)", key).captures)))
pass = pass && var in propertynames(flowrun)
end
@test pass
@test :params in propertynames(flowrun, true)
@test :data in propertynames(flowrun, true)
end
end
| FCSFiles | https://github.com/tlnagy/FCSFiles.jl.git |
|
[
"Apache-2.0"
] | 0.2.0 | b7f634d8f61ac906ad75954ba95ab174cb939d5a | docs | 3863 | # FCSFiles
Add FileIO.jl integration for FCS files
| Stable release | Repo status |
|--------------------------------------------------|--------------|
|  | [![][ci-img]][ci-url] [![][codecov-img]][codecov-url] |
## Loading an FCSFile
FCS files can be loaded by using the FileIO interface.
```julia
julia> using FileIO
julia> flowrun = load("example.fcs")
FCS.FlowSample{Float32}
Machine: LSRFortessa
Begin Time: 14:12:03
End Time: 14:12:25
Date: 17-MAR-2017
File: Specimen_001_Tube_002_002.fcs
Axes:
FSC-A
FSC-H
FSC-W
SSC-A
SSC-H
SSC-W
B_530-30-A
Time
```
## Metadata
Once loaded the parameters of the FCS file are available as properties.
```
julia> flowrun.last_modified
"2019-Oct-03 15:35:15"
julia> flowrun.p1n
"FSC-A"
```
## Indexing
There are many ways to index into the FCS file. You can index the FCS file as a matrix (actually an `AxisArray`).
```
julia> flowrun[:, 1]
1-dimensional AxisArray{Float32,1,...} with axes:
:param, ["FSC-A", "FSC-H", "SSC-A", "SSC-H", "B1-A", "B1-H", "B2-A", "B2-H", "HDR-CE", "HDR-SE" … "V2-A", "V2-H", "Y1-A", "Y1-H", "Y2-A", "Y2-H", "Y3-A", "Y3-H", "Y4-A", "Y4-H"]
And data, a 23-element Vector{Float32}:
19.319384
12.838199
44.391308
20.214031
0.01834727
0.72980446
-0.25282443
0.4430968
⋮
0.54869235
-0.027989198
0.48970717
4.498265
5.900927
0.02512901
0.3956769
```
This retrieves the values of all the parameters for the first event in the FCS file.
Similarly you can get the values of a single parameter for all events.
```
julia> flowrun[1, :]
1-dimensional AxisArray{Float32,1,...} with axes:
:event, 1:83562
And data, a 83562-element Vector{Float32}:
19.319384
22.961153
36.157864
30.91769
5.644829
14.188097
34.42944
4.4080987
⋮
23.391977
-4.813841
-1.2413055
11.075016
13.712906
23.54529
5.740017
```
You can also take ranges of events.
```
julia> flowrun[1, end-99:end]
1-dimensional AxisArray{Float32,1,...} with axes:
:event, 83463:83562
And data, a 100-element Vector{Float32}:
4.576562
2.553804
10.608879
-6.4025674
-18.626959
6.1649327
24.049818
21.735662
⋮
23.391977
-4.813841
-1.2413055
11.075016
13.712906
23.54529
5.740017
```
If you know the name of a parameter you can use that name to index.
```
julia> flowrun["FSC-A"]
1-dimensional AxisArray{Float32,1,...} with axes:
:event, 1:83562
And data, a 83562-element Vector{Float32}:
19.319384
22.961153
36.157864
30.91769
5.644829
14.188097
34.42944
4.4080987
⋮
23.391977
-4.813841
-1.2413055
11.075016
13.712906
23.54529
5.740017
```
Or you can get multiple parameters at the same time.
```
julia> flowrun[["FSC-A", "FSC-H"]]
2-dimensional AxisArray{Float32,2,...} with axes:
:param, ["FSC-A", "FSC-H"]
:event, 1:83562
And data, a 2×83562 Matrix{Float32}:
19.3194 22.9612 36.1579 30.9177 … 11.075 13.7129 23.5453 5.74002
12.8382 3.40729 17.4995 14.0875 8.80171 5.29686 13.0893 11.3576
```
In general, any indexing that works with `AxisArray`s should work the same with FCS files.
## Plotting
Here is an example which constructs a 2D histogram visualisation of a FCS file.
```
julia> using Gadfly
julia> p = plot(x=flowrun["FSC-A"], y=flowrun["SSC-A"], Geom.histogram2d,
Guide.xlabel("FSC-A"), Guide.ylabel("SSC-A"), Coord.cartesian(xmin=0, ymin=0))
julia> draw(PNG("example.png", 10cm, 7cm, dpi=300), p)
```

[ci-img]: https://github.com/tlnagy/FCSFiles.jl/workflows/CI/badge.svg
[ci-url]: https://github.com/tlnagy/FCSFiles.jl/actions
[codecov-img]: https://codecov.io/gh/tlnagy/FCSFiles.jl/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/tlnagy/FCSFiles.jl
| FCSFiles | https://github.com/tlnagy/FCSFiles.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | code | 407 | module NumberIntervals
using IntervalArithmetic
# three-value logic
include("indeterminate.jl")
# basic type definitions, conversion rules, etc
include("types.jl")
# import set-like (IEEE conform) behaviors from IntervalArithmetic
include("set_operations.jl")
include("numeric.jl")
include("boolean.jl")
include("basic.jl")
# define strict number-like arithmetic
include("nonstandard.jl")
end # module
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | code | 1350 |
import Base: -, +, *, /, ^, abs, abs2, sqrt, exp, exp2, expm1, exp10, log, log2,
log1p, log10, sin, sinpi, cos, cospi, tan, asin, acos, atan, sinh, cosh,
asinh, acosh, tanh, atanh, inv, floor, ceil, min, max, round, trunc, eps
export -, +, *, /, ^, abs, abs2, sqrt, exp, exp2, expm1, exp10, log, log2,
log1p, log10, sin, sinpi, cos, cospi, tan, asin, acos, atan, sinh, cosh,
asinh, acosh, tanh, atanh, inv, floor, ceil, min, max, round, trunc, eps
for f in (:-, :abs, :abs2, :sqrt, :exp, :exp2, :expm1, :exp10, :log, :log2,
:log1p, :log10, :sin, :sinpi, :cos, :cospi, :tan, :asin, :acos, :atan,
:sinh, :cosh, :asinh, :acosh, :tanh, :atanh, :inv, :floor, :ceil,
:round, :trunc)
@eval $f(a::NumberInterval) = NumberInterval($f(Interval(a)))
end
for f in (:+, :-, :*, :/, :^, :atan, :min, :max)
@eval $f(a::NumberInterval, b::NumberInterval) =
NumberInterval($f(Interval(a), Interval(b)))
end
# specialization necessary to avoid ambiguity
for t in (:Integer, :AbstractFloat, :Rational)
@eval ^(a::NumberInterval, n::$t) = NumberInterval(Interval(a)^n)
end
round(a::NumberInterval, mode) = NumberInterval(round(Interval(a), mode))
eps(::Type{NumberInterval{T}}) where T = eps(T)
function eps(a::NumberInterval)
_a = abs(a)
return NumberInterval(eps(_a.lo), eps(_a.hi))
end
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | code | 603 |
import IntervalArithmetic: (⊆), (≺), contains_zero, isempty, isnan,
precedes, ⊂, isinterior, isdisjoint
export (⊆), (≺), contains_zero, isempty, isnan, precedes, ⊂, isinterior,
isdisjoint
#NOTE missing: interior, disjoint
for f in (:(⊆), :(≺), :precedes, :⊂, :isinterior, :isdisjoint)
@eval $f(a::NumberInterval, b::NumberInterval) = $f(Interval(a), Interval(b))
end
for f in (:contains_zero, :isempty, :isnan)
@eval $f(a::NumberInterval) = $f(Interval(a))
end
# these fit better in IntervalArithmetic so we don't export them here
issingleton(a::NumberInterval) = iszero(radius(a))
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | code | 1025 |
export IndeterminateException
"""
IndeterminateException(msg = "")
Exception raised when the result of a numerical operation on a `NumberInterval`
is indeterminate.
See documentation of `Indeterminate` for information on enabling this behavior.
"""
struct IndeterminateException <: Exception
msg
end
IndeterminateException() = IndeterminateException("")
intercept_exception(::Any) = true
"""
missing_or_exception(msg = nothing)
Returns `Base.missing` by default.
To throw an `IndeterminateException()` instead (*only* for debugging purposes),
extend the `intercept_exception()` function from this module by defining:
```julia
NumberIntervals.intercept_exception(::IndeterminateException) = false
```
Note that this changes behavior *globally*, across all packages processing
`NumberInterval`s and therefore should never be used in production code.
"""
function missing_or_exception(msg = nothing)
exc = IndeterminateException(msg)
intercept_exception(exc) && return missing
throw(exc)
end
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | code | 1971 |
import Base: <, iszero, ==, <=, >=, sign, signbit, isinteger, isfinite
export <, iszero, ==, <=, >=, sign, signbit, isinteger, isfinite
function isinteger(a::NumberInterval)
if floor(a) ≺ a ≺ ceil(a)
return false
elseif issingleton(a)
#NOTE given the previous result, singletons must contain single integers
return true
end
return missing_or_exception(a)
end
function isfinite(a::NumberInterval)
# per IEEE standard, intervals cannot contain infinities
if !isempty(a) && !isnan(a)
return true
end
return missing_or_exception(a)
end
function <=(a::NumberInterval, b::NumberInterval)
if precedes(a, b)
return true
elseif precedes(b, a)
return false
end
return missing_or_exception((a, b))
end
function <(a::NumberInterval, b::NumberInterval)
if strictprecedes(a, b)
return true
elseif strictprecedes(b, a)
return false
elseif issingleton(a) && issingleton(b) && a ⊆ b
return false
end
return missing_or_exception((a, b))
end
>=(a::NumberInterval, b::NumberInterval) = b <= a
function iszero(a::NumberInterval)
if !contains_zero(a)
return false
end
if a ⊆ zero(typeof(a))
return true
end
return missing_or_exception(a)
end
function ==(a::NumberInterval, b::NumberInterval)
if isnan(a) || isnan(b)
return false
elseif isdisjoint(a, b)
return false
elseif issingleton(a) && issingleton(b) && a ⊆ b
return true
end
return missing_or_exception((a, b))
end
function sign(a::NumberInterval)
z = zero(typeof(a))
if a ≺ z
return -1
elseif z ≺ a
return +1
elseif a ⊆ z
return 0
end
return missing_or_exception(a)
end
function signbit(a::NumberInterval)
z = zero(typeof(a))
if a ≺ z
return true
elseif precedes(z, a)
return false
end
return missing_or_exception(a)
end
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | code | 557 |
import IntervalArithmetic: radius, mid, mag, mig, sup, inf, diam, bisect, dist
export radius, mid, mag, mig, sup, inf, diam, bisect, dist
for f in (:radius, :mid, :mag, :mig, :sup, :inf, :diam)
@eval $f(a::NumberInterval) = $f(Interval(a))
end
mid(a::NumberInterval, α) = mid(Interval(a), α)
function bisect(a::NumberInterval, α = IntervalArithmetic.where_bisect)
c, d = bisect(Interval(a), α)
return NumberInterval(c), NumberInterval(d)
end
function dist(a::NumberInterval, b::NumberInterval)
return dist(Interval(a), Interval(b))
end
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | code | 529 |
import IntervalArithmetic: ∩, ∪, entireinterval, ∈
export ∩, ∪, entireinterval, ∈
for f in (:∩, :∪, :∈)
@eval $f(a::NumberInterval, b::NumberInterval) =
NumberInterval($f(Interval(a), Interval(b)))
@eval $f(a::Interval{T}, b::NumberInterval{T}) where T =
NumberInterval($f(a, Interval(b)))
@eval $f(a::NumberInterval, b::Interval) = $f(b, a)
end
∈(a::Number, b::NumberInterval) = ∈(a, Interval(b))
for f in (:entireinterval, )
@eval $f(a::NumberInterval) = NumberInterval($f(Interval(a)))
end
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | code | 2385 |
import Base: promote_rule, convert, real, show, empty
import IntervalArithmetic: Interval, interval, ±, emptyinterval
export convert, real, show, empty
export NumberInterval, interval, ±
function _is_valid_interval(lo, hi)
if isinf(lo) && lo == hi
return false # intervals cannot represent infinities
elseif hi >= lo
return true
elseif hi == -Inf && lo == Inf
return true # allow empty interval
elseif isnan(hi) && isnan(lo)
return true # allow NaN interval
end
return false
end
"""
NumberInterval(lo, hi)
Interval which behaves like a number under standard arithmetic operations and
comparisons and raises an `IndeterminateException` when the results of these
operations cannot be rigorously determined.
"""
struct NumberInterval{T <: AbstractFloat} <: AbstractFloat
lo::T
hi::T
NumberInterval(lo, hi) = _is_valid_interval(lo, hi) ?
new{typeof(lo)}(lo, hi) : error("invalid interval ($lo , $hi)")
end
# for now only treat Reals; restriction from IntervalArithmetic
NumberInterval(a::T, b::T) where T <: Union{Integer, Rational, Irrational} =
NumberInterval(float(a), float(b))
NumberInterval(a::Interval) = NumberInterval(a.lo, a.hi)
(::Type{NumberInterval{T}})(a::NumberInterval{T}) where T = a
Interval(a::NumberInterval) = Interval(a.lo, a.hi)
interval(a::NumberInterval) = a
NumberInterval(a) = NumberInterval(Interval(a))
NumberInterval(a::NumberInterval) = a
NumberInterval{T}(a) where T = NumberInterval(Interval{T}(a))
NumberInterval{S}(a::T) where {S, T <: Union{Integer, Rational, Irrational}} =
NumberInterval(Interval{S}(a))
real(a::NumberInterval{T}) where {T <: Real} = a
_promote_interval_type(::Type{Interval{T}}) where T = NumberInterval{T}
_promote_interval_type(a::Type) = a
# promote everything like Interval, except promote Interval to NumberInterval
promote_rule(::Type{NumberInterval{T}}, b::Type) where T =
_promote_interval_type(promote_rule(Interval{T}, b))
function show(io::IO, i::NumberInterval)
print(io, "x ∈ ")
show(io, Interval(i))
end
function ±(a::NumberInterval, r)
if r < 0
return ±(a, -r)
end
NumberInterval(a.lo - r, a.hi + r)
end
function ±(a::NumberInterval, b::NumberInterval)
return NumberInterval(±(Interval(a), Interval(b)))
end
empty(a::NumberInterval) = NumberInterval(emptyinterval(Interval(a)))
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | code | 2003 |
using Test
using NumberIntervals
const a = NumberInterval(-1, 0)
const b = NumberInterval(-0.5, 0.5)
const c = NumberInterval(0.5, 2)
const d = NumberInterval(0.25, 0.8)
const z = zero(NumberInterval)
const e = NumberInterval(Inf, -Inf)
const f = NumberInterval(1)
@testset "number comparison" begin
@test a < c
@test c > a
@test (a < b) |> ismissing
@test (c > b) |> ismissing
@test !(c < a)
@test !(a > c)
@test z == z
@test z != c
@test (a == b) |> ismissing
@test (b != c) |> ismissing
@test b <= c
@test !(f < f)
end
@testset "testing for zero" begin
@test !iszero(c)
@test iszero(z)
@test iszero(a) |> ismissing
@test iszero(b) |> ismissing
end
@testset "test sign" begin
@test signbit(c) == false
@test signbit(-a) == false
@test signbit(-c) == true
@test signbit(a) |> ismissing
@test sign(c) == 1
@test sign(z) == 0
@test sign(-c) == -1
@test sign(b) |> ismissing
end
@testset "isinteger" begin
@test isinteger(z)
@test isinteger(NumberInterval(4))
@test !isinteger(NumberInterval(4.5))
@test isinteger(c) |> ismissing
@test !isinteger(d)
end
@testset "isfinite" begin
@test isfinite(a)
@test isfinite(b)
@test isfinite(c)
@test isfinite(z)
@test isfinite(NumberInterval(0., Inf))
@test isfinite(e) |> ismissing
end
@testset "IndeterminateException" begin
@test_throws IndeterminateException throw(IndeterminateException())
end
@testset "constructor" begin
@test NumberInterval(a) === a
@test NumberInterval{Float64}(a) === a
@test NumberInterval{Float32}(4) isa NumberInterval{Float32}
@test real(a) === a
@test_throws ErrorException NumberInterval(2., 1.)
@test isnan(NumberInterval(NaN))
@test_throws ErrorException NumberInterval(Inf)
@test_throws ErrorException NumberInterval(-Inf)
end
@testset "promotion" begin
@test promote_rule(NumberInterval{Float32}, Float64) ==
NumberInterval{Float64}
end
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.2.2 | 63ab01b2a0540e1cca98329a3b60d3757224766c | docs | 3292 | # NumberIntervals.jl
A package for strict intervals-as-numbers.
[](https://travis-ci.org/gwater/NumberIntervals.jl)
[](https://codecov.io/gh/gwater/NumberIntervals.jl)
# Installation
*NumberIntervals.jl* is available from the General registry. To install enter
the `Pkg` REPL (using `]` in Julia REPL) and simply enter:
```julia
add NumberIntervals
```
# Description
This package aims to provide intervals which can be safely used as drop-in replacements for numbers in [Julia](https://julialang.org).
It builds on the [IntervalArithmetic.jl](https://github.com/JuliaIntervals/IntervalArithmetic.jl) implementation of the [IEEE 1788-2015](https://standards.ieee.org/standard/1788-2015.html) standard.
However, our `NumberInterval` type behaves more predictably and cautious in many contexts than the `Interval` type:
```julia
julia> using NumberIntervals, IntervalArithmetic
julia> iszero(Interval(-1, 1))
false
julia> iszero(NumberInterval(-1, 1))
missing
```
In this case, we cannot tell if the interval (-1, 1) represents zero or not; so the `NumberInterval` returns `missing`.
The `Interval` (from `IntervalArithmetic`) is more forgiving which increases the risk of silent failure in algorithms expecting `Number`-like behavior.
In safe cases, `NumberInterval` yields the expected result:
```julia
julia> iszero(NumberInterval(-2, -1))
false
julia> iszero(NumberInterval(-0, +0))
true
```
This behavior is similar to the [default Boost implementation](https://www.boost.org/doc/libs/1_70_0/libs/numeric/interval/doc/comparisons.htm).
Through `try-catch` statements fallback algorithms can be defined when certain methods fail. A good example is `Base.hypot(x, y)`. It calculates `sqrt(x^2 + y^2)` avoiding over/underflows. Unfortunately, it is not always safe to use with intervals.
This definition uses `Base.hypot()` in safe cases and falls back to `sqrt(x^2 + y^2)` in unsafe cases:
```julia
is_missing_exception(::Exception) = false
is_missing_exception(exc::TypeError) = ismissing(exc.got)
function my_hypot(x, y)
try
hypot(x, y)
catch exc
if is_missing_exception(exc)
return sqrt(x^2 + y^2)
end
rethrow(exc)
end
end
```
Check our [example](examples/DifferentialEquationsExample.ipynb) demonstrating how `NumberInterval`s can act as drop-in replacements for numbers without sacrificing numerical validity.
## Unsupported functions
Some functions do not support NumberIntervals, usually because they call external C or FORTRAN libraries.
For these functions, [ApproxFun.jl](https://github.com/JuliaApproximation/ApproxFun.jl) produces a pure Julia approximation which can be used with NumberIntervals.
```julia
julia> using ApproxFun, NumberIntervals, SpecialFunctions
julia> besselj0(NumberInterval(1))
ERROR: StackOverflowError
julia> f = Fun(besselj0, Chebyshev(0..10))
julia> f(NumberInterval(1))
x ∈ [0.765197, 0.765198]
julia> besselj0(1)
0.7651976865579666
```
## Debugging
For debugging purposes, enable exceptions in indeterminate cases, using:
```julia
NumberIntervals.intercept_exception(::IndeterminateException) = false
```
| NumberIntervals | https://github.com/gwater/NumberIntervals.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 1310 | using Documenter
import Pkg
# Get root directory
root_dir = dirname(@__DIR__)
# Install dependencies and import modules...
Pkg.activate(root_dir)
Pkg.instantiate()
using SEAL
# Define module-wide setups such that the respective modules are available in doctests
DocMeta.setdocmeta!(SEAL,
:DocTestSetup,
:(push!(LOAD_PATH, ".."); using SEAL);
recursive=true)
# Make documentation
makedocs(
# Specify modules for which docstrings should be shown
modules = [SEAL],
# Set sitename to SEAL
sitename = "SEAL.jl",
# Set authors
authors = "Michael Schlottke-Lakemper",
# Provide additional formatting options
format = Documenter.HTML(
# Disable pretty URLs during manual testing
prettyurls = get(ENV, "CI", nothing) == "true",
# Explicitly add favicon as asset
# assets = ["assets/favicon.ico"],
# Set canonical URL to GitLab pages URL
# canonical = canonical
),
# Explicitly specify documentation structure
pages = [
"Home" => "index.md",
"Reference" => "reference.md",
"Contributing" => "contributing.md",
"License" => "license.md"
],
)
deploydocs(
repo = "github.com/JuliaCrypto/SEAL.jl.git",
devbranch = "main"
)
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 6752 | include("utilities.jl")
using SEAL
using Printf
"""
example_bfv_basics()
Perform some basic operations such as encryption/decryption, multiplication, addition etc. using the
BFV scheme. This routine is based on the file `native/examples/1_bfv_basics.cpp` of the original
SEAL library and should yield the exact same output.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/1_bfv_basics.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/1_bfv_basics.cpp)
See also: [`example_ckks_basics`](@ref)
"""
function example_bfv_basics()
print_example_banner("Example: BFV Basics")
parms = EncryptionParameters(SchemeType.bfv)
poly_modulus_degree = 4096
set_poly_modulus_degree!(parms, poly_modulus_degree)
set_coeff_modulus!(parms, coeff_modulus_bfv_default(poly_modulus_degree))
set_plain_modulus!(parms, 1024)
context = SEALContext(parms)
print_line(@__LINE__)
println("Set encryption parameters and print")
print_parameters(context)
println("Parameter validation (success): ", parameter_error_message(context))
println()
println("~~~~~~ A naive way to calculate 4(x^2+1)(x+1)^2. ~~~~~~")
keygen = KeyGenerator(context)
secret_key_ = secret_key(keygen)
public_key_ = PublicKey()
create_public_key!(public_key_, keygen)
encryptor = Encryptor(context, public_key_)
evaluator = Evaluator(context)
decryptor = Decryptor(context, secret_key_)
print_line(@__LINE__)
x = 6
x_plain = Plaintext(string(x))
println("Express x = " * string(x) * " as a plaintext polynomial 0x" * to_string(x_plain) * ".")
print_line(@__LINE__)
x_encrypted = Ciphertext()
println("Encrypt x_plain to x_encrypted.")
encrypt!(x_encrypted, x_plain, encryptor)
println(" + size of freshly encrypted x: ", length(x_encrypted))
println(" + noise budget in freshly encrypted x: ",
invariant_noise_budget(x_encrypted, decryptor),
" bits")
x_decrypted = Plaintext()
decrypt!(x_decrypted, x_encrypted, decryptor)
println(" + decryption of x_encrypted: 0x", to_string(x_decrypted), " ...... Correct.")
print_line(@__LINE__)
println("Compute x_sq_plus_one (x^2+1).")
x_sq_plus_one = Ciphertext()
square!(x_sq_plus_one, x_encrypted, evaluator)
plain_one = Plaintext("1")
add_plain_inplace!(x_sq_plus_one, plain_one, evaluator)
println(" + size of x_sq_plus_one: ", length(x_sq_plus_one))
println(" + noise budget in x_sq_plus_one: ",
invariant_noise_budget(x_sq_plus_one, decryptor),
" bits")
decrypted_result = Plaintext()
decrypt!(decrypted_result, x_sq_plus_one, decryptor)
println(" + decryption of x_sq_plus_one: 0x", to_string(decrypted_result), " ...... Correct.")
print_line(@__LINE__)
println("Compute x_plus_one_sq ((x+1)^2).")
x_plus_one_sq = Ciphertext()
add_plain!(x_plus_one_sq, x_encrypted, plain_one, evaluator)
square_inplace!(x_plus_one_sq, evaluator)
println(" + size of x_plus_one_sq: ", length(x_plus_one_sq))
println(" + noise budget in x_plus_one_sq: ",
invariant_noise_budget(x_plus_one_sq, decryptor),
" bits")
decrypt!(decrypted_result, x_plus_one_sq, decryptor)
println(" + decryption of x_plus_one_sq: 0x", to_string(decrypted_result),
" ...... Correct.")
print_line(@__LINE__)
println("Compute encrypted_result (4(x^2+1)(x+1)^2).")
encrypted_result = Ciphertext()
plain_four = Plaintext("4")
multiply_plain_inplace!(x_sq_plus_one, plain_four, evaluator)
multiply!(encrypted_result, x_sq_plus_one, x_plus_one_sq, evaluator)
println(" + size of encrypted_result: ", length(encrypted_result))
println(" + noise budget in encrypted_result: ",
invariant_noise_budget(encrypted_result, decryptor),
" bits")
println("NOTE: Decryption can be incorrect if noise budget is zero.")
println()
println("~~~~~~ A better way to calculate 4(x^2+1)(x+1)^2. ~~~~~~")
print_line(@__LINE__)
println("Generate relinearization keys.")
relin_keys_ = RelinKeys()
create_relin_keys!(relin_keys_, keygen)
print_line(@__LINE__)
println("Compute and relinearize x_squared (x^2),")
println(" "^13, "then compute x_sq_plus_one (x^2+1)")
x_squared = Ciphertext()
square!(x_squared, x_encrypted, evaluator)
println(" + size of x_squared: ", length(x_squared))
relinearize_inplace!(x_squared, relin_keys_, evaluator)
println(" + size of x_squared (after relinearization): ", length(x_squared))
add_plain!(x_sq_plus_one, x_squared, plain_one, evaluator)
println(" + noise budget in x_sq_plus_one: ",
invariant_noise_budget(x_sq_plus_one, decryptor),
" bits")
decrypt!(decrypted_result, x_sq_plus_one, decryptor)
println(" + decryption of x_sq_plus_one: 0x", to_string(decrypted_result), " ...... Correct.")
print_line(@__LINE__)
x_plus_one = Ciphertext()
println("Compute x_plus_one (x+1),")
println(" "^13, "then compute and relinearize x_plus_one_sq ((x+1)^2).")
add_plain!(x_plus_one, x_encrypted, plain_one, evaluator)
square!(x_plus_one_sq, x_plus_one, evaluator)
println(" + size of x_plus_one_sq: ", length(x_plus_one_sq))
relinearize_inplace!(x_plus_one_sq, relin_keys_, evaluator)
println(" + noise budget in x_plus_one_sq: ",
invariant_noise_budget(x_plus_one_sq, decryptor),
" bits")
decrypt!(decrypted_result, x_plus_one_sq, decryptor)
println(" + decryption of x_plus_one_sq: 0x", to_string(decrypted_result),
" ...... Correct.")
print_line(@__LINE__)
println("Compute and relinearize encrypted_result (4(x^2+1)(x+1)^2).")
multiply_plain_inplace!(x_sq_plus_one, plain_four, evaluator)
multiply!(encrypted_result, x_sq_plus_one, x_plus_one_sq, evaluator)
println(" + size of encrypted_result: ", length(encrypted_result))
relinearize_inplace!(encrypted_result, relin_keys_, evaluator)
println(" + size of encrypted_result (after relinearization): ", length(encrypted_result))
println(" + noise budget in encrypted_result: ",
invariant_noise_budget(encrypted_result, decryptor),
" bits")
println()
println("NOTE: Notice the increase in remaining noise budget.")
print_line(@__LINE__)
println("Decrypt encrypted_result (4(x^2+1)(x+1)^2).")
decrypt!(decrypted_result, encrypted_result, decryptor)
println(" + decryption of 4(x^2+1)(x+1)^2 = 0x", to_string(decrypted_result),
" ...... Correct.")
println()
print_line(@__LINE__)
println("An example of invalid parameters")
set_poly_modulus_degree!(parms, 2048)
context = SEALContext(parms)
print_parameters(context)
println("Parameter validation (failed): ", parameter_error_message(context))
println()
return
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 6481 | include("utilities.jl")
using SEAL
using Printf
"""
example_batch_encoder()
Example to demonstrate encoding and decoding vectors of integers with the BFV scheme.
This function is based on the file `native/examples/2_encoders.cpp` of the original
SEAL library and should yield the exact same output.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/2_encoders.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/2_encoders.cpp)
See also: [`example_ckks_encoder`](@ref), [`example_encoders`](@ref)
"""
function example_batch_encoder()
print_example_banner("Example: Encoders / Batch Encoder")
parms = EncryptionParameters(SchemeType.bfv)
poly_modulus_degree = 8192
set_poly_modulus_degree!(parms, poly_modulus_degree)
set_coeff_modulus!(parms, coeff_modulus_bfv_default(poly_modulus_degree))
set_plain_modulus!(parms, plain_modulus_batching(poly_modulus_degree, 20))
context = SEALContext(parms)
print_parameters(context)
println()
context_data = first_context_data(context)
epq = qualifiers(context_data)
println("Batching enabled: ", using_batching(epq))
keygen = KeyGenerator(context)
public_key_ = PublicKey()
create_public_key!(public_key_, keygen)
secret_key_ = secret_key(keygen)
relin_keys_ = RelinKeys()
create_relin_keys!(relin_keys_, keygen)
encryptor = Encryptor(context, public_key_)
evaluator = Evaluator(context)
decryptor = Decryptor(context, secret_key_)
batch_encoder = BatchEncoder(context)
slot_count_ = slot_count(batch_encoder)
row_size = div(slot_count_, 2)
println("Plaintext matrix row size: ", row_size)
pod_matrix = zeros(UInt64, slot_count_)
pod_matrix[1] = 0
pod_matrix[2] = 1
pod_matrix[3] = 2
pod_matrix[4] = 3
pod_matrix[row_size + 1] = 4
pod_matrix[row_size + 2] = 5
pod_matrix[row_size + 3] = 6
pod_matrix[row_size + 4] = 7
println("Input plaintext matrix:")
print_matrix(pod_matrix, row_size)
plain_matrix = Plaintext()
print_line(@__LINE__)
println("Encode plaintext matrix:")
encode!(plain_matrix, pod_matrix, batch_encoder)
println(" + Decode plaintext matrix ...... Correct.")
pod_result = similar(pod_matrix)
decode!(pod_result, plain_matrix, batch_encoder)
print_matrix(pod_result, row_size)
encrypted_matrix = Ciphertext()
print_line(@__LINE__)
println("Encrypt plain_matrix to encrypted_matrix.")
encrypt!(encrypted_matrix, plain_matrix, encryptor)
println(" + Noise budget in encrypted_matrix: ",
invariant_noise_budget(encrypted_matrix, decryptor),
" bits")
pod_matrix2 = ones(UInt64, slot_count_)
pod_matrix2[2:2:slot_count_] .= 2
plain_matrix2 = Plaintext()
encode!(plain_matrix2, pod_matrix2, batch_encoder)
println()
println("Second input plaintext matrix:")
print_matrix(pod_matrix2, row_size)
print_line(@__LINE__)
println("Sum, square, and relinearize.")
add_plain_inplace!(encrypted_matrix, plain_matrix2, evaluator)
square_inplace!(encrypted_matrix, evaluator)
relinearize_inplace!(encrypted_matrix, relin_keys_, evaluator)
println(" + Noise budget in result: ",
invariant_noise_budget(encrypted_matrix, decryptor),
" bits")
plain_result = Plaintext()
print_line(@__LINE__)
println("Decrypt and decode result.")
decrypt!(plain_result, encrypted_matrix, decryptor)
decode!(pod_result, plain_result, batch_encoder)
println(" + Result plaintext matrix ...... Correct.")
print_matrix(pod_result, row_size)
end
"""
example_ckks_encoder()
Example to demonstrate encoding and decoding vectors of floating point values with the CKKS scheme.
This function is based on the file `native/examples/2_encoders.cpp` of the original
SEAL library and should yield the exact same output.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/2_encoders.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/2_encoders.cpp)
See also: [`example_batch_encoder`](@ref), [`example_encoders`](@ref)
"""
function example_ckks_encoder()
print_example_banner("Example: Encoders / CKKS Encoder")
parms = EncryptionParameters(SchemeType.ckks)
poly_modulus_degree = 8192
set_poly_modulus_degree!(parms, poly_modulus_degree)
set_coeff_modulus!(parms, coeff_modulus_create(poly_modulus_degree, [40, 40, 40, 40, 40]))
context = SEALContext(parms)
print_parameters(context)
println()
keygen = KeyGenerator(context)
public_key_ = PublicKey()
create_public_key!(public_key_, keygen)
secret_key_ = secret_key(keygen)
relin_keys_ = RelinKeys()
create_relin_keys!(relin_keys_, keygen)
encryptor = Encryptor(context, public_key_)
evaluator = Evaluator(context)
decryptor = Decryptor(context, secret_key_)
encoder = CKKSEncoder(context)
slot_count_ = slot_count(encoder)
println("Number of slots: ", slot_count_)
input = Float64[0.0, 1.1, 2.2, 3.3]
println("Input vector: ")
print_vector(input)
plain = Plaintext()
initial_scale = 2.0^30
print_line(@__LINE__)
println("Encode input vectors.")
encode!(plain, input, initial_scale, encoder)
output = Vector{Float64}(undef, slot_count_)
println(" + Decode input vector ...... Correct.")
decode!(output, plain, encoder)
print_vector(output)
encrypted = Ciphertext()
print_line(@__LINE__)
println("Encrypt input vector, square, and relinearize.")
encrypt!(encrypted, plain, encryptor)
square_inplace!(encrypted, evaluator)
relinearize_inplace!(encrypted, relin_keys_, evaluator)
println(" + Scale in squared input: ", scale(encrypted),
" (", log2(scale(encrypted)), " bits)")
print_line(@__LINE__)
println("Decrypt and decode.")
decrypt!(plain, encrypted, decryptor)
decode!(output, plain, encoder)
println(" + Result vector ...... Correct.")
print_vector(output)
end
"""
example_encoders()
Demonstrate how vectors of integers (BFV) or floating point values (CKKS) can be encoded/decoded
with the BFV and CKKS schemes.
This function is based on the file `native/examples/2_encoders.cpp` of the original
SEAL library and should yield the exact same output.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/2_encoders.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/2_encoders.cpp)
See also: [`example_batch_encoder`](@ref), [`example_ckks_encoder`](@ref)
"""
function example_encoders()
print_example_banner("Example: Encoders")
example_batch_encoder()
example_ckks_encoder()
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 7026 | include("utilities.jl")
using SEAL
using Printf
"""
example_levels()
Illustrate the concept of levels in the BFV and CKKS schemes.
This function is based on the file `native/examples/3_levels.cpp` of the original
SEAL library and should yield the exact same output.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/3_levels.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/3_levels.cpp)
See also: [`example_bfv_basics`](@ref), [`example_ckks_basics`](@ref)
"""
function example_levels()
print_example_banner("Example: Levels")
enc_parms = EncryptionParameters(SchemeType.bfv)
poly_modulus_degree = 8192
set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
set_coeff_modulus!(enc_parms, coeff_modulus_create(poly_modulus_degree, [50, 30, 30, 50, 50]))
set_plain_modulus!(enc_parms, plain_modulus_batching(poly_modulus_degree, 20))
context = SEALContext(enc_parms)
print_parameters(context)
println()
print_line(@__LINE__)
println("Print the modulus switching chain.")
context_data = key_context_data(context)
println("----> Level (chain index): ", chain_index(context_data), " ...... key_context_data()")
print(" parms_id:")
for parm_id in parms_id(context_data)
@printf(" %016x", parm_id)
end
println()
print(" coeff_modulus primes: ")
for prime in coeff_modulus(parms(context_data))
@printf("%016x ", value(prime))
end
println()
println("\\")
print(" \\-->")
context_data = first_context_data(context)
while !isnothing(context_data)
print(" Level (chain index): ", chain_index(context_data))
if parms_id(context_data) == first_parms_id(context)
println(" ...... first_context_data()")
elseif parms_id(context_data) == last_parms_id(context)
println(" ...... last_context_data()")
else
println()
end
print(" parms_id:")
for parm_id in parms_id(context_data)
@printf(" %016x", parm_id)
end
println()
print(" coeff_modulus primes: ")
for prime in coeff_modulus(parms(context_data))
@printf("%016x ", value(prime))
end
println()
println("\\")
print(" \\-->")
context_data = next_context_data(context_data)
end
println(" End of chain reached")
keygen = KeyGenerator(context)
public_key_ = PublicKey()
create_public_key!(public_key_, keygen)
secret_key_ = secret_key(keygen)
relin_keys_ = RelinKeys()
create_relin_keys!(relin_keys_, keygen)
print_line(@__LINE__)
println("Print the parameter IDs of generated elements.")
print(" + public_key: ")
for parm_id in parms_id(public_key_)
@printf(" %016x", parm_id)
end
println()
print(" + secret_key: ")
for parm_id in parms_id(secret_key_)
@printf(" %016x", parm_id)
end
println()
print(" + relin_keys: ")
for parm_id in parms_id(relin_keys_)
@printf(" %016x", parm_id)
end
println()
encryptor = Encryptor(context, public_key_)
evaluator = Evaluator(context)
decryptor = Decryptor(context, secret_key_)
plain = Plaintext("1x^3 + 2x^2 + 3x^1 + 4")
encrypted = Ciphertext()
encrypt!(encrypted, plain, encryptor)
print(" + plain: ")
for parm_id in parms_id(plain)
@printf(" %016x", parm_id)
end
println(" (not set in BFV)")
print(" + encrypted: ")
for parm_id in parms_id(encrypted)
@printf(" %016x", parm_id)
end
println()
println()
print_line(@__LINE__)
println("Perform modulus switching on encrypted and print.")
context_data = first_context_data(context)
print("---->")
while !isnothing(next_context_data(context_data))
println(" Level (chain index): ", chain_index(context_data))
print(" parms_id of encrypted: ")
for parm_id in parms_id(encrypted)
@printf(" %016x", parm_id)
end
println()
println(" Noise budget at this level: ", invariant_noise_budget(encrypted, decryptor),
" bits")
println("\\")
print(" \\-->")
mod_switch_to_next_inplace!(encrypted, evaluator)
context_data = next_context_data(context_data)
end
println(" Level (chain index): ", chain_index(context_data))
print(" parms_id of encrypted: ")
for parm_id in parms_id(encrypted)
@printf(" %016x", parm_id)
end
println()
println(" Noise budget at this level: ", invariant_noise_budget(encrypted, decryptor),
" bits")
println("\\")
print(" \\-->")
println(" End of chain reached")
println()
print_line(@__LINE__)
println("Decrypt still works after modulus switching.")
decrypt!(plain, encrypted, decryptor)
print(" + Decryption of encrypted: ", to_string(plain))
println(" ...... Correct.")
println()
println("Computation is more efficient with modulus switching.")
print_line(@__LINE__)
println("Compute the 8th power.")
encrypt!(encrypted, plain, encryptor)
println(" + Noise budget fresh: ",
invariant_noise_budget(encrypted, decryptor),
" bits")
square_inplace!(encrypted, evaluator)
relinearize_inplace!(encrypted, relin_keys_, evaluator)
println(" + Noise budget of the 2nd power: ",
invariant_noise_budget(encrypted, decryptor),
" bits")
square_inplace!(encrypted, evaluator)
relinearize_inplace!(encrypted, relin_keys_, evaluator)
println(" + Noise budget of the 4th power: ",
invariant_noise_budget(encrypted, decryptor),
" bits")
mod_switch_to_next_inplace!(encrypted, evaluator)
println(" + Noise budget after modulus switching: ",
invariant_noise_budget(encrypted, decryptor),
" bits")
square_inplace!(encrypted, evaluator)
relinearize_inplace!(encrypted, relin_keys_, evaluator)
println(" + Noise budget of the 8th power: ",
invariant_noise_budget(encrypted, decryptor),
" bits")
mod_switch_to_next_inplace!(encrypted, evaluator)
println(" + Noise budget after modulus switching: ",
invariant_noise_budget(encrypted, decryptor),
" bits")
decrypt!(plain, encrypted, decryptor)
println(" + Decryption of the 8th power (hexadecimal) ...... Correct.")
println(" ", to_string(plain))
println()
context = SEALContext(enc_parms, expand_mod_chain=false)
println("Optionally disable modulus switching chain expansion.")
print_line(@__LINE__)
println("Print the modulus switching chain.")
print("---->")
context_data = key_context_data(context)
while !isnothing(context_data)
println(" Level (chain index): ", chain_index(context_data))
print(" parms_id:")
for parm_id in parms_id(context_data)
@printf(" %016x", parm_id)
end
println()
print(" coeff_modulus primes: ")
for prime in coeff_modulus(parms(context_data))
@printf("%016x ", value(prime))
end
println()
println("\\")
print(" \\-->")
context_data = next_context_data(context_data)
end
println(" End of chain reached")
println()
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 5691 | include("utilities.jl")
using SEAL
using Printf
"""
example_ckks_basics()
Perform some basic operations such as encryption/decryption, multiplication, addition etc. using the
CKKS scheme. This routine is based on the file `native/examples/4_ckks_basics.cpp` of the original
SEAL library and should yield the exact same output.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/4_ckks_basics.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/4_ckks_basics.cpp)
See also: [`example_ckks_basics`](@ref)
"""
function example_ckks_basics()
print_example_banner("Example: CKKS Basics")
parms = EncryptionParameters(SchemeType.ckks)
poly_modulus_degree = 8192
set_poly_modulus_degree!(parms, poly_modulus_degree)
set_coeff_modulus!(parms, coeff_modulus_create(poly_modulus_degree, [60, 40, 40, 60]))
initial_scale = 2.0^40
context = SEALContext(parms)
print_parameters(context)
println()
keygen = KeyGenerator(context)
public_key_ = PublicKey()
create_public_key!(public_key_, keygen)
secret_key_ = secret_key(keygen)
relin_keys_ = RelinKeys()
create_relin_keys!(relin_keys_, keygen)
encryptor = Encryptor(context, public_key_)
evaluator = Evaluator(context)
decryptor = Decryptor(context, secret_key_)
encoder = CKKSEncoder(context)
slot_count_ = slot_count(encoder)
println("Number of slots: ", slot_count_)
input = collect(range(0.0, 1.0, length=slot_count_))
println("Input vector:")
print_vector(input, 3, 7)
println("Evaluating polynomial PI*x^3 + 0.4x + 1 ...")
plain_coeff3 = Plaintext()
plain_coeff1 = Plaintext()
plain_coeff0 = Plaintext()
encode!(plain_coeff3, 3.14159265, initial_scale, encoder)
encode!(plain_coeff1, 0.4, initial_scale, encoder)
encode!(plain_coeff0, 1.0, initial_scale, encoder)
x_plain = Plaintext()
print_line(@__LINE__)
println("Encode input vectors.")
encode!(x_plain, input, initial_scale, encoder)
x1_encrypted = Ciphertext()
encrypt!(x1_encrypted, x_plain, encryptor)
x3_encrypted = Ciphertext()
print_line(@__LINE__)
println("Compute x^2 and relinearize:")
square!(x3_encrypted, x1_encrypted, evaluator)
relinearize_inplace!(x3_encrypted, relin_keys_, evaluator)
println(" + Scale of x^2 before rescale: ", log2(scale(x3_encrypted)), " bits")
print_line(@__LINE__)
println("Rescale x^2.")
rescale_to_next_inplace!(x3_encrypted, evaluator)
println(" + Scale of x^2 after rescale: ", log2(scale(x3_encrypted)), " bits")
print_line(@__LINE__)
println("Compute and rescale PI*x.")
x1_encrypted_coeff3 = Ciphertext()
multiply_plain!(x1_encrypted_coeff3, x1_encrypted, plain_coeff3, evaluator)
println(" + Scale of PI*x before rescale: ", log2(scale(x1_encrypted_coeff3)), " bits")
rescale_to_next_inplace!(x1_encrypted_coeff3, evaluator)
println(" + Scale of PI*x after rescale: ", log2(scale(x1_encrypted_coeff3)), " bits")
print_line(@__LINE__)
println("Compute, relinearize, and rescale (PI*x)*x^2.")
multiply_inplace!(x3_encrypted, x1_encrypted_coeff3, evaluator)
relinearize_inplace!(x3_encrypted, relin_keys_, evaluator)
println(" + Scale of PI*x^3 before rescale: ", log2(scale(x3_encrypted)), " bits")
rescale_to_next_inplace!(x3_encrypted, evaluator)
println(" + Scale of PI*x^3 after rescale: ", log2(scale(x3_encrypted)), " bits")
print_line(@__LINE__)
println("Compute and rescale 0.4*x.")
multiply_plain_inplace!(x1_encrypted, plain_coeff1, evaluator)
println(" + Scale of 0.4*x before rescale: ", log2(scale(x1_encrypted)), " bits")
rescale_to_next_inplace!(x1_encrypted, evaluator)
println(" + Scale of 0.4*x after rescale: ", log2(scale(x1_encrypted)), " bits")
println()
print_line(@__LINE__)
println("Parameters used by all three terms are different.")
ci_x3 = chain_index(get_context_data(context, parms_id(x3_encrypted)))
println(" + Modulus chain index for x3_encrypted: ", ci_x3)
ci_x1 = chain_index(get_context_data(context, parms_id(x1_encrypted)))
println(" + Modulus chain index for x1_encrypted: ", ci_x1)
ci_c0 = chain_index(get_context_data(context, parms_id(plain_coeff0)))
println(" + Modulus chain index for plain_coeff0: ", ci_c0)
println()
print_line(@__LINE__)
println("The exact scales of all three terms are different:")
@printf(" + Exact scale in PI*x^3: %.10f\n", scale(x3_encrypted))
@printf(" + Exact scale in 0.4*x: %.10f\n", scale(x1_encrypted))
@printf(" + Exact scale in 1: %.10f\n", scale(plain_coeff0))
println()
print_line(@__LINE__)
println("Normalize scales to 2^40.")
scale!(x3_encrypted, 2.0^40)
scale!(x1_encrypted, 2.0^40)
print_line(@__LINE__)
println("Normalize encryption parameters to the lowest level.")
last_parms_id = parms_id(x3_encrypted)
mod_switch_to_inplace!(x1_encrypted, last_parms_id, evaluator)
mod_switch_to_inplace!(plain_coeff0, last_parms_id, evaluator)
print_line(@__LINE__)
println("Compute PI*x^3 + 0.4*x + 1.")
encrypted_result = Ciphertext()
add!(encrypted_result, x3_encrypted, x1_encrypted, evaluator)
add_plain_inplace!(encrypted_result, plain_coeff0, evaluator)
plain_result = Plaintext()
print_line(@__LINE__)
println("Decrypt and decode PI*x^3 + 0.4x + 1.")
println(" + Expected result:")
true_result = similar(input)
for (i, x) in enumerate(input)
true_result[i] = (3.14159265 * x * x + 0.4) * x + 1
end
print_vector(true_result, 3, 7)
decrypt!(plain_result, encrypted_result, decryptor)
result = similar(input)
decode!(result, plain_result, encoder)
println(" + Computed result ...... Correct.")
print_vector(result, 3, 7)
return
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 6109 | include("utilities.jl")
using SEAL
using Printf
"""
example_rotation_bfv()
Perform some rotation on data encryped with the BFV scheme. This routine is based on the file
`native/examples/5_rotation.cpp` of the original SEAL library and should yield the exact same
output.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/5_rotation.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/5_rotation.cpp)
"""
function example_rotation_bfv()
print_example_banner("Example: Rotation / Rotation in BFV")
parms = EncryptionParameters(SchemeType.bfv)
poly_modulus_degree = 8192
set_poly_modulus_degree!(parms, poly_modulus_degree)
set_coeff_modulus!(parms, coeff_modulus_bfv_default(poly_modulus_degree))
set_plain_modulus!(parms, plain_modulus_batching(poly_modulus_degree, 20))
context = SEALContext(parms)
print_parameters(context)
println()
keygen = KeyGenerator(context)
secret_key_ = secret_key(keygen)
public_key_ = PublicKey()
create_public_key!(public_key_, keygen)
relin_keys_ = RelinKeys()
create_relin_keys!(relin_keys_, keygen)
encryptor = Encryptor(context, public_key_)
evaluator = Evaluator(context)
decryptor = Decryptor(context, secret_key_)
batch_encoder = BatchEncoder(context)
slot_count_ = slot_count(batch_encoder)
row_size = div(slot_count_, 2)
println("Plaintext matrix row size: ", row_size)
pod_matrix = zeros(UInt64, slot_count_)
pod_matrix[1] = 0
pod_matrix[2] = 1
pod_matrix[3] = 2
pod_matrix[4] = 3
pod_matrix[row_size + 1] = 4
pod_matrix[row_size + 2] = 5
pod_matrix[row_size + 3] = 6
pod_matrix[row_size + 4] = 7
println("Input plaintext matrix:")
print_matrix(pod_matrix, row_size)
plain_matrix = Plaintext()
print_line(@__LINE__)
println("Encode and encrypt.")
encode!(plain_matrix, pod_matrix, batch_encoder)
encrypted_matrix = Ciphertext()
encrypt!(encrypted_matrix, plain_matrix, encryptor)
println(" + Noise budget in fresh encryption: ",
invariant_noise_budget(encrypted_matrix, decryptor),
" bits")
println()
galois_keys = GaloisKeys()
create_galois_keys!(galois_keys, keygen)
print_line(@__LINE__)
println("Rotate rows 3 steps left.")
rotate_rows_inplace!(encrypted_matrix, 3, galois_keys, evaluator)
plain_result = Plaintext()
println(" + Noise budget after rotation: ",
invariant_noise_budget(encrypted_matrix, decryptor),
" bits")
println(" + Decrypt and decode ...... Correct.")
decrypt!(plain_result, encrypted_matrix, decryptor)
decode!(pod_matrix, plain_result, batch_encoder)
print_matrix(pod_matrix, row_size)
print_line(@__LINE__)
println("Rotate columns.")
rotate_columns_inplace!(encrypted_matrix, galois_keys, evaluator)
println(" + Noise budget after rotation: ",
invariant_noise_budget(encrypted_matrix, decryptor),
" bits")
println(" + Decrypt and decode ...... Correct.")
decrypt!(plain_result, encrypted_matrix, decryptor)
decode!(pod_matrix, plain_result, batch_encoder)
print_matrix(pod_matrix, row_size)
print_line(@__LINE__)
println("Rotate rows 4 steps right.")
rotate_rows_inplace!(encrypted_matrix, -4, galois_keys, evaluator)
plain_result = Plaintext()
println(" + Noise budget after rotation: ",
invariant_noise_budget(encrypted_matrix, decryptor),
" bits")
println(" + Decrypt and decode ...... Correct.")
decrypt!(plain_result, encrypted_matrix, decryptor)
decode!(pod_matrix, plain_result, batch_encoder)
print_matrix(pod_matrix, row_size)
end
"""
example_rotation_ckks()
Perform some rotation on data encryped with the CKKS scheme. This routine is based on the file
`native/examples/5_rotation.cpp` of the original SEAL library and should yield the exact same
output.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/5_rotation.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/5_rotation.cpp)
"""
function example_rotation_ckks()
print_example_banner("Example: Rotation / Rotation in CKKS")
parms = EncryptionParameters(SchemeType.ckks)
poly_modulus_degree = 8192
set_poly_modulus_degree!(parms, poly_modulus_degree)
set_coeff_modulus!(parms, coeff_modulus_create(poly_modulus_degree, [40, 40, 40, 40, 40]))
context = SEALContext(parms)
print_parameters(context)
println()
keygen = KeyGenerator(context)
public_key_ = PublicKey()
create_public_key!(public_key_, keygen)
secret_key_ = secret_key(keygen)
relin_keys_ = RelinKeys()
create_relin_keys!(relin_keys_, keygen)
galois_keys_ = GaloisKeys()
create_galois_keys!(galois_keys_, keygen)
encryptor = Encryptor(context, public_key_)
evaluator = Evaluator(context)
decryptor = Decryptor(context, secret_key_)
encoder = CKKSEncoder(context)
slot_count_ = slot_count(encoder)
println("Number of slots: ", slot_count_)
input = collect(range(0.0, 1.0, length=slot_count_))
println("Input vector:")
print_vector(input, 3, 7)
initial_scale = 2.0^50
print_line(@__LINE__)
println("Encode and encrypt.")
plain = Plaintext()
encode!(plain, input, initial_scale, encoder)
encrypted = Ciphertext()
encrypt!(encrypted, plain, encryptor)
rotated = Ciphertext()
print_line(@__LINE__)
println("Rotate 2 steps left.")
rotate_vector!(rotated, encrypted, 2, galois_keys_, evaluator)
println(" + Decrypt and decode ...... Correct.")
decrypt!(plain, rotated, decryptor)
result = similar(input)
decode!(result, plain, encoder)
print_vector(result, 3, 7)
return
end
"""
example_rotation()
Perform some rotation on data encryped with the BFV and CKKS schemes. This routine is based on the
file `native/examples/5_rotation.cpp` of the original SEAL library and should yield the exact same
output.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/5_rotation.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/5_rotation.cpp)
"""
function example_rotation()
print_example_banner("Example: Rotation")
example_rotation_bfv()
example_rotation_ckks()
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 5794 | include("utilities.jl")
using SEAL
using Printf
"""
example_serialization()
Show example for how to use serialization in a client-server setup, where only the client knows the
secret key and the servers does not have knowledge of any unencrypted data.
This function is based on the file `native/examples/6_serialization.cpp` of the original
SEAL library and should yield the exact same output, except for differences in compression ratios.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/6_serialization.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/6_serialization.cpp)
See also: [`example_bfv_basics`](@ref), [`example_ckks_basics`](@ref)
"""
function example_serialization()
print_example_banner("Example: Serialization")
parms_stream = UInt8[]
data_stream1 = UInt8[]
data_stream2 = UInt8[]
data_stream3 = UInt8[]
data_stream4 = UInt8[]
sk_stream = UInt8[]
# Use `let` to create new variable scope to mimic curly braces-delimited blocks in C++
# Server
let
parms = EncryptionParameters(SchemeType.ckks)
poly_modulus_degree = 8192
set_poly_modulus_degree!(parms, poly_modulus_degree)
set_coeff_modulus!(parms, coeff_modulus_create(poly_modulus_degree, [50, 20, 50]))
resize!(parms_stream, save_size(parms))
out_bytes = save!(parms_stream, parms)
resize!(parms_stream, out_bytes)
print_line(@__LINE__)
println("EncryptionParameters: wrote ", out_bytes, " bytes")
print_line(@__LINE__)
println("EncryptionParameters: data size upper bound (compr_mode_type::none): ",
save_size(ComprModeType.none, parms))
println(" EncryptionParameters: data size upper bound (compression): ",
save_size(parms))
byte_buffer = Vector{UInt8}(undef, save_size(parms))
save!(byte_buffer, length(byte_buffer), parms)
parms2 = EncryptionParameters()
load!(parms2, byte_buffer, length(byte_buffer))
print_line(@__LINE__)
println("EncryptionParameters: parms == parms2: ", parms == parms2)
end
# Client
let
parms = EncryptionParameters()
load!(parms, parms_stream)
context = SEALContext(parms)
keygen = KeyGenerator(context)
sk = secret_key(keygen)
pk = PublicKey()
create_public_key!(pk, keygen)
resize!(sk_stream, save_size(sk))
out_bytes = save!(sk_stream, sk)
resize!(sk_stream, out_bytes)
rlk = create_relin_keys(keygen)
rlk_big = RelinKeys()
create_relin_keys!(rlk_big, keygen)
resize!(data_stream1, save_size(rlk))
size_rlk = save!(data_stream1, rlk)
resize!(data_stream1, size_rlk)
resize!(data_stream2, save_size(rlk_big))
size_rlk_big = save!(data_stream2, rlk_big)
resize!(data_stream2, size_rlk_big)
print_line(@__LINE__)
println("Serializable<RelinKeys>: wrote ", size_rlk, " bytes")
println(" ", "RelinKeys wrote ", size_rlk_big, " bytes")
initial_scale = 2.0^20
encoder = CKKSEncoder(context)
plain1 = Plaintext()
plain2 = Plaintext()
encode!(plain1, 2.3, initial_scale, encoder)
encode!(plain2, 4.5, initial_scale, encoder)
encryptor = Encryptor(context, pk)
encrypted1 = Ciphertext()
encrypt!(encrypted1, plain1, encryptor)
resize!(data_stream2, save_size(encrypted1))
size_encrypted1 = save!(data_stream2, encrypted1)
resize!(data_stream2, size_encrypted1)
set_secret_key!(encryptor, sk)
sym_encrypted2 = encrypt_symmetric(plain2, encryptor)
resize!(data_stream3, save_size(sym_encrypted2))
size_sym_encrypted2 = save!(data_stream3, sym_encrypted2)
resize!(data_stream3, size_sym_encrypted2)
print_line(@__LINE__)
println("Serializable<Ciphertext> (public-key): wrote ", size_encrypted1, " bytes")
println(" ",
"Serializable<Ciphertext> (seeded secret-key): wrote ", size_sym_encrypted2, " bytes")
end
# Server
let
parms = EncryptionParameters()
load!(parms, parms_stream)
context = SEALContext(parms)
evaluator = Evaluator(context)
rlk = RelinKeys()
encrypted1 = Ciphertext()
encrypted2 = Ciphertext()
load!(rlk, context, data_stream1)
load!(encrypted1, context, data_stream2)
load!(encrypted2, context, data_stream3)
encrypted_prod = Ciphertext()
multiply!(encrypted_prod, encrypted1, encrypted2, evaluator)
relinearize_inplace!(encrypted_prod, rlk, evaluator)
rescale_to_next_inplace!(encrypted_prod, evaluator)
resize!(data_stream4, save_size(encrypted_prod))
size_encrypted_prod = save!(data_stream4, encrypted_prod)
resize!(data_stream4, size_encrypted_prod)
print_line(@__LINE__)
println("Ciphertext (secret-key): wrote ", size_encrypted_prod, " bytes")
end
# Client
let
parms = EncryptionParameters()
load!(parms, parms_stream)
context = SEALContext(parms)
sk = SecretKey()
load!(sk, context, sk_stream)
decryptor = Decryptor(context, sk)
encoder = CKKSEncoder(context)
encrypted_result = Ciphertext()
load!(encrypted_result, context, data_stream4)
plain_result = Plaintext()
decrypt!(plain_result, encrypted_result, decryptor)
slot_count_ = slot_count(encoder)
result = Vector{Float64}(undef, slot_count_)
decode!(result, plain_result, encoder)
print_line(@__LINE__)
println("Result: ")
print_vector(result, 3, 7)
end
pt = Plaintext("1x^2 + 3")
stream = Vector{UInt8}(undef, save_size(pt))
data_size = save!(stream, pt)
resize!(stream, data_size)
header = SEALHeader()
load_header!(header, stream)
print_line(@__LINE__)
println("Size written to stream: ", data_size, " bytes")
println(" ",
"Size indicated in SEALHeader: ", header.size, " bytes")
println()
return
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 23762 | include("utilities.jl")
using SEAL
using Printf
using Random
"""
bfv_performance_test(context)
Perform multiple performance tests with the BFV scheme for the SEAL encryption context given in
`context`.
This function is based on the file `native/examples/7_performance.cpp` of the original
SEAL library and should yield the exact same output, except (of course) for the actual performance
numbers.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/7_performance.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/7_performance.cpp)
See also: [`example_performance_test`](@ref),
[`example_ckks_performance_default`](@ref), [`example_ckks_performance_custom`](@ref),
[`bfv_performance_test`](@ref)
"""
function bfv_performance_test(context)
print_parameters(context)
println()
enc_params = parms(first_context_data(context))
plain_modulus_ = plain_modulus(enc_params)
poly_modulus_degree_ = poly_modulus_degree(enc_params)
print("Generating secret/public keys: ")
keygen = KeyGenerator(context)
println("Done")
secret_key_ = secret_key(keygen)
public_key_ = PublicKey()
create_public_key!(public_key_, keygen)
if using_keyswitching(context)
print("Generating relinearization keys: ")
time_diff = @elapsedus begin
relin_keys_ = RelinKeys()
create_relin_keys!(relin_keys_, keygen)
end
println("Done [", time_diff, " microseconds]")
if !using_batching(qualifiers(key_context_data(context)))
println("Given encryption parameters do not support batching.")
return
end
print("Generating Galois keys: ")
time_diff = @elapsedus begin
galois_keys_ = GaloisKeys()
create_galois_keys!(galois_keys_, keygen)
end
println("Done [", time_diff, " microseconds]")
end
encryptor = Encryptor(context, public_key_)
decryptor = Decryptor(context, secret_key_)
evaluator = Evaluator(context)
batch_encoder = BatchEncoder(context)
time_batch_sum = 0
time_unbatch_sum = 0
time_encrypt_sum = 0
time_decrypt_sum = 0
time_add_sum = 0
time_multiply_sum = 0
time_multiply_plain_sum = 0
time_square_sum = 0
time_relinearize_sum = 0
time_rotate_rows_one_step_sum = 0
time_rotate_rows_random_sum = 0
time_rotate_columns_sum = 0
time_serialize_sum = 0
time_serialize_zlib_sum = 0
time_serialize_zstd_sum = 0
count = 10
slot_count_ = slot_count(batch_encoder)
pod_vector = rand(RandomDevice(), UInt64, slot_count_) .% value(plain_modulus_)
print("Running tests ")
for i in 1:count
plain = Plaintext(poly_modulus_degree_, 0)
plain1 = Plaintext(poly_modulus_degree_, 0)
plain2 = Plaintext(poly_modulus_degree_, 0)
time_batch_sum += @elapsedus encode!(plain, pod_vector, batch_encoder)
pod_vector2 = Vector{UInt64}(undef, slot_count_)
time_unbatch_sum += @elapsedus decode!(pod_vector2, plain, batch_encoder)
if pod_vector2 != pod_vector
error("Batch/unbatch failed. Something is wrong.")
end
encrypted = Ciphertext(context)
time_encrypt_sum += @elapsedus encrypt!(encrypted, plain, encryptor)
plain2 = Plaintext(poly_modulus_degree(enc_params), 0)
time_decrypt_sum += @elapsedus decrypt!(plain2, encrypted, decryptor)
if plain2 != plain
error("Encrypt/decrypt failed. Something is wrong.")
end
encrypted1 = Ciphertext(context)
encode!(plain1, fill(UInt64(i), slot_count_), batch_encoder)
encrypt!(encrypted1, plain1, encryptor)
encrypted2 = Ciphertext(context)
encode!(plain2, fill(UInt64(i+1), slot_count_), batch_encoder)
encrypt!(encrypted2, plain2, encryptor)
time_add_sum += @elapsedus begin
add_inplace!(encrypted1, encrypted1, evaluator)
add_inplace!(encrypted2, encrypted2, evaluator)
add_inplace!(encrypted1, encrypted2, evaluator)
end
reserve!(encrypted1, 3)
time_multiply_sum += @elapsedus multiply_inplace!(encrypted1, encrypted2, evaluator)
time_multiply_plain_sum += @elapsedus multiply_plain_inplace!(encrypted2, plain, evaluator)
time_square_sum += @elapsedus square_inplace!(encrypted2, evaluator)
if using_keyswitching(context)
time_relinearize_sum += @elapsedus relinearize_inplace!(encrypted1, relin_keys_, evaluator)
time_rotate_rows_one_step_sum += @elapsedus begin
rotate_rows_inplace!(encrypted, 1, galois_keys_, evaluator)
rotate_rows_inplace!(encrypted, -1, galois_keys_, evaluator)
end
row_size = div(slot_count(batch_encoder), 2)
random_rotation = rand(RandomDevice(), Int64) & (row_size - 1)
time_rotate_rows_random_sum += @elapsedus begin
rotate_rows_inplace!(encrypted, random_rotation, galois_keys_, evaluator)
end
time_rotate_columns_sum += @elapsedus begin
rotate_columns_inplace!(encrypted, galois_keys_, evaluator)
end
end
buf_size = save_size(ComprModeType.none, encrypted)
buf = Vector{UInt8}(undef, buf_size)
time_serialize_sum += @elapsedus begin
save!(buf, buf_size, ComprModeType.none, encrypted)
end
buf_size = save_size(ComprModeType.zlib, encrypted)
resize!(buf, buf_size)
time_serialize_zlib_sum += @elapsedus begin
save!(buf, buf_size, ComprModeType.zlib, encrypted)
end
buf_size = save_size(ComprModeType.zstd, encrypted)
resize!(buf, buf_size)
time_serialize_zstd_sum += @elapsedus begin
save!(buf, buf_size, ComprModeType.zstd, encrypted)
end
print(".")
flush(stdout)
end
println(" Done")
println()
avg_batch = div(time_batch_sum, count)
avg_unbatch = div(time_unbatch_sum, count)
avg_encrypt = div(time_encrypt_sum, count)
avg_decrypt = div(time_decrypt_sum, count)
avg_add = div(time_add_sum, (3 * count))
avg_multiply = div(time_multiply_sum, count)
avg_multiply_plain = div(time_multiply_plain_sum, count)
avg_square = div(time_square_sum, count)
avg_relinearize = div(time_relinearize_sum, count)
avg_rotate_rows_one_step = div(time_rotate_rows_one_step_sum, (2 * count))
avg_rotate_rows_random = div(time_rotate_rows_random_sum, count)
avg_rotate_columns = div(time_rotate_columns_sum, count)
avg_serialize = div(time_serialize_sum, count)
avg_serialize_zlib = div(time_serialize_zlib_sum, count)
avg_serialize_zstd = div(time_serialize_zstd_sum, count)
println("Average batch: ", avg_batch, " microseconds")
println("Average unbatch: ", avg_unbatch, " microseconds")
println("Average encrypt: ", avg_encrypt, " microseconds")
println("Average decrypt: ", avg_decrypt, " microseconds")
println("Average add: ", avg_add, " microseconds")
println("Average multiply: ", avg_multiply, " microseconds")
println("Average multiply plain: ", avg_multiply_plain, " microseconds")
println("Average square: ", avg_square, " microseconds")
if using_keyswitching(context)
println("Average relinearize: ", avg_relinearize, " microseconds")
println("Average rotate rows one step: ", avg_rotate_rows_one_step, " microseconds")
println("Average rotate rows random: ", avg_rotate_rows_random, " microseconds")
println("Average rotate columns: ", avg_rotate_columns, " microseconds")
end
println("Average serialize ciphertext: ", avg_serialize, " microseconds")
println("Average compressed (ZLIB) serialize ciphertext: ", avg_serialize_zlib, " microseconds")
println("Average compressed (Zstandard) serialize ciphertext: ", avg_serialize_zstd, " microseconds")
end
"""
ckks_performance_test(context)
Perform multiple performance tests with the CKKS scheme for the SEAL encryption context given in
`context`.
This function is based on the file `native/examples/7_performance.cpp` of the original
SEAL library and should yield the exact same output, except (of course) for the actual performance
numbers.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/7_performance.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/7_performance.cpp)
See also: [`example_performance_test`](@ref),
[`example_ckks_performance_default`](@ref), [`example_ckks_performance_custom`](@ref),
[`bfv_performance_test`](@ref)
"""
function ckks_performance_test(context)
print_parameters(context)
println()
enc_params = parms(first_context_data(context))
poly_modulus_degree_ = poly_modulus_degree(enc_params)
print("Generating secret/public keys: ")
keygen = KeyGenerator(context)
println("Done")
secret_key_ = secret_key(keygen)
public_key_ = PublicKey()
create_public_key!(public_key_, keygen)
if using_keyswitching(context)
print("Generating relinearization keys: ")
time_diff = @elapsedus begin
relin_keys_ = RelinKeys()
create_relin_keys!(relin_keys_, keygen)
end
println("Done [", time_diff, " microseconds]")
if !using_batching(qualifiers(key_context_data(context)))
println("Given encryption parameters do not support batching.")
return
end
print("Generating Galois keys: ")
time_diff = @elapsedus begin
galois_keys_ = GaloisKeys()
create_galois_keys!(galois_keys_, keygen)
end
println("Done [", time_diff, " microseconds]")
end
encryptor = Encryptor(context, public_key_)
decryptor = Decryptor(context, secret_key_)
evaluator = Evaluator(context)
ckks_encoder = CKKSEncoder(context)
time_encode_sum = 0
time_decode_sum = 0
time_encrypt_sum = 0
time_decrypt_sum = 0
time_add_sum = 0
time_multiply_sum = 0
time_multiply_plain_sum = 0
time_square_sum = 0
time_relinearize_sum = 0
time_rescale_sum = 0
time_rotate_one_step_sum = 0
time_rotate_random_sum = 0
time_conjugate_sum = 0
time_serialize_sum = 0
time_serialize_zlib_sum = 0
time_serialize_zstd_sum = 0
count = 10
pod_vector = 1.001 * collect(1:slot_count(ckks_encoder))
print("Running tests ")
for i in 1:count
plain = Plaintext(poly_modulus_degree(enc_params) * length(coeff_modulus(enc_params)), 0)
scale_ = sqrt(value(last(coeff_modulus(enc_params))))
time_encode_sum += @elapsedus encode!(plain, pod_vector, scale_, ckks_encoder)
pod_vector2 = Vector{Float64}(undef, slot_count(ckks_encoder))
time_decode_sum += @elapsedus decode!(pod_vector2, plain, ckks_encoder)
encrypted = Ciphertext(context)
time_encrypt_sum += @elapsedus encrypt!(encrypted, plain, encryptor)
plain2 = Plaintext(poly_modulus_degree_, 0)
time_decrypt_sum += @elapsedus decrypt!(plain2, encrypted, decryptor)
encrypted1 = Ciphertext()
encode!(plain, i + 1, ckks_encoder)
encrypt!(encrypted1, plain, encryptor)
encrypted2 = Ciphertext()
encode!(plain2, i + 1, ckks_encoder)
encrypt!(encrypted2, plain2, encryptor)
time_add_sum += @elapsedus begin
add_inplace!(encrypted1, encrypted1, evaluator)
add_inplace!(encrypted2, encrypted2, evaluator)
add_inplace!(encrypted1, encrypted2, evaluator)
end
reserve!(encrypted1, 3)
time_multiply_sum += @elapsedus multiply_inplace!(encrypted1, encrypted2, evaluator)
time_multiply_plain_sum += @elapsedus multiply_plain_inplace!(encrypted2, plain, evaluator)
time_square_sum += @elapsedus square_inplace!(encrypted2, evaluator)
if using_keyswitching(context)
time_relinearize_sum += @elapsedus relinearize_inplace!(encrypted1, relin_keys_, evaluator)
time_rescale_sum += @elapsedus rescale_to_next_inplace!(encrypted1, evaluator)
time_rotate_one_step_sum += @elapsedus begin
rotate_vector_inplace!(encrypted, 1, galois_keys_, evaluator)
rotate_vector_inplace!(encrypted, -1, galois_keys_, evaluator)
end
random_rotation = rand(RandomDevice(), Int64) & (slot_count(ckks_encoder) - 1)
time_rotate_random_sum += @elapsedus begin
rotate_vector_inplace!(encrypted, random_rotation, galois_keys_, evaluator)
end
time_conjugate_sum += @elapsedus complex_conjugate_inplace!(encrypted, galois_keys_, evaluator)
end
buf_size = save_size(ComprModeType.none, encrypted)
buf = Vector{UInt8}(undef, buf_size)
time_serialize_sum += @elapsedus begin
save!(buf, buf_size, ComprModeType.none, encrypted)
end
buf_size = save_size(ComprModeType.zlib, encrypted)
resize!(buf, buf_size)
time_serialize_zlib_sum += @elapsedus begin
save!(buf, buf_size, ComprModeType.zlib, encrypted)
end
buf_size = save_size(ComprModeType.zstd, encrypted)
resize!(buf, buf_size)
time_serialize_zstd_sum += @elapsedus begin
save!(buf, buf_size, ComprModeType.zstd, encrypted)
end
print(".")
flush(stdout)
end
println(" Done")
println()
avg_encode = div(time_encode_sum, count)
avg_decode = div(time_decode_sum, count)
avg_encrypt = div(time_encrypt_sum, count)
avg_decrypt = div(time_decrypt_sum, count)
avg_add = div(time_add_sum, (3 * count))
avg_multiply = div(time_multiply_sum, count)
avg_multiply_plain = div(time_multiply_plain_sum, count)
avg_square = div(time_square_sum, count)
avg_relinearize = div(time_relinearize_sum, count)
avg_rescale = div(time_rescale_sum, count)
avg_rotate_one_step = div(time_rotate_one_step_sum, (2 * count))
avg_rotate_random = div(time_rotate_random_sum, count)
avg_conjugate = div(time_conjugate_sum, count)
avg_serialize = div(time_serialize_sum, count)
avg_serialize_zlib = div(time_serialize_zlib_sum, count)
avg_serialize_zstd = div(time_serialize_zstd_sum, count)
println("Average encode: ", avg_encode, " microseconds")
println("Average decode: ", avg_decode, " microseconds")
println("Average encrypt: ", avg_encrypt, " microseconds")
println("Average decrypt: ", avg_decrypt, " microseconds")
println("Average add: ", avg_add, " microseconds")
println("Average multiply: ", avg_multiply, " microseconds")
println("Average multiply plain: ", avg_multiply_plain, " microseconds")
println("Average square: ", avg_square, " microseconds")
if using_keyswitching(context)
println("Average relinearize: ", avg_relinearize, " microseconds")
println("Average rescale: ", avg_rescale, " microseconds")
println("Average rotate vector one step: ", avg_rotate_one_step, " microseconds")
println("Average rotate vector random: ", avg_rotate_random, " microseconds")
println("Average complex conjugate: ", avg_conjugate, " microseconds")
end
println("Average serialize ciphertext: ", avg_serialize, " microseconds")
println("Average compressed (ZLIB) serialize ciphertext: ", avg_serialize_zlib, " microseconds")
println("Average compressed (Zstandard) serialize ciphertext: ", avg_serialize_zstd, " microseconds")
flush(stdout)
end
"""
example_bfv_performance_default()
Perform multiple performance tests of the BFV scheme for several polynomial modulus degrees.
This function is based on the file `native/examples/7_performance.cpp` of the original
SEAL library and should yield the exact same output, except (of course) for the actual performance
numbers.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/7_performance.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/7_performance.cpp)
See also: [`example_performance_test`](@ref), [`example_bfv_performance_custom`](@ref),
[`bfv_performance_test`](@ref),
[`example_ckks_performance_default`](@ref)
"""
function example_bfv_performance_default()
print_example_banner("BFV Performance Test with Degrees: 4096, 8192, and 16384")
enc_parms = EncryptionParameters(SchemeType.bfv)
poly_modulus_degree = 4096
set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
set_plain_modulus!(enc_parms, 786433)
bfv_performance_test(SEALContext(enc_parms))
println()
poly_modulus_degree = 8192
set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
set_plain_modulus!(enc_parms, 786433)
bfv_performance_test(SEALContext(enc_parms))
println()
poly_modulus_degree = 16384
set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
set_plain_modulus!(enc_parms, 786433)
bfv_performance_test(SEALContext(enc_parms))
# Comment out the following to run the biggest example
#
# println()
# poly_modulus_degree = 32768
# set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
# set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
# set_plain_modulus!(enc_parms, 786433)
# bfv_performance_test(SEALContext(enc_parms))
end
"""
example_bfv_performance_custom()
Show a terminal menu for selecting a custom polynomial modulus degree and use it for performance
tests with the BFV scheme.
This function is based on the file `native/examples/7_performance.cpp` of the original
SEAL library and should yield the exact same output, except (of course) for the actual performance
numbers.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/7_performance.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/7_performance.cpp)
See also: [`example_performance_test`](@ref), [`example_bfv_performance_default`](@ref),
[`bfv_performance_test`](@ref),
[`example_ckks_performance_custom`](@ref)
"""
function example_bfv_performance_custom()
poly_modulus_degree = 0
println()
print("Set poly_modulus_degree (1024, 2048, 4096, 8192, 16384, or 32768): ")
input = readline()
if !isopen(stdin)
return
end
try
poly_modulus_degree = parse(Int, input)
catch
println("Invalid option")
return
end
if (poly_modulus_degree < 1024 || poly_modulus_degree > 32768 || (poly_modulus_degree &
(poly_modulus_degree - 1)) != 0)
println("Invalid option")
return
end
print_example_banner("BFV Performance Test with Degree: $poly_modulus_degree")
enc_parms = EncryptionParameters(SchemeType.bfv)
set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
if poly_modulus_degree == 1024
set_plain_modulus!(enc_parms, 12289)
else
set_plain_modulus!(enc_parms, 786433)
end
bfv_performance_test(SEALContext(enc_parms))
end
"""
example_ckks_performance_default()
Perform multiple performance tests of the CKKS scheme for several polynomial modulus degrees.
This function is based on the file `native/examples/7_performance.cpp` of the original
SEAL library and should yield the exact same output, except (of course) for the actual performance
numbers.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/7_performance.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/7_performance.cpp)
See also: [`example_performance_test`](@ref), [`example_ckks_performance_custom`](@ref),
[`ckks_performance_test`](@ref),
[`example_bfv_performance_default`](@ref)
"""
function example_ckks_performance_default()
print_example_banner("CKKS Performance Test with Degrees: 4096, 8192, and 16384")
# BFV primes are not recommended for CKKS, but are good enough for performance testing
enc_parms = EncryptionParameters(SchemeType.ckks)
poly_modulus_degree = 4096
set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
ckks_performance_test(SEALContext(enc_parms))
println()
poly_modulus_degree = 8192
set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
ckks_performance_test(SEALContext(enc_parms))
println()
poly_modulus_degree = 16384
set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
ckks_performance_test(SEALContext(enc_parms))
# Comment out the following to run the biggest example
#
# println()
# poly_modulus_degree = 32768
# set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
# set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
# ckks_performance_test(SEALContext(enc_parms))
end
"""
example_ckks_performance_custom()
Show a terminal menu for selecting a custom polynomial modulus degree and use it for performance
tests with the CKKS scheme.
This function is based on the file `native/examples/7_performance.cpp` of the original
SEAL library and should yield the exact same output, except (of course) for the actual performance
numbers.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/7_performance.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/7_performance.cpp)
See also: [`example_performance_test`](@ref), [`example_ckks_performance_default`](@ref),
[`ckks_performance_test`](@ref),
[`example_bfv_performance_custom`](@ref)
"""
function example_ckks_performance_custom()
poly_modulus_degree = 0
println()
print("Set poly_modulus_degree (1024, 2048, 4096, 8192, 16384, or 32768): ")
input = readline()
if !isopen(stdin)
return
end
try
poly_modulus_degree = parse(Int, input)
catch
println("Invalid option")
return
end
if (poly_modulus_degree < 1024 || poly_modulus_degree > 32768 || (poly_modulus_degree &
(poly_modulus_degree - 1)) != 0)
println("Invalid option")
return
end
print_example_banner("CKKS Performance Test with Degree: $poly_modulus_degree")
enc_parms = EncryptionParameters(SchemeType.ckks)
set_poly_modulus_degree!(enc_parms, poly_modulus_degree)
set_coeff_modulus!(enc_parms, coeff_modulus_bfv_default(poly_modulus_degree))
ckks_performance_test(SEALContext(enc_parms))
end
"""
example_performance_test()
Show a terminal menu for selecting different performance tests.
This function is based on the file `native/examples/7_performance.cpp` of the original
SEAL library and should yield the exact same output, except (of course) for the actual performance
numbers.
* [SEAL](https://github.com/microsoft/SEAL)
* [native/examples/7_performance.cpp](https://github.com/microsoft/SEAL/blob/master/native/examples/7_performance.cpp)
See also: [`example_bfv_performance_default`](@ref), [`example_bfv_performance_custom`](@ref),
[`bfv_performance_test`](@ref),
[`example_ckks_performance_default`](@ref), [`example_ckks_performance_custom`](@ref),
[`ckks_performance_test`](@ref)
"""
function example_performance_test()
print_example_banner("Example: Performance Test")
while true
println()
println("Select a scheme (and optionally poly_modulus_degree):")
println(" 1. BFV with default degrees")
println(" 2. BFV with a custom degree")
println(" 3. CKKS with default degrees")
println(" 4. CKKS with a custom degree")
println(" 0. Back to main menu")
selection = 0
println()
print("> Run performance test (1 ~ 4) or go back (0): ")
input = readline()
if !isopen(stdin)
println()
return
end
try
selection = parse(Int, input)
catch
println("Invalid option")
continue
end
if selection == 1
example_bfv_performance_default()
elseif selection == 2
example_bfv_performance_custom()
elseif selection == 3
example_ckks_performance_default()
elseif selection == 4
example_ckks_performance_custom()
elseif selection == 0
println()
return
else
println("Invalid option")
end
end
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 2276 | using SEAL
include("1_bfv_basics.jl")
include("2_encoders.jl")
include("3_levels.jl")
include("4_ckks_basics.jl")
include("5_rotation.jl")
include("6_serialization.jl")
include("7_performance.jl")
function seal_examples()
println("Microsoft SEAL version: ", version())
while true
println("+---------------------------------------------------------+")
println("| The following examples should be executed while reading |")
println("| comments in associated files in examples/. |")
println("+---------------------------------------------------------+")
println("| Examples | Source Files |")
println("+----------------------------+----------------------------+")
println("| 1. BFV Basics | 1_bfv_basics.jl |")
println("| 2. Encoders | 2_encoders.jl |")
println("| 3. Levels | 3_levels.jl |")
println("| 4. CKKS Basics | 4_ckks_basics.jl |")
println("| 5. Rotation | 5_rotation.jl |")
println("| 6. Serialization | 6_serialization.jl |")
println("| 7. Performance Test | 7_performance.jl |")
println("+----------------------------+----------------------------+")
megabytes = alloc_byte_count(memory_manager_get_pool()) >> 20
@printf("[% 7d MB] Total allocation from the memory pool\n", megabytes)
selection = 0
invalid = true
while true
println()
print("> Run example (1 ~ 7) or exit (0): ")
input = readline()
if !isopen(stdin)
return
end
try
selection = parse(Int, input)
break
catch
println(" [Beep~~] Invalid option: type 0 ~ 7")
continue
end
end
if selection == 1
example_bfv_basics()
elseif selection == 2
example_encoders()
elseif selection == 3
example_levels()
elseif selection == 4
example_ckks_basics()
elseif selection == 5
example_rotation()
elseif selection == 6
example_serialization()
elseif selection == 7
example_performance_test()
elseif selection == 0
return
end
end
return
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 3536 | using SEAL
using Printf
function print_example_banner(title)
if isempty(title)
return nothing
end
title_length = length(title)
banner_length = title_length + 2 * 10
banner_border = "+" * "-"^(banner_length - 2) * "+"
banner_center = "|" * " "^9 * title * " "^9 * "|"
println()
println(banner_border)
println(banner_center)
println(banner_border)
end
function print_parameters(context::SEALContext)
context_data = key_context_data(context)
encryption_parms = parms(context_data)
scheme_type = scheme(encryption_parms)
if scheme_type == SchemeType.bfv
scheme_name = "BFV"
elseif scheme_type == SchemeType.ckks
scheme_name = "CKKS"
else
error("unsupported scheme")
end
println("/")
println("| Encryption parameters :")
println("| scheme: ", scheme_name)
println("| poly_modulus_degree: ", poly_modulus_degree(encryption_parms))
print("| coeff_modulus size: ", total_coeff_modulus_bit_count(context_data), " (")
bit_counts = [bit_count(modulus) for modulus in coeff_modulus(encryption_parms)]
print(join(bit_counts, " + "))
println(") bits")
if scheme_type == SchemeType.bfv
println("| plain_modulus: ", value(plain_modulus(encryption_parms)))
end
println("\\")
end
function print_line(line_number)
if line_number < 10
padding = " "
elseif line_number < 100
padding = " "
else
padding = ""
end
print("Line ", padding, line_number, " --> ")
end
function print_vector(vector, print_size=4, prec=3)
slot_count = length(vector)
println()
if slot_count <= 2 * print_size
print(" [ ")
if prec == 7
@printf "%.7f" first(vector)
else
@printf "%.3f" first(vector)
end
for i in 2:slot_count
if prec == 7
@printf ", %.7f" vector[i]
else
@printf ", %.3f" vector[i]
end
end
println(" ]")
else
print(" [ ")
if prec == 7
@printf "%.7f" first(vector)
else
@printf "%.3f" first(vector)
end
for i in 2:print_size
if prec == 7
@printf ", %.7f" vector[i]
else
@printf ", %.3f" vector[i]
end
end
if slot_count > 2 * print_size
print(", ...")
end
for i in (slot_count - print_size + 1):slot_count
if prec == 7
@printf ", %.7f" vector[i]
else
@printf ", %.3f" vector[i]
end
end
println(" ]")
end
println()
end
function print_matrix(matrix, row_size)
print_size = 5
println()
# First row
print(" [")
for i in 1:print_size
@printf("%3d,", matrix[i])
end
print(" ...,")
for i in (row_size - print_size + 1):row_size
if i != row_size
@printf("%3d,", matrix[i])
else
@printf("%3d ]\n", matrix[i])
end
end
# Second row
print(" [")
for i in (row_size + 1):(row_size + print_size)
@printf("%3d,", matrix[i])
end
print(" ...,")
for i in (2 * row_size - print_size + 1):(2 * row_size)
if i != 2 * row_size
@printf("%3d,", matrix[i])
else
@printf("%3d ]\n", matrix[i])
end
end
println()
end
"""
@elapsedus(ex)
Return integer number of elapsed microseconds required for executing `ex`. Modified from
`Base.@elapsed`, which returns the number of seconds as a floating point number.
See also: [`@elapsed`](@ref)
"""
macro elapsedus(ex)
quote
while false; end # compiler heuristic: compile this block (alter this if the heuristic changes)
local t0 = time_ns()
$(esc(ex))
Int(div(time_ns() - t0, 1000))
end
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 3994 | module SEAL
# SEAL_jll provides `libsealc`, which we will use in this package
using SEAL_jll
"""
SEALObject
Abstract parent type for all types based on SEAL classes.
"""
abstract type SEALObject end
"""
gethandle(object::SEALObject)
Return the raw C pointer to where `object` resides in memory.
"""
@inline gethandle(object::SEALObject) = object.handle
"""
sethandle!(object::SEALObject, handle)
Set the underlying raw C pointer to where `object` resides in memory to `handle`.
"""
@inline sethandle!(object::SEALObject, handle) = object.handle = handle
"""
destroy!(object::SEALObject)
Call the corresponding destruction function on `object` to free up memory and reset object handle to
a null pointer. If `object` is not allocated, `destroy!` will not do anything.
"""
function destroy!(object::SEALObject) end
"""
isnull(object::SEALObject)
Return true if the object handle is a null pointer and false otherwise.
"""
@inline isnull(object::SEALObject) = gethandle(object) == C_NULL
"""
isallocated(object::SEALObject)
Return true if the object is allocated, i.e., if it is not null.
"""
@inline isallocated(object::SEALObject) = !isnull(object)
export SEALObject, gethandle, sethandle!, destroy!, isnull, isallocated
Base.unsafe_convert(::Type{Ptr{Cvoid}}, object::SEALObject) = gethandle(object)
include("auxiliary.jl")
# Julia-only auxiliary methods -> no exports
include("version.jl")
export version_major, version_minor, version_patch, version
include("modulus.jl")
export Modulus, SecLevelType, bit_count, value, coeff_modulus_create, coeff_modulus_bfv_default
include("serialization.jl")
export ComprModeType, SEALHeader, load_header!
include("encryptionparams.jl")
export EncryptionParameters, SchemeType, poly_modulus_degree,
set_poly_modulus_degree!, set_coeff_modulus!, coeff_modulus,
scheme, plain_modulus, set_plain_modulus!, plain_modulus_batching, parms_id, save!,
save_size, load!
include("context.jl")
export SEALContext, first_parms_id, last_parms_id, get_context_data, key_context_data,
first_context_data, parameter_error_message, using_keyswitching
export ContextData, chain_index, parms, parms_id, total_coeff_modulus_bit_count, qualifiers,
next_context_data
export EncryptionParameterQualifiers, using_batching
include("publickey.jl")
export PublicKey, parms_id
include("secretkey.jl")
export SecretKey, parms_id, save!, load!
include("galoiskeys.jl")
export GaloisKeys, parms_id
include("relinkeys.jl")
export RelinKeys, parms_id, save_size, save!, load!
include("keygenerator.jl")
export KeyGenerator, create_public_key!, create_public_key, secret_key, create_relin_keys!,
create_relin_keys, create_galois_keys!
include("plaintext.jl")
export Plaintext, scale, scale!, parms_id, to_string, save_size, save!
include("ciphertext.jl")
export Ciphertext, scale, scale!, parms_id, size, length, save_size, save!, load!, reserve!
include("encryptor.jl")
export Encryptor, set_secret_key!, encrypt!, encrypt_symmetric, encrypt_symmetric!
include("evaluator.jl")
export Evaluator, square!, square_inplace!, relinearize!, relinearize_inplace!, rescale_to_next!,
rescale_to_next_inplace!, multiply_plain!, multiply_plain_inplace!, multiply!,
multiply_inplace!, mod_switch_to!, mod_switch_to_inplace!, mod_switch_to_next!,
mod_switch_to_next_inplace!, add!, add_inplace!, add_plain!, add_plain_inplace!,
rotate_vector!, rotate_vector_inplace!, rotate_rows!, rotate_rows_inplace!,
rotate_columns!, rotate_columns_inplace!, complex_conjugate!, complex_conjugate_inplace!,
negate!, negate_inplace!, sub!, sub_inplace!
include("decryptor.jl")
export Decryptor, decrypt!, invariant_noise_budget
include("ckks.jl")
export CKKSEncoder, slot_count, encode!, decode!
include("batchencoder.jl")
export BatchEncoder, slot_count, encode!, decode!
include("memorymanager.jl")
export MemoryPoolHandle, alloc_byte_count, memory_manager_get_pool
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
|
[
"MIT"
] | 0.4.2 | 6fc3f65aca571c817968def8e74065fc98f6bce4 | code | 1493 |
"""
check_return_value(value, location="")
Check the return value `value` of calls to C bindings of the SEAL library and throw an exception if
there were errors. `location` can be used to pass information about were the error occurred and will
be printed as well.
See also: [`@check_return_value`](@ref)
"""
function check_return_value(value, location="")
if isempty(location)
loc = ""
else
loc = " at $location"
end
if value == 0
return true
elseif value == 0x80004003
error("invalid pointer/null pointer error in SEAL function (E_POINTER)", loc)
elseif value == 0x80070057
error("invalid argument error (E_INVALIDARG)", loc)
elseif value == 0x8007000E
error("out of memory error in SEAL function (E_OUTOFMEMORY)", loc)
elseif value == 0x8000FFFF
error("unexpected error in SEAL function (E_UNEXPECTED)", loc)
elseif value == 0x80131620
error("I/O error in SEAL function (COR_E_IO)", loc)
elseif value == 0x80131509
error("invalid operation error in SEAL function (COR_E_INVALIDOPERATION)", loc)
else
error("unknown error", loc)
end
end
"""
@check_return_value value
Call `check_return_value(value, location)` with `location` being a string of the format
`<filename>:<line_number>`.
See also: [`check_return_value`](@ref)
"""
macro check_return_value(value)
return quote
check_return_value($(esc(value)),
join([$(string(__source__.file)), $(string(__source__.line))], ":"))
end
end
| SEAL | https://github.com/JuliaCrypto/SEAL.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.