licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
5965
# UniqueKronecker.jl <div align="center"> <picture> <img alt="logo" src="docs/src/assets/logo.png" width="250" height="250"> </picture> </div> <div align="center"> [![Powered by ACE Lab](https://img.shields.io/badge/powered%20by-ACE%20Lab-pink)](https://sites.google.com/view/elizabeth-qian/research/ace-group) [![CI](https://github.com/smallpondtom/UniqueKronecker.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/smallpondtom/UniqueKronecker.jl/actions/workflows/CI.yml) [![codecov](https://codecov.io/gh/smallpondtom/UniqueKronecker.jl/graph/badge.svg?token=30U7MIN4RM)](https://codecov.io/gh/smallpondtom/UniqueKronecker.jl) [![Doc](https://img.shields.io/badge/docs-stable-blue.svg)](https://smallpondtom.github.io/UniqueKronecker.jl/stable) [![Doc](https://img.shields.io/badge/docs-dev-green.svg)](https://smallpondtom.github.io/UniqueKronecker.jl/dev) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) </div> ## Overview **UniqueKronecker.jl** is a Julia package for computing non-redundant (unique) Kronecker products of vectors, generalizing to _n_ dimensions and _k_-repeated products. It provides utility functions to work with the associated coefficient matrices, enabling conversions between unique Kronecker products and their standard (possibly redundant) Kronecker counterparts. ### What is the Unique Kronecker Product? The standard Kronecker product of a vector $x \in \mathbb{R}^n$ with itself, $\text{kron}(x, x) = x \otimes x$, produces all possible pairwise products of its elements, resulting in redundant terms when $x_i x_j = x_j x_i$. The **unique Kronecker product**, denoted here as $x^{\langle k \rangle} = x \oslash x$, eliminates these redundancies by considering only unique combinations of indices. For example: For $\mathbf{x} \in \mathbb{R}^2$: - **Standard Kronecker product**: $$ \mathbf{x} \otimes \mathbf{x} = \begin{bmatrix} x_1^2 \\ x_1 x_2 \\ x_2 x_1 \\ x_2^2 \end{bmatrix} $$ - **Unique Kronecker product**: $$ \mathbf{x} \oslash \mathbf{x} = \begin{bmatrix} x_1^2 \\ x_1 x_2 \\ x_2^2 \end{bmatrix} $$ Here, $x_1 x_2$ and $x_2 x_1$ are considered the same and included only once. ### Coefficient Matrices The package provides functions to compute the associated coefficient matrices: - **Polynomial Matrix $\mathbf{A}_{2u} \in \mathbb{R}^{n \times \frac{n(n+1)}{2}}$**: Represents the mapping of the unique Kronecker product back to the original vector $x\in\mathbb{R}^2$. - **Kronecker Coefficient Matrix $\mathbf{A}_2 \in \mathbb{R}^{n \times n^2}$**: Relates the unique Kronecker product to the standard Kronecker product, including coefficients for redundant terms. These matrices are useful for applications in polynomial regression, symmetric tensor computations, and vectorization of symmetric matrices. ## Features - Compute the unique Kronecker product for vectors of any dimension $n$ and any repeated (Kronecker) order $k$. - Generate the associated polynomial and Kronecker coefficient matrices $\mathbf{A}_{2u}$ and $\mathbf{A}_2$. - Convert between unique and standard Kronecker products. - Utility functions for polynomial modeling and symmetric tensor operations. ## Installation You can install it using the command ```julia using Pkg Pkg.add("UniqueKronecker") using UniqueKronecker ``` or install it directly from GitHub: ```julia using Pkg Pkg.add(url="https://github.com/YourUsername/UniqueKronecker.jl") ``` Replace `YourUsername` with the actual GitHub username or organization where the package is hosted. ## Usage ### Importing the Package ```julia using UniqueKronecker ``` ### Computing the Unique Kronecker Product Compute the $k$-th order unique Kronecker product of vector `x`: ```julia x = [2.0, 3.0, 4.0] # Example vector in ℝ³ x_unique_kron = x ⊘ x println(x_unique_kron) # Output: [4.0, 6.0, 8.0, 9.0, 12.0, 16.0] # Corresponding to [x₁², x₁x₂, x₁x₃, x₂², x₂x₃, x₃²] ``` ### Computing Coefficient Matrices #### Polynomial Matrix $H$ Compute the polynomial coefficient matrix $H$: ```julia n = 3 H = zeros(n,n^2) for i in 1:n x = rand(n) H[i,:] = kron(x,x) end println(H) # Output: A matrix of size (3, 9) for this example ``` #### Unique/Nonredundant Polynomial Coefficient Matrix $F$ Convert the polynomial matrix $H$ into the unique polynomial coefficient matrix $F$: ```julia F = eliminate(H, 2) println(F) # Output: A matrix of size (3, 6) for this example ``` This can be converted back ```julia H = duplicate(F, 2) println(H) # Output: the H matrix ``` To make the coefficients symmetric for redundant terms use `duplicate_symmetric` ```julia Hs = duplicate_symmetric(F, 2) println(Hs) # Output: the H matrix with symmetric coefficients ``` ### Relationship Between Matrices The following relationship holds: $$ F \cdot (x \oslash x) = H \cdot (x \otimes x) $$ This allows mapping between the unique Kronecker product space and the standard Kronecker product space. ### Generalizing to Higher-Order Products Compute higher-order unique Kronecker products by specifying a higher value of $k$: ```julia k = 3 # Third-order product x_unique_kron_k3 = unique_kronecker(x, k) # or ⊘(x,k) println(x_unique_kron_k3) # Output: Corresponding unique products of order 3 ``` ## Applications - **Polynomial Regression**: Efficient computation of polynomial features without redundant terms. - **Symmetric Tensor Computations**: Simplifies operations involving symmetric tensors. - **Statistical Modeling**: Construction of design matrices with interaction terms. - **Machine Learning**: Feature engineering for higher-order interactions. ## Contributing Contributions are welcome! If you find a bug or have a feature request, please open an issue. If you'd like to contribute code, feel free to submit a pull request. ## License This project is licensed under the [MIT License](https://github.com/smallpondtom/UniqueKronecker.jl/blob/main/LICENSE).
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
234
```@meta CurrentModule = UniqueKronecker ``` ```@contents Pages = ["api.md"] ``` # API All APIs of UniqueKronecker listed in a unstructured manner. ```@autodocs Modules = [UniqueKronecker] Order = [:module, :function, :macro] ```
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
5046
# UniqueKronecker.jl **UniqueKronecker.jl** is a Julia package for computing non-redundant (unique) Kronecker products of vectors, generalizing to _n_ dimensions and _k_-repeated products. It provides utility functions to work with the associated coefficient matrices, enabling conversions between unique Kronecker products and their standard (possibly redundant) Kronecker counterparts. ### What is the Unique Kronecker Product? The standard Kronecker product of a vector ``x \in \mathbb{R}^n`` with itself, ``\text{kron}(x, x) = x \otimes x``, produces all possible pairwise products of its elements, resulting in redundant terms when ``x_i x_j = x_j x_i``. The **unique Kronecker product**, denoted here as ``x^{\langle k \rangle} = x \oslash x``, eliminates these redundancies by considering only unique combinations of indices. For example: For ``\mathbf{x} \in \mathbb{R}^2``: - **Standard Kronecker product**: ```math \mathbf{x} \otimes \mathbf{x} = \begin{bmatrix} x_1^2 \\ x_1 x_2 \\ x_2 x_1 \\ x_2^2 \end{bmatrix} ``` - **Unique Kronecker product**: ```math \mathbf{x} \oslash \mathbf{x} = \begin{bmatrix} x_1^2 \\ x_1 x_2 \\ x_2^2 \end{bmatrix} ``` Here, ``x_1 x_2`` and ``x_2 x_1`` are considered the same and included only once. ### Coefficient Matrices The package provides functions to compute the associated coefficient matrices: - **Polynomial Matrix ``\mathbf{A}_{2u} \in \mathbb{R}^{n \times \frac{n(n+1)}{2}}``**: Represents the mapping of the unique Kronecker product back to the original vector ``x\in\mathbb{R}^2``. - **Kronecker Coefficient Matrix ``\mathbf{A}_2 \in \mathbb{R}^{n \times n^2}``**: Relates the unique Kronecker product to the standard Kronecker product, including coefficients for redundant terms. These matrices are useful for applications in polynomial regression, symmetric tensor computations, and vectorization of symmetric matrices. ## Features - Compute the unique Kronecker product for vectors of any dimension ``n`` and any repeated (Kronecker) order ``k``. - Generate the associated polynomial and Kronecker coefficient matrices ``\mathbf{A}_{2u}`` and ``\mathbf{A}_2``. - Convert between unique and standard Kronecker products. - Utility functions for polynomial modeling and symmetric tensor operations. ## Installation You can install it using the command ```julia using Pkg Pkg.add("UniqueKronecker") using UniqueKronecker ``` or install it directly from GitHub: ```julia using Pkg Pkg.add(url="https://github.com/YourUsername/UniqueKronecker.jl") ``` Replace `YourUsername` with the actual GitHub username or organization where the package is hosted. ## Usage ### Importing the Package ```julia using UniqueKronecker ``` ### Computing the Unique Kronecker Product Compute the ``k``-th order unique Kronecker product of vector `x`: ```julia x = [2.0, 3.0, 4.0] # Example vector in ℝ³ x_unique_kron = x ⊘ x println(x_unique_kron) # Output: [4.0, 6.0, 8.0, 9.0, 12.0, 16.0] # Corresponding to [x₁², x₁x₂, x₁x₃, x₂², x₂x₃, x₃²] ``` ### Computing Coefficient Matrices #### Polynomial Matrix ``H`` Compute the polynomial coefficient matrix ``H``: ```julia n = 3 H = zeros(n,n^2) for i in 1:n x = rand(n) H[i,:] = kron(x,x) end println(H) # Output: A matrix of size (3, 9) for this example ``` #### Unique/Nonredundant Polynomial Coefficient Matrix ``F`` Convert the polynomial matrix ``H`` into the unique polynomial coefficient matrix ``F``: ```julia F = eliminate(H, 2) println(F) # Output: A matrix of size (3, 6) for this example ``` This can be converted back ```julia H = duplicate(F, 2) println(H) # Output: the H matrix ``` To make the coefficients symmetric for redundant terms use `duplicate_symmetric` ```julia Hs = duplicate_symmetric(F, 2) println(Hs) # Output: the H matrix with symmetric coefficients ``` ### Relationship Between Matrices The following relationship holds: ```math F \cdot (x \oslash x) = H \cdot (x \otimes x) ``` This allows mapping between the unique Kronecker product space and the standard Kronecker product space. ### Generalizing to Higher-Order Products Compute higher-order unique Kronecker products by specifying a higher value of ``k``: ```julia k = 3 # Third-order product x_unique_kron_k3 = unique_kronecker(x, k) # or ⊘(x,k) println(x_unique_kron_k3) # Output: Corresponding unique products of order 3 ``` ## Applications - **Polynomial Regression**: Efficient computation of polynomial features without redundant terms. - **Symmetric Tensor Computations**: Simplifies operations involving symmetric tensors. - **Statistical Modeling**: Construction of design matrices with interaction terms. - **Machine Learning**: Feature engineering for higher-order interactions. ## Contributing Contributions are welcome! If you find a bug or have a feature request, please open an issue. If you'd like to contribute code, feel free to submit a pull request. ## License This project is licensed under the [MIT License](https://github.com/smallpondtom/UniqueKronecker.jl/blob/main/LICENSE).
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
93
# Paper Below you have a list of publications referenced in this work. ```@bibliography ```
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
5891
# Circulant Kronecker Product The **Circulant Kronecker Product** is a generalized operation that extends the standard Kronecker product by summing over all cyclic permutations of the given vectors or matrices. This operation can be applied to any number of vectors or matrices. ## Mathematical Definition Given a sequence of vectors or matrices $\mathbf{x}_1, \mathbf{x}_2, \dots, \mathbf{x}_n$, the circulant Kronecker product is defined as: ```math \mathbf{x}_1 \circledast \mathbf{x}_2 \circledast \dots \circledast \mathbf{x}_n = \sum_{k=0}^{n-1} \mathbf{x}_{1+k} \otimes \mathbf{x}_{2+k} \otimes \dots \otimes \mathbf{x}_{n+k} ``` where the indices are taken modulo $n$, i.e., $\mathbf{x}_{i+n} = \mathbf{x}_i$. ## Implementation ### Function `circulant_kronecker` ```@repl using UniqueKronecker x = [1, 2]; y = [3, 4]; z = [5, 6]; circulant_kronecker(x, y, z) ``` ```@docs circulant_kronecker ``` ### Operator `⊛` #### Example 1: Two Vectors ```@repl using UniqueKronecker x = [1, 2] y = [3, 4] x ⊛ y ``` Explanation: - The circulant Kronecker product for two vectors is: ```math \mathbf{x} \circledast \mathbf{y} = \mathbf{x} \otimes \mathbf{y} + \mathbf{y} \otimes \mathbf{x} ``` - Computation: ```julia x ⊗ y = [1*3, 1*4, 2*3, 2*4] = [3, 4, 6, 8] y ⊗ x = [3*1, 3*2, 4*1, 4*2] = [3, 6, 4, 8] Sum: [3+3, 4+6, 6+4, 8+8] = [6, 10, 10, 16] ``` Note: The output `[6, 10, 10, 16]` is the sum of the Kronecker products in this case. #### Example 2: Three Vectors ```@repl using UniqueKronecker x = [1, 2] y = [3, 4] z = [5, 6] ⊛(x, y, z) ``` Explanation: - The circulant Kronecker product for three vectors is: ```math \mathbf{x} \circledast \mathbf{y} \circledast \mathbf{z} = \mathbf{x} \otimes \mathbf{y} \otimes \mathbf{z} + \mathbf{y} \otimes \mathbf{z} \otimes \mathbf{x} + \mathbf{z} \otimes \mathbf{x} \otimes \mathbf{y} ``` - Computation involves computing each Kronecker product and summing the results. #### Example 3: Matrices ```@repl using UniqueKronecker A = [1 2; 3 4]; B = [5 6; 7 8]; C = [9 10; 11 12]; result = ⊛(A, B, C) ``` ## Generalization With this implementation, you can now use the ⊛ operator or `circulant_kronecker` function with any number of vectors or matrices. The operation will automatically handle the necessary cyclic permutations and compute the sum of their Kronecker products. ## Columnwise Operation on Snapshot Matrices Using the function `circulant_kron_snapshot_matrix`, the circulant Kronecker product operation can be applied to construct a snapshot matrix with each column containing the circulant Kronecker product result computed from each column of the input matrices. ### Example ```@repl using UniqueKronecker X1 = [1 2; 3 4] X2 = [5 6; 7 8] X3 = [9 10; 11 12] X = circulant_kron_snapshot_matrix(X1, X2, X3) ``` ```@docs circulant_kron_snapshot_matrix ``` ## Derivative of Kronecker products This circulant Kronecker product is useful because it is a well-known result that the derivative of Kronecker products hold the circulant Kronecker structure. For example, if $\mathbf{x}\in\mathbb{R}^2$ then ```math \frac{\partial}{\partial \mathbf{x}}(\mathbf{x} \otimes \mathbf{x}) = \mathbf{I}_2 \otimes \mathbf{x} + \mathbf{x} \otimes \mathbf{I}_2 ``` and ```math \frac{\partial}{\partial \mathbf{x}}(\mathbf{x} \otimes \mathbf{x} \otimes \mathbf{x}) = \mathbf{I}_2 \otimes \mathbf{x} \otimes \mathbf{x} + \mathbf{x} \otimes \mathbf{I}_2 \otimes \mathbf{x} + \mathbf{x} \otimes \mathbf{x} \otimes \mathbf{I}_2 ``` which can be reformulated using the circulant Kronecker product as, e.g., ```math \frac{\partial}{\partial \mathbf{x}}(\mathbf{x} \otimes \mathbf{x}) = \mathbf{I}_2 \circledast \mathbf{x} ``` ## Symmetry and Conversion using Elimination and Duplication Matrices The circulant Kronecker product inherently captures the symmetric structure present in Kronecker products involving permutations of vectors or matrices. This symmetry can be leveraged to simplify computations, reduce redundancy, and improve efficiency in mathematical operations, particularly when dealing with higher-order tensors or polynomial systems. ### Role of Elimination and Duplication Matrices When working with circulant Kronecker products, especially in the context of symmetric tensors or polynomial dynamical systems, you may need to convert between the full Kronecker product and its unique representation. #### From Full Kronecker Product to Unique Representation 1. **Compute the Full Circulant Kronecker Product**: Use the `circulant_kronecker` function to compute the sum over all cyclic permutations. 2. **Apply the Elimination Matrix**: Multiply the result by the elimination matrix $\mathbf{L}_{n,k}$ to extract the unique elements. ```math \text{Unique Elements} = \mathbf{L}_{n,k} \left( \mathbf{x}_1 \circledast \mathbf{x}_2 \circledast \dots \circledast \mathbf{x}_n \right) ``` #### From Unique Representation to Full Kronecker Product 1. **Start with Unique Elements**: Obtain the vector containing the unique monomials. 2. **Apply the Duplication Matrix**: Multiply the unique elements by the duplication matrix $\mathbf{D}_{n,k}$ to reconstruct the full symmetric tensor. ```math \text{Full Kronecker Product} = \mathbf{D}_{n,k} \times \text{Unique Elements} ``` ##### Example Consider vectors $\mathbf{x}, \mathbf{y} \in \mathbb{R}^2$: 1. **Compute the Circulant Kronecker Product**: ```math \mathbf{x} \circledast \mathbf{y} = \mathbf{x} \otimes \mathbf{y} + \mathbf{y} \otimes \mathbf{x} ``` 2. **Apply the Elimination Matrix**: - Use the elimination matrix $\mathbf{L}_{2,2}$ to extract unique terms: ```math \text{Unique Elements} = \mathbf{L}_{2,2} (\mathbf{x} \circledast \mathbf{y}) ``` 3. **Result**: - The unique elements correspond to the monomials $x_1 y_1$, $x_1 y_2 + x_2 y_1$, and $x_2 y_2$.
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
3455
# Commutation Matrix The commutation matrix $\mathbf{K}$ is a special permutation matrix that rearranges the vectorization of matrices and interchanges the Kronecker products of vectors and matrices. It plays a crucial role in simplifying expressions involving vectorization and Kronecker products in linear algebra, control theory, and other mathematical fields. ## Definition The **Commutation Matrix** $\mathbf{K}_{m,n} \in \mathbb{R}^{mn \times mn}$ is defined as: ```math \mathbf{K}_{m,n} = \sum_{i=1}^m \sum_{j=1}^n \mathbf{E}_{ij} \otimes \mathbf{E}_{ji} ``` where $\mathbf{E}_{ij}$ is the elementary matrix of size $m \times n$ with a one in the $(i, j)$-th position and zeros elsewhere. **Properties of the Commutation Matrix:** 1. **Vectorization Transposition:** For any matrix $\mathbf{A} \in \mathbb{R}^{m \times n}$: ```math \mathbf{K}_{m,n} \operatorname{vec}(\mathbf{A}) = \operatorname{vec}(\mathbf{A}^\top) ``` This property states that the commutation matrix transforms the vectorization of a matrix into the vectorization of its transpose. 2. **Kronecker Product Permutation:** For matrices $\mathbf{A} \in \mathbb{R}^{m \times n}$ and $\mathbf{B} \in \mathbb{R}^{p \times q}$: ```math \mathbf{K}_{p m, n q} (\mathbf{A} \otimes \mathbf{B}) \mathbf{K}_{n, q} = \mathbf{B} \otimes \mathbf{A} ``` This property allows interchanging matrices within a Kronecker product. 3. **Vector Kronecker Product Permutation:** For vectors $\mathbf{v} \in \mathbb{R}^m$ and $\mathbf{w} \in \mathbb{R}^n$: ```math \mathbf{K}_{n,m} (\mathbf{v} \otimes \mathbf{w}) = \mathbf{w} \otimes \mathbf{v} ``` This property enables swapping vectors within a Kronecker product. **Additional Properties:** - **Symmetry:** $\mathbf{K}_{n,m} = \mathbf{K}_{m,n}^\top$. - **Involution:** $\mathbf{K}_{m,n} \mathbf{K}_{n,m} = \mathbf{I}_{mn}$, where $\mathbf{I}_{mn}$ is the identity matrix of size $mn \times mn$. - **Eigenvalues:** The eigenvalues of $\mathbf{K}_{m,n}$ are either $+1$ or $-1$. ## Use Cases The commutation matrix is particularly useful in the following contexts: 1. **Rearranging Kronecker Products:** The commutation matrix allows us to move matrices or vectors within Kronecker products. For example: ```math \mathbf{K}_{n,n^2} (\mathbf{A} \mathbf{x} \otimes \mathbf{x} \otimes \mathbf{x}) = \mathbf{x} \otimes \mathbf{A} \mathbf{x} \otimes \mathbf{x} ``` ```math \mathbf{K}_{n^2,n} (\mathbf{A} \mathbf{x} \otimes \mathbf{x} \otimes \mathbf{x}) = \mathbf{x} \otimes \mathbf{x} \otimes \mathbf{A} \mathbf{x} ``` Here, $\mathbf{x} \in \mathbb{R}^n$ and $\mathbf{A} \in \mathbb{R}^{n \times n}$. 2. **Simplifying Vectorized Equations:** In mathematical modeling, especially in statistics and econometrics, the commutation matrix simplifies expressions involving vectorized matrices. 3. **Matrix Derivatives:** It is used in deriving matrix derivatives where the order of differentiation and vectorization matters. 4. **Permutation of Tensor Products:** In higher-order tensor computations, the commutation matrix helps in permuting indices. 5. **Construct second-order symmetrizer matrix** For the second-order Kronecker product, the symmetrizer matrix is defined by ```math \mathbf{S}_2 = \frac{1}{2}(\mathbf{I}_{n^2} + \mathbf{K}_{n,n}) ``` See more details on the [symmetrizer matrix](symmetrizer.md). ```@docs commat ```
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
5242
# Duplication Matrix In the second-order Kronecker product sense, the duplication matrix $\mathbf{D}$ is a matrix that transforms a vector containing only the unique elements of a symmetric matrix (vectorized in half-vectorization form) into the full vectorization of the symmetric matrix, effectively duplicating the symmetric elements to their appropriate positions. It plays a crucial role in manipulating Kronecker products and converting between non-redundant and redundant polynomial operators in polynomial dynamical systems. ## Definition The duplication matrix $\mathbf{D}_n$ is a unique matrix of size $\left(n^2 \times \tfrac{n(n+1)}{2}\right)$ defined such that for any symmetric matrix $\mathbf{S} \in \mathbb{R}^{n \times n}$: ```math \mathrm{vec}(\mathbf{S}) = \mathbf{D}_n \mathrm{vech}(\mathbf{S}) ``` where: (1) $\mathrm{vec}(\mathbf{S})$ stacks all columns of $\mathbf{S}$ into a single vector of length $n^2$; (2) $\mathrm{vech}(\mathbf{S})$ stacks only the elements on and below (or above) the main diagonal into a vector of length $\tfrac{n(n+1)}{2}$. The duplication matrix effectively "duplicates" the unique elements in $\mathrm{vech}(\mathbf{S})$ to fill the positions in $\mathrm{vec}(\mathbf{S})$ that correspond to symmetric entries. **Properties of the Duplication Matrix:** - **Construction:** Each column of $\mathbf{D}_n$ contains ones at positions corresponding to the symmetric elements in $\operatorname{vec}(\mathbf{S})$ and zeros elsewhere. - **Relation to Elimination Matrix:** The duplication matrix is related to the elimination matrix $\mathbf{L}_n$ via: ```math \mathbf{L}_n\mathbf{D}_n = \mathbf{I}_n ``` for more definitions see [MagnusEML1980](@citet). !!! note Similar to the elimination matrix, this matrix is not formally/mathematically generalized for higher-order Kronecker products in the literature. ## Converting Between Kronecker Products In polynomial dynamical systems, Kronecker powers of vectors often involve redundancy due to symmetric terms. The duplication matrix facilitates the conversion from the unique Kronecker product vector to the standard Kronecker product vector. **Unique Kronecker Power:** Given a vector $\mathbf{x} \in \mathbb{R}^n$, the unique Kronecker power is: ```math \mathbf{x}^{\langle k \rangle} \in \mathbb{R}^{\tbinom{n + k - 1}{k}} ``` which contains only the unique monomials of degree $k$. **Standard Kronecker Power:** The standard Kronecker power is: ```math \mathbf{x}^{[k]} = \underbrace{\mathbf{x} \otimes \mathbf{x} \otimes \cdots \otimes \mathbf{x}}_{k \text{ times}} \in \mathbb{R}^{n^k} ``` which includes all possible combinations, including redundant terms. **Conversion Using the Duplication Matrix:** The duplication matrix $\mathbf{D}_{n,k}$ of order $k$ is used to expand the unique Kronecker power to the standard Kronecker power: ```math \mathbf{x}^{[k]} = \mathbf{D}_{n,k} \mathbf{x}^{\langle k \rangle} ``` Here, $\mathbf{D}_{n,k}$ is a matrix of size $\left(n^k \times \tbinom{n + k - 1}{k}\right)$. **Example:** For $n = 2$ and $k = 2$, let $\mathbf{x} = [x_1, x_2]^\top$. Then: - **Unique Kronecker Power:** ```math \mathbf{x}^{\langle 2 \rangle} = [x_1^2, x_1 x_2, x_2^2]^\top ``` - **Standard Kronecker Power:** ```math \mathbf{x}^{[2]} = [x_1^2, x_1 x_2, x_2 x_1, x_2^2]^\top ``` The duplication matrix $\mathbf{D}_{2,2}$ duplicates the mixed term $x_1 x_2$ to account for both $x_1 x_2$ and $x_2 x_1$ in the standard Kronecker power: ```math \mathbf{x}^{[2]} = \mathbf{D}_{2,2} \mathbf{x}^{\langle 2 \rangle} ``` **Note on Julia Implementation:** The Julia function `dupmat(n::Int, p::Int)` generates the duplication matrix of order `p` for vectors of length `n`. This function can be used to create the duplication matrix needed for converting unique Kronecker products to standard ones. ```@docs dupmat ``` **Benefits:** - **Expands Unique Terms:** Allows reconstruction of the full Kronecker power from the unique monomials. - **Simplifies Computations:** Facilitates operations that require the full Kronecker power. ## Converting Between Operators The duplication matrix is also instrumental in converting between non-redundant (unique) and redundant polynomial operators in dynamical systems. **Unique Operators:** In the polynomial dynamical system: ```math \dot{\mathbf{x}}(t) = \mathbf{A} \mathbf{x}(t) + \mathbf{A}_{2u} \mathbf{x}^{\langle 2 \rangle}(t) + \mathbf{A}_{3u} \mathbf{x}^{\langle 3 \rangle}(t) + \cdots ``` the matrices $\mathbf{A}_{ku} \in \mathbb{R}^{n \times \tbinom{n + k - 1}{k}}$ operate on the unique Kronecker powers. **Redundant Operators:** Alternatively, using the standard Kronecker powers: ```math \dot{\mathbf{x}}(t) = \mathbf{A} \mathbf{x}(t) + \mathbf{A}_2 \mathbf{x}^{[2]}(t) + \mathbf{A}_3 \mathbf{x}^{[3]}(t) + \cdots ``` with $\mathbf{A}_k \in \mathbb{R}^{n \times n^k}$. **Conversion Using the Duplication Matrix:** The unique operator $\mathbf{A}_{ku}$ and the redundant operator $\mathbf{A}_k$ are related through the duplication matrix: ```math \mathbf{A}_{ku} = \mathbf{A}_{k} \mathbf{D}_{n,k} ``` which eliminates the redundant terms. ```@docs eliminate ```
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
6667
# Polynomial Dynamical System The main use case of the unique Kronecker product is in a polynomial structured dynamical systems defined by ```math \dot{\mathbf{x}}(t) = \mathbf{A}\mathbf{x}(t) + \mathbf{A}_2\mathbf{x}^{[2]}(t) + \mathbf{A}_3\mathbf{x}^{[3]}(t) + \cdots ``` where $\mathbf{x}$ is the system variable and $\mathbf{A}_2\in\mathbb{R}^{n\times n^2}$, $\mathbf{A}_3\in\mathbb{R}^{n^3}$ are the system matrices/operators. This can be represented using the unique Kronecker product as ```math \dot{\mathbf{x}}(t) = \mathbf{A}\mathbf{x}(t) + \mathbf{A}_{2u}\mathbf{x}^{\langle 2 \rangle}(t) + \mathbf{A}_{3u}\mathbf{x}^{\langle 3 \rangle}(t) + \cdots ``` where $\mathbf{A}_{2u}\in\mathbb{R}^{n(n+1)/2}$ and $\mathbf{A}_{3u}\in\mathbb{R}^{n(n+1)(n+2)/6}$. This package is also dedicated to converting between the unique operators $\mathbf{A}_{2u},~\mathbf{A}_{3u}$ and non-unique operators $\mathbf{A}_2,~\mathbf{A}_3$. # Creating the Polynomial Operators This packages offers a built-in function that allows the construction of redundant and non-redundant polynomial operators generalized for the dimension of the system variable and order of the Kronecker product. This function is called `makePolyOp` which easily creates the matrices by accepting the indices and values as arguments. ```@docs makePolyOp ``` # Example Here we show some famous systems which possess the polynomial structure: ## Van der Pol Oscillator The Van der Pol oscillator is a nonlinear system that exhibits self-sustained oscillations with non-constant amplitude and frequency. It is governed by the second-order differential equation: ```math \ddot{x} - \mu (1 - x^2) \dot{x} + x = 0 ``` where $x$ is the state variable and $\mu$ is a scalar parameter representing the nonlinearity and damping of the system. To express this as a first-order system suitable for the polynomial dynamical system framework, we define the state vector $\mathbf{x} = [x_1, x_2]^T$, where $x_1 = x$ and $x_2 = \dot{x}$. The system then becomes: ```math \begin{aligned} \dot{x}_1 &= x_2 \\ \dot{x}_2 &= \mu (1 - x_1^2) x_2 - x_1 \end{aligned} ``` This can be rewritten in matrix form as: ```math \dot{\mathbf{x}} = \mathbf{A} \mathbf{x} + \mathbf{A}_{3u} \mathbf{x}^{\langle 3 \rangle} ``` Here, the matrices are defined as: - Linear term: ```math \mathbf{A} = \begin{bmatrix} 0 & 1 \\ -1 & \mu \end{bmatrix} ``` - Cubic term: ```math \mathbf{A}_{3u} = \begin{bmatrix} 0 & 0 & 0 & 0 \\ 0 & -\mu & 0 & 0 \end{bmatrix} ``` The cubic term arises from the $- \mu x_1^2 x_2$ component, which can be represented using the unique Kronecker product: ```math \mathbf{x}^{\langle 3 \rangle} = [x_1^3,~x_1^2 x_2, ~x_1 x_2^2, ~x_2^3]^\top ``` Thus, the Van der Pol oscillator fits into the polynomial dynamical system framework by capturing its nonlinear dynamics through the unique Kronecker product, facilitating analysis and simulation. !!! tip `UniqueKronecker.jl` provides a convenient function to construct the polynomial operators called `makePolyOp`. For example, you can construct the (redundant) cubic operator using the following command: ```@repl using UniqueKronecker: makePolyOp μ = 1.0 A3 = makePolyOp(2, [(1,1,2,2)], [μ]) ``` ## Lorenz System The Lorenz system is a set of three coupled, nonlinear differential equations originally developed to model atmospheric convection. It is famous for its chaotic solutions for certain parameter values. The system is given by: ```math \begin{aligned} \dot{x}_1 &= \sigma (x_2 - x_1) \\ \dot{x}_2 &= x_1 (\rho - x_3) - x_2 \\ \dot{x}_3 &= x_1 x_2 - \beta x_3 \end{aligned} ``` where $x_1$, $x_2$, and $x_3$ are the state variables, and $\sigma$, $\rho$, and $\beta$ are parameters. To express the Lorenz system within the polynomial dynamical system framework, we identify the nonlinear terms and represent them using the unique Kronecker product: - Quadratic terms: $x_1 x_2$, $x_1 x_3$ We define the state vector $\mathbf{x} = [x_1, x_2, x_3]^\top$ and compute the unique Kronecker powers: ```math \mathbf{x}^{\langle 2 \rangle} = [x_1^2, ~x_1 x_2, ~x_1 x_3, ~x_2^2, ~x_2 x_3, ~x_3^2]^\top ``` The system can then be represented as: ```math \dot{\mathbf{x}} = \mathbf{A} \mathbf{x} + \mathbf{A}_{2u} \mathbf{x}^{\langle 2 \rangle} ``` Where: - Linear term: ```math \mathbf{A} = \begin{bmatrix} -\sigma & \sigma & 0 \\ \rho & -1 & 0 \\ 0 & 0 & -\beta \end{bmatrix} ``` - Quadratic term: ```math \mathbf{A}_{2u} = \begin{bmatrix} 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & -1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 \end{bmatrix} ``` In this form, the Lorenz system's nonlinear dynamics are captured using the unique Kronecker product, making it amenable to analysis using polynomial system techniques. !!! tip The quadratic operator can be constructed using the `makePolyOp` function as follows: ```@repl using UniqueKronecker: makePolyOp A2 = makePolyOp(3, [(1,3,2), (1,2,3)], [-1, 1]) ``` ## Viscous Burgers' Equation The viscous Burgers' equation is a fundamental partial differential equation from fluid mechanics and nonlinear acoustics. It models various physical processes like gas dynamics and traffic flow. The equation is: ```math \frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} = \nu \frac{\partial^2 u}{\partial x^2} ``` where $u(x, t)$ is the velocity field, and $\nu$ is the viscosity coefficient. To convert this PDE into a finite-dimensional polynomial dynamical system, we discretize the spatial domain using methods like finite differences. Let $\mathbf{u}$ be the vector of discretized values of $u(x, t)$. Assuming periodic boundary condition, the discretized equation becomes: ```math \dot{\mathbf{u}} = \mathbf{A} \mathbf{u} + \mathbf{A}_2 (\mathbf{u} \otimes \mathbf{u}) ``` Here: - the discretized Laplacian operator (diffusion term) is repsented by $\mathbf{A}$. - and the discretized convection operator is $\mathbf{A}_2$ . By rearranging, we can express the nonlinear term using the unique Kronecker product: ```math \dot{\mathbf{u}} = \mathbf{A} \mathbf{u} + \mathbf{A}_{2u} \mathbf{u}^{\langle 2 \rangle} ``` where: ```math \mathbf{u}^{\langle 2 \rangle} = [u_1^2, ~u_1 u_2, ~\dots, ~u_n^2]^\top ``` This formulation allows us to apply polynomial system analysis tools to the viscous Burgers' equation, enabling efficient simulation and control design for systems modeled by this equation.
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
5780
# Elimination Matrix Elimination matrix $\mathbf{L}$, first mentioned by Tracy and Singh (1972) and later by Vetter (1975), was studied in depth by Magnus and Neudecker in [MagnusEML1980](@citet). This matrix holds properties that are crucial to converting the standard Kronecker product vector to the unique Kronecker product vector as well as converting the non-redundant polynomial operators to the redundant operators. ## Definition The elimination matrix $\mathbf{L}_n$ is a unique matrix of size $\left(\tfrac{n(n+1)}{2} \times n^2\right)$ that extracts the unique elements from the vectorization of a symmetric matrix. For any symmetric matrix $\mathbf{S} \in \mathbb{R}^{n \times n}$, the vectorization $\mathrm{vec}(\mathbf{S})$ contains redundant elements due to symmetry. The elimination matrix $\mathbf{L}_n$ is defined such that: ```math \mathrm{vech}(\mathbf{S}) = \mathbf{L}_n \mathrm{vec}(\mathbf{S}) ``` where: - operator $\mathrm{vec}(\mathbf{S})$ stacks all columns of $\mathbf{S}$ into a single vector of length $n^2$. - and $\mathrm{vech}(\mathbf{S})$ stacks only the elements on and below (or above) the main diagonal into a vector of length $\tfrac{n(n+1)}{2}$. The elimination matrix effectively "eliminates" the redundant elements in $\mathrm{vec}(\mathbf{S})$, preserving only the unique components. **Properties of the Elimination Matrix:** - **Idempotency:** $\mathbf{L}_n \mathbf{L}_n^\top$ is an idempotent matrix, meaning $(\mathbf{L}_n \mathbf{L}_n^\top)^2 = \mathbf{L}_n \mathbf{L}_n^\top$. - **Construction:** Each row of $\mathbf{L}_n$ contains a single one and zeros elsewhere, mapping elements from $\mathrm{vec}(\mathbf{S})$ to $\mathrm{vech}(\mathbf{S})$. !!! note Unfortunately, the definition of the elimination matrix is not formally/mathematically defined for Kronecker products beyond the order of 2. However, implementation-wise, this package has generalized the matrix. ## Converting Between Kronecker Products In polynomial dynamical systems, we often deal with Kronecker powers of vectors, which can be redundant due to symmetric terms. The elimination matrix facilitates the conversion between the standard Kronecker product vector and the unique Kronecker product vector. **Standard Kronecker Power:** Given a vector $\mathbf{x} \in \mathbb{R}^n$, the $k$-th order Kronecker power is: ```math \mathbf{x}^{[k]} = \underbrace{\mathbf{x} \otimes \mathbf{x} \otimes \cdots \otimes \mathbf{x}}_{k \text{ times}} \in \mathbb{R}^{n^k} ``` **Unique Kronecker Power:** The unique Kronecker power, denoted by $\mathbf{x}^{\langle k \rangle}$, contains only the unique monomials of degree $k$ formed from the elements of $\mathbf{x}$. It has a length of $\tbinom{n + k - 1}{k}$. **Conversion Using the Elimination Matrix:** The relationship between the standard and unique Kronecker powers is given by: ```math \mathbf{x}^{\langle k \rangle} = \mathbf{L}_{n,k} \mathbf{x}^{[k]} ``` where $\mathbf{L}_{n,k}$ is the elimination matrix corresponding to the $k$-th Kronecker power, of size $\left(\tbinom{n + k - 1}{k} \times n^k\right)$. **Example:** For $n = 2$ and $k = 2$, let $\mathbf{x} = [x_1, x_2]^\top$. Then: - **Standard Kronecker Power:** ```math \mathbf{x}^{[2]} = [x_1^2, x_1 x_2, x_2 x_1, x_2^2]^\top ``` - **Unique Kronecker Power:** ```math \mathbf{x}^{\langle 2 \rangle} = [x_1^2, x_1 x_2, x_2^2]^\top ``` The elimination matrix $\mathbf{L}_{2,2}$ maps $\mathbf{x}^{[2]}$ to $\mathbf{x}^{\langle 2 \rangle}$ by combining redundant terms (since $x_1 x_2$ and $x_2 x_1$ are the same): ```math \mathbf{x}^{\langle 2 \rangle} = \mathbf{L}_{2,2} \mathbf{x}^{[2]} ``` ```@docs elimat ``` **Benefits:** - **Efficiency:** Reduces computational complexity by working with smaller vectors. - **Simplicity:** Simplifies expressions and computations involving symmetric terms. - **Clarity:** Makes the structure of polynomial terms more transparent. ## Converting Between Operators The elimination matrix also plays a crucial role in converting between redundant and non-redundant polynomial operators in dynamical systems. **Redundant Operators:** In the polynomial system: ```math \dot{\mathbf{x}}(t) = \mathbf{A}\mathbf{x}(t) + \mathbf{A}_2 \mathbf{x}^{[2]}(t) + \mathbf{A}_3 \mathbf{x}^{[3]}(t) + \cdots ``` the matrices $\mathbf{A}_k \in \mathbb{R}^{n \times n^k}$ operate on the full Kronecker powers, which include redundant terms. **Unique Operators:** To eliminate redundancy, we define unique operators $\mathbf{A}_{ku} \in \mathbb{R}^{n \times \tbinom{n + k - 1}{k}}$ such that: ```math \dot{\mathbf{x}}(t) = \mathbf{A}\mathbf{x}(t) + \mathbf{A}_{2u} \mathbf{x}^{\langle 2 \rangle}(t) + \mathbf{A}_{3u} \mathbf{x}^{\langle 3 \rangle}(t) + \cdots ``` **Conversion Using the Elimination Matrix:** The redundant operator $\mathbf{A}_k$ and the unique operator $\mathbf{A}_{ku}$ are related through the elimination matrix: ```math \mathbf{A}_{k} = \mathbf{A}_{ku} \mathbf{L}_{n,k} ``` which actually works to duplicate the entries of the non-redundant operator. Thus, though seemingly counter-intuitive, the elimination matrix duplicates the entries and constructs to convert the $\mathbf{A}_2$ matrix to the $\mathbf{A}_{2u}$ matrix. **Example:** Consider a system with $n = 2$: - **Redundant operator:** $\mathbf{A}_2 \in \mathbb{R}^{2 \times 4}$ - **Unique operator:** $\mathbf{A}_{2u} \in \mathbb{R}^{2 \times 3}$ The elimination matrix $\mathbf{L}_{2,2}$ maps $\mathbf{x}^{[2]}$ to $\mathbf{x}^{\langle 2 \rangle}$: ```math \mathbf{x}^{\langle 2 \rangle} = \mathbf{L}_{2,2} \mathbf{x}^{[2]} ``` The operators are related by: ```math \mathbf{A}_{2u} = \mathbf{A}_2 \mathbf{L}_{2,2}^\top ``` ```@docs duplicate ```
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
2830
# Symmetrizer Matrix The symmetrizer matrix $\mathbf{S}$ is a matrix that symmetrizes tensors or higher-order Kronecker products. It ensures that the resulting product is symmetric with respect to its indices. In the context of polynomial dynamical systems and Kronecker products, the symmetrizer matrix is crucial for handling symmetric terms efficiently and accurately. ## Definition The **Symmetrizer Matrix** $\mathbf{S}_{n,p} \in \mathbb{R}^{n^p \times n^p}$ of order $p$ for a vector of length $n$ is defined such that it symmetrizes a tensor obtained from the $p$-th Kronecker power of a vector $\mathbf{x} \in \mathbb{R}^n$. Given the $p$-th Kronecker power: ```math \mathbf{x}^{[p]} = \underbrace{\mathbf{x} \otimes \mathbf{x} \otimes \cdots \otimes \mathbf{x}}_{p \text{ times}} \in \mathbb{R}^{n^p} ``` The symmetrizer matrix $\mathbf{S}_{n,p}$ symmetrizes $\mathbf{x}^{[p]}$ to produce a vector where all permutations of indices are averaged. The symmetrized vector is: ```math \mathbf{x}^{\{p\}} = \mathbf{S}_{n,p} \mathbf{x}^{[p]} ``` **Properties of the Symmetrizer Matrix:** - **Idempotent:** $\mathbf{S}_{n,p}^2 = \mathbf{S}_{n,p}$. - **Symmetric:** $\mathbf{S}_{n,p}^\top = \mathbf{S}_{n,p}$. - **Projection Matrix:** It projects any tensor onto the space of symmetric tensors. For the quadratic case ($p = 2$), the symmetrizer matrix can be explicitly defined using the commutation matrix $\mathbf{K}_{n,n}$: ```math \mathbf{S}_{n,2} = \frac{1}{2} \left( \mathbf{I}_{n^2} + \mathbf{K}_{n,n} \right) ``` where $\mathbf{I}_{n^2}$ is the identity matrix of size $n^2 \times n^2$. ```@docs symmtzrmat ``` ## Use Cases The symmetrizer matrix is particularly useful in the following contexts: 1. **Symmetrizing Kronecker Products:** When dealing with polynomial terms in dynamical systems, it's often necessary to ensure that the terms are symmetric. The symmetrizer matrix averages all permutations of indices in the Kronecker product to produce a symmetric tensor. **Example:** For $\mathbf{x} \in \mathbb{R}^n$ and $p = 2$: ```math \mathbf{x}^{\{2\}} = \mathbf{S}_{n,2} (\mathbf{x} \otimes \mathbf{x}) ``` This results in a vector containing terms like $x_i x_j$ averaged over all permutations. 2. **Ensuring Symmetric Operators:** In polynomial dynamical systems, operators (matrices) that act on Kronecker powers of state vectors should often be symmetric to preserve certain properties like stability. The symmetrizer matrix can be used to enforce symmetry in these operators. 3. **Duplicating Symmetric Coefficients:** When converting between unique and redundant representations of polynomial operators, the symmetrizer matrix ensures that coefficients are duplicated symmetrically, maintaining the symmetry of the operator. ```docs duplicate_symmetric ```
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
3629
# Unique Kronecker Product ## Introduction The unique Kronecker product is a math operation which is similar to the Kronecker product but eliminates all the redundant terms appearing due to terms invariant under index permutations. This is easiest to understand through an example. ```@raw html <img src="../../images/unique_kronecker_example.png" alt="unique kronecker example" style="float: left; margin-right: 10px;" /> ``` The example above shows the unique Kronecker product for a vector of $\mathbf{x}\in\mathbb{R}^3$. For a standard Kronecker product the resulting vector becomes a 9-dimensional vector, and we have a 6-dimensional vector when using the unique Kronecker product. Which shows how the unique Kronecker product eliminates 3 of the redundant terms. ## Definitions We define the basic syntax for the general Kronecker product and unique Kronecker product of order $k$ as follows: ```math \begin{align} \mathbf{x}^{[k]} &= \underbrace{\mathbf{x} \otimes \cdots \otimes \mathbf{x}}_{k-\text{times}} \in \mathbb{R}^{n^k}, \\ \mathbf{x}^{\langle k \rangle} &= \underbrace{\mathbf{x} \oslash \cdots \oslash \mathbf{x}}_{k-\text{times}} \in \mathbb{R}^{\binom{n+k-1}{k}} \end{align} ```math where $\mathbf{x}\in\mathbb{R}^n$. From this definition, we observe that the dimensions of the Kronecker product grows in the order of $n^k$ but the unique Kronecker grows in the order of $\binom{n+k-1}{k}$. The reduction in computational cost from this order difference becomes significantly obvious in higher-dimensions. For a second-order Kronecker product, the package supports the following syntax ```@repl using UniqueKronecker n = 3 x = rand(n) x2u = x ⊘ x # or unique_kronecker(x,x) ``` for higher-order Kronecker products, you can do ```@repl using UniqueKronecker n = 3 k = 5 x = rand(n) xku = ⊘(x, k) ``` Another concept we need to define is the vectorization and half-vectorization operators $\mathrm{vec}(\cdot)$ and $\mathrm{vech}(\cdot)$, respectively. The vectorization operator flattens a matrix $\mathbf{A}\in\mathbb{R}^{m\times n}$ in the column direction creating a vector of size $mn$. On the other hand, the half-vectorization operator vectorizes the matrix but only half of it or discarding the supradiagonal entries. These operations are strongly related to the second-order Kronecker and unique Kronecker products, and those relationships are described in the picture below. ```@raw html <img src="../../images/vectorize_and_kronecker.png" alt="unique kronecker example" style="float: left; margin-right: 10px;" /> ``` The vectorization operator is already defined in the `LinearAlgebra` package as the function `vec`, but we define the functions `vech` for the half-vectorization operator and `invec` function for the inverse-vectorization operator that reverses the vectorization. We are aware that similar concepts exists in the tensor algebra literature, and the vectorization and half-vectorization operations can be generalized to higher-order Kronecker products. However, for ease of exposition, we only illustrate the second-order Kronecker product case. ## Columnwise Operation on Snapshot Matrices We also employ the functions - `kron_snapshot_matrix` - `unique_kron_snapshot_matrix` which allows you to apply the Kronecker product and unique Kronecker product on each column of a matrix. For example ```@repl using UniqueKronecker X = [1 2; 3 4] X2 = kron_snapshot_matrix(X, 2) ``` ```@repl using UniqueKronecker X = [1 2; 3 4] X2u = unique_kron_snapshot_matrix(X, 2) ``` ```@docs unique_kronecker ⊘ kron_snapshot_matrix unique_kron_snapshot_matrix ```
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.1.0
6e0e59cf030ff08603780c7595a52748e1e68014
docs
3098
# Unique Kronecker Powers One unique feature of this package is the generalization of the unique Kronecker product for any *n*-dimensional vector with any Kronecker product of order *k*. This allows significant computational efficiency in higher-order polynomial systems. ## Definition The **unique Kronecker power** of order $k$ of a vector $\mathbf{x} \in \mathbb{R}^n$, denoted by $\mathbf{x}^{\langle k \rangle}$, is a vector containing all the unique monomials of degree $k$ formed by the elements of $\mathbf{x}$. Unlike the standard Kronecker power $\mathbf{x}^{[k]}$, which includes all possible combinations (including duplicates due to commutativity), the unique Kronecker power includes each distinct monomial only once. Formally, the unique Kronecker power is defined as: ```math \mathbf{x}^{\langle k \rangle} = \mathrm{vec}_{\text{unique}} \left( \mathbf{x}^{[k]} \right) \in \mathbb{R}^{\tbinom{n + k - 1}{k}} ``` where: - the term $\mathbf{x}^{[k]} = \underbrace{\mathbf{x} \otimes \mathbf{x} \otimes \cdots \otimes \mathbf{x}}_{k \text{ times}}$ is the $k$-th Kronecker power of $\mathbf{x}$. - and $\mathrm{vec}_{\text{unique}}$ extracts only the unique monomials, considering that the variables commute (e.g., $x_i x_j = x_j x_i$). The length of $\mathbf{x}^{\langle k \rangle}$ is given by the multiset coefficient (number of combinations with repetition): ```math \mathrm{length}(\mathbf{x}^{\langle k \rangle}) = \tbinom{n + k - 1}{k} ``` ## Properties - **Efficiency:** By considering only unique monomials, the unique Kronecker power significantly reduces the dimensionality compared to the standard Kronecker power, which has length $n^k$. - **Symmetry:** The unique Kronecker power leverages the commutative property of multiplication, avoiding redundant terms. - **Polynomial Representation:** Each element corresponds to a unique monomial of degree $k$ in the variables $x_1, x_2, \dots, x_n$. ## Computation To compute the unique Kronecker power of a vector $\mathbf{x}$, generate all combinations of indices with replacement and compute the products corresponding to those combinations. **Example for $n = 2$ and $k = 2$:** Let $\mathbf{x} = [x_1, x_2]^\top$. The unique Kronecker power is: ```math \mathbf{x}^{\langle 2 \rangle} = \begin{bmatrix} x_1^2 \\ x_1 x_2 \\ x_2^2 \end{bmatrix} ``` **Example for $n = 3$ and $k = 2$:** ```math \mathbf{x}^{\langle 2 \rangle} = \begin{bmatrix} x_1^2 \\ x_1 x_2 \\ x_1 x_3 \\ x_2^2 \\ x_2 x_3 \\ x_3^2 \end{bmatrix} ``` ## Conversion Between Standard and Unique Kronecker Powers The package provides tools to convert between the standard Kronecker power $\mathbf{x}^{[k]}$ and the unique Kronecker power $\mathbf{x}^{\langle k \rangle}$ using the elimination matrix $\mathbf{L}_{n,k}$ and the duplication matrix $\mathbf{D}_{n,k}$. **From Standard to Unique:** ```math \mathbf{x}^{\langle k \rangle} = \mathbf{L}_{n,k} \mathbf{x}^{[k]} ``` **From Unique to Standard:** ```math \mathbf{x}^{[k]} = \mathbf{D}_{n,k} \mathbf{x}^{\langle k \rangle} ``` ```@docs UniqueKronecker.UniqueCombinationIterator ```
UniqueKronecker
https://github.com/smallpondtom/UniqueKronecker.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
20740
# Currently unmaintained function plotLsrScanFeats(br::Array{Float64,2}) Cart = zeros(size(br)) Cart[:,1] = br[:,2].*cos(br[:,1]) Cart[:,2] = br[:,2].*sin(br[:,1]) plot(x=Cart[:,1],y=Cart[:,2],Geom.point, Guide.xticks(ticks=collect(-60:10:60)), Guide.yticks(ticks=collect(0:10:80))) end function plotFeatTrackers(trkrs::Dict{Int64,Feature}, bfts::Array{Float64,2}) musX = Float64[] varX = Float64[] musY = Float64[] varY = Float64[] allPtsX = Float64[] allPtsY = Float64[] for ftr in trkrs pts = getPoints(ftr[2].bel) allPtsX = [allPtsX; vec(pts[1,:])] allPtsY = [allPtsY; vec(pts[2,:])] push!(musX, Statistics.mean(vec(pts[1,:]))) push!(varX, Statistics.std(vec(pts[1,:]))) push!(musY, Statistics.mean(vec(pts[2,:]))) push!(varY, Statistics.std(vec(pts[2,:]))) end X = Float64[] Y = Float64[] if size(bfts,2) > 0 if bfts[1,1] != 0.0 && bfts[2,1] != 0.0 && bfts[3,1] != 0.0 for i in 1:size(bfts,2) u, R = p2c(vec(bfts[:,i])) push!(X, u[1]) push!(Y, u[2]) end end end # Guide.yticks(ticks=collect(-60:10:60)), # Guide.xticks(ticks=collect(0:10:80)) p = plot(layer(x=musX, y=musY, Geom.point, Theme(default_color=colorant"red")), layer(x=allPtsX, y=allPtsY, Geom.histogram2d), Guide.yticks(ticks=collect(-70:10:70)), Guide.xticks(ticks=collect(-40:10:80))) for i in 1:length(X) push!(p.layers, Gadfly.layer(x=[0.0;X[i]], y=[0.0;Y[i]], Geom.line, Gadfly.Theme(default_color=colorant"magenta"))[1]) end p end function saveImgSeq(d::Dict{Int64,Array{Float64,2}}; from::Int=1,to::Int=10,step::Int=1) for i in from:step:to p = plotLsrScanFeats([d[i][2,:];d[i][1,:]]') #lsrBR(d[i])); Gadfly.draw(PNG(string("imgs/img",i,".png"),25cm,25cm),p) end nothing end """ $SIGNATURES Plot trajectory of Array{,2} with rows as consecutive entries and columns as x,y,theta. """ function plotTrajectoryArrayPose2(arr::AbstractMatrix__{<:Real}; spscale::Real=0.5, triadStride::Int=50) # @assert size(arr,2)==3 trajPlt = Gadfly.plot(x=arr[:,1], y=arr[:,2], Geom.path, Coord.cartesian(fixed=true, aspect_ratio=1)) if triadStride != -1 Xpp = arr[1:triadStride:end,1] Ypp = arr[1:triadStride:end,2] Thpp = arr[1:triadStride:end,3] addXYLineLayers!(trajPlt, Xpp, Ypp, Thpp, l=spscale) end return trajPlt end # Victoria Park Plotting functions function progressExamplePlot(dOdo, lsrFeats; toT=Inf) len = length(dOdo) pose = SE2(zeros(3)) lastpose = zeros(3) idx = 1 T = dOdo[idx][4] lstlaseridx = 1 WFTSX = Array{Float64,1}() WFTSY = Array{Float64,1}() WLBLS = String[] lastX = Array{Float64,1}() lastY = Array{Float64,1}() while T < toT && idx <= len lastX = Array{Float64,1}() lastY = Array{Float64,1}() pose = pose*SE2(dOdo[idx][1:3]) # todo -- replace with inferred latest pose #@show idx, T, vec(pose[1:2,3]) lastpose = vec(se2vee(pose)) # lstlaseridx, Ta = getFeatsAtT(lsrFeats, T, prev=lstlaseridx) # bfts = lsrFeats[lstlaseridx].feats fe = lsrFeats[idx] if length(lsrFeats[idx]) > 0 bfts = zeros(3,length(fe)) lbls = String[] k = collect(keys(fe)) for i in 1:length(fe) bfts[1:length(fe[k[i]]),i] = fe[k[i]] push!(lbls, "l$(k[i])") end if bfts[1,1] != 0.0 && bfts[2,1] != 0.0 && bfts[3,1] != 0.0 wfts = rotateFeatsToWorld(bfts, pose) for i in 1:size(wfts,2) push!(WFTSX, wfts[1,i]) push!(WFTSY, wfts[2,i]) push!(WLBLS, lbls[i]) push!(lastX, wfts[1,i]) push!(lastY, wfts[2,i]) end end end idx += 1 if idx <= len T = dOdo[idx][4] end end p = plotPoseDict(dOdo,to=idx-1) if length(WFTSX) > 0 l = Gadfly.layer(x=WFTSX, y=WFTSY, label=WLBLS, Geom.label, Geom.point, Gadfly.Theme(default_color=colorant"red")) push!(p.layers, l[1]) l2 = Gadfly.layer(x=WFTSX, y=WFTSY, Geom.point, Gadfly.Theme(default_color=colorant"red")) push!(p.layers, l2[1]) for i in 1:length(lastX) push!(p.layers, Gadfly.layer(x=[lastpose[1];lastX[i]], y=[lastpose[2];lastY[i]], Geom.line, Gadfly.Theme(default_color=colorant"magenta"))[1]) end end p end function plotTrckStep(DBG, i, fid, m) @show keys(DBG[i]) pf = DBG[i][fid] arr = Array{BallTreeDensity,1}() for j in 1:3 push!(arr, marginal(pf[j],[m])) end plotKDE(arr, c=["red";"green";"black"]) end function plotPose3Pairs(fgl::AbstractDFG, sym::Symbol; fill::Bool=true) p1= plotKDE(fgl, sym, dims=[1;2], fill=fill) p2 = plotKDE(fgl, sym, dims=[6;3], fill=fill) p3 = plotKDE(fgl, sym, dims=[4;5], fill=fill) Gadfly.draw(PDF("/tmp/RoMEvstackPose3.pdf",15cm, 20cm), vstack(p1,p2,p3) ) @async run(`evince /tmp/RoMEvstackPose3.pdf`) nothing end """ $SIGNATURES Convenience function to plot one Point2 or Pose2 location along with reference data if desired. """ function plotVariable2D(dfg::AbstractDFG, varsym::Symbol; refs::Vector=[], levels::Int=10 ) # # make sure variable is in the right family var = getVariable(dfg, varsym) @assert isa(getSofttype(var), Union{Pose2, Point2}) pl = plotKDE(dfg, varsym, levels=levels) if 0 < length(refs) XX, YY = zeros(0), zeros(0) for dict in refs push!(XX,dict[varsym][1]) push!(YY,dict[varsym][2]) end p2 = Gadfly.plot(x=XX, y=YY, Geom.point, Guide.Theme(default_color=colorant"red", point_size=5pt)) union!(p2.layers, pl.layers) pl = p2 end return pl end # pl = plotKDE(dfg, varsym, levels=levels) # pl = Gadfly.plot(x=[landmarks_design[:l1][1]; landmarks_real[:l1][1]], # y=[landmarks_design[:l1][2]; landmarks_real[:l1][2]], # Geom.point, # Guide.Theme(default_color=colorant"red", point_size=5pt)) # p2 = plotKDE(fg, :l1, levels=20) # union!(pl.layers, p2.layers) function plotTrailingPoses(pt::Pose2, pp::Vector{BallTreeDensity}, title=""; levels=2, c=nothing, axis=nothing, scale::Real=0.2, circlen::Int=5) ran = axis === nothing ? getKDERange(pp) : axis cc=["red"; ["pink" for i in 1:100]] p1 = plotKDE(pp, dims=[1;2], levels=levels, c=cc, title=title, axis=ran ) GG = BallTreeDensity[] for ppc in pp gg = marginal(ppc,[3]) # gg = (x)->pc(reshape([x], :,1))[1] push!(GG, gg) end p2 = AMP.plotKDECircular(GG[(end-circlen):end], scale=scale, c=cc) p2,p1 end function plotTrailingPoses(fg::AbstractDFG, pp::Vector{Symbol}, title=""; solveKey::Symbol=:default, levels=2, c=nothing, axis=nothing, scale::Real=0.2, circlen::Int=5) # plotTrailingPoses(Pose2(), map(x->getBelief(fg,x, solveKey),pp), scale=scale, title=title, circlen=circlen) end # gg = (x)->plotTrailingPoses(fg, [Symbol("x$i") for i in (x+60):-5:x],circlen=3) # # for i in 5:5:290 # g1,g2 = gg(i) # # g1 |> SVG("/tmp/trailingimgs/g1_$(i).svg") # g1 |> SVG("/tmp/trailingimgs/g1_$(i+1).svg") # g1 |> SVG("/tmp/trailingimgs/g1_$(i+2).svg") # g1 |> SVG("/tmp/trailingimgs/g1_$(i+3).svg") # g1 |> SVG("/tmp/trailingimgs/g1_$(i+4).svg") # # g2 |> SVG("/tmp/trailingimgs/g2_$(i).svg") # g2 |> SVG("/tmp/trailingimgs/g2_$(i+1).svg") # g2 |> SVG("/tmp/trailingimgs/g2_$(i+2).svg") # g2 |> SVG("/tmp/trailingimgs/g2_$(i+3).svg") # g2 |> SVG("/tmp/trailingimgs/g2_$(i+4).svg") # end function investigateMultidimKDE(p::BallTreeDensity, p0::BallTreeDensity) co = ["black"; "blue"] h = Union{} x = plotKDE([marginal(p,[1]); marginal(p0,[1])], c=co ) y = plotKDE([marginal(p,[2]); marginal(p0,[2])], c=co ) if p.bt.dims >= 3 th = plotKDE([marginal(p,[3]); marginal(p0,[3])], c=co ) h = hstack(x,y,th) else h = hstack(x,y) end return h end function investigateMultidimKDE(p::Array{BallTreeDensity,1}) co = ["black"; "blue"; "green"; "red"; "magenta"; "cyan"; "cyan1"; "cyan2"; "magenta"; "cyan"; "cyan1"; "cyan2"; "magenta"; "cyan"; "cyan1"; "cyan2"; "magenta"; "cyan"; "cyan1"; "cyan2"; "magenta"; "cyan"; "cyan1"; "cyan2"] # compute all the marginals Pm = Array{Array{BallTreeDensity,1},1}() push!(Pm,stackMarginals(p,1)) #[marginal(p[1],[1]); marginal(p[2],[1])] push!(Pm,stackMarginals(p,2)) #[marginal(p[1],[2]); marginal(p[2],[2])] h = Union{} x = plotKDE(Pm[1], c=co ) y = plotKDE(Pm[2], c=co ) if p[1].bt.dims >= 3 #Pm3 = [marginal(p[1],[3]); marginal(p[2],[3])] push!(Pm,stackMarginals(p,3)) # [marginal(p[1],[3]); marginal(p[2],[3])] th = plotKDE(Pm[3], c=co ) h = hstack(x,y,th) else h = hstack(x,y) end return h end function investigateMultidimKDE(p::BallTreeDensity) x = plotKDE(marginal(p,[1]) ) y = plotKDE(marginal(p,[2]) ) if p.bt.dims >= 3 th = plotKDE(marginal(p,[3]) ) return hstack(x,y,th) end return hstack(x,y) end function plotLbl(fgl::G, lbl::Symbol) where G <: AbstractDFG plotKDE(getBelief(getVariable(fgl,lbl))) end drawLbl(fgl::G, lbl::T) where {G <: AbstractDFG, T <: AbstractString} = drawLbl(fgl, Symbol(lbl)) function plotFrontalDens( fg::AbstractDFG, bt::AbstractBayesTree; N=300, gt=Union{} ) # len = length(bt.cliques) vv = Array{Gadfly.Compose.Context,1}(len) i = 0 for cliq in bt.cliques #@show cliq[2].attributes["label"] lenfr = length(cliq[2].attributes["data"].frontalIDs) p = Array{BallTreeDensity,1}(lenfr) j=0 #pvals = Array{Array{Float64,2},1}(lenfr) gtvals = Dict{Int,Array{Float64,2}}() lbls = String[] for frid in cliq[2].attributes["data"].frontalIDs j+=1 p[j] = getBelief(getVariable(fg, frid)) # getBelief(fg.v[frid]) # p[j] = kde!(fg.v[frid].attributes["val"]) #pvals[j] = fg.v[frid].attributes["val"] if gt!=Union{} gtvals[j] = gt[getVariable(fg,frid).label] # fg.v[frid]. #push!(gtvals, gt[fg.v[frid].attributes["label"]][1]) #push!(gtvals, gt[fg.v[frid].attributes["label"]][2]) end push!(lbls, getVariable(fg,frid).label) # fg.v[frid]. end #r = Array{RemoteRef,1}(lenfr) #[r[j] = @spawn kde!(pvals[j]) for j in 1:lenfr] #[p[j] = fetch(r[j]) for j in 1:lenfr] i+=1 if length(gtvals) > 0 #gtvals = reshape(gtvals,2,round(Int,length(gtvals)/2))' vv[i] = drawHorDens(p, N, gt=gtvals, lbls=lbls) else vv[i] = drawHorDens(p, N,lbls=lbls) end end #r = Array{RemoteRef,1}(lenfr) #[r[j] = @spawn kde!(pvals[j]) for j in 1:lenfr] #[p[j] = fetch(r[j]) for j in 1:lenfr] i+=1 if length(gtvals) > 0 #gtvals = reshape(gtvals,2,round(Int,length(gtvals)/2))' vv[i] = drawHorDens(p, N, gt=gtvals, lbls=lbls) else vv[i] = drawHorDens(p, N,lbls=lbls) end # return vv end function saveplot(pl;name="pl",frt=:png,w=25cm,h=25cm,nw=false,fill=true) if frt==:png Gadfly.draw(PNG(string(name,".png"),w,h),pl) # if fill run(`composite $(name).png plB.png $(name).png`) end if !nw run(`eog $(name).png`) end end if frt==:pdf Gadfly.draw(PDF(string(name,".pdf"),w,h),pl) if !nw run(`evince $(name).pdf`) end end nothing end function animateVertexBelief(FGL::Array{<:AbstractDFG,1}, lbl; nw=false) len = length(FGL) [saveplot(plotLocalProduct(FG[i],lbl),h=15cm,w=30cm,name="gifs/pl$(i)",nw=true) for i=1:len]; run(`convert -delay 100 gifs/pl'*'.png result.gif`) if !nw run(`eog result.gif`) end nothing end function fixRotWrapErr!(RT::Array{Float64,1}) for i in 1:length(RT) if RT[i] > pi RT[i] = abs(RT[i]-2.0*pi) end end nothing end function asyncUniComp(fgl::G, isamdict::Dict{Int,Array{Float64,1}}) where G <: AbstractDFG r,rt,lb = computeGraphResiduals(fgl,isamdict); fixRotWrapErr!(rt) return [sqrt(mean(r.^2));maximum(abs(r));sqrt(mean(rt.^2));maximum(rt)] end function unimodalCompare(FGL::Array{<:AbstractDFG,1},isamdict::Dict{Int,Array{Float64,1}}) len = length(FGL) RMS = Float64[] MAX = Float64[] RMSth = Float64[] MAXth = Float64[] rr = Future[] #RemoteRef[] for fgl in FGL push!(rr, remotecall(uppA(),asyncUniComp, fgl, isamdict)) end for r in rr err = fetch(r) push!(RMS, err[1]) push!(MAX, err[2]) push!(RMSth, err[3]) push!(MAXth, err[4]) end x=0:(len-1) df1 = DataFrame(x=x, y=RMS, label="rms") df2 = DataFrame(x=x, y=MAX, label="max") df3 = DataFrame(x=x, y=RMSth*180.0/pi, label="rmsth") df4 = DataFrame(x=x, y=MAXth*180.0/pi, label="maxth") df = vcat(df1, df2) dfth = vcat(df3,df4) return df,dfth end function asyncAnalyzeSolution(fgl::G, sym::Symbol) where G <: AbstractDFG lbl = string(sym) pp, arr, partials = IncrementalInference.localProduct(fgl, lbl) lpm = getKDEMax(pp) em = getKDEMax(getBelief(getVariable(fgl,lbl))) err1 = norm(lpm[1:2]-em[1:2]) err2 = 0.0 if lbl[1]=='x' err2 = abs(lpm[3]-em[3]) end return [err1;err2] end function analyzeSolution(FGL::Array{<: AbstractDFG,1},fggt=Union{}) len = length(FGL) RMS = Float64[] MAX = Float64[] RMSth = Float64[] MAXth = Float64[] for fgl in FGL xLB, lLB = ls(fgl) ERR = Float64[] ERRth = Float64[] ALB = [xLB;lLB] rr = Future[] #RemoteRef[] for lbl in ALB push!(rr, remotecall(uppA(),asyncAnalyzeSolution, fgl, lbl)) # err # push!(ERR, err[1]) # if lbl[1]=='x' # push!(ERRth, err[2]) # end end idx = 1 for r in rr err = fetch(r) push!(ERR, err[1]) if ALB[idx][1]=='x' push!(ERRth, err[2]) end idx += 1 end push!(RMS, sqrt(mean(ERR.^2))) push!(MAX, maximum(abs(ERR))) push!(RMSth, sqrt(mean(ERRth.^2))) push!(MAXth, maximum(ERRth)) end x=0:(len-1) df1 = DataFrame(x=x, y=RMS, label="rms") df2 = DataFrame(x=x, y=MAX, label="max") df3 = DataFrame(x=x, y=RMSth*180.0/pi, label="rmsth") df4 = DataFrame(x=x, y=MAXth*180.0/pi, label="maxth") df = vcat(df1, df2) dfth = vcat(df3,df4) return df,dfth end # discrete_color_manual(colors...; levels=nothing,order=nothing) is deprecated, use color_discrete_manual(colors...; levels=levels,order=order) instead. function plotAnalysis(df,dfth) return vstack( Gadfly.plot(df, x="x", y="y", color="label", Geom.line, Scale.discrete_color_manual("red","black")), Gadfly.plot(dfth, x="x", y="y", color="label", Geom.line, Scale.discrete_color_manual("red","black")) ) end function getAllFGsKDEs(fgD::Array{<: AbstractDFG,1}, vertsym::Symbol) ret = Array{BallTreeDensity,1}() for i in 1:length(fgD) push!(ret, getBelief(getVariable(fgD[i],vertsym)) ) end return ret end function plotAllPose2DBeliefs(plots::Array{Gadfly.Compose.Context,1}, fgD::Array{<: AbstractDFG,1}) ids = sort(collect(keys(fgD[1].v))) co = ["black"; "blue"; "green"; "red"; "magenta"; "cyan"; "cyan1"; "cyan2"] println(co[1:length(fgD)]) for i in ids getVariable(fgD[1],i).label kdes = getAllFGsKDEs(fgD, i) push!(plots, plotKDE( kdes )) # [kde!(getVal(V)); kde!(getVal(V0))] end vstackedPlots(plots) end # legacy function -- use the array version instead function plotAllPose2DBeliefs(plots::Array{Gadfly.Compose.Context,1}, fgD::G, fgD0=Union{}) where G <: AbstractDFG println("WARNING: drawAllPose2DBeliefs -- legacy function -- use the array version instead.") if fgD0 != Union{} drawAllPose2DBeliefs(plots, [fgD;fgD0]) else drawAllPose2DBeliefs(plots, [fgD]) end end function plotComicStripLM(fgD::Array{<: AbstractDFG,1}) comicA = Array{Gadfly.Plot,1}() for fgd in fgD cv = drawPosesLandms(fgd) # cv = drawPoses(fgd) push!(comicA,cv) end hstack(comicA) end function plotComicStrip(fgD::Array{<: AbstractDFG,1}) comicA = Array{Gadfly.Plot,1}() for fgd in fgD cv = drawPoses(fgd) push!(comicA,cv) end hstack(comicA) end function compositeComic(fnc::Function, fgGT, fgA::Array{<: AbstractDFG,1}) v = Union{} @show length(fgA) if length(fgA) == 2 Gadfly.set_default_plot_size(25cm, 10cm) v = fnc([fgA[1:2];fgGT]) elseif length(fgA) == 3 Gadfly.set_default_plot_size(25cm, 20cm) v = vstack(fnc(fgA[1:2]) ,fnc([fgA[3];fgGT]) ) elseif length(fgA) == 4 Gadfly.set_default_plot_size(25cm, 20cm) v = vstack(fnc(fgA[1:3]) ,fnc([fgA[4];fgGT]) ) elseif length(fgA) == 7 Gadfly.set_default_plot_size(25cm, 25cm) v = vstack(fnc(fgA[1:3]) ,fnc(fgA[4:6]) ,fnc([fgA[7];fgGT]) ) elseif length(fgA) == 10 Gadfly.set_default_plot_size(25cm, 25cm) v = vstack(fnc(fgA[1:3]) ,fnc(fgA[4:6]) ,fnc(fgA[7:9]) ,fnc([fgA[10];fgGT]) ) elseif length(fgA) == 13 Gadfly.set_default_plot_size(25cm, 30cm) v = vstack(fnc(fgA[1:3]) ,fnc(fgA[4:6]) ,fnc(fgA[7:9]) ,fnc(fgA[10:12]) ,fnc([fgA[13];fgGT]) ) end v end function compositeComic(fnc::Function, fgA::Array{<: AbstractDFG,1}) v = Union{} @show length(fgA) if length(fgA) == 2 Gadfly.set_default_plot_size(25cm, 10cm) v = fnc(fgA[1:2]) elseif length(fgA) == 3 Gadfly.set_default_plot_size(25cm, 20cm) v = fnc(fgA[1:3]) elseif length(fgA) == 4 Gadfly.set_default_plot_size(25cm, 25cm) v = vstack(fnc(fgA[1:2]) ,fnc(fgA[3:4])) elseif length(fgA) == 6 Gadfly.set_default_plot_size(25cm, 25cm) v = vstack(fnc(fgA[1:3]) ,fnc(fgA[4:6]) ) elseif length(fgA) == 9 Gadfly.set_default_plot_size(25cm, 25cm) v = vstack(fnc(fgA[1:3]) ,fnc(fgA[4:6]) ,fnc(fgA[7:9]) ) elseif length(fgA) == 12 Gadfly.set_default_plot_size(25cm, 30cm) v = vstack(fnc(fgA[1:3]) ,fnc(fgA[4:6]) ,fnc(fgA[7:9]) ,fnc(fgA[10:12]) ) end v end # # # # function spyCliqMat(cliq::Graphs.ExVertex; showmsg=true) # mat = deepcopy(getCliqMat(cliq, showmsg=showmsg)) # # TODO -- add improved visualization here, iter vs skip # mat = map(Float64, mat)*2.0.-1.0 # numlcl = size(IIF.getCliqAssocMat(cliq),1) # mat[(numlcl+1):end,:] *= 0.9 # mat[(numlcl+1):end,:] .-= 0.1 # numfrtl1 = floor(Int,length(getData(cliq).frontalIDs) + 1) # mat[:,numfrtl1:end] *= 0.9 # mat[:,numfrtl1:end] .-= 0.1 # @show getData(cliq).itervarIDs # @show getData(cliq).directvarIDs # @show getData(cliq).msgskipIDs # @show getData(cliq).directFrtlMsgIDs # @show getData(cliq).directPriorMsgIDs # sp = Gadfly.spy(mat) # push!(sp.guides, Gadfly.Guide.title("$(cliq.attributes["label"]) || $(cliq.attributes["data"].frontalIDs) :$(cliq.attributes["data"].conditIDs)")) # push!(sp.guides, Gadfly.Guide.xlabel("fmcmcs $(cliq.attributes["data"].itervarIDs)")) # push!(sp.guides, Gadfly.Guide.ylabel("lcl=$(numlcl) || msg=$(size(getCliqMsgMat(cliq),1))" )) # return sp # end # function spyCliqMat(bt::BayesTree, lbl::Symbol; showmsg=true) # spyCliqMat(whichCliq(bt,lbl), showmsg=showmsg) # end function plotPose2Vels(fgl::G, sym::Symbol; coord=nothing) where G <: AbstractDFG X = getBelief(getVariable(fgl, sym)) px = plotKDE(X, dims=[4], title="Velx") coord != nothing ? (px.coord = coord) : nothing py = plotKDE(X, dims=[5], title="Vely") coord != nothing ? (py.coord = coord) : nothing hstack(px, py) end """ $(SIGNATURES) Analysis function to compare KDE plots between the factor graph centric product of a variable with current value stored in the factor graph object. """ function plotProductVsKDE(fgl::G, sym::Symbol; levels::Int=3, c::Vector{String}=["red";"black"] ) where G <: AbstractDFG # plotKDE([IIF.localProduct(fgl, sym)[1], getBelief(getVariable(fgl, sym))], levels=3, c=c) end #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
2379
## ======================================================================================= ## Remove before v0.11 ## ======================================================================================= # see JuliaRobotics/Caesar.jl#811 @deprecate plotKDE(w...;kw...) plotBelief(w...;kw...) ## ======================================================================================= ## Remove before v0.10 ## ======================================================================================= # function getColorsByLength(len::Int=7) # len > 99 ? error("Don't have enough colors, 100 is the max.") : nothing # COLORS = String["red";"green";"blue";"magenta";"yellow";"deepskyblue"] # if len > 6 # scale = len -7 + 2 # + 2 is artificial and avoids gray100==white # scale = 100/scale # for i in 7:len # push!(COLORS, "gray$(floor(Int,(i-7)*scale))") # end # end # return COLORS[1:len] # end export togglePrtStbLines export stbPrtLineLayers! # export drawHorDens # from KDEPlotting # export plotMCMC, plotPose2DMC!, mcmcPose2D! # for some reason we still need msgPlots of right size in the global for these functions to work. # precall drawTreeUpwardMsgs or drawFrontalDens to make this work properly TODO function vstackedDensities(msgPlots) #msgPlots = f(fg, bt) # drawTreeUpwardMsgs evalstr = "" for i in 1:length(msgPlots) evalstr = string(evalstr, ",msgPlots[$(i)]") end eval(parse(string("vstack(",evalstr[2:end],")"))) end global DISABLESTBPRTLINES = false function togglePrtStbLines() global DISABLESTBPRTLINES DISABLESTBPRTLINES = !DISABLESTBPRTLINES end ## TODO -- you were here with port starboard lines function stbPrtLineLayers!(pl, Xpp, Ypp, Thpp; l::Real=5.0) if DISABLESTBPRTLINES return nothing end lnstpr = [0.0;l;0.0] lnstpg = [0.0;-l;0.0] Rd =SE2(lnstpr) Gr = SE2(lnstpg) for i in 1:length(Xpp) lnstt = [Xpp[i];Ypp[i];Thpp[i]] Ps = SE2(lnstt) lnr = se2vee(Ps*Rd) lng = se2vee(Ps*Gr) xsr = [Xpp[i];lnr[1]] ysr = [Ypp[i];lnr[2]] xsg = [Xpp[i];lng[1]] ysg = [Ypp[i];lng[2]] push!(pl.layers, layer(x=xsr, y=ysr, Geom.path(), Gadfly.Theme(default_color=colorant"red", line_width=1.5pt))[1] ) push!(pl.layers, layer(x=xsg, y=ysg, Geom.path(), Gadfly.Theme(default_color=colorant"green", line_width=1.5pt))[1] ) end nothing end #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
2059
## ===================================================================================== # Primary supported functionality ## ===================================================================================== export plotBelief export plotPose export plotVariable2D export plotSLAM2D, plotSLAM2D_KeyAndRef, plotSLAM2DLandmarks, plotSLAM2DPoses export getColorsByLength # FIXME what to do about this? export plot # needs better testing (might be broken following upgrade to Manifolds.jl) export plotPose2Vels export plotFactor export plotFactorValues, plotFactorMeasurements, plotVariableGivenFactor export plotPairVariables, plotPairPose2, plotPose3Pairs export localProduct, plotLocalProductCylinder, plotLocalProduct export saveplot export plotMarginalContour, accumulateMarginalContours # plot tree functionality (needs testing, possible broken with recent upgrades) export plotUpMsgsAtCliq export plotTreeProductUp, plotTreeProductDown, plotCliqUpMsgs, plotCliqDownMsgs ## ===================================================================================== ## Known FIXME issues ## ===================================================================================== # export reportFactor # export plotPriorsAtCliq ## ===================================================================================== ## CURRENTLY UNMAINTAINED, utility functions that must be refactored, consolidated, standardized, or deprecated ## ===================================================================================== export investigateMultidimKDE, plotKDEofnc, plotKDEresiduals, investigateMultidimKDE, plotLbl, animateVertexBelief, # Associated with RoME plotTrajectoryArrayPose2, saveImgSeq, plotProductVsKDE ## ===================================================================================== ## Old Victoria Park dataset features that were good but unmaintained ## ===================================================================================== export plotLsrScanFeats, progressExamplePlot, plotTrckStep #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
430
# features specifically related to Flux.jl @info "RoMEPlotting is adding Flux related functionality." @eval PlotTypesPose2 = Union{Type{Pose2Pose2}, Type{Pose2Point2BearingRange}, Type{Pose2Point2Range}, Type{Pose2Point2Bearing}, Type{MixtureFluxPose2Pose2}} @eval ExtendedPose2Pose2Types = Union{Pose2Pose2, MixtureFluxPose2Pose2} # rerun since a few functions need to be reloaded with Flux include("PlotFactorsReload.jl") #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
6318
""" $(SIGNATURES) Plot absolute values of variables and measurement surrounding fsym factor. """ function plotKDEofnc(fgl::AbstractDFG, fsym::Symbol; solveKey::Symbol=:default, marg=nothing, N::Int=100 ) # fnc = nothing if haskey(fgl.fIDs, fsym) fnc = getfnctype( fgl, fgl.fIDs[fsym] ) else error("fIDs doesn't have $(fsym)") end p = kde!( getSample(fnc, N)[1] ) # mmarg = length(marg) > 0 ? marg : collect(1:Ndim(p)) plotKDE(fgl, lsf(fgl, fsym), solveKey=solveKey, addt=[p], marg=marg) end """ $(SIGNATURES) Try plot relative values of variables and measurement surrounding fsym factor. """ function plotKDEresiduals(fgl::AbstractDFG, fsym::Symbol; N::Int=100, levels::Int=3, dims=nothing, fill=false ) # # COLORS = ["black";"red";"green";"blue";"cyan";"deepskyblue"] fnc = getfnctype( fgl, fgl.fIDs[fsym] ) # @show sxi = lsf(fgl, fsym)[1] # @show sxj = lsf(fgl, fsym)[2] fct = getFactor(fgl, fsym) @show sxi = getData(fct).fncargvID[1] @show sxj = getData(fct).fncargvID[2] xi = getVal(fgl, sxi) xj = getVal(fgl, sxj) measM = getSample(fnc, N) meas = length(measM) == 1 ? (0*measM[1], ) : (0*measM[1], measM[2]) @show size(meas[1]) d = size(measM[1],1) RES = zeros(d,N) for i in 1:N res = zeros(d) fnc(res, i, meas, xi, xj) RES[:,i] = res if length(measM) > 1 if measM[2][i] == 0 RES[:,i] = 0.5*randn(d) end end end pR = kde!(RES) pM = kde!(measM[1]) fncvar = getfnctype(fct) COLORS = getColorsByLength() plotKDE([pR;pM], c=COLORS[1:2], dims=dims,levels=3, legend=["residual";"model"], fill=fill, title=string(fsym, ", ", fncvar)) end # """ # $(SIGNATURES) # Plot the product of priors and incoming upward messages for variable in clique. # plotPriorsAtCliq(tree, :x2, :x1[, marg=[1;2]]) # """ # function plotPriorsAtCliq(tree::BayesTree, # lb::Symbol, # cllb::Symbol; # dims::Vector{Int}=Int[], # levels::Int=1, # fill::Bool=false ) # # # # COLORS = ["black";"red";"green";"blue";"cyan";"deepskyblue"] # cliq = whichCliq(tree, cllb) # cliqprs = cliq.attributes["debug"].priorprods[1] # vidx = 1 # for lbel in cliqprs.lbls # if lbel == lb # break; # else # vidx += 1 # end # end # dims = length(dims)>0 ? dims : collect(1:size(cliqprs.prods[vidx].prev,1)) # arr = BallTreeDensity[] # push!(arr, marginal(kde!(cliqprs.prods[vidx].prev), dims) ) # push!(arr, marginal(kde!(cliqprs.prods[vidx].product), dims) ) # len = length(cliqprs.prods[vidx].potentials) # lg = String["p";"n"] # i=0 # for pot in cliqprs.prods[vidx].potentials # push!(arr, marginal(pot, dims) ) # i+=1 # push!(lg, cliqprs.prods[vidx].potentialfac[i]) # end # COLORS = getColorsByLength(len+2) # # cc = COLORS[1:(len+2)] # plotKDE(arr, c=COLORS, legend=lg, levels=levels, fill=fill ); # end # function plotMCMC(treel::BayesTree, # lbll::Symbol; # delay::Int=200, # show::Bool=true, # w=20cm, h=15cm, # levels::Int=1, # dims=nothing ) # # # cliq = whichCliq(treel, string(lbll)) # cliqdbg = cliq.attributes["debug"] # vidx = 1 # for lb in cliqdbg.mcmc[1].lbls # if lb == lbll # break; # else # vidx += 1 # end # end # tmpfilepath = joinpath(dirname(@__FILE__),"tmpimgs") # ARR = BallTreeDensity[] # COLORS = getColorsByLength() # # COLORS = ["black";"red";"green";"blue";"cyan";"deepskyblue";"magenta"] # for i in 1:length(cliqdbg.mcmc) # ppr = kde!(cliqdbg.mcmc[i].prods[vidx].prev) # ppp = kde!(cliqdbg.mcmc[i].prods[vidx].product) # ARR = [ARR;ppr;ppr;cliqdbg.mcmc[i].prods[vidx].potentials] # end # rangeV = getKDERange(ARR) # ppp = nothing # for i in 1:length(cliqdbg.mcmc) # ppr = kde!(cliqdbg.mcmc[i].prods[vidx].prev) # ppp = kde!(cliqdbg.mcmc[i].prods[vidx].product) # arr = [ppr;ppp;cliqdbg.mcmc[i].prods[vidx].potentials] # len = length(cliqdbg.mcmc[i].prods[vidx].potentials) # lg = String["p";"n";cliqdbg.mcmc[i].prods[vidx].potentialfac] #map(string, 1:len)] # COLORS_l = getColorsByLength(len+2) # cc = plotKDE(arr, c=COLORS_l, legend=lg, levels=levels, fill=true, axis=rangeV, dims=dims ); # Gadfly.draw(PNG(joinpath(tmpfilepath,"$(string(lbll))mcmc$(i).png"),w,h),cc) # end # # draw initial and final result # pp0 = kde!(cliqdbg.mcmc[1].prods[vidx].prev) # i = 0 # cc = plotKDE([pp0], c=[COLORS[1]], legend=["0"], levels=levels, fill=true, axis=rangeV, dims=dims ); # Gadfly.draw(PNG(joinpath(tmpfilepath,"$(string(lbll))mcmc$(i).png"),w,h),cc) # i = length(cliqdbg.mcmc)+1 # cc = plotKDE([pp0;ppp], c=COLORS[1:2], legend=["0";"n"], levels=levels, fill=true, axis=rangeV, dims=dims ); # Gadfly.draw(PNG(joinpath(tmpfilepath,"$(string(lbll))mcmc$(i).png"),w,h),cc) # # generate output # @warn "Maintenance required, run manually: \"convert -delay $(delay) $(tmpfilepath)/$(string(lbll))mcmc*.png $(tmpfilepath)/$(string(lbll))mcmc.gif\"" # # run(`convert -delay $(delay) $(tmpfilepath)/$(string(lbll))mcmc*.png $(tmpfilepath)/$(string(lbll))mcmc.gif`) # # !show ? nothing : (@async run(`eog $(tmpfilepath)/$(string(lbll))mcmc.gif`) ) # # return "$(tmpfilepath)/$(string(lbll))mcmc.gif" # end # function plotMCMCDebug(cliq; offs=2.0) # println("$(cliq.attributes["label"])") # cliqDbg = cliq.attributes["data"].debug # MCd = 100.0/length(cliqDbg.mcmc) # MCo=0.0 # minmax=[99999,-99999,-10,-99999.0] # for mc in cliqDbg.mcmc # drawOneMC!(mc, minmax, MCo, offs=offs) # MCo+=MCd # end # n = 3 # y = linspace(minmax[1], minmax[2], n) # x = linspace(minmax[3],minmax[4],n) # xgrid = repmat(x',n,1) # ygrid = repmat(y,1,n) # z = zeros(n,n) # for i in 1:length(cliqDbg.mcmc[1].prods) # surf(xgrid,ygrid,z-(i-1)*offs,alpha=0.04, linewidth=0.0) # end # end
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
10673
# import RoMEPlotting: plotFactor, reportFactors, plotFactorMeasurements, getTimeEasy """ $SIGNATURES Plot Pose2Pose2 measurement and predicted values in factor centric manner -- i.e. used with inverse solve. """ function plotFactorValues(asMeasured::AbstractMatrix{<:Real}, asPredicted::AbstractMatrix{<:Real}, fct::Type{T}=Pose2Pose2; title="inv. solve", fctsym="", hdl=[], dist::Vector{Float64}=zeros(1) ) where {T <: AbstractFactor} # PPg = manikde!(Point2, asMeasured[1:2,:]) PP = manikde!(Point2, asPredicted[1:2,:]) # dist[1] = minimum(abs.([kld(PPg, PP)[1]; kld(PP, PPg)[1]])) mmd!(dist, asPredicted, asMeasured, SE2_Manifold) pt = plotKDE([PPg;PP], c=["blue";"red"], legend=["meas";"pred";], levels=3, title="$title $fctsym,\nmmd(..)=$(round(dist[1],digits=6))") pc = plotKDECircular([manikde!(Sphere1, asMeasured[3:3,:]);manikde!(Sphere1, asPredicted[3:3,:]);], c=["blue";"red";], legend=["meas";"pred";], title="$title $fctsym,\n$(T)") push!(hdl, pt) push!(hdl, pc) hstack(pt, pc) end """ $SIGNATURES Calculate the "inverse" SLAM solution to compare measured and predicted noise model samples. """ function plotFactorMeasurements(dfg::AbstractDFG, fctsym::Symbol, fct::AbstractFactor; hdl=[], dist::Vector{Float64}=zeros(1) ) # @error "plotFactorMeasurements not implemented yet for $(typeof(fct))." end function plotFactorMeasurements(dfg::AbstractDFG, fctsym::Symbol, fct::Pose2Point2BearingRange; hdl=[], dist::Vector{Float64}=[0.0;] ) # asMeas, asPred = solveFactorMeasurements(dfg, fctsym) pc = plotKDECircular([manikde!(Sphere1, asPred[1:1,:]);manikde!(Sphere1, asMeas[1:1,:])], c=["blue";"red";], legend=["meas";"pred";], title="inv. solve, $fctsym,\nPose2Point2BearingRange") pcl = plotKDE([manikde!(ContinuousScalar, asPred[1:1,:]);manikde!(ContinuousScalar, asMeas[1:1,:])], c=["blue";"red";], legend=["meas";"pred";], title="unwrapped rotation, should be [-pi,pi)") pl = plotKDE([ manikde!(ContinuousScalar, asPred[2:2,:]);manikde!(ContinuousScalar, asMeas[2:2,:])], c=["blue";"red";], legend=["meas";"pred";]) push!(hdl, pc) push!(hdl, pcl) push!(hdl, pl) hstack(vstack(pc,pcl), pl) end function plotFactorMeasurements(dfg::AbstractDFG, fctsym::Symbol; hdl=[], dist::Vector{Float64}=[0.0;] ) # fct = getFactorType(dfg, fctsym) plotFactorMeasurements(dfg, fctsym, fct, hdl=hdl, dist=dist) end """ $SIGNATURES Return plot of each specific factor. """ function plotFactor(dfg::AbstractDFG, fctsym::Symbol, fct::Pose2Point2Range; hdl=[], dist::Vector{Float64}=Float64[0.0;] ) # variables vars = ls(dfg, fctsym) # the pose pose = intersect(vars, ls(dfg, Pose2))[1] poin = intersect(vars, ls(dfg, Point2))[1] # calculate predicted range (inverse solve) ptss = map(x->getPoints(getBelief(dfg, x)), vars) dpts = (ptss[1][1:2,:] - ptss[2][1:2,:]).^2 pred = sqrt.(sum(dpts, dims=1)) plpr = Gadfly.plot(x=pred, Geom.histogram(density=true), Theme(default_color=colorant"deepskyblue"), Guide.title("predicted")) # measured # meas = getSamples(fct, length(pred)) smps = rand(fct.Z, length(pred)) plme = Gadfly.plot(x=smps, Geom.histogram(density=true), Theme(default_color=colorant"magenta"), Guide.title("measured")) # measure kl divergence PP = manikde!(ContinuousScalar, smps) PPg = manikde!(ContinuousScalar, pred) dist[1] = minimum(abs.([kld(PPg, PP)[1]; kld(PP, PPg)[1]])) modl = Gadfly.plot( Gadfly.layer(x=smps, Geom.histogram(density=true), Theme(default_color=colorant"magenta")), Gadfly.layer(x=pred, Geom.histogram(density=true), Theme(default_color=colorant"deepskyblue")), Guide.manual_color_key("Legend", ["samples";"predicted"], ["magenta";"deepskyblue"]), Guide.title("Pose2Point2Range $fctsym\nmin(|kld...|)=$(round(dist[1],digits=3))"), Guide.xlabel("range") ) plxy = plotKDE(map(x->getBelief(dfg, x), vars), dims=[1;2], legend=string.(vars), title="Pose2Point2Range: XY plane") # plx = plotKDE([getBelief(dfg, vars[1]);], dims=[1;2], legend=[string(vars[1]);], title="Pose2Point2Range: XY plane") # ply = plotKDE([getBelief(dfg, vars[2]);], dims=[1;2], legend=[string(vars[2]);], title="Pose2Point2Range: XY plane") # mock projection tfg = initfg() addVariable!(tfg, pose, Pose2) addVariable!(tfg, poin, Point2) addFactor!(tfg, [pose;poin], fct, autoinit=false) manualinit!(tfg, pose, getBelief(dfg,pose)) manualinit!(tfg, poin, getBelief(dfg,poin)) apts=Array{Float64,2}(undef, 2, 0) loop =true while loop try apts = approxConv(tfg, ls(tfg,pose)[1], poin) loop = false catch @warn "plotFactor Pose2Point2BearingRange non-linear solve fail on approxConv, retrying" end end plhist2 = Gadfly.plot(x=apts[1,:], y=apts[2,:], Geom.histogram2d) spc = mean(smps) plt = drawPosesLandms(tfg, point_size=5pt, spscale=0.2*spc) union!(plhist2.layers, plt.layers) pla = plotKDE(manikde!(Point2, apts),levels=3,c=["gray50"]) # plot pose by itself # poseplot = plotPose(dfg, pose) posepl1 = plotKDE(dfg, pose, dims=[1;2], c=["green"]) posepl2 = plotKDECircular(marginal(getBelief(dfg, pose), [3])) landmpl = plotKDE(dfg, poin, c=["red"]) # plot handles push!(hdl, landmpl) push!(hdl, posepl1) push!(hdl, posepl2) push!(hdl, modl) push!(hdl, plme) push!(hdl, plpr) push!(hdl, plhist2) # put plot together botr = vstack(modl, plme, plpr) # 4,5,6 # bot = hstack(plhist2, botr) # 7,(4,5,6) farl = vstack(landmpl, posepl1, posepl2) # 1,2,3 hstack(farl, botr, plhist2) # (1,2,3),(4,5,6),7 end function plotFactor(dfg::AbstractDFG, fctsym::Symbol, fct::Pose2Point2Bearing; hdl=[], dist::Vector{Float64}=Float64[0.0;] ) # # variables vars = ls(dfg, fctsym) # the pose pose = intersect(vars, ls(dfg, Pose2))[1] poin = intersect(vars, ls(dfg, Point2))[1] # basic max estimates xp = getKDEMax(getBelief(dfg,pose)) lp = getKDEMax(getBelief(dfg,poin)) # convolve the yaw angle with bearing rotation model pX = marginal(getBelief(dfg, pose), [3]) pts = approxConvCircular(pX, fct.bearing) # TODO fix by using approxConvBelief instead # draw plots measest = manikde!(Sphere1, pts) # inverse solve for predicted bearing dx = getPoints(getBelief(dfg, poin))[1,:] - getPoints(getBelief(dfg, pose))[1,:] dy = getPoints(getBelief(dfg, poin))[2,:] - getPoints(getBelief(dfg, pose))[2,:] pred = reshape(atan.(dy,dx), 1,:) ppX = manikde!(Sphere1, pred) scal = 0.2*norm(xp[1:2]-lp) plcl = plotKDECircular( [measest; ppX], logpdf=true, legend=["Meas. Est.";"Predicted"], radix=scal, scale=0.2*scal, rVo=[xp[1:2];0.0] ) # plot pose and point by itself posepl1 = plotKDE(dfg, pose, dims=[1;2], c=["green"]) posepl2 = plotKDECircular(marginal(getBelief(dfg, pose), [3])) landmpl = plotKDE(dfg, poin, c=["red"]) tfg = initfg() addVariable!(tfg, pose, Pose2) addVariable!(tfg, poin, Point2) addFactor!(tfg, [pose;poin], fct, autoinit=false) manualinit!(tfg, pose, getBelief(dfg,pose)) manualinit!(tfg, poin, getBelief(dfg,poin)) plt = drawPosesLandms(tfg, point_size=5pt) union!(plt.layers, plcl.layers) plt.coord = Coord.cartesian(aspect_ratio=1.0) # draw line from pose to point push!(plt.layers, Gadfly.layer(x=[xp[1];lp[1]], y=[xp[2];lp[2]], Geom.line)[1]) # plot handles push!(hdl, landmpl) push!(hdl, posepl1) push!(hdl, posepl2) push!(hdl, plcl) push!(hdl, plt) hstack(vstack(landmpl,posepl1, posepl2), vstack(plcl, plt)) end function plotFactor(dfg::AbstractDFG, fctsym::Symbol, fct::Pose2Point2BearingRange; hdl=[], dist::Vector{Float64}=Float64[0.0;] ) # hdlb = [] # variables vars = ls(dfg, fctsym) # the pose pose = intersect(vars, ls(dfg, Pose2))[1] poin = intersect(vars, ls(dfg, Point2))[1] # plot current pose & point # pl_poin = plotKDE(dfg, poin, levels=5, c=["red";]) # pl_pose = plotPose(dfg, pose, c=["black"]) # project landmark # do range model separately too pr = Pose2Point2Range(fct.range) plotFactor(dfg, fctsym, pr, hdl=hdl) br = Pose2Point2Bearing(fct.bearing) plotFactor(dfg, fctsym, br, hdl=hdlb) newguid = Gadfly.GuideElement[] for guid in hdl[4].guides if typeof(guid) == Gadfly.Guide.Title push!(newguid, Gadfly.Guide.Title("Pose2Point2BearingRange $fctsym")) else push!(newguid, guid) end end hdl[4].guides = newguid union!(hdl, hdlb) # plot a prediction of landmark predpoints = approxConv(dfg, fctsym, poin) PP = manikde!(Point2, predpoints) PPg= getBelief(dfg, poin) dist[1] = minimum(abs.([kld(PPg, PP)[1]; kld(PP, PPg)[1]])) predLandm = plotKDE([PPg; PP], levels=2, c=["red"; "deepskyblue"], legend=["landmark";"predicted"], title="min(|kld...|)=$(round(dist[1],digits=3))") push!(hdl, predLandm) # AMP.mmd!(dist, PPg, predpoints) # measurement solution plotFactorMeasurements(dfg, fctsym, hdl=hdl) return hstack(vstack(hdl[1],hdl[2],hdl[3]),vstack(hdl[4],hdl[5],hdl[6]),vstack(predLandm, hdlb[5],hdl[7]), vstack(hdl[14],hdl[15],hdl[16])) end function plotFactor(dfg::AbstractDFG, fctsym::Symbol; hdl=[], dist::Vector{Float64}=Float64[0.0;] ) # plotFactor(dfg, fctsym, getFactorType(dfg, fctsym), hdl=hdl, dist=dist) end ## Reports getTimeEasy() = split(split("$(now())", 'T')[end],'.')[1] # import RoMEPlotting: getTimeEasy, reportFactors # import ApproxManifoldProducts: mmd! ## Also in IIF >v0.7.9 import IncrementalInference: isMultihypo isMultihypo(fct) = isa(solverData(fct).fnc.hypotheses, Distribution) """ $SIGNATURES Methods to generate plots of all requested factor user supplied vs. current predicted measurement -- i.e. inverse solve. """ reportFactors() = @info "Empty function to support both automated documentation and conditional features (@require)." #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
2068
# functions that might need to be loaded multiple times (dont add docs here) function plotFactorMeasurements(dfg::AbstractDFG, fctsym::Symbol, fct::ExtendedPose2Pose2Types; hdl=[], dist::Vector{Float64}=[0.0;] ) # asMeas, asPred = solveFactorMeasurements(dfg, fctsym) plotFactorValues(asMeas, asPred, Pose2Pose2, fctsym=fctsym,hdl=hdl,dist=dist) end function plotFactor(dfg::AbstractDFG, fctsym::Symbol, fct::ExtendedPose2Pose2Types; hdl=[], dist::Vector{Float64}=Float64[0.0;] ) # variables fct = getFactor(dfg, fctsym) vars = fct._variableOrderSymbols pv1 = plotPose(dfg, vars[1], hdl=hdl) pv2 = plotPose(dfg, vars[2], hdl=hdl) pv12 = plotFactorMeasurements(dfg, fctsym, hdl=hdl, dist=dist) vstack(pv1, pv2, pv12) end function reportFactors(dfg::AbstractDFG, T::PlotTypesPose2, fcts::Vector{Symbol}=ls(dfg, T); prefix::AbstractString="", filepath=joinpath(getSolverParams(dfg).logpath, "$prefix"*getTimeEasy()*"_$T.pdf"), show::Bool=true, pdfWidth=20cm, pdfHeight=30cm) # ss = split(filepath, '/') path = joinpath("/", joinpath(ss[1:(end-1)]...), "tmp") mkpath(path) alldists= Vector{Float64}() files = String[] ndist = Float64[0.0;] for fc in fcts if isMultihypo(getFactor(dfg, fc)) # skip this factor continue end file = joinpath(path,"$fc.pdf") ndist[1] = 0.0 plotFactor(dfg, fc, dist=ndist) |> PDF(file, pdfWidth, pdfHeight) push!(files, file) push!(alldists, ndist[1]) end fileord = sortperm(alldists, rev=true) files = files[fileord] push!(files, filepath) 2 < length(files) ? run(`pdfunite $files`) : nothing !show ? nothing : (@async run(`evince $filepath`)) return filepath end #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
2005
export layerLine, plotHex!, plotHex, plotHex_6, plotBeehive_6 # draw a line on plot function layerLine(start::Vector{Float64}, stop::Vector{Float64}, color=colorant"green") layer(x=[start[1];stop[1]], y=[start[2];stop[2]], Geom.path, Theme(default_color=color))[1] end # draw a default hex shape on plot function plotHex!(offsetxy::Vector{Float64}=zeros(2); len::Float64=10.0, PLT = []) # push!(PLT, layerLine([offsetxy[1]+0.0;offsetxy[2]+0.0], [offsetxy[1]+len;offsetxy[2]+0.0])) push!(PLT, layerLine([offsetxy[1]+len;offsetxy[2]+0.0], [offsetxy[1]+len*3/2;offsetxy[2]+len*sqrt(3)/2])) push!(PLT, layerLine([offsetxy[1]+len+5.0;offsetxy[2]+len*sqrt(3)/2], [offsetxy[1]+len;offsetxy[2]+len*sqrt(3)])) push!(PLT, layerLine([offsetxy[1]+0;offsetxy[2]+len*sqrt(3)], [offsetxy[1]+10;offsetxy[2]+len*sqrt(3)])) push!(PLT, layerLine([offsetxy[1]+0;offsetxy[2]+len*sqrt(3)], [offsetxy[1]-len/2; offsetxy[2]+len*sqrt(3)/2])) push!(PLT, layerLine([offsetxy[1]-len/2; offsetxy[2]+len*sqrt(3)/2], [offsetxy[1]+0.0; offsetxy[2]+0])) PLT end # draw a default hex shape on plot function plotHex(offsetxy::Vector{Float64}=zeros(2); len::Float64=10.0) # Gadfly.plot(plotHex!(offsetxy, len=len)...) end # draw a default ring of 6 hexes on plot function plotHex_6(;PLT=[], len::Float64=10.0) plotHex!(zeros(2),PLT=PLT) plotHex!([3/2*len;-sqrt(3)/2*len],PLT=PLT) plotHex!([3/2*len;-sqrt(3)*3/2*len],PLT=PLT) plotHex!([0.0;-sqrt(3)*2*len],PLT=PLT) plotHex!([-3/2*len;-sqrt(3)*3/2*len],PLT=PLT) plotHex!([-3/2*len;-sqrt(3)/2*len],PLT=PLT) Gadfly.plot(PLT...) end """ $SIGNATURES Plot first ring (ground truth) of beehive example. """ function plotBeehive_6(fgl::G; from::Int=0, to::Int=(2^(Sys.WORD_SIZE-1)-1), meanmax::Symbol=:max) where G <: AbstractDFG pl = plotHex_6() pl2 = drawPosesLandms(fgl, from=from, to=to, meanmax=meanmax) union!(pl2.layers, pl.layers) return pl2 end
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
1868
# new file for plotVariable related functionality export plotSLAM2DSolveKeys # function plotSolveKey(dfg::AbstractDFG, # refSym::Symbol, # refKey::Symbol, # tstSym::Symbol, # tstKey::Symbol; # bw::AbstractVector{<:Real}=[0.001;], # plotVarHack::Function=plotPose ) # # # pts, fctT = deconvSolveKey(dfg, refSym, refKey, tstSym, tstKey) # Xref = manikde!(fctT, pts[2]) # Xtst = manikde!(fctT, pts[1]) # mmdDist = mmd(Xref, Xtst, fctT, bw=bw) # # FIXME not all variables are Poses, so this is really hacky # plotVarHack(getManifold(fctT)(), [Xref, Xtst], "$fctT\n$(refSym)_$(refKey) <-> $(tstSym)_$tstKey\nmmd=$(round(mmdDist,digits=6))", c=["red","blue"], legend=["Identity";"Delta"]) # end """ $SIGNATURES Analyzing repeat solves is easier if you can animate repeat solves. Notes - Repeat solves can be stored using `solveTree!(fg, storeOld=true)`. - Experimental, see DFG #641 Example ```julia using Images, Caesar, RoMEPlotting fg = generateGraph_Hexagonal() for i in 1:10 solveTree!(fg, storeOld=true) end # generate all the plots in RAM plts = plotSLAM2DSolveKeys(fg) # export all images to a video imgs = convert.(Matrix{RGB},plts) Caesar.writevideo("/tmp/test.avi", imgs) @async run(`totem /tmp/test.avi`) ``` Related writevideo, plotSolveKey, listSolveKeys """ function plotSLAM2DSolveKeys( dfg::AbstractDFG, pattern::Regex=r"default_\d+"; xmin=nothing, xmax=nothing, ymin=nothing, ymax=nothing, contour=false ) # kys = listSolveKeys(dfg, filterSolveKeys=pattern) |> collect |> sortDFG kys .|> x -> plotSLAM2D(dfg, solveKey=x, contour=contour, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) end #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
2298
module RoMEPlotting using Cairo, Fontconfig using Reexport @reexport using Gadfly @reexport using Colors using Statistics, LinearAlgebra using StatsBase using Compose using Dates using DistributedFactorGraphs using KernelDensityEstimate, KernelDensityEstimatePlotting using IncrementalInference, RoME using DocStringExtensions using ApproxManifoldProducts using TensorCast using Requires using PrecompileTools # import ApproxManifoldProducts: mmd! # future dependency import Gadfly: plot import KernelDensityEstimatePlotting: plot, drawHorDens, plotKDE import KernelDensityEstimatePlotting: getColorsByLength import KernelDensityEstimatePlotting: plotKDE # assuming this is a good size for everybody @info "For larger plots when using a browswer, run Gadfly.set_default_plot_size(30cm,20cm)" # Gadfly.set_default_plot_size(30cm,20cm) include("ExportAPI.jl") # EXPERIMENTAL const AbstractMatrix__{T} = Union{<:AbstractArray{T,2}, <:Adjoint{T,<:AbstractArray{T,2}}} # will be overwritten if flux is present (dont make const) PlotTypesPose2 = Union{Type{<:Pose2Pose2}, Type{<:Pose2Point2BearingRange}, Type{<:Pose2Point2Range}, Type{<:Pose2Point2Bearing}} ExtendedPose2Pose2Types = Pose2Pose2 include("services/PlotBelief.jl") include("SolverVisualization.jl") include("services/PlotEllipseUtils.jl") include("RobotViz.jl") include("services/PlotPose.jl") include("services/PlotTree.jl") include("CurrentlyUnmaintained.jl") include("PlotHexUtils.jl") include("PlotFactors.jl") include("PlotVariables.jl") include("PlotFactorsReload.jl") include("Deprecated.jl") include("NeedsFixing.jl") function __init__() @require Flux="587475ba-b771-5e3f-ad9e-33799f191a9c" include("FluxSpecificFeatures.jl") @require ImageMagick="6218d12a-5da1-5696-b52f-db25d2ecc6d1" include("imagemagick.jl") @require Caesar="62eebf14-49bc-5f46-9df9-f7b7ef379406" include("services/ScatterAlignPlotting.jl") end @compile_workload begin # In here put "toy workloads" that exercise the code you want to precompile fg = generateGraph_Hexagonal() initAll!(fg) plotSLAM2D(fg) plotSLAM2D(fg; drawEllipse=true, drawContour=true) plotSLAM2D(fg; drawEllipse=true, drawContour=false) plotSLAM2D(fg; drawEllipse=true, drawContour=false, drawPoints=false) plotBelief(fg, ls(fg); dims=[1;2]) end end
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
18444
# new exports from this file, WIP export calcDyadScaleAdaptive export covEllipseParameterized, plotCovEllipseLayer export plotSLAM2D_KeyAndRef ## Src # draw the reference frame as a red-green dyad function addXYLineLayers!(pl, Xpp, Ypp, Thpp; l::Real=1.0, manualColor::Union{Nothing, AbstractString}=nothing ) lnstpr = [l;0.0;0.0] lnstpg = [0.0;l;0.0] Rd =SE2(lnstpr) Gr = SE2(lnstpg) for i in 1:length(Xpp) lnstt = [Xpp[i];Ypp[i];Thpp[i]] Ps = SE2(lnstt) lnr = se2vee(Ps*Rd) lng = se2vee(Ps*Gr) xsr = [Xpp[i];lnr[1]] ysr = [Ypp[i];lnr[2]] xsg = [Xpp[i];lng[1]] ysg = [Ypp[i];lng[2]] push!(pl.layers, layer(x=xsr, y=ysr, Geom.path(), Gadfly.Theme(default_color=parse(Colorant, manualColor === nothing ? "red" : manualColor), line_width=1.5pt))[1] ) push!(pl.layers, layer(x=xsg, y=ysg, Geom.path(), Gadfly.Theme(default_color=parse(Colorant, manualColor === nothing ? "green" : manualColor), line_width=1.5pt))[1] ) end nothing end """ $SIGNATURES Adaptively size the `dyadScale` value for plotSLAM2DPose. """ function calcDyadScaleAdaptive( Xpp::AbstractVector{<:Real}, Ypp::AbstractVector{<:Real}; scaling::Real=0.25) dists = diff(Xpp).^2 + diff(Ypp).^2 |> vec .|> sqrt scaling*Statistics.mean(dists) end """ $(SIGNATURES) 2D plot of all poses, assuming poses are labeled from ``::Symbol` type `:x0, :x1, ..., :xn`. Use `to` and `from` to limit the range of numbers `n` to be drawn. The underlying histogram can be enabled or disabled, and the size of maximum-point belief estimate cursors can be controlled with `spscale`. Future: - Relax to user defined pose labeling scheme, for example `:p1, :p2, ...` """ function plotSLAM2DPoses( fg::AbstractDFG; solveKey::Symbol=:default, regexPoses=r"x\d", from::Int=0, to::Int=(2^(Sys.WORD_SIZE-1)-1), variableList::AbstractVector{Symbol}=listVariablesLabelsWithinRange(fg, regexPoses, from=from, to=to), meanmax=:null, ppe=:suggested, recalcPPEs::Bool=false, lbls=true, scale::Real=1, x_off::Real=0, y_off::Real=0, drawhist=false, spscale::Union{Nothing, <:Real}=nothing, dyadScale::Union{Nothing, <:Real}=nothing, drawTriads::Bool=true, drawContour::Bool=true, levels::Int=1, contour::Union{Nothing, Bool}=nothing, line_width=1pt, drawPoints::Bool=true, pointsColor::AbstractString="gray30", drawEllipse::Bool=false, ellipseColor::AbstractString="gray30", manualColor=nothing ) # # deprecations if meanmax != :null @warn "plotSLAM2DPoses meanmax keyword is deprecated, use ppe=:suggested instead." ppe = meanmax end !(spscale isa Nothing) ? (dyadScale=spscale; @warn("keyword spscale is deprecated, use dyadScale instead")) : nothing !(contour isa Nothing) ? (drawContour=contour; @warn("keyword contour is being deprecated, use drawContour instead")) : nothing ## Use PPE.suggested Ppes = if recalcPPEs map(x->calcVariablePPE(fg, x, solveKey=solveKey), variableList) else getPPE.(fg, variableList, solveKey) end mask = Ppes .!== nothing variableList = variableList[mask] suggPpes = (x->getfield(x,ppe)).(Ppes[mask]) Xpp::Vector{Float64} = Float64.( (x->x[1]).(suggPpes) ) Ypp::Vector{Float64} = Float64.( (x->x[2]).(suggPpes) ) Thpp::Vector{Float64} = Float64.( (x->x[3]).(suggPpes) ) LBLS = string.(variableList) Xpp .+= x_off Ypp .+= y_off Xpp .*= scale Ypp .*= scale # adaptively scale dyad size dyadScale = dyadScale isa Nothing ? calcDyadScaleAdaptive(Xpp, Ypp) : dyadScale # lbls = lblsFromTo(1,length(Xpp)) psplt = Union{} thm = manualColor === nothing ? Theme(line_width=1pt) : Theme(line_width=line_width, default_color=parse(Colorant, manualColor)) if lbls psplt = Gadfly.plot( Gadfly.layer(x=Xpp,y=Ypp,label=LBLS,Geom.path(), thm, Geom.label), Coord.cartesian(fixed=true) ) else psplt = Gadfly.plot( Gadfly.layer(x=Xpp,y=Ypp,Geom.path(), thm),Coord.cartesian(fixed=true), Coord.cartesian(fixed=true) ) end # return psplt drawTriads && addXYLineLayers!(psplt, Xpp, Ypp, Thpp, l=dyadScale, manualColor=manualColor) if drawhist Xp,Yp = get2DPoseSamples(fg, from=from, to=to) push!(psplt.layers, Gadfly.layer(x=Xp, y=Yp, Geom.histogram2d)[1] )#(xbincount=100, ybincount=100)) end # add contours to pose estimates # varsyms = Symbol.(LBLS) if drawContour for vsym in variableList pln = plotKDE(fg, vsym, solveKey=solveKey, dims=[1;2], levels=levels, c=[(manualColor === nothing ? "gray90" : manualColor);]) union!(psplt.layers, pln.layers) end end # drawEllipse for vsym in variableList pln = plotCovEllipseLayer(fg, vsym, solveKey=solveKey, drawEllipse=drawEllipse,drawPoints=drawPoints,ellipseColor=ellipseColor,pointsColor=pointsColor) union!(psplt.layers, pln) end return psplt end """ $(SIGNATURES) 2D plot of landmarks, assuming `:l1, :l2, ... :ln`. Use `from` and `to` to control the range of landmarks `n` to include. """ function plotSLAM2DLandmarks( fg::AbstractDFG; solveKey::Symbol=:default, regexLandmark::Regex=r"l", from::Int=0, to::Int=(2^(Sys.WORD_SIZE-1)-1), minnei::Int=0, variableList::AbstractVector{Symbol}=listVariablesLabelsWithinRange(fg, regexLandmark, from=from, to=to), meanmax=:null, ppe::Symbol=:suggested, recalcPPEs::Bool=false, lbls=true,showmm=false, scale::Real=1, x_off::Real=0, y_off::Real=0, drawhist=false, drawContour::Bool=true, levels::Int=1, contour::Union{Nothing, Bool}=nothing, manualColor=nothing, c= manualColor===nothing ? "red" : manualColor, MM::Dict{Int,T}=Dict{Int,Int}(), point_size=1pt, drawPoints::Bool=true, pointsColor::AbstractString="gray30", drawEllipse::Bool=false, ellipseColor::AbstractString="gray30", resampleGaussianFit::Int=0 ) where T # if meanmax != :null @error "plotSLAM2DPoses meanmax keyword is deprecated, use ppe instead." ppe = meanmax end # remove before v0.10 !(contour isa Nothing) ? (drawContour=contour; @warn("keyword contour is being deprecated, use drawContour instead")) : nothing ## Use PPE.suggested Ppes = if recalcPPEs map(x->calcVariablePPE(fg, x, solveKey=solveKey), variableList) else getPPE.(fg, variableList, solveKey) end mask = Ppes .!== nothing variableList = variableList[mask] suggPpes = (x->getfield(x,ppe)).(Ppes[mask]) Xpp = (x->x[1]).(suggPpes) Ypp = (x->x[2]).(suggPpes) lbltags = string.(variableList) Xpp .+= x_off Ypp .+= y_off Xpp .*= scale Ypp .*= scale # Xp,Yp = get2DLandmSamples(fg, from=from, to=to) # Xpp = Float64[]; Ypp=Float64[]; Thpp=Float64[]; lblstags=String[]; # # TODO transition to new PPE.suggested # if meanmax==:mean # Xpp,Ypp, t, lbltags = get2DLandmMeans(fg, from=from, to=to, regexLandmark=regexLandmark) # elseif meanmax==:max # Xpp,Ypp, t, lbltags = get2DLandmMax(fg, from=from, to=to,showmm=showmm,MM=MM, regexLandmark=regexLandmark) # end psplt = if lbls Gadfly.plot( Gadfly.layer(x=Xpp,y=Ypp, label=lbltags, Geom.point, Theme(line_width=1pt, default_color=parse(Colorant,c), point_size=point_size), Geom.label), Coord.cartesian(fixed=true) # ,Gadfly.layer(x=Xp, y=Yp, Geom.histogram2d)#(xbincount=100, ybincount=100) ) else Gadfly.plot( Gadfly.layer(x=Xpp,y=Ypp, Geom.point, Theme(line_width=1pt, default_color=parse(Colorant,c), point_size=point_size)), Coord.cartesian(fixed=true) ) end if drawhist push!(psplt.layers, Gadfly.layer(x=Xpp, y=Ypp, Geom.histogram2d)[1]) #(xbincount=100, ybincount=100) end if drawContour # make pretty near Gaussian contours? if resampleGaussianFit != 0 # end varsyms = Symbol.(lbltags) for vsym in varsyms pln = plotKDE(fg, vsym, solveKey=solveKey, dims=[1;2], levels=levels, c=[(manualColor===nothing ? "gray90" : manualColor);]) union!(psplt.layers, pln.layers) end end # if drawEllipse for vsym in variableList pln = plotCovEllipseLayer(fg, vsym, solveKey=solveKey, drawEllipse=drawEllipse,drawPoints=drawPoints,ellipseColor=ellipseColor,pointsColor=pointsColor) union!(psplt.layers, pln) end psplt end """ $(SIGNATURES) 2D plot of both poses and landmarks contained in factor graph. Assuming poses and landmarks are labeled `:x1, :x2, ...` and `:l0, :l1, ...`, respectively. The range of numbers to include can be controlled with `from` and `to` along with other keyword functionality for manipulating the plot. Notes - Assumes `:l1`, `:l2`, ... for landmarks -- - Can increase default Gadfly plot size (for JSSVG in browser): `Gadfly.set_default_plot_size(35cm,20cm)`. - Enable or disable features such as the covariance ellipse with keyword `drawEllipse=true`. DevNotes - TODO update to use e.g. `tags=[:LANDMARK]`, - TODO fix `drawHist`, - TODO deprecate, `showmm`, `spscale`. Examples: ```julia fg = generateGraph_Hexagonal() plotSLAM2D(fg) plotSLAM2D(fg, drawPoints=false) plotSLAM2D(fg, contour=false, drawEllipse=true) plotSLAM2D(fg, contour=false, title="SLAM result 1") # or load a factor graph fg_ = loadDFG("somewhere.tar.gz") plotSLAM2D(fg_) ``` Related [`plotSLAM2DPoses`](@ref), [`plotSLAM2DLandmarks`](@ref), [`plotPose`](@ref), [`plotBelief`](@ref) """ function plotSLAM2D(fgl::AbstractDFG; solveKey::Symbol=:default, from::Int=0, to::Int=(2^(Sys.WORD_SIZE-1)-1), minnei::Int=0, meanmax=:null, posesPPE=:suggested, landmsPPE=:suggested, recalcPPEs::Bool=false, lbls=true, scale::Real=1, x_off::Real=0, y_off::Real=0, drawTriads::Bool=true, dyadScale::Union{Nothing, <:Real}=nothing, levels::Int=1, drawhist=false, MM::Dict{Int,T}=Dict{Int,Int}(), xmin=nothing, xmax=nothing, ymin=nothing, ymax=nothing, showmm=true, window::Union{Nothing, Tuple{Symbol, Real}}=nothing, point_size=4pt, line_width=1pt, regexLandmark=r"l\d+", regexPoses=r"x\d+", variableList::AbstractVector{Symbol}=union(listVariablesLabelsWithinRange(fgl, regexPoses, from=from, to=to), listVariablesLabelsWithinRange(fgl, regexLandmark, from=from, to=to)), manualColor = nothing, drawPoints::Bool = solveKey != :parametric, pointsColor::AbstractString="gray30", drawContour::Bool = solveKey != :parametric, drawEllipse::Bool=false, ellipseColor::AbstractString="gray30", title::AbstractString="", aspect_ratio::Real=1 ) where T # # xmin !== nothing && xmax !== nothing && xmin == xmax ? error("xmin must be less than xmax") : nothing ymin !== nothing && ymax !== nothing && ymin == ymax ? error("ymin must be less than ymax") : nothing p = plotSLAM2DPoses(fgl; solveKey, from, to, regexPoses, variableList=intersect(variableList, listVariablesLabelsWithinRange(fgl, regexPoses; from, to)), ppe=posesPPE, lbls, scale, x_off, y_off, drawhist, dyadScale, drawContour, drawTriads, manualColor, line_width, drawPoints, ellipseColor, pointsColor, drawEllipse, recalcPPEs ) # ll = listVariables(fgl, regexLandmark) if length(ll) > 0 pl = plotSLAM2DLandmarks( fgl; solveKey, from, to, regexLandmark, variableList=intersect(variableList, listVariablesLabelsWithinRange(fgl, regexLandmark; from, to)), ppe=landmsPPE, minnei, lbls, scale, x_off, y_off, drawhist, MM, showmm, point_size, drawContour, manualColor, drawPoints, ellipseColor, pointsColor, drawEllipse, recalcPPEs ) # for l in pl.layers push!(p.layers, l) end end if window !== nothing focusX = getPPE(fgl, window[1], solveKey).max # getKDEMax( getBelief(getVariable(fgl,window[1]),solveKey) ) pwind = window[2] p.coord = Coord.cartesian(xmin=focusX[1]-pwind,xmax=focusX[1]+pwind,ymin=focusX[2]-pwind,ymax=focusX[2]+pwind) end co = Coord.Cartesian(;xmin,xmax,ymin,ymax,aspect_ratio) p.coord = co if title != "" push!(p.guides, Guide.title(title)) end return p end function plotSLAM2DSubmaps( fgl::AbstractDFG, fromto::Array{Int,2}; m1hist=false, m2hist=false, m3hist=false, showmm=false, MM::Dict{Int,T} = Dict{Int,Any}(), xmin=nothing, xmax=nothing, ymin=nothing, ymax=nothing ) where T # p = plotSLAM2DLandmarks(fgl, from=fromto[1,1], to=fromto[1,2], drawhist=m1hist, showmm=showmm, MM=MM) if size(fromto,1) >1 p2 = plotSLAM2DLandmarks(fgl, from=fromto[2,1], to=fromto[2,2], drawhist=m2hist,c="blue", showmm=showmm, MM=MM) for l in p2.layers push!(p.layers, l) end end if size(fromto,1) >2 p3 = plotSLAM2DLandmarks(fgl, from=fromto[3,1], to=fromto[3,2], drawhist=m3hist,c="magenta", showmm=showmm, MM=MM) for l in p3.layers push!(p.layers, l) end end co = Coord.Cartesian(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax) p.coord = co return p end function plotSLAM2DSubmaps( fgl::G, fromto::Array{Int,1}; spread::Int=25, m1hist=false, m2hist=false, m3hist=false, showmm=false, MM::Dict{Int,T}=Dict{Int,Any}(), xmin=nothing, xmax=nothing, ymin=nothing, ymax=nothing ) where {G <: AbstractDFG, T} # ft = zeros(Int,length(fromto),2) for i in 1:length(fromto) ft[i,1] = fromto[i]-spread; ft[i,2] = fromto[i]+spread; end plotSLAM2DSubmaps(fgl, ft, m1hist=m1hist, m2hist=m2hist, m3hist=m3hist, showmm=showmm, MM=MM, xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax) end function plotSLAM2D_KeyAndRef(fg, solveKey=:default; refkey=:simulated, recalcPPEs=true) # pl_ = plotSLAM2D(fg, solveKey=refkey, drawContour=false, drawPoints=false, drawEllipse=false, manualColor="black", drawTriads=false); pl1 = plotSLAM2D(fg, solveKey=solveKey, recalcPPEs=recalcPPEs, drawContour=false, drawPoints=false, drawEllipse=false); union!(pl1.layers, pl_.layers); pl1 end # import RoMEPlotting: drawMarginalContour function plotMarginalContour( fgl::AbstractDFG, lbl::String; solveKey::Symbol=:default, xmin=-150,xmax=150,ymin=-150,ymax=150, n::Int=200 ) # p = getBelief(getVariable(fgl,Symbol(lbl)), solveKey) # p = getBelief(getVert(fgl,lbl)) Gadfly.plot(z=(x,y)->evaluateDualTree(p,vectoarr2([x,y]))[1], x=collect(range(xmin,stop=xmax,length=n)), y=collect(range(ymin,stop=ymax,length=n)), Geom.contour, Coord.Cartesian(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax), Guide.title(lbl) ) end # ┌ Warning: `Scale.color_none` to be deprecated. Instead use e.g. `plot(..., Geom.contour, color=[colorant"black"])` # └ @ Gadfly.Scale ~/.julia/packages/Gadfly/B5yQc/src/scale.jl:446 function accumulateMarginalContours(fgl, order; solveKey::Symbol=:default, xmin=-150,xmax=150,ymin=-150,ymax=150,n=200 ) # pl = plotMarginalContour(fgl, order[1],solveKey=solveKey, xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax,n=n) pl2 = nothing PL = [] for or in order[1:end] pl2 = plotMarginalContour(fgl, or, solveKey=solveKey, xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax,n=n) push!(PL, pl2) push!(pl.layers, pl2.layers[1]) end return pl, PL end #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
8418
""" $(SIGNATURES) Plot the proposal belief from neighboring factors to `lbl` in the factor graph (ignoring Bayes tree representation), and show with new product approximation for reference. DevNotes - TODO, standardize around ::MIME="image/svg", see JuliaRobotics/DistributedFactorGraphs.jl#640 """ function plotLocalProduct(fgl::AbstractDFG, lbl::Symbol; solveKey::Symbol=:default, N::Int=100, dims::Vector{Int}=Int[], levels::Int=1, show::Bool=false, dirpath="/tmp/", mimetype::AbstractString="svg", sidelength=20cm, title::String="Local product ($solveKey), ", xmin=nothing, xmax=nothing, ymin=nothing, ymax=nothing ) # @warn "not showing partial constraints, but included in the product" arr = Array{BallTreeDensity,1}() lbls = String[] push!(arr, getBelief(getVariable(fgl, lbl), solveKey)) push!(lbls, "curr") pl = nothing pp, parr, lb, sinfd = IIF.localProduct(fgl, lbl, N=N, solveKey=solveKey) partials = [] # another sanity check xmin !== nothing && xmax !== nothing && xmin == xmax ? error("xmin must be less than xmax") : nothing ymin !== nothing && ymax !== nothing && ymin == ymax ? error("ymin must be less than ymax") : nothing # helper functions function plotDirectProducts() if pp != parr[1] push!(arr,pp) push!(lbls, "prod") for a in parr push!(arr, a) end @show lb, lbls lbls = union(lbls, string.(lb)) end dims = length(dims) > 0 ? dims : collect(1:Ndim(pp)) colors = getColorsByLength(length(arr)) plotKDE(arr, dims=dims, levels=levels, c=colors, title=string(title,lbl), legend=string.(lbls)) # end function plotPartialProducts() # stack 1d plots to accomodate all the partials PL = [] lbls = String["prod";"curr";string.(lb)] pdims = sort(collect(keys(partials))) for dimn in pdims vals = partials[dimn] proddim = marginal(pp, [dimn]) colors = getColorsByLength(length(vals)+2) newbel_ = getBelief(getVariable(fgl, lbl),solveKey) newbel = newbel_ isa ManifoldKernelDensity ? newbel_.belief : newbel_ pl = plotKDE( [proddim;newbel;vals], dims=[1;], levels=levels, c=colors, title=string("Local product, dim=$(dimn), ",lbl)) push!(PL, pl) end Gadfly.vstack(PL...) end @show length(parr), length(partials) if length(parr) > 0 && length(partials) == 0 pl = plotDirectProducts() elseif length(parr) == 0 && length(partials) > 0 pl = plotPartialProducts() else return error("plotLocalProduct not built for lengths parr, partials = $(length(parr)), $(length(partials)) yet.") end # # set coordinates accordingly # co = Coord.Cartesian(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax) # pl.coord = co # now let's export: backend = getfield(Gadfly, Symbol(uppercase(mimetype))) Gadfly.draw(backend(dirpath*"test_$(lbl).$(mimetype)",sidelength,0.75*sidelength), pl) driver = mimetype in ["pdf"] ? "evince" : "eog" show ? (@async run(`$driver $(dirpath)test_$(lbl).$(mimetype)`)) : nothing return pl end """ $(SIGNATURES) Plot---for the cylindrical manifold only---the proposal belief from neighboring factors to `lbl` in the factor graph (ignoring Bayes tree representation), and show with new product approximation for reference. The linear and circular belief products are returned as a tuple. """ function plotLocalProductCylinder(fgl::G, lbl::Symbol; N::Int=100, levels::Int=1, show=false, dirpath="/tmp/", mimetype::AbstractString="svg", sidelength=30cm, scale::Float64=0.2 ) where G <: AbstractDFG # @warn "not showing partial constraints, but included in the product" arr = Array{BallTreeDensity,1}() carr = Array{BallTreeDensity,1}() lbls = String[] push!(arr, getBelief(getVariable(fgl, lbl))) push!(lbls, "curr") pl = nothing plc = nothing pp, parr, partials, lb = IncrementalInference.localProduct(fgl, lbl, N=N) if length(parr) > 0 && length(partials) == 0 if pp != parr[1] push!(arr, marginal(pp,[1])) push!(lbls, "prod") push!(carr, marginal(pp, [2])) for a in parr push!(arr, marginal(a,[1])) push!(carr, marginal(a,[2])) end lbls = union(lbls, lb) end colors = getColorsByLength(length(arr)) pll = plotKDE(arr, dims=[1;], levels=levels, c=colors, legend=lbls, title=string("Local product, ",lbl)) plc = AMP.plotKDECircular(carr, c=colors, scale=scale) # (pll, plc) elseif length(parr) == 0 && length(partials) > 0 # stack 1d plots to accomodate all the partials PL = [] PLC = [] lbls = ["prod";"curr";lb] pdims = sort(collect(keys(partials))) for dimn in pdims vals = partials[dimn] proddim = marginal(pp, [dimn]) colors = getColorsByLength(length(vals)+2) if dimn == 1 pll = plotKDE([proddim;getBelief(getVariable(fgl, lbl));vals], dims=[1;], levels=levels, c=colors, title=string("Local product, dim=$(dimn), ",lbl)) push!(PL, pl) else plc = AMP.plotKDECircular([proddim; marginal(getBelief(getVariable(fgl, lbl)),[2]);vals], c=colors, scale=scale) push!(PLC, plc) end end pl = Gadfly.vstack(PL..., PLC...) else return error("plotLocalProduct not built for lengths parr, partials = $(length(parr)), $(length(partials)) yet.") end # now let's export: # backend = getfield(Gadfly, Symbol(uppercase(mimetype))) # Gadfly.draw(backend(dirpath*"test_$(lbl).$(mimetype)",sidelength,sidelength), pl) # driver = mimetype in ["pdf"] ? "evince" : "eog" # show ? (@async run(`$driver $(dirpath)test_$(lbl).$(mimetype)`)) : nothing return pll, plc end """ $SIGNATURES Plot the proposal belief from neighboring factors to `lbl` in the factor graph (ignoring Bayes tree representation), and show with new product approximation for reference. String version is obsolete and will be deprecated. """ plotLocalProduct(fgl::AbstractDFG, lbl::AbstractString; N::Int=100, dims::Vector{Int}=Int[] ) = plotLocalProduct(fgl, Symbol(lbl), N=N, dims=dims) """ $SIGNATURES Development function to plot the same variable from both factor graphs together. """ function plotPairVariables(dfg1::G1, dfg2::G2, sym::Symbol; dims=nothing, levels::Int=3, title::String="") where {G1 <: AbstractDFG, G2 <: AbstractDFG} # X1 = getBelief(dfg1, sym) X2 = getBelief(dfg2, sym) plotKDE([X1;X2], c=["black";"red"], legend=["dfg1";"dfg2"], dims=dims, levels=levels, title=title*" $sym") end function plotPairPose2(dfg1::G1, dfg2::G2, sym::Symbol; dims=nothing, levels::Int=3, title::String="") where {G1 <: AbstractDFG, G2 <: AbstractDFG} # X1 = getBelief(dfg1, sym) X2 = getBelief(dfg2, sym) plotPose(Pose2(), [X1;X2], title*" $sym", c=["black";"red"], levels=levels) # , legend=["dfg1";"dfg2"] end """ $SIGNATURES Plot new proposal (convolution) for factor x of variable y given all other -- i.e. y|X Notes - plot new result on `towards` as first color. - Plot other variables in factor on 2nd to m colors. """ function plotVariableGivenFactor(dfg::G, fct::Symbol, towards::Symbol; levels::Int=2, dims=nothing ) where G <: AbstractDFG # pts = approxConv(dfg,fct,towards) mani = getManifold(dfg, towards) res = manikde!(mani, pts) lie = ls(dfg, fct) setdiff!(lie, [towards]) otr = map(x->getBelief(dfg,x),lie) lbls = string.([towards;lie]) pl = plotKDE([res;otr],dims=dims,levels=levels,legend=lbls) return pl end #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
602
@info "RoMEPlotting.jl is loading tools based on ImageMagick.jl" using .ImageMagick export makeImage """ $SIGNATURES Use PNG from Cairo and Fontconfig to convert a Gadfly plot into a Julia Images style matrix. Example ```julia pl = Gadlfy.plot(y=randn(10), Geom.line) makeImage(pl) ``` See also: [`toFormat`](@ref) """ function makeImage(pl::Gadfly.Plot) buf = IOBuffer() pl |> PNG(buf) plbytes = take!(buf) ImageMagick.readblob(plbytes) end # deprecate before RoME v0.18.0 import Base: convert @deprecate convert(::Type{<:AbstractArray{<:Color, 2}}, pl::Gadfly.Plot) makeImage(pl) #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
2616
plotBelief(mkd::ManifoldKernelDensity,w...;kw...) = plotKDE(mkd.belief, w...;kw...) plotBelief(arr::AbstractVector{<:ManifoldKernelDensity},w...;kw...) = plotKDE((x->x.belief).(arr), w...;kw...) """ $(SIGNATURES) A peneric KDE plotting function that allows marginals of higher dimensional beliefs and various keyword options. Example for `Position2`: ----------------------- ```julia p = manikde!(Position2, [randn(2) for _ in 1:100]) q = manikde!(Position2, [randn(2).+[5;0] for _ in 1:100]) plotBelief(p) plotBelief(p, dims=[1;2], levels=3) plotBelief(p, dims=[1]) plotBelief([p;q]) plotBelief([p;q], dims=[1;2], levels=3) plotBelief([p;q], dims=[1]) ``` Example for `Pose2`: -------------------- ```julia # TODO ``` """ function plotBelief(fgl::AbstractDFG, sym::Symbol; solveKey::Symbol=:default, dims=nothing, title="", levels::Int=5, fill::Bool=false, layers::Bool=false, c=nothing, overlay=nothing ) # p = getBelief(getVariable(fgl,sym), solveKey) # mmarg = length(marg) > 0 ? marg : collect(1:Ndim(p)) # mp = marginal(p,mmarg) bel = p isa BallTreeDensity ? p : p.belief plotKDE(bel, levels=levels, dims=dims, title=string(sym, " ", title), fill=fill, layers=layers, c=c, overlay=overlay ) end function plotBelief(fgl::AbstractDFG, syms::AbstractVector{Symbol}; solveKey::Symbol=:default, addt::Union{<:AbstractVector{<:BallTreeDensity},AbstractVector{<:ManifoldKernelDensity}}=BallTreeDensity[], dims=nothing, title=nothing, levels=3, layers::Bool=false, c=getColorsByLength(length(syms)), overlay=nothing ) # # TODO -- consider automated rotisary of color # colors = ["black";"red";"green";"blue";"cyan";"deepskyblue"; "yellow"] # COLORS = repmat(colors, 10) # COLORS = getColorsByLength(length(syms)) MP = BallTreeDensity[] LEG = String[] # mmarg = Int[] for sym in syms p = getBelief(getVariable(fgl,sym), solveKey) # mmarg = length(marg) > 0 ? marg : collect(1:Ndim(p)) # mp = marginal(p,mmarg) if p isa BallTreeDensity push!(MP, p) else push!(MP, p.belief) end push!(LEG, string(sym)) end for p in addt # mp = marginal(p,mmarg) push!(MP, p) push!(LEG, "add") end plotKDE(MP; c, levels, dims, legend=LEG, title, layers, overlay) end #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
3097
""" $SIGNATURES Calculate the ellipse from covariance matrix and return as lambda function. Notes - https://cookierobotics.com/007/ Related plotCovEllipseLayer """ function covEllipseParameterized(distr::MvNormal; meanOffset::Bool=true) # println(round.(cov(distr), digits=3) ) a = cov(distr)[1,1] b = cov(distr)[1,2] + cov(distr)[2,1] b *= 0.5 c = cov(distr)[2,2] λ1 = 0.5*(a+c) + sqrt(0.25*(a-c)^2 + b^2) λ2 = 0.5*(a+c) - sqrt(0.25*(a-c)^2 + b^2) θ = if b ≈ 0 && a >= c 0 elseif b ≈ 0 && a < c pi/2 else atan(λ1-a, b) end sλ1 = sqrt(λ1) sλ2 = sqrt(λ2) sθ = sin(θ) cθ = cos(θ) ox = meanOffset ? distr.μ[1] : 0 oy = meanOffset ? distr.μ[2] : 0 (t) -> [sλ1*cθ*cos(t)-sλ2*sθ*sin(t)+ox; sλ1*sθ*cos(t)+sλ2*cθ*sin(t)+oy] end covEllipseParameterized(pts::Array{Float64,2}; meanOffset::Bool=true) = covEllipseParameterized( fit(MvNormal, pts), meanOffset=meanOffset ) covEllipseParameterized(X::Union{<:BallTreeDensity,<:ManifoldKernelDensity}; meanOffset::Bool=true) = covEllipseParameterized( getPoints(X), meanOffset=meanOffset ) covEllipseParameterized(dfg::AbstractDFG, sym::Symbol; meanOffset::Bool=true, solveKey::Symbol=:default) = covEllipseParameterized( getBelief(dfg, sym, solveKey), meanOffset=meanOffset, solveKey=solveKey ) """ $SIGNATURES Plotting tool to draw Gadfly layers of ellipses of 2D covariance fitted to the belief of factor graph variable nonparametric points. Related covEllipseParameterized, plotSLAM2DPosesLandms """ function plotCovEllipseLayer( dfg::AbstractDFG, vsym::Symbol; solveKey::Symbol=:default, drawPoints::Bool=true, ellipseColor::AbstractString="gray30", pointsColor::AbstractString="gray30", drawEllipse::Bool=true ) # PL = [] if !(drawEllipse || drawPoints) return PL end # points to work from bel = getBelief(dfg, vsym, solveKey) pp__ = getPoints(bel) pp_ = if bel.manifold isa SpecialEuclidean # assume Pose2 (x->submanifold_component(x,1)).(pp__) else # assume Point2 pp__ end @cast pp[i,j] := pp_[j][i] if drawEllipse # get ellipse function eX = covEllipseParameterized(pp[1:2,:], meanOffset=false) vEl = eX.(0:0.02:2pi) el = [(x->x[1]).(vEl) (x->x[2]).(vEl)] # add suggested PPE mean offset el[:,1] .+= getVariablePPE(dfg, vsym, solveKey).suggested[1] el[:,2] .+= getVariablePPE(dfg, vsym, solveKey).suggested[2] # add the ellipse layers plelX2 = Gadfly.layer(x=el[:,1], y=el[:,2], Geom.path, Theme(default_color=parse(Colorant, ellipseColor))) push!(PL, plelX2[1]) end # add the points layer if needed if drawPoints plelX1 = Gadfly.layer(x=pp[1,:], y=pp[2,:], Geom.point, Theme(default_color=parse(Colorant, pointsColor), point_size=1pt)) # push!(PL, plelX1[1]) end return PL end
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
4490
# plotPose functions """ $SIGNATURES Plot pose belief as contour information on visually sensible manifolds. Example: ```julia fg = generateGraph_ZeroPose() initAll!(fg); plotPose(fg, :x0) ``` Related [`plotSLAM2D`](@ref), [`plotSLAM2DPoses`](@ref), [`plotBelief`](@ref), `plotKDECircular` """ function plotPose(::IIF.InstanceType{Pose2}, pp::AbstractVector{<:BallTreeDensity}, title="plotPose2"; levels=3, c=nothing, legend=nothing, axis=nothing, scale::Real=0.2, overlay=nothing, hdl=[] ) # # ops = buildHybridManifoldCallbacks(pt.manifolds) # @show ran = getKDERange(p, addop=ops[1], diffop=ops[2]) ran = axis === nothing ? getKDERange(pp) : axis p1 = plotKDE(pp, dims=[1;2], levels=levels, c=c, axis=ran ) # p2 = plotKDE(bels, dims=[3], c=c) cc = c === nothing ? getColorsByLength(length(pp)) : c GG = BallTreeDensity[] for ppc in pp gg = marginal(ppc,[3]) # gg = (x)->pc(reshape([x], :,1))[1] push!(GG, gg) end # p2 = AMP.plotCircBeliefs(GG, c=cc) p2 = AMP.plotKDECircular(GG, scale=scale, c=cc, legend=legend, title=title) # deal with overlay push!(hdl, p1) push!(hdl, p2) Gadfly.hstack(p1,p2) end plotPose(pt::IIF.InstanceType{Pose2}, bds::AbstractVector{<:ManifoldKernelDensity}, w...;kw...) = plotPose(pt, (s->s.belief).(bds), w...; kw...) function plotPose(pt::IIF.InstanceType{Pose2}, pp::Union{<:BallTreeDensity,<:ManifoldKernelDensity}, title="plotPose2"; kw... ) # plotPose(pt, [pp;],title; kw... ) end function plotPose(::DynPose2, bels::Union{<:AbstractVector{<:BallTreeDensity},<:AbstractVector{<:ManifoldKernelDensity}}, title; levels::Int=5, c=nothing, axis=nothing, hdl=[], scale::Real=0.2 ) # p1 = plotKDE(bels, dims=[1;2], levels=levels, c=c, title=title) p2 = plotKDE(bels, dims=[3], c=c) p3 = plotKDE(bels, dims=[4;5], levels=levels, c=c) push!(hdl, p1) push!(hdl, p2) push!(hdl, p3) Gadfly.vstack(p1,p2,p3) end # import RoMEPlotting: plotPose function plotPose(::Pose3, bels::Union{<:AbstractVector{<:BallTreeDensity},<:AbstractVector{<:ManifoldKernelDensity}}, title; levels::Int=5, c=nothing, axis=nothing, hdl=[], scale::Real=0.2 ) # @show title p1 = plotKDE(bels, dims=[1;2], levels=levels, c=c, title=title) p2 = plotKDE(bels, dims=[3], c=c) p3 = plotKDE(bels, dims=[4;5], levels=levels, c=c) p4 = plotKDE(bels, dims=[6], c=c) push!(hdl, p1) push!(hdl, p2) push!(hdl, p3) push!(hdl, p4) Gadfly.vstack(p1,p2,p3,p4) end """ $(SIGNATURES) Example: pl = plotPose(fg, [:x1; :x2; :x3]) """ function plotPose(fgl::AbstractDFG, syms::Vector{Symbol}; solveKey::Symbol=:default, levels::Int=5, c=nothing, axis=nothing, scale::Real=0.2, show::Bool=false, filepath::AbstractString="/tmp/tempposeplot.svg", app::AbstractString="eog", hdl=[] ) # typ = getSolverData(getVariable(fgl, syms[1]), solveKey).variableType pt = string(string.(syms)...) getvertsgg = (sym) -> getBelief(getVariable(fgl, sym), solveKey) pl = plotPose(typ, getvertsgg.(syms), pt, levels=levels, c=c, axis=axis, scale=scale, hdl=hdl ) if length(filepath) > 0 ext = split(filepath, '.')[end] cmd = getfield(Gadfly,Symbol(uppercase(ext))) h = 1*7Gadfly.cm if typ == DynPose2 h *= 1.5 end Gadfly.draw(cmd(filepath,15Gadfly.cm,h),pl) @async !show ? nothing : run(`$app $filepath`) end return pl end function plotPose(fgl::AbstractDFG, sym::Symbol; levels::Int=5, c=nothing, axis=nothing, scale::Real=0.2, show::Bool=false, filepath::AbstractString="/tmp/tempposeplot.svg", app::AbstractString="eog", hdl=[] ) # plotPose(fgl, [sym;], levels=levels, axis=axis, show=show, filepath=filepath, app=app, hdl=hdl ) end
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
4934
""" $(SIGNATURES) Draw the upward belief from clique `cllb::Symbol` message on variable `lb::Symbol`. Example: ```julia plotUpMsgsAtCliq(tree, :x2, :x1) ``` Related plotKDE, getUpMsgs """ function plotUpMsgsAtCliq(treel::AbstractBayesTree, cllb::Symbol, lb::Symbol; show::Bool=true, w=20cm, h=15cm, levels::Int=1, dims::Union{Vector{Int}, Nothing}=nothing ) # cliq = getClique(treel, cllb) cliqoutmsg = getUpMsgs(cliq) bel = convert(BallTreeDensity, cliqoutmsg.belief[lb]) plotKDE(bel, dims=dims) end function plotTreeUpwardMsgs(fgl::G, bt::AbstractBayesTree; N=300 ) where G <: AbstractDFG # len = length(bt.cliques)-1 vv = Array{Gadfly.Compose.Context,1}(undef, len) #r = Array{RemoteRef,1}(len) i = 0 for cliq in bt.cliques if cliq[1] == 1 println("No upward msgs from root."); continue; end @show cliq[2].attributes["label"] i+=1 vv[i] = drawHorDens(fgl, cliq[2].attributes["debug"].outmsg.p, N) end vv end """ $SIGNATURES Project (convolve) to and take product of variable in Bayes/Junction tree. Notes - assume cliq and var sym the same, unless both specified. - `cliqsym` defines a frontal variable of a clique. """ function plotTreeProductUp(fgl::G, treel::AbstractBayesTree, cliqsym::Symbol, varsym::Symbol=cliqsym; levels::Int=1, dims::Vector{Int}=Int[] ) where G <: AbstractDFG # # build a subgraph copy of clique cliq = getClique(treel, cliqsym) syms = getCliqAllVarIds(cliq) subfg = buildSubgraph(fgl, syms) # add upward messages to subgraph msgs = fetchMsgsUpChildren(treel,cliq, TreeBelief) # @show typeof(msgs) addMsgFactors!.(subfg, msgs, IIF.UpwardPass) # predictBelief cllbl = cliq.attributes["label"] return plotLocalProduct(subfg, varsym, title="Tree Up $(cllbl) | ", levels=levels, dims=dims) end function plotTreeProductDown( fgl::AbstractDFG, treel::AbstractBayesTree, cliqsym::Symbol, varsym::Symbol=cliqsym; levels::Int=1 ) # # build a subgraph copy of clique cliq = whichCliq(treel, cliqsym) syms = getCliqAllVarIds(cliq) subfg = buildSubgraphFromLabels!(fgl,syms) # add upward messages to subgraph msgs = getCliqParentMsgDown(treel,cliq) addMsgFactors!(subfg, msgs) # predictBelief cllbl = cliq.attributes["label"] return plotLocalProduct(subfg, varsym, title="Tree Dwn $(cllbl) | ", levels=levels) end """ $SIGNATURES Overlay plot all upward messages from cliques. """ function plotCliqUpMsgs(fg::G, tree::AbstractBayesTree, sym::Symbol; show::Bool=true, dims::Vector{Int}=Int[], levels::Int=1, c=nothing, title="up msgs on $(sym)" ) where G <: AbstractDFG # # get all msgs allmsgs = getTreeCliqUpMsgsAll(tree) # stack messages by variable sckmsgs = stackCliqUpMsgsByVariable(tree, allmsgs) if !haskey(sckmsgs, sym) @warn "plotCliqUpMsgs -- tree does not have up messages for $sym." return nothing end # prepend current estimate too Xs = getBelief(fg, sym) # vectorize beliefs beliefs = BallTreeDensity[Xs;] lbls = String["curr,-1";] for msg in sckmsgs[sym] push!(beliefs, msg.belief) push!(lbls, "$(msg.cliqId),$(msg.depth)") end # ignoring legend and color information cc = c === nothing ? getColorsByLength(length(beliefs)) : c # plot and return plotKDE(beliefs, levels=levels, c=cc, title=title, legend=lbls) end """ $SIGNATURES Plot the downward messages currently stored in a clique. """ function plotCliqDownMsgs(tree::AbstractBayesTree, frnt::Symbol; show::Bool=true, levels::Int=2, dims=nothing, existing=nothing ) # cliq = getClique(tree,frnt) msgs = IIF.getMessageBuffer(cliq).downRx.belief PL = [] for (key, beldim) in msgs npl = plotKDE(manikde!(beldim.varType, beldim.val), levels=levels, title="dwn msg $key", dims=dims) existing === nothing ? nothing : union!(npl.layers, existing.layers) push!(PL, npl) end existing === nothing ? nothing : push!(PL, existing) pl = vstack(PL...) folderpath = "/tmp/caesar/random/" filepath = folderpath*"downmsgs_cliq$(cliq.index).pdf" Base.mkpath(folderpath) pl |> PDF(filepath, 20cm, length(PL)*12cm) @async run(`evince $filepath`) pl end #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
1381
@info "RoMEPlotting.jl is including ScatterAlign tools associated with Caesar.jl." using .Gadfly export plotScatterAlign """ $SIGNATURES Plot name tuple output from [`overlayScatter`](@ref) See also: [`overlayScatterMutate`](@ref) """ function plotScatterAlign(snt::NamedTuple; title::String="") N = size(snt.pP1,2) pP1 = Gadfly.layer(x=snt.pP1[1,:],y=snt.pP1[2,:],color=[1;zeros(N-1)]) qP2 = Gadfly.layer(x=snt.qP2[1,:],y=snt.qP2[2,:],color=[0;ones(N-2);2]) pP2_u = Gadfly.layer(x=snt.pP2_u[1,:],y=snt.pP2_u[2,:],color=[0;2*ones(N-1)]) pP2_b = Gadfly.layer(x=snt.pP2_b[1,:],y=snt.pP2_b[2,:],color=[0;2*ones(N-1)]) uo = haskey(snt, :user_offset) ? "$(round.(snt.user_offset, digits=3))" : "" ar = Gadfly.Coord.cartesian(; aspect_ratio=1) H1 = Gadfly.plot(pP1, qP2, ar, Guide.title("body frame data."*title)) H2 = Gadfly.plot(pP1, pP2_u, ar, Guide.title("User transform: $(round.(snt.user_coords,digits=3))\nu_score=$(snt.u_score)")) H3 = Gadfly.plot(pP1, pP2_b, ar, Guide.title("Best fit: $(snt.best_coords)\nb_score=$(snt.b_score)")) hstack(H1,H2, H3) end plotScatterAlign( sap::ScatterAlignPose2; sample_count::Integer = sap.align.sample_count, bw::Real = sap.align.bw, kw... ) = plotScatterAlign(overlayScatterMutate(sap; sample_count, bw); kw...) # #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
913
using Test using KernelDensityEstimatePlotting using IncrementalInference using RoME using RoMEPlotting ## include("testPose2Point2Plotting.jl") include("testPlotKDE.jl") include("testPlotSLAMandPose.jl") # @warn "plotMCMC needs ImageMagick on osx, not running test yet." # plotMCMC(tree, :x1, show=false) # println("Success") # test ellipse function # Z = MvNormal([0.0;0],[9.0 5; 5 4]) # eX = covEllipseParameterized(Z) ## legacy # println("[TEST] with local Graphs.jl dictionary and arrays only (multicore)...") # include(joinpath(dirname(@__FILE__),"..","..","IncrementalInference","test","fourdoortest.jl")) # println("Success") # # println("[TEST] plot functions...") # using Gadfly # # draw all beliefs # DOYTICKS = false # xx,ll = ls(fg) # msgPlots = drawHorBeliefsList(fg, xx, gt=gt,nhor=2); # pl = vstack(msgPlots...); # # Gadfly.draw(PDF("/tmp/test.pdf",15cm,30cm),pl) # println("Success")
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
391
# test multi kde plot, issue 65 using RoME, RoMEPlotting using Test # Gadfly.set_default_plot_size(35cm, 25cm) @testset "test plotKDE array (issue 65)" begin fg = initfg() addVariable!(fg, :x0, ContinuousScalar) addVariable!(fg, :x1, ContinuousScalar) addFactor!(fg, [:x0], Prior(Normal())) addFactor!(fg, [:x0;:x1], LinearRelative(Normal())) initAll!(fg) plotKDE(fg, ls(fg)) end
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
3496
# test plotSLAM2D and plotPose features using RoME, RoMEPlotting using Test ## @testset "test plotSLAM2D features" begin ## fg = generateGraph_Hexagonal() plotSLAM2D(fg, drawhist=false, drawPoints=false, drawContour=false, drawEllipse=false) plotSLAM2D(fg, drawhist=false, drawPoints=false, drawContour=false, drawEllipse=true) plotSLAM2D(fg, drawhist=false, drawPoints=false, drawContour=true, drawEllipse=false) plotSLAM2D(fg, drawhist=false, drawPoints=false, drawContour=true, drawEllipse=true) plotSLAM2D(fg, drawhist=false, drawPoints=true, drawContour=false, drawEllipse=false) plotSLAM2D(fg, drawhist=false, drawPoints=true, drawContour=false, drawEllipse=true) plotSLAM2D(fg, drawhist=false, drawPoints=true, drawContour=true, drawEllipse=false) plotSLAM2D(fg, drawhist=false, drawPoints=true, drawContour=true, drawEllipse=true) plotSLAM2D(fg, drawhist=true, drawPoints=false, drawContour=false, drawEllipse=false) plotSLAM2D(fg, drawhist=true, drawPoints=false, drawContour=false, drawEllipse=true) plotSLAM2D(fg, drawhist=true, drawPoints=false, drawContour=true, drawEllipse=false) plotSLAM2D(fg, drawhist=true, drawPoints=false, drawContour=true, drawEllipse=true) plotSLAM2D(fg, drawhist=true, drawPoints=true, drawContour=false, drawEllipse=false) plotSLAM2D(fg, drawhist=true, drawPoints=true, drawContour=false, drawEllipse=true) plotSLAM2D(fg, drawhist=true, drawPoints=true, drawContour=true, drawEllipse=false) plotSLAM2D(fg, drawhist=true, drawPoints=true, drawContour=true, drawEllipse=true) plotSLAM2D(fg; variableList=[:x1;:x5;:l1]) # plot runs but doesnt draw the levels at time of wrting the test. Good to test the API regardless. plotSLAM2D(fg, drawhist=false, drawPoints=true, drawContour=true, drawEllipse=false, levels=5) ## test with save and load of factor graph saveDFG("/tmp/rp_test", fg) fg_ = loadDFG("/tmp/rp_test.tar.gz") plotSLAM2D(fg, drawhist=false, drawPoints=true, drawContour=true, drawEllipse=false, levels=5) # plotSLAM2D(fg_, drawhist=true, drawPoints=true, drawContour=true, drawEllipse=true) # gets deleted lower down # Base.rm("/tmp/rp_test.tar.gz") ## end @testset "test CJL Docs example with plotSLAM2DPoses" begin ## fg = generateGraph_Hexagonal() # Draw the (x,y) marginal estimated belief contour for :x0, :x2, and Lx4 pl = plotKDE(fg, [:x0; :x2; :x4], c=["red";"green";"blue"], levels=2, dims=[1;2]) # add a few fun layers pl3 = plotSLAM2DPoses(fg, regexPoses=r"x\d", from=3, to=3, drawContour=false, drawEllipse=true) pl5 = plotSLAM2DPoses(fg, regexPoses=r"x\d", from=5, to=5, drawContour=false, drawEllipse=true, drawPoints=false) pl_ = plotSLAM2DPoses(fg, drawContour=false, drawPoints=false, dyadScale=0.001, to=5) union!(pl.layers, pl3.layers) union!(pl.layers, pl5.layers) union!(pl.layers, pl_.layers) # change the plotting coordinates pl.coord = Coord.Cartesian(xmin=-10,xmax=20, ymin=-1, ymax=25) # save the plot to SVG and giving dedicated (although optional) sizing pl |> SVG("/tmp/test.svg", 25cm, 15cm) Base.rm("/tmp/test.svg") ## end ## @testset "test plotPose features" begin ## fg = generateGraph_Hexagonal() X1 = getBelief(fg, :x1) plotPose(Pose2, X1) plotPose(fg, :x1) plotPose(fg, :x1, levels=1, scale=0.3) plotPose(fg, [:x1;:x2], levels=2, c=["green"; "magenta"]) @warn "fix plotPose legend keyword" # plotPose(fg, [:x1;:x2], levels=2, c=["green"; "magenta"], legend=["hello"; "world"]) ## fg_ = loadDFG("/tmp/rp_test.tar.gz") Base.rm("/tmp/rp_test.tar.gz") plotPose(fg, :x1) ## end
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
code
2123
# test Pose2DPoint2D constraint evaluation function using LinearAlgebra, Statistics using RoME # using KernelDensityEstimate using RoMEPlotting, Gadfly using Test # to export PDF using Gadfly using Cairo ## @testset "Prepare a 2D factor graph with poses and points..." begin ## N = 100 fg = initfg() initCov = Matrix(Diagonal([0.03;0.03;0.001])) odoCov = Matrix(Diagonal([3.0;3.0;0.01])) # Some starting position addVariable!(fg, :x0, Pose2, N=N) initPosePrior = PriorPose2(MvNormal(zeros(3), initCov)) addFactor!(fg,[:x0], initPosePrior) # and a second pose addVariable!(fg, :x1, Pose2, N=N) ppc = Pose2Pose2(MvNormal([50.0;0.0;pi/2], odoCov)) addFactor!(fg, [:x0; :x1], ppc) # test evaluation of pose pose constraint pts = approxConv(fg, :x0x1f1, :x1) # perform inference tree = solveTree!(fg) # check that yaw is working addVariable!(fg, :x2, Pose2, N=N) ppc = Pose2Pose2(MvNormal([50.0;0.0;0.0], odoCov)) addFactor!(fg, [:x1;:x2], ppc) # new landmark l1 = addVariable!(fg, :l1, Point2, N=N) # and pose to landmark constraint rhoZ1 = norm([10.0;0.0]) ppr = Pose2Point2BearingRange{Uniform, Normal}(Uniform(-pi,pi),Normal(rhoZ1,1.0)) addFactor!(fg, [:x0;:l1], ppr) # add a prior to landmark pp2 = PriorPoint2(MvNormal([10.0;0.0], Matrix(Diagonal([1.0;1.0])))) f5 = addFactor!(fg,[:l1], pp2) # do inference tree = solveTree!(fg) println("test Pose2D plotting") plotSLAM2DPoses(fg); plotSLAM2DLandmarks(fg); plotSLAM2D(fg); p1 = getBelief(fg, :l1) # pts = getVal(fg, :l1) # p1= kde!(pts) p1c = getBelief(fg, :x0) plotBelief( p1 , dimLbls=["x";"y";"z"]) # |> PDF("/tmp/test.pdf") plotBelief( [p1c;p1] , dimLbls=["x";"y";"z"],c=["red";"black"],levels=3, dims=[1;2]) # plotBelief( [marginal(p1c,[1;2]);marginal(p1,[1;2])] , dimLbls=["x";"y";"z"],c=["red";"black"],levels=3, dims=[1;2]) p1c = deepcopy(p1) plotBelief( marginal(getBelief(getVariable(fg, :x2)),[1;2]) , dimLbls=["x";"y";"z"]) axis = [[1.5;3.5]';[-1.25;1.25]';[-1.0;1.0]'] # @warn "Reinsert draw test.pdf" plotBelief( p1, dimLbls=["x";"y";"z"], axis=axis) |> PDF("/tmp/test.pdf",30cm,20cm) # Base.rm("/tmp/test.pdf") ## end #
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
docs
283
## Changes in v0.9 - Standardize to `plotBelief` instead of previous `plotKDE`, see JuliaRobotics/Caesar.jl#811 - Major refactor of code placement in src files -- ongoing work through multiple versions. (2022Q1): Starting to individually list larger change in the NEWS.md file.
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.10.4
63b213d3870dd87ac49244815fc6d2fc97ec8d67
docs
1545
# RoMEPlotting.jl Release v0.10 | Dev | Test Coverage | Caesar Docs --------------|-----|---------------|-------------- [![build-0-10]][CI-url] | [![build-dev]][CI-url] | [![codecov-img]][codecov-url] | [![docs][docs-shield]][caesar-docs] 2D plotting functionality for the RoME.jl package (presently only using Gadfly). This package is part of the [Caesar.jl](http://www.github.com/JuliaRobotics/Caesar.jl) suite of tools. This package contains all the plotting functions relating to the [IncrementalInference.jl](http://www.github.com/JuliaRobotics/IncrementalInference.jl) and [RoME.jl](http://www.github.com/JuliaRobotics/RoME.jl) packages. # Installation This is a registered package: ``` julia> ] # switch to package manager pkg> add RoMEPlotting ``` # Usage Example Documentation for this package will be covered in the plotting section of [Caesar.jl Docs](https://juliarobotics.org/Caesar.jl/latest/) [CI-url]: https://github.com/JuliaRobotics/RoMEPlotting.jl/actions/workflows/ci.yml [build-0-10]: https://github.com/JuliaRobotics/RoMEPlotting.jl/actions/workflows/ci.yml/badge.svg?branch=release%2Fv0.10 [build-dev]: https://github.com/JuliaRobotics/RoMEPlotting.jl/actions/workflows/ci.yml/badge.svg?branch=master [codecov-url]: https://codecov.io/github/JuliaRobotics/RoMEPlotting.jl?branch=master [codecov-img]: https://codecov.io/github/JuliaRobotics/RoMEPlotting.jl/coverage.svg?branch=master [docs-shield]: https://img.shields.io/badge/docs-latest-blue.svg [caesar-docs]: https://juliarobotics.org/Caesar.jl/latest/
RoMEPlotting
https://github.com/JuliaRobotics/RoMEPlotting.jl.git
[ "MIT" ]
0.15.1
1370f8202dac30758f3c345f9909b97f53d87d3f
code
3066
module Lazy ############ # Utilities ############ include("macros.jl") include("dynamic.jl") include("tail.jl") export @listable import Base: *, ==, +, - macro listable(f) if typeof(f) == Expr && f.head == :tuple return Expr(:block, [:(@listable $f) for f in f.args]...) end f = esc(f) :($f(l1::List, ls::List...) = map($f, l1, ls...)) end ######## # Types ######## import Base: isempty, first export List, list, @lazy, prepend, tail abstract type List end mutable struct EmptyList <: List end mutable struct LinkedList <: List head tail::List end mutable struct LazyList <: List list::List realised::Bool f::Function LazyList(f) = new(EmptyList(), false, f) end # Empty List first(::EmptyList) = nothing tail(l::EmptyList) = l isempty(::EmptyList) = true # Lists prepend(x, l::List) = LinkedList(x, l) (::Colon)(x, xs::List) = prepend(x, xs) (::Colon)(x::List, xs::List) = prepend(x, xs) # special case: prepend list (::Colon)(x::T, y, xs::T) where T<:List = prepend(x, prepend(y, xs)) (::Colon)(x, y, xs::List) = x:prepend(y,xs) list() = EmptyList() list(x, xs...) = x:list(xs...) first(l::LinkedList) = l.head tail(l::LinkedList) = l.tail isempty(::LinkedList) = false # Lazy Lists function realise!(xs::LazyList) xs.realised && return xs.list xs.realised = true xs.list = xs.f() return xs.list end function realise(xs::LazyList) realise!(xs) # Unroll in a loop to avoid overflow while isa(xs.list, LazyList) xs.list = realise!(xs.list) end return xs.list end macro lazy(code) :(LazyList(() -> seq($(esc(code))))) end for f in [:first :isempty] @eval $f(l::LazyList) = $f(realise(l)) end tail(l::LazyList) = @lazy tail(realise(l)) ######## # Usage ######## include("liblazy.jl") include("collections.jl") # ----- # Eager # ----- import Base.foreach export dorun, doall, foreach @rec dorun(xs::List) = isempty(xs) ? nothing : dorun(tail(xs)) doall(xs::List) = (dorun(xs); xs) foreach(f, ls::List...) = map(f, ls...) |> dorun # ------- # Interop # ------- import Base: getindex, setindex! getindex(l::List, i::Int) = i <= 1 ? first(l) : tail(l)[i-1] getindex(l::List, r::UnitRange) = take(length(r), drop(r.start - 1, l)) setindex!(xs::LinkedList, v, i::Integer) = i <= 1 ? xs.first = v : (tail(xs)[i-1] = v) setindex!(xs::LazyList, v, i::Integer) = i <= 1 ? realise(xs)[1] = v : (tail(xs)[i-1] = v) # Iteration over a list holds on to the head function Base.iterate(L::List, xs::List=L) isempty(xs) && return nothing first(xs), tail(xs) end ########### # Printing ########### function Base.show(io::IO, xs::List) print(io, "List: (") for (i, x) in enumerate(interpose(xs, " ")) print(io, x) if i > 21 print(io, "…") break end end print(io, ")") end # Some example lists @listable +, -, Base.exp, Base.log, Base.sin, Base.cos, Base.tan const fibs = @lazy 0:big(1):(fibs + tail(fibs)) isprime(n) = @>> primes begin takewhile(x -> x<=sqrt(n)) map(x -> n % x == 0) any; ! end const primes = filter(isprime, range(2)) end
Lazy
https://github.com/MikeInnes/Lazy.jl.git
[ "MIT" ]
0.15.1
1370f8202dac30758f3c345f9909b97f53d87d3f
code
990
# TODO: Implement liblazy functions over standard arrays / other collections function Base.split(xs::Vector{T}, x; keep = true) where T result = Vector{T}[] push!(result, T[]) for i = 1:length(xs) if xs[i] == x (keep || !(isempty(result[end]) || i == length(xs))) && push!(result, T[]) else push!(result[end], xs[i]) end end isempty(result[end]) && pop!(result) return result end export frequencies function frequencies(xs) freqs = Dict{eltype(xs),Int}() for x in xs freqs[x] = get(freqs, x, 0) + 1 end return freqs end export init init(xs) = xs[1:end-1] # function Base.getindex{K, V}(d::Dict{K, V}, ks::Vector{K}) # vs = similar(ks, V, 0) # for k in ks # push!(vs, d[k]) # end # return vs # end for f in (:takewhile, :splitby, :takeuntil) @eval $(f)(f::Function, xs) = $(f)(f, seq(xs)) end function groupby(f, xs) result = d() for x in xs push!(get!(()->[], result, f(x)), x) end return result end
Lazy
https://github.com/MikeInnes/Lazy.jl.git
[ "MIT" ]
0.15.1
1370f8202dac30758f3c345f9909b97f53d87d3f
code
2415
# Dynamic binding is invaluable for creating certain kinds of # complex control flow in an intuitive way. Declare and access # a dynamic var: # @dynamic a = 1 # a[] #> 1 # Binding `a` alters its value for everywhere further down in # the stack. # showa() = @show a[] # @dynamic let a = 2 # showa() # end # #> a[] => 2 # Including for sub tasks which may continue to run: # function showa() # @schedule for i = 1:10 # @show a[] # sleep(1) # end # end # @dynamic let a = 3 # showa() # end # This will print `a[] => 3` repeatedly, while evluating `a[]` # will return `1`. # You can also use the syntax # a[] = 5 # which will modify either the most recent binding value or the # root of the var, as applicable. # See also Clojure's dynamic vars for the inspiration: # http://clojure.org/vars import Base: getindex, setindex! export @dynamic mutable struct Binding{T} root::T end root(b::Binding) = b.root function dynamic_eq(def) name, val = def.args if isexpr(name, :(::)) name, T = name.args :(const $(esc(name)) = Binding{$(esc(T))}($(esc(val)))) else :(const $(esc(name)) = Binding($(esc(val)))) end end function dynamic_let(ex) bindings = [:(bind($(esc(b.args[1])), $(esc(b.args[2])), t)) for b in ex.args[2:end]] quote t = @task $(esc(ex.args[1])) $(bindings...) schedule(t) wait(t) end end macro dynamic(def) isexpr(def, :(=)) ? dynamic_eq(def) : isexpr(def, :let) ? dynamic_let(def) : error("Unsupported @dynamic expression") end Base.parent(t::Task) = t.parent storage(t::Task) = t.storage == nothing ? (t.storage = ObjectIdDict()) : t.storage isroot(task::Task) = task.parent == task bindings(task::Task) = get!(storage(task), :bindings, @d()) bind(b::Binding{T}, v::T, t::Task) where {T} = bindings(t)[b] = v function bind(f::Function, b::Binding{T}, v::T) where T t = Task(f) bind(b, v, t) schedule(t) return wait(t) end binding(b::Binding{T}, t::Task = current_task()) where {T} = haskey(bindings(t), b) ? bindings(t)[b]::T : isroot(t) ? root(b) : binding(b, parent(t)) set!(b::Binding{T}, v::T, t::Task = current_task()) where {T} = haskey(bindings(t), b) ? (bindings(t)[b] = v) : isroot(t) ? (b.root = v) : set!(b, v, parent(t)) getindex(b::Binding) = binding(b) setindex!(b::Binding{T}, v::T) where {T} = set!(b, v)
Lazy
https://github.com/MikeInnes/Lazy.jl.git
[ "MIT" ]
0.15.1
1370f8202dac30758f3c345f9909b97f53d87d3f
code
6323
# ------------ # Construction # ------------ export seq, constantly, repeatedly, iterated, concat seq(xs::List) = xs seq(xs::Array) = isempty(xs) ? list() : xs[1]:seq(xs[2:end]) seq(xs::Tuple) = seq(collect(xs)) function seq(itr) xs = iterate(itr) xs == nothing && return EmptyList() x, state = xs prepend(x, seq(itr, state)) end # there should maybe be a @lazy here, but tests pass function seq(itr, state) xs = iterate(itr, state) xs == nothing && return EmptyList() x, state = xs prepend(x, seq(itr, state)) end constantly(x) = @lazy x:constantly(x) constantly(n, x) = @>> constantly(x) take(n) cycle(xs) = @lazy xs * cycle(xs) repeatedly(f) = @lazy f():repeatedly(f) repeatedly(n, f) = @>> repeatedly(f) take(n) iterated(f, v) = @lazy v:iterated(f, f(v)) range(x, y, step=1) = @lazy x <= y ? (x:range(x+step, y, step)) : [] range(x=1) = # Optimisation for y=Inf @lazy x:range(x+1) concat(xs::List, ys::List) = @lazy isempty(xs) ? ys : (first(xs):concat(tail(xs), ys)) *(xs::List, ys::List) = concat(xs, ys) *(xs::BitArray, ys::List) = concat(seq(xs), ys) *(xs::AbstractArray, ys::List) = concat(seq(xs), ys) *(xs::List, ys::AbstractArray) = concat(xs, seq(ys)) # ------------ # Manipulation # ------------ import Base: length, map, reduce, filter, reverse import Base.Iterators: drop, take export riffle, interpose, take, drop, takelast, droplast, takenth, takewhile, takeuntil, dropwhile, lazymap, reductions, remove, dorun, foreach, distinct, groupby, partition, partitionby, splitat, splitby, flatten riffle(ls...) = riffle(map(seq, ls)...) riffle(ls::List...) = @lazy any(isempty, ls) ? [] : seq(map(first, ls)) * riffle(map(tail, ls)...) interpose(xs, args...) = interpose(seq(xs), args...) interpose(xs::List, y, n = 1) = @lazy isempty(xs) ? [] : take(n, xs) * (isempty(drop(n, xs)) ? [] : prepend(y, interpose(drop(n, xs), y, n))) function length(l::List) ret = 0 # unroll in while loop in order to avoid stackoverflow while !isempty(l) l = tail(l) ret += 1 end return ret end Base.lastindex(l::List) = error("Cant use `end` with List.") take(n::Integer, l::List) = @lazy n <= 0 || isempty(l) ? [] : prepend(first(l), take(n-1, tail(l))) drop(n::Integer, l::List) = @lazy n <= 0 ? l : drop(n-1, tail(l)) takelast(n::Integer, l::List) = @lazy isempty(drop(n, l)) ? l : takelast(n, tail(l)) Base.last(l::List) = @>> l takelast(1) first droplast(n::Integer, l::List) = map((x,_)->x, l, drop(n,l)) takenth(n::Integer, l::List) = @lazy isempty(l) ? [] : first(drop(n-1,l)):takenth(n, drop(n, l)) for f in [:take :drop :takelast :droplast :takenth] # This avoid the ambiguity with the base versions @eval $f(l::List, n::Int) = $f(n, l) @eval $f(l::List, n::Integer) = $f(n, l) end """ takeuntil(pred, list) Take the elements in `list` until the `pred` function return true. Notice that the one which makes `pred` true is also taken. All elements will be taken if no one satisfy the `pred` function. """ takeuntil(pred::Function, l::List) = @lazy isempty(l) ? [] : pred(first(l)) ? [first(l)] : first(l):takeuntil(pred, tail(l)) takewhile(pred::Function, l::List) = @lazy isempty(l) || !pred(first(l)) ? [] : first(l):takewhile(pred, tail(l)) dropwhile(pred::Function, l::List) = @lazy isempty(l) || !pred(first(l)) ? l : dropwhile(pred, tail(l)) mapply(f::Union{Function, DataType}, ls...) = @lazy any(isempty, ls) ? [] : prepend(f(map(first, ls)...), mapply(f, map(tail, ls)...)) # Resolves amibguity error map(f::Function, ls::List...) = mapply(f, ls...) map(f::DataType, ls::List...) = mapply(f, ls...) lazymap(f::Union{Function, DataType}, ls...) = map(f, map(seq, ls)...) @rec reduce(f::Function, v, xs::List) = isempty(xs) ? v : reduce(f, f(v, first(xs)), tail(xs)) reduce(f::Function, xs::List) = isempty(xs) ? f() : reduce(f, first(xs), tail(xs)) reductions(f::Function, v, xs::List) = @lazy if isempty(xs) [] else acc = f(v, first(xs)) acc:reductions(f, acc, tail(xs)) end reductions(f::Function, xs::List) = @lazy isempty(xs) ? [] : reductions(f, first(xs), tail(xs)) filter(f::Function, xs::List) = @lazy isempty(xs) ? [] : f(first(xs)) ? (first(xs):filter(f, tail(xs))) : filter(f, tail(xs)) remove(f::Function, xs::List) = filter(x->!f(x), xs) reverse(xs::List) = reduce((xs, x)->x:xs, list(), xs) distinct(xs::List) = distinct(xs, Set()) distinct(xs::List, seen::Set) = @lazy isempty(xs) ? [] : first(xs) in seen ? distinct(tail(xs), seen) : first(xs):distinct(tail(xs), push!(seen, first(xs))) function groupby(f, xs::List) groups = Dict() for x in xs k = f(x) groups[k] = x:get(groups, k, list()) end return groups end partition(n, xs::List; step = n, pad = nothing) = @lazy isempty(xs) ? [] : @with (l = take(n, xs), len = length(l)), len < n ? (pad == nothing ? [] : list(l * take(n-len, pad))) : (l:partition(n, drop(step, xs); step = step, pad = pad)) partitionby(f, xs::List) = @lazy isempty(xs) ? [] : @with (x = first(xs), v = f(x), run = takewhile(x->f(x)==v, tail(xs))), prepend(x,run):partitionby(f, @lazy drop(length(run)+1, xs)) splitat(n, xs::List) = (take(n, xs), drop(n, xs)) splitby(p::Function, xs::List) = takewhile(p, xs), dropwhile(p, xs) walk(inner, outer, xs::List) = @>> xs map(inner) outer walk(inner, outer, x) = outer(x) prewalk(f, xs) = walk(x -> prewalk(f, x), identity, f(xs)) postwalk(f, xs) = walk(x -> postwalk(f, x), f, xs) flatten(x) = list(x) flatten(xs::List) = reduce((xs, x) -> xs*flatten(x), list(), xs) # ---------- # Predicates # ---------- import Base: any, all ==(xs::List, ys::List) = isempty(xs) == isempty(ys) && (isempty(xs) || first(xs) == first(ys) && tail(xs) == tail(ys)) if isdefined(Base, :Predicate) any(f::Base.Predicate, xs::List) = @>> xs map(f) any all(f::Base.Predicate, xs::List) = @>> xs map(f) all else any(f, xs::List) = @>> xs map(f) any all(f, xs::List) = @>> xs map(f) all end @rec any(xs::List) = isempty(xs) ? false : first(xs) || any(tail(xs)) any(::typeof(identity), xs::List) = any(xs) @rec all(xs::List) = isempty(xs) ? true : first(xs) && all(tail(xs)) all(::typeof(identity), xs::List) = all(xs)
Lazy
https://github.com/MikeInnes/Lazy.jl.git
[ "MIT" ]
0.15.1
1370f8202dac30758f3c345f9909b97f53d87d3f
code
7836
using MacroTools # Threading macros import Base: replace export @>, @>>, @as, @switch, @or, @dotimes, @oncethen, @defonce, @with, @errs, @forward, @iter """ A switch statement of sorts: @switch x begin 1; "x equals one!" 2; "x equals two!" "x equals something else!" end However, it's a bit more general than a regular switch in that you can test more than just equality: @switch isa(x, _) begin Integer; "x is an integer!" FloatingPoint; "x is a float!" "x is something else!" end @switch _ begin a > b; "more than!" a < b; "less than!" a == b; "equal!" # Note that this level of enthusiasm is not mandatory. end Where `_` is replaced by the value for testing in each case. The final expression, if there is one, is used as the default value; if there is no default and nothing matches an error will be thrown. """ macro switch(args...) test, exprs = splitswitch(args...) length(exprs) == 0 && return nothing length(exprs) == 1 && return esc(exprs[1]) test_expr(test, val) = test == :_ ? val : isa(test, Expr) ? :(let _ = $val; $test; end) : :($test==$val) thread(val, yes, no) = :($(test_expr(test, val)) ? $yes : $no) thread(val, yes) = thread(val, yes, :(error($"No match for $test in @switch"))) thread(val, yes, rest...) = thread(val, yes, thread(rest...)) esc(thread(exprs...)) end function splitswitch(test, exprs) @assert isexpr(exprs, :block) "@switch requires a begin block" test, rmlines(exprs).args end function splitswitch(ex) test = ex.args[1] exprs = c() for ex in ex.args[2:end] isexpr(ex, :->) ? push!(exprs, map(unblock, ex.args)...) : push!(exprs, ex) end test, exprs end """ The threading macro is like a more flexible version of the [`|>`](@ref) operator. @> x f = f(x) @> x g f == f(g(x)) @> x a b c d e == e(d(c(b(a(x))))) Unlike [`|>`](@ref), functions can have arguments - the value preceding a function will be treated as its first argument @> x g(y, z) f == f(g(x, y, z)) @> x g f(y, z) == f(g(x), y, z) See also [`@>>`](@ref), [`@as`](@ref). """ macro >(exs...) thread(x) = isexpr(x, :block) ? thread(rmlines(x).args...) : x @static if VERSION < v"0.7" thread(x, ex) = isexpr(ex, :call, :macrocall) ? Expr(ex.head, ex.args[1], x, ex.args[2:end]...) : @capture(ex, f_.(xs__)) ? :($f.($x, $(xs...))) : isexpr(ex, :block) ? thread(x, rmlines(ex).args...) : Expr(:call, ex, x) else thread(x, ex) = isexpr(ex, :macrocall) ? Expr(ex.head, ex.args[1], ex.args[2], x, ex.args[3:end]...) : isexpr(ex, :call,) ? Expr(ex.head, ex.args[1], x, ex.args[2:end]...) : @capture(ex, f_.(xs__)) ? :($f.($x, $(xs...))) : isexpr(ex, :block) ? thread(x, rmlines(ex).args...) : Expr(:call, ex, x) end thread(x, exs...) = reduce(thread, exs, init=x) esc(thread(exs...)) end """ Same as [`@>`](@ref), but threads the last argument. @>> x g(y, z) f == f(g(y, z, x)) @>> x g f(y, z) == f(y, z, g(x)) See also: [`@>>`](@ref) """ macro >>(exs...) thread(x) = isexpr(x, :block) ? thread(rmlines(x).args...) : x thread(x, ex) = isexpr(ex, Symbol, :->) ? Expr(:call, ex, x) : isexpr(ex, :call, :macrocall) ? Expr(ex.head, ex.args..., x) : @capture(ex, f_.(xs__)) ? :($f.($(xs...), $x)) : isexpr(ex, :block) ? thread(x, rmlines(ex).args...) : error("Unsupported expression $ex in @>>") thread(x, exs...) = reduce(thread, exs; init=x) esc(thread(exs...)) end """ @as as, exs... `@as` lets you name the threaded argmument @as _ x f(_, y) g(z, _) == g(z, f(x, y)) All threading macros work over begin blocks ```julia 6 === @as x 2 begin x^2 x+2 end ``` """ macro as(as, exs...) thread(x) = isexpr(x, :block) ? thread(rmlines(x).args...) : x thread(x, ex) = isexpr(ex, Symbol, :->) ? Expr(:call, ex, x) : isexpr(ex, :block) ? thread(x, rmlines(ex).args...) : :(let $as = $x $ex end) thread(x, exs...) = reduce((x, ex) -> thread(x, ex), exs, init=x) esc(thread(exs...)) end @static if VERSION < v"0.7" """ Same as `@as` but uses `_` as the argmument name. """ macro _(args...) :(@as $(esc(:_)) $(map(esc, args)...)) end end macro or(exs...) thread(x) = isexpr(x, :block) ? thread(rmlines(x).args...) : esc(x) thread(x, xs...) = :(let x = $(esc(x)) !(x == nothing || x == false) ? x : $(thread(xs...)) end) thread(exs...) end """ @dottimes(n, body) Repeat `body` `n` times. """ macro dotimes(n, body) quote for i = 1:$(esc(n)) $(esc(body)) end end end """ A `do`-`while` loop – executes the `while` loop once regardless of the condition, then tests the condition before subsequent iterations. """ macro oncethen(expr::Expr) @assert expr.head == :while esc(quote $(expr.args[2]) # body of loop $expr # loop end) end """ Stop Julia from complaining about redifined struct/consts – @defonce struct MyType ... end or @defonce const pi = 3.14 """ macro defonce(def) name = namify(isexpr(def, :struct) ? def.args[2] : def) if !isdefined(__module__, name) return :($(esc(def))) end end """ End-less `let` block, e.g. @with (x = 1, y = 2), x+y """ macro with(ex) @capture(ex, ((bindings__,), body_)) || error("Invalid expression @with $ex") ex = :(let $(bindings...) $body end) return esc(ex) end # Other syntax export c, s, d, @d c(xs...) = Any[xs...] s(xs...) = Set{Any}(xs) d(xs...) = Dict{Any, Any}(xs...) """ Creates an **un**typed dictionary, e.g. ```julia julia> @d(:a=>1, :b=>2) Dict{Any,Any} with 2 entries: :a => 1 :b => 2 ``` """ macro d(xs...) :(Dict{Any, Any}($(map(esc, xs)...))) end macro errs(ex) :(try $(esc(ex)) catch e showerror(stderr, e, catch_backtrace()) println(stderr) end) end """ @forward T.x functions... Define methods for `functions` on type `T`, which call the relevant function on the field `x`. # Example ```julia struct Wrapper x end @forward Wrapper.x Base.sqrt # now sqrt(Wrapper(4.0)) == 2.0 @forward Wrapper.x Base.length, Base.getindex, Base.iterate # several forwarded functions are put in a tuple @forward Wrapper.x (Base.length, Base.getindex, Base.iterate) # equivalent to above ``` """ macro forward(ex, fs) @capture(ex, T_.field_) || error("Syntax: @forward T.x f, g, h") T = esc(T) fs = isexpr(fs, :tuple) ? map(esc, fs.args) : [esc(fs)] :($([:($f(x::$T, args...; kwargs...) = (Base.@_inline_meta; $f(x.$field, args...; kwargs...))) for f in fs]...); nothing) end # Forwarding iteration struct SubIter{I,S} iter::I state::S end # Julia#16096 macro iter(ex) @capture(ex, x_::T_ -> it_) || error("Use @iter x::T -> y ...") @capture(it, $x.f_) && return :(@forward $(esc(T)).$f Base.iterate, Base.iterate) quote @inline function Base.iterate($x::$T) it = $it Lazy.SubIter(it, Base.iterate(it)) end @inline function Base.iterate(::$T, sub::Lazy.SubIter) next, state = Base.iterate(sub.iter, sub.state) next == nothing && return nothing next, Lazy.SubIter(sub.iter, state) end end |> esc end # Init macro export @init function initm(ex) quote if !isdefined(@__MODULE__, :__inits__) const $(esc(:__inits__)) = Function[] end if !isdefined(@__MODULE__, :__init__) function $(esc(:__init__))() for f in $(esc(:__inits__)) f() end end end push!($(esc(:__inits__)), () -> $(esc(ex))) nothing end end macro init(args...) initm(args...) end
Lazy
https://github.com/MikeInnes/Lazy.jl.git
[ "MIT" ]
0.15.1
1370f8202dac30758f3c345f9909b97f53d87d3f
code
3470
using MacroTools # Tail call operations function lastcalls(f, ex) isexpr(ex, :block) && return :(begin $(lastcalls(f, ex.args)...) end) @match ex begin let __ end => :(let $(lastcalls(f, ex.args)...) end) (c_ ? y_ : n_) => :($c ? $(lastcalls(f, y)) : $(lastcalls(f, n))) (a_ && b_) => :($a && $(lastcalls(f, b))) (a_ || b_) => :($a || $(lastcalls(f, b))) _ => f(ex) end end lastcalls(f, ex::Array) = isempty(ex) ? ex : [ex[1:end-1]..., lastcalls(f, ex[end])] function retcalls(f, ex) MacroTools.postwalk(ex) do ex @capture(ex, return x_) ? :(return $(lastcalls(f, x))) : ex end end tailcalls(f, ex) = @>> ex lastcalls(f) retcalls(f) # Tail recursion export @rec, @bounce "Generate an expression like `(a, b) = (c, d)`." tupleassign(xs, ys) = Expr(:(=), Expr(:tuple, xs...), Expr(:tuple, ys...)) tco(ex, f, dummy, start) = @capture(ex, $f(args__)) ? :($(tupleassign(dummy, args)); @goto $start) : ex """ Enables efficient recursive functions, e.g. @rec reduce(f::Function, v, xs::List) = isempty(xs) ? v : reduce(f, f(v, first(xs)), tail(xs)) Without `@rec` this function would overflow the stack for lists of 80,000 or more elements. Caveats: - No support for trampolining, i.e. only calls to the given function are optimised away. - Ignores multiple dispatch – it is assumed that the function's name always refers to the given definition. - Don't rebind the function's name in a let (see above). - Don't use this with varargs functions. Use the more flexible, but slower, [`@bounce`](@ref) to avoid these issues. """ macro rec(def) def = shortdef(macroexpand(@__MODULE__, def)) @capture(def, f_(args__) = body_) || error("@rec: $def is not a function definition.") f = namify(f) dummy = @>> args map(namify) map(string) map(gensym) # Set up of variables @gensym start body = quote $(tupleassign(dummy, args)) @label $start $(tupleassign(args, dummy)) $body end def.args[2] = tailcalls(ex -> tco(ex, f, dummy, start), body) return esc(def) end # Trampolining trampname(f) = Symbol(string("#__", f, "_tramp__")) mutable struct Bounce f::Function end function trampoline(f, args...) val = f(args...) while isa(val, Bounce) val = val.f() end return val end function bounce(ex) @capture(ex, f_(args__)) || return ex f_tramp = trampname(f) :(Lazy.Bounce(() -> $f_tramp($(args...)))) end function trampdef(f) f_tramp = trampname(f) @isdefined(f_tramp) && return :($f_tramp(args...) = $f(args...)) end """ Tail recursion that doesn't blow the stack. @bounce even(n) = n == 0 ? true : odd(n-1) @bounce odd(n) = n == 0 ? false : even(n-1) even(1_000_000) # Blows up without `@bounce`. #> true For simple cases you probably want the much faster [`@rec`](@ref). """ macro bounce(def) def = macroexpand(@__MODULE__, def) @assert isdef(def) @assert isexpr(def.args[1].args[1], Symbol) # TODO: handle f{T}() = ... f = namify(def) f_tramp = trampname(f) args = def.args[1].args[2:end] def.args[1].args[1] = f_tramp calls = Symbol[] def.args[2] = tailcalls(ex -> (isexpr(ex, :call) && push!(calls, ex.args[1]); bounce(ex)), def.args[2]) quote $([trampdef(call) for call in calls]...) $def $f($(args...)) = Lazy.trampoline($f_tramp, $(args...)) end |> esc end
Lazy
https://github.com/MikeInnes/Lazy.jl.git
[ "MIT" ]
0.15.1
1370f8202dac30758f3c345f9909b97f53d87d3f
code
4058
using Lazy import Lazy: cycle, range, drop, take using Test # dummy function to test threading macros on function add_things(n1, n2, n3) 100n1 + 10n2 + n3 end # dummy macro to test threading macros on macro m_add_things(n1, n2, n3) quote 100 * $(esc(n1)) + 10 * $(esc(n2)) + $(esc(n3)) end end # define structs for @forward macro testing below (PR #112) struct Foo112 end struct Bar112 f::Foo112 end @testset "Lazy" begin if VERSION >= v"1.0.0" @test isempty(detect_ambiguities(Base, Core, Lazy)) end @testset "Lists" begin @test list(1, 2, 3)[2] == 2 @test prepend(1, list(2,3,4)) == 1:list(2, 3, 4) @test seq([1, 2, 3]) == list(1, 2, 3) @test seq(1:3) == list(1, 2, 3) @test constantly(1)[50] == 1 testfn() = 1 @test repeatedly(testfn)[50] == 1 @test cycle([1, 2, 3])[50] == 2 @test iterated(x->x^2, 2)[3] == 16 @test range(1, 5)[3] == 3 @test range(1, 5)[10] == nothing @test range(1, 5)[-1] == 1 @test list(1, 2, 3) * list(4, 5, 6) == list(1, 2, 3, 4, 5, 6) @test first(list(1, 2, 3)) == 1 @test tail(list(1, 2, 3)) == list(2, 3) @test flatten(list(1,2,list(3,4))) == list(1, 2, 3, 4) @test list(1,2,list(3,4))[3] == list(3, 4) @test list(list(1), list(2))[1] == list(1) @test reductions(+, 0, list(1, 2, 3)) == list(1, 3, 6) @test [i for i in @lazy[1,2,3]] == [1,2,3] l = list(1, 2, 3) @test l:7:l == list(list(1, 2, 3), 7, 1, 2, 3) # ambiguity test end @testset "Fibs" begin fibs = @lazy 0:1:(fibs + drop(1, fibs)); @test fibs[20] == 4181 @test take(5, fibs) == list(0, 1, 1, 2, 3) end @testset "Primes" begin isprime(n) = @>> primes begin take_while(x -> x<=sqrt(n)) map(x -> n % x == 0) any; ! end primes = filter(isprime, range(2)); end @testset "Even squares" begin esquares = @>> range() map(x->x^2) filter(iseven); @test take(5, esquares) == list(4, 16, 36, 64, 100) end @testset "Threading macros" begin temp = @> [2 3] sum @test temp == 5 # Reverse from after index 2 temp = @>> 2 reverse([1, 2, 3, 4, 5]) @test temp == [1, 5, 4, 3, 2] temp = @as x 2 begin x^2 x + 2 end @test temp == 6 # test that threading macros work with functions temp = @> 1 add_things(2,3) @test temp == 123 temp = @>> 3 add_things(1,2) @test temp == 123 temp = @as x 2 add_things(1,x,3) @test temp == 123 # test that threading macros work with macros temp = @> 1 @m_add_things(2,3) @test temp == 123 temp = @>> 3 @m_add_things(1,2) @test temp == 123 temp = @as x 2 @m_add_things(1,x,3) @test temp == 123 end @testset "Forward macro" begin play(x::Foo112; y) = y # uses keyword arg play(x::Foo112, z) = z # uses regular arg play(x::Foo112, z1, z2; y) = y + z1 + z2 # uses both @forward Bar112.f play # forward `play` function to field `f` let f = Foo112(), b = Bar112(f) @test play(f, y = 1) === play(b, y = 1) @test play(f, 2) === play(b, 2) @test play(f, 2, 3, y = 1) === play(b, 2, 3, y = 1) end end @testset "getindex" begin l = Lazy.range(1,10) @test l[1] == 1 @test collect(l[1:5]) == collect(1:5) end @testset "Listables" begin @test_throws MethodError sin() end @static VERSION ≥ v"1.2" && @testset "avoid stackoverflow" begin @test (length(takewhile(<(10), Lazy.range(1))); true) @test (length(takewhile(<(100000), Lazy.range(1))); true) end @testset "any/all" begin let xs = list(true, false, false) @test any(identity, xs) == true @test any(xs) == true @test all(identity, xs) == false @test all(xs) == false end let yy = list(1, 0, 1) @test any(Bool, yy) == true @test all(Bool, yy) == false end # Base method--ensures no ambiguity with methods here @test all([true true; true true], dims=1) == [true true] end end
Lazy
https://github.com/MikeInnes/Lazy.jl.git
[ "MIT" ]
0.15.1
1370f8202dac30758f3c345f9909b97f53d87d3f
docs
5148
# Lazy.jl [![Gitter chat](https://badges.gitter.im/one-more-minute/Lazy.jl.png)](https://gitter.im/one-more-minute/Lazy.jl) ```julia Pkg.add("Lazy") ``` Lazy.jl provides Julia with the cornerstones of functional programming - lazily-evaluated lists and a large library of functions for working with them. It's also a repository for some neat macros, which might be useful to you even if you don't want lazy lists (see below). Firstly, the canonical examples, in Julia: ```julia using Lazy # Note : prepends. Don't forget the semicolon! # -- When running interactively, the semi-colon prevents the environment # from trying to display an infinite list. # Fibonacci sequence defined in terms of itself: fibs = @lazy 0:1:(fibs + drop(1, fibs)); take(20, fibs) #> (0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181) # isprime defined in terms of the prime numbers: isprime(n) = @>> primes begin takewhile(x -> x<=sqrt(n)) map(x -> n % x == 0) any; ! end # the prime numbers defined in terms of isprime: primes = filter(isprime, Lazy.range(2)); take(20, primes) #> (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71) ``` If you've done any functional programming, you already know how to use Lazy.jl; just head down to the reference below to see what functions are available. ### Intro to Laziness For the unfamiliar, laziness just means that the elements of the list aren't actually calculated until you use them. This allows you to perform all sorts of magic, like working with infinite lists or lists of items from the future. ```julia # Even square numbers: > esquares = @>> Lazy.range() map(x->x^2) filter(iseven); # first 5 > take(5, esquares) List: 4 16 36 64 100 # 99th > esquares[99] 39204 ``` But lazy lists aren't just for mathematical tricks; you can use them very practically for things like file IO. For example, you might represent the lines of a terabyte-large file with a lazy list; you can process the lines as any other list, letting the IO happen in the background. ```julia # TODO: lineseq example @>> "file.txt" lineseq foreach(println) # Will work no matter many lines file.txt has ``` The other thing that separates lists from arrays is the huge amount of functionality that comes with most functional programming libraries, including Lazy.jl - if you know your way around them, most data manipulation becomes a simple case of chaining a few functions together. Even if you do ultimately need arrays for speed, you could do worse than to prototype with lists. ### Macros The threading macros will pipe values through functions, a bit like the `|>` operator but far more flexible. They can make code a *lot* cleaner by putting function calls in the order they are applied. The best way to understand them is by example: ```julia # Just like x |> f etc. @> x f == f(x) @> x g f == f(g(x)) @> x a b c d e == e(d(c(b(a(x))))) # Unlike |>, functions can have arguments - the value # preceding a function will be treated as its first argument @> x g(y, z) f == f(g(x, y, z)) @> x g f(y, z) == f(g(x), y, z) # @>> does the exact same thing, but with value treated as the *last* argument. @>> x g(y, z) f == f(g(y, z, x)) @>> x g f(y, z) == f(y, z, g(x)) # @as lets you name the threaded argument @as _ x f(_, y) g(z, _) == g(z, f(x, y)) # All threading macros work over begin blocks @as x 2 begin x^2 x+2 end == 6 ``` ### Function Reference ```julia List # The abstract type that represents lazy lists list(1,2,3) == (1 2 3) prepend(1, list(2,3,4)) == 1:list(2,3,4) == (1 2 3 4) # Most list handling functions have similar names # to those in Clojure. # Create a seq from any iterator or array seq([1,2,3]) == seq(1:3) == (1 2 3) # Infinite list of an element constantly(x) == (x x x ...) constantly(1) == (1 1 1 ...) # Infinite list of function calls repeatedly(f) == (f() f() f() ...) repeatedly(rand) == (0.634 0.478 0.776 ...) # Infinitely repeat list cycle(a) == (a... a... a... ...) cycle([1,2,3]) == (1 2 3 1 2 3 1 2 3 1 ...) # Repeatedly nest function calls iterated(f, x) == (x f(x) f(f(x)) ...) iterated(x->x^2, 2) == (2 4 16 256 65536 ...) range(2) == (2 3 4 5 ...) range(1, 5) == (1 2 3 4 5) range(1, 5, 2) == (1 3 5) list(1,2,3) * list(4,5,6) == (1 2 3 4 5 6) first(list(1,2,3)) == 1 tail(list(1,2,3)) == (2 3) flatten(list(1,2,list(3,4))) == (1 2 3 4) takeuntil(x -> x > 1, 0:1) == (0 1) takeuntil(x -> x > 1, 0:5) == (0 1 2) takeuntil(x -> x > 1, 2:5) == (2) takeuntil(x -> x > 1, []) == () riffle interpose take drop takelast droplast takenth takewhile dropwhile # These work as for arrays, but are # lazy where appropriate. map, reduce, filter, reverse lazymap reductions remove dorun foreach distinct groupby partition partitionby splitat splitby # @lazy is the secret sauce that makes infinite definitions # work; usually you can just wrap your list definition in it: @lazy [1,2,3] == (1 2 3) # Define a lazy recursive function constantly(x) = @lazy x:constantly(x) # Make a function map itself over lists @listable exp exp(range()) == (2.71 7.38 20.08 54.59 148.41 ...) # Threading macros, see above @>, @>> ```
Lazy
https://github.com/MikeInnes/Lazy.jl.git
[ "MIT" ]
0.1.1
e5a84c06644be8675ef8b8bb664d4c62399f2c30
code
2563
cd(pwd()) Pkg.activate("./EventStudyInteracts") using EventStudyInteracts using DataFrames, Random, Plots, FixedEffectModels using CSV units = 100000 start = 1 finish = 20 nlvls = 5 time = finish - start + 1 obsv = units * time K=100 id1 = rand(1:(obsv/K), obsv) id2 = rand(1:K, obsv) df = DataFrame(id = repeat(1:units, inner=time), t = repeat(start:finish, outer=units), id1 = id1, id2 = id2) Random.seed!(20211222) df.Y .= 0 # outcome variable df.D .= 0 # intervention variable df.cohort .= repeat([rand(0:nlvls) for i in 1:units], inner=time) # treatment cohort effect = [rand(2:10) for i in unique(df.cohort)] first_treat = [rand(start:(finish + 20)) for i in unique(df.cohort)] df.effect = similar(df.cohort) df.first_treat = similar(df.cohort, Union{Int64, Missing}) for i in 0:nlvls df.effect[df.cohort .== i] .= effect[i+1] df.first_treat[df.cohort .== i] .= first_treat[i+1] end df.first_treat[df.first_treat .> finish] .= missing df.D = ifelse.(coalesce.(df.t .>= df.first_treat, false), 1, 0) df.rel_time .= df.t .- df.first_treat df.Y = df.t .+ ifelse.(df.D .== 1, df.effect .* df.rel_time, 0) .+ randn(nrow(df)) plot(df.t, df.Y, label=false) df.never_treat = ismissing.(df.first_treat) # We will consider the dynamic effect of union status on income. We first generate these relative time indicators, and leave out the distant leads due to few observations. Implicitly this assumes that effects outside the lead windows are zero. relmin = abs(minimum(skipmissing(df.rel_time))) relmax = abs(maximum(skipmissing(df.rel_time))) for k in relmin:-1:2 df[!, Symbol("g_$k")] = Int.(coalesce.(df.rel_time .== -k, false)) end for k in 0:relmax df[!, Symbol("g$k")] = Int.(coalesce.(df.rel_time .== k, false)) end absorb = [:id,:t] formula1 = term(:Y) ~ sum(fe.(term.(absorb))) rel_varlist1 = Symbol[] for i in relmin:-1:2 push!(rel_varlist1, Symbol("g_"*string(i))) end for i in 0:relmax push!(rel_varlist1, Symbol("g"*string(i))) end control_cohort1 = :never_treat cohort1 = :first_treat CSV.write("./EventStudyInteracts/benchmark/bench.csv", df) m1 = eventreg(df, formula1, rel_varlist1, control_cohort1, cohort1) @time m1 = eventreg(df, formula1, rel_varlist1, control_cohort1, cohort1) # 76.965495 seconds (395.81 k allocations: 218.291 GiB, 23.78% gc time) absorb = [:id,:id1,:id2,:t] formula2 = term(:Y) ~ sum(fe.(term.(absorb))) @time m2 = eventreg(df, formula2, rel_varlist1, control_cohort1, cohort1) # 88.459680 seconds (3.09 M allocations: 218.534 GiB, 21.19% gc time, 0.86% compilation time)
EventStudyInteracts
https://github.com/xiaobaaaa/EventStudyInteracts.jl.git
[ "MIT" ]
0.1.1
e5a84c06644be8675ef8b8bb664d4c62399f2c30
code
7278
############################################################################## ## ## Type EventStudyInteract ## ############################################################################## struct EventStudyInteract <: RegressionModel coef::Vector{Float64} # Vector of coefficients vcov::Matrix{Float64} # Covariance matrix vcov_type::CovarianceEstimator nclusters::Union{NamedTuple, Nothing} esample::BitVector # Is the row of the original dataframe part of the estimation sample? residuals::Union{AbstractVector, Nothing} fe::DataFrame fekeys::Vector{Symbol} coefnames::Vector # Name of coefficients responsename::Union{String, Symbol} # Name of dependent variable formula::FormulaTerm # Original formula formula_schema::FormulaTerm # Schema for predict contrasts::Dict nobs::Int64 # Number of observations dof::Int64 # Number parameters estimated - has_intercept dof_residual::Int64 # dof used for t-test and F-stat. nobs - degrees of freedoms with simple std rss::Float64 # Sum of squared residuals tss::Float64 # Total sum of squares r2::Float64 # R squared adjr2::Float64 # R squared adjusted F::Float64 # F statistics p::Float64 # p value for the F statistics # for FE iterations::Union{Int, Nothing} # Number of iterations converged::Union{Bool, Nothing} # Has the demeaning algorithm converged? r2_within::Union{Float64, Nothing} # within r2 (with fixed effect feresult::FixedEffectModel end StatsAPI.coef(m::EventStudyInteract) = m.coef StatsAPI.coefnames(m::EventStudyInteract) = m.coefnames StatsAPI.responsename(m::EventStudyInteract) = m.responsename StatsAPI.vcov(m::EventStudyInteract) = m.vcov StatsAPI.nobs(m::EventStudyInteract) = m.nobs StatsAPI.dof(m::EventStudyInteract) = m.dof StatsAPI.dof_residual(m::EventStudyInteract) = m.dof_residual StatsAPI.r2(m::EventStudyInteract) = m.r2 StatsAPI.adjr2(m::EventStudyInteract) = m.adjr2 StatsAPI.islinear(m::EventStudyInteract) = true StatsAPI.deviance(m::EventStudyInteract) = m.tss StatsAPI.rss(m::EventStudyInteract) = m.rss StatsAPI.mss(m::EventStudyInteract) = deviance(m) - rss(m) StatsAPI.residuals(m::EventStudyInteract) = m.residuals2 function StatsAPI.confint(m::EventStudyInteract; level::Real = 0.95) scale = tdistinvcdf(StatsAPI.dof_residual(m), 1 - (1 - level) / 2) se = stderror(m) hcat(m.coef - scale * se, m.coef + scale * se) end function StatsAPI.coeftable(m::EventStudyInteract; level = 0.95) cc = coef(m) se = stderror(m) coefnms = coefnames(m) conf_int = confint(m; level = level) # put (intercept) last if !isempty(coefnms) && ((coefnms[1] == Symbol("(Intercept)")) || (coefnms[1] == "(Intercept)")) newindex = vcat(2:length(cc), 1) cc = cc[newindex] se = se[newindex] conf_int = conf_int[newindex, :] coefnms = coefnms[newindex] end tt = cc ./ se CoefTable( hcat(cc, se, tt, fdistccdf.(Ref(1), Ref(StatsAPI.dof_residual(m)), abs2.(tt)), conf_int[:, 1:2]), ["Estimate","Std.Error","t value", "Pr(>|t|)", "Lower 95%", "Upper 95%" ], ["$(coefnms[i])" for i = 1:length(cc)], 4) end ############################################################################## ## ## Display Result ## ############################################################################## function title(m::EventStudyInteract) return "EventStudyInteract IW estimator" end format_scientific(x) = @sprintf("%.3f", x) function top(m::EventStudyInteract) out = [ "Number of obs" sprint(show, nobs(m), context = :compact => true); "Degrees of freedom" sprint(show, dof(m), context = :compact => true); "R2" format_scientific(r2(m)); "R2 Adjusted" format_scientific(adjr2(m)); "F-Stat" sprint(show, m.F, context = :compact => true); "p-value" format_scientific(m.p); ] out = vcat(out, ["R2 within" format_scientific(m.r2_within); "Iterations" sprint(show, m.iterations, context = :compact => true); ]) return out end function Base.show(io::IO, m::EventStudyInteract) ctitle = title(m) ctop = top(m) cc = coef(m) se = stderror(m) yname = responsename(m) coefnms = coefnames(m) conf_int = confint(m) # put (intercept) last if !isempty(coefnms) && ((coefnms[1] == Symbol("(Intercept)")) || (coefnms[1] == "(Intercept)")) newindex = vcat(2:length(cc), 1) cc = cc[newindex] se = se[newindex] conf_int = conf_int[newindex, :] coefnms = coefnms[newindex] end tt = cc ./ se mat = hcat(cc, se, tt, fdistccdf.(Ref(1), Ref(StatsAPI.dof_residual(m)), abs2.(tt)), conf_int[:, 1:2]) nr, nc = size(mat) colnms = ["Estimate","Std.Error","t value", "Pr(>|t|)", "Lower 95%", "Upper 95%"] rownms = ["$(coefnms[i])" for i = 1:length(cc)] pvc = 4 # print if length(rownms) == 0 rownms = AbstractString[lpad("[$i]",floor(Integer, log10(nr))+3) for i in 1:nr] end if length(rownms) > 0 rnwidth = max(4, maximum(length(nm) for nm in rownms) + 2, length(yname) + 2) else # if only intercept, rownms is empty collection, so previous would return error rnwidth = 4 end rownms = [rpad(nm,rnwidth-1) * "|" for nm in rownms] widths = [length(cn)::Int for cn in colnms] str = [sprint(show, mat[i,j]; context=:compact => true) for i in 1:nr, j in 1:nc] if pvc != 0 # format the p-values column for i in 1:nr str[i, pvc] = format_scientific(mat[i, pvc]) end end for j in 1:nc for i in 1:nr lij = length(str[i, j]) if lij > widths[j] widths[j] = lij end end end widths .+= 1 totalwidth = sum(widths) + rnwidth if length(ctitle) > 0 halfwidth = div(totalwidth - length(ctitle), 2) println(io, " " ^ halfwidth * string(ctitle) * " " ^ halfwidth) end if length(ctop) > 0 for i in 1:size(ctop, 1) ctop[i, 1] = ctop[i, 1] * ":" end println(io, "=" ^totalwidth) halfwidth = div(totalwidth, 2) - 1 interwidth = 2 + mod(totalwidth, 2) for i in 1:(div(size(ctop, 1) - 1, 2)+1) print(io, ctop[2*i-1, 1]) print(io, lpad(ctop[2*i-1, 2], halfwidth - length(ctop[2*i-1, 1]))) print(io, " " ^interwidth) if size(ctop, 1) >= 2*i print(io, ctop[2*i, 1]) print(io, lpad(ctop[2*i, 2], halfwidth - length(ctop[2*i, 1]))) end println(io) end end println(io,"=" ^totalwidth) println(io, rpad(string(yname), rnwidth-1) * "|" * join([lpad(string(colnms[i]), widths[i]) for i = 1:nc], "")) println(io,"-" ^totalwidth) for i in 1:nr print(io, rownms[i]) for j in 1:nc print(io, lpad(str[i,j],widths[j])) end println(io) end println(io,"=" ^totalwidth) end
EventStudyInteracts
https://github.com/xiaobaaaa/EventStudyInteracts.jl.git
[ "MIT" ]
0.1.1
e5a84c06644be8675ef8b8bb664d4c62399f2c30
code
709
module EventStudyInteracts # slows down tss #if isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol("@optlevel")) # @eval Base.Experimental.@optlevel 1 #end using DataFrames using FixedEffectModels using LinearAlgebra using Printf using Reexport using Statistics using StatsAPI using StatsBase using StatsFuns @reexport using StatsModels using Tables using Vcov include("EventStudyInteract.jl") include("eventfit.jl") include("ee.jl") include("avar.jl") # Export from StatsBase export coef, coefnames, coeftable, responsename, vcov, stderror, nobs, dof_residual, r2, adjr2, islinear, deviance, rss, mss, confint, predict, residuals, fit export eventreg, EventStudyInteract, Vcov end
EventStudyInteracts
https://github.com/xiaobaaaa/EventStudyInteracts.jl.git
[ "MIT" ]
0.1.1
e5a84c06644be8675ef8b8bb664d4c62399f2c30
code
457
function avar(e::Matrix, Z::Matrix, robust::Bool=true) N = size(e, 1) L = size(Z, 2) p = size(e, 2) S = zeros(L*p, L*p) for j in 1:p for k in 1:p if robust S[(j-1)*L+1:j*L,(k-1)*L+1:k*L] = (Z' * Diagonal(e[:,j] .* e[:,k]) * Z) / N else S[(j-1)*L+1:j*L,(k-1)*L+1:k*L] = (Z' * Z) * cov(e[:,j], e[:,k]) / N end end end return S end
EventStudyInteracts
https://github.com/xiaobaaaa/EventStudyInteracts.jl.git
[ "MIT" ]
0.1.1
e5a84c06644be8675ef8b8bb664d4c62399f2c30
code
83
function ee(i::Int, n::Int) v = zeros(1, n) v[i] = 1 return v end
EventStudyInteracts
https://github.com/xiaobaaaa/EventStudyInteracts.jl.git
[ "MIT" ]
0.1.1
e5a84c06644be8675ef8b8bb664d4c62399f2c30
code
7914
function eventreg(@nospecialize(df), @nospecialize(formula::FormulaTerm), @nospecialize(rel_varlist::Vector{Symbol}), @nospecialize(control_cohort::Symbol), @nospecialize(cohort::Symbol), @nospecialize(vcov::CovarianceEstimator = Vcov.simple()); @nospecialize(contrasts::Dict = Dict{Symbol, Any}()), @nospecialize(weights::Union{Symbol, Nothing} = nothing), @nospecialize(save::Union{Bool, Symbol} = :none), @nospecialize(method::Symbol = :cpu), @nospecialize(nthreads::Integer = method == :cpu ? Threads.nthreads() : 256), @nospecialize(double_precision::Bool = true), @nospecialize(tol::Real = 1e-6), @nospecialize(maxiter::Integer = 10000), @nospecialize(drop_singletons::Bool = true), @nospecialize(progress_bar::Bool = true), @nospecialize(dof_add::Integer = 0), @nospecialize(subset::Union{Nothing, AbstractVector} = nothing)) StatsAPI.fit(EventStudyInteract, formula, df, rel_varlist, control_cohort, cohort, vcov; contrasts = contrasts, weights = weights, save = save, method = method, nthreads = nthreads, double_precision = double_precision, tol = tol, maxiter = maxiter, drop_singletons = drop_singletons, progress_bar = progress_bar, dof_add = dof_add, subset = subset) end function StatsAPI.fit(::Type{EventStudyInteract}, @nospecialize(formula::FormulaTerm), @nospecialize(df), @nospecialize(rel_varlist::Vector{Symbol}), @nospecialize(control_cohort::Symbol), @nospecialize(cohort::Symbol), @nospecialize(vcov::CovarianceEstimator = Vcov.simple()); @nospecialize(contrasts::Dict = Dict{Symbol, Any}()), @nospecialize(weights::Union{Symbol, Nothing} = nothing), @nospecialize(save::Union{Bool, Symbol} = :none), @nospecialize(method::Symbol = :cpu), @nospecialize(nthreads::Integer = method == :cpu ? Threads.nthreads() : 256), @nospecialize(double_precision::Bool = true), @nospecialize(tol::Real = 1e-6), @nospecialize(maxiter::Integer = 10000), @nospecialize(drop_singletons::Bool = true), @nospecialize(progress_bar::Bool = true), @nospecialize(dof_add::Integer = 0), @nospecialize(subset::Union{Nothing, AbstractVector} = nothing)) df = DataFrame(df; copycols = false) # Prepare the varlists nvarlist = Symbol[] dvarlist = Symbol[] for l in rel_varlist push!(dvarlist,l) n_l = Symbol("n",l) df[!,n_l] = df[!,l] df[!,n_l][df[!,control_cohort].==1] .= 0 push!(nvarlist,n_l) end cohort_list = unique(df[!,cohort][df[!,control_cohort].==0]) cohort_list = sort(cohort_list) cohort_list = Int.(cohort_list) nrel_times = length(nvarlist) ncohort = length(cohort_list) # Prepare interaction terms for the interacted regression cohort_rel_varlist = Symbol[] for l in nvarlist for yy in cohort_list n_l_yy = Symbol("n"*string(l)*"_"*string(yy)) df[!, :D] .= ifelse.(coalesce.(df[!, cohort] .== yy, false), 1, 0) df[!, n_l_yy] = df[!, :D] .* df[!, l] push!(cohort_rel_varlist, n_l_yy) end end # bcohort_rel_varlist = Symbol[] # for l in rel_varlist # for yy in cohort_list # push!(bcohort_rel_varlist, Symbol(string(l)*"_x_"*string(yy))) # end # end # Estimate the interacted regression formula1 = formula.lhs ~ sum(term.(cohort_rel_varlist)) + formula.rhs result = reg(df, formula1, vcov, contrasts = contrasts, weights = weights, save = save, method = method, nthreads = nthreads, double_precision = double_precision, tol = tol, maxiter = maxiter, drop_singletons = drop_singletons, progress_bar = progress_bar, dof_add = dof_add, subset = subset) #Caculate the weights. df = df[result.esample .== 1, :] ff_w = zeros(0,length(nvarlist)) nresidlist = Symbol[] for yy in cohort_list cohort_ind = Symbol("cohort_ind") resid_yy = Symbol("resid", yy) df[!, cohort_ind] .= ifelse.(coalesce.(df[!,cohort] .== yy,false) , 1 , 0) formula2 = term(cohort_ind) ~ sum(term.(nvarlist)) + term(0) reg1 = reg(df[df[!,control_cohort] .== 0,:], formula2) bb = reg1.coef ff_w = vcat(ff_w,bb') df[!,resid_yy] = residuals(reg1,df) push!(nresidlist,resid_yy) end X = hcat([df[df[!, control_cohort] .== 0, i] for i in nvarlist]...) XX = X' * X Sxx = XX*(1/size(X)[1]) Sxxi = FixedEffectModels.invsym!(Sxx) e = hcat([df[df[!, control_cohort] .== 0, i] for i in nresidlist]...) S_robust = avar(e, X, true) # using the robust estimator KSxxi = kron(Matrix{Float64}(I, ncohort, ncohort), Sxxi) Sigma_ff = KSxxi * S_robust * KSxxi/ size(X)[1] b = result.coef V = diag(result.vcov) replace!(V, NaN => 0) # Convert the delta estimate vector to a matrix where each column is a relative time end_ = 0 evt_bb = zeros(ncohort,0) evt_VV = zeros(ncohort,0) for i in 1:nrel_times start = end_ + 1 end_ = start + ncohort - 1 b_i = b[start:end_] evt_bb = hcat(evt_bb, b_i) V_i = V[start:end_] evt_VV = hcat(evt_VV, V_i) end # Take weighted average for IW estimators w = ff_w delta = evt_bb b_iw = sum(w .* delta, dims=1) nc, nr = size(w) # Ptwise variance from cohort share estimation and interacted regression VV = result.vcov # VCV from the interacted regression replace!(VV, NaN => 0) VV = VV[1:nr*nc, 1:nr*nc] # in case reports _cons wlong = w'.*repeat(ee(1, nr)', 1, nc) for i in 2:nrel_times # loop from 2 to nrel_times wlong = [wlong (w' .* repeat(ee(i, nr)', 1, nc))] # concatenate end V_iw = wlong * VV * wlong' Vshare = Sigma_ff Sigma_l = zeros(0, 0) share_idx = 0:nr:(nc-1)*nr for i in 1:nrel_times for j in 1:i Vshare_evt = Vshare[share_idx .+ i, share_idx .+ j] V_iw[i,j] += delta[:,i]' * Vshare_evt * delta[:,j] end end coef_iw = vec(b_iw') vcov_iw = Symmetric(V_iw) vcov_iw_diag = diag(vcov_iw) ############################################################################## ## ## Test Statistics ## ############################################################################## # Compute standard error # Compute Fstat F = result.F p = result.p dof = result.dof dof_residual = result.dof_residual # Compute rss, tss, r2, r2 adjusted rss = result.rss r2 = result.r2 r2_within = result.r2_within tss_total = rss /(1-r2) mss = tss_total - rss adjr2 = result.adjr2 # Others nclusters = result.nclusters esample = result.esample fekeys = result.fekeys coef_names = [string(x) for x in dvarlist] # coef_names = coefnames response_name = responsename(result) # response_name, coef_names = coefnames(formula_schema) formula_origin = formula1 formula_schema = result.formula_schema contrasts = result.contrasts nobs = result.nobs residuals2 = nothing if (save == :residuals) | (save == :all) residuals2 = result.residuals2 end iterations = result.iterations fe2 = result.fe converged = result.converged feresult = result return EventStudyInteract(coef_iw, vcov_iw, vcov, nclusters, esample, residuals2, fe2, fekeys, coef_names, response_name, formula_origin, formula_schema, contrasts, nobs, dof , dof_residual, rss, tss_total, r2, adjr2, F, p, iterations, converged, r2_within, feresult) end
EventStudyInteracts
https://github.com/xiaobaaaa/EventStudyInteracts.jl.git
[ "MIT" ]
0.1.1
e5a84c06644be8675ef8b8bb664d4c62399f2c30
docs
23858
# EventStudyInteracts.jl This package is a Julia replication of the Stata package [`eventstudyinteract` ](https://github.com/lsun20/EventStudyInteract)provided by [Sun and Abraham (2021)](https://www.sciencedirect.com/science/article/abs/pii/S030440762030378X). The estimation process is identical to that of eventstudyinteract, and this package used [`FixedEffectModels.jl`](https://github.com/FixedEffects/FixedEffectModels.jl) to implement the Stata command [`reghdfe`](https://github.com/sergiocorreia/reghdfe) functionality. As introduced in the Stata package [`eventstudyinteract`](https://github.com/lsun20/EventStudyInteract) provided by [Sun and Abraham (2021)](https://www.sciencedirect.com/science/article/abs/pii/S030440762030378X), the function of this package is: > [`eventstudyinteract`](https://github.com/lsun20/EventStudyInteract) implements the interaction weighted (IW) estimator and constructs pointwise confidence interval for the estimation of dynamic treatment effects. To estimate the dynamic effects of an absorbing treatment, researchers often use two-way fixed effects (TWFE) regressions that include leads and lags of the treatment (event study specification). Units are categorized into different cohorts based on their initial treatment timing. Sun and Abraham (2020) proposes this estimator as an alternative to the TWFE regression in the presence of treatment effects heterogeneous across cohorts. Under treatment effects heterogeneity, the TWFE regression can result in estimates with uninterpretable weights, which can be assessed by the Stata module eventstudyweights. The IW estimator is implemented in three steps. First, estimate the interacted regression with reghdfe, where the interactions are between relative time indicators and cohort indicators. Second, estimate the cohort shares underlying each relative time. Third, take the weighted average of estimates from the first step, with weights set to the estimated cohort shares. ## Introduction - Julia is faster than Stata, and [`FixedEffectModels.jl`](https://github.com/FixedEffects/FixedEffectModels.jl) is much faster than reghdfe. - I am a beginner in programming and the code is a complete translation of the Stata package [`eventstudyinteract`](https://github.com/lsun20/EventStudyInteract). I used newbing to help me with programming, and it is very helpful for beginners. - I used [`FixedEffectModels.jl`](https://github.com/FixedEffects/FixedEffectModels.jl) directly for estimation and I am grateful to the author of this package. Other parts of this package, such as reporting of estimation results, also refer to [`FixedEffectModels.jl`](https://github.com/FixedEffects/FixedEffectModels.jl). - The Stata package [`eventstudyinteract`](https://github.com/lsun20/EventStudyInteract) is very flexible, and one important feature is that it can compare event study estimates for subsamples, i.e. perform heterogeneous estimation. I did not find this feature in the existing Julia package [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) or the  R packages [`fixest`](https://lrberge.github.io/fixest/). I think the design of the Stata package [`eventstudyinteract`](https://github.com/lsun20/EventStudyInteract) is more user-friendly. - This package fully supports the features of [`FixedEffectModels.jl`](https://github.com/FixedEffects/FixedEffectModels.jl), such as using GPU for estimation. The syntax of this package is similar to that of [`FixedEffectModels.jl`](https://github.com/FixedEffects/FixedEffectModels.jl). ## Installation The package is registered in the [`General`](https://github.com/JuliaRegistries/General) registry and so can be installed at the REPL with `] add EventStudyInteracts`. ## Syntax ```julia result = reg(df, formula, rel_varlist::Vector{Symbol}, control_cohort::Symbol, cohort::Symbol, vcov, contrasts = contrasts, weights = weights, save = save, method = method, nthreads = nthreads, double_precision = double_precision, tol = tol, maxiter = maxiter, drop_singletons = drop_singletons, progress_bar = progress_bar, dof_add = dof_add, subset = subset) ``` The syntax is similar to [`FixedEffectModels.jl`](https://github.com/FixedEffects/FixedEffectModels.jl) (You must use a version higher than v1.9.1),but users need to specify separately `rel_varlist::Vector{Symbol}`, `control_cohort::Symbol`, and `cohort::Symbol`. The `rel_varlist` is the list of relative time indicators as you would have included in the canonical two-way fixed effects regression. The `rel_varlist` must be defined as a `Vector{Symbol}`. ``` rel_varlist = Symbol[:g_4, :g_3, :g_2, :g0, :g1, :g2, :3] ``` See illustration for an example of generating these relative time indicators. The relative time indicators should take the value of zero for never treated units. Users should shape their dataset to a long format where each observation is at the unit-time level. See illustration for an example of specifying the syntax. The syntax is similar to [`FixedEffectModels.jl`](https://github.com/FixedEffects/FixedEffectModels.jl) in specifying fixed effects and the type of standard error reported. Furthermore, it also requires the user to specify the cohort categories as well as which cohort is the control cohort. Note that [Sun and Abraham (2021)](https://www.sciencedirect.com/science/article/abs/pii/S030440762030378X) only establishes the validity of the IW estimators for balanced panel data without covariates. eventstudyinteract does not impose a balanced panel by dropping units with observations that are missing in any iod. Instead, it evaluates the IW estimators for unbalanced panel data by estimating the interacted regression using all observations. The `control_cohort` must be defined as a `Symbol`, which is a binary variable that corresponds to the control cohort, which can be never-treated units or last-treated units. If using **last-treated** unit as control cohort, **exclude the time periods when the last cohort receives treatment**. The `cohort` must be defined as a `Symbol`, which is a categorical variable that corresponds to the initial treatment timing of each unit. If there are units that receive multiple treatments, [Sun and Abraham (2021)](https://www.sciencedirect.com/science/article/abs/pii/S030440762030378X) defines the initial treatment timing to be based on the first treatment. This categorical variable should be set to be **missing** for **never treated** units. ## Examples - You can download the `nlswork.dta` data from the repository, which is the example data used by [`eventstudyinteract`](https://github.com/lsun20/EventStudyInteract), and the method of generating variables is the same as that of [`eventstudyinteract`](https://github.com/lsun20/EventStudyInteract). ```julia using DataFrames using FixedEffectModels using EventStudyInteract using ReadStatTables using RegressionTables using CUDA using Plots # Load the 1968 extract of the National Longitudinal Survey of Young Women and Mature Women. df =DataFrame(readstat(EventStudyInteracts\dataset\nlswork.dta")) # Code the cohort categorical variable based on when the individual first joined the union, which will be inputted in cohort(varname). df.union_year = ifelse.(coalesce.(df.union, false) .== 1, df.year, missing) # This is really frustrating. In Stata, the simple code bysort idcode: egen first_union = min(union_year) can achieve this. Why is Julia so complicated? function min_skipmissing(x) v = collect(skipmissing(x)) return isempty(v) ? missing : minimum(v) end transform!(groupby(df, :idcode), :union_year => min_skipmissing => :first_union) select!(df, Not(:union_year)) # Code the relative time categorical variable. df.ry = df.year - df.first_union # For the first example, we take the control cohort to be individuals that never unionized. df.never_union = ismissing.(df.first_union) # Check if there is a sufficient number of treated units for each relative time. With very few units it might be better to bin the relative times and assume constant treatment effects within the bin. function tab1(df::DataFrame, catevar::Symbol) gdf = groupby(df, catevar) result = combine(gdf, nrow => :freq) result.percent = result.freq / nrow(df) * 100 sort!(result, catevar) result.cum = cumsum(result.percent) return result end tab1(df,:ry) # We will consider the dynamic effect of union status on income. We first generate these relative time indicators, and leave out the distant leads due to few observations. Implicitly this assumes that effects outside the lead windows are zero. relmin = abs(minimum(skipmissing(df.ry))) relmax = abs(maximum(skipmissing(df.ry))) for k in relmin:-1:2 df[!, Symbol("g_$k")] = Int.(coalesce.(df.ry .== -k, false)) end for k in 0:relmax df[!, Symbol("g$k")] = Int.(coalesce.(df.ry .== k, false)) end absorb = [:idcode,:year] formula1 = term(:ln_wage) ~ term(:south) + sum(fe.(term.(absorb))) # To test whether the package can run successfully when there are collinear variables. df.g_19 .= 0 # The rel_varlist must be defined as a Vector{Symbol}. In the example below, when defining an empty Vector, you cannot use rel_varlist1 = []. rel_varlist1 = Symbol[:g_4, :g_5] for i in relmin:-1:2 push!(rel_varlist1, Symbol("g_"*string(i))) end for i in 0:relmax push!(rel_varlist1, Symbol("g"*string(i))) end control_cohort1 = :never_union cohort1 = :first_union vcov1 = Vcov.cluster(:idcode) m1 = eventreg(df, formula1, rel_varlist1, control_cohort1, cohort1, vcov1) # EventStudyInteract IW estimator # ======================================================================== # Number of obs: 27979 Degrees of freedom: 166 # R2: 0.666 R2 Adjusted: 0.664 # F-Stat: 2.81691 p-value: 0.000 # R2 within: 0.030 Iterations: 11 # ======================================================================== # ln_wage | Estimate Std.Error t value Pr(>|t|) Lower 95% Upper 95% # ------------------------------------------------------------------------ # g_19 | 0.0 0.0 NaN NaN 0.0 0.0 # g_18 | -0.0609283 0.0513893 -1.18562 0.236 -0.161679 0.0398221 # g_17 | -0.0489819 0.0432146 -1.13346 0.257 -0.133706 0.0357418 # g_16 | -0.0680484 0.0495311 -1.37385 0.170 -0.165156 0.0290589 # g_15 | -0.135218 0.0448805 -3.01284 0.003 -0.223208 -0.0472281 # g_14 | -0.103295 0.0443376 -2.32975 0.020 -0.190221 -0.01637 # g_13 | -0.0684827 0.0416284 -1.6451 0.100 -0.150097 0.0131311 # g_12 | -0.132015 0.0385567 -3.42392 0.001 -0.207606 -0.0564232 # g_11 | -0.15239 0.0376567 -4.04683 0.000 -0.226217 -0.078563 # g_10 | -0.11842 0.0291013 -4.06925 0.000 -0.175474 -0.0613663 # g_9 | -0.172996 0.0330077 -5.24109 0.000 -0.237709 -0.108284 # g_8 | -0.116192 0.030757 -3.77773 0.000 -0.176492 -0.0558915 # g_7 | -0.140938 0.0287493 -4.90233 0.000 -0.197302 -0.0845745 # g_6 | -0.133223 0.0369878 -3.60181 0.000 -0.205739 -0.0607073 # g_5 | -0.131416 0.0238826 -5.50261 0.000 -0.178239 -0.0845938 # g_4 | -0.150598 0.0330246 -4.56016 0.000 -0.215344 -0.0858518 # g_3 | -0.0559142 0.0202356 -2.76316 0.006 -0.0955869 -0.0162416 # g_2 | -0.0565837 0.0191366 -2.95683 0.003 -0.0941016 -0.0190657 # g0 | 0.0515795 0.0146284 3.52598 0.000 0.0229 0.0802591 # g1 | 0.0961542 0.0194692 4.93879 0.000 0.0579842 0.134324 # g2 | 0.0677024 0.0182556 3.70858 0.000 0.0319116 0.103493 # g3 | 0.0663372 0.018431 3.59923 0.000 0.0302027 0.102472 # g4 | 0.132223 0.0276378 4.78414 0.000 0.0780381 0.186408 # g5 | 0.0565864 0.0182183 3.10603 0.002 0.0208689 0.0923039 # g6 | 0.117224 0.0215077 5.4503 0.000 0.0750571 0.15939 # g7 | 0.072123 0.0221207 3.26042 0.001 0.0287545 0.115491 # g8 | 0.0666257 0.0193959 3.43504 0.001 0.0285993 0.104652 # g9 | 0.0929835 0.0349948 2.65707 0.008 0.024375 0.161592 # g10 | 0.0675955 0.0237323 2.84825 0.004 0.0210676 0.114124 # g11 | 0.106953 0.0212674 5.02896 0.000 0.0652575 0.148649 # g12 | 0.0647985 0.0365021 1.7752 0.076 -0.00676515 0.136362 # g13 | 0.134787 0.0412699 3.26599 0.001 0.0538762 0.215698 # g14 | 0.155875 0.0501801 3.10631 0.002 0.0574951 0.254255 # g15 | 0.0665542 0.0426601 1.56011 0.119 -0.0170823 0.150191 # g16 | 0.181412 0.0511286 3.54815 0.000 0.0811727 0.281651 # g17 | 0.0233864 0.0438817 0.532943 0.594 -0.0626452 0.109418 # g18 | -0.0477967 0.0750543 -0.636828 0.524 -0.194943 0.0993498 # ======================================================================== ``` - **Event study plots**. We may define a ``coefplot`` function for an event study plot. ```julia function mycoefplot(m) n = coefnames(m) vals = coef(m) errors = stderror(m) Plots.scatter( n, vals, legend = false, yerror = 1.96 .* errors, #title = "Coefficient plot", xtickfont = font(10, "Times"), ytickfont = font(10, "Times"), titlefont = font(14, "Times"), # markersize = 2 ) Plots.vline!([3.5,],linestyle = :dash,linecolor=:red) Plots.hline!([0,],linestyle = :dash,linecolor=:black,linewidth=:2) end plot1 = mycoefplot(m1)1 = mycoefplot(m1) ``` - **Binning**. Pre-treatment effects seem relatively constant, which might suggest binning the many leads.  TODO: current implementation of bins does not follow Sun and Abraham (2020) exactly due to coding challenge.  But it is valid if effects in the bin are constant for each cohort. ```julia df.g_l4 = Int.(coalesce.(df.ry .<= -4, false)) rel_varlist2 = Symbol[:g_l4] for i in 3:-1:2 push!(rel_varlist2, Symbol("g_"*string(i))) end for i in 0:18 push!(rel_varlist2, Symbol("g"*string(i))) end m2 = eventreg(df, formula1, rel_varlist2, control_cohort1, cohort1, vcov1) ``` - **Using the last treated as the control cohort**. Alternatively, we can take the control cohort to be individuals that were unionized last. ```julia df.last_union = Int.(coalesce.(df.first_union .== 88, false)) control_cohort2 = :last_union # If using the last-treated cohort as the control, be sure to restrict the analysis sample to exclude the never-treated (if any) and to be before the treated periods for the last-treated cohort. m3 = eventreg(df[(.!ismissing.(df.first_union)) .& (df.year .< 88), :], formula1, rel_varlist2, control_cohort1, cohort1, vcov1) ``` - **Aggregating event study estimates**. In Stata one can use `lincom` looks for coefficients and variance covariance matrix stored in e(b) and e(V). There is no package like ``lincom`` in Julia. I am still working on this. - **Compare event study estimates for subsamples**. Suppose we want to compare the average effect over the first five years of joining the union between college graduates and non-college graduates. We can first estimate their separate effects by interacting the relative time indicators with icator of college graduates: ```julia for k in 18:-1:2 df[!, Symbol("g_", k, "_collgrad0")] = ifelse.(coalesce.(df.ry .== -k, false) .& coalesce.(df.collgrad .== 0, false), 1, 0) end for k in 0:18 df[!, Symbol("g", k, "_collgrad0")] = ifelse.(coalesce.(df.ry .== k, false) .& coalesce.(df.collgrad .== 0, false), 1, 0) end df.g_l4_collgrad0 = ifelse.(coalesce.(df.ry .<= -4, false) .& coalesce.(df.collgrad .== 0, false), 1, 0) for k in 18:-1:2 df[!, Symbol("g_", k, "_collgrad1")] = ifelse.(coalesce.(df.ry .== -k, false) .& coalesce.(df.collgrad .== 1, false), 1, 0) end for k in 0:18 df[!, Symbol("g", k, "_collgrad1")] = ifelse.(coalesce.(df.ry .== k, false) .& coalesce.(df.collgrad .== 1, false), 1, 0) end df.g_l4_collgrad1 = ifelse.(coalesce.(df.ry .<= -4, false) .& coalesce.(df.collgrad .== 1, false), 1, 0) rel_varlist3 = Symbol[:g_l4_collgrad0] for i in 3:-1:2 push!(rel_varlist3, Symbol("g_"*string(i)*"_collgrad0")) end for i in 0:18 push!(rel_varlist3, Symbol("g"*string(i)*"_collgrad0")) end push!(rel_varlist3, :g_l4_collgrad1) for i in 3:-1:2 push!(rel_varlist3, Symbol("g_"*string(i)*"_collgrad1")) end for i in 0:18 push!(rel_varlist3, Symbol("g"*string(i)*"_collgrad1")) end m4 = eventreg(df, formula1, rel_varlist3, control_cohort1, cohort1, vcov1) ``` ## Output `eventreg` returns a light object like ``FixedEffectModels.reg``. It is composed of the vector of coefficients & the covariance matrix (use coef, coefnames, vcov on the output of reg) a boolean vector reporting rows used in the estimation a set of scalars (number of observations, the degree of freedoms, r2, etc). We can use RegressionTables.jl to get the Regression Tables. ```julia regtable(m1, m2, m3,m4; renderSettings = asciiOutput(), estim_decoration=make_estim_decorator([0.01, 0.05, 0.1])) regtable(m1, m2, m3,m4; renderSettings = htmlOutput("base_reg.html"), estim_decoration=make_estim_decorator([0.01, 0.05, 0.1])) ``` ## Use other features of FixedEffectModels.jl We can also use other features of FixedEffectModels.jl, such as using GPU for estimation. ```julia eventreg(df, formula1, rel_varlist1, control_cohort1, cohort1, vcov1, method = :gpu, double_precision = false) ``` ## Another example Refer to [Difference-in-Difference (DiD) | DiD](https://asjadnaqvi.github.io/DiD/). ```julia # Generate sample data using Random units = 30 start = 1 finish = 60 nlvls = 5 time = finish - start + 1 obsv = units * time df = DataFrame(id = repeat(1:units, inner=time), t = repeat(start:finish, outer=units)) Random.seed!(20211222) df.Y .= 0 # outcome variable df.D .= 0 # intervention variable df.cohort .= repeat([rand(0:nlvls) for i in 1:units], inner=time) # treatment cohort effect = [rand(2:10) for i in unique(df.cohort)] first_treat = [rand(start:(finish + 20)) for i in unique(df.cohort)] df.effect = similar(df.cohort) df.first_treat = similar(df.cohort, Union{Int64, Missing}) for i in 0:nlvls df.effect[df.cohort .== i] .= effect[i+1] df.first_treat[df.cohort .== i] .= first_treat[i+1] end df.first_treat[df.first_treat .> finish] .= missing df.D = ifelse.(coalesce.(df.t .>= df.first_treat, false), 1, 0) df.rel_time .= df.t .- df.first_treat df.Y = df.id .+ df.t .+ ifelse.(df.D .== 1, df.effect .* df.rel_time, 0) .+ randn(nrow(df)) plot(df.t, df.Y, label=false) tab1(df,:cohort) df.never_treat = ismissing.(df.first_treat) tab1(df,:rel_time) # We will consider the dynamic effect of union status on income. We first generate these relative time indicators, and leave out the distant leads due to few observations. Implicitly this assumes that effects outside the lead windows are zero. relmin = abs(minimum(skipmissing(df.rel_time))) relmax = abs(maximum(skipmissing(df.rel_time))) for k in relmin:-1:2 df[!, Symbol("g_$k")] = Int.(coalesce.(df.rel_time .== -k, false)) end for k in 0:relmax df[!, Symbol("g$k")] = Int.(coalesce.(df.rel_time .== k, false)) end absorb = [:id,:t] formula1 = term(:Y) ~ sum(fe.(term.(absorb))) rel_varlist1 = Symbol[] for i in relmin:-1:2 push!(rel_varlist1, Symbol("g_"*string(i))) end for i in 0:relmax push!(rel_varlist1, Symbol("g"*string(i))) end control_cohort1 = :never_treat cohort1 = :first_treat m5 = eventreg(df, formula1, rel_varlist1, control_cohort1, cohort1) plot2 = mycoefplot(m5) ``` ## Performance EventStudyInteracts.jl is **3.69** times faster than Stata when controlling only for id and year fixed effects with a sample size of 2 million observations. EventStudyInteracts.jl is **4.75** times faster than Stata when controlling for an additional two fixed effects. As the sample size increases and more fixed effects are controlled for, performance improvement should be even greater. Furthermore, EventStudyInteracts.jl can also utilize CUDA. Many thanks to FixedEffectModels.jl for its outstanding performance! - Julia Codes ```julia using CSV, DataFrames, Random, Plots, FixedEffectModels, EventStudyInteracts units = 100000 start = 1 finish = 20 nlvls = 5 time = finish - start + 1 obsv = units * time K=100 id1 = rand(1:(obsv/K), obsv) id2 = rand(1:K, obsv) df = DataFrame(id = repeat(1:units, inner=time), t = repeat(start:finish, outer=units), id1 = id1, id2 = id2) Random.seed!(20211222) df.Y .= 0 # outcome variable df.D .= 0 # intervention variable df.cohort .= repeat([rand(0:nlvls) for i in 1:units], inner=time) # treatment cohort effect = [rand(2:10) for i in unique(df.cohort)] first_treat = [rand(start:(finish + 20)) for i in unique(df.cohort)] df.effect = similar(df.cohort) df.first_treat = similar(df.cohort, Union{Int64, Missing}) for i in 0:nlvls df.effect[df.cohort .== i] .= effect[i+1] df.first_treat[df.cohort .== i] .= first_treat[i+1] end df.first_treat[df.first_treat .> finish] .= missing df.D = ifelse.(coalesce.(df.t .>= df.first_treat, false), 1, 0) df.rel_time .= df.t .- df.first_treat df.Y = df.t .+ ifelse.(df.D .== 1, df.effect .* df.rel_time, 0) .+ randn(nrow(df)) plot(df.t, df.Y, label=false) df.never_treat = ismissing.(df.first_treat) # We will consider the dynamic effect of union status on income. We first generate these relative time indicators, and leave out the distant leads due to few observations. Implicitly this assumes that effects outside the lead windows are zero. relmin = abs(minimum(skipmissing(df.rel_time))) relmax = abs(maximum(skipmissing(df.rel_time))) for k in relmin:-1:2 df[!, Symbol("g_$k")] = Int.(coalesce.(df.rel_time .== -k, false)) end for k in 0:relmax df[!, Symbol("g$k")] = Int.(coalesce.(df.rel_time .== k, false)) end absorb = [:id,:t] formula1 = term(:Y) ~ sum(fe.(term.(absorb))) rel_varlist1 = Symbol[] for i in relmin:-1:2 push!(rel_varlist1, Symbol("g_"*string(i))) end for i in 0:relmax push!(rel_varlist1, Symbol("g"*string(i))) end control_cohort1 = :never_treat cohort1 = :first_treat CSV.write("bench.csv", df) m1 = eventreg(df, formula1, rel_varlist1, control_cohort1, cohort1) @time m1 = eventreg(df, formula1, rel_varlist1, control_cohort1, cohort1) # 76.965495 seconds (395.81 k allocations: 218.291 GiB, 23.78% gc time) absorb = [:id,:id1,:id2,:t] formula2 = term(:Y) ~ sum(fe.(term.(absorb))) @time m2 = eventreg(df, formula2, rel_varlist1, control_cohort1, cohort1) # 88.459680 seconds (3.09 M allocations: 218.534 GiB, 21.19% gc time, 0.86% compilation time) ``` - Stata Codes ```stata import delimited "~\EventStudyInteracts\benchmark\bench.csv", clear timer clear set rmsg on gen never_treat1 = never_treat=="true" eventstudyinteract y g_* g0-g16, cohort(first_treat) control_cohort(never_treat1) absorb(i.id i.t) r; t=284.17 eventstudyinteract y g_* g0-g16, cohort(first_treat) control_cohort(never_treat1) absorb(i.id i.id1 i.id2 i.t) r; t=420.61 ``` ## References [GitHub - FixedEffects/FixedEffectModels.jl: Fast Estimation of Linear Models with IV and High Dimensional Categorical Variables](https://github.com/FixedEffects/FixedEffectModels.jl) [lsun20/EventStudyInteract (github.com)](https://github.com/lsun20/EventStudyInteract) [Difference-in-Difference (DiD) | DiD](https://asjadnaqvi.github.io/DiD/)
EventStudyInteracts
https://github.com/xiaobaaaa/EventStudyInteracts.jl.git
[ "MIT" ]
0.5.4
cd8f9da92f751a1fc421120c66971d008d695cdb
code
585
using Scanf using Documenter DocMeta.setdocmeta!(Scanf, :DocTestSetup, :(using Scanf); recursive=true) makedocs(; modules=[Scanf], authors="KlausC <[email protected]> and contributors", repo="https://github.com/KlausC/Scanf.jl/blob/{commit}{path}#{line}", sitename="Scanf.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://KlausC.github.io/Scanf.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/KlausC/Scanf.jl", )
Scanf
https://github.com/KlausC/Scanf.jl.git
[ "MIT" ]
0.5.4
cd8f9da92f751a1fc421120c66971d008d695cdb
code
24378
module Scanf using BufferedStreams export @scanf, @sscanf, scanf const EOF = -1 const ARGNUM_TYPE = UInt16 const WIDTH_TYPE = UInt32 # whitespace characters in format strings const WHITESPACE = b" \n\t\r\f\v" # format escape character const ESC = UInt8('%') # format specifier to skip whitespace const SKIP = UInt8('_') # format indicator no-assign const NOASSIGN = UInt8('*') # format specifiers for character sets const CSOPEN = UInt8('[') const CSCLOSE = UInt8(']') const CSNEG = UInt8('^') const CSMINUS = UInt8('-') # format specifier categories const Ints = Union{Val{'d'},Val{'i'},Val{'u'},Val{'x'},Val{'X'},Val{'o'}} const Floats = Val{'f'} const Chars = Val{'c'} const Strings = Val{'s'} const Pointer = Val{'p'} const HexBases = Union{Val{'x'},Val{'X'},Val{'a'},Val{'A'}} const DecBases = Union{Val{'d'},Val{'u'}} const OctBases = Val{'o'} const IntBases = Val{'i'} const PositionCounter = Val{'n'} const Whitespace = Val{Char(SKIP)} const CharSets = Union{Val{Char(CSOPEN)},Val{Char(CSNEG)}} const EscapeChar = Val{Char(ESC)} const DECIMAL = b"0123456789" const OCTAL = b"01234567" const HEXADECIMAL = b"0123456789ABCDEFabcdef" abstract type AbstractSpec{T} end """ Spec{T} Typed representation of a format specifier. `T` is a `Val{'X'}`, where `X` is a valid format specifier character. Special case `X == '_'` represents whitespace (not assigning) See also `CharsetSpec` and `LiteralSpec`. """ struct Spec{T<:Val} <: AbstractSpec{T} # T => %type => Val{'type'} assign::ARGNUM_TYPE width::WIDTH_TYPE end """ CharsetSpec{T,S} Format specifier representing a character set (inclusive or exclusive) """ struct CharsetSpec{T<:Val,S} <: AbstractSpec{T} assign::ARGNUM_TYPE width::WIDTH_TYPE set::S end """ LiteralSpec{S<:AbstractString} Non-assigning Format specifier representing a literal matching string. """ struct LiteralSpec{S} <: AbstractSpec{0} string::S end # replace double %% by single % function LiteralSpec(str::T) where {T<:AbstractString} if contains(str, "%%") str = replace(str, "%%" => "%") S = typeof(str) else S = T end LiteralSpec{S}(str) end """ Scanf.Format(format_str) Create a C scanf-compatible format object that can be used for parse formatted texts. The input `format_str` can include any valid format specifier character and modifiers. A `Format` object can be passed to `scanf(str::String, f::Format, args...)` to parse a formatted string, or `scanf(io::IO, f::Format, args...)` to parse the formatted string directly from `io`. For convenience, the `Scanf.format"..."` string macro form can be used for building a `Scanf.Format` object at macro-expansion-time. The `@scanf` macro converts a literal string into a `Scanf.Format` implicitly. """ struct Format{S,T} str::S # original full format string as CodeUnits formats::T # Tuple of Specs (including whitespace specs and literal specs) end """ Scanf.scanf(b::String, f::Scanf.Format, args...) Scanf.scanf([io::IO,] f::Scanf.Format, args...) Apply a Scanf format object `f` to provided String (1st method), or scan directly from an `io` object (2nd method). See [`@scanf`](@ref) for more details on C `scanf` support. `io` defaults to `stdin`. The args determine the type and default value for the output data. Return the number of assigned arguments, followed by the assigned output data. """ function scanf end scanf(io::IO, f::Format, args...) = scanner(io, f, args...) scanf(io::Base.TTY, f::Format, args...) = scanf(BufferedInputStream(io), f, args...) scanf(f::Format, args...) = scanf(stdin, f, args...) scanf(str::AbstractString, f::Format, args...) = scanf(IOBuffer(str), f, args...) """ @scanf([io:Union{IO,String}, ], "%Fmt", args::...) Scan input stream or string of using C `scanf` style format specification string and assign values to arguments. The format string (not a variable) is analyzed at macro expansion time. Equivalent to `scanf(io, Scanf.format"%Fmt", args...)`. # Examples ```jldoctest r, a... = @scanf("%f%f%f%f", zeros(4)...) julia> r, a, b = @scanf "23.4 text" "%f %2s" Float64 String (2, 23.4, "te") ``` """ macro scanf(arg, args...) n = length(args) if arg isa String && !(n > 0 && args[1] isa String) fmt = arg io = :stdin elseif n >= 1 && args[1] isa String fmt = args[1] io = arg args = Base.tail(args) else throwa("invalid macro arguments: @scanf $arg $(join(args, ' '))") end f = Format(unescape_string(fmt)) return esc(:($Scanf.scanf($io, $f, $(args...)))) end """ Scanf.format"..." Convenience string macro to call `Scanf.Format("...") """ macro format_str(str) str = unescape_string(str) esc(:(Scanf.Format($str))) end # Implementation details # construct Format object by parsing the format string function Format(f::AbstractString) isempty(f) && throwa("empty format string") bytes = codeunits(f) len = length(bytes) fmts = AbstractSpec[] pos, b = pushliteral!(fmts, f, bytes, 1) ac = 0 # count number of assigning specifiers while pos <= len || b == SKIP assign = true width = 0 charset = nothing if b == ESC b = bytes[pos] pos += 1 # positioned at start of first format str % # parse flags if b == NOASSIGN assign = false pos > len && throwa("incomplete format string: '$f'") b = bytes[pos] pos += 1 end # parse width while 0x00 <= b - UInt8('0') < 0x0a width = 10 * width + (b - UInt8('0')) b = bytes[pos] pos += 1 pos > len && break end if !(0 <= width <= typemax(WIDTH_TYPE)) throwi("\"$f\", width not in 1..$(typemax(Int32))") end # type modifier characters (ignored) if b == UInt8('h') || b == UInt8('l') prev = b pos > len && throwa("incomplete format string: \"$f\"") b = bytes[pos] pos += 1 if b == prev # cases "ll" and "hh" pos > len && throwa("incomplete format string: \"$f\"") b = bytes[pos] pos += 1 end elseif b in b"Ljqtz" # more type modifiers (ignored) b = bytes[pos] pos += 1 end # parse conversion specifier if b in b"diouxXcspn" # uper case variants are invalid type = Val{lowercase(Char(b))} elseif b in b"eEfFgGaA" type = Val{Char('f')} elseif b == CSOPEN txt = "[" start = pos xpos = findnext(isequal(CSCLOSE), bytes, start) if start <= len && bytes[start] == CSNEG b = CSNEG txt = "[^" start += 1 end if xpos === nothing throwi("\"$f\", after '$txt' a Char(CSCLOSE) is missing") end if bytes[start] == CSCLOSE # first character after "[" or "[^" xpos = findnext(isequal(CSCLOSE), bytes, start + 1) end if (xpos === nothing || start >= xpos) throwi("\"$f\", after '$txt]' a Char(CSCLOSE) is missing") end charset = view(bytes, start:(xpos-1)) pos = xpos + 1 type = Val{Char(b)} else throwi("\"$f\", invalid conversion specifier: '$(Char(b))'") end else # format contains a WS character type = Whitespace assign = false end ac += assign ass = ifelse(assign, ac, 0) if ass > typemax(ARGNUM_TYPE) throwi("\"$f\", too many assignable conversion specifiers") end push!(fmts, make_spec(type, ass, width, charset)) pos, b = pushliteral!(fmts, f, bytes, pos) end return Format(bytes, Tuple(fmts)) end # consume characters in format string up to next % or whitespace and insert LiteralSpec @inline function pushliteral!(fmts, f, bytes, pos) len = length(bytes) start = pos b = 0x00 j = -1 while pos <= len b = bytes[pos] pos += 1 if b == ESC pos > len && throwa("incomplete format string: \"$f\"") if bytes[pos] == ESC # "%%" will be removed in LiteralSpec pos += 1 else j = pos - 2 break end elseif b in WHITESPACE j = pos - 2 while pos <= len && bytes[pos] in WHITESPACE pos += 1 end b = SKIP break end end j = j < 0 ? pos - 1 : j start <= j && push!(fmts, LiteralSpec(SubString(f, start:j))) return pos, b end Format(f::Format) = f # extract text items from input stream # match literal strings @inline function fmt(io, pos, spec::LiteralSpec) str = spec.string len = sizeof(str) ix = 1 while ix <= len && !eof(io) c = str[ix] peek(io, Char) != c && break skip(io, ncodeunits(c)) ix = nextind(str, ix) end l = ix - 1 IOBuffer(), l == len, pos + l end # skip whitespace spec @inline function fmt(io, pos, ::Spec{Whitespace}) pos = skip_ws(io, pos) IOBuffer(), true, pos end # string spec @inline function fmt(io, pos, spec::Spec{T}) where {T<:Strings} pos = skip_ws(io, pos) width = spec.width l = 0 out = IOBuffer() while (width == 0 || l < width) && !eof(io) c = peek(io, Char) (isspace(c) || !isvalid(Char, c)) && break write(out, c) n = ncodeunits(c) skip(io, n) l += 1 end out, l > 0, pos + l end # charset and chars specs @inline function fmt(io, pos, spec::S) where {S<:Union{CharsetSpec,Spec{<:Chars}}} width = spec.width width = ifelse(width == 0, S <: Spec{<:Chars} ? 1 : typemax(Int), width) l = 0 out = IOBuffer() while l < width && !eof(io) c = peek(io, Char) n = ncodeunits(c) check_set(c, spec) || break skip(io, n) write(out, c) l += 1 pos += 1 end out, l > 0, pos end # integer specs @inline function fmt(io, pos, spec::Spec{T}) where {T<:Ints} pos = skip_ws(io, pos) out = IOBuffer() eof(io) && return out, false, pos width = spec.width width = ifelse(width == 0, typemax(Int), width) l = 0 sig = false b = peek(io) negate = false if b in b"+-" l = writeskip(io, out, b, l) negate = b == UInt('-') sig = true end digits = DECIMAL base, digits = basespec(T) ndig = 0 if base === nothing || base == 16 b = peek(io) if b == UInt('0') ndig += 1 l = writeskip(io, out, b, l) if !eof(io) && (b = peek(io)) in b"xX" digits = HEXADECIMAL l = writeskip(io, out, b, l) ndig = 0 elseif base === nothing digits = OCTAL end end end while l < width && !eof(io) b = peek(io) if b in digits ndig += 1 l = writeskip(io, out, b, l) else break end end succ = ndig > 0 out, succ, pos + l end # pointer spec @inline function fmt(io, pos, spec::Spec{T}) where {T<:Pointer} pos = skip_ws(io, pos) out = IOBuffer() eof(io) && return out, false, pos width = spec.width width = ifelse(width == 0, typemax(Int), width) digits = HEXADECIMAL l = 0 while l < width && !eof(io) b = peek(io) if l == 0 && b == UInt8('0') l = writeskip(io, out, b, l) if !eof(io) && (b = peek(io)) in b"xX" l = writeskip(io, out, b, l) end elseif b in digits l = writeskip(io, out, b, l) else break end end out, l > 2, pos + l end # floating point spec @inline function fmt(io, pos, spec::Spec{T}) where {T<:Floats} pos = skip_ws(io, pos) width = spec.width width = ifelse(width == 0, typemax(Int), width) digits = DECIMAL expch = b"eEfF" x_sign = 0x001 x_sep = 0x002 x_exp = 0x004 x_base = 0x008 x_inexp = 0x010 x_nexp = 0x020 x_mdigits = 0x040 x_edigits = 0x080 x_infnan = 0x100 l = 0 out = IOBuffer() status = x_sign | x_sep | x_base | x_edigits | x_infnan while l < width && !eof(io) b = peek(io) if status & x_base != 0 && b == UInt8('0') l = writeskip(io, out, b, l) if !eof(io) && (b = peek(io)) in b"xX" digits = HEXADECIMAL expch = b"pP" l = writeskip(io, out, b, l) else status |= x_mdigits end status = (status | x_exp | x_edigits) & ~(x_base | x_sign | x_infnan) continue elseif b in digits status = (status | x_exp) & ~(x_base | x_sign | x_infnan) status |= (status & x_inexp != 0) ? x_edigits : x_mdigits elseif b == UInt8('-') && (status & x_sign) != 0 status |= ifelse(status & x_base == 0, x_nexp, 0) status = status & ~x_sign elseif b == UInt8('+') && (status & x_sign) != 0 status = status & ~x_sign elseif b == UInt8('.') && (status & x_sep) != 0 status = status & ~(x_base | x_sign | x_sep | x_infnan) elseif b in expch && (status & x_exp) != 0 status = (status & ~(x_base | x_exp | x_edigits | x_sep)) | x_sign | x_inexp digits = DECIMAL elseif b in b"iI" && (status & x_infnan) != 0 n = expect(io, out, b"INFINITY", 3) l = (n == 3 || n == 8) ? l + n : 0 status |= x_mdigits | x_edigits break elseif b in b"nN" && (status & x_infnan) != 0 n = expect(io, out, b"NAN", 3) l = n == 3 ? l + n : 0 status |= x_mdigits | x_edigits break else break end l = writeskip(io, out, b, l) end succ = l > 0 && (status & x_mdigits != 0) && (status & x_edigits != 0) out, succ, pos + l end # helpers for matching nan and inf @inline function expect(io::IO, out::IO, bytes::AbstractVector{UInt8}, n) mark(io) m = length(bytes) rbytes = read(io, n) if !isequiv(rbytes, bytes, n) reset(io) return 0 end write(out, rbytes) if n < m mark(io) xbytes = read(io, m - n) append!(rbytes, xbytes) if isequiv(rbytes, bytes, m) unmark(io) return m else reset(io) return n end end return n end @inline function isequiv(rbytes, bytes, n) length(rbytes) >= n || return false for i = 1:n if !(rbytes[i] == bytes[i] || rbytes[i] == bytes[i] + (UInt8('a') - UInt8('A'))) return false end end return true end # position counter spec @inline function fmt(_, pos, ::Spec{PositionCounter}) IOBuffer(string(pos - 1)), true, pos end # convert to output type specializations function toout(::Type{<:Val}, out, arg::AbstractString) r = String(take!(out)) oftype(arg, r) end function toout(::Type{<:Val}, out, arg::AbstractChar) r = String(take!(out)) length(r) >= 1 ? oftype(arg, r[1]) : arg end function toout(::Type{<:Val}, out, arg::AbstractVector{<:AbstractChar}) r = String(take!(out)) resize!(arg, length(r)) arg .= collect(r) arg end const IntsAndPointers = Union{Ints,Val{'p'},Val{'n'}} function toout(::Type{T}, out, arg::R) where {T<:IntsAndPointers,R<:Union{Real,Ptr}} S = inttype(typeof(arg)) r = String(take!(out)) x = xparse(S, r; base = basespec(T)[1]) x !== nothing ? convert(R, x) : nothing end function toout(::Type{T}, out, arg::R) where {T<:Floats,R<:Real} r = String(take!(out)) A = floattype(typeof(arg)) s = xparse(A, r) s !== nothing ? convert(R, s) : nothing end function toout(::Type{<:Strings}, out, arg::R) where R<:Real r = String(take!(out)) xparse(R, r; base = R <: Integer ? 10 : nothing) end # fmt helpers # try parse float - assume input string is syntaxtically correct @inline function xparse(::Type{A}, r::AbstractString; base = nothing) where A<:AbstractFloat if 'f' in r || 'F' in r r = replace(r, r"[fF]" => 'e') end s = tryparse(A, r) if s === nothing expos = findfirst(x -> x in "eEfF", r) negx = expos !== nothing && expos < length(r) && r[nextind(r, expos)] == '-' s = ifelse(negx, zero(A), typemax(A)) r[1] == '-' && (s = -s) end s end # try parse integers - assume input string is syntaxtically correct @inline function xparse(::Type{S}, r::AbstractString; base = nothing) where {S<:Integer} sig = r[1] in "+-" negate = r[1] == '-' n = length(r) if n >= 1 && r[1+sig] == '0' base = n >= 2 + sig && r[2+sig] in "xX" ? nothing : base === nothing ? 8 : base end if sig && S <: Unsigned r = SubString(r, 2:n) end x = tryparse(S, r; base = base) if x !== nothing && negate && S <: Unsigned x = -x end x end # skip WS characters in io stream @inline function skip_ws(io, pos) while !eof(io) b = peek(io) n = _ncodeunits(b) if n == 1 if b in WHITESPACE skip(io, 1) pos += 1 else break end else c = peek(io, Char) if isspace(c) skip(io, n) pos += 1 else break end end end pos end # consume 1 byte @inline function writeskip(io, out, b, l) write(out, b) skip(io, 1) l + 1 end itemtype(::AbstractSpec{T}) where {T<:Union{Strings,CharSets}} = Val{'s'} itemtype(::AbstractSpec{T}) where {T} = T # call the format specifiers aligned with the IO stream @inline function scanner(io::IO, f::Format, args...) n = length(args) m = countspecs(f) n == m || argmismatch(m, n) res = Any[valuefor(x) for x in args] eof(io) && return EOF, res... pos = 1 # for each format, scan arg and next substring # unroll up to 8 formats formats = f.formats N = length(formats) j = 0 UNROLL_UPTO = 8 Base.@nexprs 8 i -> begin if N >= i fi = formats[i] out, succ, pos = fmt(io, pos, fi) succ || @goto BREAK assign, argno = assignnr(fi) if assign r = toout(itemtype(fi), out, res[argno]) r === nothing && @goto BREAK res[argno] = r j += 1 end end end if N > UNROLL_UPTO for i = (UNROLL_UPTO+1):N fi = formats[i] out, succ, pos = fmt(io, pos, fi) succ || break assign, argno = assignnr(fi) if assign r = toout(itemtype(fi), out, res[argno]) r === nothing && break res[argno] = r j += 1 end end end @label BREAK return tuple(j, res...) end # utility functions # default value for types valuefor(v::AbstractVector{T}) where {T<:AbstractChar} = resize!(v, 0) valuefor(::Type{Ptr}) = Ptr{Nothing}(0) valuefor(::Type{T}) where {T<:Union{Real,Ptr,Char}} = T(0) valuefor(::Type{T}) where {T<:AbstractString} = T("") valuefor(a::T) where {T<:Union{Real,AbstractChar,AbstractString,Ptr}} = a # accessor functions assignnr(::LiteralSpec) = false, 0 assignnr(spec::AbstractSpec) = !iszero(spec.assign), Int(spec.assign) assign(spec::AbstractSpec) = assignnr(spec)[1] # showing formats # recreate the format specifier string from a typed Spec Base.string(f::Spec{Val{T}}) where {T} = string(string_header(f), T) function Base.string(f::CharsetSpec{T}) where T<:CharSets string( string_header(f), Char(CSOPEN), T <: Val{Char(CSNEG)} ? Char(CSNEG) : "", showset(f.set), Char(CSCLOSE), ) end Base.string(f::LiteralSpec) = string('"', f.string, '"') function string_header(f::AbstractSpec) string(Char(ESC), !assign(f) ? "*" : "", f.width > 0 ? f.width : "") end Base.show(io::IO, f::AbstractSpec) = print(io, string(f)) Base.show(io::IO, f::Format) = print(io, string("Scanf.format\"", String(f.str), '"')) # reconstruct internals of %[...] showset(s::UnitRange) = "$(Char(first(s)))-$(Char(last(s)))" function showset(t::Tuple{String,Vararg}) s = t[1] m, s = special(Char(CSMINUS), s) b, s = special(Char(CSCLOSE), s) string(b, s, showset.(t[2:end])..., m) end showset(t::Tuple) = string(showset.(t)...) showset(s::AbstractString) = isempty(s) ? "1-0" : s function special(x::Char, s::AbstractString) if occursin(x, s) string(x), filter(!isequal(x), s) else "", s end end # internal representation of % and whitespace format specifiers function make_spec(T, assign, width, cs) if cs === nothing || isempty(cs) Spec{T}(assign, width) else charset = make_charset(cs) CharsetSpec{T,typeof(charset)}(assign, width, charset) end end # details of internal representation of %[...] format specifiers make_charset(cs::AbstractVector{UInt8}) = make_charset(String(cs)) function make_charset(cs::String) M = Char(CSMINUS) ch = String[] ra = Any[] start = 1 stop = lastindex(cs) mind = findall(isequal(M), cs) a = start for i in mind if i > start && i < stop j = prevind(cs, i) k = nextind(cs, i) cj, ck = cs[j], cs[k] if cj < ck push!(ra, UInt32(cj):UInt32(ck)) b = prevind(cs, j) elseif cj == ck b = j else b = prevind(cs, j) end push!(ch, SubString(cs, a:b)) a = nextind(cs, k) end end push!(ch, SubString(cs, a:stop)) str = String(unique(collect(string(ch...)))) isempty(ra) ? str : isempty(str) ? (length(ra) == 1 ? ra[1] : (ra...,)) : (str, ra...) end # bases for integer specs basespec(::Type{<:HexBases}) = 16, HEXADECIMAL basespec(::Type{<:OctBases}) = 8, OCTAL basespec(::Type{<:DecBases}) = 10, DECIMAL basespec(::Type) = nothing, DECIMAL # type conversion hints for integer specs inttype(::Type{<:Float64}) = Int64 inttype(::Type{<:Float32}) = Int32 inttype(::Type{<:Float16}) = Int16 inttype(::Type{<:BigFloat}) = BigInt inttype(::Type{<:Ptr}) = UInt inttype(::Type{T}) where {T} = T floattype(::Type{T}) where {T<:Integer} = float(T) floattype(::Type{T}) where {T} = T # check if character is in or not in charset @inline check_set(c::Char, spec::Spec{<:Chars}) = true @inline check_set(c::Char, spec::CharsetSpec{Val{Char(CSOPEN)}}) = check_in(c, spec.set) @inline check_set(c::Char, spec::CharsetSpec{Val{Char(CSNEG)}}) = check_!in(c, spec.set) @inline check_in(c, set::AbstractString) = occursin(c, set) @inline check_!in(c, set::AbstractString) = !occursin(c, set) @inline check_in(c, set::UnitRange) = in(UInt32(c), set) @inline check_!in(c, set::UnitRange) = !in(UInt32(c), set) @inline check_in(c, set::Tuple) = any(x -> check_in(c, x), set) @inline check_!in(c, set::Tuple) = all(x -> check_!in(c, x), set) # count number of assigning format specifiers in format countspecs(f::Format) = count(assign, f.formats) import Base: == function ==(f::T, g::T) where {T<:Format} f.formats == g.formats end # length of utf8 encoding of character starting with this byte @inline _ncodeunits(a::UInt8) = a < 0xc0 ? 1 : a < 0xe0 ? 2 : a < 0xf0 ? 3 : 4 # error @noinline function argmismatch(a, b) throwa("mismatch between # of format specifiers and provided args: $a != $b") end @noinline throwa(msg) = throw(ArgumentError(msg)) @noinline throwi(msg) = throwa("invalid format string: " * msg) end # module
Scanf
https://github.com/KlausC/Scanf.jl.git
[ "MIT" ]
0.5.4
cd8f9da92f751a1fc421120c66971d008d695cdb
code
12289
using Test, Scanf @testset "Scanf" begin # pointer @testset "%p" begin r, p = @scanf("0x42 ", "%4p", Ptr{Nothing}) @test p == Ptr{Nothing}(UInt(0x42)) end # whitespace is squeezed @testset "whitespace" begin f = Scanf.format" " @test length(f.formats) == 1 end # %% is maintained before WS @testset "%% before WS" begin f = Scanf.format"%% " @test length(f.formats) == 2 @test f.formats[1] isa Scanf.LiteralSpec @test f.formats[2] isa Scanf.Spec{Val{Char(Scanf.SKIP)}} end # floating point numbers @testset "float to $T" for T in (Float64, Float32, Float16, BigFloat) f1 = Scanf.Format("%g") f2 = Scanf.Format("%4e") @testset "$res" for (inp, res) in ( ("-13", big"-13.0"), ("99.76 ", big"99.76"), ("42.11f3", big"42.11e3"), ("-12.7491234797912347971e-4", big"-12.7491234797912347971e-4"), ("0x1.4711p2", 0x1.4711p2) ) @test scanf(inp, f1, T) == (1, T(res)) @test scanf(inp, f2, T) == (1, parse(T, inp[1:min(4, length(inp))])) end end # floating point nan and infinity @testset "float to $T" for T in (Float64, Float32, Float16, BigFloat) f = Scanf.format"%f%n" @testset "$inp" for (inp, res, rr, nn, nc) in ( ("InfX", T(Inf), 2, 3, "X"), ("-InFX", T(-Inf), 2, 4, "X"), ("infiNITYX", T(Inf), 2, 8, "X"), ("NANX", T(NaN), 2, 3, "X"), ("-nanX", T(-NaN), 2, 4, "X"), ("infiX", T(Inf), 2, 3, "iX"), ("naX", T(0.0), 0, 0, "naX"), ) io = IOBuffer(inp) r, x, n = scanf(io, f, T(0.0), 0) @test r == rr @test n == nn @test x === res || T <: BigFloat && (x == res || isnan(x) && isnan(res)) @test peek(io, String) == nc end end @testset "marginal floats" begin end @testset "incomplete floats $inp" for inp in ("Z", "0xZ", ".Z", "e", "+e", "-e", "1eZ", "0E-Z") io = IOBuffer(inp) @test (@scanf io "%f" 0.0) == (0, 0.0) @test peek(io, Char) == inp[end] end # integers @testset "integer %i to $T" for T in (UInt64, UInt32, UInt16) f1 = Scanf.Format("%i") @testset "$res" for res in ("17", "4711", "0x7ffe") @test scanf(res, f1, T) == (1, parse(T, res)) end end sigreals = (Int64, Int32, Int16, BigInt, Float64, Float32, Float16, BigFloat) @testset "integer %i to $T" for T in sigreals f1 = Scanf.Format("%i") @testset "$res" for res in ("+17", "-4711", "0x7ffe", "-0x7ffe") @test scanf(res, f1, T) == (1, parse(T, res)) end end @testset "integer %i octal to $T " for T in sigreals @testset "$res" for (inp, res) in (("077", 63), ("-077", -63)) @test scanf(inp, Scanf.format"%i", T) == (1, res) end end @testset "incomplete integers $inp" for inp in ("Z", "0xZ",) io = IOBuffer(inp) @test (@scanf io "%i" 0) == (0, 0) @test peek(io) == UInt8('Z') end @testset "incomplete pointers $inp $arg" for inp in ("Z", "0Z", "0XZ"), arg in (Ptr{String}, Ptr{String}(0)) io = IOBuffer(inp) @test (@scanf io "%p" arg) == (0, Ptr{String}(0)) @test peek(io) == UInt8('Z') end @testset "integer %i octal input" for T in (Int64,) @test scanf("0377", Scanf.Format("%i"), T) == (1, 255) end @testset "integer %i negated input" for T in (UInt64, UInt16) @test scanf("-99", Scanf.Format("%i"), T) == (1, -T(99)) end @testset "integer %o to $T" for T in (Int64, UInt64, Int32, UInt32, Int16, UInt16) f1 = Scanf.Format("%o") @testset "$res" for res in ("17", "4711", "0377") @test scanf(res, f1, T) == (1, parse(T, res, base=8)) end end @testset "integer %x to $T" for T in (Int64, UInt64, Int32, UInt32, Int16, UInt16) f1 = Scanf.Format("%x") @testset "$res" for res in ("0x4711",) @test scanf(res, f1, T) == (1, parse(T, res)) end end @testset "convert integer to other type" begin f = Scanf.format"%i" @test scanf(" 14", f, String) == (1, "14") end @testset "%i follow up" for (inp, rr, a, b) in [ ("Z", 0, 0, ""), ("0", 1, 0, ""), ("0x", 0, 0, ""), ("0xZ", 0, 0, ""), ] f = Scanf.format"%i%s" r, x, y = scanf(inp, f, 42, String) @test r == rr @test r < 1 || a == x end # character sets @testset "character set [" begin f1 = Scanf.Format("%10[a-c ]") f2 = Scanf.Format("%10[abc ]") f3 = Scanf.Format("%10[abcx-y ]") res = " abbcbbcbadabbdbbabbbann" @test scanf(res, f1, String) == (1, res[1:10]) @test scanf(res, f2, "") == (1, res[1:10]) @test scanf(res, f3, "") == (1, res[1:10]) end @testset "character set ^" begin f1 = Scanf.Format("%10[^A-A]") f2 = Scanf.Format("%10[^A-B]") f3 = Scanf.Format("%10[^A-BX]") res = " abbcb Abadabbdbbabbbann" @test scanf(res, f1, "") == (1, res[1:7]) @test scanf(res, f2, String) == (1, res[1:7]) @test scanf(res, f3, "") == (1, res[1:7]) end @testset "string to Char" begin @test @scanf("äbc", "%s", Char[]) == (1, ['ä', 'b', 'c']) @test @scanf("äbc", "%[a-zäöü]", Char) == (1, 'ä') @test @scanf("Äbc", "%[a-zäöü]", Char[]) == (0, Char[]) @test @scanf("Äbc", "%[a-zäöü]", Char) == (0, '\0') end @testset "many arguments" begin f = Scanf.Format("%d%d%d%d%d%d%d%d%d%d ") @test scanf("1 2 3 4 5 6 7 8 9 10", f, fill(Int, 10)...)[1] == 10 end @testset "single characters" begin @test @scanf("a%bX", "a%%b%c", Char) == (1, 'X') @test @scanf("a%bX", "a%%b%c", String) == (1, "X") end @testset "multiple characters" begin v = Char[] r, cc = @scanf("abXYZ", "ab%3c", v) @test ['X', 'Y', 'Z'] == cc == v r, cc = @scanf("abXYZ", "ab%3c", Char[]) @test ['X', 'Y', 'Z'] == cc r, cc = @scanf("abXYZ", "ab%3c", Char) @test 'X' == cc r, cc = @scanf("abXYZ", "ab%3c", String) @test "XYZ" == cc end # string @testset "strings" begin r, a, b = @scanf("Hällo\u1680heimør", "%s%s", String, String) @test r == 2 @test "Hällo" == a @test "heimør" == b end # position @testset "%n" begin @test @scanf("aäc 15 16 \n", "aäc %*hhd %*Ld%n", 0) == (1, 10) @test @scanf("abc", "abd%n", Int) == (0, 0) end # basics @testset "basics" begin @test_throws ArgumentError try @eval @scanf(1, 2, 3) catch ex rethrow(ex.error) end @test @scanf("%15", "%%%d", Int) == (1, 15) @test_throws ArgumentError Scanf.Format("") @test_throws ArgumentError Scanf.Format("%") @test_throws ArgumentError Scanf.Format("%l") @test_throws ArgumentError Scanf.Format("%hh") @test_throws ArgumentError Scanf.Format("%hhU") @test_throws ArgumentError Scanf.Format("%+") @test_throws ArgumentError Scanf.Format("%.") @test_throws ArgumentError Scanf.Format("%.0") @test Scanf.Format("%%").formats[1].string == "%" @test_throws ArgumentError Scanf.Format("%y%d") @test_throws ArgumentError Scanf.Format("%\u00d0%d") @test_throws ArgumentError Scanf.Format("%\u0f00%d") @test_throws ArgumentError Scanf.Format("%\U0001ffff%d") @test_throws ArgumentError Scanf.Format("%[") @test_throws ArgumentError Scanf.Format("%[^") @test_throws ArgumentError Scanf.Format("%[]") @test_throws ArgumentError Scanf.Format("%[^]") @test Scanf.Format("%[A-A]").formats[1].set == "A" f = Scanf.Format("%d ") @test Scanf.Format(f) === f @test Scanf.format"%d " == f @test_throws ArgumentError scanf("", f) toobig_argnum = (Int64(typemax(Scanf.ARGNUM_TYPE)) + 1) @test Scanf.Format("%d"^(toobig_argnum - 1)) isa Scanf.Format @test_throws ArgumentError Scanf.Format("%d"^toobig_argnum) toobig_width = (Int64(typemax(Scanf.WIDTH_TYPE)) + 1) @test Scanf.Format("%$(toobig_width - 1)d") isa Scanf.Format @test_throws ArgumentError Scanf.Format("%$(toobig_width)d") end @testset "default arguments" begin def = (1, 2.0, "x", 'y') r, i, f, s, c = @scanf("42X", "%i%f%s%c", def...) @test r == 1 @test (i, f, s, c) == (42, def[2:end]...) end # failing literal match consumes all matching characters @testset "literal string" begin io = IOBuffer("AÖÜdef") @test scanf(io, Scanf.format"AÖÜDEF")[1] == 0 @test read(io, String) == "def" end @testset "%n" begin @test @scanf("1234", "%3d4%n", Int, 0) == (2, 123, 4) @test @scanf("😉", "%s%n", String, 0) == (2, "😉", 1) @test @scanf("1234 ", "%s%n", String, 0) == (2, "1234", 4) end @testset "show specifiers" begin f = Scanf.format"%dABC%[a-cA-C]%[^]a-cx] %[]B-Aa-zC-]%[B-A]" @test sprint(show, f.formats) == "(%d, \"ABC\", %[a-cA-C], %[^]xa-c], %*_, %[]Ca-z-], %[1-0])" @test sprint(show, f) == "Scanf.format\"%dABC%[a-cA-C]%[^]a-cx] %[]B-Aa-zC-]%[B-A]\"" end @testset "scanf from stdin" begin f1 = () -> scanf(Scanf.format"abc%i", 0) f2 = () -> @scanf "abc%i" 0 file = tempname(cleanup=true) write(file, "abc42") io = open(file) @test redirect_stdin(f1, io) == (1, 42) close(io) io = open(file) @test redirect_stdin(f2, io) == (1, 42) close(io) end @testset "overflow $T" for T in (Float64, Float32, Float16, BigFloat) @testset "$T $res" for (input, res) in [ ("+1.55e9999999999999999999", Inf), ("-1.55e+9999999999999999999", -Inf), ("1.5e-9999999999999999999", 0.0), ("-1.5e-9999999999999999999", -0.0), ] @test ((r, a) = @scanf(input, "%f", oneunit(T)); r == 1) && isequal(a, T(res)) end end @testset "overflow $T" for T in (Int128, Int64, Int32, Int16, Int8) str = "270141183460469231731687303715884105727" @testset "$T $input" for input in [str, "-" * str] @test @scanf(input, "%d", T) == (0, 0) end end @testset "overflow $T" for T in (UInt128, UInt64, UInt32, UInt16, UInt8) str = "470141183460469231731687303715884105727" @testset "$T $input" for input in [str, "-" * str] @test @scanf(input, "%d", T) == (0, 0) end end @testset "overflow Ptr" begin T = Ptr{String} input = "0x12341234abcdabcd0" @test @scanf(input, "%p", T) == (0, T(0)) end @testset "convert to different type" begin inp = "-1.5e+3" f = Scanf.format"%f" @test scanf(inp, f, "") == (1, inp) @test scanf(inp, f, Int) == (1, -1500) end @testset "convert string to $T" for T in (Int, Float32) f = Scanf.format"%s" @test scanf("-1.5f+3", f, Float64) == (1, -1500.0) @test scanf("-1.5f+3", f, Int) == (0, 0) @test scanf("-077", f, Int) == (1, -77) # like %d @test scanf("-0x77", f, Int) == (1, -119) # like %x end @testset "issue #8" begin f = Scanf.format"%2i%2i" @test scanf("7", f, Int, -777) == (1, 7, -777) f = Scanf.format"%2i%2p" @test scanf("7", f, Int, Ptr) == (1, 7, Ptr{Nothing}(0)) end @testset "issue #9" begin f = Scanf.format"%c" @test scanf("äbcd", f, '1') == (1, 'ä') @test scanf("äbcd", f, "123") == (1, "ä") @test scanf("äbcd", f, ['1']) == (1, ['ä']) end @testset "issue #11" begin f = Scanf.format"%f%fi%n" @test scanf("1.5-2.1i", f, 0.0, 0.0, 0) == (3, 1.5, -2.1, 8) @test isequal(scanf("-NaN -Infi", f, 0.0, 0.0, 0), (3, NaN, -Inf, 10)) end end # @testset "Scanf"
Scanf
https://github.com/KlausC/Scanf.jl.git
[ "MIT" ]
0.5.4
cd8f9da92f751a1fc421120c66971d008d695cdb
docs
12617
# Scanf [![Build Status](https://github.com/KlausC/Scanf.jl/workflows/CI/badge.svg)](https://github.com/KlausC/Scanf.jl/actions) [![Coverage](https://codecov.io/gh/KlausC/Scanf.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/KlausC/Scanf.jl) Scanf scans UTF8-encoded input streams or strings and creates output data according to a format string. It mimics the behaviour of the C-function with the same name. ## Usage ```julia julia> using Scanf julia> r, a, b = @scanf(" 13 This is a prime number", "%d%[ a-zA-Z]", Int, String) (2, 13, " This is a prime number") # collect data in a happy tuple julia> r, t... = @scanf "1 2 -inf 4 \u4119" "%d%u%e%x%s" 0 UInt 0.0 Int "" (5, 1, 0x0000000000000002, -Inf, 4, "䄙") # scan date-time string - note the S and ms parts use the default values julia> f = Scanf.format"%d.%2d.%2d%*1[ T]%2d:%2d:%2d.%3d"; julia> r, y, m, d, H, M, S, ms = scanf("2021.07.04T15:53", f, Int, zeros(Int8, 5)..., Int16) (5, 2021, 7, 4, 15, 53, 0, 0) ``` ## Features `Scanf` provides the macro `r, a,... = @scanf([io, ] "format_string", args...)` and the function `r, a,... = scanf(io, f::Scanf.Format, args...)`. The format string must be a string literal, which is evaluated once at macro expansion time. Alternatively `f = Scanf.format"format_string"` or `f = Scanf.Format(::AbstractString)` create a format object, which can be used in the function call. The arguments are default values of types `Real`, `AbstractChar`, `AbstractString`, `Ptr`, `AbstractVector{Char}`. They may also be concrete subtypes of `Real`, `AbstractChar`, `AbstractString`, `Ptr`. Numeric format specifiers are compatible with numeric arguments and `String`. Conversion errors may happen (float => int). If the numeric arg type is not wide enough for the value, boundary values with the correct sign are stored (e.g. `Inf`, `-0.0`). Format specifiers `c`, `s`, `[` are all compatible with arguments `Char`, `Char[]`, and `String`. In case of `Char` the first character of a string is taken. All output data are returned as a tuple including the number of assigned values as the first element. If a value cannot be parsed, the default value is assigned. In the case of no value is in the corresponding element of `arg`, the default value is derived form `T`. If the default argument is a `Vector` object, the output values are additionally stored in it. The format strings follow the definition of C++-scanf [C++ reference](https://en.cppreference.com/w/c/io/fscanf) with some adaptations: + All unicode characters are supported in format strings and input data. + in format strings, whitespace specifiers are only the ASCII space characters in `" \n\r\t\f\v"`. + in input data, all characters `x` with `isspace(x) == true` are skipped by any whitespace specifier in the format string. + The `%n$...` form of format specifications is not supported. + Optional type modifiers like `h`, `l`, `L` etc. are ignored; the target type is derived from the corresponding default argument, instead. + for type specifier `%c`, without `width` specified, the corresponding argument must have type `Char` or `String`. + for type specifier `%Nc`, with a width field `N`, the argument must have type `String` or `Vector{Char}`. This vector is re-used and resized to the number of characters actually read. + the type specifier `%n`, returns an integer value, which is the character offset in the input data, consumed by this scanf so far. + the type specifier `%p` requires a `Ptr` default argument. + The return value of both calls is the amount of output arguments, followed by all output data, the trailing ones maybe default values. In contrast to C and C++, also the arguments for `%n` are counted. ### Implementation If the input stream is exhausted before a character is read, the EOF-indicator `-1` is returned in place of the number of assigned values. For format specifiers "Whitespace", any number of characters (also zero) `x` with `isspace(x) == true` are consumed from the input stream. For a format specifier literal character, the next character is read and compared with the literal character. If it is equal, it is consumed, otherwise the process fails. If format specifier "Character" `%c` is processed, at least one character is read and assigned to the output argument. If no character is available, the process fails. If format specifier `%n` is processed, no data are consumed (and no EOF returned), but the current read position is returned. ## Description As derived from [C++ reference](https://en.cppreference.com/w/c/io/fscanf) The `scanf` function reads input from the stream pointed to by `io`, under control of the string `format` that specifies the admissible input sequences and how they are to be interpreted, using subsequent arguments to define the type of the converted input. The number of arguments must match the number of format specifiers required by the format. The format is composed of zero or more directives: one or more (ASCII) white-space characters, an ordinary (UTF8) character (neither `'%'` nor a (ASCII) white-space character), or a conversion specification. Each conversion specification is introduced by the character `'%'`. After the `'%'`, the following appear in sequence: + An optional assignment-suppressing character `'*'`. + An optional decimal integer greater than zero that specifies the maximum field width (in characters). + An optional length modifier that is not used by this implementation. + A conversion specifier character that specifies the type of conversion to be applied. The `scanf` function executes each directive of the format in turn. When all directives have been executed, or if a directive fails (as detailed below), the function returns. Failures are described as input failures (due to the occurrence of an encoding error or the unavailability of input characters), or matching failures (due to inappropriate input). A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails. A directive that is an ordinary character is executed by reading the next character of the stream. If that character differs from the directive, the directive fails and the differing and subsequent characters remain unread. Similarly, if end-of-file, an encoding error, or a read error prevents a character from being read, the directive fails. A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier. A conversion specification is executed in the following steps: Input white-space characters (as specified by the `isspace` function) are skipped, unless the specification includes a `'['`, `'c'`, or `'n'` specifier. These white-space characters are not counted against a specified field width. An input item is read from the stream, unless the specification includes an `'n'` specifier. An input item is defined as the longest sequence of input characters which does not exceed any specified field width and which is, or is a prefix of, a matching input sequence. The first character, if any, after the input item remains unread. If the length of the input item is zero, the execution of the directive fails; this condition is a matching failure unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure. Except in the case of a `'%'` specifier, the input item (or, in the case of a `'%n'` directive, the count of input characters) is converted to a type appropriate to the conversion specifier and corresponding argument. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a `*`, the result of the conversion is pushed to the ouput tuple. If the result of the conversion cannot be represented in the output type, a conversion error is thrown. Optional length modifiers `l`, `ll`, `h`, `hh`, `L`, `j`, `z`, `t` are accepted before all type specifier characters, but otherwise ignored. The conversion specifiers and their meanings are: + `d` Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the `parse(T, _, base=10)` function, where `T` is the integer type of the argument. + `i` Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the `parse(T, _, base=nothing)` function. + `o` Matches an optionally signed octal integer, whose format is the same as expected for the subject sequence of the `parse(T, _, base=8)` function. + `u` Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the `parse(T, _, base=10)` function. + `x` Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of thew `parse(T, _, base=16)` function. + `a`,`e`,`f`,`g` Matches an optionally signed floating-point number, `infinity`, or `NaN`, whose format is the same as expected for the subject sequence of the `parse(T, _)` function, where `T` is a floating point type. + `c` Matches a sequence of characters of exactly the number specified by the field width (`1` if no field width is present in the directive). The argument type must be `String`, `Char`, or `Vector{Char}`, If the field width is greater than `1` and a `Char` type is given, only the first character is stored. + `s` Matches a (non-empty) sequence of non-white-space characters. The argument types are as for `c`. + `[` Matches a nonempty sequence of characters from a set of expected characters (the scanset). The argument types are as for `c`. The conversion specifier includes all subsequent characters in the format string, up to and including the matching right bracket (`]`). The characters between the brackets (the scanlist) compose the scanset, unless the character after the left bracket is a circumflex (`^`), in which case the scanset contains all characters that do not appear in the scanlist between the circumflex and the right bracket. If the conversion specifier begins with `[]` or `[^]`, the right bracket character is in the scanlist and the next following right bracket character is the matching right bracket that ends the specification; otherwise the first following right bracket character is the one that ends the specification. If a `-` character is in the scanlist and is not the first, nor the second where the first character is a `^`, nor the last character, it defines the range between the character left of `-` and the character right of `-`. The order defining the range is the integer range of unicode codepoints of the characters. Empty ranges (like `b-a`) are ignored. + `p` Matches an set of sequences, which are the same as the set of sequences that may be produced by the `%p` conversion of the `printf`-function. The corresponding argument must be of type `Ptr{T}` where T may be any type. The input item is converted to a pointer value in an implementation-defined manner. If the input item is a value converted earlier during the same program execution, the pointer that results shall compare equal to that value; otherwise the behavior of the `%p` conversion is undefined. + `n` No input is consumed. The corresponding argument must be an integer type, into which is converted the number of characters read from the input stream so far by this call to the `scanf` function. Execution of a `%n` directive does as well increment the assignment count returned at the completion of execution of the `scanf` function. If the conversion specification includes an assignment-suppressing character no argument is consumed. An optional width field is ignored. + `%` Matches a single `'%'` character; no conversion or assignment occurs. The complete conversion specification is `%%`. (with other words, `%%` is treated like a single ordinary character `%`). If a conversion specification is invalid, the behavior is undefined. The conversion specifiers `A`,`E`,`F`,`G`, and `X` are also valid and behave the same as, respectively, `a`,`e`,`f`,`g`, and `x`. Trailing white space (including new-line characters) is left unread unless matched by a directive. The success of literal matches and suppressed assignments is not directly determinable other than via the `%n` directive.
Scanf
https://github.com/KlausC/Scanf.jl.git
[ "MIT" ]
0.5.4
cd8f9da92f751a1fc421120c66971d008d695cdb
docs
159
```@meta CurrentModule = Scanf ``` # Scanf Documentation for [Scanf](https://github.com/KlausC/Scanf.jl). ```@index ``` ```@autodocs Modules = [Scanf] ```
Scanf
https://github.com/KlausC/Scanf.jl.git
[ "MIT" ]
0.2.1
862a932ea451f5dd272d8ae796b726c7227e755b
code
378
using Clang using Clang.Generators using Telescope_jll cd(@__DIR__) include_dir = joinpath(Telescope_jll.artifact_dir, "include") |> normpath telescope_h = joinpath(include_dir, "telescope.h") options = load_options(joinpath(@__DIR__, "generator.toml")) args = get_default_args() push!(args, "-I$include_dir") ctx = create_context([telescope_h], args, options) build!(ctx)
Telescope
https://github.com/jhigginbotham64/Telescope.jl.git
[ "MIT" ]
0.2.1
862a932ea451f5dd272d8ae796b726c7227e755b
code
3903
module Telescope using Telescope_jll export Telescope_jll using CEnum struct TS_PositionInfo x::Cfloat y::Cfloat z::Cfloat end struct TS_VelocityInfo x::Cfloat y::Cfloat z::Cfloat end struct TS_CollisionEvent id1::Cint id2::Cint colliding::Bool end function TS_BtAddRigidBox(id, hx, hy, hz, m, px, py, pz, isKinematic) ccall((:TS_BtAddRigidBox, libtelescope), Cvoid, (Cint, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat, Bool), id, hx, hy, hz, m, px, py, pz, isKinematic) end function TS_BtAddStaticBox(id, hx, hy, hz, px, py, pz) ccall((:TS_BtAddStaticBox, libtelescope), Cvoid, (Cint, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat), id, hx, hy, hz, px, py, pz) end function TS_BtAddTriggerBox(id, hx, hy, hz, px, py, pz) ccall((:TS_BtAddTriggerBox, libtelescope), Cvoid, (Cint, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat), id, hx, hy, hz, px, py, pz) end function TS_BtRemovePhysicsObject(id) ccall((:TS_BtRemovePhysicsObject, libtelescope), Cvoid, (Cint,), id) end function TS_BtSetLinearVelocity(id, vx, vy, vz) ccall((:TS_BtSetLinearVelocity, libtelescope), Cvoid, (Cint, Cfloat, Cfloat, Cfloat), id, vx, vy, vz) end function TS_BtGetLinearVelocity(id) ccall((:TS_BtGetLinearVelocity, libtelescope), TS_VelocityInfo, (Cint,), id) end function TS_BtSetGravity(gx, gy, gz) ccall((:TS_BtSetGravity, libtelescope), Cvoid, (Cfloat, Cfloat, Cfloat), gx, gy, gz) end function TS_BtSetCollisionMargin(id, margin) ccall((:TS_BtSetCollisionMargin, libtelescope), Cvoid, (Cint, Cfloat), id, margin) end # no prototype is found for this function at telescope.h:51:6, please use with caution function TS_BtStepSimulation() ccall((:TS_BtStepSimulation, libtelescope), Cvoid, ()) end # no prototype is found for this function at telescope.h:53:26, please use with caution function TS_BtGetNextCollision() ccall((:TS_BtGetNextCollision, libtelescope), TS_CollisionEvent, ()) end function TS_BtGetPosition(id) ccall((:TS_BtGetPosition, libtelescope), TS_PositionInfo, (Cint,), id) end # no prototype is found for this function at telescope.h:57:14, please use with caution function TS_SDLGetError() ccall((:TS_SDLGetError, libtelescope), Ptr{Cchar}, ()) end function TS_VkCmdDrawRect(r, g, b, a, x, y, w, h) ccall((:TS_VkCmdDrawRect, libtelescope), Cvoid, (Cfloat, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat), r, g, b, a, x, y, w, h) end function TS_VkCmdDrawSprite(img, r, g, b, a, rx, ry, rw, rh, cw, ch, ci, cj, px, py, sx, sy) ccall((:TS_VkCmdDrawSprite, libtelescope), Cvoid, (Ptr{Cchar}, Cfloat, Cfloat, Cfloat, Cfloat, Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cfloat, Cfloat, Cfloat, Cfloat), img, r, g, b, a, rx, ry, rw, rh, cw, ch, ci, cj, px, py, sx, sy) end function TS_VkCmdClearColorImage(r, g, b, a) ccall((:TS_VkCmdClearColorImage, libtelescope), Cvoid, (Cfloat, Cfloat, Cfloat, Cfloat), r, g, b, a) end # no prototype is found for this function at telescope.h:65:6, please use with caution function TS_VkBeginDrawPass() ccall((:TS_VkBeginDrawPass, libtelescope), Cvoid, ()) end function TS_VkEndDrawPass(r, g, b, a) ccall((:TS_VkEndDrawPass, libtelescope), Cvoid, (Cfloat, Cfloat, Cfloat, Cfloat), r, g, b, a) end function TS_Init(ttl, wdth, hght) ccall((:TS_Init, libtelescope), Cvoid, (Ptr{Cchar}, Cint, Cint), ttl, wdth, hght) end # no prototype is found for this function at telescope.h:71:6, please use with caution function TS_Quit() ccall((:TS_Quit, libtelescope), Cvoid, ()) end function TS_PlaySound(sound_file, loops, ticks) ccall((:TS_PlaySound, libtelescope), Cvoid, (Ptr{Cchar}, Cint, Cint), sound_file, loops, ticks) end # exports const PREFIXES = ["TS_"] for name in names(@__MODULE__; all=true), prefix in PREFIXES if startswith(string(name), prefix) @eval export $name end end end # module
Telescope
https://github.com/jhigginbotham64/Telescope.jl.git
[ "MIT" ]
0.2.1
862a932ea451f5dd272d8ae796b726c7227e755b
code
91
using Telescope using Test @testset "Telescope.jl" begin # Write your tests here. end
Telescope
https://github.com/jhigginbotham64/Telescope.jl.git
[ "MIT" ]
0.2.1
862a932ea451f5dd272d8ae796b726c7227e755b
docs
88
# Telescope Julia bindings for Telescope: https://github.com/jhigginbotham64/Telescope
Telescope
https://github.com/jhigginbotham64/Telescope.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
832
using Documenter, DocumenterMarkdown, FluxMPI deployconfig = Documenter.auto_detect_deploy_system() Documenter.post_status( deployconfig; type="pending", repo="github.com/avik-pal/FluxMPI.jl.git") makedocs(; sitename="Lux", authors="Avik Pal et al.", clean=true, doctest=true, modules=[FluxMPI], strict=[:doctest, :linkcheck, :parse_error, :example_block], checkdocs=:all, format=DocumenterMarkdown.Markdown(), draft=false, build=joinpath(@__DIR__, "docs")) deploydocs(; repo="github.com/avik-pal/FluxMPI.jl.git", push_preview=true, deps=Documenter.Deps.pip("mkdocs", "pygments", "python-markdown-math", "mkdocs-material", "pymdown-extensions", "mkdocstrings", "mknotebooks", "pytkdocs_tweaks", "mkdocs_include_exclude_files", "jinja2"), make=() -> run(`mkdocs build`), target="site", devbranch="main")
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
319
module FluxMPIComponentArraysExt isdefined(Base, :get_extension) ? (using ComponentArrays) : (using ..ComponentArrays) using FluxMPI, MPI function FluxMPI.synchronize!(x::ComponentArray; root_rank::Integer=0) d = FluxMPI.bcast!(getdata(x), root_rank, MPI.COMM_WORLD) return ComponentArray(d, getaxes(x)) end end
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
258
module FluxMPIFluxExt isdefined(Base, :get_extension) ? (using Flux) : (using ..Flux) using FluxMPI, Functors function FluxMPI.synchronize!(x::FluxMPIFluxModel; root_rank::Integer=0) return fmap(x -> FluxMPI.synchronize!(x; root_rank), x.model) end end
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
2663
module FluxMPI using Adapt, CUDA, Dates, Functors, MPI, Optimisers, Setfield using Preferences import ChainRulesCore as CRC const FluxMPI_Initialized = Ref(false) # Extensions if !isdefined(Base, :get_extension) using Requires end const MPI_IS_CUDA_AWARE = Ref(false) function __init__() if haskey(ENV, "FLUXMPI_DISABLE_CUDAMPI_SUPPORT") @warn "FLUXMPI_DISABLE_CUDAMPI_SUPPORT environment variable has been removed and has no effect. Please use `FluxMPI.disable_cudampi_support()` instead." maxlog=1`` end disable_cuda_aware_support = @load_preference("FluxMPIDisableCUDAMPISupport", false) MPI_IS_CUDA_AWARE[] = !disable_cuda_aware_support && MPI.has_cuda() if disable_cuda_aware_support && MPI.has_cuda() @info "CUDA-aware MPI support disabled using LocalPreferences.toml." maxlog=1 elseif !MPI_IS_CUDA_AWARE[] @warn "MPI Implementation is not CUDA Aware." maxlog=1 else @info "MPI Implementation is CUDA Aware." maxlog=1 end @static if !isdefined(Base, :get_extension) # Handling ComponentArrays @require ComponentArrays="b0b7db55-cfe3-40fc-9ded-d10e2dbeff66" begin include("../ext/FluxMPIComponentArraysExt.jl") end # Handling Flux @require Flux="587475ba-b771-5e3f-ad9e-33799f191a9c" begin include("../ext/FluxMPIFluxExt.jl") end end end """ disable_cudampi_support(; disable=true) Disable CUDA MPI support. Julia Session needs to be restarted for this to take effect. """ function disable_cudampi_support(; disable=true) @set_preferences!("FluxMPIDisableCUDAMPISupport"=>disable) @info "CUDA-aware MPI support "* (disable ? "disabled" : "enabled")* ". Restart Julia for this change to take effect!" maxlog=1 end # Error Handling struct FluxMPINotInitializedError <: Exception end function Base.showerror(io::IO, e::FluxMPINotInitializedError) return print(io, "Please call FluxMPI.init(...) before using FluxMPI functionalities!") end # MPI Extensions include("mpi_extensions.jl") # General Utilities -- Init, Clean Printing include("common.jl") # synchronize! include("synchronize.jl") # Implementation of Distributed Optimiser include("optimizer.jl") # Support for MLUtils.jl DataLoader include("data.jl") # Extensions: Flux ## We need this because Flux works on arbitrary types. Which means we cannot dispatch ## `synchronize!` correctly. It is the user's responsibility to call `synchronize!` on ## `FluxMPIFluxModel`. struct FluxMPIFluxModel{M} model::M end export local_rank, total_workers, DistributedOptimizer, fluxmpi_print, fluxmpi_println, DistributedDataContainer, allreduce_gradients export FluxMPIFluxModel end
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
2569
""" Initialized() Has FluxMPI been initialized? """ Initialized() = FluxMPI_Initialized[] """ Init(; gpu_devices::Union{Nothing,Vector{Int}}=nothing, verbose::Bool=false) Setup `FluxMPI`. If GPUs are available and CUDA is functional, each rank is allocated a GPU in a round-robin fashion. If calling this function, no need to call `MPI.Init` first. """ function Init(; gpu_devices::Union{Nothing, Vector{Int}}=nothing, verbose::Bool=false) if Initialized() verbose && fluxmpi_println("FluxMPI already initialized; Skipping...") return end !MPI.Initialized() && MPI.Init() FluxMPI_Initialized[] = true if verbose && total_workers() == 1 @warn "Using FluxMPI with only 1 worker. It might be faster to run the code without MPI" maxlog=1 end rank = local_rank() if CUDA.functional() gpu_device = if gpu_devices === nothing device_count = length(CUDA.devices()) (rank + 1) % device_count else gpu_devices[rank + 1] end verbose && fluxmpi_println("Using GPU $gpu_device") CUDA.device!(gpu_device) else verbose && fluxmpi_println("Using CPU") end return end """ local_rank() Get the rank of the process. """ @inline function local_rank() !Initialized() && throw(FluxMPINotInitializedError()) return MPI.Comm_rank(MPI.COMM_WORLD) end CRC.@non_differentiable local_rank() """ total_workers() Get the total number of workers. """ @inline function total_workers() !Initialized() && throw(FluxMPINotInitializedError()) return MPI.Comm_size(MPI.COMM_WORLD) end CRC.@non_differentiable total_workers() # Print Functions for print_fn in (:println, :print) function_name = Symbol("fluxmpi_" * string(print_fn)) @eval begin function $(function_name)(args...; kwargs...) if !Initialized() $(print_fn)("$(Dates.now()) ", args...; kwargs...) return end rank = local_rank() size = total_workers() if size == 1 $(print_fn)(args...; kwargs...) return end for r in 0:(size - 1) if r == rank $(print_fn)("$(Dates.now()) [$(rank) / $(size)] ", args...; kwargs...) flush(stdout) end MPI.Barrier(MPI.COMM_WORLD) end return end CRC.@non_differentiable $(function_name)(::Any...) end end """ fluxmpi_println(args...; kwargs...) Add `rank` and `size` information to the printed statement """ fluxmpi_println """ fluxmpi_print(args...; kwargs...) Add `rank` and `size` information to the printed statement """ fluxmpi_print
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
768
""" DistributedDataContainer(data) `data` must be compatible with `MLUtils` interface. The returned container is compatible with `MLUtils` interface and is used to partition the dataset across the available processes. """ struct DistributedDataContainer data::Any idxs::Any end function DistributedDataContainer(data) total_size = length(data) split_across = total_workers() size_per_process = Int(ceil(total_size / split_across)) partitions = collect(Iterators.partition(1:total_size, size_per_process)) idxs = collect(partitions[local_rank() + 1]) return DistributedDataContainer(data, idxs) end Base.length(ddc::DistributedDataContainer) = length(ddc.idxs) Base.getindex(ddc::DistributedDataContainer, i) = getindex(ddc.data, ddc.idxs[i])
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
4284
# NOTE(@avik-pal): Data Movement between CPU and GPU. `Lux` & `Flux` have much better # support for this but this is all we need here. If not an abstract array # don't do anything. # Maybe we want to have a central repository containing these device transfer utilities cpu(x) = x gpu(x) = x cpu(x::AbstractArray) = adapt(Array, x) gpu(x::AbstractArray) = adapt(CuArray, x) ## Certain Non-blocking collective communication primitives """ Iallreduce!(sendbuf, recvbuf, op, comm) Iallreduce!(sendrecvbuf, op, comm) Performs non-blocking elementwise reduction using the operator `op` on the buffer `sendbuf`. `sendbuf` can also be a scalar, in which case `recvbuf` will be a value of the same type. `recvbuf` and an MPI_Request object are returned. The value in `recvbuf` is only valid after the request has been completed. (`MPI.Wait!`) !!! warning OpenMPI doesn't support Iallreduce! with CUDA. See [this issue](https://github.com/open-mpi/ompi/issues/9845). """ function Iallreduce!(rbuf::MPI.RBuffer, op::Union{MPI.Op, MPI.MPI_Op}, comm::MPI.Comm) req = MPI.Request() # int MPI_Iallreduce(const void *sendbuf, void *recvbuf, int count, # MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, # MPI_Request * request) MPI.@mpichk ccall((:MPI_Iallreduce, MPI.libmpi), Cint, (MPI.MPIPtr, MPI.MPIPtr, Cint, MPI.MPI_Datatype, MPI.MPI_Op, MPI.MPI_Comm, Ptr{MPI.MPI_Request}), rbuf.senddata, rbuf.recvdata, rbuf.count, rbuf.datatype, op, comm, req) req.buffer = rbuf finalizer(MPI.free, req) return rbuf.recvdata, req end function Iallreduce!(rbuf::MPI.RBuffer, op, comm::MPI.Comm) return Iallreduce!(rbuf, MPI.Op(op, eltype(rbuf)), comm) end function Iallreduce!(sendbuf, recvbuf, op, comm::MPI.Comm) return Iallreduce!(MPI.RBuffer(sendbuf, recvbuf), op, comm) end Iallreduce!(buf, op, comm::MPI.Comm) = Iallreduce!(MPI.IN_PLACE, buf, op, comm) """ Ibcast!(buf, root, comm) Non-blocking broadcast of the buffer `buf` to all processes in `comm`. `recvbuf` and an MPI_Request object are returned. The value in `recvbuf` is only valid after the request has been completed. (`MPI.Wait!`) """ function Ibcast!(buf::MPI.Buffer, root::Integer, comm::MPI.Comm) req = MPI.Request() # int MPI_Ibcast(void *buffer, int count, MPI_Datatype datatype, int root, # MPI_Comm comm, MPI_Request *request) MPI.@mpichk ccall((:MPI_Ibcast, MPI.libmpi), Cint, (MPI.MPIPtr, Cint, MPI.MPI_Datatype, Cint, MPI.MPI_Comm, Ptr{MPI.MPI_Request}), buf.data, buf.count, buf.datatype, root, comm, req) req.buffer = buf finalizer(MPI.free, req) return buf.data, req end Ibcast!(buf, root::Integer, comm::MPI.Comm) = Ibcast!(MPI.Buffer(buf), root, comm) # Simpler wrappers """ allreduce!(v, op, comm) Perform `MPI.Allreduce!` ensuring that CuArrays are safely transfered to CPU if CUDA-aware MPI is unavailable/disabled. """ function allreduce!(v::CuArray, op::Any, comm::MPI.Comm) @static if !MPI_IS_CUDA_AWARE[] v = cpu(v) end MPI.Allreduce!(v, op, comm) @static if !MPI_IS_CUDA_AWARE[] v = gpu(v) end return v end function allreduce!(v::AbstractArray, op::Any, comm::MPI.Comm) MPI.Allreduce!(v, op, comm) return v end """ bcast!(v, op, comm) Perform `MPI.Bcast!` ensuring that CuArrays are safely transfered to CPU if CUDA-aware MPI is unavailable/disabled. """ function bcast!(v::CuArray, root::Integer, comm::MPI.Comm) @static if !MPI_IS_CUDA_AWARE[] v = cpu(v) end MPI.Bcast!(v, root, comm) @static if !MPI_IS_CUDA_AWARE[] v = gpu(v) end return v end function bcast!(v::AbstractArray, root::Integer, comm::MPI.Comm) MPI.Bcast!(v, root, comm) return v end """ reduce!(v, op, comm) Perform `MPI.Reduce!` ensuring that CuArrays are safely transfered to CPU if CUDA-aware MPI is unavailable/disabled. """ function reduce!(v::CuArray, op::Any, root::Integer, comm::MPI.Comm) @static if !MPI_IS_CUDA_AWARE[] v = cpu(v) end MPI.Reduce!(v, op, root, comm) @static if !MPI_IS_CUDA_AWARE[] v = gpu(v) end return v end function reduce!(v::AbstractArray, op::Any, root::Integer, comm::MPI.Comm) MPI.Reduce!(v, op, root, comm) return v end
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
1735
""" DistributedOptimizer(optimizer) Wrap the `optimizer` in a `DistributedOptimizer`. Before updating the parameters, this adds the gradients across the processes using non-blocking Allreduce ## Arguments - `optimizer`: An Optimizer compatible with the Optimisers.jl package !!! note Remember to scale the loss function by `1 / total_workers()` to ensure that the gradients are correctly averaged """ struct DistributedOptimizer{O} <: Optimisers.AbstractRule optimizer::O end function Optimisers.apply!(o::DistributedOptimizer, state, x, y) y_ = allreduce!(y, +, MPI.COMM_WORLD) return Optimisers.apply!(o.optimizer, state, x, y_) end Optimisers.init(o::DistributedOptimizer, x::AbstractArray) = Optimisers.init(o.optimizer, x) """ allreduce_gradients(gs::NamedTuple; on_gpu::Bool=CUDA.functional()) Allreduce the gradients. This uses a non-blocking API which will be efficient for large containers of multiple parameter arrays. ## Arguments - `gs`: A `NamedTuple` of gradients ## Keyword Arguments - `on_gpu`: Specify if the gradients are on GPU. Defaults to `CUDA.functional()` ## Returns - `Allreduce`d NamedTuple of gradients """ function allreduce_gradients(gs::NamedTuple; on_gpu::Bool=CUDA.functional()) # Transfer data to CPU since OpenMPI Iallreduce! doesn't work for CUDA gs = on_gpu ? fmap(cpu, gs) : gs requests = MPI.Request[] nonblocking_reduce_gradients(g) = g function nonblocking_reduce_gradients(g::AbstractArray) g, req = Iallreduce!(g, +, MPI.COMM_WORLD) push!(requests, req) return g end gs = fmap(nonblocking_reduce_gradients, gs) MPI.Waitall!(requests) # Transfer data back to GPU gs = on_gpu ? fmap(gpu, gs) : gs return gs end
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
1012
""" synchronize!(x; root_rank::Integer=0) Synchronize `x` across all processes. !!! note this function is not in-place for CuArrays when MPI is not CUDA aware. """ function synchronize!(ps::Union{NamedTuple, Tuple}; root_rank::Integer=0) length(ps) == 0 && return ps return fmap(x -> synchronize!(x; root_rank), ps) end function synchronize!(x::AbstractArray{T}; root_rank::Integer=0) where {T <: Number} return bcast!(x, root_rank, MPI.COMM_WORLD) end # Ideally these things should be Tuples and not arrays function synchronize!(x::AbstractArray; root_rank::Integer=0) return synchronize!.(x; root_rank) end function synchronize!(l::Optimisers.Leaf; root_rank::Integer=0) @set! l.state = synchronize!(l.state; root_rank) return l end function synchronize!(x::Number; root_rank::Integer=0) return bcast!([x], root_rank, MPI.COMM_WORLD)[1] end # If we don't know what to synchronize, we don't do it # -- Symbols, Nothing, Missing, Val, etc. synchronize!(x; root_rank::Integer=0) = x
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
482
using FluxMPI, MPI, Test nprocs_str = get(ENV, "JULIA_MPI_TEST_NPROCS", "") nprocs = nprocs_str == "" ? clamp(Sys.CPU_THREADS, 2, 4) : parse(Int, nprocs_str) testdir = @__DIR__ istest(f) = endswith(f, ".jl") && startswith(f, "test_") testfiles = sort(filter(istest, readdir(testdir))) @info "Running FluxMPI tests" nprocs @testset "$f" for f in testfiles MPI.mpiexec() do cmd run(`$cmd -n $nprocs $(Base.julia_cmd()) $(joinpath(testdir, f))`) Test.@test true end end
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
424
using FluxMPI, MPI, Test FluxMPI.Init(; verbose=true) @testset "Common Utilities" begin @test FluxMPI.Initialized() # Should always hold true @test FluxMPI.local_rank() < FluxMPI.total_workers() @test_nowarn FluxMPI.fluxmpi_println("Printing from Rank ", FluxMPI.local_rank()) @test_nowarn FluxMPI.fluxmpi_print("Printing from Rank ", FluxMPI.local_rank(), "\n") MPI.Finalize() @test MPI.Finalized() end
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
671
using FluxMPI, MPI, Random, Test rng = Random.MersenneTwister() Random.seed!(rng, 19) FluxMPI.Init(; verbose=true) @testset "DistributedDataContainer" begin data = randn(rng, Float32, 10) tworkers = total_workers() rank = local_rank() dcontainer = DistributedDataContainer(data) if rank != tworkers - 1 @test length(dcontainer) == ceil(length(data) / tworkers) else @test length(dcontainer) == length(data) - ceil(length(data) / tworkers) * (tworkers - 1) end dsum = 0 for i in 1:length(dcontainer) dsum += dcontainer[i] end @test isapprox(FluxMPI.allreduce!([dsum], +, MPI.COMM_WORLD)[1], sum(data)) end MPI.Finalize()
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
1259
using FluxMPI, MPI, Test FluxMPI.Init(; verbose=true) function _get_array_based_on_rank(dims; root_rank) return local_rank() == root_rank ? ones(dims...) : zeros(dims...) end @testset "Iallreduce!" begin x = ones(4) y = similar(x) y, req = FluxMPI.Iallreduce!(x, y, +, MPI.COMM_WORLD) MPI.Wait!(req) @test y == x .* total_workers() y = similar(x) y, req = FluxMPI.Iallreduce!(x, y, *, MPI.COMM_WORLD) MPI.Wait!(req) @test y == x end @testset "Ibcast!" begin x = _get_array_based_on_rank((2, 3); root_rank=0) y, req = FluxMPI.Ibcast!(x, 0, MPI.COMM_WORLD) MPI.Wait!(req) @test y == one.(x) end @testset "Wrappers" begin @testset "allreduce" begin x = ones(4) y = FluxMPI.allreduce!(copy(x), +, MPI.COMM_WORLD) @test y == x .* total_workers() y = FluxMPI.allreduce!(copy(x), *, MPI.COMM_WORLD) @test y == x end @testset "bcast" begin x = _get_array_based_on_rank((2, 3); root_rank=0) y = FluxMPI.bcast!(copy(x), 0, MPI.COMM_WORLD) @test y == one.(x) end @testset "reduce" begin x = ones(4) y = FluxMPI.reduce!(copy(x), +, 0, MPI.COMM_WORLD) if local_rank() == 0 @test y == x .* total_workers() else @test y == x end end end MPI.Finalize()
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
1012
using FluxMPI, MPI, Optimisers, Test FluxMPI.Init(; verbose=true) @testset "DistributedOptimizer" begin opt = Adam(0.001f0) ps = (a=zeros(4), b=zeros(4)) st_opt = Optimisers.setup(opt, ps) dopt = FluxMPI.DistributedOptimizer(opt) st_dopt = Optimisers.setup(dopt, ps) @test st_dopt.a.state == st_opt.a.state @test st_dopt.b.state == st_opt.b.state @test_nowarn FluxMPI.synchronize!(st_dopt; root_rank=0) gs = (a=ones(4), b=ones(4)) _, ps_dopt = Optimisers.update(st_dopt, ps, gs) _, ps_opt = Optimisers.update( st_opt, ps, (a=gs.a .* FluxMPI.total_workers(), b=gs.b .* FluxMPI.total_workers())) @test isapprox(ps_dopt.a, ps_opt.a; atol=1.0e-5, rtol=1.0e-5) @test isapprox(ps_dopt.b, ps_opt.b; atol=1.0e-5, rtol=1.0e-5) end @testset "allreduce_gradients" begin gs = (a=ones(4), b=ones(4)) gs_ = FluxMPI.allreduce_gradients(deepcopy(gs); on_gpu=false) @test gs_.a == gs.a .* FluxMPI.total_workers() @test gs_.b == gs.b .* FluxMPI.total_workers() end MPI.Finalize()
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
code
2569
using ComponentArrays, FluxMPI, MPI, Optimisers, Test FluxMPI.Init(; verbose=true) function _get_array_based_on_rank(dims; root_rank) if FluxMPI.local_rank() == root_rank return ones(dims...) else return zeros(dims...) end end @testset "synchronize" begin root_rank = 0 @testset "NamedTuple" begin gs = ( a=(b=_get_array_based_on_rank((2, 3); root_rank), c=_get_array_based_on_rank((2, 3); root_rank)), d=_get_array_based_on_rank((2, 3); root_rank)) gs_ = FluxMPI.synchronize!(gs; root_rank) @test all(gs_.a.b .== 1) @test all(gs_.a.c .== 1) @test all(gs_.d .== 1) @testset "Optimisers" begin opt = Adam(0.001f0) st_opt = Optimisers.setup(opt, gs) if local_rank() == root_rank st_opt.a.b.state[1] .= 1 st_opt.a.b.state[2] .= 1 st_opt.a.c.state[1] .= 1 st_opt.a.c.state[2] .= 1 st_opt.d.state[1] .= 1 st_opt.d.state[2] .= 1 end st_opt = FluxMPI.synchronize!(st_opt; root_rank) @test all(st_opt.a.b.state[1] .== 1) @test all(st_opt.a.b.state[2] .== 1) @test all(st_opt.a.c.state[1] .== 1) @test all(st_opt.a.c.state[2] .== 1) @test all(st_opt.d.state[1] .== 1) @test all(st_opt.d.state[2] .== 1) # Has no state opt = Descent(0.001f0) st_opt = Optimisers.setup(opt, gs) @test_nowarn FluxMPI.synchronize!(st_opt; root_rank) end @testset "ComponentArray" begin gs = ( a=(b=_get_array_based_on_rank((2, 3); root_rank), c=_get_array_based_on_rank((2, 3); root_rank)), d=_get_array_based_on_rank((2, 3); root_rank)) cgs = ComponentArray(gs) cgs_ = FluxMPI.synchronize!(cgs; root_rank) @test all(cgs_.a.b .== 1) @test all(cgs_.a.c .== 1) @test all(cgs_.d .== 1) end end @testset "Tuple" begin gs = ( (_get_array_based_on_rank((2, 3); root_rank), _get_array_based_on_rank((2, 3); root_rank)), _get_array_based_on_rank((2, 3); root_rank)) gs = FluxMPI.synchronize!(gs; root_rank) @test all(gs[1][1] .== 1) @test all(gs[1][2] .== 1) @test all(gs[2] .== 1) end @testset "Misc." begin x = nothing x = FluxMPI.synchronize!(x; root_rank) @test x == nothing if root_rank == local_rank() x = :x else x = :y end x_ = FluxMPI.synchronize!(x; root_rank) # Symbol should not change @test x_ == x x = FluxMPI.synchronize!(local_rank(); root_rank) @test x == root_rank end end MPI.Finalize()
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
docs
5198
# FluxMPI.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://avik-pal.github.io/FluxMPI.jl/stable/) [![Latest](https://img.shields.io/badge/docs-dev-blue.svg)](https://avik-pal.github.io/FluxMPI.jl/dev/) [![CI](https://github.com/avik-pal/FluxMPI.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/avik-pal/FluxMPI.jl/actions/workflows/CI.yml) [![codecov](https://codecov.io/github/avik-pal/FluxMPI.jl/branch/main/graph/badge.svg?token=1L3ePmqyPo)](https://codecov.io/github/avik-pal/FluxMPI.jl) [![Package Downloads](https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/FluxMPI)](https://pkgs.genieframework.com?packages=FluxMPI) [![ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://img.shields.io/badge/ColPrac-Contributor's%20Guide-blueviolet)](https://github.com/SciML/ColPrac) [![SciML Code Style](https://img.shields.io/static/v1?label=code%20style&message=SciML&color=9558b2&labelColor=389826)](https://github.com/SciML/SciMLStyle) Distributed Data Parallel Training of Neural Networks ## Installation Stable release: ```julia ] add FluxMPI ``` Latest development version: ```julia ] add FluxMPI#main ``` ## Quick Start ```julia using CUDA, FluxMPI, Lux, Optimisers, Random, Zygote FluxMPI.Init() CUDA.allowscalar(false) model = Chain(Dense(1 => 256, tanh), Dense(256 => 512, tanh), Dense(512 => 256, tanh), Dense(256 => 1)) rng = Random.default_rng() Random.seed!(rng, local_rank()) ps, st = Lux.setup(rng, model) .|> gpu ps = FluxMPI.synchronize!(ps; root_rank = 0) st = FluxMPI.synchronize!(st; root_rank = 0) x = rand(rng, 1, 16) |> gpu y = x .^ 2 opt = DistributedOptimizer(Adam(0.001f0)) st_opt = Optimisers.setup(opt, ps) loss(p) = sum(abs2, model(x, p, st)[1] .- y) st_opt = FluxMPI.synchronize!(st_opt; root_rank = 0) gs_ = gradient(loss, ps)[1] Optimisers.update(st_opt, ps, gs_) t1 = time() for epoch in 1:100 global ps, st_opt l, back = Zygote.pullback(loss, ps) FluxMPI.fluxmpi_println("Epoch $epoch: Loss $l") gs = back(one(l))[1] st_opt, ps = Optimisers.update(st_opt, ps, gs) end FluxMPI.fluxmpi_println(time() - t1) ``` Run the code using `mpiexecjl -n 3 julia --project=. <filename>.jl`. ## Examples * [Deep Equilibrium Models](https://github.com/SciML/FastDEQ.jl) -- Deep Implicit Neural Networks & Infinite Time Neural ODEs * [ImageNet Training with Lux.jl](https://github.com/avik-pal/Lux.jl/tree/main/examples/ImageNet) ## Style Guide We follow the [Lux Style Guide](http://lux.csail.mit.edu/stable/devdocs/style_guide/). All contributions must adhere to this style guide. ## Changelog ### v0.7 * Dropped support for MPI v0.19. * `FLUXMPI_DISABLE_CUDAMPI_SUPPORT` is no longer used. Instead use `FluxMPI.disable_cudampi_support()` to setup a LocalPreferences.toml file. * `clean_(print/println)` functions are now `fluxmpi_(print/println)`. <details> <summary><h3>v0.6</h3></summary> * Dropped support for `LearnBase`, aka `DataLoaders.jl`. `DistributedDataContainer` is now the only compatible with `MLUtils.jl`. * `DistributedOptimiser` name changed to `DistributedOptimizer`. </details> <details> <summary><h3>v0.5</h3></summary> #### v0.5.3 * Introduces a new API for gradient synchronization * Don't wrap in `DistributedOptimiser` * Instead just add a line `allreduce_gradients(gs::NamedTuple)` #### v0.5.1 * Internal `MPIExtensions` functions renamed * `Allreduce!` --> `allreduce!` * `Bcast!` --> `bcast!` * `Reduce!` --> `reduce!` * CUDA-unaware MPI bug resolved https://github.com/avik-pal/Lux.jl/issues/18 * Disable CUDA-aware MPI support from `FluxMPI` using `FLUXMPI_DISABLE_CUDAMPI_SUPPORT=true` * Temporarily re-added dependencies on `MLDataUtils` and `LearnBase` to ensure `DataLoaders.jl` still works -- This will be dropped in a future release #### v0.5.0 * `DistributedOptimiser` no longer averages the gradients. Instead, the values are summed across the processes. To ensure averaging divide the loss by `total_workers()` * `rrule`s and `frule`s defined for `local_rank()` and `total_workers` -- they can now be safely used inside loss functions. </details> <details> <summary><h3>v0.4</h3></summary> * `fluxmpi_print` and `fluxmpi_println` print the current time even if `FluxMPI` has not been initialized. * Calling `local_rank` or `total_workers` before `FluxMPI.Init` doesn't lead to a segfault. Rather we throw an error. * `MLDataUtils` and `LearnBase` dependencies have been dropped (See https://github.com/avik-pal/FluxMPI.jl/issues/17) * `Zygote` and `Flux` dependencies have been removed * No dispatch for `FluxMPI.synchronize!` is now available for `Zygote.Params`. Instead users should be manually broadcasting the function over `Zygote.Params` </details> <details> <summary><h3>v0.3</h3></summary> * `broadcast_parameters` has been renamed to `FluxMPI.synchronize!` since it synchronizes a lot more than trainable parameters now. * DistributedOptimiser is no longer tied with Flux. We can essentially deal with any training as long as it is compatible with [Optimisers.jl](https://github.com/FluxML/Optimisers.jl) </details>
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
docs
653
```@meta CurrentModule = FluxMPI ``` ```@index Pages = ["api.md"] ``` ## Data Helpers ```@docs DistributedDataContainer ``` ## General Functions ```@docs FluxMPI.Init FluxMPI.Initialized fluxmpi_print fluxmpi_println local_rank total_workers ``` ## MPIExtensions: Blocking Communication Wrappers ```@docs FluxMPI.allreduce! FluxMPI.bcast! FluxMPI.reduce! ``` ## MPIExtensions: Non-Blocking Communication ```@docs FluxMPI.Iallreduce! FluxMPI.Ibcast! ``` ## Optimization ```@docs DistributedOptimizer allreduce_gradients ``` ## Synchronization ```@docs FluxMPI.synchronize! ``` ## Configuration ```@docs FluxMPI.disable_cudampi_support ```
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
docs
633
## CUDA-aware MPI ### Setup OpenMPI has extensive instructions on building [CUDA-aware MPI](https://www-lb.open-mpi.org/faq/?category=buildcuda). Next rebuild MPI.jl using these [instructions](https://juliaparallel.org/MPI.jl/stable/configuration/#Using-a-system-provided-MPI). Additionally, make sure to set `JULIA_CUDA_USE_MEMPOOL=none`. ### Should you use CUDA-aware MPI? I would recommend **not** using this atm, since `JULIA_CUDA_USE_MEMPOOL=none` will severely slow down your code (*~2-3x* for most workloads I tested). Instead setup `MPI.jl` using you system provided MPI and execute `FluxMPI.disable_cudampi_support()`.
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
docs
856
# Guide to integrating FluxMPI into your code There are essentially 6 main steps to remember: 1. Initialize FluxMPI [`FluxMPI.Init()`](@ref). 2. Sync Model Parameters and States [`FluxMPI.synchronize!(ps; root_rank)`](@ref). (Remember to use `FluxMPIFluxModel` for Flux models.) 3. Use [`DistributedDataContainer`](@ref) to distribute your data evenly across the processes. (Of course an alternative is to just manually partition your data.) 4. Wrap the optimizer in [`DistributedOptimizer`](@ref) or call [`allreduce_gradients(gs::NamedTuple)`](@ref) before eveery `Optimisers.update`. 5. Sync the optimizer state across the processes [`FluxMPI.synchronize!(opt_state; root_rank)`](@ref). 6. Change logging code to check for [`local_rank`](@ref) == 0. Finally, start the code using `mpiexecjl -n <np> julia --project=. <filename>.jl`
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
docs
1410
# FluxMPI.jl Distributed Data Parallel Training of Neural Networks !!! note This package has very little to do with Flux. FWIW it doesn't even depend on it. It can be seamlessly used with [Flux.jl](https://github.com/FluxML/Flux.jl), [Lux.jl](https://github.com/avik-pal/Lux.jl), and pretty much any framework which works with [Optimisers.jl](https://github.com/FluxML/Optimisers.jl). ## Installation Install [julia v1.6 or above](https://julialang.org/downloads/). Next Install the stable release: ```julia using Pkg Pkg.add("FluxMPI") ``` To install the Latest development version (not very beneficial we release most patches almost immediately): ```julia using Pkg Pkg.add("FluxMPI", rev="main") ``` ## Design Principles - Efficient distributed data parallelism using MPI. - Not tied to any specific framework -- works with [Lux.jl](https://github.com/avik-pal/Lux.jl), [Flux.jl](https://github.com/FluxML/Flux.jl), etc. - Should not be too intrusive. ## Citation If you found this library to be useful in academic work, then please cite: ```bibtex @misc{pal2022lux, author = {Pal, Avik}, title = {FluxMPI: Distributed Data Parallel Training of Neural Networks}, year = {2021}, publisher = {GitHub}, journal = {GitHub repository}, howpublished = {\url{https://github.com/avik-pal/FluxMPI.jl/}} } ``` Also consider starring our github repo
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
docs
3084
# Usage example with FLux.jl [Flux.jl](http://lux.csail.mit.edu/stable/) is one of the defacto deep learning framework in Julia. ## Step 0: Import the necessary packages !!! tip You can install these packages using `using Pkg; Pkg.add.(["CUDA", "Optimisers", "Flux", "Random", "Zygote"])` ```julia using CUDA, Optimisers, FluxMPI, Flux, Random, Zygote ``` ## Step 1: Initialize FluxMPI. Not doing this will segfault your code ```julia FluxMPI.Init() CUDA.allowscalar(false) ``` ## Step 2: Sync Model Parameters and States ```julia model = Chain(Dense(1 => 256, tanh), Dense(256 => 512, tanh), Dense(512 => 256, tanh), Dense(256 => 1)) rng = Random.default_rng() Random.seed!(rng, local_rank()) # Always remember to wrap the model in FluxMPIFluxModel model = FluxMPI.synchronize!(FluxMPIFluxModel(model); root_rank=0) ``` ## Step 3: Ensure data is properly partitioned It is the user's responsibility to partition the data across the processes. In this case, we are training on a total of `16 * <np>` samples. Instead of manually partitioning the data, we can use [`DistributedDataContainer`](@ref) to partition the data. ```julia x = rand(rng, 1, 16) |> gpu y = x .^ 2 ``` ## Step 4: Wrap the optimizer in [`DistributedOptimizer`](@ref) Remember to scale the learning rate by the number of workers [`total_workers`](@ref). ```julia opt = DistributedOptimizer(Optimisers.Adam(0.001f0)) st_opt = Optimisers.setup(opt, model) loss(model) = sum(abs2, model(x) .- y) ``` ## Step 5: Synchronize the optimizer state ```julia st_opt = FluxMPI.synchronize!(st_opt; root_rank = 0) ``` ## Step 6: Train your model Remember to print using [`fluxmpi_println`](@ref) or [`fluxmpi_print`](@ref). ```julia gs_ = gradient(loss, model)[1] Optimisers.update(st_opt, ps, gs_) t1 = time() for epoch in 1:100 global model, st_opt l, back = Zygote.pullback(loss, model) FluxMPI.fluxmpi_println("Epoch $epoch: Loss $l") gs = back(one(l))[1] st_opt, model = Optimisers.update(st_opt, model, gs) end FluxMPI.fluxmpi_println(time() - t1) ``` Run the code using `mpiexecjl -n 3 julia --project=. <filename>.jl`. ## Complete Script ```julia using CUDA, FluxMPI, Flux, Optimisers, Random, Zygote FluxMPI.Init() CUDA.allowscalar(false) model = Chain(Dense(1 => 256, tanh), Dense(256 => 512, tanh), Dense(512 => 256, tanh), Dense(256 => 1)) |> gpu rng = Random.default_rng() Random.seed!(rng, local_rank()) model = FluxMPI.synchronize!(FluxMPIFluxModel(model); root_rank=0) x = rand(rng, 1, 16) |> gpu y = x .^ 2 opt = DistributedOptimizer(Optimisers.Adam(0.001f0)) st_opt = Optimisers.setup(opt, model) loss(model) = sum(abs2, model(x) .- y) st_opt = FluxMPI.synchronize!(st_opt; root_rank = 0) gs_ = gradient(loss, model)[1] Optimisers.update(st_opt, ps, gs_) t1 = time() for epoch in 1:100 global model, st_opt l, back = Zygote.pullback(loss, model) FluxMPI.fluxmpi_println("Epoch $epoch: Loss $l") gs = back(one(l))[1] st_opt, model = Optimisers.update(st_opt, model, gs) end FluxMPI.fluxmpi_println(time() - t1) ```
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.7.2
b59264f8a69d35191671a4db42dd50b7548345d1
docs
3301
# Usage example with Lux.jl [Lux.jl](http://lux.csail.mit.edu/stable/) is a deep learning framework which provides a functional design to implement neural networks in Julia. If you are not familiar with Lux, first check-out [this tutorial](http://lux.csail.mit.edu/stable/examples/generated/beginner/Basics/main/) before proceeding. ## Step 0: Import the necessary packages !!! tip You can install these packages using `using Pkg; Pkg.add.(["CUDA", "Optimisers", "Lux", "Random", "Zygote"])` ```julia using CUDA, Optimisers, FluxMPI, Lux, Random, Zygote ``` ## Step 1: Initialize FluxMPI. Not doing this will segfault your code ```julia FluxMPI.Init() CUDA.allowscalar(false) ``` ## Step 2: Sync Model Parameters and States ```julia model = Chain(Dense(1 => 256, tanh), Dense(256 => 512, tanh), Dense(512 => 256, tanh), Dense(256 => 1)) rng = Random.default_rng() Random.seed!(rng, local_rank()) ps, st = Lux.setup(rng, model) .|> gpu ps = FluxMPI.synchronize!(ps; root_rank = 0) st = FluxMPI.synchronize!(st; root_rank = 0) ``` ## Step 3: Ensure data is properly partitioned It is the user's responsibility to partition the data across the processes. In this case, we are training on a total of `16 * <np>` samples. Instead of manually partitioning the data, we can use [`DistributedDataContainer`](@ref) to partition the data. ```julia x = rand(rng, 1, 16) |> gpu y = x .^ 2 ``` ## Step 4: Wrap the optimizer in [`DistributedOptimizer`](@ref) Remember to scale the learning rate by the number of workers [`total_workers`](@ref). ```julia opt = DistributedOptimizer(Adam(0.001f0)) st_opt = Optimisers.setup(opt, ps) loss(p) = sum(abs2, model(x, p, st)[1] .- y) ``` ## Step 5: Synchronize the optimizer state ```julia st_opt = FluxMPI.synchronize!(st_opt; root_rank = 0) ``` ## Step 6: Train your model Remember to print using [`fluxmpi_println`](@ref) or [`fluxmpi_print`](@ref). ```julia gs_ = gradient(loss, ps)[1] Optimisers.update(st_opt, ps, gs_) t1 = time() for epoch in 1:100 global ps, st_opt l, back = Zygote.pullback(loss, ps) FluxMPI.fluxmpi_println("Epoch $epoch: Loss $l") gs = back(one(l))[1] st_opt, ps = Optimisers.update(st_opt, ps, gs) end FluxMPI.fluxmpi_println(time() - t1) ``` Run the code using `mpiexecjl -n 3 julia --project=. <filename>.jl`. ## Complete Script ```julia using CUDA, FluxMPI, Lux, Optimisers, Random, Zygote FluxMPI.Init() CUDA.allowscalar(false) model = Chain(Dense(1 => 256, tanh), Dense(256 => 512, tanh), Dense(512 => 256, tanh), Dense(256 => 1)) rng = Random.default_rng() Random.seed!(rng, local_rank()) ps, st = Lux.setup(rng, model) .|> gpu ps = FluxMPI.synchronize!(ps; root_rank = 0) st = FluxMPI.synchronize!(st; root_rank = 0) x = rand(rng, 1, 16) |> gpu y = x .^ 2 opt = DistributedOptimizer(Adam(0.001f0)) st_opt = Optimisers.setup(opt, ps) loss(p) = sum(abs2, model(x, p, st)[1] .- y) st_opt = FluxMPI.synchronize!(st_opt; root_rank = 0) gs_ = gradient(loss, ps)[1] Optimisers.update(st_opt, ps, gs_) t1 = time() for epoch in 1:100 global ps, st_opt l, back = Zygote.pullback(loss, ps) FluxMPI.fluxmpi_println("Epoch $epoch: Loss $l") gs = back(one(l))[1] st_opt, ps = Optimisers.update(st_opt, ps, gs) end FluxMPI.fluxmpi_println(time() - t1) ```
FluxMPI
https://github.com/avik-pal/FluxMPI.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
4098
## Load WGPU using WGPUNative include("$(pkgdir(WGPUNative))/examples/requestDevice.jl") ## Buffer dimensions width, height = (200, 200) struct BufferDimensions height::UInt32 width::UInt32 padded_bytes_per_row::UInt32 unpadded_bytes_per_row::UInt32 function BufferDimensions(width, height) bytes_per_pixel = sizeof(UInt32) unpadded_bytes_per_row = width*bytes_per_pixel align = 256 padded_bytes_per_row_padding = (align - unpadded_bytes_per_row % align) % align padded_bytes_per_row = unpadded_bytes_per_row + padded_bytes_per_row_padding return new(height, width, padded_bytes_per_row, unpadded_bytes_per_row) end end bufferDimensions = BufferDimensions(width, height) bufferSize = bufferDimensions.padded_bytes_per_row*bufferDimensions.height outputBuffer = wgpuDeviceCreateBuffer( device[], cStruct( WGPUBufferDescriptor; nextInChain = C_NULL, label = toCString("Output Buffer"), usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, size = bufferSize, mappedAtCreation = false ) |> ptr ) ## textureExtent textureExtent = cStruct( WGPUExtent3D; width = bufferDimensions.width, height = bufferDimensions.height, depthOrArrayLayers = 1 ) ## texture texture = wgpuDeviceCreateTexture( device[], cStruct( WGPUTextureDescriptor; size = textureExtent |> concrete, mipLevelCount = 1, sampleCount = 1, dimension = WGPUTextureDimension_2D, format = WGPUTextureFormat_RGBA8UnormSrgb, usage = WGPUTextureUsage_RenderAttachment | WGPUTextureUsage_CopySrc, ) |> ptr ) ## encoder encoder = wgpuDeviceCreateCommandEncoder( device[], cStruct(WGPUCommandEncoderDescriptor) |> ptr ) ## outputAttachment # outputAttachment = wgpuTextureCreateView( # texture, # pointer_from_objref(Ref(defaultInit(WGPUTextureViewDescriptor))) # ) outputAttachment = wgpuTextureCreateView( texture, C_NULL ) ## renderPass renderPass = wgpuCommandEncoderBeginRenderPass( encoder, cStruct( WGPURenderPassDescriptor; colorAttachments = cStruct( WGPURenderPassColorAttachment; view = outputAttachment, resolveTarget = 0, loadOp = WGPULoadOp_Clear, storeOp = WGPUStoreOp_Store, clearValue = WGPUColor(1.0, 0.0, 0.0, 1.0), ) |> ptr, colorAttachmentCount = 1, depthStencilAttachment = C_NULL ) |> ptr ) ## end renderpass wgpuRenderPassEncoderEnd(renderPass) ## Copy texture to buffer wgpuCommandEncoderCopyTextureToBuffer( encoder, cStruct( WGPUImageCopyTexture; texture = texture, miplevel = 0, origin = WGPUOrigin3D(0, 0, 0) ) |> ptr, cStruct( WGPUImageCopyBuffer; buffer = outputBuffer, layout = cStruct( WGPUTextureDataLayout; offset = 0, bytesPerRow = bufferDimensions.padded_bytes_per_row, rowsPerImage = WGPU_COPY_STRIDE_UNDEFINED ) |> concrete ) |> ptr, (textureExtent) |> ptr ) queue = wgpuDeviceGetQueue(device[]) ## commandBuffer cmdBuffer = wgpuCommandEncoderFinish( encoder, cStruct(WGPUCommandBufferDescriptor) |> ptr ) ## submit queue wgpuQueueSubmit(queue, 1, Ref(cmdBuffer)) ## MapAsync asyncstatus = Ref(WGPUBufferMapAsyncStatus(3)) function readBufferMap( status::WGPUBufferMapAsyncStatus, userData) asyncstatus[] = status return nothing end readbuffermap = @cfunction(readBufferMap, Cvoid, (WGPUBufferMapAsyncStatus, Ptr{Cvoid})) wgpuBufferMapAsync(outputBuffer, WGPUMapMode_Read, 0, bufferSize, readbuffermap, C_NULL) print(asyncstatus[]) ## device polling wgpuDevicePoll(device[], true, C_NULL) ## times times = convert(Ptr{UInt8}, wgpuBufferGetMappedRange(outputBuffer, 0, bufferSize)) ## result for i in 1:width*height println(i, " : ", unsafe_load(times, i)) end ## Unmap wgpuBufferUnmap(outputBuffer) ## TODO dump as an image
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
8904
## Load WGPU using WGPUNative ## Constants numbers = UInt32[1,2,3,4] const DEFAULT_ARRAY_SIZE = 256 ## Init Window Size const width = 200 const height = 200 ## default inits for non primitive types defaultInit(::Type{T}) where T<:Number = T(0) defaultInit(::Type{T}) where T = begin if isprimitivetype(T) return T(0) else ins = [] for t = fieldnames(T) push!(ins, defaultInit(fieldtype(T, t))) end return T(ins...) end end defaultInit(::Type{WGPUNativeFeature}) = WGPUNativeFeature(0x10000000) defaultInit(::Type{WGPUSType}) = WGPUSType(6) defaultInit(::Type{T}) where T<:Ptr{Nothing} = Ptr{Nothing}() defaultInit(::Type{Array{T, N}}) where T where N = zeros(T, DEFAULT_ARRAY_SIZE) defaultInit(::Type{WGPUPowerPreference}) = WGPUPowerPreference(1) function partialInit(target::Type{T}; fields...) where T ins = [] inPairs = pairs(fields) for field in fieldnames(T) if field in keys(inPairs) push!(ins, inPairs[field]) else push!(ins, defaultInit(fieldtype(T, field))) end end return T(ins...) end println("Current Version : $(wgpuGetVersion())") function logCallBack(logLevel::WGPULogLevel, msg::Ptr{Cchar}) if logLevel == WGPULogLevel_Error level_str = "ERROR" elseif logLevel == WGPULogLevel_Warn level_str = "WARN" elseif logLevel == WGPULogLevel_Info level_str = "INFO" elseif logLevel == WGPULogLevel_Debug level_str = "DEBUG" elseif logLevel == WGPULogLevel_Trace level_str = "TRACE" else level_str = "UNKNOWN LOG LEVEL" end println("$(level_str) $(unsafe_string(msg))") end logcallback = @cfunction(logCallBack, Cvoid, (WGPULogLevel, Ptr{Cchar})) wgpuSetLogCallback(logcallback, Ptr{Cvoid}()) wgpuSetLogLevel(WGPULogLevel(4)) ## adapter = Ref(WGPUAdapter()) device = Ref(WGPUDevice()) adapterOptions = Ref(defaultInit(WGPURequestAdapterOptions)) function request_adapter_callback( a::WGPURequestAdapterStatus, b::WGPUAdapter, c::Ptr{Cchar}, d::Ptr{Nothing}) global adapter[] = b return nothing end requestAdapterCallback = @cfunction(request_adapter_callback, Cvoid, (WGPURequestAdapterStatus, WGPUAdapter, Ptr{Cchar}, Ptr{Cvoid})) ## device callback function request_device_callback( a::WGPURequestDeviceStatus, b::WGPUDevice, c::Ptr{Cchar}, d::Ptr{Nothing}) global device[] = b return nothing end requestDeviceCallback = @cfunction(request_device_callback, Cvoid, (WGPURequestDeviceStatus, WGPUDevice, Ptr{Cchar}, Ptr{Cvoid})) ## request adapter instance = wgpuCreateInstance(WGPUInstanceDescriptor(0) |> Ref) wgpuInstanceRequestAdapter(instance, adapterOptions, requestAdapterCallback, adapter) ## # chain = WGPUChainedStruct(C_NULL, WGPUSType(6)) # # deviceName = Vector{UInt8}("Device") # deviceExtras = WGPUDeviceExtras(chain, defaultInit(WGPUNativeFeature), pointer(deviceName), C_NULL) # # const DEFAULT_ARRAY_SIZE = 256 # # wgpuLimits = partialInit(WGPULimits; maxBindGroups = 1) # # wgpuRequiredLimits = WGPURequiredLimits(C_NULL, wgpuLimits) # # wgpuQueueDescriptor = WGPUQueueDescriptor(C_NULL, C_NULL) # # wgpuDeviceDescriptor = Ref( # partialInit( # WGPUDeviceDescriptor, # nextInChain = pointer_from_objref(Ref(partialInit(WGPUChainedStruct, chain=deviceExtras))), # requiredLimits = pointer_from_objref(Ref(wgpuRequiredLimits)), # defaultQueue = wgpuQueueDescriptor # ) # ) wgpuAdapterRequestDevice( adapter[], C_NULL, requestDeviceCallback, device[]) ## Buffer dimensions struct BufferDimensions height::UInt32 width::UInt32 padded_bytes_per_row::UInt32 unpadded_bytes_per_row::UInt32 function BufferDimensions(width, height) bytes_per_pixel = sizeof(UInt32) unpadded_bytes_per_row = width*bytes_per_pixel align = 256 padded_bytes_per_row_padding = (align - unpadded_bytes_per_row % align) % align padded_bytes_per_row = unpadded_bytes_per_row + padded_bytes_per_row_padding return new(height, width, padded_bytes_per_row, unpadded_bytes_per_row) end end bufferDimensions = BufferDimensions(width, height) bufferSize = bufferDimensions.padded_bytes_per_row*bufferDimensions.height outputBuffer = wgpuDeviceCreateBuffer( device[], pointer_from_objref(Ref(partialInit(WGPUBufferDescriptor; nextInChain = C_NULL, label = pointer(Vector{UInt8}("Output Buffer")), usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, size = bufferSize, mappedAtCreation = false ))) ) ## textureExtent textureExtent = partialInit( WGPUExtent3D; width = bufferDimensions.width, height = bufferDimensions.height, depthOrArrayLayers = 1 ) ## texture texture = wgpuDeviceCreateTexture( device[], pointer_from_objref(Ref(partialInit(WGPUTextureDescriptor; size = textureExtent, mipLevelCount = 1, sampleCount = 1, dimension = WGPUTextureDimension_2D, format = WGPUTextureFormat_RGBA8UnormSrgb, usage = WGPUTextureUsage_RenderAttachment | WGPUTextureUsage_CopySrc, )))) ## encoder encoder = wgpuDeviceCreateCommandEncoder( device[], pointer_from_objref(Ref(defaultInit(WGPUCommandEncoderDescriptor)))) ## outputAttachment # outputAttachment = wgpuTextureCreateView( # texture, # pointer_from_objref(Ref(defaultInit(WGPUTextureViewDescriptor))) # ) outputAttachment = wgpuTextureCreateView( texture, C_NULL ) ## renderPass renderPass = wgpuCommandEncoderBeginRenderPass( encoder, pointer_from_objref(Ref(partialInit(WGPURenderPassDescriptor; colorAttachments = pointer_from_objref(Ref(partialInit(WGPURenderPassColorAttachment; view = outputAttachment, resolveTarget = 0, loadOp = WGPULoadOp_Clear, storeOp = WGPUStoreOp_Store, clearValue = WGPUColor(1.0, 0.0, 0.0, 1.0), ))), colorAttachmentCount = 1, depthStencilAttachment = C_NULL ))) ) ## end renderpass wgpuRenderPassEncoderEnd(renderPass) ## Copy texture to buffer wgpuCommandEncoderCopyTextureToBuffer( encoder, pointer_from_objref(Ref(partialInit(WGPUImageCopyTexture; texture = texture, miplevel = 0, origin = WGPUOrigin3D(0, 0, 0)))), pointer_from_objref(Ref(partialInit(WGPUImageCopyBuffer; buffer = outputBuffer, layout = partialInit(WGPUTextureDataLayout; offset = 0, bytesPerRow = bufferDimensions.padded_bytes_per_row, rowsPerImage = WGPU_COPY_STRIDE_UNDEFINED )))), Ref(textureExtent)) ## ## # # # # ## # # # ## # # # # ## # # # # ## queue queue = wgpuDeviceGetQueue(device[]) ## commandBuffer cmdBuffer = wgpuCommandEncoderFinish( encoder, pointer_from_objref(Ref(defaultInit(WGPUCommandBufferDescriptor))) ) ## submit queue wgpuQueueSubmit(queue, 1, Ref(cmdBuffer)) ## MapAsync asyncstatus = Ref(WGPUBufferMapAsyncStatus(3)) function readBufferMap( status::WGPUBufferMapAsyncStatus, userData) asyncstatus[] = status return nothing end readbuffermap = @cfunction(readBufferMap, Cvoid, (WGPUBufferMapAsyncStatus, Ptr{Cvoid})) wgpuBufferMapAsync(outputBuffer, WGPUMapMode_Read, 0, bufferSize, readbuffermap, C_NULL) print(asyncstatus[]) ## device polling wgpuDevicePoll(device[], true, C_NULL) ## times times = convert(Ptr{UInt8}, wgpuBufferGetMappedRange(outputBuffer, 0, bufferSize)) ## result for i in 1:width*height println(i, " : ", unsafe_load(times, i)) end ## Unmap # wgpuBufferUnmap(outputBuffer) ## TODO dump as an image
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
5989
using WGPUNative numbers = UInt32[1,2,3,4] include("$(pkgdir(WGPUNative))/examples/requestDevice.jl") ## b = read("examples/shader.wgsl") wgslDescriptor = cStruct(WGPUShaderModuleWGSLDescriptor) wgslDescriptor.chain = cStruct(WGPUChainedStruct) |> concrete wgslDescriptor.code = pointer(b) # wgslDescriptor = WGPUShaderModuleWGSLDescriptor( # cStruct(WGPUChainedStruct) |> concrete, # pointer(b) # ) ## WGSL loading function load_wgsl(filename) b = read(filename) wgslDescriptor = cStruct(WGPUShaderModuleWGSLDescriptor) wgslDescriptor.chain = cStruct( WGPUChainedStruct; sType=WGPUSType_ShaderModuleWGSLDescriptor ) |> concrete wgslDescriptor.code = pointer(b) a = cStruct( WGPUShaderModuleDescriptor; nextInChain = wgslDescriptor |> ptr, label = toCString(filename) ) return (a, wgslDescriptor) end (shaderSource, _) = load_wgsl("examples/shader.wgsl") ## shader = wgpuDeviceCreateShaderModule( device[], shaderSource |> ptr ) ## StagingBuffer stagingBuffer = wgpuDeviceCreateBuffer( device[], cStruct( WGPUBufferDescriptor; nextInChain = C_NULL, label = toCString("StagingBuffer"), usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, size = sizeof(numbers), mappedAtCreation = false ) |> ptr ) ## StorageBuffer storageBuffer = wgpuDeviceCreateBuffer( device[], cStruct( WGPUBufferDescriptor; nextInChain = C_NULL, label = toCString("StorageBuffer"), usage = WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst | WGPUBufferUsage_CopySrc, size = sizeof(numbers), mappedAtCreation = false ) |> ptr ) ## BindGroupLayout bindGroupLayout = wgpuDeviceCreateBindGroupLayout( device[], cStruct( WGPUBindGroupLayoutDescriptor; label = toCString("Bind Group Layout"), entries = cStruct( WGPUBindGroupLayoutEntry; nextInChain = C_NULL, binding = 0, visibility = WGPUShaderStage_Compute, buffer = cStruct( WGPUBufferBindingLayout; type=WGPUBufferBindingType_Storage ) |> concrete, sampler = cStruct( WGPUSamplerBindingLayout; ) |> concrete, texture = cStruct( WGPUTextureBindingLayout; ) |> concrete, storageTexture = cStruct( WGPUStorageTextureBindingLayout; ) |> concrete ) |> ptr, entryCount = 1 ) |> ptr ) ## BindGroup bindGroup = wgpuDeviceCreateBindGroup( device[], cStruct( WGPUBindGroupDescriptor; label = toCString("Bind Group"), layout = bindGroupLayout, entries = cStruct( WGPUBindGroupEntry; binding = 0, buffer = storageBuffer, offset = 0, size = sizeof(numbers) ) |> ptr, entryCount = 1 ) |> ptr ) ## bindGroupLayouts bindGroupLayouts = [bindGroupLayout,] ## Pipeline Layout pipelineLayout = wgpuDeviceCreatePipelineLayout( device[], cStruct( WGPUPipelineLayoutDescriptor; bindGroupLayouts = pointer(bindGroupLayouts), bindGroupLayoutCount = 1 ) |> ptr ) ## TODO fix compute = cStruct( WGPUProgrammableStageDescriptor; _module = shader, entryPoint = toCString("main") ) |> concrete ## compute pipeline computePipeline = wgpuDeviceCreateComputePipeline( device[], cStruct( WGPUComputePipelineDescriptor, layout = pipelineLayout, compute = cStruct( WGPUProgrammableStageDescriptor; _module = shader, entryPoint = toCString("main") ) |> concrete ) |> ptr ) ## encoder encoder = wgpuDeviceCreateCommandEncoder( device[], cStruct( WGPUCommandEncoderDescriptor; label = toCString("Command Encoder") ) |> ptr ) ## computePass computePass = wgpuCommandEncoderBeginComputePass( encoder, cStruct( WGPUComputePassDescriptor; label = toCString("Compute Pass") ) |> ptr ) ## set pipeline wgpuComputePassEncoderSetPipeline(computePass, computePipeline) wgpuComputePassEncoderSetBindGroup(computePass, 0, bindGroup, 0, C_NULL) wgpuComputePassEncoderDispatchWorkgroups(computePass, length(numbers), 1, 1) wgpuComputePassEncoderEnd(computePass) ## buffer copy buffer wgpuCommandEncoderCopyBufferToBuffer(encoder, storageBuffer, 0, stagingBuffer, 0, sizeof(numbers)) ## queue queue = wgpuDeviceGetQueue(device[]) ## commandBuffer cmdBuffer = wgpuCommandEncoderFinish( encoder, cStruct(WGPUCommandBufferDescriptor) |> ptr ) ## writeBuffer wgpuQueueWriteBuffer(queue, storageBuffer, 0, pointer(numbers), sizeof(numbers)) ## submit queue wgpuQueueSubmit(queue, 1, Ref(cmdBuffer)) ## MapAsync asyncstatus = Ref(WGPUBufferMapAsyncStatus(3)) function readBufferMap( status::WGPUBufferMapAsyncStatus, userData) asyncstatus[] = status return nothing end readbuffermap = @cfunction(readBufferMap, Cvoid, (WGPUBufferMapAsyncStatus, Ptr{Cvoid})) wgpuBufferMapAsync(stagingBuffer, WGPUMapMode_Read, 0, sizeof(numbers), readbuffermap, C_NULL) print(asyncstatus[]) ## device polling wgpuDevicePoll(device[], true, C_NULL) ## times times = convert(Ptr{UInt32}, wgpuBufferGetMappedRange(stagingBuffer, 0, sizeof(numbers))) ## result for i in eachindex(numbers) println(numbers[i], " : " ,unsafe_load(times, i)) end
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
10116
## Load WGPU using WGPUNative ## Constants numbers = UInt32[1,2,3,4] const DEFAULT_ARRAY_SIZE = 256 ## Init Window Size const width = 200 const height = 200 ## default inits for non primitive types defaultInit(::Type{T}) where T<:Number = T(0) defaultInit(::Type{T}) where T = begin if isprimitivetype(T) return T(0) else ins = [] for t = fieldnames(T) push!(ins, defaultInit(fieldtype(T, t))) end return T(ins...) end end defaultInit(::Type{WGPUNativeFeature}) = WGPUNativeFeature(0x10000000) defaultInit(::Type{WGPUSType}) = WGPUSType(6) defaultInit(::Type{T}) where T<:Ptr{Nothing} = Ptr{Nothing}() defaultInit(::Type{Array{T, N}}) where T where N = zeros(T, DEFAULT_ARRAY_SIZE) defaultInit(::Type{WGPUPowerPreference}) = WGPUPowerPreference(1) function partialInit(target::Type{T}; fields...) where T ins = [] inPairs = pairs(fields) for field in fieldnames(T) if field in keys(inPairs) push!(ins, inPairs[field]) else push!(ins, defaultInit(fieldtype(T, field))) end end return T(ins...) end ## Print current version println("Current Version : $(wgpuGetVersion())") ## Set Log callbacks function logCallBack(logLevel::WGPULogLevel, msg::Ptr{Cchar}) if logLevel == WGPULogLevel_Error level_str = "ERROR" elseif logLevel == WGPULogLevel_Warn level_str = "WARN" elseif logLevel == WGPULogLevel_Info level_str = "INFO" elseif logLevel == WGPULogLevel_Debug level_str = "DEBUG" elseif logLevel == WGPULogLevel_Trace level_str = "TRACE" else level_str = "UNKNOWN LOG LEVEL" end println("$(level_str) $(unsafe_string(msg))") end logcallback = @cfunction(logCallBack, Cvoid, (WGPULogLevel, Ptr{Cchar})) wgpuSetLogCallback(logcallback, C_NULL) wgpuSetLogLevel(WGPULogLevel(4)) ## adapter = Ref(WGPUAdapter()) device = Ref(WGPUDevice()) adapterOptions = Ref(defaultInit(WGPURequestAdapterOptions)) function request_adapter_callback( a::WGPURequestAdapterStatus, b::WGPUAdapter, c::Ptr{Cchar}, d::Ptr{Nothing}) global adapter[] = b return nothing end requestAdapterCallback = @cfunction(request_adapter_callback, Cvoid, (WGPURequestAdapterStatus, WGPUAdapter, Ptr{Cchar}, Ptr{Cvoid})) ## device callback function request_device_callback( a::WGPURequestDeviceStatus, b::WGPUDevice, c::Ptr{Cchar}, d::Ptr{Nothing}) global device[] = b return nothing end requestDeviceCallback = @cfunction(request_device_callback, Cvoid, (WGPURequestDeviceStatus, WGPUDevice, Ptr{Cchar}, Ptr{Cvoid})) instance = wgpuCreateInstance(WGPUInstanceDescriptor(0) |> Ref) ## request adapter wgpuInstanceRequestAdapter(instance, adapterOptions, requestAdapterCallback, adapter) ## # chain = WGPUChainedStruct(C_NULL, WGPUSType(6)) # # deviceName = Vector{UInt8}("Device") # deviceExtras = WGPUDeviceExtras(chain, defaultInit(WGPUNativeFeature), pointer(deviceName), C_NULL) # # const DEFAULT_ARRAY_SIZE = 256 # # wgpuLimits = partialInit(WGPULimits; maxBindGroups = 1) # # wgpuRequiredLimits = WGPURequiredLimits(C_NULL, wgpuLimits) # # wgpuQueueDescriptor = WGPUQueueDescriptor(C_NULL, C_NULL) # # wgpuDeviceDescriptor = Ref( # partialInit( # WGPUDeviceDescriptor, # nextInChain = pointer_from_objref(Ref(partialInit(WGPUChainedStruct, chain=deviceExtras))), # requiredLimits = pointer_from_objref(Ref(wgpuRequiredLimits)), # defaultQueue = wgpuQueueDescriptor # ) # ) # wgpuAdapterRequestDevice( # adapter[], # wgpuDeviceDescriptor, # requestDeviceCallback, # device[]) wgpuAdapterRequestDevice( adapter[], C_NULL, requestDeviceCallback, device[]) ## b = read("examples/shader.wgsl") wgslDescriptor = WGPUShaderModuleWGSLDescriptor( defaultInit(WGPUChainedStruct), pointer(b) ) ## WGSL loading function load_wgsl(filename) b = read(filename) wgslDescriptor = Ref(WGPUShaderModuleWGSLDescriptor( defaultInit(WGPUChainedStruct), pointer(b) )) a = partialInit( WGPUShaderModuleDescriptor; nextInChain = pointer_from_objref(wgslDescriptor), label = pointer(Vector{UInt8}("$(filename)")) ) return (a, wgslDescriptor) end shaderSource = Ref(load_wgsl("examples/shader.wgsl")[1]) ## shader = wgpuDeviceCreateShaderModule( device[], pointer_from_objref(shaderSource) ) ## StagingBuffer stagingBuffer = wgpuDeviceCreateBuffer(device[], Ref(partialInit(WGPUBufferDescriptor; nextInChain = C_NULL, label = pointer(Vector{UInt8}("StagingBuffer")), usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, size = sizeof(numbers), mappedAtCreation = false ))) ## StorageBuffer storageBuffer = wgpuDeviceCreateBuffer(device[], Ref(partialInit(WGPUBufferDescriptor; nextInChain = C_NULL, label = pointer(Vector{UInt8}("StorageBuffer")), usage = WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst | WGPUBufferUsage_CopySrc, size = sizeof(numbers), mappedAtCreation = false ))) ## BindGroupLayout bindGroupLayout = wgpuDeviceCreateBindGroupLayout( device[], Ref(partialInit(WGPUBindGroupLayoutDescriptor; label = pointer(Vector{UInt8}("Bind Group Layout")), entries = pointer_from_objref(Ref(partialInit( WGPUBindGroupLayoutEntry; nextInChain = C_NULL, binding = 0, visibility = WGPUShaderStage_Compute, buffer = partialInit( WGPUBufferBindingLayout; type=WGPUBufferBindingType_Storage ), sampler = defaultInit( WGPUSamplerBindingLayout; ), texture = defaultInit( WGPUTextureBindingLayout; ), storageTexture = defaultInit( WGPUStorageTextureBindingLayout; ) ))), entryCount = 1 )) ) ## BindGroup bindGroup = wgpuDeviceCreateBindGroup( device[], pointer_from_objref(Ref(partialInit( WGPUBindGroupDescriptor; label = pointer(Vector{UInt8}("Bind Group")), layout = bindGroupLayout, entries = pointer_from_objref(Ref(partialInit(WGPUBindGroupEntry; binding = 0, buffer = storageBuffer, offset = 0, size = sizeof(numbers)))), entryCount = 1 )))) ## bindGroupLayouts bindGroupLayouts = [bindGroupLayout,] ## Pipeline Layout pipelineLayout = wgpuDeviceCreatePipelineLayout( device[], pointer_from_objref(Ref(partialInit( WGPUPipelineLayoutDescriptor; bindGroupLayouts = pointer(bindGroupLayouts), bindGroupLayoutCount = 1 ) ))) ## TODO fix compute = partialInit( WGPUProgrammableStageDescriptor; _module = shader, entryPoint = pointer(Vector{UInt8}("main")) ) ## compute pipeline computePipeline = wgpuDeviceCreateComputePipeline( device[], pointer_from_objref(Ref(partialInit( WGPUComputePipelineDescriptor, layout = pipelineLayout, compute = partialInit( WGPUProgrammableStageDescriptor; _module = shader, entryPoint = pointer(Vector{UInt8}("main")) ) )))) ## encoder encoder = wgpuDeviceCreateCommandEncoder(device[], pointer_from_objref(Ref(partialInit( WGPUCommandEncoderDescriptor; label = pointer(Vector{UInt8}("Command Encoder")) )))) ## computePass computePass = wgpuCommandEncoderBeginComputePass(encoder, pointer_from_objref(Ref(partialInit( WGPUComputePassDescriptor; label = pointer(Vector{UInt8}("Compute Pass")) )))) ## set pipeline wgpuComputePassEncoderSetPipeline(computePass, computePipeline) wgpuComputePassEncoderSetBindGroup(computePass, 0, bindGroup, 0, C_NULL) wgpuComputePassEncoderDispatchWorkgroups(computePass, length(numbers), 1, 1) wgpuComputePassEncoderEnd(computePass) ## buffer copy buffer wgpuCommandEncoderCopyBufferToBuffer(encoder, storageBuffer, 0, stagingBuffer, 0, sizeof(numbers)) ## queue queue = wgpuDeviceGetQueue(device[]) ## commandBuffer cmdBuffer = wgpuCommandEncoderFinish( encoder, pointer_from_objref(Ref(defaultInit(WGPUCommandBufferDescriptor))) ) ## writeBuffer wgpuQueueWriteBuffer(queue, storageBuffer, 0, pointer(numbers), sizeof(numbers)) ## submit queue wgpuQueueSubmit(queue, 1, Ref(cmdBuffer)) ## MapAsync asyncstatus = Ref(WGPUBufferMapAsyncStatus(3)) function readBufferMap( status::WGPUBufferMapAsyncStatus, userData) asyncstatus[] = status return nothing end readbuffermap = @cfunction(readBufferMap, Cvoid, (WGPUBufferMapAsyncStatus, Ptr{Cvoid})) wgpuBufferMapAsync(stagingBuffer, WGPUMapMode_Read, 0, sizeof(numbers), readbuffermap, C_NULL) print(asyncstatus[]) ## device polling wgpuDevicePoll(device[], true, C_NULL) ## times times = convert(Ptr{UInt32}, wgpuBufferGetMappedRange(stagingBuffer, 0, sizeof(numbers))) ## result for i in 1:length(numbers) println(numbers[i], " : " ,unsafe_load(times, i)) end
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
2315
## Load WGPU using WGPUNative function logCallBack(logLevel::WGPULogLevel, msg::Ptr{Cchar}) if logLevel == WGPULogLevel_Error level_str = "ERROR" elseif logLevel == WGPULogLevel_Warn level_str = "WARN" elseif logLevel == WGPULogLevel_Info level_str = "INFO" elseif logLevel == WGPULogLevel_Debug level_str = "DEBUG" elseif logLevel == WGPULogLevel_Trace level_str = "TRACE" else level_str = "UNKNOWN LOG LEVEL" end println("$(level_str) $(unsafe_string(msg))") end logcallback = @cfunction(logCallBack, Cvoid, (WGPULogLevel, Ptr{Cchar})) wgpuSetLogCallback(logcallback, Ptr{Cvoid}()) wgpuSetLogLevel(WGPULogLevel_Debug) adapter = Ref{WGPUAdapter}() chain = cStruct( WGPUChainedStruct; sType = WGPUSType(Int64(WGPUSType_AdapterExtras)), ) extras = cStruct( WGPUAdapterExtras; backend=WGPUBackendType_Vulkan, # TODO hardcoding on windows for now chain = chain |> concrete ) # extras.chain = chain |> concrete adapterOptions = cStruct(WGPURequestAdapterOptions) adapterOptions.compatibleSurface = C_NULL adapterOptions.nextInChain = rawCast(WGPUChainedStruct, extras) adapterOptions.powerPreference = WGPUPowerPreference_HighPerformance adapterOptions.forceFallbackAdapter = false function request_adapter_callback( status::WGPURequestAdapterStatus, returnAdapter::WGPUAdapter, message::Ptr{Cchar}, userData::Ptr{Cvoid}) global adapter # @debug status if status == WGPURequestAdapterStatus_Success adapter[] = returnAdapter elseif message != C_NULL @error unsafe_string(message) end return nothing end requestAdapterCallback = @cfunction(request_adapter_callback, Cvoid, (WGPURequestAdapterStatus, WGPUAdapter, Ptr{Cchar}, Ptr{Cvoid})) ## request adapter instanceDesc = cStruct(WGPUInstanceDescriptor) instanceDesc.nextInChain = C_NULL instance = wgpuCreateInstance(instanceDesc |> ptr) wgpuInstanceRequestAdapter(instance, adapterOptions |> ptr, requestAdapterCallback, C_NULL) @assert adapter[] != C_NULL properties = cStruct(WGPUAdapterProperties) wgpuAdapterGetProperties(adapter[], properties |> ptr) supportedLimits = cStruct(WGPUSupportedLimits) cLimits = supportedLimits.limits wgpuAdapterGetLimits(adapter[], supportedLimits |> ptr)
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
2438
## Load WGPU using WGPUNative function logCallBack(logLevel::WGPULogLevel, msg::Ptr{Cchar}) if logLevel == WGPULogLevel_Error level_str = "ERROR" elseif logLevel == WGPULogLevel_Warn level_str = "WARN" elseif logLevel == WGPULogLevel_Info level_str = "INFO" elseif logLevel == WGPULogLevel_Debug level_str = "DEBUG" elseif logLevel == WGPULogLevel_Trace level_str = "TRACE" else level_str = "UNKNOWN LOG LEVEL" end println("$(level_str) $(unsafe_string(msg))") end logcallback = @cfunction(logCallBack, Cvoid, (WGPULogLevel, Ptr{Cchar})) wgpuSetLogCallback(logcallback, Ptr{Cvoid}()) wgpuSetLogLevel(WGPULogLevel_Debug) adapter = Ref{WGPUAdapter}() adapterOptions = cStruct(WGPURequestAdapterOptions) adapterOptions.compatibleSurface = C_NULL adapterOptions.powerPreference = WGPUPowerPreference_HighPerformance adapterOptions.forceFallbackAdapter = false function request_adapter_callback( status::WGPURequestAdapterStatus, returnAdapter::WGPUAdapter, message::Ptr{Cchar}, userData::Ptr{Cvoid}) global adapter # @debug status if status == WGPURequestAdapterStatus_Success adapter[] = returnAdapter elseif message != C_NULL @error unsafe_string(message) end return nothing end requestAdapterCallback = @cfunction(request_adapter_callback, Cvoid, (WGPURequestAdapterStatus, WGPUAdapter, Ptr{Cchar}, Ptr{Cvoid})) ## request adapter instanceDesc = cStruct(WGPUInstanceDescriptor) instanceDesc.nextInChain = C_NULL instance = wgpuCreateInstance(instanceDesc |> ptr) wgpuInstanceRequestAdapter(instance, adapterOptions |> ptr, requestAdapterCallback, C_NULL) @assert adapter[] != C_NULL properties = cStruct(WGPUAdapterProperties) wgpuAdapterGetProperties(adapter[], properties |> ptr) supportedLimits = cStruct(WGPUSupportedLimits) cLimits = supportedLimits.limits wgpuAdapterGetLimits(adapter[], supportedLimits |> ptr) device = Ref{WGPUDevice}() function request_device_callback( a::WGPURequestDeviceStatus, b::WGPUDevice, c::Ptr{Cchar}, d::Ptr{Nothing}) global device[] = b return nothing end requestDeviceCallback = @cfunction(request_device_callback, Cvoid, (WGPURequestDeviceStatus, WGPUDevice, Ptr{Cchar}, Ptr{Cvoid})) wgpuAdapterRequestDevice( adapter[], C_NULL, requestDeviceCallback, device[])
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
13415
## Load WGPU using WGPUNative using GLFW ## Constants numbers = UInt32[1,2,3,4] const DEFAULT_ARRAY_SIZE = 256 ## Init Window Size width = 400 height = 400 ## default inits for non primitive types defaultInit(::Type{T}) where T<:Number = T(0) defaultInit(::Type{T}) where T = begin if isprimitivetype(T) return T(0) else ins = [] for t = fieldnames(T) push!(ins, defaultInit(fieldtype(T, t))) end return T(ins...) end end defaultInit(::Type{WGPUNativeFeature}) = WGPUNativeFeature(0x10000000) defaultInit(::Type{WGPUSType}) = WGPUSType(6) defaultInit(::Type{T}) where T<:Ptr{Nothing} = Ptr{Nothing}() defaultInit(::Type{Array{T, N}}) where T where N = zeros(T, DEFAULT_ARRAY_SIZE) defaultInit(::Type{WGPUPowerPreference}) = WGPUPowerPreference(1) function partialInit(target::Type{T}; fields...) where T ins = [] inPairs = pairs(fields) for field in fieldnames(T) if field in keys(inPairs) push!(ins, inPairs[field]) else push!(ins, defaultInit(fieldtype(T, field))) end end return T(ins...) end ## Print current version println("Current Version : $(wgpuGetVersion())") ## Set Log callbacks function logCallBack(logLevel::WGPULogLevel, msg::Ptr{Cchar}) if logLevel == WGPULogLevel_Error level_str = "ERROR" elseif logLevel == WGPULogLevel_Warn level_str = "WARN" elseif logLevel == WGPULogLevel_Info level_str = "INFO" elseif logLevel == WGPULogLevel_Debug level_str = "DEBUG" elseif logLevel == WGPULogLevel_Trace level_str = "TRACE" else level_str = "UNKNOWN LOG LEVEL" end println("$(level_str) $(unsafe_string(msg))") end logcallback = @cfunction(logCallBack, Cvoid, (WGPULogLevel, Ptr{Cchar})) wgpuSetLogCallback(logcallback, C_NULL) wgpuSetLogLevel(WGPULogLevel(4)) ## Surface ## X11 Surface # using WGPU # using WGPU: partialInit, defaultInit, pointerRef using WGPUNative using GLFW surface = Ref(Ptr{Nothing}()) display = GLFW.GetX11Display() window = GLFW.Window() windowX11 = GLFW.GetX11Window(window) surface = wgpuInstanceCreateSurface( C_NULL, pointer_from_objref( Ref(partialInit( WGPUSurfaceDescriptor; label = C_NULL, nextInChain = pointer_from_objref(Ref(partialInit( WGPUSurfaceDescriptorFromXlibWindow; chain = partialInit( WGPUChainedStruct; next = C_NULL, sType = WGPUSType_SurfaceDescriptorFromXlibWindow ), display = display, window = windowX11.handle ))) )) ) ) adapter = Ref(WGPUAdapter()) device = Ref(WGPUDevice()) adapterOptions = Ref(defaultInit(WGPURequestAdapterOptions)) function request_adapter_callback( a::WGPURequestAdapterStatus, b::WGPUAdapter, c::Ptr{Cchar}, d::Ptr{Nothing}) global adapter[] = b return nothing end requestAdapterCallback = @cfunction(request_adapter_callback, Cvoid, (WGPURequestAdapterStatus, WGPUAdapter, Ptr{Cchar}, Ptr{Cvoid})) ## device callback function request_device_callback( a::WGPURequestDeviceStatus, b::WGPUDevice, c::Ptr{Cchar}, d::Ptr{Nothing}) global device[] = b return nothing end requestDeviceCallback = @cfunction(request_device_callback, Cvoid, (WGPURequestDeviceStatus, WGPUDevice, Ptr{Cchar}, Ptr{Cvoid})) ## request adapter wgpuInstanceRequestAdapter(C_NULL, adapterOptions, requestAdapterCallback, adapter) ## chain = WGPUChainedStruct(C_NULL, WGPUSType(6)) deviceName = Vector{UInt8}("Device") deviceExtras = WGPUDeviceExtras(chain, defaultInit(WGPUNativeFeature), pointer(deviceName), C_NULL) const DEFAULT_ARRAY_SIZE = 256 wgpuLimits = partialInit(WGPULimits; maxBindGroups = 1) wgpuRequiredLimits = WGPURequiredLimits(C_NULL, wgpuLimits) wgpuQueueDescriptor = WGPUQueueDescriptor(C_NULL, C_NULL) wgpuDeviceDescriptor = Ref( partialInit( WGPUDeviceDescriptor, nextInChain = pointer_from_objref(Ref(partialInit(WGPUChainedStruct, chain=deviceExtras))), requiredLimits = pointer_from_objref(Ref(wgpuRequiredLimits)), defaultQueue = wgpuQueueDescriptor ) ) wgpuAdapterRequestDevice( adapter[], wgpuDeviceDescriptor, requestDeviceCallback, device[]) ## Device un captured callbacks ## Device lost callbacks ## ## b = read(pkgdir(WGPUNative)*"/examples/shader.wgsl") wgslDescriptor = WGPUShaderModuleWGSLDescriptor( defaultInit(WGPUChainedStruct), pointer(b) ) ## WGSL loading function load_wgsl(filename) b = read(filename) wgslDescriptor = Ref(WGPUShaderModuleWGSLDescriptor( defaultInit(WGPUChainedStruct), pointer(b) )) a = partialInit( WGPUShaderModuleDescriptor; nextInChain = pointer_from_objref(wgslDescriptor), label = pointer(Vector{UInt8}("$(filename)")) ) return (a, wgslDescriptor) end shaderSource = Ref(pkgdir(WGPUNative)*"/examples/triangle.wgsl")[1]) ## shader = wgpuDeviceCreateShaderModule( device[], pointer_from_objref(shaderSource) ) ## ## Pipeline Layout pipelineLayout = wgpuDeviceCreatePipelineLayout( device[], pointer_from_objref(Ref(partialInit( WGPUPipelineLayoutDescriptor; bindGroupLayouts = C_NULL, bindGroupLayoutCount = 0 ) ))) ## swapchains swapChainFormat = wgpuSurfaceGetPreferredFormat(surface, adapter[]) ## pipeline # # pipeline = wgpuDeviceCreateRenderPipeline( # device[], # pointer_from_objref(Ref(partialInit( # WGPURenderPipelineDescriptor; # label = pointer(Vector{UInt8}("Render pipeline")), # layout = pipelineLayout, # vertex = partialInit( # WGPUVertexState, # _module=shader, # entryPoint = pointer(Vector{UInt8}("vs_main")), # bufferCount = 0, # buffers = C_NULL # ), # primitive = partialInit( # WGPUPrimitiveState; # topology = WGPUPrimitiveTopology_TriangleList, # stripIndexFormat = WGPUIndexFormat_Undefined, # frontFace = WGPUFrontFace_CCW, # cullMode = WGPUCullMode_None), # multisample = partialInit( # WGPUMultisampleState; # count = 1, # mask = typemax(UInt32), # alphaToCoverageEnabled = false, # ), # fragment = pointer_from_objref(Ref(partialInit( # WGPUFragmentState; # _module = shader, # entryPoint = pointer(Vector{UInt8}("fs_main")), # targetCount = 1, # targets = pointer_from_objref(Ref(partialInit( # WGPUColorTargetState; # format=swapChainFormat, # blend = pointer_from_objref(Ref(partialInit( # WGPUBlendState; # color = partialInit( # WGPUBlendComponent; # srcFactor = WGPUBlendFactor_One, # dstFactor = WGPUBlendFactor_Zero, # operation = WGPUBlendOperation_Add, # ), # alpha = partialInit( # WGPUBlendComponent; # srcFactor = WGPUBlendFactor_One, # dstFactor = WGPUBlendFactor_Zero, # operation = WGPUBlendOperation_Add, # ), # ))), # writeMask = WGPUColorWriteMask_All))))), # ), # depthStencil = C_NULL, # )))) pipeline = wgpuDeviceCreateRenderPipeline( device[], pointer_from_objref(Ref(partialInit( WGPURenderPipelineDescriptor; label = pointer(Vector{UInt8}("Render pipeline")), layout = pipelineLayout, vertex = partialInit( WGPUVertexState, _module=shader, entryPoint = pointer(Vector{UInt8}("vs_main")), bufferCount = 0, buffers = C_NULL ), primitive = partialInit( WGPUPrimitiveState; topology = WGPUPrimitiveTopology_TriangleList, stripIndexFormat = WGPUIndexFormat_Undefined, frontFace = WGPUFrontFace_CCW, cullMode = WGPUCullMode_None), multisample = partialInit( WGPUMultisampleState; count = 1, mask = typemax(UInt32), alphaToCoverageEnabled = false, ), fragment = pointer([partialInit( WGPUFragmentState; _module = shader, entryPoint = pointer(Vector{UInt8}("fs_main")), targetCount = 1, targets = pointer([partialInit( WGPUColorTargetState; format=swapChainFormat, blend = pointer_from_objref(Ref(partialInit( WGPUBlendState; color = partialInit( WGPUBlendComponent; srcFactor = WGPUBlendFactor_One, dstFactor = WGPUBlendFactor_Zero, operation = WGPUBlendOperation_Add, ), alpha = partialInit( WGPUBlendComponent; srcFactor = WGPUBlendFactor_One, dstFactor = WGPUBlendFactor_Zero, operation = WGPUBlendOperation_Add, ), ))), writeMask = WGPUColorWriteMask_All)]) )]), depthStencil = C_NULL, ))) ) ## previos dims prevWidth = 0; prevHeight = 0; (prevWidth, prevHeight) = GLFW.GetWindowSize(window) swapChain = Ref(wgpuDeviceCreateSwapChain( device[], surface, pointer_from_objref(Ref(partialInit( WGPUSwapChainDescriptor; usage = WGPUTextureUsage_RenderAttachment, format = swapChainFormat, width = prevWidth, height = prevHeight, presentMode = WGPUPresentMode_Fifo, ))))) ## Window loop queue = Ref(C_NULL) encoder = Ref(C_NULL) renderPass = Ref(C_NULL) nextTexture = Ref(C_NULL) cmdBuffer = Ref(C_NULL) while !GLFW.WindowShouldClose(window) global encoder, renderPass, nextTexture for attempt in 0:2 global width = 0 global height = 0 (width, height) = GLFW.GetWindowSize(window) if (width != prevWidth) || (height != prevHeight) global prevWidth = width global prevHeight = height swapChain[] = wgpuDeviceCreateSwapChain( device[], surface, pointer_from_objref(Ref(partialInit( WGPUSwapChainDescriptor; usage = WGPUTextureUsage_RenderAttachment, format = swapChainFormat, width = prevWidth, height = prevHeight, presentMode = WGPUPresentMode_Fifo, )))) end nextTexture[] = wgpuSwapChainGetCurrentTextureView(swapChain[]); if attempt == 0 && nextTexture[] == C_NULL @error ("wgpuSwapChainGetCurrentTextureView() failed; Trying to create a new swap chain") prevWidth = 0 prevHeight = 0 continue end break end if nextTexture[] == C_NULL @error ("Cannot acquire next swap chain texture\n") exit(1) end encoder[] = wgpuDeviceCreateCommandEncoder( device[], pointer_from_objref(Ref(partialInit( WGPUCommandEncoderDescriptor; label = pointer(Vector{UInt8}("Command Encoder")) ) ))) renderPass[] = wgpuCommandEncoderBeginRenderPass( encoder[], pointer_from_objref(Ref(partialInit( WGPURenderPassDescriptor; colorAttachments = pointer_from_objref(Ref(partialInit( WGPURenderPassColorAttachment; view = nextTexture[], resolveTarget = 0, loadOp = WGPULoadOp_Clear, storeOp = WGPUStoreOp_Store, clearValue = WGPUColor(0.0, 1.0, 0.0, 1.0), ))), colorAttachmentCount = 1, depthStencilAttachment = C_NULL, )))) wgpuRenderPassEncoderSetPipeline(renderPass[], pipeline) wgpuRenderPassEncoderDraw(renderPass[], 3, 1, 0, 0) wgpuRenderPassEncoderEnd(renderPass[]) queue[] = wgpuDeviceGetQueue(device[]) cmdBuffer[] = wgpuCommandEncoderFinish( encoder[], pointer_from_objref(Ref(partialInit( WGPUCommandBufferDescriptor; label = C_NULL )))) wgpuQueueSubmit(queue[], 1, pointer_from_objref(cmdBuffer)) wgpuSwapChainPresent(swapChain[]) GLFW.PollEvents() end ## Destroy window GLFW.DestroyWindow(window) GLFW.Terminate()
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
2129
using Debugger using Downloads using Tar, Inflate, SHA arch = lowercase(String(Sys.ARCH)) kernel = lowercase(String(Sys.KERNEL)) # modifying conventions for wgpu specifically based on # releases at https://github.com/gfx-rs/wgpu-native/releases/tag/v0.12.0.1 version = "v0.1.4" kernels = ["macos", "linux", "windows"] archs = ["aarch64", "i686", "x86_64"] upstreamVersion = "v0.19.1.1" io = IOBuffer() function writeIO(io, arch, kernel, sha1, sha256, filename, url) write( io, """ [[WGPUNative]] arch = "$arch" git-tree-sha1 = "$sha1" os = "$kernel" [[WGPUNative.download]] sha256 = "$sha256" url = "$url" """ ) end remoteurl = "https://github.com/JuliaWGPU/WGPUNative.jl/releases/download/$(version)" function generateArtifacts() for kernel in kernels for arch in archs releasefile = "wgpu-$kernel-$arch-release.zip" tarfile = "WGPU.$(upstreamVersion).$(arch)-$(kernel).tar.gz" try url = "https://github.com/gfx-rs/wgpu-native/releases/download/$(upstreamVersion)/$releasefile" Downloads.download(url, releasefile) run(`rm -rf "wgpulibs$arch$kernel"`) run(`mkdir wgpulibs$arch$kernel`) run(`unzip $releasefile -d wgpulibs$arch$kernel`) run(`cd "wgpulibs$arch$kernel"`) run(`tar -C wgpulibs$arch$kernel -czvf $tarfile .`) run(`cd ".."`) catch(e) println("$e") end end end end function writeArtifactsTOML() for kernel in kernels for arch in archs releasefile = "wgpu-$kernel-$arch-release.zip" tarfile = "WGPU.$(upstreamVersion).$(arch)-$(kernel).tar.gz" try # Downloads.download(joinpath(remoteurl, tarfile), tarfile) sha256Val = bytes2hex(open(sha256, tarfile)) sha1Val = Tar.tree_hash(IOBuffer(inflate_gzip(tarfile))) writeIO(io, arch, kernel, sha1Val, sha256Val, "", joinpath(remoteurl, tarfile)) catch(e) println("$e") end end end seek(io, 0) f = open("Artifacts.toml", "w") write(f, io) close(f) end generateArtifacts() # TODO # publish artifacts as a release through github through github API # for now we could simply add input for confirmation of upload. writeArtifactsTOML()
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
817
using Clang.Generators arch = lowercase(String(Sys.ARCH)) kernel = lowercase(String(Sys.KERNEL)) if kernel == "darwin" kernel = "macos" if arch == "aarch64" arch = "aarch64" end end releasefile = "wgpu-$kernel-$arch-release.zip" location = "$releasefile" upstreamVersion = "v0.19.1.1" url = "https://github.com/gfx-rs/wgpu-native/releases/download/$(upstreamVersion)/wgpu-$kernel-$arch-release.zip" download(url, location) run(`rm -rf wgpulib`) run(`mkdir wgpulib`) run(`unzip $location -d wgpulib`) run(`rm $releasefile`) const C_HEADERS = ["wgpu.h",] const WGPU_HEADERS = [joinpath(@__DIR__, "wgpulib", h) for h in C_HEADERS] options = load_options(joinpath(@__DIR__, "generator.toml")) args = get_default_args() ctx = create_context(WGPU_HEADERS, args, options) build!(ctx) run(`rm -rf wgpulib`)
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
388
# SIZE_MAX needs verification const SIZE_MAX = 2^16 using Libdl using Pkg using Pkg.Artifacts artifact_toml = joinpath(@__DIR__, "..", "Artifacts.toml") wgpu_hash = artifact_hash("WGPUNative", artifact_toml) wgpulibpath = artifact_path(wgpu_hash) resourceName = Sys.iswindows() ? "wgpu_native" : "libwgpu_native" const libWGPU = "$wgpulibpath/$resourceName.$(Libdl.dlext)" |> normpath
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
112094
module LibWGPU using CEnum # SIZE_MAX needs verification const SIZE_MAX = 2^16 using Libdl using Pkg using Pkg.Artifacts artifact_toml = joinpath(@__DIR__, "..", "Artifacts.toml") wgpu_hash = artifact_hash("WGPUNative", artifact_toml) wgpulibpath = artifact_path(wgpu_hash) resourceName = Sys.iswindows() ? "wgpu_native" : "libwgpu_native" const libWGPU = "$wgpulibpath/$resourceName.$(Libdl.dlext)" |> normpath const WGPUFlags = UInt32 const WGPUBool = UInt32 mutable struct WGPUAdapterImpl end const WGPUAdapter = Ptr{WGPUAdapterImpl} mutable struct WGPUBindGroupImpl end const WGPUBindGroup = Ptr{WGPUBindGroupImpl} mutable struct WGPUBindGroupLayoutImpl end const WGPUBindGroupLayout = Ptr{WGPUBindGroupLayoutImpl} mutable struct WGPUBufferImpl end const WGPUBuffer = Ptr{WGPUBufferImpl} mutable struct WGPUCommandBufferImpl end const WGPUCommandBuffer = Ptr{WGPUCommandBufferImpl} mutable struct WGPUCommandEncoderImpl end const WGPUCommandEncoder = Ptr{WGPUCommandEncoderImpl} mutable struct WGPUComputePassEncoderImpl end const WGPUComputePassEncoder = Ptr{WGPUComputePassEncoderImpl} mutable struct WGPUComputePipelineImpl end const WGPUComputePipeline = Ptr{WGPUComputePipelineImpl} mutable struct WGPUDeviceImpl end const WGPUDevice = Ptr{WGPUDeviceImpl} mutable struct WGPUInstanceImpl end const WGPUInstance = Ptr{WGPUInstanceImpl} mutable struct WGPUPipelineLayoutImpl end const WGPUPipelineLayout = Ptr{WGPUPipelineLayoutImpl} mutable struct WGPUQuerySetImpl end const WGPUQuerySet = Ptr{WGPUQuerySetImpl} mutable struct WGPUQueueImpl end const WGPUQueue = Ptr{WGPUQueueImpl} mutable struct WGPURenderBundleImpl end const WGPURenderBundle = Ptr{WGPURenderBundleImpl} mutable struct WGPURenderBundleEncoderImpl end const WGPURenderBundleEncoder = Ptr{WGPURenderBundleEncoderImpl} mutable struct WGPURenderPassEncoderImpl end const WGPURenderPassEncoder = Ptr{WGPURenderPassEncoderImpl} mutable struct WGPURenderPipelineImpl end const WGPURenderPipeline = Ptr{WGPURenderPipelineImpl} mutable struct WGPUSamplerImpl end const WGPUSampler = Ptr{WGPUSamplerImpl} mutable struct WGPUShaderModuleImpl end const WGPUShaderModule = Ptr{WGPUShaderModuleImpl} mutable struct WGPUSurfaceImpl end const WGPUSurface = Ptr{WGPUSurfaceImpl} mutable struct WGPUTextureImpl end const WGPUTexture = Ptr{WGPUTextureImpl} mutable struct WGPUTextureViewImpl end const WGPUTextureView = Ptr{WGPUTextureViewImpl} @cenum WGPUAdapterType::UInt32 begin WGPUAdapterType_DiscreteGPU = 0 WGPUAdapterType_IntegratedGPU = 1 WGPUAdapterType_CPU = 2 WGPUAdapterType_Unknown = 3 WGPUAdapterType_Force32 = 2147483647 end @cenum WGPUAddressMode::UInt32 begin WGPUAddressMode_Repeat = 0 WGPUAddressMode_MirrorRepeat = 1 WGPUAddressMode_ClampToEdge = 2 WGPUAddressMode_Force32 = 2147483647 end @cenum WGPUBackendType::UInt32 begin WGPUBackendType_Undefined = 0 WGPUBackendType_Null = 1 WGPUBackendType_WebGPU = 2 WGPUBackendType_D3D11 = 3 WGPUBackendType_D3D12 = 4 WGPUBackendType_Metal = 5 WGPUBackendType_Vulkan = 6 WGPUBackendType_OpenGL = 7 WGPUBackendType_OpenGLES = 8 WGPUBackendType_Force32 = 2147483647 end @cenum WGPUBlendFactor::UInt32 begin WGPUBlendFactor_Zero = 0 WGPUBlendFactor_One = 1 WGPUBlendFactor_Src = 2 WGPUBlendFactor_OneMinusSrc = 3 WGPUBlendFactor_SrcAlpha = 4 WGPUBlendFactor_OneMinusSrcAlpha = 5 WGPUBlendFactor_Dst = 6 WGPUBlendFactor_OneMinusDst = 7 WGPUBlendFactor_DstAlpha = 8 WGPUBlendFactor_OneMinusDstAlpha = 9 WGPUBlendFactor_SrcAlphaSaturated = 10 WGPUBlendFactor_Constant = 11 WGPUBlendFactor_OneMinusConstant = 12 WGPUBlendFactor_Force32 = 2147483647 end @cenum WGPUBlendOperation::UInt32 begin WGPUBlendOperation_Add = 0 WGPUBlendOperation_Subtract = 1 WGPUBlendOperation_ReverseSubtract = 2 WGPUBlendOperation_Min = 3 WGPUBlendOperation_Max = 4 WGPUBlendOperation_Force32 = 2147483647 end @cenum WGPUBufferBindingType::UInt32 begin WGPUBufferBindingType_Undefined = 0 WGPUBufferBindingType_Uniform = 1 WGPUBufferBindingType_Storage = 2 WGPUBufferBindingType_ReadOnlyStorage = 3 WGPUBufferBindingType_Force32 = 2147483647 end @cenum WGPUBufferMapAsyncStatus::UInt32 begin WGPUBufferMapAsyncStatus_Success = 0 WGPUBufferMapAsyncStatus_ValidationError = 1 WGPUBufferMapAsyncStatus_Unknown = 2 WGPUBufferMapAsyncStatus_DeviceLost = 3 WGPUBufferMapAsyncStatus_DestroyedBeforeCallback = 4 WGPUBufferMapAsyncStatus_UnmappedBeforeCallback = 5 WGPUBufferMapAsyncStatus_MappingAlreadyPending = 6 WGPUBufferMapAsyncStatus_OffsetOutOfRange = 7 WGPUBufferMapAsyncStatus_SizeOutOfRange = 8 WGPUBufferMapAsyncStatus_Force32 = 2147483647 end @cenum WGPUBufferMapState::UInt32 begin WGPUBufferMapState_Unmapped = 0 WGPUBufferMapState_Pending = 1 WGPUBufferMapState_Mapped = 2 WGPUBufferMapState_Force32 = 2147483647 end @cenum WGPUCompareFunction::UInt32 begin WGPUCompareFunction_Undefined = 0 WGPUCompareFunction_Never = 1 WGPUCompareFunction_Less = 2 WGPUCompareFunction_LessEqual = 3 WGPUCompareFunction_Greater = 4 WGPUCompareFunction_GreaterEqual = 5 WGPUCompareFunction_Equal = 6 WGPUCompareFunction_NotEqual = 7 WGPUCompareFunction_Always = 8 WGPUCompareFunction_Force32 = 2147483647 end @cenum WGPUCompilationInfoRequestStatus::UInt32 begin WGPUCompilationInfoRequestStatus_Success = 0 WGPUCompilationInfoRequestStatus_Error = 1 WGPUCompilationInfoRequestStatus_DeviceLost = 2 WGPUCompilationInfoRequestStatus_Unknown = 3 WGPUCompilationInfoRequestStatus_Force32 = 2147483647 end @cenum WGPUCompilationMessageType::UInt32 begin WGPUCompilationMessageType_Error = 0 WGPUCompilationMessageType_Warning = 1 WGPUCompilationMessageType_Info = 2 WGPUCompilationMessageType_Force32 = 2147483647 end @cenum WGPUCompositeAlphaMode::UInt32 begin WGPUCompositeAlphaMode_Auto = 0 WGPUCompositeAlphaMode_Opaque = 1 WGPUCompositeAlphaMode_Premultiplied = 2 WGPUCompositeAlphaMode_Unpremultiplied = 3 WGPUCompositeAlphaMode_Inherit = 4 WGPUCompositeAlphaMode_Force32 = 2147483647 end @cenum WGPUCreatePipelineAsyncStatus::UInt32 begin WGPUCreatePipelineAsyncStatus_Success = 0 WGPUCreatePipelineAsyncStatus_ValidationError = 1 WGPUCreatePipelineAsyncStatus_InternalError = 2 WGPUCreatePipelineAsyncStatus_DeviceLost = 3 WGPUCreatePipelineAsyncStatus_DeviceDestroyed = 4 WGPUCreatePipelineAsyncStatus_Unknown = 5 WGPUCreatePipelineAsyncStatus_Force32 = 2147483647 end @cenum WGPUCullMode::UInt32 begin WGPUCullMode_None = 0 WGPUCullMode_Front = 1 WGPUCullMode_Back = 2 WGPUCullMode_Force32 = 2147483647 end @cenum WGPUDeviceLostReason::UInt32 begin WGPUDeviceLostReason_Undefined = 0 WGPUDeviceLostReason_Destroyed = 1 WGPUDeviceLostReason_Force32 = 2147483647 end @cenum WGPUErrorFilter::UInt32 begin WGPUErrorFilter_Validation = 0 WGPUErrorFilter_OutOfMemory = 1 WGPUErrorFilter_Internal = 2 WGPUErrorFilter_Force32 = 2147483647 end @cenum WGPUErrorType::UInt32 begin WGPUErrorType_NoError = 0 WGPUErrorType_Validation = 1 WGPUErrorType_OutOfMemory = 2 WGPUErrorType_Internal = 3 WGPUErrorType_Unknown = 4 WGPUErrorType_DeviceLost = 5 WGPUErrorType_Force32 = 2147483647 end @cenum WGPUFeatureName::UInt32 begin WGPUFeatureName_Undefined = 0 WGPUFeatureName_DepthClipControl = 1 WGPUFeatureName_Depth32FloatStencil8 = 2 WGPUFeatureName_TimestampQuery = 3 WGPUFeatureName_TextureCompressionBC = 4 WGPUFeatureName_TextureCompressionETC2 = 5 WGPUFeatureName_TextureCompressionASTC = 6 WGPUFeatureName_IndirectFirstInstance = 7 WGPUFeatureName_ShaderF16 = 8 WGPUFeatureName_RG11B10UfloatRenderable = 9 WGPUFeatureName_BGRA8UnormStorage = 10 WGPUFeatureName_Float32Filterable = 11 WGPUFeatureName_Force32 = 2147483647 end @cenum WGPUFilterMode::UInt32 begin WGPUFilterMode_Nearest = 0 WGPUFilterMode_Linear = 1 WGPUFilterMode_Force32 = 2147483647 end @cenum WGPUFrontFace::UInt32 begin WGPUFrontFace_CCW = 0 WGPUFrontFace_CW = 1 WGPUFrontFace_Force32 = 2147483647 end @cenum WGPUIndexFormat::UInt32 begin WGPUIndexFormat_Undefined = 0 WGPUIndexFormat_Uint16 = 1 WGPUIndexFormat_Uint32 = 2 WGPUIndexFormat_Force32 = 2147483647 end @cenum WGPULoadOp::UInt32 begin WGPULoadOp_Undefined = 0 WGPULoadOp_Clear = 1 WGPULoadOp_Load = 2 WGPULoadOp_Force32 = 2147483647 end @cenum WGPUMipmapFilterMode::UInt32 begin WGPUMipmapFilterMode_Nearest = 0 WGPUMipmapFilterMode_Linear = 1 WGPUMipmapFilterMode_Force32 = 2147483647 end @cenum WGPUPowerPreference::UInt32 begin WGPUPowerPreference_Undefined = 0 WGPUPowerPreference_LowPower = 1 WGPUPowerPreference_HighPerformance = 2 WGPUPowerPreference_Force32 = 2147483647 end @cenum WGPUPresentMode::UInt32 begin WGPUPresentMode_Fifo = 0 WGPUPresentMode_FifoRelaxed = 1 WGPUPresentMode_Immediate = 2 WGPUPresentMode_Mailbox = 3 WGPUPresentMode_Force32 = 2147483647 end @cenum WGPUPrimitiveTopology::UInt32 begin WGPUPrimitiveTopology_PointList = 0 WGPUPrimitiveTopology_LineList = 1 WGPUPrimitiveTopology_LineStrip = 2 WGPUPrimitiveTopology_TriangleList = 3 WGPUPrimitiveTopology_TriangleStrip = 4 WGPUPrimitiveTopology_Force32 = 2147483647 end @cenum WGPUQueryType::UInt32 begin WGPUQueryType_Occlusion = 0 WGPUQueryType_Timestamp = 1 WGPUQueryType_Force32 = 2147483647 end @cenum WGPUQueueWorkDoneStatus::UInt32 begin WGPUQueueWorkDoneStatus_Success = 0 WGPUQueueWorkDoneStatus_Error = 1 WGPUQueueWorkDoneStatus_Unknown = 2 WGPUQueueWorkDoneStatus_DeviceLost = 3 WGPUQueueWorkDoneStatus_Force32 = 2147483647 end @cenum WGPURequestAdapterStatus::UInt32 begin WGPURequestAdapterStatus_Success = 0 WGPURequestAdapterStatus_Unavailable = 1 WGPURequestAdapterStatus_Error = 2 WGPURequestAdapterStatus_Unknown = 3 WGPURequestAdapterStatus_Force32 = 2147483647 end @cenum WGPURequestDeviceStatus::UInt32 begin WGPURequestDeviceStatus_Success = 0 WGPURequestDeviceStatus_Error = 1 WGPURequestDeviceStatus_Unknown = 2 WGPURequestDeviceStatus_Force32 = 2147483647 end @cenum WGPUSType::UInt32 begin WGPUSType_Invalid = 0 WGPUSType_SurfaceDescriptorFromMetalLayer = 1 WGPUSType_SurfaceDescriptorFromWindowsHWND = 2 WGPUSType_SurfaceDescriptorFromXlibWindow = 3 WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector = 4 WGPUSType_ShaderModuleSPIRVDescriptor = 5 WGPUSType_ShaderModuleWGSLDescriptor = 6 WGPUSType_PrimitiveDepthClipControl = 7 WGPUSType_SurfaceDescriptorFromWaylandSurface = 8 WGPUSType_SurfaceDescriptorFromAndroidNativeWindow = 9 WGPUSType_SurfaceDescriptorFromXcbWindow = 10 WGPUSType_RenderPassDescriptorMaxDrawCount = 15 WGPUSType_Force32 = 2147483647 end @cenum WGPUSamplerBindingType::UInt32 begin WGPUSamplerBindingType_Undefined = 0 WGPUSamplerBindingType_Filtering = 1 WGPUSamplerBindingType_NonFiltering = 2 WGPUSamplerBindingType_Comparison = 3 WGPUSamplerBindingType_Force32 = 2147483647 end @cenum WGPUStencilOperation::UInt32 begin WGPUStencilOperation_Keep = 0 WGPUStencilOperation_Zero = 1 WGPUStencilOperation_Replace = 2 WGPUStencilOperation_Invert = 3 WGPUStencilOperation_IncrementClamp = 4 WGPUStencilOperation_DecrementClamp = 5 WGPUStencilOperation_IncrementWrap = 6 WGPUStencilOperation_DecrementWrap = 7 WGPUStencilOperation_Force32 = 2147483647 end @cenum WGPUStorageTextureAccess::UInt32 begin WGPUStorageTextureAccess_Undefined = 0 WGPUStorageTextureAccess_WriteOnly = 1 WGPUStorageTextureAccess_ReadOnly = 2 WGPUStorageTextureAccess_ReadWrite = 3 WGPUStorageTextureAccess_Force32 = 2147483647 end @cenum WGPUStoreOp::UInt32 begin WGPUStoreOp_Undefined = 0 WGPUStoreOp_Store = 1 WGPUStoreOp_Discard = 2 WGPUStoreOp_Force32 = 2147483647 end @cenum WGPUSurfaceGetCurrentTextureStatus::UInt32 begin WGPUSurfaceGetCurrentTextureStatus_Success = 0 WGPUSurfaceGetCurrentTextureStatus_Timeout = 1 WGPUSurfaceGetCurrentTextureStatus_Outdated = 2 WGPUSurfaceGetCurrentTextureStatus_Lost = 3 WGPUSurfaceGetCurrentTextureStatus_OutOfMemory = 4 WGPUSurfaceGetCurrentTextureStatus_DeviceLost = 5 WGPUSurfaceGetCurrentTextureStatus_Force32 = 2147483647 end @cenum WGPUTextureAspect::UInt32 begin WGPUTextureAspect_All = 0 WGPUTextureAspect_StencilOnly = 1 WGPUTextureAspect_DepthOnly = 2 WGPUTextureAspect_Force32 = 2147483647 end @cenum WGPUTextureDimension::UInt32 begin WGPUTextureDimension_1D = 0 WGPUTextureDimension_2D = 1 WGPUTextureDimension_3D = 2 WGPUTextureDimension_Force32 = 2147483647 end @cenum WGPUTextureFormat::UInt32 begin WGPUTextureFormat_Undefined = 0 WGPUTextureFormat_R8Unorm = 1 WGPUTextureFormat_R8Snorm = 2 WGPUTextureFormat_R8Uint = 3 WGPUTextureFormat_R8Sint = 4 WGPUTextureFormat_R16Uint = 5 WGPUTextureFormat_R16Sint = 6 WGPUTextureFormat_R16Float = 7 WGPUTextureFormat_RG8Unorm = 8 WGPUTextureFormat_RG8Snorm = 9 WGPUTextureFormat_RG8Uint = 10 WGPUTextureFormat_RG8Sint = 11 WGPUTextureFormat_R32Float = 12 WGPUTextureFormat_R32Uint = 13 WGPUTextureFormat_R32Sint = 14 WGPUTextureFormat_RG16Uint = 15 WGPUTextureFormat_RG16Sint = 16 WGPUTextureFormat_RG16Float = 17 WGPUTextureFormat_RGBA8Unorm = 18 WGPUTextureFormat_RGBA8UnormSrgb = 19 WGPUTextureFormat_RGBA8Snorm = 20 WGPUTextureFormat_RGBA8Uint = 21 WGPUTextureFormat_RGBA8Sint = 22 WGPUTextureFormat_BGRA8Unorm = 23 WGPUTextureFormat_BGRA8UnormSrgb = 24 WGPUTextureFormat_RGB10A2Uint = 25 WGPUTextureFormat_RGB10A2Unorm = 26 WGPUTextureFormat_RG11B10Ufloat = 27 WGPUTextureFormat_RGB9E5Ufloat = 28 WGPUTextureFormat_RG32Float = 29 WGPUTextureFormat_RG32Uint = 30 WGPUTextureFormat_RG32Sint = 31 WGPUTextureFormat_RGBA16Uint = 32 WGPUTextureFormat_RGBA16Sint = 33 WGPUTextureFormat_RGBA16Float = 34 WGPUTextureFormat_RGBA32Float = 35 WGPUTextureFormat_RGBA32Uint = 36 WGPUTextureFormat_RGBA32Sint = 37 WGPUTextureFormat_Stencil8 = 38 WGPUTextureFormat_Depth16Unorm = 39 WGPUTextureFormat_Depth24Plus = 40 WGPUTextureFormat_Depth24PlusStencil8 = 41 WGPUTextureFormat_Depth32Float = 42 WGPUTextureFormat_Depth32FloatStencil8 = 43 WGPUTextureFormat_BC1RGBAUnorm = 44 WGPUTextureFormat_BC1RGBAUnormSrgb = 45 WGPUTextureFormat_BC2RGBAUnorm = 46 WGPUTextureFormat_BC2RGBAUnormSrgb = 47 WGPUTextureFormat_BC3RGBAUnorm = 48 WGPUTextureFormat_BC3RGBAUnormSrgb = 49 WGPUTextureFormat_BC4RUnorm = 50 WGPUTextureFormat_BC4RSnorm = 51 WGPUTextureFormat_BC5RGUnorm = 52 WGPUTextureFormat_BC5RGSnorm = 53 WGPUTextureFormat_BC6HRGBUfloat = 54 WGPUTextureFormat_BC6HRGBFloat = 55 WGPUTextureFormat_BC7RGBAUnorm = 56 WGPUTextureFormat_BC7RGBAUnormSrgb = 57 WGPUTextureFormat_ETC2RGB8Unorm = 58 WGPUTextureFormat_ETC2RGB8UnormSrgb = 59 WGPUTextureFormat_ETC2RGB8A1Unorm = 60 WGPUTextureFormat_ETC2RGB8A1UnormSrgb = 61 WGPUTextureFormat_ETC2RGBA8Unorm = 62 WGPUTextureFormat_ETC2RGBA8UnormSrgb = 63 WGPUTextureFormat_EACR11Unorm = 64 WGPUTextureFormat_EACR11Snorm = 65 WGPUTextureFormat_EACRG11Unorm = 66 WGPUTextureFormat_EACRG11Snorm = 67 WGPUTextureFormat_ASTC4x4Unorm = 68 WGPUTextureFormat_ASTC4x4UnormSrgb = 69 WGPUTextureFormat_ASTC5x4Unorm = 70 WGPUTextureFormat_ASTC5x4UnormSrgb = 71 WGPUTextureFormat_ASTC5x5Unorm = 72 WGPUTextureFormat_ASTC5x5UnormSrgb = 73 WGPUTextureFormat_ASTC6x5Unorm = 74 WGPUTextureFormat_ASTC6x5UnormSrgb = 75 WGPUTextureFormat_ASTC6x6Unorm = 76 WGPUTextureFormat_ASTC6x6UnormSrgb = 77 WGPUTextureFormat_ASTC8x5Unorm = 78 WGPUTextureFormat_ASTC8x5UnormSrgb = 79 WGPUTextureFormat_ASTC8x6Unorm = 80 WGPUTextureFormat_ASTC8x6UnormSrgb = 81 WGPUTextureFormat_ASTC8x8Unorm = 82 WGPUTextureFormat_ASTC8x8UnormSrgb = 83 WGPUTextureFormat_ASTC10x5Unorm = 84 WGPUTextureFormat_ASTC10x5UnormSrgb = 85 WGPUTextureFormat_ASTC10x6Unorm = 86 WGPUTextureFormat_ASTC10x6UnormSrgb = 87 WGPUTextureFormat_ASTC10x8Unorm = 88 WGPUTextureFormat_ASTC10x8UnormSrgb = 89 WGPUTextureFormat_ASTC10x10Unorm = 90 WGPUTextureFormat_ASTC10x10UnormSrgb = 91 WGPUTextureFormat_ASTC12x10Unorm = 92 WGPUTextureFormat_ASTC12x10UnormSrgb = 93 WGPUTextureFormat_ASTC12x12Unorm = 94 WGPUTextureFormat_ASTC12x12UnormSrgb = 95 WGPUTextureFormat_Force32 = 2147483647 end @cenum WGPUTextureSampleType::UInt32 begin WGPUTextureSampleType_Undefined = 0 WGPUTextureSampleType_Float = 1 WGPUTextureSampleType_UnfilterableFloat = 2 WGPUTextureSampleType_Depth = 3 WGPUTextureSampleType_Sint = 4 WGPUTextureSampleType_Uint = 5 WGPUTextureSampleType_Force32 = 2147483647 end @cenum WGPUTextureViewDimension::UInt32 begin WGPUTextureViewDimension_Undefined = 0 WGPUTextureViewDimension_1D = 1 WGPUTextureViewDimension_2D = 2 WGPUTextureViewDimension_2DArray = 3 WGPUTextureViewDimension_Cube = 4 WGPUTextureViewDimension_CubeArray = 5 WGPUTextureViewDimension_3D = 6 WGPUTextureViewDimension_Force32 = 2147483647 end @cenum WGPUVertexFormat::UInt32 begin WGPUVertexFormat_Undefined = 0 WGPUVertexFormat_Uint8x2 = 1 WGPUVertexFormat_Uint8x4 = 2 WGPUVertexFormat_Sint8x2 = 3 WGPUVertexFormat_Sint8x4 = 4 WGPUVertexFormat_Unorm8x2 = 5 WGPUVertexFormat_Unorm8x4 = 6 WGPUVertexFormat_Snorm8x2 = 7 WGPUVertexFormat_Snorm8x4 = 8 WGPUVertexFormat_Uint16x2 = 9 WGPUVertexFormat_Uint16x4 = 10 WGPUVertexFormat_Sint16x2 = 11 WGPUVertexFormat_Sint16x4 = 12 WGPUVertexFormat_Unorm16x2 = 13 WGPUVertexFormat_Unorm16x4 = 14 WGPUVertexFormat_Snorm16x2 = 15 WGPUVertexFormat_Snorm16x4 = 16 WGPUVertexFormat_Float16x2 = 17 WGPUVertexFormat_Float16x4 = 18 WGPUVertexFormat_Float32 = 19 WGPUVertexFormat_Float32x2 = 20 WGPUVertexFormat_Float32x3 = 21 WGPUVertexFormat_Float32x4 = 22 WGPUVertexFormat_Uint32 = 23 WGPUVertexFormat_Uint32x2 = 24 WGPUVertexFormat_Uint32x3 = 25 WGPUVertexFormat_Uint32x4 = 26 WGPUVertexFormat_Sint32 = 27 WGPUVertexFormat_Sint32x2 = 28 WGPUVertexFormat_Sint32x3 = 29 WGPUVertexFormat_Sint32x4 = 30 WGPUVertexFormat_Force32 = 2147483647 end @cenum WGPUVertexStepMode::UInt32 begin WGPUVertexStepMode_Vertex = 0 WGPUVertexStepMode_Instance = 1 WGPUVertexStepMode_VertexBufferNotUsed = 2 WGPUVertexStepMode_Force32 = 2147483647 end @cenum WGPUBufferUsage::UInt32 begin WGPUBufferUsage_None = 0 WGPUBufferUsage_MapRead = 1 WGPUBufferUsage_MapWrite = 2 WGPUBufferUsage_CopySrc = 4 WGPUBufferUsage_CopyDst = 8 WGPUBufferUsage_Index = 16 WGPUBufferUsage_Vertex = 32 WGPUBufferUsage_Uniform = 64 WGPUBufferUsage_Storage = 128 WGPUBufferUsage_Indirect = 256 WGPUBufferUsage_QueryResolve = 512 WGPUBufferUsage_Force32 = 2147483647 end const WGPUBufferUsageFlags = WGPUFlags @cenum WGPUColorWriteMask::UInt32 begin WGPUColorWriteMask_None = 0 WGPUColorWriteMask_Red = 1 WGPUColorWriteMask_Green = 2 WGPUColorWriteMask_Blue = 4 WGPUColorWriteMask_Alpha = 8 WGPUColorWriteMask_All = 15 WGPUColorWriteMask_Force32 = 2147483647 end const WGPUColorWriteMaskFlags = WGPUFlags @cenum WGPUMapMode::UInt32 begin WGPUMapMode_None = 0 WGPUMapMode_Read = 1 WGPUMapMode_Write = 2 WGPUMapMode_Force32 = 2147483647 end const WGPUMapModeFlags = WGPUFlags @cenum WGPUShaderStage::UInt32 begin WGPUShaderStage_None = 0 WGPUShaderStage_Vertex = 1 WGPUShaderStage_Fragment = 2 WGPUShaderStage_Compute = 4 WGPUShaderStage_Force32 = 2147483647 end const WGPUShaderStageFlags = WGPUFlags @cenum WGPUTextureUsage::UInt32 begin WGPUTextureUsage_None = 0 WGPUTextureUsage_CopySrc = 1 WGPUTextureUsage_CopyDst = 2 WGPUTextureUsage_TextureBinding = 4 WGPUTextureUsage_StorageBinding = 8 WGPUTextureUsage_RenderAttachment = 16 WGPUTextureUsage_Force32 = 2147483647 end const WGPUTextureUsageFlags = WGPUFlags # typedef void ( * WGPUBufferMapCallback ) ( WGPUBufferMapAsyncStatus status , void * userdata ) const WGPUBufferMapCallback = Ptr{Cvoid} # typedef void ( * WGPUCompilationInfoCallback ) ( WGPUCompilationInfoRequestStatus status , struct WGPUCompilationInfo const * compilationInfo , void * userdata ) const WGPUCompilationInfoCallback = Ptr{Cvoid} # typedef void ( * WGPUCreateComputePipelineAsyncCallback ) ( WGPUCreatePipelineAsyncStatus status , WGPUComputePipeline pipeline , char const * message , void * userdata ) const WGPUCreateComputePipelineAsyncCallback = Ptr{Cvoid} # typedef void ( * WGPUCreateRenderPipelineAsyncCallback ) ( WGPUCreatePipelineAsyncStatus status , WGPURenderPipeline pipeline , char const * message , void * userdata ) const WGPUCreateRenderPipelineAsyncCallback = Ptr{Cvoid} # typedef void ( * WGPUDeviceLostCallback ) ( WGPUDeviceLostReason reason , char const * message , void * userdata ) const WGPUDeviceLostCallback = Ptr{Cvoid} # typedef void ( * WGPUErrorCallback ) ( WGPUErrorType type , char const * message , void * userdata ) const WGPUErrorCallback = Ptr{Cvoid} # typedef void ( * WGPUProc ) ( void ) const WGPUProc = Ptr{Cvoid} # typedef void ( * WGPUQueueWorkDoneCallback ) ( WGPUQueueWorkDoneStatus status , void * userdata ) const WGPUQueueWorkDoneCallback = Ptr{Cvoid} # typedef void ( * WGPURequestAdapterCallback ) ( WGPURequestAdapterStatus status , WGPUAdapter adapter , char const * message , void * userdata ) const WGPURequestAdapterCallback = Ptr{Cvoid} # typedef void ( * WGPURequestDeviceCallback ) ( WGPURequestDeviceStatus status , WGPUDevice device , char const * message , void * userdata ) const WGPURequestDeviceCallback = Ptr{Cvoid} struct WGPUChainedStruct next::Ptr{WGPUChainedStruct} sType::WGPUSType end struct WGPUChainedStructOut next::Ptr{WGPUChainedStructOut} sType::WGPUSType end struct WGPUAdapterProperties nextInChain::Ptr{WGPUChainedStructOut} vendorID::UInt32 vendorName::Ptr{Cchar} architecture::Ptr{Cchar} deviceID::UInt32 name::Ptr{Cchar} driverDescription::Ptr{Cchar} adapterType::WGPUAdapterType backendType::WGPUBackendType end struct WGPUBindGroupEntry nextInChain::Ptr{WGPUChainedStruct} binding::UInt32 buffer::WGPUBuffer offset::UInt64 size::UInt64 sampler::WGPUSampler textureView::WGPUTextureView end struct WGPUBlendComponent operation::WGPUBlendOperation srcFactor::WGPUBlendFactor dstFactor::WGPUBlendFactor end struct WGPUBufferBindingLayout nextInChain::Ptr{WGPUChainedStruct} type::WGPUBufferBindingType hasDynamicOffset::WGPUBool minBindingSize::UInt64 end struct WGPUBufferDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} usage::WGPUBufferUsageFlags size::UInt64 mappedAtCreation::WGPUBool end struct WGPUColor r::Cdouble g::Cdouble b::Cdouble a::Cdouble end struct WGPUCommandBufferDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} end struct WGPUCommandEncoderDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} end struct WGPUCompilationMessage nextInChain::Ptr{WGPUChainedStruct} message::Ptr{Cchar} type::WGPUCompilationMessageType lineNum::UInt64 linePos::UInt64 offset::UInt64 length::UInt64 utf16LinePos::UInt64 utf16Offset::UInt64 utf16Length::UInt64 end struct WGPUComputePassTimestampWrites querySet::WGPUQuerySet beginningOfPassWriteIndex::UInt32 endOfPassWriteIndex::UInt32 end struct WGPUConstantEntry nextInChain::Ptr{WGPUChainedStruct} key::Ptr{Cchar} value::Cdouble end struct WGPUExtent3D width::UInt32 height::UInt32 depthOrArrayLayers::UInt32 end struct WGPUInstanceDescriptor nextInChain::Ptr{WGPUChainedStruct} end struct WGPULimits maxTextureDimension1D::UInt32 maxTextureDimension2D::UInt32 maxTextureDimension3D::UInt32 maxTextureArrayLayers::UInt32 maxBindGroups::UInt32 maxBindGroupsPlusVertexBuffers::UInt32 maxBindingsPerBindGroup::UInt32 maxDynamicUniformBuffersPerPipelineLayout::UInt32 maxDynamicStorageBuffersPerPipelineLayout::UInt32 maxSampledTexturesPerShaderStage::UInt32 maxSamplersPerShaderStage::UInt32 maxStorageBuffersPerShaderStage::UInt32 maxStorageTexturesPerShaderStage::UInt32 maxUniformBuffersPerShaderStage::UInt32 maxUniformBufferBindingSize::UInt64 maxStorageBufferBindingSize::UInt64 minUniformBufferOffsetAlignment::UInt32 minStorageBufferOffsetAlignment::UInt32 maxVertexBuffers::UInt32 maxBufferSize::UInt64 maxVertexAttributes::UInt32 maxVertexBufferArrayStride::UInt32 maxInterStageShaderComponents::UInt32 maxInterStageShaderVariables::UInt32 maxColorAttachments::UInt32 maxColorAttachmentBytesPerSample::UInt32 maxComputeWorkgroupStorageSize::UInt32 maxComputeInvocationsPerWorkgroup::UInt32 maxComputeWorkgroupSizeX::UInt32 maxComputeWorkgroupSizeY::UInt32 maxComputeWorkgroupSizeZ::UInt32 maxComputeWorkgroupsPerDimension::UInt32 end struct WGPUMultisampleState nextInChain::Ptr{WGPUChainedStruct} count::UInt32 mask::UInt32 alphaToCoverageEnabled::WGPUBool end struct WGPUOrigin3D x::UInt32 y::UInt32 z::UInt32 end struct WGPUPipelineLayoutDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} bindGroupLayoutCount::Csize_t bindGroupLayouts::Ptr{WGPUBindGroupLayout} end struct WGPUPrimitiveDepthClipControl chain::WGPUChainedStruct unclippedDepth::WGPUBool end struct WGPUPrimitiveState nextInChain::Ptr{WGPUChainedStruct} topology::WGPUPrimitiveTopology stripIndexFormat::WGPUIndexFormat frontFace::WGPUFrontFace cullMode::WGPUCullMode end struct WGPUQuerySetDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} type::WGPUQueryType count::UInt32 end struct WGPUQueueDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} end struct WGPURenderBundleDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} end struct WGPURenderBundleEncoderDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} colorFormatCount::Csize_t colorFormats::Ptr{WGPUTextureFormat} depthStencilFormat::WGPUTextureFormat sampleCount::UInt32 depthReadOnly::WGPUBool stencilReadOnly::WGPUBool end struct WGPURenderPassDepthStencilAttachment view::WGPUTextureView depthLoadOp::WGPULoadOp depthStoreOp::WGPUStoreOp depthClearValue::Cfloat depthReadOnly::WGPUBool stencilLoadOp::WGPULoadOp stencilStoreOp::WGPUStoreOp stencilClearValue::UInt32 stencilReadOnly::WGPUBool end struct WGPURenderPassDescriptorMaxDrawCount chain::WGPUChainedStruct maxDrawCount::UInt64 end struct WGPURenderPassTimestampWrites querySet::WGPUQuerySet beginningOfPassWriteIndex::UInt32 endOfPassWriteIndex::UInt32 end struct WGPURequestAdapterOptions nextInChain::Ptr{WGPUChainedStruct} compatibleSurface::WGPUSurface powerPreference::WGPUPowerPreference backendType::WGPUBackendType forceFallbackAdapter::WGPUBool end struct WGPUSamplerBindingLayout nextInChain::Ptr{WGPUChainedStruct} type::WGPUSamplerBindingType end struct WGPUSamplerDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} addressModeU::WGPUAddressMode addressModeV::WGPUAddressMode addressModeW::WGPUAddressMode magFilter::WGPUFilterMode minFilter::WGPUFilterMode mipmapFilter::WGPUMipmapFilterMode lodMinClamp::Cfloat lodMaxClamp::Cfloat compare::WGPUCompareFunction maxAnisotropy::UInt16 end struct WGPUShaderModuleCompilationHint nextInChain::Ptr{WGPUChainedStruct} entryPoint::Ptr{Cchar} layout::WGPUPipelineLayout end struct WGPUShaderModuleSPIRVDescriptor chain::WGPUChainedStruct codeSize::UInt32 code::Ptr{UInt32} end struct WGPUShaderModuleWGSLDescriptor chain::WGPUChainedStruct code::Ptr{Cchar} end struct WGPUStencilFaceState compare::WGPUCompareFunction failOp::WGPUStencilOperation depthFailOp::WGPUStencilOperation passOp::WGPUStencilOperation end struct WGPUStorageTextureBindingLayout nextInChain::Ptr{WGPUChainedStruct} access::WGPUStorageTextureAccess format::WGPUTextureFormat viewDimension::WGPUTextureViewDimension end struct WGPUSurfaceCapabilities nextInChain::Ptr{WGPUChainedStructOut} formatCount::Csize_t formats::Ptr{WGPUTextureFormat} presentModeCount::Csize_t presentModes::Ptr{WGPUPresentMode} alphaModeCount::Csize_t alphaModes::Ptr{WGPUCompositeAlphaMode} end struct WGPUSurfaceConfiguration nextInChain::Ptr{WGPUChainedStruct} device::WGPUDevice format::WGPUTextureFormat usage::WGPUTextureUsageFlags viewFormatCount::Csize_t viewFormats::Ptr{WGPUTextureFormat} alphaMode::WGPUCompositeAlphaMode width::UInt32 height::UInt32 presentMode::WGPUPresentMode end struct WGPUSurfaceDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} end struct WGPUSurfaceDescriptorFromAndroidNativeWindow chain::WGPUChainedStruct window::Ptr{Cvoid} end struct WGPUSurfaceDescriptorFromCanvasHTMLSelector chain::WGPUChainedStruct selector::Ptr{Cchar} end struct WGPUSurfaceDescriptorFromMetalLayer chain::WGPUChainedStruct layer::Ptr{Cvoid} end struct WGPUSurfaceDescriptorFromWaylandSurface chain::WGPUChainedStruct display::Ptr{Cvoid} surface::Ptr{Cvoid} end struct WGPUSurfaceDescriptorFromWindowsHWND chain::WGPUChainedStruct hinstance::Ptr{Cvoid} hwnd::Ptr{Cvoid} end struct WGPUSurfaceDescriptorFromXcbWindow chain::WGPUChainedStruct connection::Ptr{Cvoid} window::UInt32 end struct WGPUSurfaceDescriptorFromXlibWindow chain::WGPUChainedStruct display::Ptr{Cvoid} window::UInt64 end struct WGPUSurfaceTexture texture::WGPUTexture suboptimal::WGPUBool status::WGPUSurfaceGetCurrentTextureStatus end struct WGPUTextureBindingLayout nextInChain::Ptr{WGPUChainedStruct} sampleType::WGPUTextureSampleType viewDimension::WGPUTextureViewDimension multisampled::WGPUBool end struct WGPUTextureDataLayout nextInChain::Ptr{WGPUChainedStruct} offset::UInt64 bytesPerRow::UInt32 rowsPerImage::UInt32 end struct WGPUTextureViewDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} format::WGPUTextureFormat dimension::WGPUTextureViewDimension baseMipLevel::UInt32 mipLevelCount::UInt32 baseArrayLayer::UInt32 arrayLayerCount::UInt32 aspect::WGPUTextureAspect end struct WGPUVertexAttribute format::WGPUVertexFormat offset::UInt64 shaderLocation::UInt32 end struct WGPUBindGroupDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} layout::WGPUBindGroupLayout entryCount::Csize_t entries::Ptr{WGPUBindGroupEntry} end struct WGPUBindGroupLayoutEntry nextInChain::Ptr{WGPUChainedStruct} binding::UInt32 visibility::WGPUShaderStageFlags buffer::WGPUBufferBindingLayout sampler::WGPUSamplerBindingLayout texture::WGPUTextureBindingLayout storageTexture::WGPUStorageTextureBindingLayout end struct WGPUBlendState color::WGPUBlendComponent alpha::WGPUBlendComponent end struct WGPUCompilationInfo nextInChain::Ptr{WGPUChainedStruct} messageCount::Csize_t messages::Ptr{WGPUCompilationMessage} end struct WGPUComputePassDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} timestampWrites::Ptr{WGPUComputePassTimestampWrites} end struct WGPUDepthStencilState nextInChain::Ptr{WGPUChainedStruct} format::WGPUTextureFormat depthWriteEnabled::WGPUBool depthCompare::WGPUCompareFunction stencilFront::WGPUStencilFaceState stencilBack::WGPUStencilFaceState stencilReadMask::UInt32 stencilWriteMask::UInt32 depthBias::Int32 depthBiasSlopeScale::Cfloat depthBiasClamp::Cfloat end struct WGPUImageCopyBuffer nextInChain::Ptr{WGPUChainedStruct} layout::WGPUTextureDataLayout buffer::WGPUBuffer end struct WGPUImageCopyTexture nextInChain::Ptr{WGPUChainedStruct} texture::WGPUTexture mipLevel::UInt32 origin::WGPUOrigin3D aspect::WGPUTextureAspect end struct WGPUProgrammableStageDescriptor nextInChain::Ptr{WGPUChainedStruct} _module::WGPUShaderModule entryPoint::Ptr{Cchar} constantCount::Csize_t constants::Ptr{WGPUConstantEntry} end struct WGPURenderPassColorAttachment nextInChain::Ptr{WGPUChainedStruct} view::WGPUTextureView resolveTarget::WGPUTextureView loadOp::WGPULoadOp storeOp::WGPUStoreOp clearValue::WGPUColor end struct WGPURequiredLimits nextInChain::Ptr{WGPUChainedStruct} limits::WGPULimits end struct WGPUShaderModuleDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} hintCount::Csize_t hints::Ptr{WGPUShaderModuleCompilationHint} end struct WGPUSupportedLimits nextInChain::Ptr{WGPUChainedStructOut} limits::WGPULimits end struct WGPUTextureDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} usage::WGPUTextureUsageFlags dimension::WGPUTextureDimension size::WGPUExtent3D format::WGPUTextureFormat mipLevelCount::UInt32 sampleCount::UInt32 viewFormatCount::Csize_t viewFormats::Ptr{WGPUTextureFormat} end struct WGPUVertexBufferLayout arrayStride::UInt64 stepMode::WGPUVertexStepMode attributeCount::Csize_t attributes::Ptr{WGPUVertexAttribute} end struct WGPUBindGroupLayoutDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} entryCount::Csize_t entries::Ptr{WGPUBindGroupLayoutEntry} end struct WGPUColorTargetState nextInChain::Ptr{WGPUChainedStruct} format::WGPUTextureFormat blend::Ptr{WGPUBlendState} writeMask::WGPUColorWriteMaskFlags end struct WGPUComputePipelineDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} layout::WGPUPipelineLayout compute::WGPUProgrammableStageDescriptor end struct WGPUDeviceDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} requiredFeatureCount::Csize_t requiredFeatures::Ptr{WGPUFeatureName} requiredLimits::Ptr{WGPURequiredLimits} defaultQueue::WGPUQueueDescriptor deviceLostCallback::WGPUDeviceLostCallback deviceLostUserdata::Ptr{Cvoid} end struct WGPURenderPassDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} colorAttachmentCount::Csize_t colorAttachments::Ptr{WGPURenderPassColorAttachment} depthStencilAttachment::Ptr{WGPURenderPassDepthStencilAttachment} occlusionQuerySet::WGPUQuerySet timestampWrites::Ptr{WGPURenderPassTimestampWrites} end struct WGPUVertexState nextInChain::Ptr{WGPUChainedStruct} _module::WGPUShaderModule entryPoint::Ptr{Cchar} constantCount::Csize_t constants::Ptr{WGPUConstantEntry} bufferCount::Csize_t buffers::Ptr{WGPUVertexBufferLayout} end struct WGPUFragmentState nextInChain::Ptr{WGPUChainedStruct} _module::WGPUShaderModule entryPoint::Ptr{Cchar} constantCount::Csize_t constants::Ptr{WGPUConstantEntry} targetCount::Csize_t targets::Ptr{WGPUColorTargetState} end struct WGPURenderPipelineDescriptor nextInChain::Ptr{WGPUChainedStruct} label::Ptr{Cchar} layout::WGPUPipelineLayout vertex::WGPUVertexState primitive::WGPUPrimitiveState depthStencil::Ptr{WGPUDepthStencilState} multisample::WGPUMultisampleState fragment::Ptr{WGPUFragmentState} end # typedef WGPUInstance ( * WGPUProcCreateInstance ) ( WGPU_NULLABLE WGPUInstanceDescriptor const * descriptor ) const WGPUProcCreateInstance = Ptr{Cvoid} # typedef WGPUProc ( * WGPUProcGetProcAddress ) ( WGPUDevice device , char const * procName ) const WGPUProcGetProcAddress = Ptr{Cvoid} # typedef size_t ( * WGPUProcAdapterEnumerateFeatures ) ( WGPUAdapter adapter , WGPUFeatureName * features ) const WGPUProcAdapterEnumerateFeatures = Ptr{Cvoid} # typedef WGPUBool ( * WGPUProcAdapterGetLimits ) ( WGPUAdapter adapter , WGPUSupportedLimits * limits ) const WGPUProcAdapterGetLimits = Ptr{Cvoid} # typedef void ( * WGPUProcAdapterGetProperties ) ( WGPUAdapter adapter , WGPUAdapterProperties * properties ) const WGPUProcAdapterGetProperties = Ptr{Cvoid} # typedef WGPUBool ( * WGPUProcAdapterHasFeature ) ( WGPUAdapter adapter , WGPUFeatureName feature ) const WGPUProcAdapterHasFeature = Ptr{Cvoid} # typedef void ( * WGPUProcAdapterRequestDevice ) ( WGPUAdapter adapter , WGPU_NULLABLE WGPUDeviceDescriptor const * descriptor , WGPURequestDeviceCallback callback , void * userdata ) const WGPUProcAdapterRequestDevice = Ptr{Cvoid} # typedef void ( * WGPUProcAdapterReference ) ( WGPUAdapter adapter ) const WGPUProcAdapterReference = Ptr{Cvoid} # typedef void ( * WGPUProcAdapterRelease ) ( WGPUAdapter adapter ) const WGPUProcAdapterRelease = Ptr{Cvoid} # typedef void ( * WGPUProcBindGroupSetLabel ) ( WGPUBindGroup bindGroup , char const * label ) const WGPUProcBindGroupSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcBindGroupReference ) ( WGPUBindGroup bindGroup ) const WGPUProcBindGroupReference = Ptr{Cvoid} # typedef void ( * WGPUProcBindGroupRelease ) ( WGPUBindGroup bindGroup ) const WGPUProcBindGroupRelease = Ptr{Cvoid} # typedef void ( * WGPUProcBindGroupLayoutSetLabel ) ( WGPUBindGroupLayout bindGroupLayout , char const * label ) const WGPUProcBindGroupLayoutSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcBindGroupLayoutReference ) ( WGPUBindGroupLayout bindGroupLayout ) const WGPUProcBindGroupLayoutReference = Ptr{Cvoid} # typedef void ( * WGPUProcBindGroupLayoutRelease ) ( WGPUBindGroupLayout bindGroupLayout ) const WGPUProcBindGroupLayoutRelease = Ptr{Cvoid} # typedef void ( * WGPUProcBufferDestroy ) ( WGPUBuffer buffer ) const WGPUProcBufferDestroy = Ptr{Cvoid} # typedef void const * ( * WGPUProcBufferGetConstMappedRange ) ( WGPUBuffer buffer , size_t offset , size_t size ) const WGPUProcBufferGetConstMappedRange = Ptr{Cvoid} # typedef WGPUBufferMapState ( * WGPUProcBufferGetMapState ) ( WGPUBuffer buffer ) const WGPUProcBufferGetMapState = Ptr{Cvoid} # typedef void * ( * WGPUProcBufferGetMappedRange ) ( WGPUBuffer buffer , size_t offset , size_t size ) const WGPUProcBufferGetMappedRange = Ptr{Cvoid} # typedef uint64_t ( * WGPUProcBufferGetSize ) ( WGPUBuffer buffer ) const WGPUProcBufferGetSize = Ptr{Cvoid} # typedef WGPUBufferUsageFlags ( * WGPUProcBufferGetUsage ) ( WGPUBuffer buffer ) const WGPUProcBufferGetUsage = Ptr{Cvoid} # typedef void ( * WGPUProcBufferMapAsync ) ( WGPUBuffer buffer , WGPUMapModeFlags mode , size_t offset , size_t size , WGPUBufferMapCallback callback , void * userdata ) const WGPUProcBufferMapAsync = Ptr{Cvoid} # typedef void ( * WGPUProcBufferSetLabel ) ( WGPUBuffer buffer , char const * label ) const WGPUProcBufferSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcBufferUnmap ) ( WGPUBuffer buffer ) const WGPUProcBufferUnmap = Ptr{Cvoid} # typedef void ( * WGPUProcBufferReference ) ( WGPUBuffer buffer ) const WGPUProcBufferReference = Ptr{Cvoid} # typedef void ( * WGPUProcBufferRelease ) ( WGPUBuffer buffer ) const WGPUProcBufferRelease = Ptr{Cvoid} # typedef void ( * WGPUProcCommandBufferSetLabel ) ( WGPUCommandBuffer commandBuffer , char const * label ) const WGPUProcCommandBufferSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcCommandBufferReference ) ( WGPUCommandBuffer commandBuffer ) const WGPUProcCommandBufferReference = Ptr{Cvoid} # typedef void ( * WGPUProcCommandBufferRelease ) ( WGPUCommandBuffer commandBuffer ) const WGPUProcCommandBufferRelease = Ptr{Cvoid} # typedef WGPUComputePassEncoder ( * WGPUProcCommandEncoderBeginComputePass ) ( WGPUCommandEncoder commandEncoder , WGPU_NULLABLE WGPUComputePassDescriptor const * descriptor ) const WGPUProcCommandEncoderBeginComputePass = Ptr{Cvoid} # typedef WGPURenderPassEncoder ( * WGPUProcCommandEncoderBeginRenderPass ) ( WGPUCommandEncoder commandEncoder , WGPURenderPassDescriptor const * descriptor ) const WGPUProcCommandEncoderBeginRenderPass = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderClearBuffer ) ( WGPUCommandEncoder commandEncoder , WGPUBuffer buffer , uint64_t offset , uint64_t size ) const WGPUProcCommandEncoderClearBuffer = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderCopyBufferToBuffer ) ( WGPUCommandEncoder commandEncoder , WGPUBuffer source , uint64_t sourceOffset , WGPUBuffer destination , uint64_t destinationOffset , uint64_t size ) const WGPUProcCommandEncoderCopyBufferToBuffer = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderCopyBufferToTexture ) ( WGPUCommandEncoder commandEncoder , WGPUImageCopyBuffer const * source , WGPUImageCopyTexture const * destination , WGPUExtent3D const * copySize ) const WGPUProcCommandEncoderCopyBufferToTexture = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderCopyTextureToBuffer ) ( WGPUCommandEncoder commandEncoder , WGPUImageCopyTexture const * source , WGPUImageCopyBuffer const * destination , WGPUExtent3D const * copySize ) const WGPUProcCommandEncoderCopyTextureToBuffer = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderCopyTextureToTexture ) ( WGPUCommandEncoder commandEncoder , WGPUImageCopyTexture const * source , WGPUImageCopyTexture const * destination , WGPUExtent3D const * copySize ) const WGPUProcCommandEncoderCopyTextureToTexture = Ptr{Cvoid} # typedef WGPUCommandBuffer ( * WGPUProcCommandEncoderFinish ) ( WGPUCommandEncoder commandEncoder , WGPU_NULLABLE WGPUCommandBufferDescriptor const * descriptor ) const WGPUProcCommandEncoderFinish = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderInsertDebugMarker ) ( WGPUCommandEncoder commandEncoder , char const * markerLabel ) const WGPUProcCommandEncoderInsertDebugMarker = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderPopDebugGroup ) ( WGPUCommandEncoder commandEncoder ) const WGPUProcCommandEncoderPopDebugGroup = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderPushDebugGroup ) ( WGPUCommandEncoder commandEncoder , char const * groupLabel ) const WGPUProcCommandEncoderPushDebugGroup = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderResolveQuerySet ) ( WGPUCommandEncoder commandEncoder , WGPUQuerySet querySet , uint32_t firstQuery , uint32_t queryCount , WGPUBuffer destination , uint64_t destinationOffset ) const WGPUProcCommandEncoderResolveQuerySet = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderSetLabel ) ( WGPUCommandEncoder commandEncoder , char const * label ) const WGPUProcCommandEncoderSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderWriteTimestamp ) ( WGPUCommandEncoder commandEncoder , WGPUQuerySet querySet , uint32_t queryIndex ) const WGPUProcCommandEncoderWriteTimestamp = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderReference ) ( WGPUCommandEncoder commandEncoder ) const WGPUProcCommandEncoderReference = Ptr{Cvoid} # typedef void ( * WGPUProcCommandEncoderRelease ) ( WGPUCommandEncoder commandEncoder ) const WGPUProcCommandEncoderRelease = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderDispatchWorkgroups ) ( WGPUComputePassEncoder computePassEncoder , uint32_t workgroupCountX , uint32_t workgroupCountY , uint32_t workgroupCountZ ) const WGPUProcComputePassEncoderDispatchWorkgroups = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderDispatchWorkgroupsIndirect ) ( WGPUComputePassEncoder computePassEncoder , WGPUBuffer indirectBuffer , uint64_t indirectOffset ) const WGPUProcComputePassEncoderDispatchWorkgroupsIndirect = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderEnd ) ( WGPUComputePassEncoder computePassEncoder ) const WGPUProcComputePassEncoderEnd = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderInsertDebugMarker ) ( WGPUComputePassEncoder computePassEncoder , char const * markerLabel ) const WGPUProcComputePassEncoderInsertDebugMarker = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderPopDebugGroup ) ( WGPUComputePassEncoder computePassEncoder ) const WGPUProcComputePassEncoderPopDebugGroup = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderPushDebugGroup ) ( WGPUComputePassEncoder computePassEncoder , char const * groupLabel ) const WGPUProcComputePassEncoderPushDebugGroup = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderSetBindGroup ) ( WGPUComputePassEncoder computePassEncoder , uint32_t groupIndex , WGPU_NULLABLE WGPUBindGroup group , size_t dynamicOffsetCount , uint32_t const * dynamicOffsets ) const WGPUProcComputePassEncoderSetBindGroup = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderSetLabel ) ( WGPUComputePassEncoder computePassEncoder , char const * label ) const WGPUProcComputePassEncoderSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderSetPipeline ) ( WGPUComputePassEncoder computePassEncoder , WGPUComputePipeline pipeline ) const WGPUProcComputePassEncoderSetPipeline = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderReference ) ( WGPUComputePassEncoder computePassEncoder ) const WGPUProcComputePassEncoderReference = Ptr{Cvoid} # typedef void ( * WGPUProcComputePassEncoderRelease ) ( WGPUComputePassEncoder computePassEncoder ) const WGPUProcComputePassEncoderRelease = Ptr{Cvoid} # typedef WGPUBindGroupLayout ( * WGPUProcComputePipelineGetBindGroupLayout ) ( WGPUComputePipeline computePipeline , uint32_t groupIndex ) const WGPUProcComputePipelineGetBindGroupLayout = Ptr{Cvoid} # typedef void ( * WGPUProcComputePipelineSetLabel ) ( WGPUComputePipeline computePipeline , char const * label ) const WGPUProcComputePipelineSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcComputePipelineReference ) ( WGPUComputePipeline computePipeline ) const WGPUProcComputePipelineReference = Ptr{Cvoid} # typedef void ( * WGPUProcComputePipelineRelease ) ( WGPUComputePipeline computePipeline ) const WGPUProcComputePipelineRelease = Ptr{Cvoid} # typedef WGPUBindGroup ( * WGPUProcDeviceCreateBindGroup ) ( WGPUDevice device , WGPUBindGroupDescriptor const * descriptor ) const WGPUProcDeviceCreateBindGroup = Ptr{Cvoid} # typedef WGPUBindGroupLayout ( * WGPUProcDeviceCreateBindGroupLayout ) ( WGPUDevice device , WGPUBindGroupLayoutDescriptor const * descriptor ) const WGPUProcDeviceCreateBindGroupLayout = Ptr{Cvoid} # typedef WGPUBuffer ( * WGPUProcDeviceCreateBuffer ) ( WGPUDevice device , WGPUBufferDescriptor const * descriptor ) const WGPUProcDeviceCreateBuffer = Ptr{Cvoid} # typedef WGPUCommandEncoder ( * WGPUProcDeviceCreateCommandEncoder ) ( WGPUDevice device , WGPU_NULLABLE WGPUCommandEncoderDescriptor const * descriptor ) const WGPUProcDeviceCreateCommandEncoder = Ptr{Cvoid} # typedef WGPUComputePipeline ( * WGPUProcDeviceCreateComputePipeline ) ( WGPUDevice device , WGPUComputePipelineDescriptor const * descriptor ) const WGPUProcDeviceCreateComputePipeline = Ptr{Cvoid} # typedef void ( * WGPUProcDeviceCreateComputePipelineAsync ) ( WGPUDevice device , WGPUComputePipelineDescriptor const * descriptor , WGPUCreateComputePipelineAsyncCallback callback , void * userdata ) const WGPUProcDeviceCreateComputePipelineAsync = Ptr{Cvoid} # typedef WGPUPipelineLayout ( * WGPUProcDeviceCreatePipelineLayout ) ( WGPUDevice device , WGPUPipelineLayoutDescriptor const * descriptor ) const WGPUProcDeviceCreatePipelineLayout = Ptr{Cvoid} # typedef WGPUQuerySet ( * WGPUProcDeviceCreateQuerySet ) ( WGPUDevice device , WGPUQuerySetDescriptor const * descriptor ) const WGPUProcDeviceCreateQuerySet = Ptr{Cvoid} # typedef WGPURenderBundleEncoder ( * WGPUProcDeviceCreateRenderBundleEncoder ) ( WGPUDevice device , WGPURenderBundleEncoderDescriptor const * descriptor ) const WGPUProcDeviceCreateRenderBundleEncoder = Ptr{Cvoid} # typedef WGPURenderPipeline ( * WGPUProcDeviceCreateRenderPipeline ) ( WGPUDevice device , WGPURenderPipelineDescriptor const * descriptor ) const WGPUProcDeviceCreateRenderPipeline = Ptr{Cvoid} # typedef void ( * WGPUProcDeviceCreateRenderPipelineAsync ) ( WGPUDevice device , WGPURenderPipelineDescriptor const * descriptor , WGPUCreateRenderPipelineAsyncCallback callback , void * userdata ) const WGPUProcDeviceCreateRenderPipelineAsync = Ptr{Cvoid} # typedef WGPUSampler ( * WGPUProcDeviceCreateSampler ) ( WGPUDevice device , WGPU_NULLABLE WGPUSamplerDescriptor const * descriptor ) const WGPUProcDeviceCreateSampler = Ptr{Cvoid} # typedef WGPUShaderModule ( * WGPUProcDeviceCreateShaderModule ) ( WGPUDevice device , WGPUShaderModuleDescriptor const * descriptor ) const WGPUProcDeviceCreateShaderModule = Ptr{Cvoid} # typedef WGPUTexture ( * WGPUProcDeviceCreateTexture ) ( WGPUDevice device , WGPUTextureDescriptor const * descriptor ) const WGPUProcDeviceCreateTexture = Ptr{Cvoid} # typedef void ( * WGPUProcDeviceDestroy ) ( WGPUDevice device ) const WGPUProcDeviceDestroy = Ptr{Cvoid} # typedef size_t ( * WGPUProcDeviceEnumerateFeatures ) ( WGPUDevice device , WGPUFeatureName * features ) const WGPUProcDeviceEnumerateFeatures = Ptr{Cvoid} # typedef WGPUBool ( * WGPUProcDeviceGetLimits ) ( WGPUDevice device , WGPUSupportedLimits * limits ) const WGPUProcDeviceGetLimits = Ptr{Cvoid} # typedef WGPUQueue ( * WGPUProcDeviceGetQueue ) ( WGPUDevice device ) const WGPUProcDeviceGetQueue = Ptr{Cvoid} # typedef WGPUBool ( * WGPUProcDeviceHasFeature ) ( WGPUDevice device , WGPUFeatureName feature ) const WGPUProcDeviceHasFeature = Ptr{Cvoid} # typedef void ( * WGPUProcDevicePopErrorScope ) ( WGPUDevice device , WGPUErrorCallback callback , void * userdata ) const WGPUProcDevicePopErrorScope = Ptr{Cvoid} # typedef void ( * WGPUProcDevicePushErrorScope ) ( WGPUDevice device , WGPUErrorFilter filter ) const WGPUProcDevicePushErrorScope = Ptr{Cvoid} # typedef void ( * WGPUProcDeviceSetLabel ) ( WGPUDevice device , char const * label ) const WGPUProcDeviceSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcDeviceSetUncapturedErrorCallback ) ( WGPUDevice device , WGPUErrorCallback callback , void * userdata ) const WGPUProcDeviceSetUncapturedErrorCallback = Ptr{Cvoid} # typedef void ( * WGPUProcDeviceReference ) ( WGPUDevice device ) const WGPUProcDeviceReference = Ptr{Cvoid} # typedef void ( * WGPUProcDeviceRelease ) ( WGPUDevice device ) const WGPUProcDeviceRelease = Ptr{Cvoid} # typedef WGPUSurface ( * WGPUProcInstanceCreateSurface ) ( WGPUInstance instance , WGPUSurfaceDescriptor const * descriptor ) const WGPUProcInstanceCreateSurface = Ptr{Cvoid} # typedef void ( * WGPUProcInstanceProcessEvents ) ( WGPUInstance instance ) const WGPUProcInstanceProcessEvents = Ptr{Cvoid} # typedef void ( * WGPUProcInstanceRequestAdapter ) ( WGPUInstance instance , WGPU_NULLABLE WGPURequestAdapterOptions const * options , WGPURequestAdapterCallback callback , void * userdata ) const WGPUProcInstanceRequestAdapter = Ptr{Cvoid} # typedef void ( * WGPUProcInstanceReference ) ( WGPUInstance instance ) const WGPUProcInstanceReference = Ptr{Cvoid} # typedef void ( * WGPUProcInstanceRelease ) ( WGPUInstance instance ) const WGPUProcInstanceRelease = Ptr{Cvoid} # typedef void ( * WGPUProcPipelineLayoutSetLabel ) ( WGPUPipelineLayout pipelineLayout , char const * label ) const WGPUProcPipelineLayoutSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcPipelineLayoutReference ) ( WGPUPipelineLayout pipelineLayout ) const WGPUProcPipelineLayoutReference = Ptr{Cvoid} # typedef void ( * WGPUProcPipelineLayoutRelease ) ( WGPUPipelineLayout pipelineLayout ) const WGPUProcPipelineLayoutRelease = Ptr{Cvoid} # typedef void ( * WGPUProcQuerySetDestroy ) ( WGPUQuerySet querySet ) const WGPUProcQuerySetDestroy = Ptr{Cvoid} # typedef uint32_t ( * WGPUProcQuerySetGetCount ) ( WGPUQuerySet querySet ) const WGPUProcQuerySetGetCount = Ptr{Cvoid} # typedef WGPUQueryType ( * WGPUProcQuerySetGetType ) ( WGPUQuerySet querySet ) const WGPUProcQuerySetGetType = Ptr{Cvoid} # typedef void ( * WGPUProcQuerySetSetLabel ) ( WGPUQuerySet querySet , char const * label ) const WGPUProcQuerySetSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcQuerySetReference ) ( WGPUQuerySet querySet ) const WGPUProcQuerySetReference = Ptr{Cvoid} # typedef void ( * WGPUProcQuerySetRelease ) ( WGPUQuerySet querySet ) const WGPUProcQuerySetRelease = Ptr{Cvoid} # typedef void ( * WGPUProcQueueOnSubmittedWorkDone ) ( WGPUQueue queue , WGPUQueueWorkDoneCallback callback , void * userdata ) const WGPUProcQueueOnSubmittedWorkDone = Ptr{Cvoid} # typedef void ( * WGPUProcQueueSetLabel ) ( WGPUQueue queue , char const * label ) const WGPUProcQueueSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcQueueSubmit ) ( WGPUQueue queue , size_t commandCount , WGPUCommandBuffer const * commands ) const WGPUProcQueueSubmit = Ptr{Cvoid} # typedef void ( * WGPUProcQueueWriteBuffer ) ( WGPUQueue queue , WGPUBuffer buffer , uint64_t bufferOffset , void const * data , size_t size ) const WGPUProcQueueWriteBuffer = Ptr{Cvoid} # typedef void ( * WGPUProcQueueWriteTexture ) ( WGPUQueue queue , WGPUImageCopyTexture const * destination , void const * data , size_t dataSize , WGPUTextureDataLayout const * dataLayout , WGPUExtent3D const * writeSize ) const WGPUProcQueueWriteTexture = Ptr{Cvoid} # typedef void ( * WGPUProcQueueReference ) ( WGPUQueue queue ) const WGPUProcQueueReference = Ptr{Cvoid} # typedef void ( * WGPUProcQueueRelease ) ( WGPUQueue queue ) const WGPUProcQueueRelease = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleSetLabel ) ( WGPURenderBundle renderBundle , char const * label ) const WGPUProcRenderBundleSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleReference ) ( WGPURenderBundle renderBundle ) const WGPUProcRenderBundleReference = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleRelease ) ( WGPURenderBundle renderBundle ) const WGPUProcRenderBundleRelease = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderDraw ) ( WGPURenderBundleEncoder renderBundleEncoder , uint32_t vertexCount , uint32_t instanceCount , uint32_t firstVertex , uint32_t firstInstance ) const WGPUProcRenderBundleEncoderDraw = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderDrawIndexed ) ( WGPURenderBundleEncoder renderBundleEncoder , uint32_t indexCount , uint32_t instanceCount , uint32_t firstIndex , int32_t baseVertex , uint32_t firstInstance ) const WGPUProcRenderBundleEncoderDrawIndexed = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderDrawIndexedIndirect ) ( WGPURenderBundleEncoder renderBundleEncoder , WGPUBuffer indirectBuffer , uint64_t indirectOffset ) const WGPUProcRenderBundleEncoderDrawIndexedIndirect = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderDrawIndirect ) ( WGPURenderBundleEncoder renderBundleEncoder , WGPUBuffer indirectBuffer , uint64_t indirectOffset ) const WGPUProcRenderBundleEncoderDrawIndirect = Ptr{Cvoid} # typedef WGPURenderBundle ( * WGPUProcRenderBundleEncoderFinish ) ( WGPURenderBundleEncoder renderBundleEncoder , WGPU_NULLABLE WGPURenderBundleDescriptor const * descriptor ) const WGPUProcRenderBundleEncoderFinish = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderInsertDebugMarker ) ( WGPURenderBundleEncoder renderBundleEncoder , char const * markerLabel ) const WGPUProcRenderBundleEncoderInsertDebugMarker = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderPopDebugGroup ) ( WGPURenderBundleEncoder renderBundleEncoder ) const WGPUProcRenderBundleEncoderPopDebugGroup = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderPushDebugGroup ) ( WGPURenderBundleEncoder renderBundleEncoder , char const * groupLabel ) const WGPUProcRenderBundleEncoderPushDebugGroup = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderSetBindGroup ) ( WGPURenderBundleEncoder renderBundleEncoder , uint32_t groupIndex , WGPU_NULLABLE WGPUBindGroup group , size_t dynamicOffsetCount , uint32_t const * dynamicOffsets ) const WGPUProcRenderBundleEncoderSetBindGroup = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderSetIndexBuffer ) ( WGPURenderBundleEncoder renderBundleEncoder , WGPUBuffer buffer , WGPUIndexFormat format , uint64_t offset , uint64_t size ) const WGPUProcRenderBundleEncoderSetIndexBuffer = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderSetLabel ) ( WGPURenderBundleEncoder renderBundleEncoder , char const * label ) const WGPUProcRenderBundleEncoderSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderSetPipeline ) ( WGPURenderBundleEncoder renderBundleEncoder , WGPURenderPipeline pipeline ) const WGPUProcRenderBundleEncoderSetPipeline = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderSetVertexBuffer ) ( WGPURenderBundleEncoder renderBundleEncoder , uint32_t slot , WGPU_NULLABLE WGPUBuffer buffer , uint64_t offset , uint64_t size ) const WGPUProcRenderBundleEncoderSetVertexBuffer = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderReference ) ( WGPURenderBundleEncoder renderBundleEncoder ) const WGPUProcRenderBundleEncoderReference = Ptr{Cvoid} # typedef void ( * WGPUProcRenderBundleEncoderRelease ) ( WGPURenderBundleEncoder renderBundleEncoder ) const WGPUProcRenderBundleEncoderRelease = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderBeginOcclusionQuery ) ( WGPURenderPassEncoder renderPassEncoder , uint32_t queryIndex ) const WGPUProcRenderPassEncoderBeginOcclusionQuery = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderDraw ) ( WGPURenderPassEncoder renderPassEncoder , uint32_t vertexCount , uint32_t instanceCount , uint32_t firstVertex , uint32_t firstInstance ) const WGPUProcRenderPassEncoderDraw = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderDrawIndexed ) ( WGPURenderPassEncoder renderPassEncoder , uint32_t indexCount , uint32_t instanceCount , uint32_t firstIndex , int32_t baseVertex , uint32_t firstInstance ) const WGPUProcRenderPassEncoderDrawIndexed = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderDrawIndexedIndirect ) ( WGPURenderPassEncoder renderPassEncoder , WGPUBuffer indirectBuffer , uint64_t indirectOffset ) const WGPUProcRenderPassEncoderDrawIndexedIndirect = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderDrawIndirect ) ( WGPURenderPassEncoder renderPassEncoder , WGPUBuffer indirectBuffer , uint64_t indirectOffset ) const WGPUProcRenderPassEncoderDrawIndirect = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderEnd ) ( WGPURenderPassEncoder renderPassEncoder ) const WGPUProcRenderPassEncoderEnd = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderEndOcclusionQuery ) ( WGPURenderPassEncoder renderPassEncoder ) const WGPUProcRenderPassEncoderEndOcclusionQuery = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderExecuteBundles ) ( WGPURenderPassEncoder renderPassEncoder , size_t bundleCount , WGPURenderBundle const * bundles ) const WGPUProcRenderPassEncoderExecuteBundles = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderInsertDebugMarker ) ( WGPURenderPassEncoder renderPassEncoder , char const * markerLabel ) const WGPUProcRenderPassEncoderInsertDebugMarker = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderPopDebugGroup ) ( WGPURenderPassEncoder renderPassEncoder ) const WGPUProcRenderPassEncoderPopDebugGroup = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderPushDebugGroup ) ( WGPURenderPassEncoder renderPassEncoder , char const * groupLabel ) const WGPUProcRenderPassEncoderPushDebugGroup = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderSetBindGroup ) ( WGPURenderPassEncoder renderPassEncoder , uint32_t groupIndex , WGPU_NULLABLE WGPUBindGroup group , size_t dynamicOffsetCount , uint32_t const * dynamicOffsets ) const WGPUProcRenderPassEncoderSetBindGroup = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderSetBlendConstant ) ( WGPURenderPassEncoder renderPassEncoder , WGPUColor const * color ) const WGPUProcRenderPassEncoderSetBlendConstant = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderSetIndexBuffer ) ( WGPURenderPassEncoder renderPassEncoder , WGPUBuffer buffer , WGPUIndexFormat format , uint64_t offset , uint64_t size ) const WGPUProcRenderPassEncoderSetIndexBuffer = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderSetLabel ) ( WGPURenderPassEncoder renderPassEncoder , char const * label ) const WGPUProcRenderPassEncoderSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderSetPipeline ) ( WGPURenderPassEncoder renderPassEncoder , WGPURenderPipeline pipeline ) const WGPUProcRenderPassEncoderSetPipeline = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderSetScissorRect ) ( WGPURenderPassEncoder renderPassEncoder , uint32_t x , uint32_t y , uint32_t width , uint32_t height ) const WGPUProcRenderPassEncoderSetScissorRect = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderSetStencilReference ) ( WGPURenderPassEncoder renderPassEncoder , uint32_t reference ) const WGPUProcRenderPassEncoderSetStencilReference = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderSetVertexBuffer ) ( WGPURenderPassEncoder renderPassEncoder , uint32_t slot , WGPU_NULLABLE WGPUBuffer buffer , uint64_t offset , uint64_t size ) const WGPUProcRenderPassEncoderSetVertexBuffer = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderSetViewport ) ( WGPURenderPassEncoder renderPassEncoder , float x , float y , float width , float height , float minDepth , float maxDepth ) const WGPUProcRenderPassEncoderSetViewport = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderReference ) ( WGPURenderPassEncoder renderPassEncoder ) const WGPUProcRenderPassEncoderReference = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPassEncoderRelease ) ( WGPURenderPassEncoder renderPassEncoder ) const WGPUProcRenderPassEncoderRelease = Ptr{Cvoid} # typedef WGPUBindGroupLayout ( * WGPUProcRenderPipelineGetBindGroupLayout ) ( WGPURenderPipeline renderPipeline , uint32_t groupIndex ) const WGPUProcRenderPipelineGetBindGroupLayout = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPipelineSetLabel ) ( WGPURenderPipeline renderPipeline , char const * label ) const WGPUProcRenderPipelineSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPipelineReference ) ( WGPURenderPipeline renderPipeline ) const WGPUProcRenderPipelineReference = Ptr{Cvoid} # typedef void ( * WGPUProcRenderPipelineRelease ) ( WGPURenderPipeline renderPipeline ) const WGPUProcRenderPipelineRelease = Ptr{Cvoid} # typedef void ( * WGPUProcSamplerSetLabel ) ( WGPUSampler sampler , char const * label ) const WGPUProcSamplerSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcSamplerReference ) ( WGPUSampler sampler ) const WGPUProcSamplerReference = Ptr{Cvoid} # typedef void ( * WGPUProcSamplerRelease ) ( WGPUSampler sampler ) const WGPUProcSamplerRelease = Ptr{Cvoid} # typedef void ( * WGPUProcShaderModuleGetCompilationInfo ) ( WGPUShaderModule shaderModule , WGPUCompilationInfoCallback callback , void * userdata ) const WGPUProcShaderModuleGetCompilationInfo = Ptr{Cvoid} # typedef void ( * WGPUProcShaderModuleSetLabel ) ( WGPUShaderModule shaderModule , char const * label ) const WGPUProcShaderModuleSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcShaderModuleReference ) ( WGPUShaderModule shaderModule ) const WGPUProcShaderModuleReference = Ptr{Cvoid} # typedef void ( * WGPUProcShaderModuleRelease ) ( WGPUShaderModule shaderModule ) const WGPUProcShaderModuleRelease = Ptr{Cvoid} # typedef void ( * WGPUProcSurfaceConfigure ) ( WGPUSurface surface , WGPUSurfaceConfiguration const * config ) const WGPUProcSurfaceConfigure = Ptr{Cvoid} # typedef void ( * WGPUProcSurfaceGetCapabilities ) ( WGPUSurface surface , WGPUAdapter adapter , WGPUSurfaceCapabilities * capabilities ) const WGPUProcSurfaceGetCapabilities = Ptr{Cvoid} # typedef void ( * WGPUProcSurfaceGetCurrentTexture ) ( WGPUSurface surface , WGPUSurfaceTexture * surfaceTexture ) const WGPUProcSurfaceGetCurrentTexture = Ptr{Cvoid} # typedef WGPUTextureFormat ( * WGPUProcSurfaceGetPreferredFormat ) ( WGPUSurface surface , WGPUAdapter adapter ) const WGPUProcSurfaceGetPreferredFormat = Ptr{Cvoid} # typedef void ( * WGPUProcSurfacePresent ) ( WGPUSurface surface ) const WGPUProcSurfacePresent = Ptr{Cvoid} # typedef void ( * WGPUProcSurfaceUnconfigure ) ( WGPUSurface surface ) const WGPUProcSurfaceUnconfigure = Ptr{Cvoid} # typedef void ( * WGPUProcSurfaceReference ) ( WGPUSurface surface ) const WGPUProcSurfaceReference = Ptr{Cvoid} # typedef void ( * WGPUProcSurfaceRelease ) ( WGPUSurface surface ) const WGPUProcSurfaceRelease = Ptr{Cvoid} # typedef void ( * WGPUProcSurfaceCapabilitiesFreeMembers ) ( WGPUSurfaceCapabilities capabilities ) const WGPUProcSurfaceCapabilitiesFreeMembers = Ptr{Cvoid} # typedef WGPUTextureView ( * WGPUProcTextureCreateView ) ( WGPUTexture texture , WGPU_NULLABLE WGPUTextureViewDescriptor const * descriptor ) const WGPUProcTextureCreateView = Ptr{Cvoid} # typedef void ( * WGPUProcTextureDestroy ) ( WGPUTexture texture ) const WGPUProcTextureDestroy = Ptr{Cvoid} # typedef uint32_t ( * WGPUProcTextureGetDepthOrArrayLayers ) ( WGPUTexture texture ) const WGPUProcTextureGetDepthOrArrayLayers = Ptr{Cvoid} # typedef WGPUTextureDimension ( * WGPUProcTextureGetDimension ) ( WGPUTexture texture ) const WGPUProcTextureGetDimension = Ptr{Cvoid} # typedef WGPUTextureFormat ( * WGPUProcTextureGetFormat ) ( WGPUTexture texture ) const WGPUProcTextureGetFormat = Ptr{Cvoid} # typedef uint32_t ( * WGPUProcTextureGetHeight ) ( WGPUTexture texture ) const WGPUProcTextureGetHeight = Ptr{Cvoid} # typedef uint32_t ( * WGPUProcTextureGetMipLevelCount ) ( WGPUTexture texture ) const WGPUProcTextureGetMipLevelCount = Ptr{Cvoid} # typedef uint32_t ( * WGPUProcTextureGetSampleCount ) ( WGPUTexture texture ) const WGPUProcTextureGetSampleCount = Ptr{Cvoid} # typedef WGPUTextureUsageFlags ( * WGPUProcTextureGetUsage ) ( WGPUTexture texture ) const WGPUProcTextureGetUsage = Ptr{Cvoid} # typedef uint32_t ( * WGPUProcTextureGetWidth ) ( WGPUTexture texture ) const WGPUProcTextureGetWidth = Ptr{Cvoid} # typedef void ( * WGPUProcTextureSetLabel ) ( WGPUTexture texture , char const * label ) const WGPUProcTextureSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcTextureReference ) ( WGPUTexture texture ) const WGPUProcTextureReference = Ptr{Cvoid} # typedef void ( * WGPUProcTextureRelease ) ( WGPUTexture texture ) const WGPUProcTextureRelease = Ptr{Cvoid} # typedef void ( * WGPUProcTextureViewSetLabel ) ( WGPUTextureView textureView , char const * label ) const WGPUProcTextureViewSetLabel = Ptr{Cvoid} # typedef void ( * WGPUProcTextureViewReference ) ( WGPUTextureView textureView ) const WGPUProcTextureViewReference = Ptr{Cvoid} # typedef void ( * WGPUProcTextureViewRelease ) ( WGPUTextureView textureView ) const WGPUProcTextureViewRelease = Ptr{Cvoid} function wgpuCreateInstance(descriptor) ccall((:wgpuCreateInstance, libWGPU), WGPUInstance, (Ptr{WGPUInstanceDescriptor},), descriptor) end function wgpuGetProcAddress(device, procName) ccall((:wgpuGetProcAddress, libWGPU), WGPUProc, (WGPUDevice, Ptr{Cchar}), device, procName) end function wgpuAdapterEnumerateFeatures(adapter, features) ccall((:wgpuAdapterEnumerateFeatures, libWGPU), Csize_t, (WGPUAdapter, Ptr{WGPUFeatureName}), adapter, features) end function wgpuAdapterGetLimits(adapter, limits) ccall((:wgpuAdapterGetLimits, libWGPU), WGPUBool, (WGPUAdapter, Ptr{WGPUSupportedLimits}), adapter, limits) end function wgpuAdapterGetProperties(adapter, properties) ccall((:wgpuAdapterGetProperties, libWGPU), Cvoid, (WGPUAdapter, Ptr{WGPUAdapterProperties}), adapter, properties) end function wgpuAdapterHasFeature(adapter, feature) ccall((:wgpuAdapterHasFeature, libWGPU), WGPUBool, (WGPUAdapter, WGPUFeatureName), adapter, feature) end function wgpuAdapterRequestDevice(adapter, descriptor, callback, userdata) ccall((:wgpuAdapterRequestDevice, libWGPU), Cvoid, (WGPUAdapter, Ptr{WGPUDeviceDescriptor}, WGPURequestDeviceCallback, Ptr{Cvoid}), adapter, descriptor, callback, userdata) end function wgpuAdapterReference(adapter) ccall((:wgpuAdapterReference, libWGPU), Cvoid, (WGPUAdapter,), adapter) end function wgpuAdapterRelease(adapter) ccall((:wgpuAdapterRelease, libWGPU), Cvoid, (WGPUAdapter,), adapter) end function wgpuBindGroupSetLabel(bindGroup, label) ccall((:wgpuBindGroupSetLabel, libWGPU), Cvoid, (WGPUBindGroup, Ptr{Cchar}), bindGroup, label) end function wgpuBindGroupReference(bindGroup) ccall((:wgpuBindGroupReference, libWGPU), Cvoid, (WGPUBindGroup,), bindGroup) end function wgpuBindGroupRelease(bindGroup) ccall((:wgpuBindGroupRelease, libWGPU), Cvoid, (WGPUBindGroup,), bindGroup) end function wgpuBindGroupLayoutSetLabel(bindGroupLayout, label) ccall((:wgpuBindGroupLayoutSetLabel, libWGPU), Cvoid, (WGPUBindGroupLayout, Ptr{Cchar}), bindGroupLayout, label) end function wgpuBindGroupLayoutReference(bindGroupLayout) ccall((:wgpuBindGroupLayoutReference, libWGPU), Cvoid, (WGPUBindGroupLayout,), bindGroupLayout) end function wgpuBindGroupLayoutRelease(bindGroupLayout) ccall((:wgpuBindGroupLayoutRelease, libWGPU), Cvoid, (WGPUBindGroupLayout,), bindGroupLayout) end function wgpuBufferDestroy(buffer) ccall((:wgpuBufferDestroy, libWGPU), Cvoid, (WGPUBuffer,), buffer) end function wgpuBufferGetConstMappedRange(buffer, offset, size) ccall((:wgpuBufferGetConstMappedRange, libWGPU), Ptr{Cvoid}, (WGPUBuffer, Csize_t, Csize_t), buffer, offset, size) end function wgpuBufferGetMapState(buffer) ccall((:wgpuBufferGetMapState, libWGPU), WGPUBufferMapState, (WGPUBuffer,), buffer) end function wgpuBufferGetMappedRange(buffer, offset, size) ccall((:wgpuBufferGetMappedRange, libWGPU), Ptr{Cvoid}, (WGPUBuffer, Csize_t, Csize_t), buffer, offset, size) end function wgpuBufferGetSize(buffer) ccall((:wgpuBufferGetSize, libWGPU), UInt64, (WGPUBuffer,), buffer) end function wgpuBufferGetUsage(buffer) ccall((:wgpuBufferGetUsage, libWGPU), WGPUBufferUsageFlags, (WGPUBuffer,), buffer) end function wgpuBufferMapAsync(buffer, mode, offset, size, callback, userdata) ccall((:wgpuBufferMapAsync, libWGPU), Cvoid, (WGPUBuffer, WGPUMapModeFlags, Csize_t, Csize_t, WGPUBufferMapCallback, Ptr{Cvoid}), buffer, mode, offset, size, callback, userdata) end function wgpuBufferSetLabel(buffer, label) ccall((:wgpuBufferSetLabel, libWGPU), Cvoid, (WGPUBuffer, Ptr{Cchar}), buffer, label) end function wgpuBufferUnmap(buffer) ccall((:wgpuBufferUnmap, libWGPU), Cvoid, (WGPUBuffer,), buffer) end function wgpuBufferReference(buffer) ccall((:wgpuBufferReference, libWGPU), Cvoid, (WGPUBuffer,), buffer) end function wgpuBufferRelease(buffer) ccall((:wgpuBufferRelease, libWGPU), Cvoid, (WGPUBuffer,), buffer) end function wgpuCommandBufferSetLabel(commandBuffer, label) ccall((:wgpuCommandBufferSetLabel, libWGPU), Cvoid, (WGPUCommandBuffer, Ptr{Cchar}), commandBuffer, label) end function wgpuCommandBufferReference(commandBuffer) ccall((:wgpuCommandBufferReference, libWGPU), Cvoid, (WGPUCommandBuffer,), commandBuffer) end function wgpuCommandBufferRelease(commandBuffer) ccall((:wgpuCommandBufferRelease, libWGPU), Cvoid, (WGPUCommandBuffer,), commandBuffer) end function wgpuCommandEncoderBeginComputePass(commandEncoder, descriptor) ccall((:wgpuCommandEncoderBeginComputePass, libWGPU), WGPUComputePassEncoder, (WGPUCommandEncoder, Ptr{WGPUComputePassDescriptor}), commandEncoder, descriptor) end function wgpuCommandEncoderBeginRenderPass(commandEncoder, descriptor) ccall((:wgpuCommandEncoderBeginRenderPass, libWGPU), WGPURenderPassEncoder, (WGPUCommandEncoder, Ptr{WGPURenderPassDescriptor}), commandEncoder, descriptor) end function wgpuCommandEncoderClearBuffer(commandEncoder, buffer, offset, size) ccall((:wgpuCommandEncoderClearBuffer, libWGPU), Cvoid, (WGPUCommandEncoder, WGPUBuffer, UInt64, UInt64), commandEncoder, buffer, offset, size) end function wgpuCommandEncoderCopyBufferToBuffer(commandEncoder, source, sourceOffset, destination, destinationOffset, size) ccall((:wgpuCommandEncoderCopyBufferToBuffer, libWGPU), Cvoid, (WGPUCommandEncoder, WGPUBuffer, UInt64, WGPUBuffer, UInt64, UInt64), commandEncoder, source, sourceOffset, destination, destinationOffset, size) end function wgpuCommandEncoderCopyBufferToTexture(commandEncoder, source, destination, copySize) ccall((:wgpuCommandEncoderCopyBufferToTexture, libWGPU), Cvoid, (WGPUCommandEncoder, Ptr{WGPUImageCopyBuffer}, Ptr{WGPUImageCopyTexture}, Ptr{WGPUExtent3D}), commandEncoder, source, destination, copySize) end function wgpuCommandEncoderCopyTextureToBuffer(commandEncoder, source, destination, copySize) ccall((:wgpuCommandEncoderCopyTextureToBuffer, libWGPU), Cvoid, (WGPUCommandEncoder, Ptr{WGPUImageCopyTexture}, Ptr{WGPUImageCopyBuffer}, Ptr{WGPUExtent3D}), commandEncoder, source, destination, copySize) end function wgpuCommandEncoderCopyTextureToTexture(commandEncoder, source, destination, copySize) ccall((:wgpuCommandEncoderCopyTextureToTexture, libWGPU), Cvoid, (WGPUCommandEncoder, Ptr{WGPUImageCopyTexture}, Ptr{WGPUImageCopyTexture}, Ptr{WGPUExtent3D}), commandEncoder, source, destination, copySize) end function wgpuCommandEncoderFinish(commandEncoder, descriptor) ccall((:wgpuCommandEncoderFinish, libWGPU), WGPUCommandBuffer, (WGPUCommandEncoder, Ptr{WGPUCommandBufferDescriptor}), commandEncoder, descriptor) end function wgpuCommandEncoderInsertDebugMarker(commandEncoder, markerLabel) ccall((:wgpuCommandEncoderInsertDebugMarker, libWGPU), Cvoid, (WGPUCommandEncoder, Ptr{Cchar}), commandEncoder, markerLabel) end function wgpuCommandEncoderPopDebugGroup(commandEncoder) ccall((:wgpuCommandEncoderPopDebugGroup, libWGPU), Cvoid, (WGPUCommandEncoder,), commandEncoder) end function wgpuCommandEncoderPushDebugGroup(commandEncoder, groupLabel) ccall((:wgpuCommandEncoderPushDebugGroup, libWGPU), Cvoid, (WGPUCommandEncoder, Ptr{Cchar}), commandEncoder, groupLabel) end function wgpuCommandEncoderResolveQuerySet(commandEncoder, querySet, firstQuery, queryCount, destination, destinationOffset) ccall((:wgpuCommandEncoderResolveQuerySet, libWGPU), Cvoid, (WGPUCommandEncoder, WGPUQuerySet, UInt32, UInt32, WGPUBuffer, UInt64), commandEncoder, querySet, firstQuery, queryCount, destination, destinationOffset) end function wgpuCommandEncoderSetLabel(commandEncoder, label) ccall((:wgpuCommandEncoderSetLabel, libWGPU), Cvoid, (WGPUCommandEncoder, Ptr{Cchar}), commandEncoder, label) end function wgpuCommandEncoderWriteTimestamp(commandEncoder, querySet, queryIndex) ccall((:wgpuCommandEncoderWriteTimestamp, libWGPU), Cvoid, (WGPUCommandEncoder, WGPUQuerySet, UInt32), commandEncoder, querySet, queryIndex) end function wgpuCommandEncoderReference(commandEncoder) ccall((:wgpuCommandEncoderReference, libWGPU), Cvoid, (WGPUCommandEncoder,), commandEncoder) end function wgpuCommandEncoderRelease(commandEncoder) ccall((:wgpuCommandEncoderRelease, libWGPU), Cvoid, (WGPUCommandEncoder,), commandEncoder) end function wgpuComputePassEncoderDispatchWorkgroups(computePassEncoder, workgroupCountX, workgroupCountY, workgroupCountZ) ccall((:wgpuComputePassEncoderDispatchWorkgroups, libWGPU), Cvoid, (WGPUComputePassEncoder, UInt32, UInt32, UInt32), computePassEncoder, workgroupCountX, workgroupCountY, workgroupCountZ) end function wgpuComputePassEncoderDispatchWorkgroupsIndirect(computePassEncoder, indirectBuffer, indirectOffset) ccall((:wgpuComputePassEncoderDispatchWorkgroupsIndirect, libWGPU), Cvoid, (WGPUComputePassEncoder, WGPUBuffer, UInt64), computePassEncoder, indirectBuffer, indirectOffset) end function wgpuComputePassEncoderEnd(computePassEncoder) ccall((:wgpuComputePassEncoderEnd, libWGPU), Cvoid, (WGPUComputePassEncoder,), computePassEncoder) end function wgpuComputePassEncoderInsertDebugMarker(computePassEncoder, markerLabel) ccall((:wgpuComputePassEncoderInsertDebugMarker, libWGPU), Cvoid, (WGPUComputePassEncoder, Ptr{Cchar}), computePassEncoder, markerLabel) end function wgpuComputePassEncoderPopDebugGroup(computePassEncoder) ccall((:wgpuComputePassEncoderPopDebugGroup, libWGPU), Cvoid, (WGPUComputePassEncoder,), computePassEncoder) end function wgpuComputePassEncoderPushDebugGroup(computePassEncoder, groupLabel) ccall((:wgpuComputePassEncoderPushDebugGroup, libWGPU), Cvoid, (WGPUComputePassEncoder, Ptr{Cchar}), computePassEncoder, groupLabel) end function wgpuComputePassEncoderSetBindGroup(computePassEncoder, groupIndex, group, dynamicOffsetCount, dynamicOffsets) ccall((:wgpuComputePassEncoderSetBindGroup, libWGPU), Cvoid, (WGPUComputePassEncoder, UInt32, WGPUBindGroup, Csize_t, Ptr{UInt32}), computePassEncoder, groupIndex, group, dynamicOffsetCount, dynamicOffsets) end function wgpuComputePassEncoderSetLabel(computePassEncoder, label) ccall((:wgpuComputePassEncoderSetLabel, libWGPU), Cvoid, (WGPUComputePassEncoder, Ptr{Cchar}), computePassEncoder, label) end function wgpuComputePassEncoderSetPipeline(computePassEncoder, pipeline) ccall((:wgpuComputePassEncoderSetPipeline, libWGPU), Cvoid, (WGPUComputePassEncoder, WGPUComputePipeline), computePassEncoder, pipeline) end function wgpuComputePassEncoderReference(computePassEncoder) ccall((:wgpuComputePassEncoderReference, libWGPU), Cvoid, (WGPUComputePassEncoder,), computePassEncoder) end function wgpuComputePassEncoderRelease(computePassEncoder) ccall((:wgpuComputePassEncoderRelease, libWGPU), Cvoid, (WGPUComputePassEncoder,), computePassEncoder) end function wgpuComputePipelineGetBindGroupLayout(computePipeline, groupIndex) ccall((:wgpuComputePipelineGetBindGroupLayout, libWGPU), WGPUBindGroupLayout, (WGPUComputePipeline, UInt32), computePipeline, groupIndex) end function wgpuComputePipelineSetLabel(computePipeline, label) ccall((:wgpuComputePipelineSetLabel, libWGPU), Cvoid, (WGPUComputePipeline, Ptr{Cchar}), computePipeline, label) end function wgpuComputePipelineReference(computePipeline) ccall((:wgpuComputePipelineReference, libWGPU), Cvoid, (WGPUComputePipeline,), computePipeline) end function wgpuComputePipelineRelease(computePipeline) ccall((:wgpuComputePipelineRelease, libWGPU), Cvoid, (WGPUComputePipeline,), computePipeline) end function wgpuDeviceCreateBindGroup(device, descriptor) ccall((:wgpuDeviceCreateBindGroup, libWGPU), WGPUBindGroup, (WGPUDevice, Ptr{WGPUBindGroupDescriptor}), device, descriptor) end function wgpuDeviceCreateBindGroupLayout(device, descriptor) ccall((:wgpuDeviceCreateBindGroupLayout, libWGPU), WGPUBindGroupLayout, (WGPUDevice, Ptr{WGPUBindGroupLayoutDescriptor}), device, descriptor) end function wgpuDeviceCreateBuffer(device, descriptor) ccall((:wgpuDeviceCreateBuffer, libWGPU), WGPUBuffer, (WGPUDevice, Ptr{WGPUBufferDescriptor}), device, descriptor) end function wgpuDeviceCreateCommandEncoder(device, descriptor) ccall((:wgpuDeviceCreateCommandEncoder, libWGPU), WGPUCommandEncoder, (WGPUDevice, Ptr{WGPUCommandEncoderDescriptor}), device, descriptor) end function wgpuDeviceCreateComputePipeline(device, descriptor) ccall((:wgpuDeviceCreateComputePipeline, libWGPU), WGPUComputePipeline, (WGPUDevice, Ptr{WGPUComputePipelineDescriptor}), device, descriptor) end function wgpuDeviceCreateComputePipelineAsync(device, descriptor, callback, userdata) ccall((:wgpuDeviceCreateComputePipelineAsync, libWGPU), Cvoid, (WGPUDevice, Ptr{WGPUComputePipelineDescriptor}, WGPUCreateComputePipelineAsyncCallback, Ptr{Cvoid}), device, descriptor, callback, userdata) end function wgpuDeviceCreatePipelineLayout(device, descriptor) ccall((:wgpuDeviceCreatePipelineLayout, libWGPU), WGPUPipelineLayout, (WGPUDevice, Ptr{WGPUPipelineLayoutDescriptor}), device, descriptor) end function wgpuDeviceCreateQuerySet(device, descriptor) ccall((:wgpuDeviceCreateQuerySet, libWGPU), WGPUQuerySet, (WGPUDevice, Ptr{WGPUQuerySetDescriptor}), device, descriptor) end function wgpuDeviceCreateRenderBundleEncoder(device, descriptor) ccall((:wgpuDeviceCreateRenderBundleEncoder, libWGPU), WGPURenderBundleEncoder, (WGPUDevice, Ptr{WGPURenderBundleEncoderDescriptor}), device, descriptor) end function wgpuDeviceCreateRenderPipeline(device, descriptor) ccall((:wgpuDeviceCreateRenderPipeline, libWGPU), WGPURenderPipeline, (WGPUDevice, Ptr{WGPURenderPipelineDescriptor}), device, descriptor) end function wgpuDeviceCreateRenderPipelineAsync(device, descriptor, callback, userdata) ccall((:wgpuDeviceCreateRenderPipelineAsync, libWGPU), Cvoid, (WGPUDevice, Ptr{WGPURenderPipelineDescriptor}, WGPUCreateRenderPipelineAsyncCallback, Ptr{Cvoid}), device, descriptor, callback, userdata) end function wgpuDeviceCreateSampler(device, descriptor) ccall((:wgpuDeviceCreateSampler, libWGPU), WGPUSampler, (WGPUDevice, Ptr{WGPUSamplerDescriptor}), device, descriptor) end function wgpuDeviceCreateShaderModule(device, descriptor) ccall((:wgpuDeviceCreateShaderModule, libWGPU), WGPUShaderModule, (WGPUDevice, Ptr{WGPUShaderModuleDescriptor}), device, descriptor) end function wgpuDeviceCreateTexture(device, descriptor) ccall((:wgpuDeviceCreateTexture, libWGPU), WGPUTexture, (WGPUDevice, Ptr{WGPUTextureDescriptor}), device, descriptor) end function wgpuDeviceDestroy(device) ccall((:wgpuDeviceDestroy, libWGPU), Cvoid, (WGPUDevice,), device) end function wgpuDeviceEnumerateFeatures(device, features) ccall((:wgpuDeviceEnumerateFeatures, libWGPU), Csize_t, (WGPUDevice, Ptr{WGPUFeatureName}), device, features) end function wgpuDeviceGetLimits(device, limits) ccall((:wgpuDeviceGetLimits, libWGPU), WGPUBool, (WGPUDevice, Ptr{WGPUSupportedLimits}), device, limits) end function wgpuDeviceGetQueue(device) ccall((:wgpuDeviceGetQueue, libWGPU), WGPUQueue, (WGPUDevice,), device) end function wgpuDeviceHasFeature(device, feature) ccall((:wgpuDeviceHasFeature, libWGPU), WGPUBool, (WGPUDevice, WGPUFeatureName), device, feature) end function wgpuDevicePopErrorScope(device, callback, userdata) ccall((:wgpuDevicePopErrorScope, libWGPU), Cvoid, (WGPUDevice, WGPUErrorCallback, Ptr{Cvoid}), device, callback, userdata) end function wgpuDevicePushErrorScope(device, filter) ccall((:wgpuDevicePushErrorScope, libWGPU), Cvoid, (WGPUDevice, WGPUErrorFilter), device, filter) end function wgpuDeviceSetLabel(device, label) ccall((:wgpuDeviceSetLabel, libWGPU), Cvoid, (WGPUDevice, Ptr{Cchar}), device, label) end function wgpuDeviceSetUncapturedErrorCallback(device, callback, userdata) ccall((:wgpuDeviceSetUncapturedErrorCallback, libWGPU), Cvoid, (WGPUDevice, WGPUErrorCallback, Ptr{Cvoid}), device, callback, userdata) end function wgpuDeviceReference(device) ccall((:wgpuDeviceReference, libWGPU), Cvoid, (WGPUDevice,), device) end function wgpuDeviceRelease(device) ccall((:wgpuDeviceRelease, libWGPU), Cvoid, (WGPUDevice,), device) end function wgpuInstanceCreateSurface(instance, descriptor) ccall((:wgpuInstanceCreateSurface, libWGPU), WGPUSurface, (WGPUInstance, Ptr{WGPUSurfaceDescriptor}), instance, descriptor) end function wgpuInstanceProcessEvents(instance) ccall((:wgpuInstanceProcessEvents, libWGPU), Cvoid, (WGPUInstance,), instance) end function wgpuInstanceRequestAdapter(instance, options, callback, userdata) ccall((:wgpuInstanceRequestAdapter, libWGPU), Cvoid, (WGPUInstance, Ptr{WGPURequestAdapterOptions}, WGPURequestAdapterCallback, Ptr{Cvoid}), instance, options, callback, userdata) end function wgpuInstanceReference(instance) ccall((:wgpuInstanceReference, libWGPU), Cvoid, (WGPUInstance,), instance) end function wgpuInstanceRelease(instance) ccall((:wgpuInstanceRelease, libWGPU), Cvoid, (WGPUInstance,), instance) end function wgpuPipelineLayoutSetLabel(pipelineLayout, label) ccall((:wgpuPipelineLayoutSetLabel, libWGPU), Cvoid, (WGPUPipelineLayout, Ptr{Cchar}), pipelineLayout, label) end function wgpuPipelineLayoutReference(pipelineLayout) ccall((:wgpuPipelineLayoutReference, libWGPU), Cvoid, (WGPUPipelineLayout,), pipelineLayout) end function wgpuPipelineLayoutRelease(pipelineLayout) ccall((:wgpuPipelineLayoutRelease, libWGPU), Cvoid, (WGPUPipelineLayout,), pipelineLayout) end function wgpuQuerySetDestroy(querySet) ccall((:wgpuQuerySetDestroy, libWGPU), Cvoid, (WGPUQuerySet,), querySet) end function wgpuQuerySetGetCount(querySet) ccall((:wgpuQuerySetGetCount, libWGPU), UInt32, (WGPUQuerySet,), querySet) end function wgpuQuerySetGetType(querySet) ccall((:wgpuQuerySetGetType, libWGPU), WGPUQueryType, (WGPUQuerySet,), querySet) end function wgpuQuerySetSetLabel(querySet, label) ccall((:wgpuQuerySetSetLabel, libWGPU), Cvoid, (WGPUQuerySet, Ptr{Cchar}), querySet, label) end function wgpuQuerySetReference(querySet) ccall((:wgpuQuerySetReference, libWGPU), Cvoid, (WGPUQuerySet,), querySet) end function wgpuQuerySetRelease(querySet) ccall((:wgpuQuerySetRelease, libWGPU), Cvoid, (WGPUQuerySet,), querySet) end function wgpuQueueOnSubmittedWorkDone(queue, callback, userdata) ccall((:wgpuQueueOnSubmittedWorkDone, libWGPU), Cvoid, (WGPUQueue, WGPUQueueWorkDoneCallback, Ptr{Cvoid}), queue, callback, userdata) end function wgpuQueueSetLabel(queue, label) ccall((:wgpuQueueSetLabel, libWGPU), Cvoid, (WGPUQueue, Ptr{Cchar}), queue, label) end function wgpuQueueSubmit(queue, commandCount, commands) ccall((:wgpuQueueSubmit, libWGPU), Cvoid, (WGPUQueue, Csize_t, Ptr{WGPUCommandBuffer}), queue, commandCount, commands) end function wgpuQueueWriteBuffer(queue, buffer, bufferOffset, data, size) ccall((:wgpuQueueWriteBuffer, libWGPU), Cvoid, (WGPUQueue, WGPUBuffer, UInt64, Ptr{Cvoid}, Csize_t), queue, buffer, bufferOffset, data, size) end function wgpuQueueWriteTexture(queue, destination, data, dataSize, dataLayout, writeSize) ccall((:wgpuQueueWriteTexture, libWGPU), Cvoid, (WGPUQueue, Ptr{WGPUImageCopyTexture}, Ptr{Cvoid}, Csize_t, Ptr{WGPUTextureDataLayout}, Ptr{WGPUExtent3D}), queue, destination, data, dataSize, dataLayout, writeSize) end function wgpuQueueReference(queue) ccall((:wgpuQueueReference, libWGPU), Cvoid, (WGPUQueue,), queue) end function wgpuQueueRelease(queue) ccall((:wgpuQueueRelease, libWGPU), Cvoid, (WGPUQueue,), queue) end function wgpuRenderBundleSetLabel(renderBundle, label) ccall((:wgpuRenderBundleSetLabel, libWGPU), Cvoid, (WGPURenderBundle, Ptr{Cchar}), renderBundle, label) end function wgpuRenderBundleReference(renderBundle) ccall((:wgpuRenderBundleReference, libWGPU), Cvoid, (WGPURenderBundle,), renderBundle) end function wgpuRenderBundleRelease(renderBundle) ccall((:wgpuRenderBundleRelease, libWGPU), Cvoid, (WGPURenderBundle,), renderBundle) end function wgpuRenderBundleEncoderDraw(renderBundleEncoder, vertexCount, instanceCount, firstVertex, firstInstance) ccall((:wgpuRenderBundleEncoderDraw, libWGPU), Cvoid, (WGPURenderBundleEncoder, UInt32, UInt32, UInt32, UInt32), renderBundleEncoder, vertexCount, instanceCount, firstVertex, firstInstance) end function wgpuRenderBundleEncoderDrawIndexed(renderBundleEncoder, indexCount, instanceCount, firstIndex, baseVertex, firstInstance) ccall((:wgpuRenderBundleEncoderDrawIndexed, libWGPU), Cvoid, (WGPURenderBundleEncoder, UInt32, UInt32, UInt32, Int32, UInt32), renderBundleEncoder, indexCount, instanceCount, firstIndex, baseVertex, firstInstance) end function wgpuRenderBundleEncoderDrawIndexedIndirect(renderBundleEncoder, indirectBuffer, indirectOffset) ccall((:wgpuRenderBundleEncoderDrawIndexedIndirect, libWGPU), Cvoid, (WGPURenderBundleEncoder, WGPUBuffer, UInt64), renderBundleEncoder, indirectBuffer, indirectOffset) end function wgpuRenderBundleEncoderDrawIndirect(renderBundleEncoder, indirectBuffer, indirectOffset) ccall((:wgpuRenderBundleEncoderDrawIndirect, libWGPU), Cvoid, (WGPURenderBundleEncoder, WGPUBuffer, UInt64), renderBundleEncoder, indirectBuffer, indirectOffset) end function wgpuRenderBundleEncoderFinish(renderBundleEncoder, descriptor) ccall((:wgpuRenderBundleEncoderFinish, libWGPU), WGPURenderBundle, (WGPURenderBundleEncoder, Ptr{WGPURenderBundleDescriptor}), renderBundleEncoder, descriptor) end function wgpuRenderBundleEncoderInsertDebugMarker(renderBundleEncoder, markerLabel) ccall((:wgpuRenderBundleEncoderInsertDebugMarker, libWGPU), Cvoid, (WGPURenderBundleEncoder, Ptr{Cchar}), renderBundleEncoder, markerLabel) end function wgpuRenderBundleEncoderPopDebugGroup(renderBundleEncoder) ccall((:wgpuRenderBundleEncoderPopDebugGroup, libWGPU), Cvoid, (WGPURenderBundleEncoder,), renderBundleEncoder) end function wgpuRenderBundleEncoderPushDebugGroup(renderBundleEncoder, groupLabel) ccall((:wgpuRenderBundleEncoderPushDebugGroup, libWGPU), Cvoid, (WGPURenderBundleEncoder, Ptr{Cchar}), renderBundleEncoder, groupLabel) end function wgpuRenderBundleEncoderSetBindGroup(renderBundleEncoder, groupIndex, group, dynamicOffsetCount, dynamicOffsets) ccall((:wgpuRenderBundleEncoderSetBindGroup, libWGPU), Cvoid, (WGPURenderBundleEncoder, UInt32, WGPUBindGroup, Csize_t, Ptr{UInt32}), renderBundleEncoder, groupIndex, group, dynamicOffsetCount, dynamicOffsets) end function wgpuRenderBundleEncoderSetIndexBuffer(renderBundleEncoder, buffer, format, offset, size) ccall((:wgpuRenderBundleEncoderSetIndexBuffer, libWGPU), Cvoid, (WGPURenderBundleEncoder, WGPUBuffer, WGPUIndexFormat, UInt64, UInt64), renderBundleEncoder, buffer, format, offset, size) end function wgpuRenderBundleEncoderSetLabel(renderBundleEncoder, label) ccall((:wgpuRenderBundleEncoderSetLabel, libWGPU), Cvoid, (WGPURenderBundleEncoder, Ptr{Cchar}), renderBundleEncoder, label) end function wgpuRenderBundleEncoderSetPipeline(renderBundleEncoder, pipeline) ccall((:wgpuRenderBundleEncoderSetPipeline, libWGPU), Cvoid, (WGPURenderBundleEncoder, WGPURenderPipeline), renderBundleEncoder, pipeline) end function wgpuRenderBundleEncoderSetVertexBuffer(renderBundleEncoder, slot, buffer, offset, size) ccall((:wgpuRenderBundleEncoderSetVertexBuffer, libWGPU), Cvoid, (WGPURenderBundleEncoder, UInt32, WGPUBuffer, UInt64, UInt64), renderBundleEncoder, slot, buffer, offset, size) end function wgpuRenderBundleEncoderReference(renderBundleEncoder) ccall((:wgpuRenderBundleEncoderReference, libWGPU), Cvoid, (WGPURenderBundleEncoder,), renderBundleEncoder) end function wgpuRenderBundleEncoderRelease(renderBundleEncoder) ccall((:wgpuRenderBundleEncoderRelease, libWGPU), Cvoid, (WGPURenderBundleEncoder,), renderBundleEncoder) end function wgpuRenderPassEncoderBeginOcclusionQuery(renderPassEncoder, queryIndex) ccall((:wgpuRenderPassEncoderBeginOcclusionQuery, libWGPU), Cvoid, (WGPURenderPassEncoder, UInt32), renderPassEncoder, queryIndex) end function wgpuRenderPassEncoderDraw(renderPassEncoder, vertexCount, instanceCount, firstVertex, firstInstance) ccall((:wgpuRenderPassEncoderDraw, libWGPU), Cvoid, (WGPURenderPassEncoder, UInt32, UInt32, UInt32, UInt32), renderPassEncoder, vertexCount, instanceCount, firstVertex, firstInstance) end function wgpuRenderPassEncoderDrawIndexed(renderPassEncoder, indexCount, instanceCount, firstIndex, baseVertex, firstInstance) ccall((:wgpuRenderPassEncoderDrawIndexed, libWGPU), Cvoid, (WGPURenderPassEncoder, UInt32, UInt32, UInt32, Int32, UInt32), renderPassEncoder, indexCount, instanceCount, firstIndex, baseVertex, firstInstance) end function wgpuRenderPassEncoderDrawIndexedIndirect(renderPassEncoder, indirectBuffer, indirectOffset) ccall((:wgpuRenderPassEncoderDrawIndexedIndirect, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPUBuffer, UInt64), renderPassEncoder, indirectBuffer, indirectOffset) end function wgpuRenderPassEncoderDrawIndirect(renderPassEncoder, indirectBuffer, indirectOffset) ccall((:wgpuRenderPassEncoderDrawIndirect, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPUBuffer, UInt64), renderPassEncoder, indirectBuffer, indirectOffset) end function wgpuRenderPassEncoderEnd(renderPassEncoder) ccall((:wgpuRenderPassEncoderEnd, libWGPU), Cvoid, (WGPURenderPassEncoder,), renderPassEncoder) end function wgpuRenderPassEncoderEndOcclusionQuery(renderPassEncoder) ccall((:wgpuRenderPassEncoderEndOcclusionQuery, libWGPU), Cvoid, (WGPURenderPassEncoder,), renderPassEncoder) end function wgpuRenderPassEncoderExecuteBundles(renderPassEncoder, bundleCount, bundles) ccall((:wgpuRenderPassEncoderExecuteBundles, libWGPU), Cvoid, (WGPURenderPassEncoder, Csize_t, Ptr{WGPURenderBundle}), renderPassEncoder, bundleCount, bundles) end function wgpuRenderPassEncoderInsertDebugMarker(renderPassEncoder, markerLabel) ccall((:wgpuRenderPassEncoderInsertDebugMarker, libWGPU), Cvoid, (WGPURenderPassEncoder, Ptr{Cchar}), renderPassEncoder, markerLabel) end function wgpuRenderPassEncoderPopDebugGroup(renderPassEncoder) ccall((:wgpuRenderPassEncoderPopDebugGroup, libWGPU), Cvoid, (WGPURenderPassEncoder,), renderPassEncoder) end function wgpuRenderPassEncoderPushDebugGroup(renderPassEncoder, groupLabel) ccall((:wgpuRenderPassEncoderPushDebugGroup, libWGPU), Cvoid, (WGPURenderPassEncoder, Ptr{Cchar}), renderPassEncoder, groupLabel) end function wgpuRenderPassEncoderSetBindGroup(renderPassEncoder, groupIndex, group, dynamicOffsetCount, dynamicOffsets) ccall((:wgpuRenderPassEncoderSetBindGroup, libWGPU), Cvoid, (WGPURenderPassEncoder, UInt32, WGPUBindGroup, Csize_t, Ptr{UInt32}), renderPassEncoder, groupIndex, group, dynamicOffsetCount, dynamicOffsets) end function wgpuRenderPassEncoderSetBlendConstant(renderPassEncoder, color) ccall((:wgpuRenderPassEncoderSetBlendConstant, libWGPU), Cvoid, (WGPURenderPassEncoder, Ptr{WGPUColor}), renderPassEncoder, color) end function wgpuRenderPassEncoderSetIndexBuffer(renderPassEncoder, buffer, format, offset, size) ccall((:wgpuRenderPassEncoderSetIndexBuffer, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPUBuffer, WGPUIndexFormat, UInt64, UInt64), renderPassEncoder, buffer, format, offset, size) end function wgpuRenderPassEncoderSetLabel(renderPassEncoder, label) ccall((:wgpuRenderPassEncoderSetLabel, libWGPU), Cvoid, (WGPURenderPassEncoder, Ptr{Cchar}), renderPassEncoder, label) end function wgpuRenderPassEncoderSetPipeline(renderPassEncoder, pipeline) ccall((:wgpuRenderPassEncoderSetPipeline, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPURenderPipeline), renderPassEncoder, pipeline) end function wgpuRenderPassEncoderSetScissorRect(renderPassEncoder, x, y, width, height) ccall((:wgpuRenderPassEncoderSetScissorRect, libWGPU), Cvoid, (WGPURenderPassEncoder, UInt32, UInt32, UInt32, UInt32), renderPassEncoder, x, y, width, height) end function wgpuRenderPassEncoderSetStencilReference(renderPassEncoder, reference) ccall((:wgpuRenderPassEncoderSetStencilReference, libWGPU), Cvoid, (WGPURenderPassEncoder, UInt32), renderPassEncoder, reference) end function wgpuRenderPassEncoderSetVertexBuffer(renderPassEncoder, slot, buffer, offset, size) ccall((:wgpuRenderPassEncoderSetVertexBuffer, libWGPU), Cvoid, (WGPURenderPassEncoder, UInt32, WGPUBuffer, UInt64, UInt64), renderPassEncoder, slot, buffer, offset, size) end function wgpuRenderPassEncoderSetViewport(renderPassEncoder, x, y, width, height, minDepth, maxDepth) ccall((:wgpuRenderPassEncoderSetViewport, libWGPU), Cvoid, (WGPURenderPassEncoder, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat, Cfloat), renderPassEncoder, x, y, width, height, minDepth, maxDepth) end function wgpuRenderPassEncoderReference(renderPassEncoder) ccall((:wgpuRenderPassEncoderReference, libWGPU), Cvoid, (WGPURenderPassEncoder,), renderPassEncoder) end function wgpuRenderPassEncoderRelease(renderPassEncoder) ccall((:wgpuRenderPassEncoderRelease, libWGPU), Cvoid, (WGPURenderPassEncoder,), renderPassEncoder) end function wgpuRenderPipelineGetBindGroupLayout(renderPipeline, groupIndex) ccall((:wgpuRenderPipelineGetBindGroupLayout, libWGPU), WGPUBindGroupLayout, (WGPURenderPipeline, UInt32), renderPipeline, groupIndex) end function wgpuRenderPipelineSetLabel(renderPipeline, label) ccall((:wgpuRenderPipelineSetLabel, libWGPU), Cvoid, (WGPURenderPipeline, Ptr{Cchar}), renderPipeline, label) end function wgpuRenderPipelineReference(renderPipeline) ccall((:wgpuRenderPipelineReference, libWGPU), Cvoid, (WGPURenderPipeline,), renderPipeline) end function wgpuRenderPipelineRelease(renderPipeline) ccall((:wgpuRenderPipelineRelease, libWGPU), Cvoid, (WGPURenderPipeline,), renderPipeline) end function wgpuSamplerSetLabel(sampler, label) ccall((:wgpuSamplerSetLabel, libWGPU), Cvoid, (WGPUSampler, Ptr{Cchar}), sampler, label) end function wgpuSamplerReference(sampler) ccall((:wgpuSamplerReference, libWGPU), Cvoid, (WGPUSampler,), sampler) end function wgpuSamplerRelease(sampler) ccall((:wgpuSamplerRelease, libWGPU), Cvoid, (WGPUSampler,), sampler) end function wgpuShaderModuleGetCompilationInfo(shaderModule, callback, userdata) ccall((:wgpuShaderModuleGetCompilationInfo, libWGPU), Cvoid, (WGPUShaderModule, WGPUCompilationInfoCallback, Ptr{Cvoid}), shaderModule, callback, userdata) end function wgpuShaderModuleSetLabel(shaderModule, label) ccall((:wgpuShaderModuleSetLabel, libWGPU), Cvoid, (WGPUShaderModule, Ptr{Cchar}), shaderModule, label) end function wgpuShaderModuleReference(shaderModule) ccall((:wgpuShaderModuleReference, libWGPU), Cvoid, (WGPUShaderModule,), shaderModule) end function wgpuShaderModuleRelease(shaderModule) ccall((:wgpuShaderModuleRelease, libWGPU), Cvoid, (WGPUShaderModule,), shaderModule) end function wgpuSurfaceConfigure(surface, config) ccall((:wgpuSurfaceConfigure, libWGPU), Cvoid, (WGPUSurface, Ptr{WGPUSurfaceConfiguration}), surface, config) end function wgpuSurfaceGetCapabilities(surface, adapter, capabilities) ccall((:wgpuSurfaceGetCapabilities, libWGPU), Cvoid, (WGPUSurface, WGPUAdapter, Ptr{WGPUSurfaceCapabilities}), surface, adapter, capabilities) end function wgpuSurfaceGetCurrentTexture(surface, surfaceTexture) ccall((:wgpuSurfaceGetCurrentTexture, libWGPU), Cvoid, (WGPUSurface, Ptr{WGPUSurfaceTexture}), surface, surfaceTexture) end function wgpuSurfaceGetPreferredFormat(surface, adapter) ccall((:wgpuSurfaceGetPreferredFormat, libWGPU), WGPUTextureFormat, (WGPUSurface, WGPUAdapter), surface, adapter) end function wgpuSurfacePresent(surface) ccall((:wgpuSurfacePresent, libWGPU), Cvoid, (WGPUSurface,), surface) end function wgpuSurfaceUnconfigure(surface) ccall((:wgpuSurfaceUnconfigure, libWGPU), Cvoid, (WGPUSurface,), surface) end function wgpuSurfaceReference(surface) ccall((:wgpuSurfaceReference, libWGPU), Cvoid, (WGPUSurface,), surface) end function wgpuSurfaceRelease(surface) ccall((:wgpuSurfaceRelease, libWGPU), Cvoid, (WGPUSurface,), surface) end function wgpuSurfaceCapabilitiesFreeMembers(capabilities) ccall((:wgpuSurfaceCapabilitiesFreeMembers, libWGPU), Cvoid, (WGPUSurfaceCapabilities,), capabilities) end function wgpuTextureCreateView(texture, descriptor) ccall((:wgpuTextureCreateView, libWGPU), WGPUTextureView, (WGPUTexture, Ptr{WGPUTextureViewDescriptor}), texture, descriptor) end function wgpuTextureDestroy(texture) ccall((:wgpuTextureDestroy, libWGPU), Cvoid, (WGPUTexture,), texture) end function wgpuTextureGetDepthOrArrayLayers(texture) ccall((:wgpuTextureGetDepthOrArrayLayers, libWGPU), UInt32, (WGPUTexture,), texture) end function wgpuTextureGetDimension(texture) ccall((:wgpuTextureGetDimension, libWGPU), WGPUTextureDimension, (WGPUTexture,), texture) end function wgpuTextureGetFormat(texture) ccall((:wgpuTextureGetFormat, libWGPU), WGPUTextureFormat, (WGPUTexture,), texture) end function wgpuTextureGetHeight(texture) ccall((:wgpuTextureGetHeight, libWGPU), UInt32, (WGPUTexture,), texture) end function wgpuTextureGetMipLevelCount(texture) ccall((:wgpuTextureGetMipLevelCount, libWGPU), UInt32, (WGPUTexture,), texture) end function wgpuTextureGetSampleCount(texture) ccall((:wgpuTextureGetSampleCount, libWGPU), UInt32, (WGPUTexture,), texture) end function wgpuTextureGetUsage(texture) ccall((:wgpuTextureGetUsage, libWGPU), WGPUTextureUsageFlags, (WGPUTexture,), texture) end function wgpuTextureGetWidth(texture) ccall((:wgpuTextureGetWidth, libWGPU), UInt32, (WGPUTexture,), texture) end function wgpuTextureSetLabel(texture, label) ccall((:wgpuTextureSetLabel, libWGPU), Cvoid, (WGPUTexture, Ptr{Cchar}), texture, label) end function wgpuTextureReference(texture) ccall((:wgpuTextureReference, libWGPU), Cvoid, (WGPUTexture,), texture) end function wgpuTextureRelease(texture) ccall((:wgpuTextureRelease, libWGPU), Cvoid, (WGPUTexture,), texture) end function wgpuTextureViewSetLabel(textureView, label) ccall((:wgpuTextureViewSetLabel, libWGPU), Cvoid, (WGPUTextureView, Ptr{Cchar}), textureView, label) end function wgpuTextureViewReference(textureView) ccall((:wgpuTextureViewReference, libWGPU), Cvoid, (WGPUTextureView,), textureView) end function wgpuTextureViewRelease(textureView) ccall((:wgpuTextureViewRelease, libWGPU), Cvoid, (WGPUTextureView,), textureView) end @cenum WGPUNativeSType::UInt32 begin WGPUSType_DeviceExtras = 196609 WGPUSType_RequiredLimitsExtras = 196610 WGPUSType_PipelineLayoutExtras = 196611 WGPUSType_ShaderModuleGLSLDescriptor = 196612 WGPUSType_SupportedLimitsExtras = 196613 WGPUSType_InstanceExtras = 196614 WGPUSType_BindGroupEntryExtras = 196615 WGPUSType_BindGroupLayoutEntryExtras = 196616 WGPUSType_QuerySetDescriptorExtras = 196617 WGPUSType_SurfaceConfigurationExtras = 196618 WGPUNativeSType_Force32 = 2147483647 end @cenum WGPUNativeFeature::UInt32 begin WGPUNativeFeature_PushConstants = 196609 WGPUNativeFeature_TextureAdapterSpecificFormatFeatures = 196610 WGPUNativeFeature_MultiDrawIndirect = 196611 WGPUNativeFeature_MultiDrawIndirectCount = 196612 WGPUNativeFeature_VertexWritableStorage = 196613 WGPUNativeFeature_TextureBindingArray = 196614 WGPUNativeFeature_SampledTextureAndStorageBufferArrayNonUniformIndexing = 196615 WGPUNativeFeature_PipelineStatisticsQuery = 196616 WGPUNativeFeature_Force32 = 2147483647 end @cenum WGPULogLevel::UInt32 begin WGPULogLevel_Off = 0 WGPULogLevel_Error = 1 WGPULogLevel_Warn = 2 WGPULogLevel_Info = 3 WGPULogLevel_Debug = 4 WGPULogLevel_Trace = 5 WGPULogLevel_Force32 = 2147483647 end @cenum WGPUInstanceBackend::UInt32 begin WGPUInstanceBackend_All = 0 WGPUInstanceBackend_Vulkan = 1 WGPUInstanceBackend_GL = 2 WGPUInstanceBackend_Metal = 4 WGPUInstanceBackend_DX12 = 8 WGPUInstanceBackend_DX11 = 16 WGPUInstanceBackend_BrowserWebGPU = 32 WGPUInstanceBackend_Primary = 45 WGPUInstanceBackend_Secondary = 18 WGPUInstanceBackend_Force32 = 2147483647 end const WGPUInstanceBackendFlags = WGPUFlags @cenum WGPUInstanceFlag::UInt32 begin WGPUInstanceFlag_Default = 0 WGPUInstanceFlag_Debug = 1 WGPUInstanceFlag_Validation = 2 WGPUInstanceFlag_DiscardHalLabels = 4 WGPUInstanceFlag_Force32 = 2147483647 end const WGPUInstanceFlags = WGPUFlags @cenum WGPUDx12Compiler::UInt32 begin WGPUDx12Compiler_Undefined = 0 WGPUDx12Compiler_Fxc = 1 WGPUDx12Compiler_Dxc = 2 WGPUDx12Compiler_Force32 = 2147483647 end @cenum WGPUGles3MinorVersion::UInt32 begin WGPUGles3MinorVersion_Automatic = 0 WGPUGles3MinorVersion_Version0 = 1 WGPUGles3MinorVersion_Version1 = 2 WGPUGles3MinorVersion_Version2 = 3 WGPUGles3MinorVersion_Force32 = 2147483647 end @cenum WGPUPipelineStatisticName::UInt32 begin WGPUPipelineStatisticName_VertexShaderInvocations = 0 WGPUPipelineStatisticName_ClipperInvocations = 1 WGPUPipelineStatisticName_ClipperPrimitivesOut = 2 WGPUPipelineStatisticName_FragmentShaderInvocations = 3 WGPUPipelineStatisticName_ComputeShaderInvocations = 4 WGPUPipelineStatisticName_Force32 = 2147483647 end @cenum WGPUNativeQueryType::UInt32 begin WGPUNativeQueryType_PipelineStatistics = 196608 WGPUNativeQueryType_Force32 = 2147483647 end struct WGPUInstanceExtras chain::WGPUChainedStruct backends::WGPUInstanceBackendFlags flags::WGPUInstanceFlags dx12ShaderCompiler::WGPUDx12Compiler gles3MinorVersion::WGPUGles3MinorVersion dxilPath::Ptr{Cchar} dxcPath::Ptr{Cchar} end struct WGPUDeviceExtras chain::WGPUChainedStruct tracePath::Ptr{Cchar} end struct WGPUNativeLimits maxPushConstantSize::UInt32 maxNonSamplerBindings::UInt32 end struct WGPURequiredLimitsExtras chain::WGPUChainedStruct limits::WGPUNativeLimits end struct WGPUSupportedLimitsExtras chain::WGPUChainedStructOut limits::WGPUNativeLimits end struct WGPUPushConstantRange stages::WGPUShaderStageFlags start::UInt32 _end::UInt32 end struct WGPUPipelineLayoutExtras chain::WGPUChainedStruct pushConstantRangeCount::Csize_t pushConstantRanges::Ptr{WGPUPushConstantRange} end const WGPUSubmissionIndex = UInt64 struct WGPUWrappedSubmissionIndex queue::WGPUQueue submissionIndex::WGPUSubmissionIndex end struct WGPUShaderDefine name::Ptr{Cchar} value::Ptr{Cchar} end struct WGPUShaderModuleGLSLDescriptor chain::WGPUChainedStruct stage::WGPUShaderStage code::Ptr{Cchar} defineCount::UInt32 defines::Ptr{WGPUShaderDefine} end struct WGPURegistryReport numAllocated::Csize_t numKeptFromUser::Csize_t numReleasedFromUser::Csize_t numError::Csize_t elementSize::Csize_t end struct WGPUHubReport adapters::WGPURegistryReport devices::WGPURegistryReport queues::WGPURegistryReport pipelineLayouts::WGPURegistryReport shaderModules::WGPURegistryReport bindGroupLayouts::WGPURegistryReport bindGroups::WGPURegistryReport commandBuffers::WGPURegistryReport renderBundles::WGPURegistryReport renderPipelines::WGPURegistryReport computePipelines::WGPURegistryReport querySets::WGPURegistryReport buffers::WGPURegistryReport textures::WGPURegistryReport textureViews::WGPURegistryReport samplers::WGPURegistryReport end struct WGPUGlobalReport surfaces::WGPURegistryReport backendType::WGPUBackendType vulkan::WGPUHubReport metal::WGPUHubReport dx12::WGPUHubReport gl::WGPUHubReport end struct WGPUInstanceEnumerateAdapterOptions nextInChain::Ptr{WGPUChainedStruct} backends::WGPUInstanceBackendFlags end struct WGPUBindGroupEntryExtras chain::WGPUChainedStruct buffers::Ptr{WGPUBuffer} bufferCount::Csize_t samplers::Ptr{WGPUSampler} samplerCount::Csize_t textureViews::Ptr{WGPUTextureView} textureViewCount::Csize_t end struct WGPUBindGroupLayoutEntryExtras chain::WGPUChainedStruct count::UInt32 end struct WGPUQuerySetDescriptorExtras chain::WGPUChainedStruct pipelineStatistics::Ptr{WGPUPipelineStatisticName} pipelineStatisticCount::Csize_t end struct WGPUSurfaceConfigurationExtras chain::WGPUChainedStruct desiredMaximumFrameLatency::WGPUBool end # typedef void ( * WGPULogCallback ) ( WGPULogLevel level , char const * message , void * userdata ) const WGPULogCallback = Ptr{Cvoid} function wgpuGenerateReport(instance, report) ccall((:wgpuGenerateReport, libWGPU), Cvoid, (WGPUInstance, Ptr{WGPUGlobalReport}), instance, report) end function wgpuInstanceEnumerateAdapters(instance, options, adapters) ccall((:wgpuInstanceEnumerateAdapters, libWGPU), Csize_t, (WGPUInstance, Ptr{WGPUInstanceEnumerateAdapterOptions}, Ptr{WGPUAdapter}), instance, options, adapters) end function wgpuQueueSubmitForIndex(queue, commandCount, commands) ccall((:wgpuQueueSubmitForIndex, libWGPU), WGPUSubmissionIndex, (WGPUQueue, Csize_t, Ptr{WGPUCommandBuffer}), queue, commandCount, commands) end function wgpuDevicePoll(device, wait, wrappedSubmissionIndex) ccall((:wgpuDevicePoll, libWGPU), WGPUBool, (WGPUDevice, WGPUBool, Ptr{WGPUWrappedSubmissionIndex}), device, wait, wrappedSubmissionIndex) end function wgpuSetLogCallback(callback, userdata) ccall((:wgpuSetLogCallback, libWGPU), Cvoid, (WGPULogCallback, Ptr{Cvoid}), callback, userdata) end function wgpuSetLogLevel(level) ccall((:wgpuSetLogLevel, libWGPU), Cvoid, (WGPULogLevel,), level) end function wgpuGetVersion() ccall((:wgpuGetVersion, libWGPU), UInt32, ()) end function wgpuRenderPassEncoderSetPushConstants(encoder, stages, offset, sizeBytes, data) ccall((:wgpuRenderPassEncoderSetPushConstants, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPUShaderStageFlags, UInt32, UInt32, Ptr{Cvoid}), encoder, stages, offset, sizeBytes, data) end function wgpuRenderPassEncoderMultiDrawIndirect(encoder, buffer, offset, count) ccall((:wgpuRenderPassEncoderMultiDrawIndirect, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPUBuffer, UInt64, UInt32), encoder, buffer, offset, count) end function wgpuRenderPassEncoderMultiDrawIndexedIndirect(encoder, buffer, offset, count) ccall((:wgpuRenderPassEncoderMultiDrawIndexedIndirect, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPUBuffer, UInt64, UInt32), encoder, buffer, offset, count) end function wgpuRenderPassEncoderMultiDrawIndirectCount(encoder, buffer, offset, count_buffer, count_buffer_offset, max_count) ccall((:wgpuRenderPassEncoderMultiDrawIndirectCount, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPUBuffer, UInt64, WGPUBuffer, UInt64, UInt32), encoder, buffer, offset, count_buffer, count_buffer_offset, max_count) end function wgpuRenderPassEncoderMultiDrawIndexedIndirectCount(encoder, buffer, offset, count_buffer, count_buffer_offset, max_count) ccall((:wgpuRenderPassEncoderMultiDrawIndexedIndirectCount, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPUBuffer, UInt64, WGPUBuffer, UInt64, UInt32), encoder, buffer, offset, count_buffer, count_buffer_offset, max_count) end function wgpuComputePassEncoderBeginPipelineStatisticsQuery(computePassEncoder, querySet, queryIndex) ccall((:wgpuComputePassEncoderBeginPipelineStatisticsQuery, libWGPU), Cvoid, (WGPUComputePassEncoder, WGPUQuerySet, UInt32), computePassEncoder, querySet, queryIndex) end function wgpuComputePassEncoderEndPipelineStatisticsQuery(computePassEncoder) ccall((:wgpuComputePassEncoderEndPipelineStatisticsQuery, libWGPU), Cvoid, (WGPUComputePassEncoder,), computePassEncoder) end function wgpuRenderPassEncoderBeginPipelineStatisticsQuery(renderPassEncoder, querySet, queryIndex) ccall((:wgpuRenderPassEncoderBeginPipelineStatisticsQuery, libWGPU), Cvoid, (WGPURenderPassEncoder, WGPUQuerySet, UInt32), renderPassEncoder, querySet, queryIndex) end function wgpuRenderPassEncoderEndPipelineStatisticsQuery(renderPassEncoder) ccall((:wgpuRenderPassEncoderEndPipelineStatisticsQuery, libWGPU), Cvoid, (WGPURenderPassEncoder,), renderPassEncoder) end const WGPU_ARRAY_LAYER_COUNT_UNDEFINED = Culong(0xffffffff) const WGPU_COPY_STRIDE_UNDEFINED = Culong(0xffffffff) const WGPU_LIMIT_U32_UNDEFINED = Culong(0xffffffff) const WGPU_LIMIT_U64_UNDEFINED = Culonglong(0xffffffffffffffff) const WGPU_MIP_LEVEL_COUNT_UNDEFINED = Culong(0xffffffff) const WGPU_QUERY_SET_INDEX_UNDEFINED = Culong(0xffffffff) const WGPU_WHOLE_MAP_SIZE = SIZE_MAX const WGPU_WHOLE_SIZE = Culonglong(0xffffffffffffffff) # exports const PREFIXES = ["WGPU", "wgpu"] for name in names(@__MODULE__; all=true), prefix in PREFIXES if startswith(string(name), prefix) @eval export $name end end end # module
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
130
module WGPUNative using Reexport include("cUtils.jl") include("LibWGPU.jl") @reexport using .LibWGPU @reexport using .CUtils end
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
code
3198
module CUtils export CStruct, cStruct, ptr, concrete, rawCast, cast, toCString, fromCString, toByteArray mutable struct CStruct{T} ptr::Ptr{T} function CStruct(cStructType::DataType) csPtr = Libc.calloc(sizeof(cStructType), sizeof(UInt8)) # f(x) = begin # @info "Destroying CStruct `$x`" # ptr = getfield(x, :ptr) # Libc.free(ptr) # setfield!(x, :ptr, typeof(ptr)(0)) # end obj = new{cStructType}(csPtr) # finalizer(f, obj) return obj end function CStruct(cptr::Ptr{T}) where T # f(x) = begin # @info "Destroying CStruct `$x`" # ptr = getfield(x, :ptr) # Libc.free(ptr) # setfield!(x, :ptr, typeof(ptr)(0)) # end obj = new{T}(csPtr) # finalizer(f, obj) return obj end end function cStructFree(cstruct::CStruct{T}) where T ptr = getfield(cstruct, :ptr) Libc.free(ptr) end function indirectionToField(cstruct::CStruct{T}, x::Symbol) where T fieldIdx::Int64 = Base.fieldindex(T, x) fieldOffset = Base.fieldoffset(T, fieldIdx) fieldType = Base.fieldtype(T, fieldIdx) fieldSize = fieldType |> sizeof offsetptr = getfield(cstruct, :ptr) + fieldOffset field = convert(Ptr{fieldType}, offsetptr) end function Base.getproperty(cstruct::CStruct{T}, x::Symbol) where T unsafe_load(indirectionToField(cstruct, x), 1) end function Base.setproperty!(cstruct::CStruct{T}, x::Symbol, v) where T field = indirectionToField(cstruct, x) unsafe_store!(field, v) end function rawCast(DType::DataType, cs::CStruct{T}) where {T} convert(Ptr{DType}, getfield(cs, :ptr)) end function cast(DType::DataType, cs::CStruct{T}) where {T} CStruct(rawCast(DType, cs)) end ptr(cs::CStruct{T}) where T = getfield(cs, :ptr) # TODO this is not working right now # left it because its not priority. # Can always use getfield # function Base.getproperty(cstruct::CStruct{T}, x::Val{:ptr}) where T # getfield(cstruct, :ptr) # end function cStruct(ctype::DataType; fields...) cs = CStruct(ctype) inPairs = pairs(fields) for field in keys(inPairs) if field in fieldnames(ctype) setproperty!(cs, field, inPairs[field]) else @warn """ CStruct : Setting property of non member field. \n Trying to set non member field `$field`. only supported fieldnames for `$ctype` are $(fieldnames(ctype)) """ end end return cs end function cStructPtr(ctype::DataType; fields...) return ptr(cStruct(ctype; fields...)) end function concrete(cstruct::CStruct{T}) where T return cstruct |> ptr |> unsafe_load end function toCString(s::String) sNullTerminated = s*"\0" sPtr = pointer(sNullTerminated) dPtr = Libc.malloc(sizeof(sNullTerminated)) dUInt8Ptr = convert(Ptr{UInt8}, dPtr) unsafe_copyto!(dUInt8Ptr, sPtr, sizeof(sNullTerminated)) end function fromCString(s::Ptr{Int8}) s != C_NULL ? unsafe_string(s) : "" end Base.sizeof(cstruct::CStruct{T}) where T = sizeof(T) function toByteArray(cstruct::CStruct{T}) where T bytePtr = convert(Ptr{UInt8}, cstruct |> ptr) unsafe_wrap(Array, bytePtr, sizeof(cstruct)) end #Base.fieldnames(::Type{CStruct{T}}) where T = Base.fieldnames(T) Base.propertynames(a::CStruct{T}) where T = Base.fieldnames(T) end
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.4
2c4204585df32fe31eaa9ea346ed469f844996b1
docs
483
[![Aqua QA](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl) # WGPUNative.jl WGPU (wgpu-native) julia bindings Supports following architectures * `macOS aarch64` (`aarch64-apple-darwin`) * `Linux aarch64 {libc=glibc}` (`aarch64-linux-gnu`) * `Windows i686` (`i686-w64-mingw32`) * `macOS x86_64` (`x86_64-apple-darwin`) * `Linux x86_64 {libc=glibc}` (`x86_64-linux-gnu`) * `Windows x86_64` (`x86_64-w64-mingw32`)
WGPUNative
https://github.com/JuliaWGPU/WGPUNative.jl.git
[ "MIT" ]
0.1.0
cdbebbe5815426ea98b195f252d7bd83f31fad2e
code
700
using Cxx const path_to_lib = dirname(@__FILE__()) addHeaderDir(path_to_lib, kind=C_System) # Compiling lastools.so is left as an exercise to the reader Libdl.dlopen(path_to_lib * "/lastools.so", Libdl.RTLD_GLOBAL) cxxinclude("~/git/LAStools/LASlib/inc/lasreader_txt.hpp") # random header # Read .laz file a = @cxxnew LASreadOpener() @cxx a -> set_file_name(pointer("~/01608_4.laz")) reader = @cxx a -> open() p = @cxx reader -> read_point() p = @cxx reader -> point x = @cxx p -> get_X() y = @cxx p -> get_Y() z = @cxx p -> get_Z() # Read .lax file cxxinclude("~/git/LAStools/LASzip/src/lasindex.hpp") i = @cxxnew LASindex() @cxx i -> read(pointer("~/01608_4.lax")) si = @cxx i -> get_spatial()
LASindex
https://github.com/evetion/LASindex.jl.git
[ "MIT" ]
0.1.0
cdbebbe5815426ea98b195f252d7bd83f31fad2e
code
312
module LASindex using FileIO using RegionTrees using StaticArrays export quadtree include("fileio.jl") include("quadtree.jl") include("spatial.jl") include("util.jl") function __init__() add_format(format"LAX", "LASX", ".lax", [:LASindex]) end end # module
LASindex
https://github.com/evetion/LASindex.jl.git
[ "MIT" ]
0.1.0
cdbebbe5815426ea98b195f252d7bd83f31fad2e
code
2952
using FileIO struct LaxHeader version::UInt32 end function Base.read(io::IO, ::Type{LaxHeader}) header = LaxHeader( read(io, UInt32), ) end struct LaxQuadtreeHeader ssignature::UInt32 # LASS stype::UInt32 qsignature::UInt32 # LASQ version::UInt32 levels::UInt32 level_index::UInt32 implicit_levels::UInt32 min_x::Float64 max_x::Float64 min_y::Float64 max_y::Float64 end function Base.read(io::IO, ::Type{LaxQuadtreeHeader}) header = LaxQuadtreeHeader( read(io, UInt32), read(io, UInt32), read(io, UInt32), read(io, UInt32), read(io, UInt32), read(io, UInt32), read(io, UInt32), Float64(read(io, Float32)), Float64(read(io, Float32)), Float64(read(io, Float32)), Float64(read(io, Float32)) ) end struct LaxIntervalHeader signature::UInt32 version::UInt32 number_cells::UInt32 end function Base.read(io::IO, ::Type{LaxIntervalHeader}) header = LaxIntervalHeader( read(io, UInt32), read(io, UInt32), read(io, UInt32), ) end struct LaxIntervalCell cell_index::Int32 number_intervals::UInt32 number_points::UInt32 end function Base.read(io::IO, ::Type{LaxIntervalCell}) header = LaxIntervalCell( read(io, UInt32), read(io, UInt32), read(io, UInt32) ) end struct LaxIntervalCellInterval _start::UInt32 _end::UInt32 end function Base.read(io::IO, ::Type{UnitRange{T}}) where T <: Integer range = UnitRange( Int64(read(io, UInt32))+1, # .lax uses 0 based indices Int64(read(io, UInt32))+1 # Int32 could theoretically overflow ) end function load(f::File{format"LAX"}) open(f) do s skipmagic(s) load(s) end end function load(s::Stream{format"LAX"}) # magic bytes are skipped header = read(s, LaxHeader) # read quadtree qheader = read(s, LaxQuadtreeHeader) # if not, qsignature and version are missing # but we ignore this other lax type for now qheader.level_index != 0 && error("Level index other than 0 is not supported yet.") # create quadtree qt = quadtree(qheader) # read cell header iheader = read(s, LaxIntervalHeader) ncells = iheader.number_cells # total number of points total_points = 0 for i = 1:ncells # Read cell and its intervals qcell = read(s, LaxIntervalCell) total_points += qcell.number_points intervals = Vector{UnitRange{Integer}}(undef, qcell.number_intervals) for j = 1:qcell.number_intervals intervals[j] = read(s, UnitRange{Integer}) end # Create cell in qt with intervals quadtree!(qt, qcell.cell_index, intervals) end # assert we are at end of file @assert eof(s) @info("Processed $(s.filename) with $(total_points) points.") return qt end
LASindex
https://github.com/evetion/LASindex.jl.git
[ "MIT" ]
0.1.0
cdbebbe5815426ea98b195f252d7bd83f31fad2e
code
1833
"""Generate quadtree root from .lax header.""" function quadtree(header::LaxQuadtreeHeader) root = Cell(SVector(header.min_x, header.min_y), SVector(header.max_x - header.min_x, header.max_y - header.min_y), Vector{UnitRange{Integer}}()) end """Add data to a quadtree cell with given index.""" function quadtree!(root::RegionTrees.Cell, index::Integer, data::Vector{UnitRange{T}}) where T <: Integer cell = quadtree!(root, index) cell.data = data return cell end """Split a quadtree until the requested index is reached.""" function quadtree!(root::RegionTrees.Cell, index::Integer) places = zlevels(index) places = reverse(places, dims=1) # bottom up for place in places (place != 0) && (isleaf(root)) && (split!(root)) root = getindex(root, place) end return root end """For a given Quadtree index, return one of [1,2,3,4] for each level in the quadtree. Levels are defined as follows, where the index is the number. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 - 84 etc """ function zlevels(index::Integer) places = Array{Integer,1}() # Determine places until root is reached while index > 4 # index one level up in the quadtree parent_cell = (index - 1) >>> 2 # place is position in Z order of four cells place = index - (parent_cell << 2) push!(places, place) index = parent_cell end push!(places, index) return places end """Convert place in Z order to RegionTrees index.""" function Base.getindex(cell::Cell, place::Integer) # 3 4 # 1 2 place == 4 && return cell[2,2] place == 3 && return cell[1,2] place == 2 && return cell[2,1] place == 1 && return cell[1,1] place == 0 && return cell # root cell error("Place can't be higher than 4.") end
LASindex
https://github.com/evetion/LASindex.jl.git