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.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
16971
# # Solve the Stokes equation of colliding flow: MINI element, general formulation # Synopsis: Compute the solution of the Stokes equation of two-dimensional # incompressible viscous flow for a manufactured problem of colliding flow. # Bubble-function triangular elements are used. # The "manufactured" colliding flow example from Elman et al 2014. The MINI # formulation with linear triangles with a cubic bubble function for the # velocity and continuous pressure on linear triangles. # The pressure is shown here with contours, and the velocities visualized with # arrows at random points. # ![Pressure and velocity](colliding.png) # The formulation is the general elasticity-like scheme with # strain-rate/velocity matrices. It can be manipulated into the one derived # in Reddy, Introduction to the finite element method, 1993. Page 486 ff. # The complete code is in the file [`tut_stokes_p1b_p1_gen.jl`](tut_stokes_p1b_p1_gen.jl). # The solution will be defined within a module in order to eliminate conflicts # with data or functions defined elsewhere. module tut_stokes_p1b_p1_gen # We'll need some functionality from linear algebra, static arrays, and the mesh # libraries. Some plotting will be produced to visualize structure of the # stiffness matrix. Finally we will need the `Elfel` functionality. using LinearAlgebra using StaticArrays using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using UnicodePlots # The boundary value problem is expressed in this weak form # ```math # \int_{V}{\underline{\varepsilon}}(\underline{\delta v})^T\; # \underline{\underline{D}}\; {\underline{\varepsilon}}(\underline{u})\; \mathrm{d} V # - \int_{V} \mathrm{div}(\underline{\delta v})\; p\; \mathrm{d} V = 0,\quad \forall \underline{\delta v} # ``` # ```math # - \int_{V} \delta q\; \mathrm{div}(\underline{u}) \; \mathrm{d} V = 0,\quad \forall \delta q # ``` # Here ``\underline{\delta v}`` are the test functions in the velocity space, # and ``\delta q`` are the pressure test functions. Further ``\underline # {u}`` is the trial velocity, and ``p`` is the trial pressure. function run() mu = 1.0 # dynamic viscosity # This is the material-property matrix ``\underline{\underline{D}}``: D = SMatrix{3, 3}( [2*mu 0 0 0 2*mu 0 0 0 mu]) A = 1.0 # half of the length of the side of the square N = 100 # number of element edges per side of the square # These three functions define the true velocity components and the true # pressure. trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 # Construct the two meshes for the mixed method. They need to support the # velocity and pressure spaces. mesh = genmesh(A, N) # Construct the velocity space: it is a vector space with two components. The # degrees of freedom are real numbers (`Float64`). The velocity mesh # carries the finite elements of the continuity ``H ^1``, i. e. both the # function values and the derivatives are square integrable. Each node # carries 2 degrees of freedom, hence there are two velocity components per # node. Uh = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 2) # Now we apply the boundary conditions at the nodes around the # circumference. locs = geometry(mesh) # We use searching based on the presence of the node within a box. The # entire boundary will be captured within these four boxes, provided we # inflate those boxes with a little tolerance (we can't rely on those # nodes to be precisely at the coordinates given, we need to introduce some # tolerance). boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] inflate = A / N / 100 for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl # Remember that all components of the velocity are known at the # boundary. setebc!(Uh, 0, i, 1, trueux(locs[i]...)) setebc!(Uh, 0, i, 2, trueuy(locs[i]...)) end end # No we construct the pressure space. It is a continuous, piecewise linear # space supported on a mesh of three-node triangles. Ph = FESpace(Float64, mesh, FEH1_T3(), 1) # The pressure in this "enclosed" flow example is only known up to a constant. # By setting pressure degree of freedom at one node will make the solution # unique. atcenter = vselect(geometry(mesh); nearestto = [0.0, 0.0]) setebc!(Ph, 0, atcenter[1], 1, 0.0) # Number the degrees of freedom. First all the free degrees of freedom are # numbered, both velocities and pressures. Next all the data degrees of # freedom are numbered, again both for the velocities and for the # pressures. numberdofs!([Uh, Ph]) # The total number of degrees of freedom is now calculated. tndof = ndofs(Uh) + ndofs(Ph) # As is the total number of unknowns. tnunk = nunknowns(Uh) + nunknowns(Ph) # Assemble the coefficient matrix. K = assembleK(Uh, Ph, tndof, D) # Display the structure of the indefinite stiffness matrix. Note that this # is the complete matrix, including rows and columns for all the degrees of # freedom, unknown and known. p = spy(K, canvas = DotCanvas) display(p) # Solve the linear algebraic system. First construct system vector of all # the degrees of freedom, in the first `tnunk` rows that corresponds to the # unknowns, and the subsequent rows are for the data degrees of freedom. U = fill(0.0, tndof) gathersysvec!(U, [Uh, Ph]) # Note that the vector `U` consists of nonzero numbers in rows are for the # data degrees of freedom. Multiplying the stiffness matrix with this # vector will generate a load vector on the right-hand side. Otherwise # there is no loading, hence the vector `F` consists of all zeros. F = fill(0.0, tndof) solve!(U, K, F, tnunk) # Once we have solved the system of linear equations, we can distribute the # solution from the vector `U` into the finite element spaces. scattersysvec!([Uh, Ph], U) # Given that the solution is manufactured, i. e. exactly known, we can # calculate the true errors. @show ep = evaluate_pressure_error(Ph, truep) @show ev = evaluate_velocity_error(Uh, trueux, trueuy) # Postprocessing. First we make attributes, scalar nodal attributes, # associated with the meshes for the pressures and the velocity. makeattribute(Ph, "p", 1) makeattribute(Uh, "ux", 1) makeattribute(Uh, "uy", 2) # The pressure and the velocity components are then written out into two VTK # files. vtkwrite("tut_stokes_p1b_p1_gen-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("tut_stokes_p1b_p1_gen-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) return true end function genmesh(A, N) # Linear triangle mesh is used for both the velocity space and the pressure # space. mesh = attach!(Mesh(), T3block(2 * A, 2 * A, N, N), "velocity") # Now translate so that the center of the square is at the origin of the # coordinates. ir = baseincrel(mesh) transform(ir, x -> x .- A) # The bubble degree of freedom is associated with the element itself. The # mesh will therefore be equipped with the incidence relation ``(2, 2)``. # The finite element space for the velocity will therefore have degrees of # freedom associated with the vertices and with the faces # (elements themselves). The finite element space does that by associating # fields with incidence relations, hence the need for this one. eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(Uh, Ph, tndof, D) function integrate!(ass, elits, qpits, D) # Consider the elementwise definition of the test strain rate, `` # {\underline{\varepsilon}}(\underline{\delta v})``. It is calculated # from the elementwise degrees of freedom and the associated basis # functions as # ```math # {\underline{\varepsilon}}(\underline{\delta v}) = # \sum_i{\delta V}_i {\underline{B}_{c(i)}(N_i)} # ``` # where ``i = 1, \ldots, n_{du}``, and ``n_{du}`` is the number of # velocity degrees of freedom per element, ``c(i)`` is the number of # the component corresponding to the degree of freedom ``i``. This is # either 1 when degree of freedom ``i`` is the ``x``-component of the # velocity, 2 otherwise(for the ``y``-component of the velocity). # Analogously for the trial strain rate. # The strain-rate/velocity matrices are defined as # ```math # {\underline{B}_{1}(N_i)} = # \left[\begin{array}{c} # \partial{N_i}/\partial{x} \\ # 0 \\ # \partial{N_i}/\partial{y} # \end{array}\right], # ``` # and # ```math # {\underline{B}_{2}(N_i)} = # \left[\begin{array}{c} # 0 \\ # \partial{N_i}/\partial{y} \\ # \partial{N_i}/\partial{x} # \end{array}\right]. # ``` # This tiny function evaluates the strain-rate/velocity matrices defined above # from the gradient of a basis function and the given number of the # component corresponding to the current degree of freedom. B = (g, k) -> (k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1]))) # This array defines the components for the element degrees of freedom, # as defined above as ``c(i)``. c = edofcompnt(Uh) # These are the totals of the velocity and pressure degrees of freedom # per element. n_du, n_dp = ndofsperel.((Uh, Ph)) # The local matrix assemblers are used as if they were ordinary # elementwise dense matrices. Here they are defined. kuu = LocalMatrixAssembler(n_du, n_du, 0.0) kup = LocalMatrixAssembler(n_du, n_dp, 0.0) for el in zip(elits...) uel, pel = el # The local matrix assemblers are initialized with zeros for the # values, and with the element degree of freedom vectors to be used # in the assembly. The assembler `kuu` is used for the velocity # degrees of freedom, and the assembler `kup` collect the coupling # coefficients between the velocity and the pressure. The function # `eldofs` collects the global numbers of the degrees of freedom # either for the velocity space, or for the pressure space # (`eldofs(pel)`). init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp # The integration is performed using the velocity quadrature points. Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) # gradients of the velocity basis functions Np = bfun(pqp) # pressure basis functions # This double loop corresponds precisely to the integrals of the # weak form. This is the matrix in the upper left corner. for i in 1:n_du DBi = D * B(gradNu[i], c[i]) for j in 1:n_du Bj = B(gradNu[j], c[j]) kuu[j, i] += dot(Bj, DBi) * (JxW) end end # And this is the coupling matrix in the top right corner. for i in 1:n_dp, j in 1:n_du kup[j, i] += gradNu[j][c[j]] * (-JxW * Np[i]) end end # Assemble the matrices. The submatrix off the diagonal is assembled # twice, once as itself, and once as its transpose. assemble!(ass, kuu) assemble!(ass, kup) # top right corner assemble!(ass, transpose(kup)) # bottom left corner end return ass # return the updated assembler of the global matrix end # In the `assembleK` function we first we create the element iterators. We # can go through all the elements, both in the velocity finite element # space and in the pressure finite element space, that define the domain of # integration using this iterator. Each time a new element is accessed, # some data are precomputed such as the element degrees of freedom, # components of the degree of freedom, etc. Note that we need to iterate # two finite element spaces, hence we create a tuple of iterators. elits = (FEIterator(Uh), FEIterator(Ph)) # These are the quadrature point iterators. We know that the elements are # triangular. We choose the three-point rule, to capture the quadratic # component in the velocity space. Quadrature-point iterators provide # access to basis function values and gradients, the Jacobian matrix and # the Jacobian determinant, the location of the quadrature point and so # on. Note that we need to iterate the quadrature rules of # two finite element spaces, hence we create a tuple of iterators. qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uh, qargs), QPIterator(Ph, qargs)) # The matrix will be assembled into this assembler. Which is initialized # with the total number of degrees of freedom (dimension of the coefficient # matrix before partitioning into unknowns and data degrees of freedom). ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) # The integration is carried out, and then... integrate!(ass, elits, qpits, D) # ...we materialize the sparse stiffness matrix and return it. return finish!(ass) end # The linear algebraic system is solved by partitioning. The vector `U` is # initially all zero, except in the degrees of freedom which are prescribed as # nonzero. Therefore the product of the stiffness matrix and the vector `U` # are the loads due to nonzero essential boundary conditions. The # submatrix of the stiffness conduction matrix corresponding to the free degrees of # freedom (unknowns), `K[1:nu, 1:nu]` is then used to solve for the unknowns `U # [1:nu]`. function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end # The function `evaluate_pressure_error` evaluates the true ``L^2`` error of # the pressure. It does that by integrating the square of the difference # between the approximate pressure and the true pressure, the true pressure # being provided by the `truep` function. function evaluate_pressure_error(Ph, truep) function integrate!(elit, qpit, truep) n_dp = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:n_dp pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end # The function `evaluate_velocity_error` evaluates the true ``L^2`` error of # the velocity. It does that by integrating the square of the difference # between the approximate pressure and the true velocity, the true velocity # being provided by the `trueux`, `trueuy` functions. function evaluate_velocity_error(Uh, trueux, trueuy) function integrate!(elit, qpit, trueux, trueuy) n_du = ndofsperel(elit) uedofcomp = edofcompnt(Uh) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:n_du (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(Uh) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Uh, qargs) return integrate!(elit, qpit, trueux, trueuy) end end # To run the example, evaluate this file which will compile the module # `.tut_stokes_p1b_p1_gen`. using .tut_stokes_p1b_p1_gen tut_stokes_p1b_p1_gen.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
17375
# # Solve the Stokes equation of colliding flow: Q1-Q0 element, general formulation # Synopsis: Compute the solution of the Stokes equation of two-dimensional # incompressible viscous flow for a manufactured problem of colliding flow. # Continuous velocity/discontinuous pressure quadrilateral elements are used. # The "manufactured" colliding flow example from Elman et al 2014. The # Continuous velocity/discontinuous pressure formulation with linear # quadrilaterals. These elements suffer from pressure oscillation instability. # The results of this simulation demonstrate it. # The analytical results are shown here: pressure is shown with contours, # and the velocities visualized with arrows at random points. # ![Pressure and velocity](colliding.png) # The formulation is the general elasticity-like scheme with # strain-rate/velocity matrices. It can be manipulated into the one derived # in Reddy, Introduction to the finite element method, 1993. Page 486 ff. # The complete code is in the file [`tut_stokes_q1_q0_gen.jl`](tut_stokes_q1_q0_gen.jl). # The solution will be defined within a module in order to eliminate conflicts # with data or functions defined elsewhere. module tut_stokes_q1_q0_gen # We'll need some functionality from linear algebra, static arrays, and the mesh # libraries. Some plotting will be produced to visualize structure of the # stiffness matrix. Finally we will need the `Elfel` functionality. using LinearAlgebra using StaticArrays using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using UnicodePlots # The boundary value problem is expressed in this weak form # ```math # \int_{V}{\underline{\varepsilon}}(\underline{\delta v})^T\; # \underline{\underline{D}}\; {\underline{\varepsilon}}(\underline{u})\; \mathrm{d} V # - \int_{V} \mathrm{div}(\underline{\delta v})\; p\; \mathrm{d} V = 0,\quad \forall \underline{\delta v} # ``` # ```math # - \int_{V} \delta q\; \mathrm{div}(\underline{u}) \; \mathrm{d} V = 0,\quad \forall \delta q # ``` # Here ``\underline{\delta v}`` are the test functions in the velocity space, # and ``\delta q`` are the pressure test functions. Further ``\underline # {u}`` is the trial velocity, and ``p`` is the trial pressure. function run() mu = 1.0 # dynamic viscosity # This is the material-property matrix ``\underline{\underline{D}}``: D = SMatrix{3, 3}( [2*mu 0 0 0 2*mu 0 0 0 mu]) A = 1.0 # half of the length of the side of the square N = 100 # number of element edges per side of the square # These three functions define the true velocity components and the true # pressure. trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 # Construct the two meshes for the mixed method. They need to support the # velocity and pressure spaces. mesh = genmesh(A, N) # Construct the velocity space: it is a vector space with two components. The # degrees of freedom are real numbers (`Float64`). The velocity mesh # carries the finite elements of the continuity ``H ^1``, i. e. both the # function values and the derivatives are square integrable. Each node # carries 2 degrees of freedom, hence there are two velocity components per # node. Uh = FESpace(Float64, mesh, FEH1_Q4(), 2) # Now we apply the boundary conditions at the nodes around the # circumference. locs = geometry(mesh) # We use searching based on the presence of the node within a box. The # entire boundary will be captured within these four boxes, provided we # inflate those boxes with a little tolerance (we can't rely on those # nodes to be precisely at the coordinates given, we need to introduce some # tolerance). boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] inflate = A / N / 100 for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl # Remember that all components of the velocity are known at the # boundary. setebc!(Uh, 0, i, 1, trueux(locs[i]...)) setebc!(Uh, 0, i, 2, trueuy(locs[i]...)) end end # No we construct the pressure space. It is a discontinuous, piecewise # constant space supported on a mesh of 4-node quadrilaterals # (``L ^2``-continuity elements). Each quadrilateral carries a single # degree of freedom. Ph = FESpace(Float64, mesh, FEL2_Q4(), 1) # The pressure in this "enclosed" flow example is only known up to a # constant. By setting pressure degree of freedom at one degree of freedom # to zero will make the solution unique. atcenter = vselect(geometry(mesh); nearestto = [0.0, 0.0]) setebc!(Ph, 2, atcenter[1], 1, 0.0) # Number the degrees of freedom. First all the free degrees of freedom are # numbered, both velocities and pressures. Next all the data degrees of # freedom are numbered, again both for the velocities and for the # pressures. numberdofs!([Uh, Ph]) # The total number of degrees of freedom is now calculated. tndof = ndofs(Uh) + ndofs(Ph) # As is the total number of unknowns. tnunk = nunknowns(Uh) + nunknowns(Ph) # Assemble the coefficient matrix. K = assembleK(Uh, Ph, tndof, D) # Display the structure of the indefinite stiffness matrix. Note that this # is the complete matrix, including rows and columns for all the degrees of # freedom, unknown and known. p = spy(K, canvas = DotCanvas) display(p) # Solve the linear algebraic system. First construct system vector of all # the degrees of freedom, in the first `tnunk` rows that corresponds to the # unknowns, and the subsequent rows are for the data degrees of freedom. U = fill(0.0, tndof) gathersysvec!(U, [Uh, Ph]) # Note that the vector `U` consists of nonzero numbers in rows are for the # data degrees of freedom. Multiplying the stiffness matrix with this # vector will generate a load vector on the right-hand side. Otherwise # there is no loading, hence the vector `F` consists of all zeros. F = fill(0.0, tndof) solve!(U, K, F, tnunk) # Once we have solved the system of linear equations, we can distribute the # solution from the vector `U` into the finite element spaces. scattersysvec!([Uh, Ph], U) # Given that the solution is manufactured, i. e. exactly known, we can # calculate the true errors. @show ep = evaluate_pressure_error(Ph, truep) @show ev = evaluate_velocity_error(Uh, trueux, trueuy) # Postprocessing. First we make attributes, scalar nodal attributes, # associated with the meshes for the pressures and the velocity. makeattribute(Ph, "p", 1) makeattribute(Uh, "ux", 1) makeattribute(Uh, "uy", 2) # The pressure and the velocity components are then written out into two VTK # files. The pressure is of the "cell-data" type, the velocity is of # the "point-data" type. vtkwrite("tut_stokes_q1_q0_gen-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("tut_stokes_q1_q0_gen-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) return true end function genmesh(A, N) # Linear quadrilateral mesh is used for both the velocity space and the # pressure space. mesh = attach!(Mesh(), Q4block(2 * A, 2 * A, N, N), "velocity") # Now translate so that the center of the square is at the origin of the # coordinates. ir = baseincrel(mesh) transform(ir, x -> x .- A) # The pressure degree of freedom is associated with the element itself. The # mesh will therefore need be equipped with the incidence relation `` # (2, 2)``. The finite element space for the velocity will have degrees of # freedom associated with the vertices. The finite element space for the # pressure will have degrees of freedom associated with the faces # (elements themselves). The finite element space does that by associating # the pressure field with the ``(2, 2)`` incidence relation. eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(Uh, Ph, tndof, D) function integrate!(ass, elits, qpits, D) # Consider the elementwise definition of the test strain rate, `` # {\underline{\varepsilon}}(\underline{\delta v})``. It is calculated # from the elementwise degrees of freedom and the associated basis # functions as # ```math # {\underline{\varepsilon}}(\underline{\delta v}) = # \sum_i{\delta V}_i {\underline{B}_{c(i)}(N_i)} # ``` # where ``i = 1, \ldots, n_{du}``, and ``n_{du}`` is the number of # velocity degrees of freedom per element, ``c(i)`` is the number of # the component corresponding to the degree of freedom ``i``. This is # either 1 when degree of freedom ``i`` is the ``x``-component of the # velocity, 2 otherwise(for the ``y``-component of the velocity). # Analogously for the trial strain rate. # The strain-rate/velocity matrices are defined as # ```math # {\underline{B}_{1}(N_i)} = # \left[\begin{array}{c} # \partial{N_i}/\partial{x} \\ # 0 \\ # \partial{N_i}/\partial{y} # \end{array}\right], # ``` # and # ```math # {\underline{B}_{2}(N_i)} = # \left[\begin{array}{c} # 0 \\ # \partial{N_i}/\partial{y} \\ # \partial{N_i}/\partial{x} # \end{array}\right]. # ``` # This tiny function evaluates the strain-rate/velocity matrices defined above # from the gradient of a basis function and the given number of the # component corresponding to the current degree of freedom. B = (g, k) -> (k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1]))) # This array defines the components for the element degrees of freedom, # as defined above as ``c(i)``. c = edofcompnt(Uh) # These are the totals of the velocity and pressure degrees of freedom # per element. n_du, n_dp = ndofsperel.((Uh, Ph)) # The local matrix assemblers are used as if they were ordinary # elementwise dense matrices. Here they are defined. kuu = LocalMatrixAssembler(n_du, n_du, 0.0) kup = LocalMatrixAssembler(n_du, n_dp, 0.0) for el in zip(elits...) uel, pel = el # The local matrix assemblers are initialized with zeros for the # values, and with the element degree of freedom vectors to be used # in the assembly. The assembler `kuu` is used for the velocity # degrees of freedom, and the assembler `kup` collect the coupling # coefficients between the velocity and the pressure. The function # `eldofs` collects the global numbers of the degrees of freedom # either for the velocity space, or for the pressure space # (`eldofs(pel)`). init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp # The integration is performed using the velocity quadrature points. Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) # gradients of the velocity basis functions Np = bfun(pqp) # pressure basis functions # This double loop corresponds precisely to the integrals of the # weak form. This is the matrix in the upper left corner. for i in 1:n_du DBi = D * B(gradNu[i], c[i]) for j in 1:n_du Bj = B(gradNu[j], c[j]) kuu[j, i] += dot(Bj, DBi) * (JxW) end end # And this is the coupling matrix in the top right corner. for i in 1:n_dp, j in 1:n_du kup[j, i] += gradNu[j][c[j]] * (-JxW * Np[i]) end end # Assemble the matrices. The submatrix off the diagonal is assembled # twice, once as itself, and once as its transpose. assemble!(ass, kuu) assemble!(ass, kup) # top right corner assemble!(ass, transpose(kup)) # bottom left corner end return ass # return the updated assembler of the global matrix end # In the `assembleK` function we first we create the element iterators. We # can go through all the elements, both in the velocity finite element # space and in the pressure finite element space, that define the domain of # integration using this iterator. Each time a new element is accessed, # some data are precomputed such as the element degrees of freedom, # components of the degree of freedom, etc. Note that we need to iterate # two finite element spaces, hence we create a tuple of iterators. elits = (FEIterator(Uh), FEIterator(Ph)) # These are the quadrature point iterators. We know that the elements are # triangular. We choose the three-point rule, to capture the quadratic # component in the velocity space. Quadrature-point iterators provide # access to basis function values and gradients, the Jacobian matrix and # the Jacobian determinant, the location of the quadrature point and so # on. Note that we need to iterate the quadrature rules of # two finite element spaces, hence we create a tuple of iterators. qargs = (kind = :Gauss, order = 2) qpits = (QPIterator(Uh, qargs), QPIterator(Ph, qargs)) # The matrix will be assembled into this assembler. Which is initialized # with the total number of degrees of freedom (dimension of the coefficient # matrix before partitioning into unknowns and data degrees of freedom). ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) # The integration is carried out, and then... integrate!(ass, elits, qpits, D) # ...we materialize the sparse stiffness matrix and return it. return finish!(ass) end # The linear algebraic system is solved by partitioning. The vector `U` is # initially all zero, except in the degrees of freedom which are prescribed as # nonzero. Therefore the product of the stiffness matrix and the vector `U` # are the loads due to nonzero essential boundary conditions. The # submatrix of the stiffness conduction matrix corresponding to the free degrees of # freedom (unknowns), `K[1:nu, 1:nu]` is then used to solve for the unknowns `U # [1:nu]`. function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end # The function `evaluate_pressure_error` evaluates the true ``L^2`` error of # the pressure. It does that by integrating the square of the difference # between the approximate pressure and the true pressure, the true pressure # being provided by the `truep` function. function evaluate_pressure_error(Ph, truep) function integrate!(elit, qpit, truep) n_dp = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:n_dp pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :Gauss, order = 2) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end # The function `evaluate_velocity_error` evaluates the true ``L^2`` error of # the velocity. It does that by integrating the square of the difference # between the approximate pressure and the true velocity, the true velocity # being provided by the `trueux`, `trueuy` functions. function evaluate_velocity_error(Uh, trueux, trueuy) function integrate!(elit, qpit, trueux, trueuy) n_du = ndofsperel(elit) uedofcomp = edofcompnt(Uh) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:n_du (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(Uh) qargs = (kind = :Gauss, order = 2) qpit = QPIterator(Uh, qargs) return integrate!(elit, qpit, trueux, trueuy) end end # To run the example, evaluate this file which will compile the module # `.tut_stokes_q1_q0_gen`. using .tut_stokes_q1_q0_gen tut_stokes_q1_q0_gen.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
3365
module t3 using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities using MeshSteward: T3block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! E = 1.0; nu = 1.0/3; D = SMatrix{3, 3}(E / (1 - nu^2) * [1 nu 0 nu 1 0 0 0 (1 - nu) / 2]) A = 1.0 # length of the side of the square N = 100;# number of subdivisions along the sides of the square domain function genmesh() conn = T3block(A, A, N, N) mesh = Mesh() attach!(mesh, conn) return mesh end function assembleK(fesp, D) function integrateK!(ass, geom, elit, qpit, D) B = (g, k) -> k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1])) c = edofcompnt(elit.fesp) nedof = ndofsperel(elit) ke = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(ke, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) for j in 1:nedof DBj = D * B(gradN[j], c[j]) for i in 1:nedof Bi = B(gradN[i], c[i]) ke[i, j] += dot(DBj, Bi) * JxW end end end assemble!(ass, ke) end return ass end elit = FEIterator(fesp) qpit = QPIterator(fesp, (kind = :default,)) geom = geometry(fesp.mesh) ass = SysmatAssemblerSparse(0.0) start!(ass, ndofs(fesp), ndofs(fesp)) @time integrateK!(ass, geom, elit, qpit, D) return finish!(ass) end function solve!(U, K, F, nu) @time KT = K * U @time U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function run() mesh = genmesh() fesp = FESpace(Float64, mesh, FEH1_T3(), 2) locs = geometry(mesh) inflate = A / N / 100 box = [0.0 0.0 0.0 A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(fesp, 0, i, 1, 0.0) setebc!(fesp, 0, i, 2, 0.0) end box = [A A 0.0 A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(fesp, 0, i, 1, A / 10) setebc!(fesp, 0, i, 2, 0.0) end numberfreedofs!(fesp) numberdatadofs!(fesp) @show nunknowns(fesp) K = assembleK(fesp, D) U = fill(0.0, ndofs(fesp)) gathersysvec!(U, fesp) F = fill(0.0, ndofs(fesp)) solve!(U, K, F, nunknowns(fesp)) scattersysvec!(fesp, U) makeattribute(fesp, "U", 1:2) vtkwrite("t3-U", baseincrel(mesh), [(name = "U", allxyz = true)]) end end t3.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
3438
module t6 using LinearAlgebra # using BenchmarkTools # using InteractiveUtils using StaticArrays # using Profile using MeshCore: nrelations, nentities using MeshSteward: T6block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! E = 1.0; nu = 1.0/3; D = SMatrix{3, 3}(E / (1 - nu^2) * [1 nu 0 nu 1 0 0 0 (1 - nu) / 2]) A = 1.0 # length of the side of the square N = 10;# number of subdivisions along the sides of the square domain function genmesh() conn = T6block(A, A, N, N) mesh = Mesh() attach!(mesh, conn) return mesh end function assembleK(fesp, D) function integrateK!(ass, geom, elit, qpit, D) B = (g, k) -> k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1])) c = edofcompnt(elit.fesp) nedof = ndofsperel(elit) ke = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(ke, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) for j in 1:nedof DBj = D * B(gradN[j], c[j]) for i in 1:nedof Bi = B(gradN[i], c[i]) ke[i, j] += dot(DBj, Bi) * JxW end end end assemble!(ass, ke) end return ass end elit = FEIterator(fesp) qpit = QPIterator(fesp, (kind = :default, npts = 3,)) geom = geometry(fesp.mesh) ass = SysmatAssemblerSparse(0.0) start!(ass, ndofs(fesp), ndofs(fesp)) @time integrateK!(ass, geom, elit, qpit, D) return finish!(ass) end function solve!(U, K, F, nu) @time KT = K * U @time U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function run() mesh = genmesh() fesp = FESpace(Float64, mesh, FEH1_T6(), 2) locs = geometry(mesh) inflate = A / N / 100 box = [0.0 0.0 0.0 A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(fesp, 0, i, 1, 0.0) setebc!(fesp, 0, i, 2, 0.0) end box = [A A 0.0 A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(fesp, 0, i, 1, A / 10) setebc!(fesp, 0, i, 2, 0.0) end numberfreedofs!(fesp) numberdatadofs!(fesp) @show nunknowns(fesp) K = assembleK(fesp, D) U = fill(0.0, ndofs(fesp)) gathersysvec!(U, fesp) F = fill(0.0, ndofs(fesp)) solve!(U, K, F, nunknowns(fesp)) scattersysvec!(fesp, U) makeattribute(fesp, "U", 1:2) vtkwrite("t6-U", baseincrel(mesh), [(name = "U", allxyz = true)]) end end t6.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
2893
""" q4 Compute the solution of the Poisson equation of heat conduction with a nonzero heat source. Quadrilateral four-node elements are used. """ module q4 using LinearAlgebra using SparseArrays using MeshCore.Exports using MeshCore: @_check using MeshSteward.Exports using Elfel.Exports using UnicodePlots A = 1.0 # length of the side of the square kappa = 1.0; # conductivity matrix Q = -6.0; # internal heat generation rate tempf(x, y) =(1.0 + x^2 + 2.0 * y^2);#the exact distribution of temperature N = 1000;# number of subdivisions along the sides of the square domain function genmesh() conn = Q4block(A, A, N, N) mesh = Mesh() attach!(mesh, conn) return mesh end function assembleKF(fesp, kappa, Q) function integrate!(am, av, geom, elit, qpit, kappa, Q) nedof = ndofsperel(elit) ke = LocalMatrixAssembler(nedof, nedof, 0.0) fe = LocalVectorAssembler(nedof, 0.0) for el in elit init!(ke, eldofs(el), eldofs(el)) init!(fe, eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof ke[i, j] += dot(gradN[i], gradN[j]) * (kappa * JxW) end fe[j] += N[j] * Q * JxW end end assemble!(am, ke) assemble!(av, fe) end return am, av end elit = FEIterator(fesp) qpit = QPIterator(fesp, (kind = :Gauss, order = 2)) geom = geometry(fesp.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(fesp), ndofs(fesp)) av = start!(SysvecAssembler(0.0), ndofs(fesp)) @time integrate!(am, av, geom, elit, qpit, kappa, Q) return finish!(am), finish!(av) end function solve!(T, K, F, nu) @time KT = K * T @time T[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function checkcorrectness(fesp) geom = geometry(fesp.mesh) ir = baseincrel(fesp.mesh) T = attribute(ir.right, "T") std = 0.0 for i in 1:length(T) std += abs(T[i][1] - tempf(geom[i]...)) end @_check (std / length(T)) <= 1.0e-9 end function run() mesh = genmesh() fesp = FESpace(Float64, mesh, FEH1_Q4()) bir = boundary(mesh); vl = connectedv(bir); locs = geometry(mesh) for i in vl setebc!(fesp, 0, i, 1, tempf(locs[i]...)) end numberfreedofs!(fesp) numberdatadofs!(fesp) @show nunknowns(fesp) K, F = assembleKF(fesp, kappa, Q) T = fill(0.0, ndofs(fesp)) gathersysvec!(T, fesp) solve!(T, K, F, nunknowns(fesp)) scattersysvec!(fesp, T) makeattribute(fesp, "T", 1) checkcorrectness(fesp) vtkwrite("q4-T", baseincrel(mesh), [(name = "T",)]) end end @time q4.run() # q4.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
3601
""" t3 Compute the solution of the Poisson equation of heat conduction with a nonzero heat source. Linear triangle elements are used. """ module t3 using LinearAlgebra using MeshCore: nrelations, nentities, attribute, @_check using MeshSteward: T3block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: connectedv, geometry using MeshSteward: vtkwrite using Elfel.RefShapes: RefShapeTriangle, manifdim, manifdimv using Elfel.FElements: FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec! using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungradpar, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! A = 1.0 # length of the side of the square kappa = 1.0; # conductivity matrix Q = -6.0; # internal heat generation rate tempf(x, y) =(1.0 + x^2 + 2.0 * y^2);#the exact distribution of temperature N = 1000;# number of subdivisions along the sides of the square domain function genmesh() conn = T3block(A, A, N, N) mesh = Mesh() attach!(mesh, conn) return mesh end function assembleKF(fesp, kappa, Q) function integrate!(am, av, geom, elit, qpit, kappa, Q) nedof = ndofsperel(elit) ke = LocalMatrixAssembler(nedof, nedof, 0.0) fe = LocalVectorAssembler(nedof, 0.0) for el in elit init!(ke, eldofs(el), eldofs(el)) init!(fe, eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof ke[i, j] += dot(gradN[i], gradN[j]) * (kappa * JxW) end fe[j] += N[j] * Q * JxW end end assemble!(am, ke) assemble!(av, fe) end return am, av end elit = FEIterator(fesp) qpit = QPIterator(fesp, (kind = :default,)) geom = geometry(fesp.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(fesp), ndofs(fesp)) av = start!(SysvecAssembler(0.0), ndofs(fesp)) @time integrate!(am, av, geom, elit, qpit, kappa, Q) return finish!(am), finish!(av) end function solve!(T, K, F, nu) @time KT = K * T @time T[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function checkcorrectness(fesp) geom = geometry(fesp.mesh) ir = baseincrel(fesp.mesh) T = attribute(ir.right, "T") std = 0.0 for i in 1:length(T) std += abs(T[i][1] - tempf(geom[i]...)) end @_check (std / length(T)) <= 1.0e-9 end function run() mesh = genmesh() fesp = FESpace(Float64, mesh, FEH1_T3()) bir = boundary(mesh); vl = connectedv(bir); locs = geometry(mesh) for i in vl setebc!(fesp, 0, i, 1, tempf(locs[i]...)) end numberfreedofs!(fesp) numberdatadofs!(fesp) @show nunknowns(fesp) K, F = assembleKF(fesp, kappa, Q) T = fill(0.0, ndofs(fesp)) gathersysvec!(T, fesp) solve!(T, K, F, nunknowns(fesp)) scattersysvec!(fesp, T) makeattribute(fesp, "T", 1) checkcorrectness(fesp) vtkwrite("t3-T", baseincrel(mesh), [(name = "T",)]) end end t3.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
3027
""" t4 Compute the solution of the Poisson equation of heat conduction with a nonzero heat source. Three-dimensional version of the problem in a cube. Linear tetrahedral elements are used. """ module t4 using LinearAlgebra using SparseArrays using MeshCore.Exports using MeshCore: @_check using MeshSteward.Exports using Elfel.Exports A = 1.0 # length of the side of the square kappa = 1.0; # conductivity matrix Q = -6.0; # internal heat generation rate tempf(x, y, z) =(1.0 + x^2 + 2.0 * y^2);#the exact distribution of temperature N = 20;# number of subdivisions along the sides of the square domain function genmesh() conn = T4block(A, A, A, N, N, N) # conn = minimize_profile(conn) println(summary(conn)) mesh = Mesh() attach!(mesh, conn) return mesh end function assembleKF(fesp, kappa, Q) function integrate!(am, av, geom, elit, qpit, kappa, Q) nedof = ndofsperel(elit) ke = LocalMatrixAssembler(nedof, nedof, 0.0) fe = LocalVectorAssembler(nedof, 0.0) for el in elit init!(ke, eldofs(el), eldofs(el)) init!(fe, eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof ke[i, j] += dot(gradN[i], gradN[j]) * (kappa * JxW) end fe[j] += N[j] * Q * JxW end end assemble!(am, ke) assemble!(av, fe) end return am, av end elit = FEIterator(fesp) qpit = QPIterator(fesp, (kind = :default,)) geom = geometry(fesp.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(fesp), ndofs(fesp)) av = start!(SysvecAssembler(0.0), ndofs(fesp)) @time integrate!(am, av, geom, elit, qpit, kappa, Q) return finish!(am), finish!(av) end function solve!(T, K, F, nu) I, J, V = findnz(K) @show bw = maximum(I .- J) + 1 @time KT = K * T @time T[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function checkcorrectness(fesp) geom = geometry(fesp.mesh) ir = baseincrel(fesp.mesh) T = attribute(ir.right, "T") std = 0.0 for i in 1:length(T) std += abs(T[i][1] - tempf(geom[i]...)) end @_check (std / length(T)) <= 1.0e-9 end function run() mesh = genmesh() fesp = FESpace(Float64, mesh, FEH1_T4()) bir = boundary(mesh); vl = connectedv(bir); locs = geometry(mesh) for i in vl setebc!(fesp, 0, i, 1, tempf(locs[i]...)) end numberfreedofs!(fesp) numberdatadofs!(fesp) @show nunknowns(fesp) K, F = assembleKF(fesp, kappa, Q) T = fill(0.0, ndofs(fesp)) gathersysvec!(T, fesp) solve!(T, K, F, nunknowns(fesp)) scattersysvec!(fesp, T) makeattribute(fesp, "T", 1) checkcorrectness(fesp) vtkwrite("t4-T", baseincrel(mesh), [(name = "T",)]) end end t4.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
5886
""" klein_gordon The Klein–Gordon equation is often written in natural units: ```latex psi_tt - psi_xx + m^2 psi = 0 ``` Here it is solved on a finite interval, with zero essential boundary conditions. Only the real part of psi is solved for. """ module klein_gordon using LinearAlgebra using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using PlotlyJS L = 2.0 m2 = 10.0 # coefficient m^2 N = 150;# number of subdivisions along the length of the domain # Boundary and initial conditions Fbc(x) = 0.0 Fic(x) = 0.0 Vic(x) = 1.0 tend = 8.0 dt = 0.02 function genmesh() return attach!(Mesh(), L2block(L, N)) end function assembleM(Psih) function integrate!(am, geom, elit, qpit) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (N[i] * N[j]) * (JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Psih) qpit = QPIterator(Psih, (kind = :Gauss, order = 2)) geom = geometry(Psih.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Psih), ndofs(Psih)) integrate!(am, geom, elit, qpit) return finish!(am) end function assembleK(Psih) function integrate!(am, geom, elit, qpit) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) x = location(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (gradN[i][1] * gradN[j][1]) * (JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Psih) qpit = QPIterator(Psih, (kind = :Gauss, order = 2)) geom = geometry(Psih.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Psih), ndofs(Psih)) integrate!(am, geom, elit, qpit) return finish!(am) end function assembleD(Psih, m2) function integrate!(am, geom, elit, qpit, m) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) x = location(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (N[i] * N[j]) * (m2 * JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Psih) qpit = QPIterator(Psih, (kind = :Gauss, order = 2)) geom = geometry(Psih.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Psih), ndofs(Psih)) integrate!(am, geom, elit, qpit, m2) return finish!(am) end function run() mesh = genmesh() Psih = FESpace(Float64, mesh, FEH1_L2()) ir = baseincrel(mesh) bdvl = connectedv(boundary(mesh)); locs = geometry(mesh) for i in bdvl setebc!(Psih, 0, i, 1, Fbc(locs[i]...)) end numberdofs!(Psih) @show nu = nunknowns(Psih) xs = [locs[i][1] for i in 1:length(locs)] M = assembleM(Psih) K = assembleK(Psih) D = assembleD(Psih, m2) Psi0 = fill(0.0, ndofs(Psih)) V0 = fill(0.0, ndofs(Psih)) for i in 1:length(locs) n = dofnum(Psih, 0, i, 1) Psi0[n] = Fic(locs[i][1]) V0[n] = Vic(locs[i][1]) end for i in bdvl n = dofnum(Psih, 0, i, 1) V0[n] = 0.0 end V1 = fill(0.0, ndofs(Psih)) L1 = fill(0.0, ndofs(Psih)) L0 = fill(0.0, ndofs(Psih)) # Plots layout = Layout(;width=700, height=700, xaxis = attr(title="x", range=[0.0, L]), yaxis = attr(title = "Psi", range=[-1.0, 1.0])) sigdig = n -> round(n*1000)/1000 function updateplot(pl, t, xs, Psis) curv = scatter(;x=xs, y=Psis, mode="lines", name = "Sol", line_color = "rgb(155, 15, 15)") plots = cat(curv; dims = 1) pl.plot.layout["title"] = "t = $(sigdig(t))" react!(pl, plots, pl.plot.layout) sleep(0.12) end function solve!(V1, M, K, D, L0, L1, Psi0, V0, dt, nu) # This assumes zero EBC R = (L1 + L0)/2 + (1/dt)*(M*V0) - K*(Psi0 + (dt/4)*V0) - D*(Psi0 + (dt/4)*V0) V1[1:nu] = ((1/dt)*M + (dt/4)*(K + D))[1:nu, 1:nu] \ R[1:nu] return V1 end pl = 0 step = 0 t = 0.0 while t < tend if mod(step, 10) == 0 Psis = [Psi0[dofnum(Psih, 0, i, 1)] for i in 1:nshapes(ir.right)] if step == 0 curv = scatter(;x=xs, y=Psis, mode="lines", name = "Sol", line_color = "rgb(155, 15, 15)") plots = cat(curv; dims = 1) pl = plot(plots, layout) display(pl) end updateplot(pl, t, xs, Psis) end solve!(V1, M, K, D, L0, L1, Psi0, V0, dt, nu) Psi1 = Psi0 + dt/2*(V1 + V0) t = t + dt step = step + 1 copyto!(V0, V1) copyto!(Psi0, Psi1) end # scattersysvec!(Psih, Psi0) # makeattribute(Psih, "Psi", 1) # vtkwrite("klein_gordon-Psi", baseincrel(mesh), [(name = "Psi",)]) end end using .klein_gordon klein_gordon.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6079
""" klein_gordon_wavelet The Klein–Gordon equation is often written in natural units: ```latex psi_tt - psi_xx + m^2 psi = 0 ``` Here it is solved on a finite interval, with essential boundary condition in the form of a bell function. Only the real part of psi is solved for. """ module klein_gordon_check using LinearAlgebra using MeshCore.Exports using MeshSteward using MeshSteward.Exports using Elfel.Exports using PlotlyJS L = 1.0 m2 = 1.0 # coefficient m^2 N = 100;# number of subdivisions along the length of the domain # Boundary and initial conditions Fbc(x) = 0.0 Fic(x) = sin(2*pi*x) Vic(x) = 0.0 tend = 5.0 dt = 0.02 function genmesh() ir = L2block(L, N) MeshSteward.transform(ir, x -> x-L/2) return attach!(Mesh(), ir) end function assembleM(Psih) function integrate!(am, geom, elit, qpit) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (N[i] * N[j]) * (JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Psih) qpit = QPIterator(Psih, (kind = :Gauss, order = 2)) geom = geometry(Psih.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Psih), ndofs(Psih)) integrate!(am, geom, elit, qpit) return finish!(am) end function assembleK(Psih) function integrate!(am, geom, elit, qpit) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) x = location(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (gradN[i][1] * gradN[j][1]) * (JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Psih) qpit = QPIterator(Psih, (kind = :Gauss, order = 2)) geom = geometry(Psih.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Psih), ndofs(Psih)) integrate!(am, geom, elit, qpit) return finish!(am) end function assembleD(Psih, m2) function integrate!(am, geom, elit, qpit, m) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) x = location(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (N[i] * N[j]) * (m2 * JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Psih) qpit = QPIterator(Psih, (kind = :Gauss, order = 2)) geom = geometry(Psih.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Psih), ndofs(Psih)) integrate!(am, geom, elit, qpit, m2) return finish!(am) end function run() mesh = genmesh() Psih = FESpace(Float64, mesh, FEH1_L2()) ir = baseincrel(mesh) bdvl = connectedv(boundary(mesh)); locs = geometry(mesh) for i in bdvl setebc!(Psih, 0, i, 1, Fbc(locs[i]...)) end numberdofs!(Psih) @show nu = nunknowns(Psih) xs = [locs[i][1] for i in 1:length(locs)] M = assembleM(Psih) K = assembleK(Psih) D = assembleD(Psih, m2) Psi0 = fill(0.0, ndofs(Psih)) V0 = fill(0.0, ndofs(Psih)) for i in 1:length(locs) n = dofnum(Psih, 0, i, 1) Psi0[n] = Fic(locs[i][1]) V0[n] = Vic(locs[i][1]) end for i in bdvl n = dofnum(Psih, 0, i, 1) V0[n] = 0.0 end V1 = fill(0.0, ndofs(Psih)) # Plots layout = Layout(;width=700, height=700, xaxis = attr(title="x", range=[-L/2, L/2]), yaxis = attr(title = "Psi", range=[-1.0, 1.0])) sigdig = n -> round(n*1000)/1000 function updateplot(pl, t, xs, Psis) curv = scatter(;x=xs, y=Psis, mode="lines", name = "Sol", line_color = "rgb(155, 15, 15)") finexs = range(-L/2, L/2, length = 100) truecurv = scatter(;x=finexs, y=sin.(2*pi*finexs).*cos(sqrt(4*pi^2+1)*t), mode="lines", name = "Sol", line_color = "rgb(15, 155, 15)") plots = cat(curv, truecurv; dims = 1) pl.plot.layout["title"] = "t = $(sigdig(t))" react!(pl, plots, pl.plot.layout) sleep(0.12) end function solve!(V1, M, K, D, Psi0, V0, dt, nu) # This assumes zero EBC R = (M*V0) - K*dt*(Psi0 + (dt/4)*V0) - D*dt*(Psi0 + (dt/4)*V0) V1[1:nu] = (M + (dt^2/4)*(K + D))[1:nu, 1:nu] \ R[1:nu] return V1 end pl = 0 step = 0 t = 0.0 while t < tend if mod(step, 1) == 0 Psis = [Psi0[dofnum(Psih, 0, i, 1)] for i in 1:nshapes(ir.right)] if step == 0 curv = scatter(;x=xs, y=Psis, mode="lines") plots = cat(curv; dims = 1) pl = plot(plots, layout) display(pl) end updateplot(pl, t, xs, Psis) end solve!(V1, M, K, D, Psi0, V0, dt, nu) Psi1 = Psi0 + dt/2*(V1 + V0) t = t + dt step = step + 1 copyto!(V0, V1) copyto!(Psi0, Psi1) end # scattersysvec!(Psih, Psi0) # makeattribute(Psih, "Psi", 1) # vtkwrite("klein_gordon_check-Psi", baseincrel(mesh), [(name = "Psi",)]) end end using .klein_gordon_check klein_gordon_check.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6657
""" klein_gordon_var The Klein–Gordon equation with a variable coefficient: ```latex psi_tt - c^2 psi_xx + g psi = 0 ``` where ``g = g(t, x)``. Here it is solved on a finite interval, with zero essential boundary conditions at the ends of the interval. Only the real part of psi is solved for. """ module klein_gordon_var using LinearAlgebra using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using PlotlyJS L = 2.0 c = 10.0 # coefficient N = 150;# number of subdivisions along the length of the domain Fbc(x) = 0.0 # G(t, x) = 800*sin(5*pi*t)*(x/L)^3*(L-x)/L;# # Harmonic vibration g(t, x) = 0.0; Fic(x) = 0.0 Vic(x) = 5*sin(pi*x/L) - 7*sin(3*pi*x/L) tend = 80.0 dt = 0.05 # Uniform velocity g(t, x) = 0.0; Fic(x) = 0.0 Vic(x) = 7.0 tend = 2.0 dt = 0.002 # Uniform velocity, nonzero constant G g(t, x) = -100; Fic(x) = 0.0 Vic(x) = 7.0 tend = 2.0 dt = 0.002 # # Uniform velocity, nonzero G variable in x g(t, x) = -1000.0*(x/L)^3; Fic(x) = 0.0 Vic(x) = -7.0 tend = 2.0 dt = 0.001 # Uniform velocity, nonzero G variable in t g(t, x) = +200*sin(1.32*pi*t) # Fic(x) = 0.0 Vic(x) = 7*sin(pi*x/L) tend = 10 dt = 0.005 function genmesh() return attach!(Mesh(), L2block(L, N)) end function assembleM(Fh) function integrate!(am, geom, elit, qpit) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (N[i] * N[j]) * (JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Fh) qpit = QPIterator(Fh, (kind = :Gauss, order = 2)) geom = geometry(Fh.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Fh), ndofs(Fh)) integrate!(am, geom, elit, qpit) return finish!(am) end function assembleK(Fh, c) function integrate!(am, geom, elit, qpit, c) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) x = location(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (gradN[i][1] * gradN[j][1]) * (c^2 * JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Fh) qpit = QPIterator(Fh, (kind = :Gauss, order = 2)) geom = geometry(Fh.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Fh), ndofs(Fh)) integrate!(am, geom, elit, qpit, c) return finish!(am) end function assembleD(Fh, g, t) function integrate!(am, geom, elit, qpit, g) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) x = location(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (N[i] * N[j]) * (g(t, x[1]) * JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Fh) qpit = QPIterator(Fh, (kind = :Gauss, order = 2)) geom = geometry(Fh.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Fh), ndofs(Fh)) integrate!(am, geom, elit, qpit, g) return finish!(am) end function run() mesh = genmesh() Psih = FESpace(Float64, mesh, FEH1_L2()) ir = baseincrel(mesh) bdvl = connectedv(boundary(mesh)); locs = geometry(mesh) for i in bdvl setebc!(Psih, 0, i, 1, Fbc(locs[i]...)) end numberdofs!(Psih) @show nu = nunknowns(Psih) xs = [locs[i][1] for i in 1:length(locs)] M = assembleM(Psih) K = assembleK(Psih, c) Psi0 = fill(0.0, ndofs(Psih)) V0 = fill(0.0, ndofs(Psih)) for i in 1:length(locs) n = dofnum(Psih, 0, i, 1) Psi0[n] = Fic(locs[i][1]) V0[n] = Vic(locs[i][1]) end for i in bdvl n = dofnum(Psih, 0, i, 1) V0[n] = 0.0 end V1 = fill(0.0, ndofs(Psih)) L1 = fill(0.0, ndofs(Psih)) L0 = fill(0.0, ndofs(Psih)) # Plots layout = Layout(;autosize = true, xaxis = attr(title="x", range=[0.0, L]), yaxis = attr(title = "F", range=[-1.0, 1.0])) sigdig = n -> round(n*1000)/1000 function updateplot(pl, t, xs, Psis) curv = scatter(;x=xs, y=Psis, mode="lines") plots = cat(curv; dims = 1) pl.plot.layout["title"] = "t = $(sigdig(t))" react!(pl, plots, pl.plot.layout) sleep(0.12) end function solve!(V1, M, K, D0, D1, L0, L1, Psi0, V0, dt, nu) # This assumes zero EBC R = (L1 + L0)/2 + (1/dt)*(M*V0) - K*(Psi0 + (dt/4)*V0) + D1*((1/2)*Psi0 + (dt/4)*V0) + D0*((1/2)*Psi0) V1[1:nu] = ((1/dt)*M + (dt/4)*(K - D1))[1:nu, 1:nu] \ R[1:nu] return V1 end pl = 0 step = 0 t = 0.0 D0 = assembleD(Psih, g, t) while t < tend D1 = assembleD(Psih, g, t + dt) if mod(step, 10) == 0 Psis = [Psi0[dofnum(Psih, 0, i, 1)] for i in 1:nshapes(ir.right)] if step == 0 curv = scatter(;x=xs, y=Psis, mode="lines", name = "Sol", line_color = "rgb(155, 15, 15)") plots = cat(curv; dims = 1) pl = plot(plots, layout; options = Dict( :showSendToCloud=>true, :plotlyServerURL=>"https://chart-studio.plotly.com" )) display(pl) end updateplot(pl, t, xs, Psis) end solve!(V1, M, K, D0, D1, L0, L1, Psi0, V0, dt, nu) Psi1 = Psi0 + dt/2*(V1 + V0) t = t + dt step = step + 1 copyto!(V0, V1) copyto!(Psi0, Psi1) copyto!(D0, D1) end scattersysvec!(Psih, Psi0) # makeattribute(Fh, "F", 1) # vtkwrite("gwl2-F", baseincrel(mesh), [(name = "F",)]) end end using .klein_gordon_var klein_gordon_var.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6005
""" klein_gordon_wavelet The Klein–Gordon equation is often written in natural units: ```latex psi_tt - psi_xx + m^2 psi = 0 ``` Here it is solved on a finite interval, with essential boundary condition in the form of a bell function. Only the real part of psi is solved for. """ module klein_gordon_wavelet using LinearAlgebra using MeshCore.Exports using MeshSteward using MeshSteward.Exports using Elfel.Exports using PlotlyJS L = 20.0 m2 = 5.0 # coefficient m^2 N = 100;# number of subdivisions along the length of the domain # Boundary and initial conditions Fbc(x) = 0.0 Fic(x) = exp(-1.5*x^2) Vic(x) = 0.0 tend = 5.0 dt = 0.01 function genmesh() ir = L2block(L, N) MeshSteward.transform(ir, x -> x-L/2) return attach!(Mesh(), ir) end function assembleM(Psih) function integrate!(am, geom, elit, qpit) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (N[i] * N[j]) * (JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Psih) qpit = QPIterator(Psih, (kind = :Gauss, order = 2)) geom = geometry(Psih.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Psih), ndofs(Psih)) integrate!(am, geom, elit, qpit) return finish!(am) end function assembleK(Psih) function integrate!(am, geom, elit, qpit) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) x = location(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (gradN[i][1] * gradN[j][1]) * (JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Psih) qpit = QPIterator(Psih, (kind = :Gauss, order = 2)) geom = geometry(Psih.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Psih), ndofs(Psih)) integrate!(am, geom, elit, qpit) return finish!(am) end function assembleD(Psih, m2) function integrate!(am, geom, elit, qpit, m) nedof = ndofsperel(elit) me = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(me, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) x = location(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof me[i, j] += (N[i] * N[j]) * (m2 * JxW) end end end assemble!(am, me) end return am end elit = FEIterator(Psih) qpit = QPIterator(Psih, (kind = :Gauss, order = 2)) geom = geometry(Psih.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(Psih), ndofs(Psih)) integrate!(am, geom, elit, qpit, m2) return finish!(am) end function run() mesh = genmesh() Psih = FESpace(Float64, mesh, FEH1_L2()) ir = baseincrel(mesh) bdvl = connectedv(boundary(mesh)); locs = geometry(mesh) for i in bdvl setebc!(Psih, 0, i, 1, Fbc(locs[i]...)) end numberdofs!(Psih) @show nu = nunknowns(Psih) xs = [locs[i][1] for i in 1:length(locs)] M = assembleM(Psih) K = assembleK(Psih) D = assembleD(Psih, m2) Psi0 = fill(0.0, ndofs(Psih)) V0 = fill(0.0, ndofs(Psih)) for i in 1:length(locs) n = dofnum(Psih, 0, i, 1) Psi0[n] = Fic(locs[i][1]) V0[n] = Vic(locs[i][1]) end @show Psi0 for i in bdvl n = dofnum(Psih, 0, i, 1) V0[n] = 0.0 end V1 = fill(0.0, ndofs(Psih)) L1 = fill(0.0, ndofs(Psih)) L0 = fill(0.0, ndofs(Psih)) # Plots layout = Layout(;width=700, height=700, xaxis = attr(title="x", range=[-L/2, L/2]), yaxis = attr(title = "Psi", range=[-1.0, 1.0])) sigdig = n -> round(n*1000)/1000 function updateplot(pl, t, xs, Psis) curv = scatter(;x=xs, y=Psis, mode="lines", name = "Sol", line_color = "rgb(155, 15, 15)") plots = cat(curv; dims = 1) pl.plot.layout["title"] = "t = $(sigdig(t))" react!(pl, plots, pl.plot.layout) sleep(0.12) end function solve!(V1, M, K, D, L0, L1, Psi0, V0, dt, nu) # This assumes zero EBC R = (L1 + L0)/2 + (1/dt)*(M*V0) - K*(Psi0 + (dt/4)*V0) - D*(Psi0 + (dt/4)*V0) V1[1:nu] = ((1/dt)*M + (dt/4)*(K + D))[1:nu, 1:nu] \ R[1:nu] return V1 end pl = 0 step = 0 t = 0.0 while t < tend if mod(step, 10) == 0 Psis = [Psi0[dofnum(Psih, 0, i, 1)] for i in 1:nshapes(ir.right)] if step == 0 curv = scatter(;x=xs, y=Psis, mode="lines") plots = cat(curv; dims = 1) pl = plot(plots, layout) display(pl) end updateplot(pl, t, xs, Psis) end solve!(V1, M, K, D, L0, L1, Psi0, V0, dt, nu) Psi1 = Psi0 + dt/2*(V1 + V0) t = t + dt step = step + 1 copyto!(V0, V1) copyto!(Psi0, Psi1) end # scattersysvec!(Psih, Psi0) # makeattribute(Psih, "Psi", 1) # vtkwrite("klein_gordon_wavelet-Psi", baseincrel(mesh), [(name = "Psi",)]) end end using .klein_gordon_wavelet klein_gordon_wavelet.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
8618
""" ht_p2_p1 The manufactured-solution colliding flow example from Elman et al 2014. The Hood-Taylor formulation with quadratic triangles for the velocity and continuous pressure on linear triangles. The formulation is the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. """ module ht_p2_p1 using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities, ir_identity, attribute, VecAttrib using MeshSteward: T6block, T6toT3 using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary, transform using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs, eldofvals using Elfel.FEIterators: jacjac, location using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 1.0 # dynamic viscosity A = 1.0 # half of the length of the side of the square trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 function genmesh(N) # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(2 * A, 2 * A, N, N), "velocity") ir = baseincrel(vmesh) transform(ir, x -> x .- A) # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(Uxh, Uyh, Ph, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(Uxh), FEIterator(Uyh), FEIterator(Ph)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs), QPIterator(Ph, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function evaluate_pressure_error(Ph) function integrate!(elit, qpit, truep) pnedof = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:pnedof pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end function evaluate_velocity_error(Uxh, Uyh) function integrate!(elits, qpits, trueux, trueuy) uxnedof, uynedof = ndofsperel.(elits) E = 0.0 for el in zip(elits...) uxel, uyel = el uxdofvals = eldofvals(uxel) uydofvals = eldofvals(uyel) for qp in zip(qpits...) uxqp, uyqp = qp Jac, J = jacjac(uxel, uxqp) JxW = J * weight(uxqp) Np = bfun(uxqp) uxt = trueux(location(uxel, uxqp)...) uyt = trueuy(location(uyel, uyqp)...) uxa = 0.0 uya = 0.0 for j in 1:uxnedof uxa += (uxdofvals[j] * Np[j]) uya += (uydofvals[j] * Np[j]) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elits = (FEIterator(Uxh), FEIterator(Uyh),) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs),) return integrate!(elits, qpits, trueux, trueuy) end function run(N) vmesh, pmesh = genmesh(N) # Velocity spaces Uxh = FESpace(Float64, vmesh, FEH1_T6(), 1) Uyh = FESpace(Float64, vmesh, FEH1_T6(), 1) locs = geometry(vmesh) inflate = A / N / 100 # The entire boundary boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, trueux(locs[i]...)) setebc!(Uyh, 0, i, 1, trueuy(locs[i]...)) end end # Pressure space Ph = FESpace(Float64, pmesh, FEH1_T3(), 1) atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(Ph, 0, atcenter[1], 1, 0.0) # Number the degrees of freedom numberdofs!([Uxh, Uyh, Ph]) tndof = ndofs(Uxh) + ndofs(Uyh) + ndofs(Ph) tnunk = nunknowns(Uxh) + nunknowns(Uyh) + nunknowns(Ph) # Assemble the coefficient matrix K = assembleK(Uxh, Uyh, Ph, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [Uxh, Uyh, Ph]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([Uxh, Uyh, Ph], U) # Postprocessing makeattribute(Ph, "p", 1) makeattribute(Uxh, "ux", 1) makeattribute(Uyh, "uy", 1) ep = evaluate_pressure_error(Ph) ev = evaluate_velocity_error(Uxh, Uyh) vtkwrite("ht_p2_p1-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("ht_p2_p1-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) geom = geometry(Ph.mesh) ir = baseincrel(Ph.mesh) pt = VecAttrib([truep(geom[i]...) for i in 1:length(geom)]) ir.right.attributes["pt"] = pt vtkwrite("ht_p2_p1-pt", baseincrel(pmesh), [(name = "pt",), ]) return (ep, ev) end end using .ht_p2_p1 let N = 4 for loop in 1:5 ep, ev = ht_p2_p1.run(N) @show N, ep, ev N = N * 2 end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6721
""" ht_p2_p1_gen The manufactured-solution colliding flow example from Elman et al 2014. The Hood-Taylor formulation with quadratic triangles for the velocity and continuous pressure on linear triangles. The formulation is the general elasticity-like scheme with strain-rate-displacement matrices. It can be manipulated into the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. """ module ht_p2_p1_gen using LinearAlgebra using StaticArrays using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using UnicodePlots mu = 1.0 # dynamic viscosity D = SMatrix{3, 3}( [2*mu 0 0 0 2*mu 0 0 0 mu]) A = 1.0 # half of the length of the side of the square trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 function genmesh(N) # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(2 * A, 2 * A, N, N), "velocity") ir = baseincrel(vmesh) transform(ir, x -> x .- A) # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(Uh, Ph, tndof, D) function integrateK!(ass, elits, qpits, D) B = (g, k) -> (k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1]))) c = edofcompnt(Uh) unedof, pnedof = ndofsperel.((Uh, Ph)) kuu = LocalMatrixAssembler(unedof, unedof, 0.0) kup = LocalMatrixAssembler(unedof, pnedof, 0.0) for el in zip(elits...) uel, pel = el init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) Np = bfun(pqp) for j in 1:unedof DBj = D * B(gradNu[j], c[j]) for i in 1:unedof Bi = B(gradNu[i], c[i]) kuu[i, j] += dot(Bi, DBj) * (JxW) end end for j in 1:pnedof, i in 1:unedof kup[i, j] += (-JxW * Np[j]) * gradNu[i][c[i]] end end assemble!(ass, kuu) assemble!(ass, kup) assemble!(ass, transpose(kup)) end return ass end elits = (FEIterator(Uh), FEIterator(Ph)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uh, qargs), QPIterator(Ph, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) integrateK!(ass, elits, qpits, D) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function evaluate_pressure_error(Ph) function integrate!(elit, qpit, truep) pnedof = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:pnedof pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end function evaluate_velocity_error(Uh) function integrate!(elit, qpit, trueux, trueuy) unedof = ndofsperel(elit) uedofcomp = edofcompnt(Uh) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:unedof (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(Uh) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Uh, qargs) return integrate!(elit, qpit, trueux, trueuy) end function run(N) vmesh, pmesh = genmesh(N) # Velocity space: space with two components Uh = FESpace(Float64, vmesh, FEH1_T6(), 2) locs = geometry(vmesh) inflate = A / N / 100 # The entire boundary boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uh, 0, i, 1, trueux(locs[i]...)) setebc!(Uh, 0, i, 2, trueuy(locs[i]...)) end end # Pressure space Ph = FESpace(Float64, pmesh, FEH1_T3(), 1) atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(Ph, 0, atcenter[1], 1, 0.0) # Number the degrees of freedom numberdofs!([Uh, Ph]) tndof = ndofs(Uh) + ndofs(Ph) tnunk = nunknowns(Uh) + nunknowns(Ph) # Assemble the coefficient matrix K = assembleK(Uh, Ph, tndof, D) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [Uh, Ph]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([Uh, Ph], U) # Postprocessing makeattribute(Ph, "p", 1) makeattribute(Uh, "ux", 1) makeattribute(Uh, "uy", 2) ep = evaluate_pressure_error(Ph) ev = evaluate_velocity_error(Uh) vtkwrite("ht_p2_p1_gen-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("ht_p2_p1_gen-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) # geom = geometry(Ph.mesh) # ir = baseincrel(Ph.mesh) # pt = VecAttrib([truep(geom[i]...) for i in 1:length(geom)]) # ir.right.attributes["pt"] = pt # vtkwrite("ht_p2_p1_gen-pt", baseincrel(pmesh), [(name = "pt",), ]) return (ep, ev) end end using .ht_p2_p1_gen let N = 4 for loop in 1:5 ep, ev = ht_p2_p1_gen.run(N) @show N, ep, ev N = N * 2 end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
8298
""" ht_p2_p1_veclap The manufactured-solution colliding flow example from Elman et al 2014. The Hood-Taylor formulation with quadratic triangles for the velocity and continuous pressure on linear triangles. The formulation is the one derived in Elman, et al., Finite elements and fast iterative solvers, p. 132. In other words, it is the vector Laplacian version. """ module ht_p2_p1_veclap using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities, ir_identity, attribute, VecAttrib using MeshSteward: T6block, T6toT3 using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary, transform using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs, eldofvals using Elfel.FEIterators: jacjac, location using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 1.0 # dynamic viscosity A = 1.0 # half of the length of the side of the square trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 function genmesh(N) # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(2 * A, 2 * A, N, N), "velocity") ir = baseincrel(vmesh) transform(ir, x -> x .- A) # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(Uxh, Uyh, Ph, tndof, mu) function integrate!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * dot(gradNux[i], gradNux[j]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * dot(gradNuy[i], gradNuy[j]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(Uxh), FEIterator(Uyh), FEIterator(Ph)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs), QPIterator(Ph, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) @time integrate!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function evaluate_pressure_error(Ph) function integrate!(elit, qpit, truep) pnedof = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:pnedof pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end function evaluate_velocity_error(Uxh, Uyh) function integrate!(elits, qpits, trueux, trueuy) uxnedof, uynedof = ndofsperel.(elits) E = 0.0 for el in zip(elits...) uxel, uyel = el uxdofvals = eldofvals(uxel) uydofvals = eldofvals(uyel) for qp in zip(qpits...) uxqp, uyqp = qp Jac, J = jacjac(uxel, uxqp) JxW = J * weight(uxqp) Np = bfun(uxqp) uxt = trueux(location(uxel, uxqp)...) uyt = trueuy(location(uyel, uyqp)...) uxa = 0.0 uya = 0.0 for j in 1:uxnedof uxa += (uxdofvals[j] * Np[j]) uya += (uydofvals[j] * Np[j]) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elits = (FEIterator(Uxh), FEIterator(Uyh),) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs),) return integrate!(elits, qpits, trueux, trueuy) end function run(N) vmesh, pmesh = genmesh(N) # Velocity spaces Uxh = FESpace(Float64, vmesh, FEH1_T6(), 1) Uyh = FESpace(Float64, vmesh, FEH1_T6(), 1) locs = geometry(vmesh) inflate = A / N / 100 # The entire boundary boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, trueux(locs[i]...)) setebc!(Uyh, 0, i, 1, trueuy(locs[i]...)) end end # Pressure space Ph = FESpace(Float64, pmesh, FEH1_T3(), 1) atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(Ph, 0, atcenter[1], 1, 0.0) # Number the degrees of freedom numberdofs!([Uxh, Uyh, Ph]) tndof = ndofs(Uxh) + ndofs(Uyh) + ndofs(Ph) tnunk = nunknowns(Uxh) + nunknowns(Uyh) + nunknowns(Ph) # Assemble the coefficient matrix K = assembleK(Uxh, Uyh, Ph, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [Uxh, Uyh, Ph]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([Uxh, Uyh, Ph], U) # Postprocessing makeattribute(Ph, "p", 1) makeattribute(Uxh, "ux", 1) makeattribute(Uyh, "uy", 1) ep = evaluate_pressure_error(Ph) ev = evaluate_velocity_error(Uxh, Uyh) vtkwrite("ht_p2_p1_veclap-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("ht_p2_p1_veclap-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) geom = geometry(Ph.mesh) ir = baseincrel(Ph.mesh) pt = VecAttrib([truep(geom[i]...) for i in 1:length(geom)]) ir.right.attributes["pt"] = pt vtkwrite("ht_p2_p1_veclap-pt", baseincrel(pmesh), [(name = "pt",), ]) return (ep, ev) end end using .ht_p2_p1_veclap let N = 2 for loop in 1:5 ep, ev = ht_p2_p1_veclap.run(N) @show N, ep, ev N = N * 2 end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
7528
""" ht_p2_p1_veclap_alt The manufactured-solution colliding flow example from Elman et al 2014. The Hood-Taylor formulation with quadratic triangles for the velocity and continuous pressure on linear triangles. This implementation is an alternative: for the velocity, a single finite element space with multiple components (2) is used instead of multiple finite element spaces. The formulation is the one derived in Donea, Huerta, Introduction to the finite element method, 1993. Page 486 ff, and Elman, et al., Finite elements and fast iterative solvers, p. 132. In other words, it is the vector Laplacian version. """ module ht_p2_p1_veclap_alt using LinearAlgebra using StaticArrays using MeshCore: retrieve, nrelations, nentities, ir_identity, attribute, VecAttrib using MeshSteward: T6block, T6toT3 using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary, transform using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs, eldofvals using Elfel.FEIterators: jacjac, location using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 1.0 # dynamic viscosity A = 1.0 # half of the length of the side of the square trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 function genmesh(N) # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(2 * A, 2 * A, N, N), "velocity") ir = baseincrel(vmesh) transform(ir, x -> x .- A) # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(ufesp, pfesp, tndof, mu) function integrate!(ass, elits, qpits, mu) unedof, pnedof = ndofsperel.(elits) uedofcomp = edofcompnt(ufesp) kuu = LocalMatrixAssembler(unedof, unedof, 0.0) kup = LocalMatrixAssembler(unedof, pnedof, 0.0) for el in zip(elits...) uel, pel = el init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) Np = bfun(pqp) for j in 1:unedof, i in 1:unedof if uedofcomp[i] == uedofcomp[j] kuu[i, j] += (mu * JxW) * (dot(gradNu[i], gradNu[j])) end end for j in 1:pnedof, i in 1:unedof kup[i, j] += (-JxW * Np[j]) * gradNu[i][uedofcomp[i]] end end assemble!(ass, kuu) assemble!(ass, kup) assemble!(ass, transpose(kup)) end return ass end elits = (FEIterator(ufesp), FEIterator(pfesp)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(ufesp, qargs), QPIterator(pfesp, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) integrate!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function evaluate_pressure_error(pfesp) function integrate!(elit, qpit, truep) pnedof = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:pnedof pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(pfesp) qargs = (kind = :default, npts = 3,) qpit = QPIterator(pfesp, qargs) return integrate!(elit, qpit, truep) end function evaluate_velocity_error(ufesp) function integrate!(elit, qpit, trueux, trueuy) unedof = ndofsperel(elit) uedofcomp = edofcompnt(ufesp) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:unedof (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(ufesp) qargs = (kind = :default, npts = 3,) qpit = QPIterator(ufesp, qargs) return integrate!(elit, qpit, trueux, trueuy) end function run(N) vmesh, pmesh = genmesh(N) # Velocity spaces ufesp = FESpace(Float64, vmesh, FEH1_T6(), 2) locs = geometry(vmesh) inflate = A / N / 100 # The entire boundary boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(ufesp, 0, i, 1, trueux(locs[i]...)) setebc!(ufesp, 0, i, 2, trueuy(locs[i]...)) end end # Pressure space pfesp = FESpace(Float64, pmesh, FEH1_T3(), 1) atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(pfesp, 0, atcenter[1], 1, 0.0) # Number the degrees of freedom numberdofs!([ufesp, pfesp]) tndof = ndofs(ufesp) + ndofs(pfesp) tnunk = nunknowns(ufesp) + nunknowns(pfesp) # Assemble the coefficient matrix K = assembleK(ufesp, pfesp, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [ufesp, pfesp]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([ufesp, pfesp], U) # Postprocessing makeattribute(pfesp, "p", 1) makeattribute(ufesp, "ux", 1) makeattribute(ufesp, "uy", 2) ep = evaluate_pressure_error(pfesp) ev = evaluate_velocity_error(ufesp) vtkwrite("ht_p2_p1_veclap_alt-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("ht_p2_p1_veclap_alt-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) return (ep, ev) end end using .ht_p2_p1_veclap_alt let N = 4 for loop in 1:5 ep, ev = ht_p2_p1_veclap_alt.run(N) @show N, ep, ev N = N * 2 end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
8060
""" p1b_p1 The manufactured-solution colliding flow example from Elman et al 2014. Formulation on linear triangles with a cubic bubble for the velocity. The formulation is the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. """ module p1b_p1 using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities, ir_identity, attribute using MeshSteward: T3block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary, transform using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T3_BUBBLE, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs, eldofvals using Elfel.FEIterators: jacjac, location using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 1.0 # dynamic viscosity A = 1.0 # half of the length of the side of the square trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 function genmesh(N) # This mesh will be both for the velocities and for the pressure mesh = Mesh() attach!(mesh, T3block(2 * A, 2 * A, N, N), "velocity+pressure") ir = baseincrel(mesh) transform(ir, x -> x .- A) eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(Uxh, Uyh, Ph, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(Uxh), FEIterator(Uyh), FEIterator(Ph)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs), QPIterator(Ph, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function evaluate_pressure_error(Ph) function integrate!(elit, qpit, truep) pnedof = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:pnedof pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end function evaluate_velocity_error(Uxh, Uyh) function integrate!(elits, qpits, trueux, trueuy) uxnedof, uynedof = ndofsperel.(elits) E = 0.0 for el in zip(elits...) uxel, uyel = el uxdofvals = eldofvals(uxel) uydofvals = eldofvals(uyel) for qp in zip(qpits...) uxqp, uyqp = qp Jac, J = jacjac(uxel, uxqp) JxW = J * weight(uxqp) Np = bfun(uxqp) uxt = trueux(location(uxel, uxqp)...) uyt = trueuy(location(uyel, uyqp)...) uxa = 0.0 uya = 0.0 for j in 1:uxnedof uxa += (uxdofvals[j] * Np[j]) uya += (uydofvals[j] * Np[j]) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elits = (FEIterator(Uxh), FEIterator(Uyh),) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs),) return integrate!(elits, qpits, trueux, trueuy) end function run(N) mesh = genmesh(N) # Velocity spaces Uxh = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 1) Uyh = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 1) locs = geometry(mesh) inflate = A / N / 100 # The entire boundary boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, trueux(locs[i]...)) setebc!(Uyh, 0, i, 1, trueuy(locs[i]...)) end end # Pressure space Ph = FESpace(Float64, mesh, FEH1_T3(), 1) atcenter = vselect(geometry(Ph.mesh); nearestto = [0.0, 0.0]) setebc!(Ph, 0, atcenter[1], 1, 0.0) # Number the degrees of freedom numberdofs!([Uxh, Uyh, Ph]) tndof = ndofs(Uxh) + ndofs(Uyh) + ndofs(Ph) tnunk = nunknowns(Uxh) + nunknowns(Uyh) + nunknowns(Ph) # Assemble the coefficient matrix K = assembleK(Uxh, Uyh, Ph, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [Uxh, Uyh, Ph]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([Uxh, Uyh, Ph], U) # Postprocessing makeattribute(Ph, "p", 1) makeattribute(Uxh, "ux", 1) makeattribute(Uyh, "uy", 1) ep = evaluate_pressure_error(Ph) ev = evaluate_velocity_error(Uxh, Uyh) vtkwrite("p1b_p1-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("p1b_p1-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) return (ep, ev) end end let N = 4 for loop in 1:5 ep, ev = p1b_p1.run(N) @show N, ep, ev N = N * 2 end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6757
""" q1_q0 The manufactured-solution colliding flow example from Elman et al 2014. The linear quadrilaterals for the velocity and discontinuous pressure. The formulation is the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. """ module q1_q0 using LinearAlgebra using StaticArrays using MeshCore using MeshCore: retrieve, nrelations, nentities, ir_identity, attribute using MeshSteward: Q4block using MeshSteward: Mesh, attach!, baseincrel, boundary, increl using MeshSteward: vselect, geometry, summary, transform using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEL2_Q4, FEH1_Q4, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 1.0 # dynamic viscosity A = 1.0 # length of the side of the square trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 function genmesh(N) # This mesh will be both for the velocities and for the pressure mesh = Mesh() attach!(mesh, Q4block(2 * A, 2 * A, N, N), "velocity+pressure") ir = baseincrel(mesh) transform(ir, x -> x .- A) eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(uxfesp, uyfesp, pfesp, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(uxel, uxqp) # L2 pressure: must integrate over the velocity mesh JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(uxfesp), FEIterator(uyfesp), FEIterator(pfesp)) qargs = (kind = :default, order = 2,) qpits = (QPIterator(uxfesp, qargs), QPIterator(uyfesp, qargs), QPIterator(pfesp, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) @time integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) @time KT = K * U @time U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end centroid(p, c) = begin (p[c[1]] + p[c[2]] + p[c[3]] + p[c[4]]) / 4 end function evaluate_error(uxfesp, uyfesp, pfesp) geom = geometry(pfesp.mesh) bir = baseincrel(pfesp.mesh) points = MeshCore.attribute(bir.right, "geom") centroids = [centroid(points, retrieve(bir, i)) for i in 1:nrelations(bir)] p = attribute(increl(pfesp.mesh, (2, 2)).right, "p") pt = [truep(centroids[i]...) for i in 1:length(centroids)] return norm(p - pt) / norm(pt) end function run(N) mesh = genmesh(N) # Velocity spaces uxfesp = FESpace(Float64, mesh, FEH1_Q4(), 1) uyfesp = FESpace(Float64, mesh, FEH1_Q4(), 1) locs = geometry(mesh) inflate = A / N / 100 # The entire boundary boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(uxfesp, 0, i, 1, trueux(locs[i]...)) setebc!(uyfesp, 0, i, 1, trueuy(locs[i]...)) end end # Pressure space pfesp = FESpace(Float64, mesh, FEL2_Q4(), 1) atcenter = vselect(geometry(mesh); nearestto = [0.0, 0.0]) setebc!(pfesp, 2, atcenter[1], 1, 0.0) # Number the degrees of freedom numberdofs!([uxfesp, uyfesp, pfesp]) @show tndof = ndofs(uxfesp) + ndofs(uyfesp) + ndofs(pfesp) @show tnunk = nunknowns(uxfesp) + nunknowns(uyfesp) + nunknowns(pfesp) # Assemble the coefficient matrix K = assembleK(uxfesp, uyfesp, pfesp, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [uxfesp, uyfesp, pfesp]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([uxfesp, uyfesp, pfesp], U) # Postprocessing makeattribute(pfesp, "p", 1) makeattribute(uxfesp, "ux", 1) makeattribute(uyfesp, "uy", 1) @show evaluate_error(uxfesp, uyfesp, pfesp) vtkwrite("q1_q0-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("q1_q0-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) true end end let N = 4 for loop in 1:5 q1_q0.run(N) N = N * 2 end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6176
""" ht_p2_p1 The famous driven-cavity benchmark is solved here with Hood-Taylor combination of quadratic and linear triangles. The formulation is the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. """ module ht_p2_p1 using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities using MeshSteward: T6block, T6toT3 using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 0.25 # dynamic viscosity A = 1.0 # length of the side of the square N = 100;# number of subdivisions along the sides of the square domain function genmesh() # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(A, A, N, N), "velocity") # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(Uxh, Uyh, Ph, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(Uxh), FEIterator(Uyh), FEIterator(Ph)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs), QPIterator(Ph, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) @time integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) @time KT = K * U @time U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function run() vmesh, pmesh = genmesh() # Velocity spaces Uxh = FESpace(Float64, vmesh, FEH1_T6(), 1) Uyh = FESpace(Float64, vmesh, FEH1_T6(), 1) locs = geometry(vmesh) inflate = A / N / 100 # Part of the boundary that is immovable boxes = [[0.0 A 0.0 0.0], [0.0 0.0 0.0 A], [A A 0.0 A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, 0.0) setebc!(Uyh, 0, i, 1, 0.0) end end # The lid uxbar = 1.0 box = [0.0 A A A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, uxbar) setebc!(Uyh, 0, i, 1, 0.0) end # Pressure space Ph = FESpace(Float64, pmesh, FEH1_T3(), 1) setebc!(Ph, 0, 1, 1, 0.0) # Number the degrees of freedom numberdofs!([Uxh, Uyh, Ph]) @show tndof = ndofs(Uxh) + ndofs(Uyh) + ndofs(Ph) @show tnunk = nunknowns(Uxh) + nunknowns(Uyh) + nunknowns(Ph) # Assemble the coefficient matrix K = assembleK(Uxh, Uyh, Ph, tndof, mu) p = spy(K, canvas = DotCanvas) display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [Uxh, Uyh, Ph]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([Uxh, Uyh, Ph], U) # Postprocessing makeattribute(Ph, "p", 1) makeattribute(Uxh, "ux", 1) makeattribute(Uyh, "uy", 1) vtkwrite("ht_p2_p1-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("ht_p2_p1-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) true end end ht_p2_p1.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
5948
""" ht_p2_p1_veclap The famous driven-cavity benchmark is solved here with Hood-Taylor combination of quadratic and linear triangles. The formulation is the one derived in Elman, et al., Finite elements and fast iterative solvers, p. 132. In other words, it is the vector Laplacian version. """ module ht_p2_p1_veclap using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities using MeshSteward: T6block, T6toT3 using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 0.25 # dynamic viscosity A = 1.0 # length of the side of the square N = 100;# number of subdivisions along the sides of the square domain function genmesh() # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(A, A, N, N), "velocity") # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(Uxh, Uyh, Ph, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(Uxh), FEIterator(Uyh), FEIterator(Ph)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs), QPIterator(Ph, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) @time integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) @time KT = K * U @time U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function run() vmesh, pmesh = genmesh() # Velocity spaces Uxh = FESpace(Float64, vmesh, FEH1_T6(), 1) Uyh = FESpace(Float64, vmesh, FEH1_T6(), 1) locs = geometry(vmesh) inflate = A / N / 100 # Part of the boundary that is immovable boxes = [[0.0 A 0.0 0.0], [0.0 0.0 0.0 A], [A A 0.0 A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, 0.0) setebc!(Uyh, 0, i, 1, 0.0) end end # The lid: driven in the X direction uxbar = 1.0 box = [0.0 A A A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, uxbar) setebc!(Uyh, 0, i, 1, 0.0) end # Pressure space Ph = FESpace(Float64, pmesh, FEH1_T3(), 1) setebc!(Ph, 0, 1, 1, 0.0) # Number the degrees of freedom numberdofs!([Uxh, Uyh, Ph]) @show tndof = ndofs(Uxh) + ndofs(Uyh) + ndofs(Ph) @show tnunk = nunknowns(Uxh) + nunknowns(Uyh) + nunknowns(Ph) # Assemble the coefficient matrix K = assembleK(Uxh, Uyh, Ph, tndof, mu) p = spy(K, canvas = DotCanvas) display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [Uxh, Uyh, Ph]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([Uxh, Uyh, Ph], U) # Postprocessing makeattribute(Ph, "p", 1) makeattribute(Uxh, "ux", 1) makeattribute(Uyh, "uy", 1) vtkwrite("ht_p2_p1_veclap-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("ht_p2_p1_veclap-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) end end ht_p2_p1_veclap.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
5994
""" p1b_p1 The famous driven-cavity benchmark is solved here with linear triangles with cubic bubbles for the velocity space and continuous linear triangle pressure space. The formulation is the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. """ module p1b_p1 using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities, ir_identity using MeshSteward: T3block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T3_BUBBLE, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 0.25 # dynamic viscosity A = 1.0 # length of the side of the square N = 100;# number of subdivisions along the sides of the square domain function genmesh() # This mesh will be both for the velocities and for the pressure mesh = Mesh() attach!(mesh, T3block(A, A, N, N), "velocity+pressure") ir = baseincrel(mesh) eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(Uxh, Uyh, Ph, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(Uxh), FEIterator(Uyh), FEIterator(Ph)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs), QPIterator(Ph, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) @time integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) @time KT = K * U @time U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function run() mesh = genmesh() # Velocity spaces Uxh = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 1) Uyh = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 1) locs = geometry(mesh) inflate = A / N / 100 # Part of the boundary that is immovable boxes = [[0.0 A 0.0 0.0], [0.0 0.0 0.0 A], [A A 0.0 A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, 0.0) setebc!(Uyh, 0, i, 1, 0.0) end end # The lid uxbar = 1.0 box = [0.0 A A A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, uxbar) setebc!(Uyh, 0, i, 1, 0.0) end # Pressure space Ph = FESpace(Float64, mesh, FEH1_T3(), 1) setebc!(Ph, 0, 1, 1, 0.0) # Number the degrees of freedom numberdofs!([Uxh, Uyh, Ph]) @show tndof = ndofs(Uxh) + ndofs(Uyh) + ndofs(Ph) @show tnunk = nunknowns(Uxh) + nunknowns(Uyh) + nunknowns(Ph) # Assemble the coefficient matrix K = assembleK(Uxh, Uyh, Ph, tndof, mu) p = spy(K, canvas = DotCanvas) display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [Uxh, Uyh, Ph]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([Uxh, Uyh, Ph], U) # Postprocessing makeattribute(Ph, "p", 1) makeattribute(Uxh, "ux", 1) makeattribute(Uyh, "uy", 1) vtkwrite("p1b_p1-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("p1b_p1-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) true end end p1b_p1.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6035
""" q1_q0 The famous driven-cavity benchmark is solved here with quadrilaterals with continuous bilinear representation for the velocity space and discontinuous piecewise constant pressure space. The formulation is the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. """ module q1_q0 using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities, ir_identity using MeshSteward: Q4block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEL2_Q4, FEH1_Q4, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 0.25 # dynamic viscosity A = 1.0 # length of the side of the square N = 35;# number of subdivisions along the sides of the square domain function genmesh() # This mesh will be both for the velocities and for the pressure mesh = Mesh() attach!(mesh, Q4block(A, A, N, N), "velocity+pressure") ir = baseincrel(mesh) eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(Uxh, Uyh, Ph, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(uxel, uxqp) # L2 pressure: must integrate elsewhere JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(Uxh), FEIterator(Uyh), FEIterator(Ph)) qargs = (kind = :default, order = 2,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs), QPIterator(Ph, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) @time integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) @time KT = K * U @time U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function run() mesh = genmesh() # Velocity spaces Uxh = FESpace(Float64, mesh, FEH1_Q4(), 1) Uyh = FESpace(Float64, mesh, FEH1_Q4(), 1) locs = geometry(mesh) inflate = A / N / 100 # Part of the boundary that is immovable boxes = [[0.0 A 0.0 0.0], [0.0 0.0 0.0 A], [A A 0.0 A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, 0.0) setebc!(Uyh, 0, i, 1, 0.0) end end # The lid uxbar = 1.0 box = [0.0 A A A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, uxbar) setebc!(Uyh, 0, i, 1, 0.0) end # Pressure space Ph = FESpace(Float64, mesh, FEL2_Q4(), 1) setebc!(Ph, 2, 1, 1, 0.0) # Number the degrees of freedom numberdofs!([Uxh, Uyh, Ph]) @show tndof = ndofs(Uxh) + ndofs(Uyh) + ndofs(Ph) @show tnunk = nunknowns(Uxh) + nunknowns(Uyh) + nunknowns(Ph) # Assemble the coefficient matrix K = assembleK(Uxh, Uyh, Ph, tndof, mu) p = spy(K, canvas = DotCanvas) display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [Uxh, Uyh, Ph]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([Uxh, Uyh, Ph], U) # Postprocessing makeattribute(Ph, "p", 1) makeattribute(Uxh, "ux", 1) makeattribute(Uyh, "uy", 1) vtkwrite("q1_q0-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("q1_q0-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) true end end q1_q0.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6123
""" q1_q0_irreg The famous driven-cavity benchmark is solved here with quadrilaterals with continuous bilinear representation for the velocity space and discontinuous piecewise constant pressure space. A strongly distorted mesh is used. The formulation is the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. """ module q1_q0_irreg using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities, ir_identity using MeshSteward: Q4blockwdistortion using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEL2_Q4, FEH1_Q4, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 0.25 # dynamic viscosity A = 1.0 # length of the side of the square N = 99;# number of subdivisions along the sides of the square domain function genmesh() # This mesh will be both for the velocities and for the pressure mesh = Mesh() attach!(mesh, Q4blockwdistortion(A, A, N, N), "velocity+pressure") ir = baseincrel(mesh) eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(Uxh, Uyh, Ph, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(uxel, uxqp) # L2 pressure: must integrate elsewhere JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(Uxh), FEIterator(Uyh), FEIterator(Ph)) qargs = (kind = :default, order = 2,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs), QPIterator(Ph, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) @time integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) @time KT = K * U @time U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function run() mesh = genmesh() # Velocity spaces Uxh = FESpace(Float64, mesh, FEH1_Q4(), 1) Uyh = FESpace(Float64, mesh, FEH1_Q4(), 1) locs = geometry(mesh) inflate = A / N / 100 # Part of the boundary that is immovable boxes = [[0.0 A 0.0 0.0], [0.0 0.0 0.0 A], [A A 0.0 A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, 0.0) setebc!(Uyh, 0, i, 1, 0.0) end end # The lid uxbar = 1.0 box = [0.0 A A A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(Uxh, 0, i, 1, uxbar) setebc!(Uyh, 0, i, 1, 0.0) end # Pressure space Ph = FESpace(Float64, mesh, FEL2_Q4(), 1) setebc!(Ph, 2, 1, 1, 0.0) # Number the degrees of freedom numberdofs!([Uxh, Uyh, Ph]) @show tndof = ndofs(Uxh) + ndofs(Uyh) + ndofs(Ph) @show tnunk = nunknowns(Uxh) + nunknowns(Uyh) + nunknowns(Ph) # Assemble the coefficient matrix K = assembleK(Uxh, Uyh, Ph, tndof, mu) p = spy(K, canvas = DotCanvas) display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [Uxh, Uyh, Ph]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([Uxh, Uyh, Ph], U) # Postprocessing makeattribute(Ph, "p", 1) makeattribute(Uxh, "ux", 1) makeattribute(Uyh, "uy", 1) vtkwrite("q1_q0_irreg-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("q1_q0_irreg-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) true end end q1_q0_irreg.run()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6413
module Assemblers using SparseArrays: sparse using LinearAlgebra using ..LocalAssemblers: LocalMatrixAssembler, init! """ AbstractSysmatAssembler Abstract type of system-matrix assembler. """ abstract type AbstractSysmatAssembler end; """ SysmatAssemblerSparse{T<:Number} <: AbstractSysmatAssembler Type for assembling a sparse global matrix from individual entries. """ mutable struct SysmatAssemblerSparse{T<:Number} <: AbstractSysmatAssembler row::Vector{Int64} col::Vector{Int64} val::Vector{T} nrow::Int64; ncol::Int64; end """ SysmatAssemblerSparse(zero::T=0.0) where {T<:Number} Construct blank system matrix assembler. The matrix entries are of type `T`. # Example This is how a sparse matrix is assembled from two rectangular dense matrices. ``` a = SysmatAssemblerSparse(0.0) start!(a, 7, 7) m = [0.24406 0.599773 0.833404 0.0420141 0.786024 0.00206713 0.995379 0.780298 0.845816 0.198459 0.355149 0.224996] gi = [1 7 5] gj = [5 2 1 4] for j in 1:size(m, 2), i in 1:size(m, 1) assemble!(a, gi[i], gj[j], m[i, j]) end m = [0.146618 0.53471 0.614342 0.737833 0.479719 0.41354 0.00760941 0.836455 0.254868 0.476189 0.460794 0.00919633 0.159064 0.261821 0.317078 0.77646 0.643538 0.429817 0.59788 0.958909] gi = [2 3 1 7 5] gj = [6 7 3 4] for j in 1:size(m, 2), i in 1:size(m, 1) assemble!(a, gi[i], gj[j], m[i, j]) end A = finish!(a) ``` """ function SysmatAssemblerSparse(zero::T=0.0) where {T<:Number} return SysmatAssemblerSparse{T}(fill(0, 0), fill(0, 0), fill(zero, 0), 0, 0) end """ start!(self::SysmatAssemblerSparse{T}, nrow, ncol) where {T<:Number} Start the assembly of a global matrix. """ function start!(self::SysmatAssemblerSparse{T}, nrow, ncol) where {T<:Number} nexpected = Int64(round(0.00001 * max(nrow, ncol, 10000)^2)) self.row = fill(0, 0) sizehint!(self.row, nexpected) self.col = fill(0, 0) sizehint!(self.col, nexpected) self.val = fill(zero(T), 0) sizehint!(self.val, nexpected) self.nrow = nrow; self.ncol = ncol; return self end """ assemble!(self::SysmatAssemblerSparse{T}, r, c, v::T) where {T<:Number} Assemble a single entry of a rectangular matrix. """ function assemble!(self::SysmatAssemblerSparse{T}, r, c, v::T) where {T<:Number} push!(self.row, r) push!(self.col, c) push!(self.val, v) return self end """ assemble!(self::SysmatAssemblerSparse{T}, lma::LocalMatrixAssembler{IT, T}) where {IT<:Integer, T<:Number} Assemble the row numbers, column numbers, and values from a local assembler. """ function assemble!(self::SysmatAssemblerSparse{T}, lma::LocalMatrixAssembler{IT, T}) where {IT<:Integer, T<:Number} append!(self.row, lma.row) append!(self.col, lma.col) append!(self.val, lma.M) return self end """ assemble!(self::SysmatAssemblerSparse{T}, lma::Transpose{T,LocalMatrixAssembler{IT,T}}) where {IT<:Integer, T<:Number} Assemble the row numbers, column numbers, and values from a local assembler. """ function assemble!(self::SysmatAssemblerSparse{T}, lma::Transpose{T,LocalMatrixAssembler{IT,T}}) where {IT<:Integer, T<:Number} append!(self.row, transpose(lma.parent.col)) append!(self.col, transpose(lma.parent.row)) append!(self.val, transpose(lma.parent.M)) return self end """ finish!(self::SysmatAssemblerSparse) Make a sparse matrix. """ function finish!(self::SysmatAssemblerSparse) return sparse(self.row, self.col, self.val, self.nrow, self.ncol); end """ AbstractSysvecAssembler Abstract type of system vector assembler. """ abstract type AbstractSysvecAssembler end; """ start!(self::SV, nrow) where {SV<:AbstractSysvecAssembler, T<:Number} Start assembly. The method makes the buffer for the vector assembly. It must be called before the first call to the method assemble. `nrow`= Total number of degrees of freedom. """ function start!(self::SV, nrow) where {SV<:AbstractSysvecAssembler, T<:Number} end """ assemble!(self::SV, i, val::T) where {SV<:AbstractSysvecAssembler, T<:Number} Assemble an elementwise vector. The method assembles a column element vector using the vector of degree of freedom numbers for the rows. """ function assemble!(self::SV, i, val::T) where {SV<:AbstractSysvecAssembler, T<:Number} end """ makevector!(self::SysvecAssembler) Make the global vector. """ function finish!(self::SV) where {SV<:AbstractSysvecAssembler} end """ SysvecAssembler Assembler for the system vector. """ mutable struct SysvecAssembler{T<:Number} <: AbstractSysvecAssembler val::Vector{T}; ndofs::Int64 end """ SysvecAssembler(zero::T=0.0) where {T<:Number} Construct blank system vector assembler. The vector entries are of type `T`. """ function SysvecAssembler(zero::T=0.0) where {T<:Number} return SysvecAssembler([zero], 0) end """ start!(self::SysvecAssembler{T}, nrow::Int64) where {T<:Number} Start assembly. The method makes the buffer for the vector assembly. It must be called before the first call to the method assemble. `nrow`= Total number of degrees of freedom. """ function start!(self::SysvecAssembler{T}, nrow::Int64) where {T<:Number} self.ndofs = nrow self.val = zeros(T, self.ndofs); return self end """ assemble!(self::SysvecAssembler{T}, i, val::T) where {T<:Number} Assemble a single value into the row `i`. """ function assemble!(self::SysvecAssembler{T}, i, val::T) where {T<:Number} self.val[i] = self.val[i] + val; return self end """ assemble!(self::SysvecAssembler{T}, lva) where {T<:Number} Assemble local vector assembler. """ function assemble!(self::SysvecAssembler{T}, lva) where {T<:Number} for i in 1:length(lva.row) gi = lva.row[i] self.val[gi] += lva.V[i]; end return self end """ finish!(self::SysvecAssembler) Make the global vector. """ function finish!(self::SysvecAssembler) return deepcopy(self.val); end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
526
module Elfel # Elfel (C) 2020, Petr Krysl include("utilities.jl") include("LocalAssemblers.jl") include("Assemblers.jl") include("RefShapes.jl") include("FElements.jl") include("FESpaces.jl") include("QPIterators.jl") include("FEIterators.jl") # We can either use/import individual functions from Elfel like so: # ``` # using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! # ``` # or we can bring into our context all exported symbols as # ``` # using Elfel.Exports # ``` include("Exports.jl") end # module
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
3193
module Exports # include("FElements.jl") # include("FEFields.jl") # include("FESpaces.jl") # include("QPIterators.jl") # include("FEIterators.jl") ############################################################################### using ..LocalAssemblers: LocalMatrixAssembler, init! using ..LocalAssemblers: LocalVectorAssembler, init! export LocalMatrixAssembler, init! export LocalVectorAssembler, init! ############################################################################### using ..Assemblers: AbstractSysmatAssembler, SysmatAssemblerSparse using ..Assemblers: AbstractSysvecAssembler, SysvecAssembler using ..Assemblers: start!, assemble!, finish! export AbstractSysmatAssembler, SysmatAssemblerSparse export AbstractSysvecAssembler, SysvecAssembler export start!, assemble!, finish! ############################################################################### using ..RefShapes: AbstractRefShape, RefShapePoint, RefShapeInterval, RefShapeSquare, RefShapeCube, RefShapeTriangle, RefShapeTetrahedron using ..RefShapes: manifdimv using ..RefShapes: IntegRule, npts, param_coords, weights, quadrature export AbstractRefShape, RefShapePoint, RefShapeInterval, RefShapeSquare, RefShapeCube, RefShapeTriangle, RefShapeTetrahedron, manifdimv export IntegRule, npts, param_coords, weights, quadrature ############################################################################### using ..FElements using ..FElements: FE, FEData using ..FElements: shapedesc, refshape, nfeatofdim, ndofperfeat, ndofsperel, manifdim, Jacobian, jacjac, bfun, bfungradpar using ..FElements: FEH1_L2, FEH1_T3, FEH1_T6, FEH1_Q4, FEH1_T3_BUBBLE, FEH1_T4 using ..FElements: FEL2_Q4, FEL2_T3, FEL2_T4 export FE, FEData export shapedesc, refshape, nfeatofdim, ndofperfeat, ndofsperel, manifdim, Jacobian, jacjac, bfun, bfungradpar export FEH1_L2, FEH1_T3, FEH1_T6, FEH1_Q4, FEH1_T3_BUBBLE, FEH1_T4 export FEL2_Q4, FEL2_T3, FEL2_T4 ############################################################################### import ..FESpaces: FESpace import ..FESpaces: doftype, edofmdim, edofbfnum, edofcompnt import ..FESpaces: ndofsperel, dofnum, numberfreedofs!, numberdatadofs!, ndofs import ..FESpaces: nunknowns, highestfreedofnum, highestdatadofnum import ..FESpaces: numberdofs!, setebc!, setdofval! import ..FESpaces: gathersysvec!, scattersysvec!, makeattribute export FESpace export doftype, edofmdim, edofbfnum, edofcompnt export ndofsperel, dofnum, numberfreedofs!, numberdatadofs!, ndofs export nunknowns, highestfreedofnum, highestdatadofnum export numberdofs!, setebc!, setdofval! export gathersysvec!, scattersysvec!, makeattribute ############################################################################### using ..QPIterators: QPIterator using ..QPIterators: bfun, bfungrad, bfungradpar, weight export QPIterator export bfun, bfungrad, bfungradpar, weight ############################################################################### using ..FEIterators: FEIterator using ..FEIterators: jacjac, location, ndofsperel, elnodes, eldofs, eldofentmdims, eldofcomps, eldofvals export FEIterator export jacjac, location, ndofsperel, elnodes, eldofs, eldofentmdims, eldofcomps, eldofvals end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6962
module FEFields using StaticArrays """ FEField{N, T, IT} Type of a finite element field. Parameterized with - `N`: number of degrees of freedom per entity, - `T`: type of the degree of freedom value, - `IT`: type of the index (integer value). This describes the serial numbers of the degrees of freedom. """ mutable struct FEField{N, T, IT} dofnums::Vector{SVector{N, IT}} isdatum::Vector{SVector{N, Bool}} dofvals::Vector{SVector{N, T}} """ FEField(::Val{N}, ::Type{T}, ::Type{IT}, ntrms) where {N, T, IT} Construct a field with the given number of terms `ntrms`. """ function FEField(::Val{N}, ::Type{T}, ::Type{IT}, ntrms) where {N, T, IT} z = fill(zero(IT), N) dofnums = [SVector{N}(z) for i in 1:ntrms] z = fill(false, N) isdatum = [z for i in 1:ntrms] z = fill(zero(T), N) dofvals = [SVector{N}(z) for i in 1:ntrms] return new{N, T, IT}(dofnums, isdatum, dofvals) end end """ doftype(fef::FEField{N, T, IT}) where {N, T, IT} Type of a degree of freedom value. """ doftype(fef::FEField{N, T, IT}) where {N, T, IT} = T """ dofnumtype(fef::FEField{N, T, IT}) where {N, T, IT} Type of the index (serial number) of the degree of freedom. Integer. """ dofnumtype(fef::FEField{N, T, IT}) where {N, T, IT} = IT """ nterms(fef::FEField) Number of terms in the field. """ nterms(fef::FEField) = length(fef.dofnums) """ ndofsperterm(fef::FEField{N}) where {N} Number of degrees of freedom per term of the field. """ ndofsperterm(fef::FEField{N}) where {N} = N """ ndofs(fef::FEField) Total number of degrees of freedom in the field. """ ndofs(fef::FEField) = nterms(fef) * ndofsperterm(fef) """ dofnums(fef::FEField, n) Provide degree of freedom numbers for given entity. """ dofnums(fef::FEField, n) = fef.dofnums[n] """ dofvals(fef::FEField, n) Provide degree of freedom values for given entity. """ dofvals(fef::FEField, n) = fef.dofvals[n] """ setebc!(self::FEField, tid, comp, val::T) where {T} Set the value of one particular degree of freedom to a given number. - `tid`: which term, - `comp`: which component of the term, - `flag`: true or false. """ function setisdatum!(self::FEField, tid, comp, flag) ik = MVector(self.isdatum[tid]) ik[comp] = flag self.isdatum[tid] = ik return self end """ setdofval!(self::FEField, tid, comp, val::T) where {T} Set the value of one particular degree of freedom to a given number. - `tid`: which term, - `comp`: which component of the term, - `val`: value to which the degree of freedom should be set. """ function setdofval!(self::FEField, tid, comp, val::T) where {T} d = MVector(self.dofvals[tid]) d[comp] = val self.dofvals[tid] = d return self end """ setebc!(self::FEField, tid, comp, val::T) where {T} Set the value of one particular degree of freedom to a given number. - `tid`: which term, - `comp`: which component of the term, - `val`: value to which the degree of freedom should be set. """ function setebc!(self::FEField, tid, comp, val::T) where {T} setisdatum!(self, tid, comp, true) setdofval!(self, tid, comp, val) return self end """ numberfreedofs!(f::FEField, firstnum = 1) Number the unknowns in the field, starting from the one supplied on input. Note: The data degrees of freedom have their numbers zeroed out. """ function numberfreedofs!(f::FEField, firstnum = 1) lnum = fnum = zero(dofnumtype(f)) + firstnum tnum = 0 for i in 1:nterms(f) n = MVector(f.dofnums[i]) for j in 1:ndofsperterm(f) if (!f.isdatum[i][j]) # unknown degree of freedom n[j] = lnum tnum = tnum + 1 lnum = lnum + 1 else n[j] = zero(dofnumtype(f)) end end f.dofnums[i] = n end return f end """ numberdatadofs!(f::FEField, firstnum = 1) Number the data degrees of freedom in the field. Start from the number supplied on input. Note: The free degrees of freedom must be numbered first. """ function numberdatadofs!(f::FEField, firstnum = 1) num = zero(dofnumtype(f)) + firstnum for i in 1:nterms(f) n = MVector(f.dofnums[i]) for j in 1:ndofsperterm(f) if (f.isdatum[i][j]) # known (data) degree of freedom n[j] = num num = num + 1 end end f.dofnums[i] = n end return f end """ freedofnums(f::FEField) Collect information about unknown (free) degree of freedom numbers. First number, last number, and the total number of degrees of freedom are returned as a tuple. """ function freedofnums(f::FEField) tnum = lnum = zero(dofnumtype(f)) fnum = typemax(dofnumtype(f)) for i in 1:nterms(f) for j in 1:ndofsperterm(f) # unknown degree of freedom if (!f.isdatum[i][j]) tnum = tnum + 1 lnum = max(lnum, f.dofnums[i][j]) fnum = min(fnum, f.dofnums[i][j]) end end end return (fnum, lnum, tnum) end """ highestfreedofnum(f::FEField) Compute the highest serial number of a free degree of freedom in the field. """ highestfreedofnum(f::FEField) = freedofnums(f)[2] """ datadofnums(f::FEField) Collect information about known (data) degree of freedom numbers. First number, last number, and the total number of degrees of freedom are returned as a tuple. """ function datadofnums(f::FEField) tnum = lnum = zero(dofnumtype(f)) fnum = typemax(dofnumtype(f)) for i in 1:nterms(f) for j in 1:ndofsperterm(f) # known degree of freedom if (f.isdatum[i][j]) tnum = tnum + 1 lnum = max(lnum, f.dofnums[i][j]) fnum = min(fnum, f.dofnums[i][j]) end end end return (fnum, lnum, tnum) end """ highestdatadofnum(f::FEField) Compute the highest serial number of a datum degree of freedom in the field. """ highestdatadofnum(f::FEField) = datadofnums(f)[2] """ gathersysvec!(vec, self::FEField) Gather system vector contributions from the field. """ function gathersysvec!(vec, self::FEField) nt = nterms(self) ndpt = ndofsperterm(self) for i in 1:nt en = self.dofnums[i] for j in 1:ndpt vec[en[j]] = self.dofvals[i][j] end end return vec end """ scattersysvec!(self::FEField, v) Scatter a system vector into the field. """ function scattersysvec!(self::FEField, v) vl = length(v) nt = nterms(self) ndpt = ndofsperterm(self) for i in 1:nt en = self.dofnums[i] for j in 1:ndpt if en[j] <= vl d = MVector(self.dofvals[i]) d[j] = v[en[j]] self.dofvals[i] = d end end end return self end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
7891
module FEIterators using StaticArrays using MeshCore using MeshCore: nshapes, indextype, nrelations, nentities, IncRel, shapedesc using MeshSteward: Mesh, baseincrel, increl using ..RefShapes: manifdim, manifdimv using ..FElements: refshape, nfeatofdim import ..FElements: jacjac using ..FESpaces.FEFields: FEField, ndofsperterm using ..FESpaces: FESpace, doftype import ..FESpaces: ndofsperel using ..QPIterators: QPIterator, bfungradpar #= TODO is it more natural to have access to the geometry from the font element space or from the iterator? =# """ FEIterator{FES, IR, G, IT, T, V, IR0, IR1, IR2, IR3, F0, F1, F2, F3} Type of finite element iterator. Parameterized with the types of - `FES`: finite element space, - `IR`: base incidence relation of the mesh, - `G`: type of the geometry attribute, - `IT`: type of integer indices, such as the numbers of nodes and degrees of freedom, - `T`: type of the degree of freedom value (real double, complex float, ... ), - `V`: `Val` representation of the manifold dimension of the base relation elements, - `IR0`, `IR1`, `IR2`, `IR3`: types of incidence relations with which degrees of freedom are associated in the finite element space, for each of the manifolds dimensions 0, 1, 2, 3, - `F0`, `F1`, `F2`, `F3`: types of fields with which degrees of freedom are associated in the finite element space, for each of the manifolds dimensions 0, 1, 2, 3. """ struct FEIterator{FES, IR, G, IT, T, V, IR0, IR1, IR2, IR3, F0, F1, F2, F3} fesp::FES _bir::IR _geom::G _dofs::Vector{IT} _dofvals::Vector{T} _entmdim::Vector{IT} _dofcomp::Vector{IT} _nodes::Vector{IT} _irs0::Union{Nothing, IR0} _irs1::Union{Nothing, IR1} _irs2::Union{Nothing, IR2} _irs3::Union{Nothing, IR3} _fld0::Union{Nothing, F0} _fld1::Union{Nothing, F1} _fld2::Union{Nothing, F2} _fld3::Union{Nothing, F3} _manifdimv::V _state::Vector{IT} function FEIterator(fesp::FES) where {FES} _bir = baseincrel(fesp.mesh) _geom = MeshCore.attribute(_bir.right, "geom") _dofs = zeros(Int64, ndofsperel(fesp)) _dofvals = zeros(doftype(fesp), ndofsperel(fesp)) _entmdim = zeros(Int64, ndofsperel(fesp)) _dofcomp = zeros(Int64, ndofsperel(fesp)) _nodes = zeros(Int64, nfeatofdim(fesp.fe, 0)) _fld0 = nothing _fld1 = nothing _fld2 = nothing _fld3 = nothing _irs0 = nothing _irs1 = nothing _irs2 = nothing _irs3 = nothing 0 in keys(fesp._irsfields) && (_irs0 = fesp._irsfields[0][1]; _fld0 = fesp._irsfields[0][2]) 1 in keys(fesp._irsfields) && (_irs1 = fesp._irsfields[1][1]; _fld1 = fesp._irsfields[1][2]) 2 in keys(fesp._irsfields) && (_irs2 = fesp._irsfields[2][1]; _fld2 = fesp._irsfields[2][2]) 3 in keys(fesp._irsfields) && (_irs3 = fesp._irsfields[3][1]; _fld3 = fesp._irsfields[3][2]) _manifdimv = Val(manifdim(refshape(fesp.fe))) p = 1 _irs0 != nothing && (p = _init_e_d!(_entmdim, _dofcomp, p, _irs0, _fld0)) _irs1 != nothing && (p = _init_e_d!(_entmdim, _dofcomp, p, _irs1, _fld1)) _irs2 != nothing && (p = _init_e_d!(_entmdim, _dofcomp, p, _irs2, _fld2)) _irs3 != nothing && (p = _init_e_d!(_entmdim, _dofcomp, p, _irs3, _fld3)) return new{FES, typeof(_bir), typeof(_geom), eltype(_dofs), doftype(fesp), typeof(_manifdimv), typeof(_irs0), typeof(_irs1), typeof(_irs2), typeof(_irs3), typeof(_fld0), typeof(_fld1), typeof(_fld2), typeof(_fld3)}(fesp, _bir, _geom, _dofs, _dofvals, _entmdim, _dofcomp, _nodes, _irs0, _irs1, _irs2, _irs3, _fld0, _fld1, _fld2, _fld3, _manifdimv, [0]) end end """ Base.iterate(it::FEIterator, state = 1) Advance the iterator to the next entity. The nodes of the finite element are cached, as is a vector of all the degrees of freedom represented on the element. """ function Base.iterate(it::FEIterator, state = 1) if state > nrelations(it._bir) return nothing else return (_update!(it, state), state+1) end end """ Base.length(it::FEIterator) Number of elements represented by this iterator. """ Base.length(it::FEIterator) = nrelations(it._bir) """ ndofsperel(it::FEIterator) Retrieve the number of degrees of freedom per element. """ ndofsperel(it::FEIterator) = ndofsperel(it.fesp) """ eldofs(it::FEIterator) Retrieve the vector of the element degrees of freedom """ eldofs(it::FEIterator) = it._dofs """ elnodes(it::FEIterator) Retrieve the vector of the nodes of the element. """ elnodes(it::FEIterator) = it._nodes """ eldofentmdims(it::FEIterator) Retrieve the vector of the entity dimensions for each element degree of freedom. Each degree of freedom is associated with some entity of the finite element: vertices, edges, faces, and so on. This vector records the dimension of the manifold entity with which each degree of freedom is associated. """ eldofentmdims(it::FEIterator) = it._entmdim """ eldofcomps(it::FEIterator) Retrieve the vector of the component numbers for each element degree of freedom. If multiple copies of the finite element are referenced in the finite element space, each copy is referred to as component. """ eldofcomps(it::FEIterator) = it._dofcomp function _init_e_d!(mdim, dofcomp, p, ir, fl) ndpt = ndofsperterm(fl) for k in 1:nentities(ir, 1) for i in 1:ndpt mdim[p] = MeshCore.manifdim(shapedesc(ir.right)) dofcomp[p] = i p = p + 1 end end return p end function _storedofs!(d, p, e, ir, fl) ndpt = ndofsperterm(fl) for k in 1:nentities(ir, e) gk = ir[e, k] for i in 1:ndpt d[p] = fl.dofnums[gk][i] p = p + 1 end end return p end function _storedofvals!(d, p, e, ir, fl) ndpt = ndofsperterm(fl) for k in 1:nentities(ir, e) gk = ir[e, k] for i in 1:ndpt d[p] = fl.dofvals[gk][i] p = p + 1 end end return p end function _update!(it::FEIterator, state) it._state[1] = state copyto!(it._nodes, it._bir[state]) p = 1 it._irs0 != nothing && (p = _storedofs!(it._dofs, p, state, it._irs0, it._fld0)) it._irs1 != nothing && (p = _storedofs!(it._dofs, p, state, it._irs1, it._fld1)) it._irs2 != nothing && (p = _storedofs!(it._dofs, p, state, it._irs2, it._fld2)) it._irs3 != nothing && (p = _storedofs!(it._dofs, p, state, it._irs3, it._fld3)) return it end """ eldofvals(it::FEIterator) Provide access to vector of element degrees of freedom. """ function eldofvals(it::FEIterator) p = 1 it._irs0 != nothing && (p = _storedofvals!(it._dofvals, p, it._state[1], it._irs0, it._fld0)) it._irs1 != nothing && (p = _storedofvals!(it._dofvals, p, it._state[1], it._irs1, it._fld1)) it._irs2 != nothing && (p = _storedofvals!(it._dofvals, p, it._state[1], it._irs2, it._fld2)) it._irs3 != nothing && (p = _storedofvals!(it._dofvals, p, it._state[1], it._irs3, it._fld3)) return it._dofvals end """ jacjac(it::FEIterator, qpit::QPIterator) Compute the Jacobian matrix and the Jacobian determinant. The finite element iterator cooperates with the quadrature point iterator here to compute the Jacobian at the current integration point. """ function jacjac(it::FEIterator, qpit::QPIterator) return jacjac(it.fesp.fe, it._geom, it._nodes, qpit._geomscalbfungrad_ps[qpit._pt]) end """ location(it::FEIterator, qpit::QPIterator) Calculate the location of the quadrature point. """ function location(it::FEIterator, qpit::QPIterator) n = it._nodes[1] loc = it._geom[n] * qpit._geomscalbfuns[qpit._pt][1] for i in 2:length(it._nodes) n = it._nodes[i] loc += it._geom[n] * qpit._geomscalbfuns[qpit._pt][i] end return loc end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
10428
module FESpaces using StaticArrays using MeshCore using MeshCore: nshapes, indextype, nrelations, nentities, IncRel, VecAttrib using MeshSteward: Mesh, baseincrel, increl using ..FElements: nfeatofdim, ndofperfeat, manifdim import ..FElements: ndofsperel include("FEFields.jl") using .FEFields: FEField, nterms import .FEFields: ndofs, setebc!, scattersysvec!, gathersysvec! import .FEFields: numberfreedofs!, numberdatadofs!, freedofnums, datadofnums import .FEFields: highestfreedofnum, highestdatadofnum, dofnums """ FESpace{FET, T} Type of a finite element space, parameterized with - `FET`: type of finite element, it is a *scalar* finite element, - `T`: type of degree of freedom value (double, complex, ...). """ struct FESpace{FET, T} mesh::Mesh fe::FET nfecopies::Int64 _irsfields::Dict _edofmdim::Vector{Int64} _edofbfnum::Vector{Int64} _edofcompnt::Vector{Int64} function FESpace(::Type{T}, mesh, fe::FET, nfecopies = 1) where {FET, T} baseir = baseincrel(mesh) _irsfields = _makefields(T, indextype(baseir), mesh, fe, nfecopies) _edofmdim, _edofbfnum, _edofcompnt = _number_edofs(fe, nfecopies) return new{FET, T}(mesh, fe, nfecopies, _irsfields, _edofmdim, _edofbfnum, _edofcompnt) end end """ doftype(fesp::FESpace{FET, T}) where {FET, T} Provide the type of the values of the degrees of freedom. """ doftype(fesp::FESpace{FET, T}) where {FET, T} = T """ edofmdim(fesp::FESpace{FET, T}) where {FET, T} Access vector of manifold dimensions of entities associated with each degree of freedom. """ edofmdim(fesp::FESpace{FET, T}) where {FET, T} = fesp._edofmdim """ edofbfnum(fesp::FESpace{FET, T}) where {FET, T} Access vector of numbers of basis functions associated with each degree of freedom. """ edofbfnum(fesp::FESpace{FET, T}) where {FET, T} = fesp._edofbfnum """ edofcompnt(fesp::FESpace{FET, T}) where {FET, T} Access vector of component number associated with each degree of freedom. When the finite element space consists of multiple copies of the scalar finite element, the component is the serial number of the copy. """ edofcompnt(fesp::FESpace{FET, T}) where {FET, T} = fesp._edofcompnt function _makefields(::Type{T}, ::Type{IT}, mesh, fe, nfecopies) where {T, IT} _irsfields= Dict() for m in 0:1:manifdim(fe) if ndofperfeat(fe, m) > 0 fir = increl(mesh, (manifdim(fe), m)) fld = FEField(Val(nfecopies), T, IT, nshapes(fir.right)) _irsfields[m] = (fir, fld) end end return _irsfields end function _number_edofs(fe, nfecopies) emdim = Int64[] bfnum = Int64[] compnt = Int64[] bfn = 1 for m in 0:1:3 for i in 1:nfeatofdim(fe, m) for k in 1:ndofperfeat(fe, m) for j in 1:nfecopies push!(emdim, m) push!(bfnum, bfn) push!(compnt, j) end bfn += 1 end end end return emdim, bfnum, compnt end """ ndofsperel(fesp::FES) where {FES<:FESpace} Total number of degrees of freedom associated with each finite element. Essentially a product of the number of the degrees of freedom the scalar finite element and the number of copies of this element in the space. """ ndofsperel(fesp::FES) where {FES<:FESpace} = ndofsperel(fesp.fe) * fesp.nfecopies """ dofnum(fesp::FES, m, eid) where {FES<:FESpace} Provide degree of freedom number for entity `eid` of manifold dimension `m` and component `comp`. """ function dofnum(fesp::FES, m, eid, comp) where {FES<:FESpace} n = zero(typeof(eid)) if ndofperfeat(fesp.fe, m) > 0 f = fesp._irsfields[m][2] n = dofnums(f, eid)[comp] end return n end """ numberfreedofs!(fesp::FES, firstnum = 1) where {FES<:FESpace} Number the free degrees of freedom. The unknown degrees of freedom in the FE space are numbered consecutively. No effort is made to optimize the numbering in any way. """ function numberfreedofs!(fesp::FES, firstnum = 1) where {FES<:FESpace} for m in keys(fesp._irsfields) if ndofperfeat(fesp.fe, m) > 0 f = fesp._irsfields[m][2] numberfreedofs!(f, firstnum) fnum, lnum, tnum = freedofnums(f) firstnum = lnum + 1 end end return fesp end """ numberdatadofs!(fesp::FES, firstnum = 1) where {FES<:FESpace} Number the data (known) degrees of freedom. The known degrees of freedom in the FE space are numbered consecutively. No effort is made to optimize the numbering in any way. """ function numberdatadofs!(fesp::FES, firstnum = 0) where {FES<:FESpace} firstnum = (firstnum == 0 ? nunknowns(fesp) + 1 : firstnum) for m in keys(fesp._irsfields) if ndofperfeat(fesp.fe, m) > 0 f = fesp._irsfields[m][2] numberdatadofs!(f, firstnum) fnum, lnum, tnum = datadofnums(f) firstnum = lnum + 1 end end return fesp end """ ndofs(fesp::FES) where {FES<:FESpace} Compute the total number of degrees of freedom. """ function ndofs(fesp::FES) where {FES<:FESpace} n = 0 for m in keys(fesp._irsfields) if ndofperfeat(fesp.fe, m) > 0 f = fesp._irsfields[m][2] n = n + ndofs(f) end end return n end """ nunknowns(fesp::FES) where {FES<:FESpace} Compute the total number of unknown degrees of freedom. """ function nunknowns(fesp::FES) where {FES<:FESpace} n = 0 for m in keys(fesp._irsfields) if ndofperfeat(fesp.fe, m) > 0 f = fesp._irsfields[m][2] fnum, lnum, tnum = freedofnums(f) n += tnum end end return n end """ highestfreedofnum(fesp::FES) where {FES<:FESpace} Compute the highest number of free (unknown) degrees of freedom. """ function highestfreedofnum(fesp::FES) where {FES<:FESpace} n = 0 for m in keys(fesp._irsfields) if ndofperfeat(fesp.fe, m) > 0 f = fesp._irsfields[m][2] n = max(n, highestfreedofnum(f)) end end return n end """ highestfreedofnum(fesp::FES) where {FES<:FESpace} Compute the highest number of data (known) degrees of freedom. """ function highestdatadofnum(fesp::FES) where {FES<:FESpace} n = 0 for m in keys(fesp._irsfields) if ndofperfeat(fesp.fe, m) > 0 f = fesp._irsfields[m][2] n = max(n, highestdatadofnum(f)) end end return n end """ numberdofs!(fesp::AbstractVector) Number the degrees of freedom of a collection of FE spaces. The unknown (free) degrees of freedom in the FE space are numbered consecutively, and then the data degrees of freedom (the known values) are numbered. No effort is made to optimize the numbering in any way. """ function numberdofs!(fesp::AbstractVector) numberfreedofs!(fesp[1], 1) for i in 2:length(fesp) numberfreedofs!(fesp[i], highestfreedofnum(fesp[i-1])+1) end numberdatadofs!(fesp[1], highestfreedofnum(fesp[end])+1) for i in 2:length(fesp) numberdatadofs!(fesp[i], highestdatadofnum(fesp[i-1])+1) end end """ numberdofs!(fesp::FESpace) Number the degrees of freedom of a single FE space. The unknown (free) degrees of freedom in the FE space are numbered consecutively, and then the data degrees of freedom (the known values) are numbered. No effort is made to optimize the numbering in any way. """ function numberdofs!(fesp::FESpace) numberdofs!([fesp]) end """ setebc!(fesp::FESpace, m, eid, comp, val::T) where {T} Set the EBCs (essential boundary conditions). - `m` = manifold dimension of the entity, - `eid` = serial number of the entity (term identifier), - `comp` = which degree of freedom in the term, - `val` = value of type T For instance, `m = 0` means set the degree of freedom at the vertex `eid`. """ function setebc!(fesp::FESpace, m, eid, comp, val::T) where {T} v = fesp._irsfields[m] setebc!(v[2], eid, comp, val) return fesp end """ setdofval!(fesp::FESpace, m, eid, comp, val::T) where {T} Set the value of a degree of freedom. - `m` = manifold dimension of the entity, - `eid` = serial number of the entity (term identifier), - `comp` = which degree of freedom in the term, - `val` = value of type T For instance, `m = 0` means set the degree of freedom at the vertex `eid`. """ function setdofval!(fesp::FESpace, m, eid, comp, val::T) where {T} v = fesp._irsfields[m] setdofval!(v[2], eid, comp, val) return fesp end """ gathersysvec!(v, fesp::FESpace) Gather values for the whole system vector. """ function gathersysvec!(v, fesp::FESpace) for m in keys(fesp._irsfields) if ndofperfeat(fesp.fe, m) > 0 gathersysvec!(v, fesp._irsfields[m][2]) end end return v end """ gathersysvec!(v, fesp) Gather values for the whole system vector from all FE spaces contributing to it. `fesp` is either a vector or a tuple of FE spaces. """ function gathersysvec!(v, fesp::AbstractVector) for i in 1:length(fesp) gathersysvec!(v, fesp[i]) end return v end """ scattersysvec!(fesp::FESpace, v) Scatter values from the system vector. """ function scattersysvec!(fesp::FESpace, v) for m in keys(fesp._irsfields) if ndofperfeat(fesp.fe, m) > 0 scattersysvec!(fesp._irsfields[m][2], v) end end return fesp end """ scattersysvec!(fesp, v) Scatter values for the whole system vector to all FE spaces contributing to it. `fesp` is either a vector or a tuple of FE spaces. """ function scattersysvec!(fesp::AbstractVector, v) for i in 1:length(fesp) scattersysvec!(fesp[i], v) end return fesp end """ makeattribute(fesp::FESpace, name, comp) Attach attribute to the right shape collection of all incidence relations. """ function makeattribute(fesp::FESpace, name, comp) for m in keys(fesp._irsfields) if ndofperfeat(fesp.fe, m) > 0 ir, fl = fesp._irsfields[m] v = fill(SVector{length(comp)}(zeros(length(comp))), nterms(fl)) for i in 1:nterms(fl) v[i] = SVector{length(comp)}(fl.dofvals[i][comp]) end ir.right.attributes[name] = VecAttrib(v) end end end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
13532
module FElements using StaticArrays using LinearAlgebra using MeshCore import MeshCore: manifdim using ..RefShapes: RefShapePoint, RefShapeInterval, RefShapeTriangle, RefShapeTetrahedron, RefShapeSquare, RefShapeCube, manifdimv """ FE{RS, SD} Abstract type of finite element, parameterized by - `RS`: type of reference shape of the element (triangle, square, ...), and - `SD`: shape descriptor; refer to the package `MeshCore`. """ abstract type FE{RS, SD} end """ FEData{SD} Type of a finite element data. Parameterized by - `SD` = shape descriptor; refer to the package `MeshCore`. """ struct FEData{SD} sd::SD _ndofperfeat::SVector{4, Int64} end """ shapedesc(fe::FE{RS, SD}) where {RS, SD} Topological shape description. Refer to the MeshCore library. """ shapedesc(fe::FE{RS, SD}) where {RS, SD} = fe.data.sd """ refshape(fe::FE{RS, SD}) where {RS, SD} Reference shape. """ refshape(fe::FE{RS, SD}) where {RS, SD} = RS """ nfeatofdim(fe::FE{RS, SD}, m) where {RS, SD} Number of features of manifold dimension `m`. Note that `0 <= m <= 3`. """ nfeatofdim(fe::FE{RS, SD}, m) where {RS, SD} = MeshCore.nfeatofdim(fe.data.sd, m) """ feathasdof(fe::FE{RS, SD}, m) where {RS, SD} How many degrees of freedom are attached to a the feature of manifold dimension `m`? Note that `0 <= m <= 3`. """ ndofperfeat(fe::FE{RS, SD}, m) where {RS, SD} = fe.data._ndofperfeat[m+1] """ ndofsperel(fe::FE{RS, SD}) where {RS, SD} Provide the number of degrees of freedom per element. Enumerate all features of all manifold dimensions, and for each feature multiply by the number of degrees of freedom per feature. The assumption is that this is a *scalar* finite element. """ function ndofsperel(fe::FE{RS, SD}) where {RS, SD} md = manifdim(fe.data.sd) n = 0 for m in 0:1:md n = n + nfeatofdim(fe, m) * ndofperfeat(fe, m) end return n end """ manifdim(fe::FE{RS, SD}) where {RS, SD} Get the manifold dimension of the finite element. """ manifdim(fe::FE{RS, SD}) where {RS, SD} = MeshCore.manifdim(fe.data.sd) """ Jacobian(::Val{0}, J::T) where {T} Evaluate the point Jacobian. - `J` = Jacobian matrix, which isn't really defined well for a 0-manifold. """ function Jacobian(::Val{0}, J::T) where {T} return 1.0; end """ Jacobian(::Val{1}, J::T) where {T} Evaluate the curve Jacobian. - `J` = Jacobian matrix, columns are tangent to parametric coordinates curves. """ function Jacobian(::Val{1}, J::T) where {T} sdim, ntan = size(J); @assert ntan == 1 "Expected number of tangent vectors: 1" return norm(J) end """ Jacobian(::Val{2}, J::T) where {T} Evaluate the curve Jacobian. - `J` = Jacobian matrix, columns are tangent to parametric coordinates curves. """ function Jacobian(::Val{2}, J::T) where {T} sdim, ntan = size(J); @assert ntan == 2 "Expected number of tangent vectors: 2" if sdim == ntan @inbounds Jac = (J[1, 1]*J[2, 2] - J[2, 1]*J[1, 2]) return Jac;# is det(J);% Compute the Jacobian else return norm(cross(J[:, 1], J[:, 2])); end end """ Jacobian(fe::T, J::FFltMat)::FFlt where {T<:AbstractFESet3Manifold} Evaluate the volume Jacobian. `J` = Jacobian matrix, columns are tangent to parametric coordinates curves. """ function Jacobian(::Val{3}, J::T) where {T} sdim, ntan = size(J); @assert (ntan == 3) && (sdim == 3) "Expected number of tangent vectors: 3" #Jac = det(J);# Compute the Jacobian # The unrolled version return (+J[1, 1]*(J[2, 2]*J[3, 3]-J[3, 2]*J[2, 3]) -J[1, 2]*(J[2, 1]*J[3, 3]-J[2, 3]*J[3, 1]) +J[1, 3]*(J[2, 1]*J[3, 2]-J[2, 2]*J[3, 1]) ) end function _jac(locs, conn, gradNpar) NBFPE = length(conn) j = 1 J = locs[conn[j]] * gradNpar[j] @inbounds for j in 2:NBFPE J += locs[conn[j]] * gradNpar[j] end return J end """ jacjac(fe::FE{RS, SD}, locs, nodes, gradNpar) where {RS, SD} Compute the Jacobian matrix and the Jacobian determinant. This is the generic version suitable for isoparametric elements. """ function jacjac(fe::FE{RS, SD}, locs, nodes, gradNpar) where {RS, SD} Jac = _jac(locs, nodes, gradNpar) return (Jac, Jacobian(manifdimv(refshape(fe)), Jac)) end """ bfun(fe::FESUBT, param_coords) where {FESUBT<:FE{RS, SD}} Evaluate the basis functions for all degrees of freedom of the scalar finite element at the parametric coordinates. Return a vector of the values. """ function bfun(fe::FESUBT, param_coords) where {FESUBT<:FE{RS, SD}} where {RS, SD} end """ bfungradpar(fe::FESUBT, param_coords) where {FESUBT<:FE{RS, SD}} Evaluate the gradients of the basis functions for all degrees of freedom of the scalar finite element with respect to the parametric coordinates, at the parametric coordinates given. Return a vector of the gradients. """ function bfungradpar(fe::FESUBT, param_coords) where {FESUBT<:FE{RS, SD}} where {RS, SD} end """ The elements that have nodal bases can be their own geometry carriers. Elements that do not have nodal bases, for instance an L2 quadrilateral with a single basis function associated with the cell, need another element type (in this case the nodal quadrilateral) to serve as geometry carriers. """ _geometrycarrier(fe::T) where {T<:FE{RS, SD}} where {RS, SD} = fe # L2 ================================================================== # Linear two-node element. Only nodal basis functions. struct FEH1_L2_Type{RS, SD} <: FE{RS, SD} data::FEData{SD} end FEH1_L2_TYPE = FEH1_L2_Type{RefShapeInterval, typeof(MeshCore.L2)} """ FEH1_L2() Construct an H1 finite element of the type L2. L2 is two-node linear segment element. """ FEH1_L2() = FEH1_L2_TYPE(FEData(MeshCore.L2, SVector{4}([1, 0, 0, 0]))) function bfun(fe::FEH1_L2_TYPE, param_coords) return SVector{2}([(1. - param_coords[1]); (1. + param_coords[1])] / 2.0) end function bfungradpar(fe::FEH1_L2_TYPE, param_coords) g = reshape([-1.0; +1.0]/2.0, 2, 1) return [SVector{1}(g[idx, :])' for idx in 1:size(g, 1)] end # T3 ================================================================== # Linear triangular element. Only nodal basis functions. struct FEH1_T3_Type{RS, SD} <: FE{RS, SD} data::FEData{SD} end FEH1_T3_TYPE = FEH1_T3_Type{RefShapeTriangle, typeof(MeshCore.T3)} """ FEH1_T3() Construct an H1 finite element of the type T3. T3 is 3-node linear triangle element. """ FEH1_T3() = FEH1_T3_TYPE(FEData(MeshCore.T3, SVector{4}([1, 0, 0, 0]))) function bfun(fe::FEH1_T3_TYPE, param_coords) return SVector{3}([(1 - param_coords[1] - param_coords[2]); param_coords[1]; param_coords[2]]) end function bfungradpar(fe::FEH1_T3_TYPE, param_coords) g = [-1. -1.; +1. 0.; 0. +1.] return [SVector{2}(g[idx, :])' for idx in 1:size(g, 1)] end # T6 ================================================================== # Quadratic triangular element. Only nodal basis functions. struct FEH1_T6_Type{RS, SD} <: FE{RS, SD} data::FEData{SD} end FEH1_T6_TYPE = FEH1_T6_Type{RefShapeTriangle, typeof(MeshCore.T6)} """ FEH1_T6() Construct an H1 finite element of the type T6. T6 is 6-node quadratic triangle element. """ FEH1_T6() = FEH1_T6_TYPE(FEData(MeshCore.T6, SVector{4}([1, 0, 0, 0]))) function bfun(fe::FEH1_T6_TYPE, param_coords) r=param_coords[1]; s=param_coords[2]; t = 1. - r - s; val = [t * (t + t - 1); r * (r + r - 1); s * (s + s - 1); 4 * r * t; 4 * r * s; 4 * s * t]; return SVector{6}(val) end function bfungradpar(fe::FEH1_T6_TYPE, param_coords) r =param_coords[1]; s =param_coords[2]; t = 1. - r - s; val = [-3+4*r+4*s -3+4*r+4*s; 4*r-1 0.0; 0.0 4*s-1; 4-8*r-4*s -4*r; 4*s 4*r; -4*s 4-4*r-8*s]; return [SVector{2}(val[idx, :])' for idx in 1:size(val, 1)] end # Q4 ================================================================== # Linear quadrilateral element. Only nodal basis functions. struct FEH1_Q4_Type{RS, SD} <: FE{RS, SD} data::FEData{SD} end FEH1_Q4_TYPE = FEH1_Q4_Type{RefShapeSquare, typeof(MeshCore.Q4)} """ FEH1_Q4() Construct an H1 finite element of the type Q4. Q4 is 4-node linear quadrilateral element. """ FEH1_Q4() = FEH1_Q4_TYPE(FEData(MeshCore.Q4, SVector{4}([1, 0, 0, 0]))) function bfun(fe::FEH1_Q4_TYPE, param_coords) val = [0.25 * (1. - param_coords[1]) * (1. - param_coords[2]); 0.25 * (1. + param_coords[1]) * (1. - param_coords[2]); 0.25 * (1. + param_coords[1]) * (1. + param_coords[2]); 0.25 * (1. - param_coords[1]) * (1. + param_coords[2])]; return SVector{4}(val) end function bfungradpar(fe::FEH1_Q4_TYPE, param_coords) g = [-(1. - param_coords[2])*0.25 -(1. - param_coords[1])*0.25; (1. - param_coords[2])*0.25 -(1. + param_coords[1])*0.25; (1. + param_coords[2])*0.25 (1. + param_coords[1])*0.25; -(1. + param_coords[2])*0.25 (1. - param_coords[1])*0.25]; return [SVector{2}(g[idx, :])' for idx in 1:size(g, 1)] end # T3-BUBBLE ================================================================== # Linear triangular element with a cubic interior bubble. struct FEH1_T3_BUBBLE_Type{RS, SD} <: FE{RS, SD} data::FEData{SD} end FEH1_T3_BUBBLE_TYPE = FEH1_T3_BUBBLE_Type{RefShapeTriangle, typeof(MeshCore.T3)} """ FEH1_T3_BUBBLE() Construct an H1 finite element of the type T3 with a cubic bubble. T3 is 3-node linear triangle element with a cubic bubble. It has the usual nodal basis functions associated with the vertices, and cubic bubble associated with the element itself. """ FEH1_T3_BUBBLE() = FEH1_T3_BUBBLE_TYPE(FEData(MeshCore.T3, SVector{4}([1, 0, 1, 0]))) function bfun(fe::FEH1_T3_BUBBLE_TYPE, param_coords) xi, eta = param_coords return SVector{4}([(1 - xi - eta); xi; eta; (1 - xi - eta) * xi * eta]) end function bfungradpar(fe::FEH1_T3_BUBBLE_TYPE, param_coords) xi, eta = param_coords g = [-1. -1.; +1. 0.; 0. +1.; (-xi * eta + (1 - xi - eta) * eta) (-xi * eta + (1 - xi - eta) * xi)] return [SVector{2}(g[idx, :])' for idx in 1:size(g, 1)] end # T4 ================================================================== # Linear tetrahedral element. Only nodal basis functions. struct FEH1_T4_Type{RS, SD} <: FE{RS, SD} data::FEData{SD} end FEH1_T4_TYPE = FEH1_T4_Type{RefShapeTetrahedron, typeof(MeshCore.T4)} """ FEH1_T4() Construct an H1 finite element of the type T4. T4 is 4-node linear tetrahedral element. """ FEH1_T4() = FEH1_T4_TYPE(FEData(MeshCore.T4, SVector{4}([1, 0, 0, 0]))) function bfun(fe::FEH1_T4_TYPE, param_coords) return SVector{4}([(1 - param_coords[1] - param_coords[2] - param_coords[3]); param_coords[1]; param_coords[2]; param_coords[3]]) end function bfungradpar(fe::FEH1_T4_TYPE, param_coords) g = [-1.0 -1.0 -1.0; +1.0 0.0 0.0; 0.0 +1.0 0.0; 0.0 0.0 +1.0] return [SVector{3}(g[idx, :])' for idx in 1:size(g, 1)] end # Q4 ================================================================== # Quadrilateral element. Only interior basis functions. # To do: Provide more than the constant basis function only. Perhaps by # additional parameters to the constructor? struct FEL2_Q4_Type{RS, SD} <: FE{RS, SD} data::FEData{SD} end FEL2_Q4_TYPE = FEL2_Q4_Type{RefShapeSquare, typeof(MeshCore.Q4)} _geometrycarrier(fe::FEL2_Q4_TYPE) = FEH1_Q4() """ FEL2_Q4() Construct an L2 finite element of the type Q4. Q4 is 4-node linear quadrilateral element. """ FEL2_Q4() = FEL2_Q4_TYPE(FEData(MeshCore.Q4, SVector{4}([0, 0, 1, 0]))) function bfun(fe::FEL2_Q4_TYPE, param_coords) return SVector{1}(1.0) end function bfungradpar(fe::FEL2_Q4_TYPE, param_coords) g = [0.0 0.0]; return [SVector{2}(g[idx, :])' for idx in 1:size(g, 1)] end # T3 ================================================================== # Triangular element. Only interior basis functions. struct FEL2_T3_Type{RS, SD} <: FE{RS, SD} data::FEData{SD} end FEL2_T3_TYPE = FEL2_T3_Type{RefShapeTriangle, typeof(MeshCore.T3)} _geometrycarrier(fe::FEL2_T3_TYPE) = FEH1_T3() """ FEL2_T3() Construct an L2 finite element of the type T3. T3 is 3-node linear triangle element. """ FEL2_T3() = FEL2_T3_TYPE(FEData(MeshCore.T3, SVector{4}([0, 0, 1, 0]))) function bfun(fe::FEL2_T3_TYPE, param_coords) return SVector{1}(1.0) end function bfungradpar(fe::FEL2_T3_TYPE, param_coords) g = [0.0 0.0]; return [SVector{2}(g[idx, :])' for idx in 1:size(g, 1)] end # T4 ================================================================== # Tetrahedral element. Only interior basis functions. # To do: Provide more than the constant basis function only. Perhaps by # additional parameters to the constructor? struct FEL2_T4_Type{RS, SD} <: FE{RS, SD} data::FEData{SD} end FEL2_T4_TYPE = FEL2_T4_Type{RefShapeTetrahedron, typeof(MeshCore.T4)} _geometrycarrier(fe::FEL2_T4_TYPE) = FEH1_T4() """ FEL2_T4() Construct an L2 finite element of the type T4. T4 is tetrahedral element with only internal degrees of freedom. """ FEL2_T4() = FEL2_T4_TYPE(FEData(MeshCore.T4, SVector{4}([0, 0, 0, 1]))) function bfun(fe::FEL2_T4_TYPE, param_coords) return SVector{1}(1.0) end function bfungradpar(fe::FEL2_T4_TYPE, param_coords) g = [0.0 0.0 0.0]; return [SVector{3}(g[idx, :])' for idx in 1:size(g, 1)] end end # module
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
4482
module LocalAssemblers """ LocalMatrixAssembler{IT<:Integer, T<:Number} <: AbstractArray{T, 2} Type of "local" matrix assembler. Local is to be understood in the sense of in the context of a single finite element. So a local matrix is an elementwise matrix which is computed entry by entry. Then it can be assembled into the global matrix in one shot. """ struct LocalMatrixAssembler{IT<:Integer, T<:Number} <: AbstractArray{T, 2} row::Matrix{IT} col::Matrix{IT} M::Matrix{T} end """ LocalMatrixAssembler(nrow::IT, ncol::IT, z::T) where {IT, T} Create a local matrix assembler, given the number of rows and columns, and the value to which the matrix should be initialized. """ function LocalMatrixAssembler(nrow::IT, ncol::IT, z::T) where {IT, T} return LocalMatrixAssembler(fill(zero(IT), nrow, ncol), fill(zero(IT), nrow, ncol), fill(z, nrow, ncol)) end """ Base.IndexStyle(::Type{<:LocalMatrixAssembler}) The data storage is assumed to be consumed best by one-dimensional traversal through the columns in a linear fashion. """ Base.IndexStyle(::Type{<:LocalMatrixAssembler}) = IndexLinear() """ Base.size(a::A) where {A<:LocalMatrixAssembler} The size is the tuple of number of rows and number of columns. """ Base.size(a::A) where {A<:LocalMatrixAssembler} = size(a.M) """ Base.getindex(a::A, i::Int, j::Int) Only access to a single entry of the matrix is provided. """ Base.getindex(a::A, i::Int, j::Int) where {A<:LocalMatrixAssembler} = a.M[i, j] """ Base.setindex!(a::A, v, i::Int, j::Int) where {A<:LocalMatrixAssembler} Only access to a single entry of the matrix is provided. """ Base.setindex!(a::A, v, i::Int, j::Int) where {A<:LocalMatrixAssembler} = (a.M[i, j] = v) """ init!(a::L, rdofs, cdofs) where {L<:LocalMatrixAssembler{IT, T}} where {IT, T} Initialize the local assembler with the global degrees of freedom in the rows and columns. The two arrays, `rdofs`, `cdofs`, define the global degree of freedom numbers for the element. The data matrix is zeroed out. This function needs to be called for each new finite element. """ function init!(a::L, rdofs, cdofs) where {L<:LocalMatrixAssembler{IT, T}} where {IT, T} nr = length(rdofs) nc = length(cdofs) k = 1 for j in 1:nc gj = cdofs[j] for i in 1:nr gi = rdofs[i] a.row[k] = gi a.col[k] = gj k += 1 end end fill!(a.M, zero(T)) return a end """ LocalVectorAssembler{IT<:Integer, T<:Number} <: AbstractArray{T, 1} Type of "local" vector assembler. Local is to be understood in the sense of in the context of a single finite element. So a local vector is an elementwise vector which is computed entry by entry. Then it can be assembled into the global vector in one shot. """ struct LocalVectorAssembler{IT<:Integer, T<:Number} <: AbstractArray{T, 1} row::Vector{IT} V::Vector{T} end """ LocalVectorAssembler(nrow::IT, z::T) where {IT, T} Create a local vector assembler, given the number of entries, and the value to which the vector should be initialized. """ function LocalVectorAssembler(nrow::IT, z::T) where {IT, T} return LocalVectorAssembler(fill(zero(IT), nrow), fill(z, nrow)) end """ Base.IndexStyle(::Type{<:LocalVectorAssembler}) Only linear access is provided. """ Base.IndexStyle(::Type{<:LocalVectorAssembler}) = IndexLinear() """ Base.size(a::A) where {A<:LocalVectorAssembler} The size is the number of rows (entries). """ Base.size(a::A) where {A<:LocalVectorAssembler} = size(a.V) """ Base.getindex(a::A, i::Int) where {A<:LocalVectorAssembler} Access is provided to a single entry of the vector. """ Base.getindex(a::A, i::Int) where {A<:LocalVectorAssembler} = a.V[i] """ Base.setindex!(a::A, v, i::Int) where {A<:LocalVectorAssembler} Access is provided to a single entry of the vector. """ Base.setindex!(a::A, v, i::Int) where {A<:LocalVectorAssembler} = (a.V[i] = v) """ init!(a::L, rdofs) where {L<:LocalVectorAssembler{IT, T}} where {IT, T} Initialize the local assembler with the global degrees of freedom in the rows. The array `rdofs` defines the global degree of freedom numbers for the element. The data vector is zeroed out. This function needs to be called for each new finite element. """ function init!(a::L, rdofs) where {L<:LocalVectorAssembler{IT, T}} where {IT, T} copyto!(a.row, rdofs) fill!(a.V, zero(T)) return a end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
4882
module QPIterators using StaticArrays using LinearAlgebra using ..RefShapes: manifdim, IntegRule, quadrature using ..RefShapes: npts, param_coords, weights using ..FElements: refshape, ndofsperel, _geometrycarrier import ..FElements: bfun, bfungradpar, jacjac using ..FESpaces: edofbfnum # To do: Create the data structure for an element that has multiple degrees of # freedom per entity. Also store the basic data for the scalar finite element # (single degree of freedom per entity). function __bfundata(fesp, qr) bfnum = edofbfnum(fesp) nedof = length(bfnum) pc = qr.param_coords w = qr.weights npts = qr.npts MDIM = manifdim(refshape(fesp.fe)) # First construct vectors of vectors of basis function values and matrices # of base function gradients in parametric coordinates for the scalar # element scalNs = Vector{Float64}[]; scalgradNps = Vector{Adjoint{Float64,SArray{Tuple{MDIM},Float64,1,MDIM}}}[]; for j in 1:npts push!(scalNs, bfun(fesp.fe, pc[j,:])) push!(scalgradNps, bfungradpar(fesp.fe, pc[j,:])) end scalgradN = similar(scalgradNps[1]) # Now extend it to the vector element Ns = Vector{Float64}[]; gradNps = Vector{Adjoint{Float64,SArray{Tuple{MDIM},Float64,1,MDIM}}}[]; for j in 1:npts N = [scalNs[j][bfnum[k]] for k in 1:nedof] gN = [scalgradNps[j][bfnum[k]] for k in 1:nedof] push!(Ns, N) push!(gradNps, gN) end gradN = similar(gradNps[1]) # Now do this for the geometry carrier gcfe = _geometrycarrier(fesp.fe) geomscalNs = Vector{Float64}[]; geomscalgradNps = Vector{Adjoint{Float64,SArray{Tuple{MDIM},Float64,1,MDIM}}}[]; for j in 1:npts push!(geomscalNs, bfun(gcfe, pc[j,:])) push!(geomscalgradNps, bfungradpar(gcfe, pc[j,:])) end return (bfnum, scalNs, scalgradNps, scalgradN, Ns, gradNps, gradN, geomscalNs, geomscalgradNps) end """ QPIterator{FES, MDIM} Type of quadrature-point iterator, parameterized by - `FES`: the type of the finite element space, - `MDIM`: the manifold dimension of the finite element. """ mutable struct QPIterator{FES, MDIM} fesp::FES _quadr::IntegRule _bfnum::Vector{Int64} _scalbfuns::Vector{Vector{Float64}} _scalbfungrad_ps::Vector{Vector{Adjoint{Float64,SArray{Tuple{MDIM},Float64,1,MDIM}}}} _scalbfungrads::Vector{Adjoint{Float64,SArray{Tuple{MDIM},Float64,1,MDIM}}} _bfuns::Vector{Vector{Float64}} _bfungrad_ps::Vector{Vector{Adjoint{Float64,SArray{Tuple{MDIM},Float64,1,MDIM}}}} _bfungrads::Vector{Adjoint{Float64,SArray{Tuple{MDIM},Float64,1,MDIM}}} _geomscalbfuns::Vector{Vector{Float64}} _geomscalbfungrad_ps::Vector{Vector{Adjoint{Float64,SArray{Tuple{MDIM},Float64,1,MDIM}}}} _pt::Int64 end """ QPIterator(fesp::FES, quadraturesettings) where {FES} Construct quadrature-point iterator by associating it with a finite element space and supplying quadrature rule settings. """ function QPIterator(fesp::FES, quadraturesettings) where {FES} _quadr = quadrature(refshape(fesp.fe), quadraturesettings) bfnum, scalNs, scalgradNps, scalgradN, Ns, gradNps, gradN, geomscalNs, geomscalgradNps = __bfundata(fesp, _quadr) _pt = 0 return QPIterator{FES, manifdim(refshape(fesp.fe))}(fesp, _quadr, bfnum, scalNs, scalgradNps, scalgradN, Ns, gradNps, gradN, geomscalNs, geomscalgradNps, _pt) end """ Base.iterate(it::QPIterator, state = 1) Advance a quadrature point iterator. """ function Base.iterate(it::QPIterator, state = 1) if state > npts(it._quadr) return nothing else return (_update!(it, state), state+1) end end Base.length(it::QPIterator) = npts(it._quadr) function _update!(it::QPIterator, state) it._pt = state return it end """ bfun(it::QPIterator) Retrieve vector of basis function values for the current quadrature point. """ function bfun(it::QPIterator) return it._bfuns[it._pt] end """ bfungradpar(it::QPIterator) Retrieve vector of basis function gradients with respect to the parametric coordinates for the current quadrature point. """ function bfungradpar(it::QPIterator) return it._bfungrad_ps[it._pt] end """ bfungrad(it::QPIterator, Jac) Retrieve vector of basis function gradients with respect to spatial coordinates for the current quadrature point. The Jacobian matrix maps between vectors in the parametric space and the spatial vectors. """ function bfungrad(it::QPIterator, Jac) for j in 1:length(it._scalbfungrads) it._scalbfungrads[j] = it._scalbfungrad_ps[it._pt][j] / Jac end for k in 1:length(it._bfungrads) it._bfungrads[k] = it._scalbfungrads[it._bfnum[k]] end return it._bfungrads end """ weight(it::QPIterator) Retrieve weight of the current quadrature point. """ weight(it::QPIterator) = it._quadr.weights[it._pt] end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
13843
module RefShapes using LinearAlgebra """ AbstractRefShape{MANIFDIM} Abstract type of a reference shape. """ abstract type AbstractRefShape{MANIFDIM} end """ RefShapePoint <: AbstractRefShape{0} Type of a reference shape for a zero-dimensional manifold (point). """ struct RefShapePoint <: AbstractRefShape{0} end """ RefShapeInterval <: AbstractRefShape{1} Type of a reference shape for a 1-dimensional manifold (curve). """ struct RefShapeInterval <: AbstractRefShape{1} end """ RefShapeSquare <: AbstractRefShape{2} Type of a logically rectangular reference shape for a 2-dimensional manifold (surface). """ struct RefShapeSquare <: AbstractRefShape{2} end """ RefShapeCube <: AbstractRefShape{3} Type of a reference shape for a 3-dimensional manifold (solid) bounded by six quadrilaterals. """ struct RefShapeCube <: AbstractRefShape{3} end """ RefShapeTriangle <: AbstractRefShape{2} Type of a logically triangular reference shape for a 2-dimensional manifold (surface). """ struct RefShapeTriangle <: AbstractRefShape{2} end """ RefShapeTetrahedron <: AbstractRefShape{3} Type of a reference shape for a 3-dimensional manifold (solid) bounded by 4 triangles. """ struct RefShapeTetrahedron <: AbstractRefShape{3} end """ manifdim(rs) Get the manifold dimension of the reference shape. """ manifdim(::Type{T}) where {T<:AbstractRefShape{MANIFDIM}} where {MANIFDIM} = MANIFDIM """ manifdimv(::Type{T}) where {T<:AbstractRefShape{MANIFDIM}} where {MANIFDIM} Get the manifold dimension of the reference shape as `Val`. """ manifdimv(::Type{T}) where {T<:AbstractRefShape{MANIFDIM}} where {MANIFDIM} = Val(MANIFDIM) """ IntegRule Type for integration rule. """ struct IntegRule npts::Int64 param_coords::Array{Float64, 2} weights::Array{Float64, 1} end npts(qr) = qr.npts param_coords(qr) = qr.param_coords weights(qr) = qr.weights function _gauss1(order) function opengauss(N, a = -1.0, b = +1.0) F = eigen(SymTridiagonal(zeros(N), [n/sqrt(4n^2 - 1) for n = 1:N-1])) return [(F.values[i]+1)*(b-a)/2 + a for i = 1:N], [2*F.vectors[1, i]^2 for i = 1:N]*(b-a)/2 end if (order==1) param_coords = vec([ 0.0 ]); weights = vec([ 2.0 ]); elseif (order==2) param_coords = vec([ -0.577350269189626 0.577350269189626 ]); weights = vec([ 1.0 1.0 ]); elseif (order==3) param_coords = vec([ -0.774596669241483 0.0 0.774596669241483 ]); weights = vec([ 0.5555555555555556 0.8888888888888889 0.5555555555555556 ]); elseif (order==4) param_coords = vec([ -0.86113631159405 -0.33998104358486 0.33998104358486 0.86113631159405]); weights = vec([ 0.34785484513745 0.65214515486255 0.65214515486255 0.34785484513745]); elseif (order==5) param_coords = vec([ -0.906179845938664 -0.538469310105683 0.000000000000000 0.538469310105683 0.906179845938664]) weights = vec([0.236926885056189 0.478628670499367 0.568888888888889 0.478628670499367 0.236926885056189]) else param_coords, weights = opengauss(order) end return length(param_coords), param_coords, weights end function _triangle(npts=1) if npts == 1 # integrates exactly linear polynomials param_coords = [1.0/3. 1.0/3.]; weights = reshape([1.0]/2.0,1,1); elseif npts == 3 # integrates exactly quadratic polynomials param_coords = [ 2.0/3 1.0/6; 1.0/6 2.0/3; 1.0/6 1.0/6 ]; weights = [1.0/3 1.0/3 1.0/3]/2; elseif npts == 4 # integrates exactly quadratic polynomials param_coords = [0.333333333333333 0.333333333333333 0.200000000000000 0.200000000000000 0.600000000000000 0.200000000000000 0.200000000000000 0.600000000000000]; weights = [-0.281250000000000 0.260416666666667 0.260416666666667 0.260416666666667]; elseif npts == 6 # integrates exactly quartic polynomials param_coords = [ 0.816847572980459 0.091576213509771; 0.091576213509771 0.816847572980459; 0.091576213509771 0.091576213509771; 0.108103018168070 0.445948490915965; 0.445948490915965 0.108103018168070; 0.445948490915965 0.445948490915965]; weights = [0.109951743655322*[1, 1, 1] 0.223381589678011*[1, 1, 1] ]/2; elseif npts == 7 # integrates exactly ? polynomials param_coords = [0.101286507323456 0.101286507323456 0.797426958353087 0.101286507323456 0.101286507323456 0.797426958353087 0.470142064105115 0.470142064105115 0.059715871789770 0.470142064105115 0.470142064105115 0.059715871789770 0.333333333333333 0.333333333333333]; weights = [0.062969590272414 0.062969590272414 0.062969590272414 0.066197076394253 0.066197076394253 0.066197076394253 0.112500000000000]; elseif npts == 9 # integrates exactly ? polynomials param_coords = [ 0.437525248383384 0.437525248383384 0.124949503233232 0.437525248383384 0.437525248383384 0.124949503233232 0.165409927389841 0.037477420750088 0.037477420750088 0.165409927389841 0.797112651860071 0.165409927389841 0.165409927389841 0.797112651860071 0.037477420750088 0.797112651860071 0.797112651860071 0.037477420750088]; weights = [ 0.205950504760887 0.205950504760887 0.205950504760887 0.063691414286223 0.063691414286223 0.063691414286223 0.063691414286223 0.063691414286223 0.063691414286223] ./ 2; elseif npts == 12 # integrates exactly ? polynomials param_coords = [ 0.063089014491502 0.063089014491502 0.873821971016996 0.063089014491502 0.063089014491502 0.873821971016996 0.249286745170910 0.249286745170910 0.501426509658179 0.249286745170910 0.249286745170910 0.501426509658179 0.310352451033785 0.053145049844816 0.053145049844816 0.310352451033785 0.636502499121399 0.310352451033785 0.310352451033785 0.636502499121399 0.053145049844816 0.636502499121399 0.636502499121399 0.053145049844816]; weights = [0.050844906370207 0.050844906370207 0.050844906370207 0.116786275726379 0.116786275726379 0.116786275726379 0.082851075618374 0.082851075618374 0.082851075618374 0.082851075618374 0.082851075618374 0.082851075618374] ./ 2; elseif npts == 13 # integrates exactly ? polynomials param_coords = [0.333333333333333 0.333333333333333 0.479308067841923 0.260345966079038 0.260345966079038 0.479308067841923 0.260345966079038 0.260345966079038 0.869739794195568 0.065130102902216 0.065130102902216 0.869739794195568 0.065130102902216 0.065130102902216 0.638444188569809 0.312865496004875 0.638444188569809 0.048690315425316 0.312865496004875 0.638444188569809 0.312865496004875 0.048690315425316 0.048690315425316 0.638444188569809 0.048690315425316 0.312865496004875 ]; weights = [ -0.149570044467670 0.175615257433204 0.175615257433204 0.175615257433204 0.053347235608839 0.053347235608839 0.053347235608839 0.077113760890257 0.077113760890257 0.077113760890257 0.077113760890257 0.077113760890257 0.077113760890257 ]'/2; else #nothing doing: this input is wrong error( "Unknown number of integration points $(npts)" ) end return npts, param_coords, weights end function _tetrahedron(npts=1) if npts == 1 # integrates exactly linear polynomials param_coords = reshape([0.25,0.25,0.25],1,3); weights = reshape([1.0]/6.0,1,1); elseif npts == 4 # integrates exactly quadratic polynomials param_coords = [[0.13819660 0.13819660 0.13819660]; [0.58541020 0.13819660 0.13819660]; [0.13819660 0.58541020 0.13819660]; [0.13819660 0.13819660 0.58541020]];; weights = [ 0.041666666666666666667 0.041666666666666666667 0.041666666666666666667 0.041666666666666666667]; elseif npts == 5 # Zienkiewicz #3. a = 1.0 / 6.0; b = 0.25; c = 0.5; d = - 0.8; e = 0.45; param_coords = [[b b b]; [c a a]; [a c a]; [a a c]; [a a a]]; weights = [d e e e e]/6; else #nothing doing: this input is wrong error( "Unknown number of integration points $(npts)" ) end return npts, param_coords, weights end """ quadrature(::Type{RefShapeInterval}, quadraturesettings = (kind = :default,)) Create a quadrature rule for the reference shape of an interval. The default is Gauss integration rule, where the order is set with the keyword `order`. """ function quadrature(::Type{RefShapeInterval}, quadraturesettings = (kind = :default,)) kind = :default for apair in pairs(quadraturesettings) sy, val = apair if sy == :kind kind = val end end if (kind == :Gauss) || (kind == :default) # Extract arguments order = 1; for apair in pairs(quadraturesettings) sy, val = apair if sy == :order order = val end end npts, param_coords, weights = _gauss1(order) return IntegRule(npts, reshape(param_coords, size(param_coords, 1), 1), vec(weights)) else error("Integration rule $(kind) not available") end end """ quadrature(::Type{RefShapeTriangle}, quadraturesettings = (kind = :default,)) Create a quadrature rule for the reference shape of an triangle. The default is a triangle rule, distinguished by the number of points set with the keyword `npts`. """ function quadrature(::Type{RefShapeTriangle}, quadraturesettings = (kind = :default,)) kind = :default for apair in pairs(quadraturesettings) sy, val = apair if sy == :kind kind = val end end if kind == :default # Extract arguments npts = 1; for apair in pairs(quadraturesettings) sy, val = apair if sy == :npts npts = val end end npts, param_coords, weights = _triangle(npts) return IntegRule(npts, reshape(param_coords, size(param_coords, 1), 2), vec(weights)) else error("Integration rule $(kind) not available") end end """ quadrature(::Type{RefShapeSquare}, quadraturesettings = (kind = :default,)) Create a quadrature rule for the reference shape of a square. The default is Gauss integration rule, where the order is set with the keyword `order`. """ function quadrature(::Type{RefShapeSquare}, quadraturesettings = (kind = :default,)) kind = :default for apair in pairs(quadraturesettings) sy, val = apair if sy == :kind kind = val end end if (kind == :Gauss) || (kind == :default) # Extract arguments order = 1; for apair in pairs(quadraturesettings) sy, val = apair if sy == :order order = val end end np, pc, w = _gauss1(order) param_coords = zeros(eltype(w),np^2,2); weights = zeros(eltype(w),np^2); r=1 for i in 1:order for j in 1:order param_coords[r,:] = [pc[i] pc[j]]; weights[r] = w[i]*w[j]; r=r+1 end end npts = r - 1 # back off one to reach the total number of points return IntegRule(npts, param_coords, weights) else error("Integration rule $(kind) not available") end end """ quadrature(::Type{RefShapeTetrahedron}, quadraturesettings = (kind = :default,)) Create a quadrature rule for the reference shape of a tetrahedron. The default is a one-point tetrahedron rule; other rules may be chosen based on the number of points set with the keyword `npts`. """ function quadrature(::Type{RefShapeTetrahedron}, quadraturesettings = (kind = :default,)) kind = :default for apair in pairs(quadraturesettings) sy, val = apair if sy == :kind kind = val end end if kind == :default # Extract arguments npts = 1; for apair in pairs(quadraturesettings) sy, val = apair if sy == :npts npts = val end end npts, param_coords, weights = _tetrahedron(npts) return IntegRule(npts, reshape(param_coords, size(param_coords, 1), 3), vec(weights)) else error("Integration rule $(kind) not available") end end end # module
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
898
module Utilities # An assert might be disabled at various optimization levels. This macro will not be. macro _check(ex, msgs...) msg = isempty(msgs) ? ex : msgs[1] if isa(msg, AbstractString) msg = msg # pass-through elseif !isempty(msgs) && (isa(msg, Expr) || isa(msg, Symbol)) # message is an expression needing evaluating msg = :(Main.Base.string($(esc(msg)))) elseif isdefined(Main, :Base) && isdefined(Main.Base, :string) && applicable(Main.Base.string, msg) msg = Main.Base.string(msg) else # string() might not be defined during bootstrap msg = quote msg = $(Expr(:quote,msg)) isdefined(Main, :Base) ? Main.Base.string(msg) : (Core.println(msg); "Error during bootstrap. See stdout.") end end return :($(esc(ex)) ? $(nothing) : throw(AssertionError($msg))) end end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
685
using Test @time @testset "Assemblers" begin include("test_assemblers.jl") end @time @testset "Reference shapes" begin include("test_refshapes.jl") end @time @testset "Finite elements" begin include("test_felements.jl") end @time @testset "Fields" begin include("test_fefields.jl") end @time @testset "Spaces" begin include("test_fespaces.jl") end @time @testset "Quadrature iterators" begin include("test_qpiterators.jl") end @time @testset "FE iterators" begin include("test_feiterators.jl") end @time @testset "Heat" begin include("test_heat.jl") end @time @testset "Elasticity" begin include("test_elasticity.jl") end @time @testset "Stokes" begin include("test_stokes.jl") end
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
9816
module mmass0 using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using LinearAlgebra using Test function test() a = SysmatAssemblerSparse(0.0) start!(a, 7, 7) m = [0.24406 0.599773 0.833404 0.0420141 0.786024 0.00206713 0.995379 0.780298 0.845816 0.198459 0.355149 0.224996] gi = [1 7 5] gj = [5 2 1 4] for j in 1:size(m, 2), i in 1:size(m, 1) assemble!(a, gi[i], gj[j], m[i, j]) end m = [0.146618 0.53471 0.614342 0.737833 0.479719 0.41354 0.00760941 0.836455 0.254868 0.476189 0.460794 0.00919633 0.159064 0.261821 0.317078 0.77646 0.643538 0.429817 0.59788 0.958909] gi = [2 3 1 7 5] gj = [6 7 3 4] for j in 1:size(m, 2), i in 1:size(m, 1) assemble!(a, gi[i], gj[j], m[i, j]) end A = finish!(a) B = [ 0.833404 0.599773 0.460794 0.0512104 0.24406 0.254868 0.476189 0 0 0.614342 0.737833 0 0.146618 0.53471 0 0 0.00760941 0.836455 0 0.479719 0.41354 0 0 0 0 0 0 0 0.355149 0.198459 0.59788 1.1839 0.845816 0.643538 0.429817 0 0 0 0 0 0 0 0.995379 0.00206713 0.317078 1.55676 0.786024 0.159064 0.261821 ] @test norm(A - B) / norm(B) < 1.0e-5 true end end using .mmass0 mmass0.test() module mmass0a using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using LinearAlgebra using Test function test() a = SysmatAssemblerSparse(0.0) start!(a, 7, 7) m = [0.24406 0.599773 0.833404 0.0420141 0.786024 0.00206713 0.995379 0.780298 0.845816 0.198459 0.355149 0.224996] gi = [1 7 5] gj = [5 2 1 4] la = LocalMatrixAssembler(3, 4, 0.0) init!(la, gi, gj) for j in 1:size(m, 2), i in 1:size(m, 1) la[i, j] += m[i, j] end assemble!(a, la) m = [0.146618 0.53471 0.614342 0.737833 0.479719 0.41354 0.00760941 0.836455 0.254868 0.476189 0.460794 0.00919633 0.159064 0.261821 0.317078 0.77646 0.643538 0.429817 0.59788 0.958909] gi = [2 3 1 7 5] gj = [6 7 3 4] la = LocalMatrixAssembler(5, 4, 0.0) init!(la, gi, gj) for j in 1:size(m, 2), i in 1:size(m, 1) la[i, j] += m[i, j] end assemble!(a, la) A = finish!(a) B = [ 0.833404 0.599773 0.460794 0.0512104 0.24406 0.254868 0.476189 0 0 0.614342 0.737833 0 0.146618 0.53471 0 0 0.00760941 0.836455 0 0.479719 0.41354 0 0 0 0 0 0 0 0.355149 0.198459 0.59788 1.1839 0.845816 0.643538 0.429817 0 0 0 0 0 0 0 0.995379 0.00206713 0.317078 1.55676 0.786024 0.159064 0.261821 ] @test norm(A - B) / norm(B) < 1.0e-5 true end end using .mmass0a mmass0a.test() module mmass0t using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using LinearAlgebra using Test function test() a = SysmatAssemblerSparse(0.0) start!(a, 7, 7) m = transpose([0.24406 0.599773 0.833404 0.0420141 0.786024 0.00206713 0.995379 0.780298 0.845816 0.198459 0.355149 0.224996]) gj = [1 7 5] gi = [5 2 1 4] la = LocalMatrixAssembler(4, 3, 0.0) @test size(la) == (4, 3) init!(la, gi, gj) for j in 1:size(m, 2), i in 1:size(m, 1) la[i, j] += m[i, j] end assemble!(a, transpose(la)) m = transpose([0.146618 0.53471 0.614342 0.737833 0.479719 0.41354 0.00760941 0.836455 0.254868 0.476189 0.460794 0.00919633 0.159064 0.261821 0.317078 0.77646 0.643538 0.429817 0.59788 0.958909] ) gj = [2 3 1 7 5] gi = [6 7 3 4] la = LocalMatrixAssembler(4, 5, 0.0) init!(la, gi, gj) for j in 1:size(m, 2), i in 1:size(m, 1) la[i, j] += m[i, j] end assemble!(a, transpose(la)) A = finish!(a) B = [ 0.833404 0.599773 0.460794 0.0512104 0.24406 0.254868 0.476189 0 0 0.614342 0.737833 0 0.146618 0.53471 0 0 0.00760941 0.836455 0 0.479719 0.41354 0 0 0 0 0 0 0 0.355149 0.198459 0.59788 1.1839 0.845816 0.643538 0.429817 0 0 0 0 0 0 0 0.995379 0.00206713 0.317078 1.55676 0.786024 0.159064 0.261821 ] @test norm(A - B) / norm(B) < 1.0e-5 la = LocalVectorAssembler(4, 0.0) @test size(la) == (4, ) true end end using .mmass0t mmass0t.test() module mvass1 using Elfel.Assemblers: SysvecAssembler, start!, finish!, assemble! using LinearAlgebra using Test function test() N = 30 v = fill(0.0, N) a = SysvecAssembler() start!(a, N) vec, dofnums = rand(3), [1, 7, 2] for i in 1:length(vec) assemble!(a, dofnums[i], vec[i]) end for (i, p) in zip(dofnums, vec) v[i] += p end vec, dofnums = rand(7), [29, 15, 1, 7, 3, 6, 2] for i in 1:length(vec) assemble!(a, dofnums[i], vec[i]) end for (i, p) in zip(dofnums, vec) v[i] += p end w = finish!(a) @test norm(v-w) / norm(w) <= 1.0e-9 end end using .mvass1 mvass1.test() module mass1 using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim, RefShapeInterval using Elfel.FElements: FE, refshape using Elfel.FElements: bfun, bfungradpar using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Test function test() a = SysmatAssemblerSparse(0.0) start!(a, 7, 7) m = [0.24406 0.599773 0.833404 0.0420141 0.786024 0.00206713 0.995379 0.780298 0.845816 0.198459 0.355149 0.224996] gi = [1 7 5] gj = [5 2 1 4] for j in 1:size(m, 2), i in 1:size(m, 1) assemble!(a, gi[i], gj[j], m[i, j]) end m = [0.146618 0.53471 0.614342 0.737833 0.479719 0.41354 0.00760941 0.836455 0.254868 0.476189 0.460794 0.00919633 0.159064 0.261821 0.317078 0.77646 0.643538 0.429817 0.59788 0.958909] gi = [2 3 1 7 5] gj = [6 7 3 4] for j in 1:size(m, 2), i in 1:size(m, 1) assemble!(a, gi[i], gj[j], m[i, j]) end A = finish!(a) @test abs.(maximum([0.833404 0.0 0.460794 0.05121043 0.24406 0.254868 0.476189; 0.0 0.0 0.614342 0.737833 0.0 0.146618 0.53471; 0.0 0.0 0.00760941 0.836455 0.0 0.479719 0.41354; 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.355149 0.0 0.59788 1.183905 0.845816 0.643538 0.429817; 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.995379 0.0 0.0 0.780298 0.786024 0.0 0.0] - A)) < 1.0e-5 # a = SysmatAssemblerSparse(0.0) # startassembly!(a, 5, 5, 3, 7, 7) # m = [0.24406 0.599773 0.833404 0.0420141 # 0.786024 0.00206713 0.995379 0.780298 # 0.845816 0.198459 0.355149 0.224996] # assemble!(a, m, [1 7 5], [5 0 1 4]) # m = [0.146618 0.53471 0.614342 0.737833 # 0.479719 0.41354 0.00760941 0.836455 # 0.254868 0.476189 0.460794 0.00919633 # 0.159064 0.261821 0.317078 0.77646 # 0.643538 0.429817 0.59788 0.958909] # assemble!(a, m, [2 3 1 0 5], [6 7 3 4]) # A = makematrix!(a) # # @show Matrix(A) # @test abs.(maximum([0.833404 0.0 0.460794 0.05121043 0.24406 0.254868 0.476189; # 0.0 0.0 0.614342 0.737833 0.0 0.146618 0.53471; 0.0 0.0 0.00760941 0.836455 0.0 0.479719 0.41354; 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.355149 0.0 0.59788 1.183905 0.845816 0.643538 0.429817; 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.995379 0.0 0.0 0.780298 0.786024 0.0 0.0] - A)) < 1.0e-5 end end using .mass1 mass1.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
6972
module mt_elasticity_t3 using Test using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities using MeshSteward: T3block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! E = 1.0; nu = 1.0/3; D = SMatrix{3, 3}(E / (1 - nu^2) * [1 nu 0 nu 1 0 0 0 (1 - nu) / 2]) A = 1.0 # length of the side of the square N = 100;# number of subdivisions along the sides of the square domain function genmesh() conn = T3block(A, A, N, N) mesh = Mesh() attach!(mesh, conn) return mesh end function assembleK(fesp, D) function integrateK!(ass, geom, elit, qpit, D) B = (g, k) -> k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1])) c = edofcompnt(elit.fesp) nedof = ndofsperel(elit) ke = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(ke, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) for j in 1:nedof DBj = D * B(gradN[j], c[j]) for i in 1:nedof Bi = B(gradN[i], c[i]) ke[i, j] += dot(DBj, Bi) * JxW end end end assemble!(ass, ke) end return ass end elit = FEIterator(fesp) qpit = QPIterator(fesp, (kind = :default,)) geom = geometry(fesp.mesh) ass = SysmatAssemblerSparse(0.0) start!(ass, ndofs(fesp), ndofs(fesp)) integrateK!(ass, geom, elit, qpit, D) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function test() mesh = genmesh() fesp = FESpace(Float64, mesh, FEH1_T3(), 2) locs = geometry(mesh) inflate = A / N / 100 box = [0.0 0.0 0.0 A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(fesp, 0, i, 1, 0.0) setebc!(fesp, 0, i, 2, 0.0) end box = [A A 0.0 A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(fesp, 0, i, 1, A / 10) setebc!(fesp, 0, i, 2, 0.0) end numberfreedofs!(fesp) numberdatadofs!(fesp) # @show nunknowns(fesp) K = assembleK(fesp, D) U = fill(0.0, ndofs(fesp)) gathersysvec!(U, fesp) F = fill(0.0, ndofs(fesp)) solve!(U, K, F, nunknowns(fesp)) scattersysvec!(fesp, U) makeattribute(fesp, "U", 1:2) vtkwrite("elast_stretch_t3-U", baseincrel(mesh), [(name = "U", allxyz = true)]) try rm("elast_stretch_t3-U.vtu"); catch end end end using .mt_elasticity_t3 mt_elasticity_t3.test() module mt_elast_stretch_t6 using Test using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities using MeshSteward: T6block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! E = 1.0; nu = 1.0/3; D = SMatrix{3, 3}(E / (1 - nu^2) * [1 nu 0 nu 1 0 0 0 (1 - nu) / 2]) A = 1.0 # length of the side of the square N = 100;# number of subdivisions along the sides of the square domain function genmesh() conn = T6block(A, A, N, N) mesh = Mesh() attach!(mesh, conn) return mesh end function assembleK(fesp, D) function integrateK!(ass, geom, elit, qpit, D) B = (g, k) -> k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1])) c = edofcompnt(elit.fesp) nedof = ndofsperel(elit) ke = LocalMatrixAssembler(nedof, nedof, 0.0) for el in elit init!(ke, eldofs(el), eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) for j in 1:nedof DBj = D * B(gradN[j], c[j]) for i in 1:nedof Bi = B(gradN[i], c[i]) ke[i, j] += dot(DBj, Bi) * JxW end end end assemble!(ass, ke) end return ass end elit = FEIterator(fesp) qpit = QPIterator(fesp, (kind = :default, npts = 3,)) geom = geometry(fesp.mesh) ass = SysmatAssemblerSparse(0.0) start!(ass, ndofs(fesp), ndofs(fesp)) integrateK!(ass, geom, elit, qpit, D) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function test() mesh = genmesh() fesp = FESpace(Float64, mesh, FEH1_T6(), 2) locs = geometry(mesh) inflate = A / N / 100 box = [0.0 0.0 0.0 A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(fesp, 0, i, 1, 0.0) setebc!(fesp, 0, i, 2, 0.0) end box = [A A 0.0 A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(fesp, 0, i, 1, A / 10) setebc!(fesp, 0, i, 2, 0.0) end numberfreedofs!(fesp) numberdatadofs!(fesp) # @show nunknowns(fesp) K = assembleK(fesp, D) U = fill(0.0, ndofs(fesp)) gathersysvec!(U, fesp) F = fill(0.0, ndofs(fesp)) solve!(U, K, F, nunknowns(fesp)) scattersysvec!(fesp, U) makeattribute(fesp, "U", 1:2) vtkwrite("elast_stretch_t6-U", baseincrel(mesh), [(name = "U", allxyz = true)]) try rm("elast_stretch_t6-U.vtu"); catch end end end using .mt_elast_stretch_t6 mt_elast_stretch_t6.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
1922
module mfld1 using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim, RefShapeInterval using Elfel.FElements: FE, refshape using Elfel.FElements: bfun, bfungradpar, FEH1_T3 using MeshSteward: Mesh, load, increl, baseincrel using MeshCore: nshapes using Elfel.FESpaces.FEFields: FEField, nterms, ndofsperterm, doftype, setebc!, gathersysvec!, ndofs using Elfel.FESpaces.FEFields: numberfreedofs!, freedofnums, numberdatadofs!, datadofnums, highestfreedofnum, highestdatadofnum using Test function test() mesh = load(Mesh(), "mt3gen3.mesh") fe = FEH1_T3() fef = FEField(Val(2), Float64, Int64, nshapes(baseincrel(mesh).right)) @test nterms(fef) == nshapes(baseincrel(mesh).right) @test ndofsperterm(fef) == 2 # Case of no data degrees of freedom numberfreedofs!(fef) fnum, lnum, tnum = freedofnums(fef) numberdatadofs!(fef, lnum + 1) fnum, lnum, tnum = freedofnums(fef) @test tnum == nterms(fef) * ndofsperterm(fef) fnum, lnum, tnum = datadofnums(fef) @test tnum == 0 @test highestfreedofnum(fef) == 42 @test highestdatadofnum(fef) == 0 # Case of 2 degrees of freedom prescribed setebc!(fef, 3, 2, 3.0) setebc!(fef, 5, 1, 5.0) numberfreedofs!(fef, 1) fnum, lnum, tnum = freedofnums(fef) numberdatadofs!(fef, lnum + 1) fnum, lnum, tnum = freedofnums(fef) @test tnum == nterms(fef) * ndofsperterm(fef) - 2 @test fnum == 1 @test lnum == nterms(fef) * ndofsperterm(fef) - 2 fnum, lnum, tnum = datadofnums(fef) @test tnum == 2 @test fnum == nterms(fef) * ndofsperterm(fef) - 2 + 1 @test lnum == nterms(fef) * ndofsperterm(fef) @test highestfreedofnum(fef) == 40 @test highestdatadofnum(fef) == 42 @test doftype(fef) == Float64 v = fill(zero(doftype(fef)), ndofs(fef)) gathersysvec!(v, fef) @test v[nterms(fef) * ndofsperterm(fef) - 1] == 3.0 end end using .mfld1 mfld1.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
7770
module mfeit1 using StaticArrays using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim, RefShapeInterval using Elfel.FElements: FE, refshape, FEH1_T3 using Elfel.FElements: bfun, bfungradpar using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FEIterators: FEIterator using MeshCore using MeshSteward: Mesh, load, nspacedims, baseincrel using Test function test() fe = FEH1_T3() mesh = load(Mesh(), "qmesh.mesh") fesp = FESpace(Float64, mesh, fe) @test doftype(fesp) == Float64 refc = [[1, 2, 5], [1, 5, 4], [4, 5, 8], [4, 8, 7], [7, 8, 11], [7, 11, 10], [2, 3, 6], [2, 6, 5], [5, 6, 9], [5, 9, 8], [8, 9, 12], [8, 12, 11], ] it = FEIterator(fesp) k = 1 for c in it @test isapprox(c._nodes, refc[k]) k = k + 1 end @test length(it) == 12 # @show summary(mesh) numberfreedofs!(fesp) numberdatadofs!(fesp) @test ndofs(fesp) == 12 @test nunknowns(fesp) == 12 for i in [1, 4, 7, 10] setebc!(fesp, 0, i, 1, 0.0) end numberfreedofs!(fesp) numberdatadofs!(fesp) @test ndofs(fesp) == 12 @test nunknowns(fesp) == 8 # @show fesp._irsfields refd = [[9], [1], [2], [10], [3], [4], [11], [5], [6], [12], [7], [8]] it = FEIterator(fesp) for el in it # @show el._dofs # @show refd[el._nodes] @test isapprox(el._dofs, [refd[n][1] for n in el._nodes] ) end end end using .mfeit1 mfeit1.test() module mfeit2 using StaticArrays using LinearAlgebra using MeshCore using MeshSteward: Mesh, load, nspacedims, baseincrel using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim, RefShapeInterval using Elfel.FElements: FE, refshape, FEH1_T3 using Elfel.FElements: bfun, bfungradpar using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FEIterators: FEIterator, eldofs using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using Test A = [0.6744582963441466 0.2853043149927861 0.27460710155821255; 0.3781923479141225 0.2838873430062512 0.6316949656630075; 0.19369805365903336 0.8926164783344779 0.07006905962860177] function test() fe = FEH1_T3() mesh = load(Mesh(), "qmesh.mesh") fesp = FESpace(Float64, mesh, fe) for i in [1, 4, 7, 10] setebc!(fesp, 0, i, 1, 0.0) end numberfreedofs!(fesp) numberdatadofs!(fesp) ass = SysmatAssemblerSparse(0.0) start!(ass, 12, 12) ke = LocalMatrixAssembler(size(A, 1), size(A, 2), 0.0) it = FEIterator(fesp) for el in it init!(ke, eldofs(el), eldofs(el)) for j in 1:size(A, 2), i in 1:size(A, 1) ke[i, j] += A[i, j] end assemble!(ass, ke) end S = finish!(ass) D = fill(0.0, 12, 12) it = FEIterator(fesp) for el in it for j in 1:size(A, 2), i in 1:size(A, 1) D[el._dofs[i], el._dofs[j]] += A[i, j] end end @test isapprox(D - S, 0 * I) end end using .mfeit2 mfeit2.test() module mfeit3 using StaticArrays using LinearAlgebra using MeshCore using MeshSteward: Mesh, load, nspacedims, baseincrel using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim, RefShapeInterval using Elfel.FElements: FE, refshape, FEH1_T3 using Elfel.FElements: bfun, bfungradpar using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FEIterators: FEIterator, eldofs, eldofs, eldofentmdims, eldofcomps using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Test A = [0.6744582963441466 0.2853043149927861 0.27460710155821255; 0.3781923479141225 0.2838873430062512 0.6316949656630075; 0.19369805365903336 0.8926164783344779 0.07006905962860177] function test() fe = FEH1_T3() mesh = load(Mesh(), "qmesh.mesh") fesp = FESpace(Float64, mesh, fe, 3) for i in [1, 4, 7, 10] setebc!(fesp, 0, i, 1, 0.0) end numberfreedofs!(fesp) numberdatadofs!(fesp) it = FEIterator(fesp) @test em = eldofentmdims(it) == [0, 0, 0, 0, 0, 0, 0, 0, 0] @test eldofcomps(it) == [1, 2, 3, 1, 2, 3, 1, 2, 3] ref = [ [33, 1, 2, 3, 4, 5, 11, 12, 13], [33, 1, 2, 11, 12, 13, 34, 9, 10], [34, 9, 10, 11, 12, 13, 19, 20, 21], [34, 9, 10, 19, 20, 21, 35, 17, 18], [35, 17, 18, 19, 20, 21, 27, 28, 29], [35, 17, 18, 27, 28, 29, 36, 25, 26], [3, 4, 5, 6, 7, 8, 14, 15, 16], [3, 4, 5, 14, 15, 16, 11, 12, 13], [11, 12, 13, 14, 15, 16, 22, 23, 24], [11, 12, 13, 22, 23, 24, 19, 20, 21], [19, 20, 21, 22, 23, 24, 30, 31, 32], [19, 20, 21, 30, 31, 32, 27, 28, 29] ] i = 1 for el in it @test isapprox(eldofs(it), ref[i]) i = i + 1 end end end using .mfeit3 mfeit3.test() module maggfeit1 using StaticArrays using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim, RefShapeInterval using Elfel.FElements: FE, refshape, FEH1_T3 using Elfel.FElements: bfun, bfungradpar using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FEIterators: FEIterator, elnodes using Elfel.Utilities: @_check using MeshCore using MeshSteward: Mesh, load, nspacedims, baseincrel using Test function test() mesh = load(Mesh(), "qmesh.mesh") fesp1 = FESpace(Float64, mesh, FEH1_T3()) fesp2 = FESpace(Float64, mesh, FEH1_T3()) fesp3 = FESpace(Float64, mesh, FEH1_T3()) refc = [[1, 2, 5], [1, 5, 4], [4, 5, 8], [4, 8, 7], [7, 8, 11], [7, 11, 10], [2, 3, 6], [2, 6, 5], [5, 6, 9], [5, 9, 8], [8, 9, 12], [8, 12, 11], ] it1 = FEIterator(fesp1) it2 = FEIterator(fesp2) it3 = FEIterator(fesp3) it = zip(it1, it2, it3) @test length(it) == 12 k = 1 for i in it @test elnodes(i[1]) == elnodes(i[2]) == elnodes(i[3]) k = k + 1 end end end using .maggfeit1 maggfeit1.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
4725
module mfes1 using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim, RefShapeInterval using Elfel.FElements: FE, refshape, FEH1_L2, FEH1_T3, FEH1_Q4 using Elfel.FElements: bfun, bfungradpar, nfeatofdim, ndofperfeat using Test function test() fe = FEH1_T3() @test ndofperfeat(fe, 0) == 1 @test ndofperfeat(fe, 1) == 0 @test ndofperfeat(fe, 2) == 0 @test ndofperfeat(fe, 3) == 0 @test refshape(fe) == RefShapeTriangle @test manifdim(refshape(fe)) == 2 @test nfeatofdim(fe, 0) == 3 @test nfeatofdim(fe, 1) == 3 @test nfeatofdim(fe, 2) == 1 @test nfeatofdim(fe, 3) == 0 @test isapprox(bfun(fe, [1/3, 1/3]), [0.3333333333333334, 0.3333333333333333, 0.3333333333333333]) g = bfungradpar(fe, [1/3, 1/3]) @test isapprox(g[1], [-1.; -1.]') @test isapprox(g[2], [+1.; 0.]') @test isapprox(g[3], [0.; +1.]') e = FEH1_T3() @test ndofperfeat(fe, 0) == true @test ndofperfeat(fe, 1) == 0 @test ndofperfeat(fe, 2) == 0 @test ndofperfeat(fe, 3) == 0 @test refshape(fe) == RefShapeTriangle @test manifdim(refshape(fe)) == 2 @test isapprox(bfun(fe, [1/3, 1/3]), [0.3333333333333334, 0.3333333333333333, 0.3333333333333333]) g = bfungradpar(fe, [1/3, 1/3]) @test isapprox(g[1], [-1.; -1.]') @test isapprox(g[2], [+1.; 0.]') @test isapprox(g[3], [0.; +1.]') fe = FEH1_L2() @test ndofperfeat(fe, 0) == true @test ndofperfeat(fe, 1) == 0 @test ndofperfeat(fe, 2) == 0 @test ndofperfeat(fe, 3) == 0 @test refshape(fe) == RefShapeInterval @test manifdim(refshape(fe)) == 1 @test isapprox(bfun(fe, [1/3]), [0.3333333333333334, 2*0.3333333333333333]) g = bfungradpar(fe, [1/3]) @test isapprox(g[1], [-1.0/2]) @test isapprox(g[2], [+1.0/2]) end end using .mfes1 mfes1.test() module mfes2 using Elfel using Elfel.RefShapes: manifdim, RefShapeTetrahedron using Elfel.FElements: FE, refshape, FEH1_T4 using Elfel.FElements: bfun, bfungradpar, nfeatofdim, ndofperfeat using Test function test() fe = FEH1_T4() @test ndofperfeat(fe, 0) == 1 @test ndofperfeat(fe, 1) == 0 @test ndofperfeat(fe, 2) == 0 @test ndofperfeat(fe, 3) == 0 @test refshape(fe) == RefShapeTetrahedron @test manifdim(refshape(fe)) == 3 @test nfeatofdim(fe, 0) == 4 @test nfeatofdim(fe, 1) == 6 @test nfeatofdim(fe, 2) == 4 @test nfeatofdim(fe, 3) == 1 @test isapprox(bfun(fe, [1/4, 1/4, 1/4]), [1/4, 1/4, 1/4, 1/4]) g = bfungradpar(fe, [1/4, 1/4, 1/4]) @test isapprox(g[1], [-1. -1. -1.]) @test isapprox(g[2], [+1. 0. 0.]) @test isapprox(g[3], [0. +1. 0.]) @test isapprox(g[4], [0. 0. +1. ]) true end end using .mfes2 mfes2.test() module mfes3 using Elfel using Elfel.RefShapes: manifdim, RefShapeSquare using Elfel.FElements: FE, refshape, FEL2_Q4 using Elfel.FElements: bfun, bfungradpar, nfeatofdim, ndofperfeat using Test function test() fe = FEL2_Q4() @test ndofperfeat(fe, 0) == 0 @test ndofperfeat(fe, 1) == 0 @test ndofperfeat(fe, 2) == 1 @test ndofperfeat(fe, 3) == 0 @test refshape(fe) == RefShapeSquare @test manifdim(refshape(fe)) == 2 @test nfeatofdim(fe, 0) == 4 @test nfeatofdim(fe, 1) == 4 @test nfeatofdim(fe, 2) == 1 @test nfeatofdim(fe, 3) == 0 @test isapprox(bfun(fe, [1/4, 1/4]), [1.0]) g = bfungradpar(fe, [1/4, 1/4]) @test isapprox(g[1], [0. 0. ]) true end end using .mfes3 mfes3.test() module mfes4 using Elfel using Elfel.RefShapes: manifdim, RefShapeTetrahedron, RefShapeTriangle using Elfel.FElements: FE, refshape, FEL2_T4, FEL2_T3 using Elfel.FElements: bfun, bfungradpar, nfeatofdim, ndofperfeat using Test function test() fe = FEL2_T4() @test ndofperfeat(fe, 0) == 0 @test ndofperfeat(fe, 1) == 0 @test ndofperfeat(fe, 2) == 0 @test ndofperfeat(fe, 3) == 1 @test refshape(fe) == RefShapeTetrahedron @test manifdim(refshape(fe)) == 3 @test nfeatofdim(fe, 0) == 4 @test nfeatofdim(fe, 1) == 6 @test nfeatofdim(fe, 2) == 4 @test nfeatofdim(fe, 3) == 1 @test isapprox(bfun(fe, [1/4, 1/4, 1/4]), [1.0]) g = bfungradpar(fe, [1/4, 1/4, 1/4]) @test isapprox(g[1], [0.0 0.0 0.0]) fe = FEL2_T3() @test ndofperfeat(fe, 0) == 0 @test ndofperfeat(fe, 1) == 0 @test ndofperfeat(fe, 2) == 1 @test ndofperfeat(fe, 3) == 0 @test refshape(fe) == RefShapeTriangle @test manifdim(refshape(fe)) == 2 @test nfeatofdim(fe, 0) == 3 @test nfeatofdim(fe, 1) == 3 @test nfeatofdim(fe, 2) == 1 @test nfeatofdim(fe, 3) == 0 @test isapprox(bfun(fe, [1/4, 1/4]), [1.0]) g = bfungradpar(fe, [1/4, 1/4]) @test isapprox(g[1], [0.0 0.0]) true end end using .mfes4 mfes4.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
4919
module mfesp1 using StaticArrays using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim, RefShapeInterval using Elfel.FElements: FE, refshape, FEH1_T3 using Elfel.FElements: bfun, bfungradpar using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype, nunknowns using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FEIterators: FEIterator using MeshCore using MeshSteward: Mesh, load, nspacedims, baseincrel using Test function test() fe = FEH1_T3() mesh = load(Mesh(), "qmesh.mesh") fesp = FESpace(Float64, mesh, fe) @test doftype(fesp) == Float64 refc = [[1, 2, 5], [1, 5, 4], [4, 5, 8], [4, 8, 7], [7, 8, 11], [7, 11, 10], [2, 3, 6], [2, 6, 5], [5, 6, 9], [5, 9, 8], [8, 9, 12], [8, 12, 11], ] it = FEIterator(fesp) k = 1 for c in it @test isapprox(c._nodes, refc[k]) k = k + 1 end @test length(it) == 12 # @show summary(mesh) numberfreedofs!(fesp) @test ndofs(fesp) == 12 @test nunknowns(fesp) == 12 for i in [1, 4, 7, 10] setebc!(fesp, 0, i, 1, 0.0) end numberfreedofs!(fesp) @test ndofs(fesp) == 12 @test nunknowns(fesp) == 8 it = FEIterator(fesp) for el in it el._dofs end # sdim = nspacedims(femesh) # mdim = manifdim(femesh) # geom = geomattr(femesh) # el = 4 # gradNpar = bfungradpar(fespace.fe, [1/3, 1/3]) # conn = connectivity(femesh) # for c in conn # J = SMatrix{sdim, mdim}(zeros(sdim, mdim)) # for j in 1:length(c) # J += geom[c[j]] * gradNpar[j] # end # end # c = iterate(conn, 1)[1] # J = SMatrix{sdim, mdim}(zeros(sdim, mdim)) # for j in 1:length(c) # J += geom[c[j]] * gradNpar[j] # end # @test isapprox(J, [0.5 0.5; 0.0 0.3333333333333333]) end end using .mfesp1 mfesp1.test() module mfesp2 using StaticArrays using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim, RefShapeInterval using Elfel.FElements: FE, refshape, FEH1_T3, shapedesc using Elfel.FElements: FEH1_T3_BUBBLE using Elfel.FElements: bfun, bfungradpar using Elfel.FElements: nfeatofdim, ndofperfeat, ndofsperel using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype, nunknowns using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, dofnum using Elfel.FESpaces: edofmdim, edofbfnum, edofcompnt using Elfel.FEIterators: FEIterator using MeshCore: ir_identity using MeshSteward: Mesh, load, nspacedims, baseincrel, attach! using Test function test() fe = FEH1_T3() mesh = load(Mesh(), "qmesh.mesh") fesp = FESpace(Float64, mesh, fe, 3) @test doftype(fesp) == Float64 @test shapedesc(fesp.fe).name == "T3" @test refshape(fesp.fe) == Elfel.RefShapes.RefShapeTriangle @test nfeatofdim(fesp.fe, 0) == 3 @test ndofperfeat(fesp.fe, 0) == 1 @test ndofsperel(fesp.fe) == 3 @test isapprox(bfun(fesp.fe, [1/3, 1/3]), [0.3333333333333334, 0.3333333333333333, 0.3333333333333333]) attach!(mesh, ir_identity(baseincrel(mesh))) fesp = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 1) @test nfeatofdim(fesp.fe, 0) == 3 @test nfeatofdim(fesp.fe, 1) == 3 @test nfeatofdim(fesp.fe, 2) == 1 @test nfeatofdim(fesp.fe, 3) == 0 @test ndofperfeat(fesp.fe, 0) == 1 @test ndofperfeat(fesp.fe, 1) == 0 @test ndofperfeat(fesp.fe, 2) == 1 @test ndofperfeat(fesp.fe, 3) == 0 @test ndofsperel(fesp.fe) == 4 @test isapprox(bfun(fesp.fe, [1/3, 1/3]), [0.3333333333333334, 0.3333333333333333, 0.3333333333333333, 0.03703703703703704]) fesp = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 2) @test nfeatofdim(fesp.fe, 0) == 3 @test nfeatofdim(fesp.fe, 1) == 3 @test nfeatofdim(fesp.fe, 2) == 1 @test nfeatofdim(fesp.fe, 3) == 0 @test ndofperfeat(fesp.fe, 0) == 1 @test ndofperfeat(fesp.fe, 1) == 0 @test ndofperfeat(fesp.fe, 2) == 1 @test ndofperfeat(fesp.fe, 3) == 0 @test ndofsperel(fesp.fe) == 4 @test isapprox(bfun(fesp.fe, [1/3, 1/3]), [0.3333333333333334, 0.3333333333333333, 0.3333333333333333, 0.03703703703703704]) emdim = Int64[] bfnum = Int64[] compnt = Int64[] bfn = 1 for m in 0:1:3 if ndofperfeat(fesp.fe, m) > 0 for i in 1:nfeatofdim(fesp.fe, m) for k in 1:ndofperfeat(fesp.fe, m) for j in 1:fesp.nfecopies push!(emdim, m) push!(bfnum, bfn) push!(compnt, j) end bfn += 1 end end end end @test edofmdim(fesp) == emdim @test edofbfnum(fesp) == bfnum @test edofcompnt(fesp) == compnt @test dofnum(fesp, 0, 1, 1) == 0 true end end using .mfesp2 mfesp2.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
7447
module mt_heat_poisson_t3 using Test using LinearAlgebra using MeshCore: nrelations, nentities, @_check, attribute using MeshSteward: T3block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: connectedv, geometry using MeshSteward: vtkwrite using Elfel.RefShapes: RefShapeTriangle, manifdim, manifdimv using Elfel.FElements: FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec! using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungradpar, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! A = 1.0 # length of the side of the square kappa = 1.0; # conductivity matrix Q = -6.0; # internal heat generation rate tempf(x, y) =(1.0 + x^2 + 2.0 * y^2);#the exact distribution of temperature N = 4;# number of subdivisions along the sides of the square domain function genmesh() conn = T3block(A, A, N, N) mesh = Mesh() attach!(mesh, conn) return mesh end function assembleKF(fesp, kappa, Q) function integrate!(am, av, geom, elit, qpit, kappa, Q) nedof = ndofsperel(elit) iterate(qpit, 1) # Why do I need to do this? ke = LocalMatrixAssembler(nedof, nedof, 0.0) fe = LocalVectorAssembler(nedof, 0.0) for el in elit init!(ke, eldofs(el), eldofs(el)) init!(fe, eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof ke[i, j] += dot(gradN[i], gradN[j]) * (kappa * JxW) end fe[j] += N[j] * Q * JxW end end assemble!(am, ke) assemble!(av, fe) end return am, av end elit = FEIterator(fesp) qpit = QPIterator(fesp, (kind = :default,)) geom = geometry(fesp.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(fesp), ndofs(fesp)) av = start!(SysvecAssembler(0.0), ndofs(fesp)) integrate!(am, av, geom, elit, qpit, kappa, Q) return finish!(am), finish!(av) end function solve!(T, K, F, nu) KT = K * T T[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function checkcorrectness(fesp) geom = geometry(fesp.mesh) ir = baseincrel(fesp.mesh) T = attribute(ir.right, "T") std = 0.0 for i in 1:length(T) std += abs(T[i][1] - tempf(geom[i]...)) end @test (std / length(T)) <= 1.0e-9 end function test() mesh = genmesh() fesp = FESpace(Float64, mesh, FEH1_T3()) bir = boundary(mesh); vl = connectedv(bir); locs = geometry(mesh) for i in vl setebc!(fesp, 0, i, 1, tempf(locs[i]...)) end numberfreedofs!(fesp) numberdatadofs!(fesp) # @show nunknowns(fesp) K, F = assembleKF(fesp, kappa, Q) T = fill(0.0, ndofs(fesp)) gathersysvec!(T, fesp) solve!(T, K, F, nunknowns(fesp)) scattersysvec!(fesp, T) makeattribute(fesp, "T", 1) checkcorrectness(fesp) vtkwrite("heat_poisson_t3-T", baseincrel(mesh), [(name = "T",)]) try rm("heat_poisson_t3-T.vtu"); catch end @test isapprox(T, [1.1875, 1.3749999999999998, 1.6874999999999998, 1.5624999999999998, 1.7499999999999998, 2.0625, 2.1875, 2.375, 2.6875, 1.0, 1.0625, 1.25, 1.5625, 2.0, 1.125, 2.125, 1.5, 2.5, 2.125, 3.125, 3.0, 3.0625, 3.25, 3.5625, 4.0]) end end using .mt_heat_poisson_t3 mt_heat_poisson_t3.test() module m_heat_poisson_q4 using Test using LinearAlgebra using MeshCore: nrelations, nentities, attribute, @_check using MeshSteward: Q4block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: connectedv, geometry using MeshSteward: vtkwrite using Elfel.RefShapes: RefShapeTriangle, manifdim, manifdimv using Elfel.FElements: FEH1_Q4, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec! using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungradpar, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! A = 1.0 # length of the side of the square kappa = 1.0; # conductivity matrix Q = -6.0; # internal heat generation rate tempf(x, y) =(1.0 + x^2 + 2.0 * y^2);#the exact distribution of temperature N = 100;# number of subdivisions along the sides of the square domain function genmesh() conn = Q4block(A, A, N, N) mesh = Mesh() attach!(mesh, conn) return mesh end function assembleKF(fesp, kappa, Q) function integrate!(am, av, geom, elit, qpit, kappa, Q) nedof = ndofsperel(elit) ke = LocalMatrixAssembler(nedof, nedof, 0.0) fe = LocalVectorAssembler(nedof, 0.0) for el in elit init!(ke, eldofs(el), eldofs(el)) init!(fe, eldofs(el)) for qp in qpit Jac, J = jacjac(el, qp) gradN = bfungrad(qp, Jac) JxW = J * weight(qp) N = bfun(qp) for j in 1:nedof for i in 1:nedof ke[i, j] += dot(gradN[i], gradN[j]) * (kappa * JxW) end fe[j] += N[j] * Q * JxW end end assemble!(am, ke) assemble!(av, fe) end return am, av end elit = FEIterator(fesp) qpit = QPIterator(fesp, (kind = :Gauss, order = 2)) geom = geometry(fesp.mesh) am = start!(SysmatAssemblerSparse(0.0), ndofs(fesp), ndofs(fesp)) av = start!(SysvecAssembler(0.0), ndofs(fesp)) integrate!(am, av, geom, elit, qpit, kappa, Q) return finish!(am), finish!(av) end function solve!(T, K, F, nu) KT = K * T T[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function checkcorrectness(fesp) geom = geometry(fesp.mesh) ir = baseincrel(fesp.mesh) T = attribute(ir.right, "T") std = 0.0 for i in 1:length(T) std += abs(T[i][1] - tempf(geom[i]...)) end @test (std / length(T)) <= 1.0e-9 end function test() mesh = genmesh() fesp = FESpace(Float64, mesh, FEH1_Q4()) bir = boundary(mesh); vl = connectedv(bir); locs = geometry(mesh) for i in vl setebc!(fesp, 0, i, 1, tempf(locs[i]...)) end numberfreedofs!(fesp) numberdatadofs!(fesp) @test nunknowns(fesp) == 9801 K, F = assembleKF(fesp, kappa, Q) T = fill(0.0, ndofs(fesp)) gathersysvec!(T, fesp) solve!(T, K, F, nunknowns(fesp)) scattersysvec!(fesp, T) makeattribute(fesp, "T", 1) checkcorrectness(fesp) vtkwrite("m_heat_poisson_q4-T", baseincrel(mesh), [(name = "T",)]) try rm("m_heat_poisson_q4-T.vtu"); catch end end end using .m_heat_poisson_q4 m_heat_poisson_q4.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
2340
module mqpit1 using Elfel using Elfel.RefShapes: npts, param_coords, weights using Elfel.FElements: FE, FEData, refshape using Elfel.FElements: bfun, bfungradpar, FEH1_T3 using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns using MeshSteward: Mesh, load, baseincrel using Elfel.QPIterators: QPIterator, bfun, bfungradpar, weight using Test # using BenchmarkTools function test() fe = FEH1_T3() mesh = load(Mesh(), "qmesh.mesh") fesp = FESpace(Float64, mesh, fe) qpit = QPIterator(fesp, (kind = :default,)) @test length(qpit) == 1 # @test isapprox(param_coords(quadrule(idom)), [0.3333333333333333 0.3333333333333333]) # @test isapprox(weights(quadrule(idom)), [0.5]) refNs = [[0.3333333333333334, 0.3333333333333333, 0.3333333333333333]] k = 1 for qp in qpit Ns = bfun(qp) @test isapprox(Ns, refNs[k]) k = k + 1 end qpit = QPIterator(fesp, (kind = :default, npts = 3)) @test length(qpit) == 3 # @test isapprox(param_coords(quadrule(idom)), [0.3333333333333333 0.3333333333333333]) # @test isapprox(weights(quadrule(idom)), [0.5]) refNs = [[0.1666666666666667, 0.6666666666666666, 0.16666666666666666], [0.16666666666666674, 0.16666666666666666, 0.6666666666666666], [0.6666666666666667, 0.16666666666666666, 0.16666666666666666]] k = 1 for qp in qpit Ns = bfun(qp) @test isapprox(Ns, refNs[k]) k = k + 1 end k = 1 for qp in qpit Ns = bfun(qp) @test isapprox(Ns, refNs[k]) k = k + 1 end refgNs = [[-1.0 -1.0], [1.0 0.0], [0.0 1.0]] for qp in qpit gradNs = bfungradpar(qp) for i in 1:length(gradNs) @test isapprox(gradNs[i], refgNs[i]) end end for qp in qpit w = weight(qp) @test w == 0.16666666666666666 end # Ns, gradNparams = bfundata(idom) # @test length(Ns[1]) == 3 # geom = geomattr(femesh) # conn = connectivity(femesh) # it = FEIterator(fesp) # @show c = iterate(it) # Ns, gradNparams = bfundata(idom) # J = jac(geom, c, gradNparams[1]) # # @btime J = jac($geom, retrieve($ir, 1), $gradNparams[1]) # @test isapprox(J, [0.5 0.5; 0.0 0.3333333333333333]) end end using .mqpit1 mqpit1.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
4785
module mrs1 using Elfel.RefShapes: RefShapeInterval, manifdim using Elfel.RefShapes: quadrature, npts, param_coords, weights using Test function test() @test manifdim(RefShapeInterval) == 1 qr = quadrature(RefShapeInterval) @test npts(qr) == 1 qr = quadrature(RefShapeInterval, (order = 3,)) @test npts(qr) == 3 @test isapprox(param_coords(qr), [-0.774596669241483; 0.0; 0.774596669241483]) @test isapprox(weights(qr), [0.5555555555555556; 0.888888888888889; 0.5555555555555556]) end end using .mrs1 mrs1.test() module mrs2 using Elfel.RefShapes: RefShapeTriangle, manifdim using Elfel.RefShapes: quadrature, npts, param_coords, weights using Test function test() @test manifdim(RefShapeTriangle) == 2 qr = quadrature(RefShapeTriangle) @test npts(qr) == 1 qr = quadrature(RefShapeTriangle, (npts = 3,)) @test npts(qr) == 3 @test isapprox(param_coords(qr), [0.6666666666666666 0.16666666666666666; 0.16666666666666666 0.6666666666666666; 0.16666666666666666 0.16666666666666666]) @test isapprox(weights(qr), [0.16666666666666666; 0.16666666666666666; 0.16666666666666666]) end end using .mrs2 mrs2.test() module mrs3 using Elfel using Elfel.RefShapes: RefShapeSquare, manifdim using Elfel.RefShapes: quadrature, npts, param_coords, weights using Test function test() @test manifdim(RefShapeSquare) == 2 qr = quadrature(RefShapeSquare) # @show qr @test npts(qr) == 1 qr = quadrature(RefShapeSquare, (order = 2,)) @test npts(qr) == 4 # @show param_coords(qr)[3, :] @test isapprox(vec(param_coords(qr)[3, :]), [0.577350269189626, -0.577350269189626]) # @test isapprox(weights(qr), [0.16666666666666666; 0.16666666666666666; 0.16666666666666666]) end end using .mrs3 mrs3.test() module mrs4 using Elfel using Elfel.RefShapes: RefShapeSquare, manifdim using Elfel.RefShapes: quadrature, npts, param_coords, weights using Test function test() @test manifdim(RefShapeSquare) == 2 qr = quadrature(RefShapeSquare) # @show qr for o in 1:10 qr = quadrature(RefShapeSquare, (order = o,)) @test npts(qr) == o^2 end true end end using .mrs4 mrs4.test() module mrs5 using Elfel using Elfel.RefShapes: RefShapeTriangle, manifdim using Elfel.RefShapes: quadrature, npts, param_coords, weights using Test function test() @test manifdim(RefShapeTriangle) == 2 for n in [1, 3, 4, 6, 7, 9, 12, 13] qr = quadrature(RefShapeTriangle, (npts = n,)) @test npts(qr) == n end true end end using .mrs5 mrs5.test() module mrs6 using Elfel.RefShapes: RefShapeTetrahedron, manifdim using Elfel.RefShapes: quadrature, npts, param_coords, weights using Test function test() @test manifdim(RefShapeTetrahedron) == 3 qr = quadrature(RefShapeTetrahedron) @test npts(qr) == 1 @test isapprox(param_coords(qr), [0.25 0.25 0.25]) @test isapprox(weights(qr), [0.16666666666666666]) qr = quadrature(RefShapeTetrahedron, (npts = 4,)) @test npts(qr) == 4 @test isapprox(param_coords(qr), [0.1381966 0.1381966 0.1381966; 0.5854102 0.1381966 0.1381966; 0.1381966 0.5854102 0.1381966; 0.1381966 0.1381966 0.5854102] ) @test isapprox(weights(qr), [0.041666666666666664, 0.041666666666666664, 0.041666666666666664, 0.041666666666666664]) qr = quadrature(RefShapeTetrahedron, (npts = 5,)) @test npts(qr) == 5 @test isapprox(param_coords(qr), [0.25 0.25 0.25; 0.5 0.16666666666666666 0.16666666666666666; 0.16666666666666666 0.5 0.16666666666666666; 0.16666666666666666 0.16666666666666666 0.5; 0.16666666666666666 0.16666666666666666 0.16666666666666666]) @test isapprox(weights(qr), [-0.13333333333333333, 0.075, 0.075, 0.075, 0.075] ) end end using .mrs6 mrs6.test() module mrs7 using Elfel.RefShapes: RefShapeInterval, manifdim using Elfel.RefShapes: quadrature, npts, param_coords, weights using Test function test() @test manifdim(RefShapeInterval) == 1 result_true = exp(1.0) - exp(-1.0) reference_results = [2.0 , 2.3426960879097307 , 2.350336928680011 , 2.3504020921563744 , 2.350402386462827 , 2.350402387286035 , 2.350402387287601 , 2.3504023872876028 , 2.3504023872876036 , 2.350402387287604 ] results = Float64[] for N in 1:10 qr = quadrature(RefShapeInterval, (order = N,)) push!(results, sum(exp.(param_coords(qr)) .* weights(qr))) end @test isapprox(results, reference_results) end end using .mrs7 mrs7.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
code
34779
module m_stokes_driven_tht6_veclap using Test using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities using MeshSteward: T6block, T6toT3 using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! # using UnicodePlots mu = 0.25 # dynamic viscosity A = 1.0 # length of the side of the square N = 100;# number of subdivisions along the sides of the square domain function genmesh() # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(A, A, N, N), "velocity") # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(uxfesp, uyfesp, pfesp, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(uxfesp), FEIterator(uyfesp), FEIterator(pfesp)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(uxfesp, qargs), QPIterator(uyfesp, qargs), QPIterator(pfesp, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function test() vmesh, pmesh = genmesh() # Velocity spaces uxfesp = FESpace(Float64, vmesh, FEH1_T6(), 1) uyfesp = FESpace(Float64, vmesh, FEH1_T6(), 1) locs = geometry(vmesh) inflate = A / N / 100 # Part of the boundary that is immovable boxes = [[0.0 A 0.0 0.0], [0.0 0.0 0.0 A], [A A 0.0 A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(uxfesp, 0, i, 1, 0.0) setebc!(uyfesp, 0, i, 1, 0.0) end end # The lid: driven in the X direction uxbar = 1.0 box = [0.0 A A A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(uxfesp, 0, i, 1, uxbar) setebc!(uyfesp, 0, i, 1, 0.0) end # Pressure space pfesp = FESpace(Float64, pmesh, FEH1_T3(), 1) setebc!(pfesp, 0, 1, 1, 0.0) # Number the degrees of freedom numberdofs!([uxfesp, uyfesp, pfesp]) tndof = ndofs(uxfesp) + ndofs(uyfesp) + ndofs(pfesp) tnunk = nunknowns(uxfesp) + nunknowns(uyfesp) + nunknowns(pfesp) @test (tndof, tnunk) == (91003, 89402) # Assemble the coefficient matrix K = assembleK(uxfesp, uyfesp, pfesp, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [uxfesp, uyfesp, pfesp]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([uxfesp, uyfesp, pfesp], U) # Postprocessing makeattribute(pfesp, "p", 1) makeattribute(uxfesp, "ux", 1) makeattribute(uyfesp, "uy", 1) vtkwrite("m_stokes_driven_tht6_veclap-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("m_stokes_driven_tht6_veclap-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) try rm("m_stokes_driven_tht6_veclap-p.vtu"); catch end try rm("m_stokes_driven_tht6_veclap-v.vtu"); catch end true end end using .m_stokes_driven_tht6_veclap m_stokes_driven_tht6_veclap.test() module m_stokes_driven_t3b using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities, ir_identity using MeshSteward: T3block using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T3_BUBBLE, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs using Elfel.FEIterators: jacjac using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! # using UnicodePlots mu = 0.25 # dynamic viscosity A = 1.0 # length of the side of the square N = 100;# number of subdivisions along the sides of the square domain function genmesh() # This mesh will be both for the velocities and for the pressure mesh = Mesh() attach!(mesh, T3block(A, A, N, N), "velocity+pressure") ir = baseincrel(mesh) eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(uxfesp, uyfesp, pfesp, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(uxfesp), FEIterator(uyfesp), FEIterator(pfesp)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(uxfesp, qargs), QPIterator(uyfesp, qargs), QPIterator(pfesp, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function test() mesh = genmesh() # Velocity spaces uxfesp = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 1) uyfesp = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 1) locs = geometry(mesh) inflate = A / N / 100 # Part of the boundary that is immovable boxes = [[0.0 A 0.0 0.0], [0.0 0.0 0.0 A], [A A 0.0 A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(uxfesp, 0, i, 1, 0.0) setebc!(uyfesp, 0, i, 1, 0.0) end end # The lid uxbar = 1.0 box = [0.0 A A A] vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(uxfesp, 0, i, 1, uxbar) setebc!(uyfesp, 0, i, 1, 0.0) end # Pressure space pfesp = FESpace(Float64, mesh, FEH1_T3(), 1) setebc!(pfesp, 0, 1, 1, 0.0) # Number the degrees of freedom numberdofs!([uxfesp, uyfesp, pfesp]) tndof = ndofs(uxfesp) + ndofs(uyfesp) + ndofs(pfesp) tnunk = nunknowns(uxfesp) + nunknowns(uyfesp) + nunknowns(pfesp) # Assemble the coefficient matrix K = assembleK(uxfesp, uyfesp, pfesp, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [uxfesp, uyfesp, pfesp]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([uxfesp, uyfesp, pfesp], U) # Postprocessing makeattribute(pfesp, "p", 1) makeattribute(uxfesp, "ux", 1) makeattribute(uyfesp, "uy", 1) vtkwrite("m_stokes_driven_t3b-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("m_stokes_driven_t3b-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) try rm("m_stokes_driven_t3b-p.vtu"); catch end try rm("m_stokes_driven_t3b-v.vtu"); catch end true end end using .m_stokes_driven_t3b m_stokes_driven_t3b.test() module mstok1 using Test """ th_p2_p1 The manufactured-solution colliding flow example from Elman et al 2014. The Hood-Taylor formulation with quadratic triangles for the velocity and continuous pressure on linear triangles. The formulation is the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. """ module th_p2_p1 using Test using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities, ir_identity, attribute, VecAttrib using MeshSteward: T6block, T6toT3 using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary, transform using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs, eldofvals using Elfel.FEIterators: jacjac, location using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 1.0 # dynamic viscosity A = 1.0 # half of the length of the side of the square trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 function genmesh(N) # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(2 * A, 2 * A, N, N), "velocity") ir = baseincrel(vmesh) transform(ir, x -> x .- A) # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(uxfesp, uyfesp, pfesp, tndof, mu) function integrateK!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNp = bfungrad(pqp, Jac) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end elits = (FEIterator(uxfesp), FEIterator(uyfesp), FEIterator(pfesp)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(uxfesp, qargs), QPIterator(uyfesp, qargs), QPIterator(pfesp, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) integrateK!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function evaluate_pressure_error(pfesp) function integrate!(elit, qpit, truep) pnedof = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:pnedof pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(pfesp) qargs = (kind = :default, npts = 3,) qpit = QPIterator(pfesp, qargs) return integrate!(elit, qpit, truep) end function evaluate_velocity_error(uxfesp, uyfesp) function integrate!(elits, qpits, trueux, trueuy) uxnedof, uynedof = ndofsperel.(elits) E = 0.0 for el in zip(elits...) uxel, uyel = el uxdofvals = eldofvals(uxel) uydofvals = eldofvals(uyel) for qp in zip(qpits...) uxqp, uyqp = qp Jac, J = jacjac(uxel, uxqp) JxW = J * weight(uxqp) Np = bfun(uxqp) uxt = trueux(location(uxel, uxqp)...) uyt = trueuy(location(uyel, uyqp)...) uxa = 0.0 uya = 0.0 for j in 1:uxnedof uxa += (uxdofvals[j] * Np[j]) uya += (uydofvals[j] * Np[j]) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elits = (FEIterator(uxfesp), FEIterator(uyfesp),) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(uxfesp, qargs), QPIterator(uyfesp, qargs),) return integrate!(elits, qpits, trueux, trueuy) end function run(N) vmesh, pmesh = genmesh(N) # Velocity spaces uxfesp = FESpace(Float64, vmesh, FEH1_T6(), 1) uyfesp = FESpace(Float64, vmesh, FEH1_T6(), 1) locs = geometry(vmesh) inflate = A / N / 100 # The entire boundary boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(uxfesp, 0, i, 1, trueux(locs[i]...)) setebc!(uyfesp, 0, i, 1, trueuy(locs[i]...)) end end # Pressure space pfesp = FESpace(Float64, pmesh, FEH1_T3(), 1) atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(pfesp, 0, atcenter[1], 1, 0.0) # Number the degrees of freedom numberdofs!([uxfesp, uyfesp, pfesp]) tndof = ndofs(uxfesp) + ndofs(uyfesp) + ndofs(pfesp) tnunk = nunknowns(uxfesp) + nunknowns(uyfesp) + nunknowns(pfesp) # Assemble the coefficient matrix K = assembleK(uxfesp, uyfesp, pfesp, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [uxfesp, uyfesp, pfesp]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([uxfesp, uyfesp, pfesp], U) # Postprocessing makeattribute(pfesp, "p", 1) makeattribute(uxfesp, "ux", 1) makeattribute(uyfesp, "uy", 1) ep = evaluate_pressure_error(pfesp) ev = evaluate_velocity_error(uxfesp, uyfesp) # vtkwrite("th_p2_p1-p", baseincrel(pmesh), [(name = "p",), ]) # vtkwrite("th_p2_p1-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) # geom = geometry(pfesp.mesh) # ir = baseincrel(pfesp.mesh) # pt = VecAttrib([truep(geom[i]...) for i in 1:length(geom)]) # ir.right.attributes["pt"] = pt # vtkwrite("th_p2_p1-pt", baseincrel(pmesh), [(name = "pt",), ]) (ep, ev) end end function test() ref = [(3.5171450671095306, 0.2968271617227661), (0.5999467323539439, 0.03781189670123018), (0.12350320261417459, 0.004741849976722882)] N = 4 for loop in 1:3 ep, ev = th_p2_p1.run(N) @test isapprox(vec([ep, ev]), vec([ref[loop]...])) N = N * 2 end end end using .mstok1 mstok1.test() """ m_th_p2_p1_veclap_alt The manufactured-solution colliding flow example from Elman et al 2014. The Hood-Taylor formulation with quadratic triangles for the velocity and continuous pressure on linear triangles. This implementation is an alternative: for the velocity, a single finite element space with multiple components (2) is used instead of multiple finite element spaces. The formulation is the one derived in Donea, Huerta, Introduction to the finite element method, 1993. Page 486 ff, and Elman, et al., Finite elements and fast iterative solvers, p. 132. In other words, it is the vector Laplacian version. """ module m_th_p2_p1_veclap_alt using Test using LinearAlgebra using StaticArrays using MeshCore: nrelations, nentities, ir_identity, attribute, VecAttrib using MeshSteward: T6block, T6toT3 using MeshSteward: Mesh, attach!, baseincrel, boundary using MeshSteward: vselect, geometry, summary, transform using MeshSteward: vtkwrite using Elfel.RefShapes: manifdim, manifdimv using Elfel.FElements: FEH1_T6, FEH1_T3, refshape, Jacobian using Elfel.FESpaces: FESpace, ndofs, setebc!, nunknowns, doftype using Elfel.FESpaces: numberfreedofs!, numberdatadofs!, numberdofs! using Elfel.FESpaces: scattersysvec!, makeattribute, gathersysvec!, edofcompnt using Elfel.FESpaces: highestfreedofnum, highestdatadofnum using Elfel.FEIterators: FEIterator, ndofsperel, elnodes, eldofs, eldofvals using Elfel.FEIterators: jacjac, location using Elfel.QPIterators: QPIterator, bfun, bfungrad, weight using Elfel.Assemblers: SysmatAssemblerSparse, start!, finish!, assemble! using Elfel.Assemblers: SysvecAssembler using Elfel.LocalAssemblers: LocalMatrixAssembler, LocalVectorAssembler, init! using UnicodePlots mu = 1.0 # dynamic viscosity A = 1.0 # half of the length of the side of the square trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 function genmesh(N) # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(2 * A, 2 * A, N, N), "velocity") ir = baseincrel(vmesh) transform(ir, x -> x .- A) # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(ufesp, pfesp, tndof, mu) function integrate!(ass, elits, qpits, mu) unedof, pnedof = ndofsperel.(elits) uedofcomp = edofcompnt(ufesp) kuu = LocalMatrixAssembler(unedof, unedof, 0.0) kup = LocalMatrixAssembler(unedof, pnedof, 0.0) for el in zip(elits...) uel, pel = el init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) Np = bfun(pqp) for j in 1:unedof, i in 1:unedof if uedofcomp[i] == uedofcomp[j] kuu[i, j] += (mu * JxW) * (dot(gradNu[i], gradNu[j])) end end for j in 1:pnedof, i in 1:unedof kup[i, j] += (-JxW * Np[j]) * gradNu[i][uedofcomp[i]] end end assemble!(ass, kuu) assemble!(ass, kup) assemble!(ass, transpose(kup)) end return ass end elits = (FEIterator(ufesp), FEIterator(pfesp)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(ufesp, qargs), QPIterator(pfesp, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) integrate!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function evaluate_pressure_error(pfesp) function integrate!(elit, qpit, truep) pnedof = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:pnedof pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(pfesp) qargs = (kind = :default, npts = 3,) qpit = QPIterator(pfesp, qargs) return integrate!(elit, qpit, truep) end function evaluate_velocity_error(ufesp) function integrate!(elit, qpit, trueux, trueuy) unedof = ndofsperel(elit) uedofcomp = edofcompnt(ufesp) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:unedof (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(ufesp) qargs = (kind = :default, npts = 3,) qpit = QPIterator(ufesp, qargs) return integrate!(elit, qpit, trueux, trueuy) end function run(N) vmesh, pmesh = genmesh(N) # Velocity spaces ufesp = FESpace(Float64, vmesh, FEH1_T6(), 2) locs = geometry(vmesh) inflate = A / N / 100 # The entire boundary boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(ufesp, 0, i, 1, trueux(locs[i]...)) setebc!(ufesp, 0, i, 2, trueuy(locs[i]...)) end end # Pressure space pfesp = FESpace(Float64, pmesh, FEH1_T3(), 1) atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(pfesp, 0, atcenter[1], 1, 0.0) # Number the degrees of freedom numberdofs!([ufesp, pfesp]) tndof = ndofs(ufesp) + ndofs(pfesp) tnunk = nunknowns(ufesp) + nunknowns(pfesp) # Assemble the coefficient matrix K = assembleK(ufesp, pfesp, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [ufesp, pfesp]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([ufesp, pfesp], U) # Postprocessing makeattribute(pfesp, "p", 1) makeattribute(ufesp, "ux", 1) makeattribute(ufesp, "uy", 2) ep = evaluate_pressure_error(pfesp) ev = evaluate_velocity_error(ufesp) # vtkwrite("m_th_p2_p1_veclap_alt-p", baseincrel(pmesh), [(name = "p",), ]) # vtkwrite("m_th_p2_p1_veclap_alt-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) return (ep, ev) end test() = begin ep, ev = m_th_p2_p1_veclap_alt.run(4) @test isapprox([ep, ev], [2.596076907594511, 0.3001331486426876]) end end using .m_th_p2_p1_veclap_alt m_th_p2_p1_veclap_alt.test() module m_th_p2_p1_veclap_alt_e using Test using LinearAlgebra using StaticArrays using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using UnicodePlots mu = 1.0 # dynamic viscosity A = 1.0 # half of the length of the side of the square trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 function genmesh(N) # Hood-Taylor pair of meshes is needed # This mesh will be for the velocities vmesh = Mesh() attach!(vmesh, T6block(2 * A, 2 * A, N, N), "velocity") ir = baseincrel(vmesh) transform(ir, x -> x .- A) # This mesh will be used for the pressures. Notice that it needs to be # "compatible" with the velocity mesh in the sense that they need to share # the nodes at the corners of the triangles. pmesh = Mesh() attach!(pmesh, T6toT3(baseincrel(vmesh, "velocity")), "pressure") return vmesh, pmesh end function assembleK(ufesp, pfesp, tndof, mu) function integrate!(ass, elits, qpits, mu) unedof, pnedof = ndofsperel.(elits) uedofcomp = edofcompnt(ufesp) kuu = LocalMatrixAssembler(unedof, unedof, 0.0) kup = LocalMatrixAssembler(unedof, pnedof, 0.0) for el in zip(elits...) uel, pel = el init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) Np = bfun(pqp) for j in 1:unedof, i in 1:unedof if uedofcomp[i] == uedofcomp[j] kuu[i, j] += (mu * JxW) * (dot(gradNu[i], gradNu[j])) end end for j in 1:pnedof, i in 1:unedof kup[i, j] += (-JxW * Np[j]) * gradNu[i][uedofcomp[i]] end end assemble!(ass, kuu) assemble!(ass, kup) assemble!(ass, transpose(kup)) end return ass end elits = (FEIterator(ufesp), FEIterator(pfesp)) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(ufesp, qargs), QPIterator(pfesp, qargs)) ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) integrate!(ass, elits, qpits, mu) return finish!(ass) end function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end function evaluate_pressure_error(pfesp) function integrate!(elit, qpit, truep) pnedof = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:pnedof pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(pfesp) qargs = (kind = :default, npts = 3,) qpit = QPIterator(pfesp, qargs) return integrate!(elit, qpit, truep) end function evaluate_velocity_error(ufesp) function integrate!(elit, qpit, trueux, trueuy) unedof = ndofsperel(elit) uedofcomp = edofcompnt(ufesp) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:unedof (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(ufesp) qargs = (kind = :default, npts = 3,) qpit = QPIterator(ufesp, qargs) return integrate!(elit, qpit, trueux, trueuy) end function run(N) vmesh, pmesh = genmesh(N) # Velocity spaces ufesp = FESpace(Float64, vmesh, FEH1_T6(), 2) locs = geometry(vmesh) inflate = A / N / 100 # The entire boundary boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl setebc!(ufesp, 0, i, 1, trueux(locs[i]...)) setebc!(ufesp, 0, i, 2, trueuy(locs[i]...)) end end # Pressure space pfesp = FESpace(Float64, pmesh, FEH1_T3(), 1) atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(pfesp, 0, atcenter[1], 1, 0.0) # Number the degrees of freedom numberdofs!([ufesp, pfesp]) tndof = ndofs(ufesp) + ndofs(pfesp) tnunk = nunknowns(ufesp) + nunknowns(pfesp) # Assemble the coefficient matrix K = assembleK(ufesp, pfesp, tndof, mu) # p = spy(K, canvas = DotCanvas) # display(p) # Solve the system U = fill(0.0, tndof) gathersysvec!(U, [ufesp, pfesp]) F = fill(0.0, tndof) solve!(U, K, F, tnunk) scattersysvec!([ufesp, pfesp], U) # Postprocessing makeattribute(pfesp, "p", 1) makeattribute(ufesp, "ux", 1) makeattribute(ufesp, "uy", 2) ep = evaluate_pressure_error(pfesp) ev = evaluate_velocity_error(ufesp) # vtkwrite("m_th_p2_p1_veclap_alt_e-p", baseincrel(pmesh), [(name = "p",), ]) # vtkwrite("m_th_p2_p1_veclap_alt_e-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) return (ep, ev) end test() = begin ep, ev = m_th_p2_p1_veclap_alt_e.run(4) @test isapprox([ep, ev], [2.596076907594511, 0.3001331486426876]) end end using .m_th_p2_p1_veclap_alt_e m_th_p2_p1_veclap_alt_e.test()
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
2343
[![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](http://www.repostatus.org/badges/latest/active.svg)](http://www.repostatus.org/#active) [![Build status](https://github.com/PetrKryslUCSD/Elfel.jl/workflows/CI/badge.svg)](https://github.com/PetrKryslUCSD/Elfel.jl/actions) [![Codecov](https://codecov.io/gh/PetrKryslUCSD/Elfel.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/PetrKryslUCSD/Elfel.jl) [![Latest documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://petrkryslucsd.github.io/Elfel.jl/dev) # Elfel.jl: Extensible library for finite element methods **elfel**<br> G. *adjective*. different, like something else, unique, unparalled ## Introduction This package provides support for the development of Finite Element Method applications, especially in continuum mechanics. Mixed methods with cooperating finite element spaces are supported. High performance is one of the focus points. Check out the [tutorials](https://petrkryslucsd.github.io/Elfel.jl/dev/tutorials/tutorials.html#Tutorials) to get a feel for the functionality of this package. ## Dependencies The library relies on mesh support from the following suite of small mesh-management packages: [`MeshCore`](https://github.com/PetrKryslUCSD/MeshCore.jl), [`MeshSteward`](https://github.com/PetrKryslUCSD/MeshSteward.jl). ## Usage Clone the repository, and execute ``` using Pkg; Pkg.activate("."); Pkg.instantiate() ``` in the `Elfel` folder. The user can either use/import individual functions from `Elfel` like so: ``` using Elfel.FElements: FEH1_T6, FEH1_T3, refshape, Jacobian ``` or all exported symbols maybe made available in the user's context as ``` using Elfel.Exports ``` The `examples` folder can be explored by simply running the files with `include()`. ## News - 07/15/2020: Implemented geometry carrier for finite elements that are not isoparametric. - 07/11/2020: Tutorial structure added. - 07/06/2020: Exports have been added to facilitate use of the library. - 07/05/2020: Vector finite element spaces tested. - 06/26/2020: L2 elements implemented, Stokes problem example. - 06/19/2020: Example of a mixed method for the discrete Stokes problem added. - 05/25/2020: Firmed up the concept of iterators for access to element and quadrature point data.
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
3370
- How do we connect the types from MeshCore to the Elfel element types? - TODO: Do I need an abstract type for the finite element? - Why does the FE iterator allocate? p = _storedofs!(it._dofs, p, state, it._irs[i], it._flds[i]) Is it the abstract types of the IRs and fields? - For multiple FE spaces, one could have an iterator which simultaneously iterates multiple spaces (invoking their own iterators). ``` struct It1 a end _update!(it::It1, state) = (it.a[state] = state) function Base.iterate(it::It1, state = 1) if state > length(it.a) return nothing else return (_update!(it, state), state+1) end end Base.length(it::It1) = length(it.a) struct It2 b end _update!(it::It2, state) = (it.b[state] = -state) function Base.iterate(it::It2, state = 1) if state > length(it.b) return nothing else return (_update!(it, state), state+1) end end Base.length(it::It2) = length(it.b) struct It it1::It1 it2::It2 end function _update!(it::It, state) iterate(it.it1, state) iterate(it.it2, state) it end function Base.iterate(it::It, state = 1) if state > length(it.it1) return nothing else return (_update!(it, state), state+1) end end Base.length(it::It2) = length(it.b) N = 3 it = It(It1(fill(0, N)), It2(fill(0, N))) for i in it @show it.it1 @show it.it2 end ``` - FE space could figure out basis function classification: which entity is it attached to, which one is it in serial order, and anything else, and share it with iterators (especially the quadrature-point iterator). Done. - Some tests with strain-displacement matrices. ``` module m using BenchmarkTools using StaticArrays using LinearAlgebra B = (g -> SVector{3}((g[1], 0, g[2])), g -> SVector{3}((0, g[2], g[1]))) function Bf(g, k) if k == 1 SVector{3}((g[1], 0, g[2])) else SVector{3}((0, g[2], g[1])) end end c = [1, 2, 1, 2, 1, 2] g = SVector{2}(rand(2)) # With allocations @btime begin v = 0.0 for i in 1:6 Bi = $B[$c[i]]($g) for j in 1:6 Bj = $B[$c[j]]($g) v += dot(Bi, Bj) end end v end # No allocations @btime begin v = 0.0 ci = 1 for i in 1:6 Bi = $B[ci]($g) ci = ci == 1 ? 2 : 1 cj = 1 for j in 1:6 Bj = $B[cj]($g) v += dot(Bi, Bj) cj = cj == 1 ? 2 : 1 end end v end # No allocations @btime begin v = 0.0 for i in 1:6 Bi = $Bf($g, $c[i]) for j in 1:6 Bj = $Bf($g, $c[j]) v += dot(Bi, Bj) end end v end function test() # With allocations begin v = 0.0 for i in 1:6 Bi = B[c[i]](g) for j in 1:6 Bj = B[c[j]](g) v += dot(Bi, Bj) end end @show v end # No allocations begin v = 0.0 ci = 1 for i in 1:6 Bi = B[ci](g) ci = ci == 1 ? 2 : 1 cj = 1 for j in 1:6 Bj = B[cj](g) v += dot(Bi, Bj) cj = cj == 1 ? 2 : 1 end end @show v end end test() end ``` - L2 element may be incapable of representing its geometry because it does not necessarily have nodal basis functions. What do we do about that? - .wslconfig [wsl2] memory=16GB swap=0
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
1043
# Elfel Documentation Elfel provides support for the development of Finite Element Method applications, especially in the area of continuum mechanics. Mixed methods with cooperating finite element spaces are supported. High performance is one of the focus points. The design of this package is predicated on the notion that it will provide simple building blocks to those who wish to explore the internals of finite element methods. Hence the focus is on low-level building blocks rather than on prepackaged, high-level, functionality. ## Tutorials Tutorials showing application of the library to some common PDE problems. ```@contents Pages = [ "tutorials/tutorials.md", ] Depth = 1 ``` ## How to guide The recipes. ```@contents Pages = [ "guide/guide.md", ] Depth = 1 ``` ## Reference manual The description of the types and functions. ```@contents Pages = [ "man/reference.md", ] Depth = 1 ``` ## Concepts The concepts and ideas are described. ```@contents Pages = [ "concepts/concepts.md", ] Depth = 1 ```
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
199
[Table of contents](https://petrkryslucsd.github.io/Elfel.jl/latest/index.html) # Design and operation concepts Needs to be written. ## Why a library of components ## Basic types ## Meshes
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
119
[Table of contents](https://petrkryslucsd.github.io/Elfel.jl/latest/index.html) # How to Guide Needs to be written.
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
808
# Reference manual ## Reference shapes ```@autodocs Modules = [Elfel.RefShapes] Pages = ["RefShapes.jl"] ``` ## Elements ```@autodocs Modules = [Elfel.FElements] Pages = ["FElements.jl"] ``` ## Spaces ```@autodocs Modules = [Elfel.FESpaces] Pages = ["FESpaces.jl"] ``` ## Fields ```@autodocs Modules = [Elfel.FESpaces.FEFields] Pages = ["FEFields.jl"] ``` ## Finite element iterators ```@autodocs Modules = [Elfel.FEIterators] Pages = ["FEIterators.jl"] ``` ## Quadrature-point iterators ```@autodocs Modules = [Elfel.QPIterators] Pages = ["QPIterators.jl"] ``` ## Assemblers ```@autodocs Modules = [Elfel.Assemblers] Pages = ["Assemblers.jl"] ``` ## Local Assemblers ```@autodocs Modules = [Elfel.LocalAssemblers] Pages = ["LocalAssemblers.jl"] ``` ## Index ```@index ```
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
9427
# Solve the heat conduction equation Synopsis: Compute the solution of the Poisson equation of heat conduction with a nonzero heat source. Quadrilateral four-node elements are used. The problem is linear heat conduction equation posed on a bi-unit square, solved with Dirichlet boundary conditions around the circumference. Uniform nonzero heat generation rate is present. The exact solution is in this way manufactured and hence known. That gives us an opportunity to calculate the true error. The complete code is in the file [`tut_poisson_q4.jl`](tut_poisson_q4.jl). The solution will be defined within a module in order to eliminate conflicts with data or functions defined elsewhere. ```julia module tut_poisson_q4 ``` We'll need some functionality from linear algebra, and the mesh libraries. Finally we will need the `Elfel` functionality. ```julia using LinearAlgebra using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports ``` This is the top level function. ```julia function run() ``` Input parameters: ```julia A = 1.0 # length of the side of the square kappa = 1.0; # thermal conductivity of the material Q = -6.0; # internal heat generation rate tempf(x, y) =(1.0 + x^2 + 2.0 * y^2); # the exact distribution of temperature N = 1000; # number of element edges along the sides of the square domain ``` Generate the computational mesh. ```julia mesh = genmesh(A, N) ``` Create the finite element space to represent the temperature solution. The degrees of freedom are real numbers (`Float64`), the quadrilaterals are defined by the mesh, and each of the elements has the continuity ``H ^1``, i. e. both the function values and the derivatives are square integrable. ```julia Uh = FESpace(Float64, mesh, FEH1_Q4()) ``` Apply the essential boundary conditions at the circumference of the square domain. We find the boundary incidence relation (`boundary(mesh)`), and then the list of all vertices connected by the boundary cells. The function `tempf` defines the analytical temperature variation, and hence for each of the vertices `i` on the boundary (they are of manifold dimension `0`), we set the component of the field (1) to the exact value of the temperature at that location. ```julia vl = connectedv(boundary(mesh)); locs = geometry(mesh) for i in vl setebc!(Uh, 0, i, 1, tempf(locs[i]...)) end ``` Number the degrees of freedom, both the unknowns and the data (prescribed) degrees of freedom. ```julia numberdofs!(Uh) @show ndofs(Uh), nunknowns(Uh) ``` Assemble the conductivity matrix and the vector of the heat loads. Refer to the definition of this function below. ```julia K, F = assembleKF(Uh, kappa, Q) ``` This is a vector to hold all degrees of freedom in the system. ```julia T = fill(0.0, ndofs(Uh)) ``` Here we collect the data degrees of freedom (the known values). ```julia gathersysvec!(T, Uh) ``` The system of linear algebraic equations is solved. ```julia solve!(T, K, F, nunknowns(Uh)) ``` The values of all the degrees of freedom can now be introduced into the finite element space. ```julia scattersysvec!(Uh, T) ``` Here we associate the values of the finite element space with the entities of the mesh as an attribute. ```julia makeattribute(Uh, "T", 1) ``` The correctness of the solution is checked by comparing the values at the vertices. ```julia checkcorrectness(Uh, tempf) ``` The attribute can now be written out for visualization into a VTK file. ```julia vtkwrite("q4-T", baseincrel(mesh), [(name = "T",)]) true # return success end ``` The domain is a square, meshed with quadrilateral elements. The function `Q4block` creates an incidence relation that defines the quadrilateral element shapes by the vertices connected into the shapes. This incidence relation is then attached to the mesh and the mesh is returned. ```julia function genmesh(A, N) conn = Q4block(A, A, N, N) return attach!(Mesh(), conn) end ``` The `assembleKF` function constructs the left-hand side coefficient matrix, conductivity matrix, as a sparse matrix, and a vector of the heat loads due to the internal heat generation rate `Q`. The boundary value problem is expressed in this weak form ```math \int_{V}(\mathrm{grad}\vartheta)\; \kappa (\mathrm{grad}T )^T\; \mathrm{d} V -\int_{V} \vartheta Q \; \mathrm{d} V = 0 ``` where the test function vanishes on the boundary where the temperature is prescribed, ``\vartheta(x) =0`` for ``x \in{S_1}`` Substituting ``\vartheta = N_j `` and ``T = \sum_i N_i T_i`` we obtain the linear algebraic equations ```math \sum_i T_i \int_{V} \mathrm{grad}N_j \; \kappa (\mathrm{grad}N_i)^T\; \mathrm{d} V -\int_{V} N_j Q \; \mathrm{d} V = 0 , \quad \forall j. ``` The volume element is ``\mathrm{d} V``, which in our case becomes ``1.0\times\mathrm{d} S``, since the thickness of the two dimensional domain is assumed to be 1.0. ```julia function assembleKF(Uh, kappa, Q) ``` At the top of the `assembleKF` we look at the function `integrate!` to evaluate the weak-form integrals. The key to making this calculation efficient is type stability. All the arguments coming in must have concrete types. This is why the `integrate!` function is an inner function: the function barrier allows for all arguments to be resolved to concrete types. ```julia function integrate!(am, av, elit, qpit, kappa, Q) nedof = ndofsperel(elit) ``` The local assemblers are just like matrices or vectors ```julia ke = LocalMatrixAssembler(nedof, nedof, 0.0) fe = LocalVectorAssembler(nedof, 0.0) for el in elit # Loop over all elements init!(ke, eldofs(el), eldofs(el)) # zero out elementwise matrix init!(fe, eldofs(el)) # and vector for qp in qpit # Now loop over the quadrature points Jac, J = jacjac(el, qp) # Calculate the Jacobian matrix, Jacobian gradN = bfungrad(qp, Jac) # Evaluate the spatial gradients JxW = J * weight(qp) # elementary volume N = bfun(qp) # Basis function values at the quadrature point ``` This double loop evaluates the elementwise conductivity matrix and the heat load vector precisely as the formula of the weak form dictates; see above. ```julia for i in 1:nedof for j in 1:nedof ke[j, i] += dot(gradN[j], gradN[i]) * (kappa * JxW) end fe[j] += N[j] * Q * JxW end end ``` Assemble the calculated contributions from this element ```julia assemble!(am, ke) assemble!(av, fe) end return am, av # Return the updated assemblers end ``` In the `assembleKF` function we first we create the element iterator. We can go through all the elements that define the domain of integration using this iterator. Each time a new element is accessed, some data are precomputed such as the element degrees of freedom. ```julia elit = FEIterator(Uh) ``` This is the quadrature point iterator. We know that the elements are quadrilateral, which makes the Gauss integration rule the obvious choice. We also select order 2 for accuracy. Quadrature-point iterators provide access to basis function values and gradients, the Jacobian matrix and the Jacobian determinant, the location of the quadrature point and so on. ```julia qpit = QPIterator(Uh, (kind = :Gauss, order = 2)) ``` Next we create assemblers, one for the sparse system matrix and one for the system vector. ```julia am = start!(SysmatAssemblerSparse(0.0), ndofs(Uh), ndofs(Uh)) av = start!(SysvecAssembler(0.0), ndofs(Uh)) ``` Now we call the integration function. The assemblers are modified inside this function... ```julia @time integrate!(am, av, elit, qpit, kappa, Q) ``` ...so that when the integration is done, we can materialize the sparse matrix and the vector and return them. ```julia return finish!(am), finish!(av) end ``` The linear algebraic system is solved by partitioning. The vector `T` is initially all zero, except in the degrees of freedom which are prescribed as nonzero. Therefore the product of the conductivity matrix and the vector `T` are the heat loads due to nonzero essential boundary conditions. To this we add the vector of heat loads due to the internal heat generation rate. The submatrix of the heat conduction matrix corresponding to the free degrees of freedom (unknowns), `K[1:nu, 1:nu]` is then used to solve for the unknowns `T [1:nu]`. ```julia function solve!(T, K, F, nu) @time KT = K * T @time T[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end ``` The correctness can be checked in various ways. Here we calculate the mean deviation of the calculated temperatures at the nodes relative to the exact values of the temperature. ```julia function checkcorrectness(Uh, tempf) geom = geometry(Uh.mesh) ir = baseincrel(Uh.mesh) T = attribute(ir.right, "T") std = 0.0 for i in 1:length(T) std += abs(T[i][1] - tempf(geom[i]...)) end @show (std / length(T)) <= 1.0e-9 end end # module ``` The module can now be used. ```julia using .tut_poisson_q4 tut_poisson_q4.run() ``` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
16810
# Solve the Stokes equation of colliding flow: Hood-Taylor, general formulation Synopsis: Compute the solution of the Stokes equation of two-dimensional incompressible viscous flow for a manufactured problem of colliding flow. Hood-Taylor triangular elements are used. The "manufactured" colliding flow example from Elman et al 2014. The Hood-Taylor formulation with quadratic triangles for the velocity and continuous pressure on linear triangles. The pressure is shown here with contours, and the velocities visualized with arrows at random points. ![Pressure and velocity](colliding.png) The formulation is the general elasticity-like scheme with strain-rate/velocity matrices. It can be manipulated into the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. The complete code is in the file [`tut_stokes_ht_p2_p1_gen.jl`](tut_stokes_ht_p2_p1_gen.jl). The solution will be defined within a module in order to eliminate conflicts with data or functions defined elsewhere. ```julia module tut_stokes_ht_p2_p1_gen ``` We'll need some functionality from linear algebra, static arrays, and the mesh libraries. Some plotting will be produced to visualize structure of the stiffness matrix. Finally we will need the `Elfel` functionality. ```julia using LinearAlgebra using StaticArrays using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using UnicodePlots ``` The boundary value problem is expressed in this weak form ```math \int_{V}{\underline{\varepsilon}}(\underline{\delta v})^T\; \underline{\underline{D}}\; {\underline{\varepsilon}}(\underline{u})\; \mathrm{d} V - \int_{V} \mathrm{div}(\underline{\delta v})\; p\; \mathrm{d} V = 0,\quad \forall \underline{\delta v} ``` ```math - \int_{V} \delta q\; \mathrm{div}(\underline{u}) \; \mathrm{d} V = 0,\quad \forall \delta q ``` Here ``\underline{\delta v}`` are the test functions in the velocity space, and ``\delta q`` are the pressure test functions. Further ``\underline {u}`` is the trial velocity, and ``p`` is the trial pressure. ```julia function run() mu = 1.0 # dynamic viscosity ``` This is the material-property matrix ``\underline{\underline{D}}``: ```julia D = SMatrix{3, 3}( [2*mu 0 0 0 2*mu 0 0 0 mu]) A = 1.0 # half of the length of the side of the square N = 100 # number of element edges per side of the square ``` These three functions define the true velocity components and the true pressure. ```julia trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 ``` Construct the two meshes for the mixed method. They need to support the velocity and pressure spaces. ```julia vmesh, pmesh = genmesh(A, N) ``` Construct the velocity space: it is a vector space with two components. The degrees of freedom are real numbers (`Float64`). The velocity mesh carries the finite elements of the continuity ``H ^1``, i. e. both the function values and the derivatives are square integrable. Each node carries 2 degrees of freedom, hence there are two velocity components per node. ```julia Uh = FESpace(Float64, vmesh, FEH1_T6(), 2) ``` Now we apply the boundary conditions at the nodes around the circumference. ```julia locs = geometry(vmesh) ``` We use searching based on the presence of the node within a box. The entire boundary will be captured within these four boxes, provided we inflate those boxes with a little tolerance (we can't rely on those nodes to be precisely at the coordinates given, we need to introduce some tolerance). ```julia boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] inflate = A / N / 100 for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl ``` Remember that all components of the velocity are known at the boundary. ```julia setebc!(Uh, 0, i, 1, trueux(locs[i]...)) setebc!(Uh, 0, i, 2, trueuy(locs[i]...)) end end ``` No we construct the pressure space. It is a continuous, piecewise linear space supported on a mesh of three-node triangles. ```julia Ph = FESpace(Float64, pmesh, FEH1_T3(), 1) ``` The pressure in this "enclosed" flow example is only known up to a constant. By setting pressure degree of freedom at one node will make the solution unique. ```julia atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(Ph, 0, atcenter[1], 1, 0.0) ``` Number the degrees of freedom. First all the free degrees of freedom are numbered, both velocities and pressures. Next all the data degrees of freedom are numbered, again both for the velocities and for the pressures. ```julia numberdofs!([Uh, Ph]) ``` The total number of degrees of freedom is now calculated. ```julia tndof = ndofs(Uh) + ndofs(Ph) ``` As is the total number of unknowns. ```julia tnunk = nunknowns(Uh) + nunknowns(Ph) ``` Assemble the coefficient matrix. ```julia K = assembleK(Uh, Ph, tndof, D) ``` Display the structure of the indefinite stiffness matrix. Note that this is the complete matrix, including rows and columns for all the degrees of freedom, unknown and known. ```julia p = spy(K, canvas = DotCanvas) display(p) ``` Solve the linear algebraic system. First construct system vector of all the degrees of freedom, in the first `tnunk` rows that corresponds to the unknowns, and the subsequent rows are for the data degrees of freedom. ```julia U = fill(0.0, tndof) gathersysvec!(U, [Uh, Ph]) ``` Note that the vector `U` consists of nonzero numbers in rows are for the data degrees of freedom. Multiplying the stiffness matrix with this vector will generate a load vector on the right-hand side. Otherwise there is no loading, hence the vector `F` consists of all zeros. ```julia F = fill(0.0, tndof) solve!(U, K, F, tnunk) ``` Once we have solved the system of linear equations, we can distribute the solution from the vector `U` into the finite element spaces. ```julia scattersysvec!([Uh, Ph], U) ``` Given that the solution is manufactured, i. e. exactly known, we can calculate the true errors. ```julia @show ep = evaluate_pressure_error(Ph, truep) @show ev = evaluate_velocity_error(Uh, trueux, trueuy) ``` Postprocessing. First we make attributes, scalar nodal attributes, associated with the meshes for the pressures and the velocity. ```julia makeattribute(Ph, "p", 1) makeattribute(Uh, "ux", 1) makeattribute(Uh, "uy", 2) ``` The pressure and the velocity components are then written out into two VTK files. ```julia vtkwrite("tut_stokes_ht_p2_p1_gen-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("tut_stokes_ht_p2_p1_gen-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) ``` The method converges very well, but, why not, here is the true pressure written out into a VTK file as well. We create a synthetic attribute by evaluating the true pressure at the locations of the nodes of the pressure mesh. ```julia geom = geometry(Ph.mesh) ir = baseincrel(Ph.mesh) ir.right.attributes["pt"] = VecAttrib([truep(geom[i]...) for i in 1:length(geom)]) vtkwrite("tut_stokes_ht_p2_p1_gen-pt", baseincrel(pmesh), [(name = "pt",), ]) return true end function genmesh(A, N) ``` Hood-Taylor pair of meshes is needed. The first mesh is for the velocities, composed of six-node triangles. ```julia vmesh = attach!(Mesh(), T6block(2 * A, 2 * A, N, N), "velocity") ``` Now translate so that the center of the square is at the origin of the coordinates. ```julia ir = baseincrel(vmesh) transform(ir, x -> x .- A) ``` The second mesh is used for the pressures, and it is composed of three-node triangles such that the corner nodes are shared between the first and the second mesh. ```julia pmesh = attach!(Mesh(), T6toT3(baseincrel(vmesh, "velocity")), "pressure") ``` Return the pair of meshes ```julia return vmesh, pmesh end function assembleK(Uh, Ph, tndof, D) function integrate!(ass, elits, qpits, D) ``` Consider the elementwise definition of the test strain rate, `` {\underline{\varepsilon}}(\underline{\delta v})``. It is calculated from the elementwise degrees of freedom and the associated basis functions as ```math {\underline{\varepsilon}}(\underline{\delta v}) = \sum_i{\delta V}_i {\underline{B}_{c(i)}(N_i)} ``` where ``i = 1, \ldots, n_{du}``, and ``n_{du}`` is the number of velocity degrees of freedom per element, ``c(i)`` is the number of the component corresponding to the degree of freedom ``i``. This is either 1 when degree of freedom ``i`` is the ``x``-component of the velocity, 2 otherwise(for the ``y``-component of the velocity). Analogously for the trial strain rate. The strain-rate/velocity matrices are defined as ```math {\underline{B}_{1}(N_i)} = \left[\begin{array}{c} \partial{N_i}/\partial{x} \\ 0 \\ \partial{N_i}/\partial{y} \end{array}\right], ``` and ```math {\underline{B}_{2}(N_i)} = \left[\begin{array}{c} 0 \\ \partial{N_i}/\partial{y} \\ \partial{N_i}/\partial{x} \end{array}\right]. ``` This tiny function evaluates the strain-rate/velocity matrices defined above from the gradient of a basis function and the given number of the component corresponding to the current degree of freedom. ```julia B = (g, k) -> (k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1]))) ``` This array defines the components for the element degrees of freedom, as defined above as ``c(i)``. ```julia c = edofcompnt(Uh) ``` These are the totals of the velocity and pressure degrees of freedom per element. ```julia n_du, n_dp = ndofsperel.((Uh, Ph)) ``` The local matrix assemblers are used as if they were ordinary elementwise dense matrices. Here they are defined. ```julia kuu = LocalMatrixAssembler(n_du, n_du, 0.0) kup = LocalMatrixAssembler(n_du, n_dp, 0.0) for el in zip(elits...) uel, pel = el ``` The local matrix assemblers are initialized with zeros for the values, and with the element degree of freedom vectors to be used in the assembly. The assembler `kuu` is used for the velocity degrees of freedom, and the assembler `kup` collect the coupling coefficients between the velocity and the pressure. The function `eldofs` collects the global numbers of the degrees of freedom either for the velocity space, or for the pressure space (`eldofs(pel)`). ```julia init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp ``` The integration is performed using the velocity quadrature points. ```julia Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) # gradients of the velocity basis functions Np = bfun(pqp) # pressure basis functions ``` This double loop corresponds precisely to the integrals of the weak form. This is the matrix in the upper left corner. ```julia for i in 1:n_du DBi = D * B(gradNu[i], c[i]) for j in 1:n_du Bj = B(gradNu[j], c[j]) kuu[j, i] += dot(Bj, DBi) * (JxW) end end ``` And this is the coupling matrix in the top right corner. ```julia for i in 1:n_dp, j in 1:n_du kup[j, i] += gradNu[j][c[j]] * (-JxW * Np[i]) end end ``` Assemble the matrices. The submatrix off the diagonal is assembled twice, once as itself, and once as its transpose. ```julia assemble!(ass, kuu) assemble!(ass, kup) # top right corner assemble!(ass, transpose(kup)) # bottom left corner end return ass # return the updated assembler of the global matrix end ``` In the `assembleK` function we first we create the element iterators. We can go through all the elements, both in the velocity finite element space and in the pressure finite element space, that define the domain of integration using this iterator. Each time a new element is accessed, some data are precomputed such as the element degrees of freedom, components of the degree of freedom, etc. Note that we need to iterate two finite element spaces, hence we create a tuple of iterators. ```julia elits = (FEIterator(Uh), FEIterator(Ph)) ``` These are the quadrature point iterators. We know that the elements are triangular. We choose the three-point rule, to capture the quadratic component in the velocity space. Quadrature-point iterators provide access to basis function values and gradients, the Jacobian matrix and the Jacobian determinant, the location of the quadrature point and so on. Note that we need to iterate the quadrature rules of two finite element spaces, hence we create a tuple of iterators. ```julia qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uh, qargs), QPIterator(Ph, qargs)) ``` The matrix will be assembled into this assembler. Which is initialized with the total number of degrees of freedom (dimension of the coefficient matrix before partitioning into unknowns and data degrees of freedom). ```julia ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) ``` The integration is carried out, and then... ```julia integrate!(ass, elits, qpits, D) ``` ...we materialize the sparse stiffness matrix and return it. ```julia return finish!(ass) end ``` The linear algebraic system is solved by partitioning. The vector `U` is initially all zero, except in the degrees of freedom which are prescribed as nonzero. Therefore the product of the stiffness matrix and the vector `U` are the loads due to nonzero essential boundary conditions. The submatrix of the stiffness conduction matrix corresponding to the free degrees of freedom (unknowns), `K[1:nu, 1:nu]` is then used to solve for the unknowns `U [1:nu]`. ```julia function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end ``` The function `evaluate_pressure_error` evaluates the true ``L^2`` error of the pressure. It does that by integrating the square of the difference between the approximate pressure and the true pressure, the true pressure being provided by the `truep` function. ```julia function evaluate_pressure_error(Ph, truep) function integrate!(elit, qpit, truep) n_dp = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:n_dp pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end ``` The function `evaluate_velocity_error` evaluates the true ``L^2`` error of the velocity. It does that by integrating the square of the difference between the approximate pressure and the true velocity, the true velocity being provided by the `trueux`, `trueuy` functions. ```julia function evaluate_velocity_error(Uh, trueux, trueuy) function integrate!(elit, qpit, trueux, trueuy) n_du = ndofsperel(elit) uedofcomp = edofcompnt(Uh) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:n_du (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(Uh) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Uh, qargs) return integrate!(elit, qpit, trueux, trueuy) end end ``` To run the example, evaluate this file which will compile the module `.tut_stokes_ht_p2_p1_gen`. ```julia using .tut_stokes_ht_p2_p1_gen tut_stokes_ht_p2_p1_gen.run() ``` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
17341
# Solve the Stokes equation of colliding flow: Reddy formulation Synopsis: Compute the solution of the Stokes equation of two-dimensional incompressible viscous flow for a manufactured problem of colliding flow. Hood-Taylor triangular elements are used. The "manufactured" colliding flow example from Elman et al 2014. The Hood-Taylor formulation with quadratic triangles for the velocity and continuous pressure on linear triangles. The pressure is shown here with contours, and the velocities visualized with arrows at random points. ![Pressure and velocity](colliding.png) The formulation is the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. The complete code is in the file [`tut_stokes_ht_p2_p1_reddy.jl`](tut_stokes_ht_p2_p1_reddy.jl). The solution will be defined within a module in order to eliminate conflicts with data or functions defined elsewhere. ```julia module tut_stokes_ht_p2_p1_reddy ``` We'll need some functionality from linear algebra, static arrays, and the mesh libraries. Some plotting will be produced to visualize structure of the stiffness matrix. Finally we will need the `Elfel` functionality. ```julia using LinearAlgebra using StaticArrays using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using UnicodePlots ``` The boundary value problem is expressed in this weak form ```math \int_{\Omega} \left(2\mu\frac{\partial{w_x}}{\partial{x}}\frac{\partial{u_x}}{\partial{x}} +\mu\frac{\partial{w_x}}{\partial{y}}\left(\frac{\partial{u_x}}{\partial{y}}+\frac{\partial{u_y}}{\partial{x}}\right) - \frac{\partial{w_x}}{\partial{x}} p \right) d\Omega = 0 ``` ```math \int_{\Omega} \left(2\mu\frac{\partial{w_y}}{\partial{y}}\frac{\partial{u_y}}{\partial{y}} +\mu\frac{\partial{w_y}}{\partial{x}}\left(\frac{\partial{u_x}}{\partial{y}}+\frac{\partial{u_y}}{\partial{x}}\right) - \frac{\partial{w_y}}{\partial{y}} p \right) d\Omega = 0 ``` ```math -\int_{\Omega} q \left(\frac{\partial{u_x}}{\partial{x}} + \frac{\partial{u_y}}{\partial{y}}\right)d\Omega = 0 ``` Here ``w_x, w_y`` are the test functions in the velocity space, and ``q`` is the pressure test functions. Further ``u_x, u_y`` is the trial velocity, and ``p`` is the trial pressure. ```julia function run() mu = 1.0 # dynamic viscosity A = 1.0 # half of the length of the side of the square N = 100 # number of element edges per side of the square ``` These three functions define the true velocity components and the true pressure. ```julia trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 ``` Construct the two meshes for the mixed method. They need to support the velocity and pressure spaces. ```julia vmesh, pmesh = genmesh(A, N) ``` Construct the velocity spaces: As an alternative to a previous treatment with a single vector space for the velocity, here we will use to vector spaces, one for each component of the velocity. The degrees of freedom are real numbers (`Float64`). The velocity mesh carries the finite elements of the continuity ``H ^1``, i. e. both the function values and the derivatives are square integrable. Each node carries just one degree of freedom (1). ```julia Uxh = FESpace(Float64, vmesh, FEH1_T6(), 1) Uyh = FESpace(Float64, vmesh, FEH1_T6(), 1) ``` Now we apply the boundary conditions at the nodes around the circumference. ```julia locs = geometry(vmesh) ``` We use searching based on the presence of the node within a box. The entire boundary will be captured within these four boxes, provided we inflate those boxes with a little tolerance (we can't rely on those nodes to be precisely at the coordinates given, we need to introduce some tolerance). ```julia boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] inflate = A / N / 100 for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl ``` Remember that all components of the velocity are known at the boundary. ```julia setebc!(Uxh, 0, i, 1, trueux(locs[i]...)) setebc!(Uyh, 0, i, 1, trueuy(locs[i]...)) end end ``` No we construct the pressure space. It is a continuous, piecewise linear space supported on a mesh of three-node triangles. ```julia Ph = FESpace(Float64, pmesh, FEH1_T3(), 1) ``` The pressure in this "enclosed" flow example is only known up to a constant. By setting pressure degree of freedom at one node will make the solution unique. ```julia atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(Ph, 0, atcenter[1], 1, 0.0) ``` Number the degrees of freedom. First all the free degrees of freedom are numbered, both velocities and pressures. Next all the data degrees of freedom are numbered, again both for the velocities and for the pressures. ```julia numberdofs!([Uxh, Uyh, Ph]) ``` The total number of degrees of freedom is now calculated. ```julia tndof = ndofs(Uxh) + ndofs(Uyh) + ndofs(Ph) ``` As is the total number of unknowns. ```julia tnunk = nunknowns(Uxh) + nunknowns(Uyh) + nunknowns(Ph) ``` Assemble the coefficient matrix. ```julia K = assembleK(Uxh, Uyh, Ph, tndof, mu) ``` Display the structure of the indefinite stiffness matrix. Note that this is the complete matrix, including rows and columns for all the degrees of freedom, unknown and known. ```julia p = spy(K, canvas = DotCanvas) display(p) ``` Solve the linear algebraic system. First construct system vector of all the degrees of freedom, in the first `tnunk` rows that corresponds to the unknowns, and the subsequent rows are for the data degrees of freedom. ```julia U = fill(0.0, tndof) gathersysvec!(U, [Uxh, Uyh, Ph]) ``` Note that the vector `U` consists of nonzero numbers in rows are for the data degrees of freedom. Multiplying the stiffness matrix with this vector will generate a load vector on the right-hand side. Otherwise there is no loading, hence the vector `F` consists of all zeros. ```julia F = fill(0.0, tndof) solve!(U, K, F, tnunk) ``` Once we have solved the system of linear equations, we can distribute the solution from the vector `U` into the finite element spaces. ```julia scattersysvec!([Uxh, Uyh, Ph], U) ``` Given that the solution is manufactured, i. e. exactly known, we can calculate the true errors. ```julia @show ep = evaluate_pressure_error(Ph, truep) @show ev = evaluate_velocity_error(Uxh, Uyh, trueux, trueuy) ``` Postprocessing. First we make attributes, scalar nodal attributes, associated with the meshes for the pressures and the velocity. ```julia makeattribute(Ph, "p", 1) makeattribute(Uxh, "ux", 1) makeattribute(Uyh, "uy", 1) ``` The pressure and the velocity components are then written out into two VTK files. ```julia vtkwrite("tut_stokes_ht_p2_p1_reddy-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("tut_stokes_ht_p2_p1_reddy-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) return true end function genmesh(A, N) ``` Hood-Taylor pair of meshes is needed. The first mesh is for the velocities, composed of six-node triangles. ```julia vmesh = attach!(Mesh(), T6block(2 * A, 2 * A, N, N), "velocity") ``` Now translate so that the center of the square is at the origin of the coordinates. ```julia ir = baseincrel(vmesh) transform(ir, x -> x .- A) ``` The second mesh is used for the pressures, and it is composed of three-node triangles such that the corner nodes are shared between the first and the second mesh. ```julia pmesh = attach!(Mesh(), T6toT3(baseincrel(vmesh, "velocity")), "pressure") ``` Return the pair of meshes ```julia return vmesh, pmesh end function assembleK(Uxh, Uyh, Ph, tndof, mu) ``` Here we demonstrate that the coefficient matrix, which is expected to have the structure ```math K = \left[ \begin{array}{cc} A & B^T \\ B & 0 \end{array}\right] ``` can be constructed in stages. Refer to the description below. The two functions below carry out the integration of two separate parts of the coefficient matrix. ```julia function integrateApart!(ass, elits, qpits, mu) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxux = LocalMatrixAssembler(uxnedof, uxnedof, 0.0) kuyuy = LocalMatrixAssembler(uynedof, uynedof, 0.0) kuxuy = LocalMatrixAssembler(uxnedof, uynedof, 0.0) for el in zip(elits...) uxel, uyel, pel = el init!(kuxux, eldofs(uxel), eldofs(uxel)) init!(kuyuy, eldofs(uyel), eldofs(uyel)) init!(kuxuy, eldofs(uxel), eldofs(uyel)) for qp in zip(qpits...) ``` Step the quadrature point iterators in step: this assumes that in fact there is the same number of quadrature points in all the quadrature rules. ```julia uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) ``` Note that the gradients of the basis functions are not necessarily the same in those two velocity spaces. Hence we must grab the gradient from the correct space. ```julia gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) for j in 1:uxnedof, i in 1:uxnedof kuxux[i, j] += (mu * JxW) * (2 * gradNux[i][1] * gradNux[j][1] + gradNux[i][2] * gradNux[j][2]) end for j in 1:uynedof, i in 1:uynedof kuyuy[i, j] += (mu * JxW) * (gradNuy[i][1] * gradNuy[j][1] + 2 * gradNuy[i][2] * gradNuy[j][2]) end for j in 1:uynedof, i in 1:uxnedof kuxuy[i, j] += (mu * JxW) * (gradNux[i][1] * gradNuy[j][2]) end end assemble!(ass, kuxux) assemble!(ass, kuxuy) # off-diagonal matrix needs to be assembled twice assemble!(ass, transpose(kuxuy)) assemble!(ass, kuyuy) end return ass end function integrateBBTparts!(ass, elits, qpits) uxnedof, uynedof, pnedof = ndofsperel.(elits) kuxp = LocalMatrixAssembler(uxnedof, pnedof, 0.0) kuyp = LocalMatrixAssembler(uynedof, pnedof, 0.0) for el in zip(elits...) ``` The iterators of the finite elements are stepped in unison. ```julia uxel, uyel, pel = el ``` Initialize the local matrix assembler with the global degree of freedom numbers, both for the velocity spaces and for the pressure space. ```julia init!(kuxp, eldofs(uxel), eldofs(pel)) init!(kuyp, eldofs(uyel), eldofs(pel)) for qp in zip(qpits...) ``` Step the quadrature point iterators in step: this assumes that in fact there is the same number of quadrature points in all the quadrature rules. ```julia uxqp, uyqp, pqp = qp Jac, J = jacjac(pel, pqp) JxW = J * weight(pqp) gradNux = bfungrad(uxqp, Jac) gradNuy = bfungrad(uyqp, Jac) Np = bfun(pqp) for j in 1:pnedof, i in 1:uxnedof kuxp[i, j] += (-JxW) * (gradNux[i][1] * Np[j]) end for j in 1:pnedof, i in 1:uynedof kuyp[i, j] += (-JxW) * (gradNuy[i][2] * Np[j]) end end assemble!(ass, kuxp) assemble!(ass, transpose(kuxp)) assemble!(ass, kuyp) assemble!(ass, transpose(kuyp)) end return ass end ``` In the `assembleK` function we first we create the element iterators. We can go through all the elements, both in the velocity finite element space and in the pressure finite element space, that define the domain of integration using this iterator. Each time a new element is accessed, some data are precomputed such as the element degrees of freedom, components of the degree of freedom, etc. Note that we need to iterate two finite element spaces, hence we create a tuple of iterators. ```julia elits = (FEIterator(Uxh), FEIterator(Uyh), FEIterator(Ph)) ``` These are the quadrature point iterators. We know that the elements are triangular. We choose the three-point rule, to capture the quadratic component in the velocity space. Quadrature-point iterators provide access to basis function values and gradients, the Jacobian matrix and the Jacobian determinant, the location of the quadrature point and so on. Note that we need to iterate the quadrature rules of three finite element spaces, hence we create a tuple of iterators. All of these quadrature point iterators refer to the "same" quadrature rule: the same number of quadrature points, the same weights, and so on. However, the services these quadrature points provide do depend on the finite element space as well, for instance they would typically have different basis functions. ```julia qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs), QPIterator(Ph, qargs)) ``` The matrix will be assembled into this assembler. Which is initialized with the total number of degrees of freedom (dimension of the coefficient matrix before partitioning into unknowns and data degrees of freedom). ```julia ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) ``` First we calculate the "A" part, using the function below. It is "assembled" into the assembler, which means that after this function finishes, the assembler represents this intermediate matrix ```math K = \left[ \begin{array}{cc} A & 0 \\ 0 & 0 \end{array}\right] ``` ```julia integrateApart!(ass, elits, qpits, mu) ``` Then the "B-transpose(B)" part using this function is added to the assembler. When the function below finishes, the assembler represents the entire ``K`` matrix. ```julia integrateBBTparts!(ass, elits, qpits) ``` Finally, we materialize the sparse stiffness matrix from the assembler and return it. ```julia return finish!(ass) end ``` The linear algebraic system is solved by partitioning. The vector `U` is initially all zero, except in the degrees of freedom which are prescribed as nonzero. Therefore the product of the stiffness matrix and the vector `U` are the loads due to nonzero essential boundary conditions. The submatrix of the stiffness conduction matrix corresponding to the free degrees of freedom (unknowns), `K[1:nu, 1:nu]` is then used to solve for the unknowns `U [1:nu]`. ```julia function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end ``` The function `evaluate_pressure_error` evaluates the true ``L^2`` error of the pressure. It does that by integrating the square of the difference between the approximate pressure and the true pressure, the true pressure being provided by the `truep` function. ```julia function evaluate_pressure_error(Ph, truep) function integrate!(elit, qpit, truep) n_dp = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:n_dp pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end ``` The function `evaluate_velocity_error` evaluates the true ``L^2`` error of the velocity. It does that by integrating the square of the difference between the approximate pressure and the true velocity, the true velocity being provided by the `trueux`, `trueuy` functions. ```julia function evaluate_velocity_error(Uxh, Uyh, trueux, trueuy) function integrate!(elits, qpits, trueux, trueuy) n_du, n_du = ndofsperel.(elits) E = 0.0 for el in zip(elits...) uxel, uyel = el uxdofvals = eldofvals(uxel) uydofvals = eldofvals(uyel) for qp in zip(qpits...) uxqp, uyqp = qp Jac, J = jacjac(uxel, uxqp) JxW = J * weight(uxqp) Nu = bfun(uxqp) uxt = trueux(location(uxel, uxqp)...) uyt = trueuy(location(uxel, uxqp)...) uxa = 0.0 uya = 0.0 for j in 1:n_du uxa += (uxdofvals[j] * Nu[j]) uya += (uydofvals[j] * Nu[j]) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elits = (FEIterator(Uxh), FEIterator(Uyh),) qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uxh, qargs), QPIterator(Uyh, qargs),) return integrate!(elits, qpits, trueux, trueuy) end end ``` To run the example, evaluate this file which will compile the module `.tut_stokes_ht_p2_p1_reddy`. ```julia using .tut_stokes_ht_p2_p1_reddy tut_stokes_ht_p2_p1_reddy.run() ``` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
15610
# Solve the Stokes equation of colliding flow: vector Laplacian version Synopsis: Compute the solution of the Stokes equation of two-dimensional incompressible viscous flow for a manufactured problem of colliding flow. Hood-Taylor triangular elements are used. The "manufactured" colliding flow example from Elman et al 2014. The Hood-Taylor formulation with quadratic triangles for the velocity and continuous pressure on linear triangles. The pressure is shown here with contours, and the velocities visualized with arrows at random points. ![Pressure and velocity](colliding.png) The formulation is the one derived in Donea, Huerta, Introduction to the finite element method, 1993. Page 486 ff, and Elman, et al., Finite elements and fast iterative solvers, p. 132. In brief, it is the vector Laplacian version. The complete code is in the file [`tut_stokes_ht_p2_p1_veclap.jl`](tut_stokes_ht_p2_p1_veclap.jl). The solution will be defined within a module in order to eliminate conflicts with data or functions defined elsewhere. ```julia module tut_stokes_ht_p2_p1_veclap ``` We'll need some functionality from linear algebra, static arrays, and the mesh libraries. Some plotting will be produced to visualize structure of the stiffness matrix. Finally we will need the `Elfel` functionality. ```julia using LinearAlgebra using StaticArrays using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using UnicodePlots ``` The boundary value problem is expressed in this weak form ```math \int_{V}\mu {\underline{\nabla}}\;\underline{\delta v}\; :\; {\underline{\nabla}}\;\underline{u}\; \mathrm{d} V - \int_{V} \mathrm{div}(\underline{\delta v})\; p\; \mathrm{d} V = 0,\quad \forall \underline{\delta v} ``` ```math - \int_{V} \delta q\; \mathrm{div}(\underline{u}) \; \mathrm{d} V = 0,\quad \forall \delta q ``` Here ``\underline{\delta v}`` are the test functions in the velocity space, and ``\delta q`` are the pressure test functions. Further ``\underline {u}`` is the trial velocity, and ``p`` is the trial pressure. The operator ``:`` produces the componentwise scalar product of the gradients, ```math A\; :\;B = A_{ij}B_{ij}``. ``` Then the first term may be rewritten as ```math {\underline{\nabla}}\;\underline{\delta v}\; :\; {\underline{\nabla}}\;\underline{u} = (\underline{\nabla}\delta v_x)^T \underline{\nabla}u_x + (\underline{\nabla}\delta v_y)^T \underline{\nabla}u_y ``` ```julia function run() mu = 1.0 # dynamic viscosity A = 1.0 # half of the length of the side of the square N = 100 # number of element edges per side of the square ``` These three functions define the true velocity components and the true pressure. ```julia trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 ``` Construct the two meshes for the mixed method. They need to support the velocity and pressure spaces. ```julia vmesh, pmesh = genmesh(A, N) ``` Construct the velocity space: it is a vector space with two components. The degrees of freedom are real numbers (`Float64`). The velocity mesh carries the finite elements of the continuity ``H ^1``, i. e. both the function values and the derivatives are square integrable. Each node carries 2 degrees of freedom, hence there are two velocity components per node. ```julia Uh = FESpace(Float64, vmesh, FEH1_T6(), 2) ``` Now we apply the boundary conditions at the nodes around the circumference. ```julia locs = geometry(vmesh) ``` We use searching based on the presence of the node within a box. The entire boundary will be captured within these four boxes, provided we inflate those boxes with a little tolerance (we can't rely on those nodes to be precisely at the coordinates given, we need to introduce some tolerance). ```julia boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] inflate = A / N / 100 for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl ``` Remember that all components of the velocity are known at the boundary. ```julia setebc!(Uh, 0, i, 1, trueux(locs[i]...)) setebc!(Uh, 0, i, 2, trueuy(locs[i]...)) end end ``` No we construct the pressure space. It is a continuous, piecewise linear space supported on a mesh of three-node triangles. ```julia Ph = FESpace(Float64, pmesh, FEH1_T3(), 1) ``` The pressure in this "enclosed" flow example is only known up to a constant. By setting pressure degree of freedom at one node will make the solution unique. ```julia atcenter = vselect(geometry(pmesh); nearestto = [0.0, 0.0]) setebc!(Ph, 0, atcenter[1], 1, 0.0) ``` Number the degrees of freedom. First all the free degrees of freedom are numbered, both velocities and pressures. Next all the data degrees of freedom are numbered, again both for the velocities and for the pressures. ```julia numberdofs!([Uh, Ph]) ``` The total number of degrees of freedom is now calculated. ```julia tndof = ndofs(Uh) + ndofs(Ph) ``` As is the total number of unknowns. ```julia tnunk = nunknowns(Uh) + nunknowns(Ph) ``` Assemble the coefficient matrix. ```julia K = assembleK(Uh, Ph, tndof, mu) ``` Display the structure of the indefinite stiffness matrix. Note that this is the complete matrix, including rows and columns for all the degrees of freedom, unknown and known. ```julia p = spy(K, canvas = DotCanvas) display(p) ``` Solve the linear algebraic system. First construct system vector of all the degrees of freedom, in the first `tnunk` rows that corresponds to the unknowns, and the subsequent rows are for the data degrees of freedom. ```julia U = fill(0.0, tndof) gathersysvec!(U, [Uh, Ph]) ``` Note that the vector `U` consists of nonzero numbers in rows are for the data degrees of freedom. Multiplying the stiffness matrix with this vector will generate a load vector on the right-hand side. Otherwise there is no loading, hence the vector `F` consists of all zeros. ```julia F = fill(0.0, tndof) solve!(U, K, F, tnunk) ``` Once we have solved the system of linear equations, we can distribute the solution from the vector `U` into the finite element spaces. ```julia scattersysvec!([Uh, Ph], U) ``` Given that the solution is manufactured, i. e. exactly known, we can calculate the true errors. ```julia @show ep = evaluate_pressure_error(Ph, truep) @show ev = evaluate_velocity_error(Uh, trueux, trueuy) ``` Postprocessing. First we make attributes, scalar nodal attributes, associated with the meshes for the pressures and the velocity. ```julia makeattribute(Ph, "p", 1) makeattribute(Uh, "ux", 1) makeattribute(Uh, "uy", 2) ``` The pressure and the velocity components are then written out into two VTK files. ```julia vtkwrite("tut_stokes_ht_p2_p1_veclap-p", baseincrel(pmesh), [(name = "p",), ]) vtkwrite("tut_stokes_ht_p2_p1_veclap-v", baseincrel(vmesh), [(name = "ux",), (name = "uy",)]) ``` The method converges very well, but, why not, here is the true pressure written out into a VTK file as well. We create a synthetic attribute by evaluating the true pressure at the locations of the nodes of the pressure mesh. ```julia geom = geometry(Ph.mesh) ir = baseincrel(Ph.mesh) ir.right.attributes["pt"] = VecAttrib([truep(geom[i]...) for i in 1:length(geom)]) vtkwrite("tut_stokes_ht_p2_p1_veclap-pt", baseincrel(pmesh), [(name = "pt",), ]) return true end function genmesh(A, N) ``` Hood-Taylor pair of meshes is needed. The first mesh is for the velocities, composed of six-node triangles. ```julia vmesh = attach!(Mesh(), T6block(2 * A, 2 * A, N, N), "velocity") ``` Now translate so that the center of the square is at the origin of the coordinates. ```julia ir = baseincrel(vmesh) transform(ir, x -> x .- A) ``` The second mesh is used for the pressures, and it is composed of three-node triangles such that the corner nodes are shared between the first and the second mesh. ```julia pmesh = attach!(Mesh(), T6toT3(baseincrel(vmesh, "velocity")), "pressure") ``` Return the pair of meshes ```julia return vmesh, pmesh end function assembleK(Uh, Ph, tndof, mu) function integrate!(ass, elits, qpits, mu) ``` This array defines the components for the element degrees of freedom: ``c(i)`` is 1 or 2. ```julia c = edofcompnt(Uh) ``` These are the totals of the velocity and pressure degrees of freedom per element. ```julia n_du, n_dp = ndofsperel.((Uh, Ph)) ``` The local matrix assemblers are used as if they were ordinary elementwise dense matrices. Here they are defined. ```julia kuu = LocalMatrixAssembler(n_du, n_du, 0.0) kup = LocalMatrixAssembler(n_du, n_dp, 0.0) for el in zip(elits...) uel, pel = el ``` The local matrix assemblers are initialized with zeros for the values, and with the element degree of freedom vectors to be used in the assembly. The assembler `kuu` is used for the velocity degrees of freedom, and the assembler `kup` collect the coupling coefficients between the velocity and the pressure. The function `eldofs` collects the global numbers of the degrees of freedom either for the velocity space, or for the pressure space (`eldofs(pel)`). ```julia init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp ``` The integration is performed using the velocity quadrature points. ```julia Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) # gradients of the velocity basis functions Np = bfun(pqp) # pressure basis functions ``` This double loop corresponds precisely to the integrals of the weak form: dot product of the gradients of the basis functions. This is the matrix in the upper left corner. ```julia for i in 1:n_du, j in 1:n_du if c[i] == c[j] kuu[j, i] += (mu * JxW) * (dot(gradNu[j], gradNu[i])) end end ``` And this is the coupling matrix in the top right corner. ```julia for i in 1:n_dp, j in 1:n_du kup[j, i] += gradNu[j][c[j]] * (-JxW * Np[i]) end end ``` Assemble the matrices. The submatrix off the diagonal is assembled twice, once as itself, and once as its transpose. ```julia assemble!(ass, kuu) assemble!(ass, kup) # top right corner assemble!(ass, transpose(kup)) # bottom left corner end return ass # return the updated assembler of the global matrix end ``` In the `assembleK` function we first we create the element iterators. We can go through all the elements, both in the velocity finite element space and in the pressure finite element space, that define the domain of integration using this iterator. Each time a new element is accessed, some data are precomputed such as the element degrees of freedom, components of the degree of freedom, etc. Note that we need to iterate two finite element spaces, hence we create a tuple of iterators. ```julia elits = (FEIterator(Uh), FEIterator(Ph)) ``` These are the quadrature point iterators. We know that the elements are triangular. We choose the three-point rule, to capture the quadratic component in the velocity space. Quadrature-point iterators provide access to basis function values and gradients, the Jacobian matrix and the Jacobian determinant, the location of the quadrature point and so on. Note that we need to iterate the quadrature rules of two finite element spaces, hence we create a tuple of iterators. ```julia qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uh, qargs), QPIterator(Ph, qargs)) ``` The matrix will be assembled into this assembler. Which is initialized with the total number of degrees of freedom (dimension of the coefficient matrix before partitioning into unknowns and data degrees of freedom). ```julia ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) ``` The integration is carried out, and then... ```julia integrate!(ass, elits, qpits, mu) ``` ...we materialize the sparse stiffness matrix and return it. ```julia return finish!(ass) end ``` The linear algebraic system is solved by partitioning. The vector `U` is initially all zero, except in the degrees of freedom which are prescribed as nonzero. Therefore the product of the stiffness matrix and the vector `U` are the loads due to nonzero essential boundary conditions. The submatrix of the stiffness conduction matrix corresponding to the free degrees of freedom (unknowns), `K[1:nu, 1:nu]` is then used to solve for the unknowns `U [1:nu]`. ```julia function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end ``` The function `evaluate_pressure_error` evaluates the true ``L^2`` error of the pressure. It does that by integrating the square of the difference between the approximate pressure and the true pressure, the true pressure being provided by the `truep` function. ```julia function evaluate_pressure_error(Ph, truep) function integrate!(elit, qpit, truep) n_dp = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:n_dp pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end ``` The function `evaluate_velocity_error` evaluates the true ``L^2`` error of the velocity. It does that by integrating the square of the difference between the approximate pressure and the true velocity, the true velocity being provided by the `trueux`, `trueuy` functions. ```julia function evaluate_velocity_error(Uh, trueux, trueuy) function integrate!(elit, qpit, trueux, trueuy) n_du = ndofsperel(elit) uedofcomp = edofcompnt(Uh) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:n_du (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(Uh) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Uh, qargs) return integrate!(elit, qpit, trueux, trueuy) end end ``` To run the example, evaluate this file which will compile the module `.tut_stokes_ht_p2_p1_veclap`. ```julia using .tut_stokes_ht_p2_p1_veclap tut_stokes_ht_p2_p1_veclap.run() ``` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
16483
# Solve the Stokes equation of colliding flow: MINI element, general formulation Synopsis: Compute the solution of the Stokes equation of two-dimensional incompressible viscous flow for a manufactured problem of colliding flow. Bubble-function triangular elements are used. The "manufactured" colliding flow example from Elman et al 2014. The MINI formulation with linear triangles with a cubic bubble function for the velocity and continuous pressure on linear triangles. The pressure is shown here with contours, and the velocities visualized with arrows at random points. ![Pressure and velocity](colliding.png) The formulation is the general elasticity-like scheme with strain-rate/velocity matrices. It can be manipulated into the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. The complete code is in the file [`tut_stokes_p1b_p1_gen.jl`](tut_stokes_p1b_p1_gen.jl). The solution will be defined within a module in order to eliminate conflicts with data or functions defined elsewhere. ```julia module tut_stokes_p1b_p1_gen ``` We'll need some functionality from linear algebra, static arrays, and the mesh libraries. Some plotting will be produced to visualize structure of the stiffness matrix. Finally we will need the `Elfel` functionality. ```julia using LinearAlgebra using StaticArrays using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using UnicodePlots ``` The boundary value problem is expressed in this weak form ```math \int_{V}{\underline{\varepsilon}}(\underline{\delta v})^T\; \underline{\underline{D}}\; {\underline{\varepsilon}}(\underline{u})\; \mathrm{d} V - \int_{V} \mathrm{div}(\underline{\delta v})\; p\; \mathrm{d} V = 0,\quad \forall \underline{\delta v} ``` ```math - \int_{V} \delta q\; \mathrm{div}(\underline{u}) \; \mathrm{d} V = 0,\quad \forall \delta q ``` Here ``\underline{\delta v}`` are the test functions in the velocity space, and ``\delta q`` are the pressure test functions. Further ``\underline {u}`` is the trial velocity, and ``p`` is the trial pressure. ```julia function run() mu = 1.0 # dynamic viscosity ``` This is the material-property matrix ``\underline{\underline{D}}``: ```julia D = SMatrix{3, 3}( [2*mu 0 0 0 2*mu 0 0 0 mu]) A = 1.0 # half of the length of the side of the square N = 100 # number of element edges per side of the square ``` These three functions define the true velocity components and the true pressure. ```julia trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 ``` Construct the two meshes for the mixed method. They need to support the velocity and pressure spaces. ```julia mesh = genmesh(A, N) ``` Construct the velocity space: it is a vector space with two components. The degrees of freedom are real numbers (`Float64`). The velocity mesh carries the finite elements of the continuity ``H ^1``, i. e. both the function values and the derivatives are square integrable. Each node carries 2 degrees of freedom, hence there are two velocity components per node. ```julia Uh = FESpace(Float64, mesh, FEH1_T3_BUBBLE(), 2) ``` Now we apply the boundary conditions at the nodes around the circumference. ```julia locs = geometry(mesh) ``` We use searching based on the presence of the node within a box. The entire boundary will be captured within these four boxes, provided we inflate those boxes with a little tolerance (we can't rely on those nodes to be precisely at the coordinates given, we need to introduce some tolerance). ```julia boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] inflate = A / N / 100 for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl ``` Remember that all components of the velocity are known at the boundary. ```julia setebc!(Uh, 0, i, 1, trueux(locs[i]...)) setebc!(Uh, 0, i, 2, trueuy(locs[i]...)) end end ``` No we construct the pressure space. It is a continuous, piecewise linear space supported on a mesh of three-node triangles. ```julia Ph = FESpace(Float64, mesh, FEH1_T3(), 1) ``` The pressure in this "enclosed" flow example is only known up to a constant. By setting pressure degree of freedom at one node will make the solution unique. ```julia atcenter = vselect(geometry(mesh); nearestto = [0.0, 0.0]) setebc!(Ph, 0, atcenter[1], 1, 0.0) ``` Number the degrees of freedom. First all the free degrees of freedom are numbered, both velocities and pressures. Next all the data degrees of freedom are numbered, again both for the velocities and for the pressures. ```julia numberdofs!([Uh, Ph]) ``` The total number of degrees of freedom is now calculated. ```julia tndof = ndofs(Uh) + ndofs(Ph) ``` As is the total number of unknowns. ```julia tnunk = nunknowns(Uh) + nunknowns(Ph) ``` Assemble the coefficient matrix. ```julia K = assembleK(Uh, Ph, tndof, D) ``` Display the structure of the indefinite stiffness matrix. Note that this is the complete matrix, including rows and columns for all the degrees of freedom, unknown and known. ```julia p = spy(K, canvas = DotCanvas) display(p) ``` Solve the linear algebraic system. First construct system vector of all the degrees of freedom, in the first `tnunk` rows that corresponds to the unknowns, and the subsequent rows are for the data degrees of freedom. ```julia U = fill(0.0, tndof) gathersysvec!(U, [Uh, Ph]) ``` Note that the vector `U` consists of nonzero numbers in rows are for the data degrees of freedom. Multiplying the stiffness matrix with this vector will generate a load vector on the right-hand side. Otherwise there is no loading, hence the vector `F` consists of all zeros. ```julia F = fill(0.0, tndof) solve!(U, K, F, tnunk) ``` Once we have solved the system of linear equations, we can distribute the solution from the vector `U` into the finite element spaces. ```julia scattersysvec!([Uh, Ph], U) ``` Given that the solution is manufactured, i. e. exactly known, we can calculate the true errors. ```julia @show ep = evaluate_pressure_error(Ph, truep) @show ev = evaluate_velocity_error(Uh, trueux, trueuy) ``` Postprocessing. First we make attributes, scalar nodal attributes, associated with the meshes for the pressures and the velocity. ```julia makeattribute(Ph, "p", 1) makeattribute(Uh, "ux", 1) makeattribute(Uh, "uy", 2) ``` The pressure and the velocity components are then written out into two VTK files. ```julia vtkwrite("tut_stokes_p1b_p1_gen-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("tut_stokes_p1b_p1_gen-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) return true end function genmesh(A, N) ``` Linear triangle mesh is used for both the velocity space and the pressure space. ```julia mesh = attach!(Mesh(), T3block(2 * A, 2 * A, N, N), "velocity") ``` Now translate so that the center of the square is at the origin of the coordinates. ```julia ir = baseincrel(mesh) transform(ir, x -> x .- A) ``` The bubble degree of freedom is associated with the element itself. The mesh will therefore be equipped with the incidence relation ``(2, 2)``. The finite element space for the velocity will therefore have degrees of freedom associated with the vertices and with the faces (elements themselves). The finite element space does that by associating fields with incidence relations, hence the need for this one. ```julia eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(Uh, Ph, tndof, D) function integrate!(ass, elits, qpits, D) ``` Consider the elementwise definition of the test strain rate, `` {\underline{\varepsilon}}(\underline{\delta v})``. It is calculated from the elementwise degrees of freedom and the associated basis functions as ```math {\underline{\varepsilon}}(\underline{\delta v}) = \sum_i{\delta V}_i {\underline{B}_{c(i)}(N_i)} ``` where ``i = 1, \ldots, n_{du}``, and ``n_{du}`` is the number of velocity degrees of freedom per element, ``c(i)`` is the number of the component corresponding to the degree of freedom ``i``. This is either 1 when degree of freedom ``i`` is the ``x``-component of the velocity, 2 otherwise(for the ``y``-component of the velocity). Analogously for the trial strain rate. The strain-rate/velocity matrices are defined as ```math {\underline{B}_{1}(N_i)} = \left[\begin{array}{c} \partial{N_i}/\partial{x} \\ 0 \\ \partial{N_i}/\partial{y} \end{array}\right], ``` and ```math {\underline{B}_{2}(N_i)} = \left[\begin{array}{c} 0 \\ \partial{N_i}/\partial{y} \\ \partial{N_i}/\partial{x} \end{array}\right]. ``` This tiny function evaluates the strain-rate/velocity matrices defined above from the gradient of a basis function and the given number of the component corresponding to the current degree of freedom. ```julia B = (g, k) -> (k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1]))) ``` This array defines the components for the element degrees of freedom, as defined above as ``c(i)``. ```julia c = edofcompnt(Uh) ``` These are the totals of the velocity and pressure degrees of freedom per element. ```julia n_du, n_dp = ndofsperel.((Uh, Ph)) ``` The local matrix assemblers are used as if they were ordinary elementwise dense matrices. Here they are defined. ```julia kuu = LocalMatrixAssembler(n_du, n_du, 0.0) kup = LocalMatrixAssembler(n_du, n_dp, 0.0) for el in zip(elits...) uel, pel = el ``` The local matrix assemblers are initialized with zeros for the values, and with the element degree of freedom vectors to be used in the assembly. The assembler `kuu` is used for the velocity degrees of freedom, and the assembler `kup` collect the coupling coefficients between the velocity and the pressure. The function `eldofs` collects the global numbers of the degrees of freedom either for the velocity space, or for the pressure space (`eldofs(pel)`). ```julia init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp ``` The integration is performed using the velocity quadrature points. ```julia Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) # gradients of the velocity basis functions Np = bfun(pqp) # pressure basis functions ``` This double loop corresponds precisely to the integrals of the weak form. This is the matrix in the upper left corner. ```julia for i in 1:n_du DBi = D * B(gradNu[i], c[i]) for j in 1:n_du Bj = B(gradNu[j], c[j]) kuu[j, i] += dot(Bj, DBi) * (JxW) end end ``` And this is the coupling matrix in the top right corner. ```julia for i in 1:n_dp, j in 1:n_du kup[j, i] += gradNu[j][c[j]] * (-JxW * Np[i]) end end ``` Assemble the matrices. The submatrix off the diagonal is assembled twice, once as itself, and once as its transpose. ```julia assemble!(ass, kuu) assemble!(ass, kup) # top right corner assemble!(ass, transpose(kup)) # bottom left corner end return ass # return the updated assembler of the global matrix end ``` In the `assembleK` function we first we create the element iterators. We can go through all the elements, both in the velocity finite element space and in the pressure finite element space, that define the domain of integration using this iterator. Each time a new element is accessed, some data are precomputed such as the element degrees of freedom, components of the degree of freedom, etc. Note that we need to iterate two finite element spaces, hence we create a tuple of iterators. ```julia elits = (FEIterator(Uh), FEIterator(Ph)) ``` These are the quadrature point iterators. We know that the elements are triangular. We choose the three-point rule, to capture the quadratic component in the velocity space. Quadrature-point iterators provide access to basis function values and gradients, the Jacobian matrix and the Jacobian determinant, the location of the quadrature point and so on. Note that we need to iterate the quadrature rules of two finite element spaces, hence we create a tuple of iterators. ```julia qargs = (kind = :default, npts = 3,) qpits = (QPIterator(Uh, qargs), QPIterator(Ph, qargs)) ``` The matrix will be assembled into this assembler. Which is initialized with the total number of degrees of freedom (dimension of the coefficient matrix before partitioning into unknowns and data degrees of freedom). ```julia ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) ``` The integration is carried out, and then... ```julia integrate!(ass, elits, qpits, D) ``` ...we materialize the sparse stiffness matrix and return it. ```julia return finish!(ass) end ``` The linear algebraic system is solved by partitioning. The vector `U` is initially all zero, except in the degrees of freedom which are prescribed as nonzero. Therefore the product of the stiffness matrix and the vector `U` are the loads due to nonzero essential boundary conditions. The submatrix of the stiffness conduction matrix corresponding to the free degrees of freedom (unknowns), `K[1:nu, 1:nu]` is then used to solve for the unknowns `U [1:nu]`. ```julia function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end ``` The function `evaluate_pressure_error` evaluates the true ``L^2`` error of the pressure. It does that by integrating the square of the difference between the approximate pressure and the true pressure, the true pressure being provided by the `truep` function. ```julia function evaluate_pressure_error(Ph, truep) function integrate!(elit, qpit, truep) n_dp = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:n_dp pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end ``` The function `evaluate_velocity_error` evaluates the true ``L^2`` error of the velocity. It does that by integrating the square of the difference between the approximate pressure and the true velocity, the true velocity being provided by the `trueux`, `trueuy` functions. ```julia function evaluate_velocity_error(Uh, trueux, trueuy) function integrate!(elit, qpit, trueux, trueuy) n_du = ndofsperel(elit) uedofcomp = edofcompnt(Uh) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:n_du (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(Uh) qargs = (kind = :default, npts = 3,) qpit = QPIterator(Uh, qargs) return integrate!(elit, qpit, trueux, trueuy) end end ``` To run the example, evaluate this file which will compile the module `.tut_stokes_p1b_p1_gen`. ```julia using .tut_stokes_p1b_p1_gen tut_stokes_p1b_p1_gen.run() ``` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
16862
# Solve the Stokes equation of colliding flow: Q1-Q0 element, general formulation Synopsis: Compute the solution of the Stokes equation of two-dimensional incompressible viscous flow for a manufactured problem of colliding flow. Continuous velocity/discontinuous pressure quadrilateral elements are used. The "manufactured" colliding flow example from Elman et al 2014. The Continuous velocity/discontinuous pressure formulation with linear quadrilaterals. These elements suffer from pressure oscillation instability. The results of this simulation demonstrate it. The analytical results are shown here: pressure is shown with contours, and the velocities visualized with arrows at random points. ![Pressure and velocity](colliding.png) The formulation is the general elasticity-like scheme with strain-rate/velocity matrices. It can be manipulated into the one derived in Reddy, Introduction to the finite element method, 1993. Page 486 ff. The complete code is in the file [`tut_stokes_q1_q0_gen.jl`](tut_stokes_q1_q0_gen.jl). The solution will be defined within a module in order to eliminate conflicts with data or functions defined elsewhere. ```julia module tut_stokes_q1_q0_gen ``` We'll need some functionality from linear algebra, static arrays, and the mesh libraries. Some plotting will be produced to visualize structure of the stiffness matrix. Finally we will need the `Elfel` functionality. ```julia using LinearAlgebra using StaticArrays using MeshCore.Exports using MeshSteward.Exports using Elfel.Exports using UnicodePlots ``` The boundary value problem is expressed in this weak form ```math \int_{V}{\underline{\varepsilon}}(\underline{\delta v})^T\; \underline{\underline{D}}\; {\underline{\varepsilon}}(\underline{u})\; \mathrm{d} V - \int_{V} \mathrm{div}(\underline{\delta v})\; p\; \mathrm{d} V = 0,\quad \forall \underline{\delta v} ``` ```math - \int_{V} \delta q\; \mathrm{div}(\underline{u}) \; \mathrm{d} V = 0,\quad \forall \delta q ``` Here ``\underline{\delta v}`` are the test functions in the velocity space, and ``\delta q`` are the pressure test functions. Further ``\underline {u}`` is the trial velocity, and ``p`` is the trial pressure. ```julia function run() mu = 1.0 # dynamic viscosity ``` This is the material-property matrix ``\underline{\underline{D}}``: ```julia D = SMatrix{3, 3}( [2*mu 0 0 0 2*mu 0 0 0 mu]) A = 1.0 # half of the length of the side of the square N = 100 # number of element edges per side of the square ``` These three functions define the true velocity components and the true pressure. ```julia trueux = (x, y) -> 20 * x * y ^ 3 trueuy = (x, y) -> 5 * x ^ 4 - 5 * y ^ 4 truep = (x, y) -> 60 * x ^ 2 * y - 20 * y ^ 3 ``` Construct the two meshes for the mixed method. They need to support the velocity and pressure spaces. ```julia mesh = genmesh(A, N) ``` Construct the velocity space: it is a vector space with two components. The degrees of freedom are real numbers (`Float64`). The velocity mesh carries the finite elements of the continuity ``H ^1``, i. e. both the function values and the derivatives are square integrable. Each node carries 2 degrees of freedom, hence there are two velocity components per node. ```julia Uh = FESpace(Float64, mesh, FEH1_Q4(), 2) ``` Now we apply the boundary conditions at the nodes around the circumference. ```julia locs = geometry(mesh) ``` We use searching based on the presence of the node within a box. The entire boundary will be captured within these four boxes, provided we inflate those boxes with a little tolerance (we can't rely on those nodes to be precisely at the coordinates given, we need to introduce some tolerance). ```julia boxes = [[-A A -A -A], [-A -A -A A], [A A -A A], [-A A A A]] inflate = A / N / 100 for box in boxes vl = vselect(locs; box = box, inflate = inflate) for i in vl ``` Remember that all components of the velocity are known at the boundary. ```julia setebc!(Uh, 0, i, 1, trueux(locs[i]...)) setebc!(Uh, 0, i, 2, trueuy(locs[i]...)) end end ``` No we construct the pressure space. It is a discontinuous, piecewise constant space supported on a mesh of 4-node quadrilaterals (``L ^2``-continuity elements). Each quadrilateral carries a single degree of freedom. ```julia Ph = FESpace(Float64, mesh, FEL2_Q4(), 1) ``` The pressure in this "enclosed" flow example is only known up to a constant. By setting pressure degree of freedom at one degree of freedom to zero will make the solution unique. ```julia atcenter = vselect(geometry(mesh); nearestto = [0.0, 0.0]) setebc!(Ph, 2, atcenter[1], 1, 0.0) ``` Number the degrees of freedom. First all the free degrees of freedom are numbered, both velocities and pressures. Next all the data degrees of freedom are numbered, again both for the velocities and for the pressures. ```julia numberdofs!([Uh, Ph]) ``` The total number of degrees of freedom is now calculated. ```julia tndof = ndofs(Uh) + ndofs(Ph) ``` As is the total number of unknowns. ```julia tnunk = nunknowns(Uh) + nunknowns(Ph) ``` Assemble the coefficient matrix. ```julia K = assembleK(Uh, Ph, tndof, D) ``` Display the structure of the indefinite stiffness matrix. Note that this is the complete matrix, including rows and columns for all the degrees of freedom, unknown and known. ```julia p = spy(K, canvas = DotCanvas) display(p) ``` Solve the linear algebraic system. First construct system vector of all the degrees of freedom, in the first `tnunk` rows that corresponds to the unknowns, and the subsequent rows are for the data degrees of freedom. ```julia U = fill(0.0, tndof) gathersysvec!(U, [Uh, Ph]) ``` Note that the vector `U` consists of nonzero numbers in rows are for the data degrees of freedom. Multiplying the stiffness matrix with this vector will generate a load vector on the right-hand side. Otherwise there is no loading, hence the vector `F` consists of all zeros. ```julia F = fill(0.0, tndof) solve!(U, K, F, tnunk) ``` Once we have solved the system of linear equations, we can distribute the solution from the vector `U` into the finite element spaces. ```julia scattersysvec!([Uh, Ph], U) ``` Given that the solution is manufactured, i. e. exactly known, we can calculate the true errors. ```julia @show ep = evaluate_pressure_error(Ph, truep) @show ev = evaluate_velocity_error(Uh, trueux, trueuy) ``` Postprocessing. First we make attributes, scalar nodal attributes, associated with the meshes for the pressures and the velocity. ```julia makeattribute(Ph, "p", 1) makeattribute(Uh, "ux", 1) makeattribute(Uh, "uy", 2) ``` The pressure and the velocity components are then written out into two VTK files. The pressure is of the "cell-data" type, the velocity is of the "point-data" type. ```julia vtkwrite("tut_stokes_q1_q0_gen-p", baseincrel(mesh), [(name = "p",), ]) vtkwrite("tut_stokes_q1_q0_gen-v", baseincrel(mesh), [(name = "ux",), (name = "uy",)]) return true end function genmesh(A, N) ``` Linear quadrilateral mesh is used for both the velocity space and the pressure space. ```julia mesh = attach!(Mesh(), Q4block(2 * A, 2 * A, N, N), "velocity") ``` Now translate so that the center of the square is at the origin of the coordinates. ```julia ir = baseincrel(mesh) transform(ir, x -> x .- A) ``` The pressure degree of freedom is associated with the element itself. The mesh will therefore need be equipped with the incidence relation `` (2, 2)``. The finite element space for the velocity will have degrees of freedom associated with the vertices. The finite element space for the pressure will have degrees of freedom associated with the faces (elements themselves). The finite element space does that by associating the pressure field with the ``(2, 2)`` incidence relation. ```julia eidir = ir_identity(ir) attach!(mesh, eidir) return mesh end function assembleK(Uh, Ph, tndof, D) function integrate!(ass, elits, qpits, D) ``` Consider the elementwise definition of the test strain rate, `` {\underline{\varepsilon}}(\underline{\delta v})``. It is calculated from the elementwise degrees of freedom and the associated basis functions as ```math {\underline{\varepsilon}}(\underline{\delta v}) = \sum_i{\delta V}_i {\underline{B}_{c(i)}(N_i)} ``` where ``i = 1, \ldots, n_{du}``, and ``n_{du}`` is the number of velocity degrees of freedom per element, ``c(i)`` is the number of the component corresponding to the degree of freedom ``i``. This is either 1 when degree of freedom ``i`` is the ``x``-component of the velocity, 2 otherwise(for the ``y``-component of the velocity). Analogously for the trial strain rate. The strain-rate/velocity matrices are defined as ```math {\underline{B}_{1}(N_i)} = \left[\begin{array}{c} \partial{N_i}/\partial{x} \\ 0 \\ \partial{N_i}/\partial{y} \end{array}\right], ``` and ```math {\underline{B}_{2}(N_i)} = \left[\begin{array}{c} 0 \\ \partial{N_i}/\partial{y} \\ \partial{N_i}/\partial{x} \end{array}\right]. ``` This tiny function evaluates the strain-rate/velocity matrices defined above from the gradient of a basis function and the given number of the component corresponding to the current degree of freedom. ```julia B = (g, k) -> (k == 1 ? SVector{3}((g[1], 0, g[2])) : SVector{3}((0, g[2], g[1]))) ``` This array defines the components for the element degrees of freedom, as defined above as ``c(i)``. ```julia c = edofcompnt(Uh) ``` These are the totals of the velocity and pressure degrees of freedom per element. ```julia n_du, n_dp = ndofsperel.((Uh, Ph)) ``` The local matrix assemblers are used as if they were ordinary elementwise dense matrices. Here they are defined. ```julia kuu = LocalMatrixAssembler(n_du, n_du, 0.0) kup = LocalMatrixAssembler(n_du, n_dp, 0.0) for el in zip(elits...) uel, pel = el ``` The local matrix assemblers are initialized with zeros for the values, and with the element degree of freedom vectors to be used in the assembly. The assembler `kuu` is used for the velocity degrees of freedom, and the assembler `kup` collect the coupling coefficients between the velocity and the pressure. The function `eldofs` collects the global numbers of the degrees of freedom either for the velocity space, or for the pressure space (`eldofs(pel)`). ```julia init!(kuu, eldofs(uel), eldofs(uel)) init!(kup, eldofs(uel), eldofs(pel)) for qp in zip(qpits...) uqp, pqp = qp ``` The integration is performed using the velocity quadrature points. ```julia Jac, J = jacjac(uel, uqp) JxW = J * weight(uqp) gradNu = bfungrad(uqp, Jac) # gradients of the velocity basis functions Np = bfun(pqp) # pressure basis functions ``` This double loop corresponds precisely to the integrals of the weak form. This is the matrix in the upper left corner. ```julia for i in 1:n_du DBi = D * B(gradNu[i], c[i]) for j in 1:n_du Bj = B(gradNu[j], c[j]) kuu[j, i] += dot(Bj, DBi) * (JxW) end end ``` And this is the coupling matrix in the top right corner. ```julia for i in 1:n_dp, j in 1:n_du kup[j, i] += gradNu[j][c[j]] * (-JxW * Np[i]) end end ``` Assemble the matrices. The submatrix off the diagonal is assembled twice, once as itself, and once as its transpose. ```julia assemble!(ass, kuu) assemble!(ass, kup) # top right corner assemble!(ass, transpose(kup)) # bottom left corner end return ass # return the updated assembler of the global matrix end ``` In the `assembleK` function we first we create the element iterators. We can go through all the elements, both in the velocity finite element space and in the pressure finite element space, that define the domain of integration using this iterator. Each time a new element is accessed, some data are precomputed such as the element degrees of freedom, components of the degree of freedom, etc. Note that we need to iterate two finite element spaces, hence we create a tuple of iterators. ```julia elits = (FEIterator(Uh), FEIterator(Ph)) ``` These are the quadrature point iterators. We know that the elements are triangular. We choose the three-point rule, to capture the quadratic component in the velocity space. Quadrature-point iterators provide access to basis function values and gradients, the Jacobian matrix and the Jacobian determinant, the location of the quadrature point and so on. Note that we need to iterate the quadrature rules of two finite element spaces, hence we create a tuple of iterators. ```julia qargs = (kind = :Gauss, order = 2) qpits = (QPIterator(Uh, qargs), QPIterator(Ph, qargs)) ``` The matrix will be assembled into this assembler. Which is initialized with the total number of degrees of freedom (dimension of the coefficient matrix before partitioning into unknowns and data degrees of freedom). ```julia ass = SysmatAssemblerSparse(0.0) start!(ass, tndof, tndof) ``` The integration is carried out, and then... ```julia integrate!(ass, elits, qpits, D) ``` ...we materialize the sparse stiffness matrix and return it. ```julia return finish!(ass) end ``` The linear algebraic system is solved by partitioning. The vector `U` is initially all zero, except in the degrees of freedom which are prescribed as nonzero. Therefore the product of the stiffness matrix and the vector `U` are the loads due to nonzero essential boundary conditions. The submatrix of the stiffness conduction matrix corresponding to the free degrees of freedom (unknowns), `K[1:nu, 1:nu]` is then used to solve for the unknowns `U [1:nu]`. ```julia function solve!(U, K, F, nu) KT = K * U U[1:nu] = K[1:nu, 1:nu] \ (F[1:nu] - KT[1:nu]) end ``` The function `evaluate_pressure_error` evaluates the true ``L^2`` error of the pressure. It does that by integrating the square of the difference between the approximate pressure and the true pressure, the true pressure being provided by the `truep` function. ```julia function evaluate_pressure_error(Ph, truep) function integrate!(elit, qpit, truep) n_dp = ndofsperel(elit) E = 0.0 for el in elit dofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Np = bfun(qp) pt = truep(location(el, qp)...) pa = 0.0 for j in 1:n_dp pa += (dofvals[j] * Np[j]) end E += (JxW) * (pa - pt)^2 end end return sqrt(E) end elit = FEIterator(Ph) qargs = (kind = :Gauss, order = 2) qpit = QPIterator(Ph, qargs) return integrate!(elit, qpit, truep) end ``` The function `evaluate_velocity_error` evaluates the true ``L^2`` error of the velocity. It does that by integrating the square of the difference between the approximate pressure and the true velocity, the true velocity being provided by the `trueux`, `trueuy` functions. ```julia function evaluate_velocity_error(Uh, trueux, trueuy) function integrate!(elit, qpit, trueux, trueuy) n_du = ndofsperel(elit) uedofcomp = edofcompnt(Uh) E = 0.0 for el in elit udofvals = eldofvals(el) for qp in qpit Jac, J = jacjac(el, qp) JxW = J * weight(qp) Nu = bfun(qp) uxt = trueux(location(el, qp)...) uyt = trueuy(location(el, qp)...) uxa = 0.0 uya = 0.0 for j in 1:n_du (uedofcomp[j] == 1) && (uxa += (udofvals[j] * Nu[j])) (uedofcomp[j] == 2) && (uya += (udofvals[j] * Nu[j])) end E += (JxW) * ((uxa - uxt)^2 + (uya - uyt)^2) end end return sqrt(E) end elit = FEIterator(Uh) qargs = (kind = :Gauss, order = 2) qpit = QPIterator(Uh, qargs) return integrate!(elit, qpit, trueux, trueuy) end end ``` To run the example, evaluate this file which will compile the module `.tut_stokes_q1_q0_gen`. ```julia using .tut_stokes_q1_q0_gen tut_stokes_q1_q0_gen.run() ``` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.4.0
d8ab448f2d6c411159c36cc2283853f006ca180c
docs
848
[Table of contents](https://petrkryslucsd.github.io/Elfel.jl/latest/index.html) # Tutorials - [Heat conduction](tut_poisson_q4.md): Poisson equation. Manufactured solution. - [Colliding flow](tut_stokes_ht_p2_p1_gen.md): Stokes equation. General formulation. Hood-Taylor mixed velocity-pressure triangles. - [Colliding flow](tut_stokes_ht_p2_p1_veclap.md): Vector Laplacian formulation. Hood-Taylor mixed velocity-pressure triangles. - [Colliding flow](tut_stokes_ht_p2_p1_reddy.md): Scalar formulation. Hood-Taylor mixed velocity-pressure triangles. - [Colliding flow](tut_stokes_p1b_p1_gen.md): Stokes equation. General formulation. Mixed velocity-pressure linear triangles with cubic bubbles. - [Colliding flow](tut_stokes_q1_q0_gen.md): Stokes equation. General formulation. Mixed continuous velocity-constant pressure with quadrilaterals.
Elfel
https://github.com/PetrKryslUCSD/Elfel.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
834
using BijectiveHilbert using Documenter makedocs(; modules=[BijectiveHilbert], authors="Andrew Dolgert <[email protected]>", repo="https://github.com/adolgert/BijectiveHilbert.jl/blob/{commit}{path}#L{line}", sitename="BijectiveHilbert.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://adolgert.github.io/BijectiveHilbert.jl", assets=String[], ), pages=[ "Home" => "index.md", "Usage" => "usage.md", "Algorithms" => [ "hilbert.md", "simple2d.md", "globalgray.md", "compact.md", "facecontinuous.md" ] ], ) deploydocs(; devbranch = "main", repo="github.com/adolgert/BijectiveHilbert.jl", deploy_config=Documenter.GitHubActions() )
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
1449
module BijectiveHilbert include("bitops.jl") include("gray_code.jl") include("hilbert_algorithm.jl") export index_type export encode_hilbert export decode_hilbert! include("global_gray.jl") export GlobalGray export axis_type export encode_hilbert_zero export decode_hilbert_zero! include("hamilton.jl") export SpaceGray export Compact # include("bijective.jl") include("simple2d.jl") import .Bijective: Simple2D @doc """ Simple2D(::Type{T}) The type is a data type to hold the Hilbert index. It should have enough bits to hold all bits of integer axes to encode. The variant algorithm used differs from the usual Hilbert code because it doesn't need to know the size of the whole grid before computing the code. It looks like a slightly-rotated version of the Hilbert curve, but it has the benefit that it is 1-1 between `(x, y)` and `z`, so you can translate back and forth. If the size of the axis values or the size of the Hilbert index are too large to be stored in the data types of the axis vector or index, then you'll see an error from a failure of `trunc`, which tries to copy values into the smaller datatype. Solve this by using a larger datatype, so UInt64 instead of UInt32. It comes from a paper: N. Chen, N. Wang, B. Shi, A new algorithm for encoding and decoding the Hilbert order. Software—Practice and Experience 2007; 37(8): 897–908. """ Simple2D export Simple2D include("facecontinuous.jl") export FaceContinuous end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
3331
module BijectivePaper # Columns are odd resolution, even resolution (rmin) # Columns are quadrants in x and y like you'd graph it. # 1 2 # 0 3 hilbert_variant_encode_table = Function[ ((x, y, w) -> (x, y)) ((x, y, w) -> (x, y)) ((x, y, w) -> (y-w, x)) ((x, y, w) -> (y, x-w)) ((x, y, w) -> (y-w, x-w)) ((x, y, w) -> (y-w, x-w)) ((x, y, w) -> (2w-x-1, w-y-1)) ((x, y, w) -> (w-x-1, 2w-y-1)) ] function encode_hilbert_zero(x::Integer, y::Integer) z = zero(x) if x == 0 && y == 0 return z end rmin = convert(typeof(x), floor(log2(max(x, y))) + 1) w = 1<<(rmin - 1) while rmin > 0 if rmin&1 == 1 # odd quadrant = x < w ? (y < w ? 0 : 1) : (y < w ? 3 : 2) parity = 1 else # even quadrant = x < w ? (y < w ? 0 : 3) : (y < w ? 1 : 2) parity = 2 end z = (z<<2) + quadrant x, y = hilbert_variant_encode_table[quadrant+1, parity](x, y, w) rmin -= 1 w >>= 1 end z end hilbert_variant_decode_table = Function[ ((x, y, w) -> (x, y)) ((x, y, w) -> (x, y)) ((x, y, w) -> (y, x+w)) ((x, y, w) -> (y+w, x)) ((x, y, w) -> (y+w, x+w)) ((x, y, w) -> (y+w, x+w)) ((x, y, w) -> (2w-x-1, w-y-1)) ((x, y, w) -> (w-x-1, 2w-y-1)) ] function decode_hilbert_zero(z) r = z & 3 x, y = typeof(z).([(0, 0), (0, 1), (1, 1), (1, 0)][r + 1]) z >>= 2 rmin = 2 w = convert(typeof(z), 2) while z > 0 r = z & 3 parity = 2 - rmin&1 x, y = hilbert_variant_decode_table[r+1, parity](x, y, w) z >>= 2 rmin += 1 w <<= 1 end x, y end encode_hilbert(x::Integer, y::Integer) = encode_hilbert_zero(x - 1, y - 1) + 1 function decode_hilbert(z::Integer) x, y = decode_hilbert_zero(z - 1) x + 1, y + 1 end """ hilbert_order(v::AbstractArray, subdivisions) Calculates the permutation of `v` that would order a 2D array by Hilbert curve, where `v` is an array of real numbers, dimension (2, N) and subdivisions is a real number that specifies how many boxes to place the `v` into, per side. This tells you how to order an array of 2-dimensional numbers so that they have more memory locality in 1 dimension. Given an array of real numbers of dimension `(2, n)`, subdivide them in each dimension by `subdivisions`, and assign each point a Hilbert code. Return the permutation that would sort the given array by that Hilbert code. See also: [`encode_hilbert_zero`](@ref). # Example ```julia rng = MersenneTwister(984720987) points_in_space = zeros(2, 100) rand!(rng, points_in_space) points_reordered = points_in_space[:, hilbert_order(points_in_space, 50)] ``` """ function hilbert_order(v::AbstractArray, subdivisions) lowx = minimum(v[1, :]) lowy = minimum(v[2, :]) highx = maximum(v[1, :]) highy = maximum(v[2, :]) iv = zeros(Int64, size(v, 2)) for i in 1:size(v, 2) iv[i] = encode_hilbert_zero( round(Int64, (v[1, i] - lowx) * subdivisions / (highx - lowx)), round(Int64, (v[2, i] - lowy) * subdivisions / (highy - lowy)) ) end sortperm(iv) end export encode_hilbert_zero, decode_hilbert_zero export encode_hilbert, decode_hilbert, hilbert_order end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
9366
bshow(i) = bitstring(i)[end-7:end] function large_enough_unsigned(bit_cnt) unsigned_types = [UInt8, UInt16, UInt32, UInt64, UInt128] atype = nothing for xtype in unsigned_types if sizeof(xtype) * 8 >= bit_cnt atype = xtype break end end atype end """ is_power_of_two(v::Base.BitInteger) This integer is a power of two. """ function is_power_of_two(v::Base.BitInteger) v != 0 && ((v & (v - 1)) == 0) end """ log_base2(v::Integer) Count the number of bits in an integer, rounding down. """ function log_base2(v::Integer)::Integer r = zero(v) while (v = v >> one(v)) > 0 r += one(v) end r end """ count_set_bits(v::Integer) A naive algorithm to count bits that are set. Look here to improve: https://graphics.stanford.edu/~seander/bithacks.html. """ function count_set_bits(v::Integer) c = zero(v) while v != zero(v) c += v & one(v) v = v>>one(v) end c end """ msb(v::Integer) Most-significant bit, zero-based count. So `0b1` is 0, `0b1010` is 3. """ function msb(v::Integer) r = 0 while (v >>= 1) != 0 r += 1 end r end """ trailing_zero_bits(v::Integer) The number of zero bits after the last one-bit. """ function trailing_zero_bits(v::Integer) c = zero(v) if v != zero(v) # Set v's trailing 0s to 1s and zero rest v = (v ⊻ (v - one(v))) >> one(v) while v != zero(v) v = v >> 1 c += one(v) end else c = 8 * sizeof(v) end c end """ trailing_set_bits(v::Integer) The number of one-bits after the last zero-bit. """ trailing_set_bits(v) = trailing_zero_bits(~v) """ Treat `x` as an `n`-bit unsigned integer. Rotate the bits `k` places to the left, wrapping them around the right side. """ function rotateleft_naive(x::Base.BitInteger, k::Integer, n::Integer) y = zero(x) for i = 0:(n - 1) ind = (i - k) % n ind = (ind >= 0) ? ind : ind + n if (x & (one(x) << ind)) > 0 y |= (one(x) << i) end # else leave unset. end y end function rotateleft(x::T, k::Integer, n::Integer) where {T <: Base.BitInteger} @assert k >= 0 @assert n > 0 @assert k < n x &= fbvn1s(T, n) x = (x << k) | (x >> (n - k)) x &= fbvn1s(T, n) x end function rotateright_naive(x::Base.BitInteger, k::Integer, n::Integer) y = zero(x) for i = 0:(n - 1) ind = (i + k) % n ind = (ind >= 0) ? ind : ind + n if (x & (one(x) << ind)) > 0 y |= (one(x) << i) end # else leave unset. end y end function rotateright(x::T, k::Integer, n::Integer) where {T <: Base.BitInteger} x &= fbvn1s(T, n) x = (x >> k) | (x << (n - k)) x &= fbvn1s(T, n) x end """ 2^n - 1, computed for an unsigned integer. """ function fbvn1s(T::DataType, n) if n == T(sizeof(T) * 8) ~zero(T) else (one(T) << n) - one(T) end end """ 2^n - 1, computed for an unsigned integer. """ function fbvn1s(_::T, n) where {T} if n == T(sizeof(T) * 8) ~zero(T) else (one(T) << n) - one(T) end end function fbvmod(i, m) if i >= m i -= m * i / m else i end end function reverse_bits(w, n) r = zero(w) for i in 0:(n - 1) r |= ((w & (one(w)<<i)) >> i) << (n - 1 - i) end r end function set_bits(h, n, i, w) h |= w << (i * n) h end function set_bits_naive(h, n, i, w) for j in 0:(n - 1) b = (w & (1 << j)) >> j h |= (b << (n * i + j)) end h end """ Get b bits from v, starting at place i. """ function get_bits(v::T, b, i) where {T} n = 8 * sizeof(T) (v << (n - b - i)) >> (n - b) end function trailing_set_bits_hamilton(i::UInt64) T = UInt64 c = zero(Int) if i == ~zero(T) return T(8) * sizeof(T) end if (i & fbvn1s(T, 32)) == fbvn1s(T, 32) i >>= T(32) c ⊻= T(32) end if (i & fbvn1s(T, 16)) == fbvn1s(T, 16) i >>= T(16) c ⊻= T(16) end if (i & fbvn1s(T, 8)) == fbvn1s(T, 8) i >>= T(8) c ⊻= T(8) end if (i & fbvn1s(T, 4)) == fbvn1s(T, 4) i >>= T(4) c ⊻= T(4) end if (i & fbvn1s(T, 2)) == fbvn1s(T, 2) i >>= T(2) c ⊻= T(2) end if (i & fbvn1s(T, 1)) == fbvn1s(T, 1) i >>= T(1) c ⊻= T(1) end c end function trailing_set_bits_hamilton(i::UInt32) T = UInt32 c = zero(Int) if i == ~zero(T) return T(8) * sizeof(T) end if (i & fbvn1s(T, 16)) == fbvn1s(T, 16) i >>= T(16) c ⊻= T(16) end if (i & fbvn1s(T, 8)) == fbvn1s(T, 8) i >>= T(8) c ⊻= T(8) end if (i & fbvn1s(T, 4)) == fbvn1s(T, 4) i >>= T(4) c ⊻= T(4) end if (i & fbvn1s(T, 2)) == fbvn1s(T, 2) i >>= T(2) c ⊻= T(2) end if (i & fbvn1s(T, 1)) == fbvn1s(T, 1) i >>= T(1) c ⊻= T(1) end c end function trailing_set_bits_hamilton(i::UInt16) T = UInt16 c = zero(Int) if i == ~zero(T) return T(8) * sizeof(T) end if (i & fbvn1s(T, 8)) == fbvn1s(T, 8) i >>= T(8) c ⊻= T(8) end if (i & fbvn1s(T, 4)) == fbvn1s(T, 4) i >>= T(4) c ⊻= T(4) end if (i & fbvn1s(T, 2)) == fbvn1s(T, 2) i >>= T(2) c ⊻= T(2) end if (i & fbvn1s(T, 1)) == fbvn1s(T, 1) i >>= T(1) c ⊻= T(1) end c end function trailing_set_bits_hamilton(i::UInt8) T = UInt8 c = zero(Int) if i == ~zero(T) return T(8) * sizeof(T) end if (i & fbvn1s(T, 4)) == fbvn1s(T, 4) i >>= T(4) c ⊻= T(4) end if (i & fbvn1s(T, 2)) == fbvn1s(T, 2) i >>= T(2) c ⊻= T(2) end if (i & fbvn1s(T, 1)) == fbvn1s(T, 1) i >>= T(1) c ⊻= T(1) end c end function first_set_bit(i::T)::Int where {T <: Integer} if i == 0 return 0 end for j = 0:(8 * sizeof(T) - 1) if (i & (T(1) << j)) != 0 return j + 1 end end end function first_set_bit(i::UInt128)::Int T = UInt128 c = zero(Int) if i == zero(T) return c end if (i & fbvn1s(T, 64)) == zero(T) i >>= T(64) c ⊻= 64 end if (i & fbvn1s(T, 32)) == zero(T) i >>= T(32) c ⊻= 32 end if (i & fbvn1s(T, 16)) == zero(T) i >>= T(16) c ⊻= 16 end if (i & fbvn1s(T, 8)) == zero(T) i >>= T(8) c ⊻= 8 end if (i & fbvn1s(T, 4)) == zero(T) i >>= T(4) c ⊻= 4 end if (i & fbvn1s(T, 2)) == zero(T) i >>= T(2) c ⊻= 2 end if (i & fbvn1s(T, 1)) == zero(T) i >>= T(1) c ⊻= 1 end c + one(Int) end function first_set_bit(i::UInt64)::Int T = UInt64 c = zero(Int) if i == zero(T) return c end if (i & fbvn1s(T, 32)) == zero(T) i >>= T(32) c ⊻= 32 end if (i & fbvn1s(T, 16)) == zero(T) i >>= T(16) c ⊻= 16 end if (i & fbvn1s(T, 8)) == zero(T) i >>= T(8) c ⊻= 8 end if (i & fbvn1s(T, 4)) == zero(T) i >>= T(4) c ⊻= 4 end if (i & fbvn1s(T, 2)) == zero(T) i >>= T(2) c ⊻= 2 end if (i & fbvn1s(T, 1)) == zero(T) i >>= T(1) c ⊻= 1 end c + one(Int) end function first_set_bit(i::UInt32)::Int T = UInt32 c = zero(Int) if i == zero(T) return c end if (i & fbvn1s(T, 16)) == zero(T) i >>= T(16) c ⊻= 16 end if (i & fbvn1s(T, 8)) == zero(T) i >>= T(8) c ⊻= 8 end if (i & fbvn1s(T, 4)) == zero(T) i >>= T(4) c ⊻= 4 end if (i & fbvn1s(T, 2)) == zero(T) i >>= T(2) c ⊻= 2 end if (i & fbvn1s(T, 1)) == zero(T) i >>= T(1) c ⊻= 1 end c + one(Int) end function first_set_bit(i::UInt16)::Int T = UInt16 c = zero(Int) if i == zero(T) return c end if (i & fbvn1s(T, 8)) == zero(T) i >>= T(8) c ⊻= 8 end if (i & fbvn1s(T, 4)) == zero(T) i >>= T(4) c ⊻= 4 end if (i & fbvn1s(T, 2)) == zero(T) i >>= T(2) c ⊻= 2 end if (i & fbvn1s(T, 1)) == zero(T) i >>= T(1) c ⊻= 1 end c + one(Int) end function first_set_bit(i::UInt8)::Int T = UInt8 c = zero(Int) if i == zero(T) return c end if (i & fbvn1s(T, 4)) == zero(T) i >>= T(4) c ⊻= 4 end if (i & fbvn1s(T, 2)) == zero(T) i >>= T(2) c ⊻= 2 end if (i & fbvn1s(T, 1)) == zero(T) i >>= T(1) c ⊻= 1 end c + one(Int) end function getloc_case(p, n, i, l, case) if case == 1 if (n <= i + 1) && (p[i] & im != 0) l | (1 << i) else l end else l = getloc_case(p, n, i + case >> 1, l, case >> 1) getloc_case(p, n, i, l, case >> 1) end end function get_location(p::Vector{T}, n, i) where {T} im = one(T) << i # p, jo=0, jn=n, ir=0, im=1<<i, l is return l = 0 getloc_case(p, n, 0, l, 8 * sizeof(T)) end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
8633
""" FaceContinuous(b::Int, n::Int) FaceContinuous(::Type{T}, b::Int, n::Int) For `n` dimensions, use `b` bits of precision in this Hilbert curve. If you specify a type `T`, this will be used as the type of the Hilbert encoding. If not, the smallest unsigned integer that can hold `n*b` bits will be used for the Hilbert index data type. This is the Butz algorithm, as presented by Lawder. Haverkort2017 says it is face continuous. The code is in lawder.c. The original paper had an error, and Lawder put a correction on his website. http://www.dcs.bbk.ac.uk/~jkl/publications.html """ struct FaceContinuous{T} <: HilbertAlgorithm{T} b::Int n::Int end function FaceContinuous(b::Int, n::Int) T = large_enough_unsigned(b * n) FaceContinuous{T}(b, n) end FaceContinuous(::Type{T}, b::Int, n::Int) where {T} = FaceContinuous{T}(b, n) """ Used during testing to pick a type for the xyz coordinate. """ axis_type(gg::FaceContinuous) = large_enough_unsigned(gg.b) # Mark one-based variables with a trailing o. # Mark zero-based variables with a trailing z. # The C code takes place in vectors, without the packed Hilbert index. # ORDER -> b The number of bits. # DIM -> n The number of dimensions. # U_int -> A, the type for the Axis coordinate. # C translation rules: # * / -> ÷ # * ^ -> ⊻ # * % -> % This is the same choice. mod() is wrong for negative numbers. # Julia has different operator precedence among addition, subtraction, bit shifts, and and xor. # Lawder knew C operator precedence well, so there are few parentheses. Add them liberally. # https://en.cppreference.com/w/c/language/operator_precedence. Relevant ones: # (++, --), (* / %), (+ -), (<< >>), (< >), (== !=), (&), (^), (= += <<= &= ^= |=) # g_mask[x] can be replaced by (1 << DIM - 1 - x) g_mask(::Type{A}, n, iz) where {A} = one(A) << (n - iz - 1) function H_encode!(gg::FaceContinuous, pt::Vector{K}, h::Vector{K}) where {K} wordbits = 8 * sizeof(K) W = zero(K) P = zero(K) h .= zero(K) # Start from the high bit in each element and work to the low bit. mask = one(K) << (gg.b - 1) # lawder puts wordbits here. # The H-index needs b * n bits of storage. i points to the base of the current level. i = gg.b * gg.n - gg.n # A will hold bits from all pt elements, at the current level. A = zero(K) for j = 0:(gg.n - 1) if (pt[j + 1] & mask) != zero(K) A |= g_mask(K, gg.n, j) end end S = tS = A P |= (S & g_mask(K, gg.n, 0)) for j = 1:(gg.n - 1) gm = g_mask(K, gg.n, j) if ((S & gm) ⊻ ((P >> 1) & gm)) != 0 P |= gm end end # P is the answer, but it has to be packed into a vector. element = i ÷ wordbits if (i % wordbits) > (wordbits - gg.n) h[element + 1] |= (P << (i % wordbits)) h[element + 2] |= P >> (wordbits - (i % wordbits)) else h[element + 1] |= (P << (i - element * wordbits)) end J = gg.n j = 1 while j < gg.n if ((P >> j) & one(K)) == (P & one(K)) j += 1 continue else break end end if j != gg.n J -= j end xJ = J - 1 if P < K(3) T = zero(K) else if (P % K(2)) != zero(K) T = (P - one(K)) ⊻ ((P - one(K)) >> 1) else T = (P - K(2)) ⊻ ((P - K(2)) >> 1) end end tT = T i -= gg.n mask >>= 1 while i >= 0 # println("i=$i mask=$mask T=$T P=$P") # println("h[0]=$(h[1]) h[1]=$(h[2]) h[2]=$(h[3])") A = zero(K) for j = 0:(gg.n - 1) if pt[j + 1] & mask != zero(K) A |= g_mask(K, gg.n, j) end end W ⊻= tT tS = A ⊻ W if xJ % gg.n != 0 temp1 = tS << (xJ % gg.n) temp2 = tS >> (gg.n - (xJ % gg.n)) S = temp1 | temp2 S &= (one(K) << gg.n) - one(K) else S = tS end P = S & g_mask(K, gg.n, 0) for j = 1:(gg.n - 1) gn = g_mask(K, gg.n, j) if ((S & gn) ⊻ ((P >> 1) & gn)) != 0 P |= gn end end element = i ÷ wordbits if (i % wordbits) > (wordbits - gg.n) h[element + 1] |= (P << (i % wordbits)) h[element + 2] |= (P >> (wordbits - (i % wordbits))) else h[element + 1] |= P << (i - element * wordbits) end if i > 0 if P < K(3) T = 0 else if P % K(2) != zero(K) T = (P - one(K)) ⊻ ((P - one(K)) >> 1) else T = (P - K(2)) ⊻ ((P - K(2)) >> 1) end end if xJ % gg.n != 0 temp1 = T >> (xJ % gg.n) temp2 = T << (gg.n - (xJ % gg.n)) tT = temp1 | temp2 tT &= (one(K) << gg.n) - one(K) else tT = T end J = gg.n j = 1 while j < gg.n if ((P >> j) & one(K)) == (P & one(K)) j += 1 continue else break end end if j != gg.n J -= j end xJ += J - 1 end i -= gg.n mask >>= 1 end # println("h[0]=$(h[1]) h[1]=$(h[2]) h[2]=$(h[3])") end mutable struct FCLevel{K} mask::K i::Int n::Int end function FCLevel(fc, ::Type{K}) where {K} # XXX lawder uses wordbits instead of fc.b FCLevel{K}(one(K) << (fc.b - 1), fc.b * fc.n - fc.n, fc.n) end function downlevel!(l::FCLevel) l.mask >>= 1 l.i -= l.n end function index_at_level(H::Vector{K}, l::FCLevel{K}) where {K} wordbits = 8 * sizeof(K) element = l.i ÷ wordbits P = H[element + 1] if (l.i % wordbits) > (wordbits - l.n) temp1 = H[element + 2] # one-based P >>= l.i % wordbits temp1 <<= wordbits - (l.i % wordbits) P |= temp1 else P >>= (l.i % wordbits) end # /* the & masks out spurious highbit values */ if l.n < wordbits P &= (one(K) << l.n) - one(K) end P end function distribute_to_coords!(bits::K, axes::Vector{K}, l::FCLevel{K}) where K j = l.n - 1 while bits > 0 if bits & one(K) != 0 axes[j + 1] |= l.mask end bits >>= 1 j -= 1 end end function fc_parity_match(P, n) J = n j = 1 parity = P & one(P) while j < n if ((P >> j) & one(P)) != parity break end j += 1 end j end function fc_rotation(P, n) j = fc_parity_match(P, n) if j == n xJ = n - 1 else xJ = n - j - 1 end xJ end function fc_flip(P::K) where {K} if P < K(3) T = zero(K) else if P % 2 != 0 T = (P - one(K)) ⊻ ((P - one(K)) >> 1) else T = (P - K(2)) ⊻ ((P - K(2)) >> 1) end end T end function H_decode!(gg::FaceContinuous, H::Vector{K}, pt::Vector{K}) where {K} pt .= zero(K) l = FCLevel(gg, K) P = index_at_level(H, l) xJ = fc_rotation(P, gg.n) A = S = tS = brgc(P) tT = T = fc_flip(P) # XXX Lawder's code puts P here instead of A. distribute_to_coords!(A, pt, l) nmask = (one(K) << gg.n) - one(K) # mask of n bits. W = zero(K) downlevel!(l) while l.i >= 0 P = index_at_level(H, l) S = brgc(P) @assert S & ~nmask == 0 tS = rotateright(S, xJ % gg.n, gg.n) W ⊻= tT A = W ⊻ tS distribute_to_coords!(A, pt, l) if l.i > 0 T = fc_flip(P) @assert T & ~nmask == 0 tT = rotateright(T, xJ % gg.n, gg.n) xJ += fc_rotation(P, gg.n) end downlevel!(l) end end function encode_hilbert_zero(fc::FaceContinuous{T}, X::Vector{A})::T where {A,T} hvec = zeros(A, fc.n) H_encode!(fc::FaceContinuous, X, hvec) # Encoding packs H into a vector of A, using all bits in the A type. h = zero(T) for i in fc.n:-1:1 h <<= 8 * sizeof(A) h |= hvec[i] end h end function decode_hilbert_zero!(fc::FaceContinuous{T}, X::Vector{A}, h::T) where {A,T} # H is in a larger type T but algorithm expects it packed into a vector of A. hvec = zeros(A, fc.n) for i in 1:fc.n hvec[i] |= h & ~zero(A) h >>= 8 * sizeof(A) end H_decode!(fc::FaceContinuous, hvec, X) end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
4892
""" transpose_to_axes(coord, b, n) Convert from Hilbert index to a coordinatefor `b` bits in `n` dimensions. """ function transpose_to_axes!(X::Vector{T}, b, n) where {T <: Integer} N = T(2) << (b - 1) # Gray decode by H^(H/2) t = X[n] >> 1 for io = n:-1:2 X[io] ⊻= X[io - 1] end X[1] ⊻= t # Undo excess work Q = T(2) while Q != N P = Q - one(T) for jo = n:-1:1 if (X[jo] & Q) != zero(T) X[1] ⊻= P # invert else # exchange t = (X[1] ⊻ X[jo]) & P X[1] ⊻= t X[jo] ⊻= t end end Q <<= 1 end end function axes_to_transpose!(X::Vector{T}, b, n) where {T <: Integer} M = one(T) << (b - 1) # Inverse undo Q = M while Q > one(T) P = Q - one(T) for io = 1:n if (X[io] & Q) != zero(T) X[1] ⊻= P else t = (X[1] ⊻ X[io]) & P X[1] ⊻= t X[io] ⊻= t end end Q >>= 1 end # Gray encode for jo = 2:n X[jo] ⊻= X[jo - 1] end t2 = zero(T) Q = M while Q > one(T) if (X[n] & Q) != 0 t2 ⊻= (Q - one(T)) end Q >>= one(T) end for ko = 1:n X[ko] ⊻= t2 end end """ Takes a vector of length `n` and places the bits of all `n` integers into a single integer. The vector's 1st component is the most significant bit. """ function interleave_transpose(::Type{T}, X::Vector, b, n) where {T} h = zero(T) for i in 0:(b - 1) for d in 1:n ith_bit = (X[d] & (1<<i)) >> i h |= ith_bit << (i * n + n - d) end end h end """ Takes a single integer and places its values into components of a vector, bit-by-bit. """ function outerleave_transpose!(X::Vector{T}, h, b, n) where {T <: Integer} X .= zero(T) for i in 0:(b-1) for d in 1:n ith_bit = (h & (one(h) << (i * n + n - d))) >> (i * n + n - d) X[d] |= ith_bit << i end end end """ Takes a vector of length `n` and places the bits of all `n` integers into a single integer. The vector's 1st component is the least significant bit. """ function interleave_transpose_low(::Type{T}, X::Vector{T}, b, n) where {T} h = zero(T) for i in 0:(b - 1) for d in 1:n h |= ((X[d] & (one(T)<<i))) << (i*(n - 1) + d - 1) end end h end function outerleave_transpose_low!(X::Vector{T}, h, b, n) where {T <: Integer} X .= zero(T) for i in 0:(b-1) for d in 1:n X[d] |= (h & (one(T) << (i * n + d - 1))) >> (i * (n - 1) + d - 1) end end end """ GlobalGray(b, n) GlobalGray(T, b, n) `T` is a data type for the Hilbert index. It can be signed or unsigned, as long as it has at least `n * b` bits. `n` is the number of dimensions, and `b` is the bits per dimension, so each axis value should be between 0 and ``2^b - 1``, inclusive, for the zero-based interface. They should be between 1 and ``2^b``, inclusive, for the one-based interface. The GlobalGray algorithm is an n-dimensional Hilbert curve with a simplified implementation. It follows an article, "Programming the Hilbert Curve," by John Skilling, 707 (2004), http://dx.doi.org/10.1063/1.1751381. I call it "Global Gray" because the insight of the article is that a single, global Gray code can be applied to all np bits of a Hilbert length. """ struct GlobalGray{T} <: HilbertAlgorithm{T} b::Int n::Int end axis_type(gg::GlobalGray) = large_enough_unsigned(gg.b) function GlobalGray(b, n) ttype = large_enough_unsigned(b * n) GlobalGray{ttype}(b, n) end function GlobalGray(::Type{T}, b, n) where {T} GlobalGray{T}(b, n) end function encode_hilbert_zero!(g::GlobalGray{T}, X::Vector)::T where {T} axes_to_transpose!(X, g.b, g.n) interleave_transpose(T, X, g.b, g.n) end """ encode_hilbert_zero(ha::HilbertAlgorithm{T}, X::Vector{A}) Takes an n-dimensional vector `X` and returns a single integer of type `T` which orders `X` to improve spatial locality. The input `X` has multiple axes and the output is called a Hilbert index. This version is zero-based, so each axis counts from 0, and the smallest Hilbert index is 0. """ function encode_hilbert_zero(g::GlobalGray{T}, X::Vector)::T where {T} Y = copy(X) encode_hilbert_zero!(g, Y) end """ decode_hilbert_zero!(ha::HilbertAlgorithm{T}}, X::Vector{A}, h::T) Given a Hilbert index, `h`, computes an n-dimensional coordinate `X`. The type of the Hilbert index is large enought to contain the bits of all dimensions of the axis vector, `X`. """ function decode_hilbert_zero!(g::GlobalGray{T}, X::Vector, h::T) where {T} outerleave_transpose!(X, h, g.b, g.n) transpose_to_axes!(X, g.b, g.n) end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
2863
""" Binary-reflected Gray code. """ brgc(i) = i ⊻ (i >> 1) """ This is how the paper describes the inverse of the binary-reflected gray code. """ function brgc_inv(g::Integer) i = g m = log_base2(g) for j = 1:m i = i ⊻ (g >> j) end i end """ Inverse of the binary-reflected Gray code. This takes you from the Gray code to its index. """ function brgc_inv(i::UInt128) i ⊻= (i >> 1) i ⊻= (i >> 2) i ⊻= (i >> 4) i ⊻= (i >> 8) i ⊻= (i >> 16) i ⊻= (i >> 32) i ⊻= (i >> 64) end function brgc_inv(i::UInt64) i ⊻= (i >> 1) i ⊻= (i >> 2) i ⊻= (i >> 4) i ⊻= (i >> 8) i ⊻= (i >> 16) i ⊻= (i >> 32) end function brgc_inv(i::UInt32) i ⊻= (i >> 1) i ⊻= (i >> 2) i ⊻= (i >> 4) i ⊻= (i >> 8) i ⊻= (i >> 16) end function brgc_inv(i::UInt16) i ⊻= (i >> 1) i ⊻= (i >> 2) i ⊻= (i >> 4) i ⊻= (i >> 8) end function brgc_inv(i::UInt8) i ⊻= (i >> 1) i ⊻= (i >> 2) i ⊻= (i >> 4) end """ GrayCodeRank, Algorithm 3 from the paper mask μ pattern π """ function brgc_rank2(mask::T, w::T, n) where {T} r = zero(w) for j = (n-1):-1:0 if (mask >>j ) & one(w) != 0 r = (r<<1) | ((w>>j) & one(w)) end end r end """ Gray code rank from Hamilton's code. """ function brgc_rank(mask::T, w::T, n) where {T} r = zero(T) im = one(T) jm = one(T) for i = 0:(n-1) if mask & im != 0 if w & im != 0 r |= jm end jm <<= 1 end im <<= 1 end r end function bbv_modsplit(T, k) bits = 8 * sizeof(T) b = k r = b ÷ bits b -= r * bits r, b end """ grayCodeRankInv(mask, ptrn, r, n, b, t, w) Returns t, w. """ function brgc_rank_inv(mask::T, ptrn, r, n, b) where {T} g = zero(T) gi = zero(T) i = n - 1 ir, ims = bbv_modsplit(T, i) im = one(T) << ims j = b - 1 jr, jms = bbv_modsplit(T, j) jm = one(T) << jms gi0 = zero(T) gi1 = zero(T) g0 = zero(T) while i >= 0 if mask & im != 0 gi1 = gi0 gi0 = ((r & jm) > 0) ? one(T) : zero(T) g0 = gi0 ⊻ gi1 if gi0 != 0 gi |= im end if g0 != 0 g |= im end jm >>= 1 if jm == 0 jm = one(T) << (8 * sizeof(T) - 1) jr -= 1 end else g0 = ((ptrn & im) > 0) ? one(T) : zero(T) gi1 = gi0 gi0 = g0 ⊻ gi1 if gi0 != 0 gi |= im end if g0 != 0 g |= im end end im >>= 1 if im == 0 im = one(T) << (8 * sizeof(T) - 1) ir -= 1 end i -= 1 end g, gi end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
11769
# Compact Hilbert Indices by Chris Hamilton. Technical Report CS-2006-07. # 6059 University Ave., Halifax, Nova Scotia, B3H 1W5, Canada. # # In this document, the notation is: # ∧ = & for and # ∨ = | for or # ⊻ = for xor # ▷ = >> for shift right # ◁ = << for shift left # ⌈x⌉ = ceil(x) # ⌊x⌋ = floor(x) # hi_g(i) is the direction in which brgc changes. # It is also tells us the axis along which the exit of one # subcube meets the entrance of the next subcube. hi_g(i) = trailing_set_bits(i) # This is the definition of g, to compare against for testing. hi_g_orig(i) = floor(typeof(i), log2(brgc(i) ⊻ brgc(i + 1))) # e is the entry vertex of the ith sub-hypercube in a Gray code # ordering of sub-hypercubes. If e is 0b011, then this is z-y-x # within the subcube of 0 in the z, 1 in the y, 1 in the x. # e = gc(2⌊(i-1)/2⌋) = gc(2*floor((i-1)/2)). # domain is i=0 to i=2^n - 1. function hi_e(i::Integer) i == zero(i) && return zero(i) brgc((i - one(i)) & ~one(i)) end # This is verbatim from the article, for comparison. function hi_e_orig(i::Base.BitInteger) i == zero(i) && return zero(i) brgc(2 * floor(typeof(i), (i - 1) / 2)) end """ f is the exit vertex of the ith sub-hypercube in a Gray code ordering of the sub-hypercubes. Corllary 2.7 on pg. 12 says: hi_f(i, n) = hi_e(i) ⊻ hi_d(i, n) """ hi_f(i, n) = hi_e(one(i)<<n - one(i) - i) ⊻ (one(i)<<(n-1)) # hi_f(i, n) = hi_e(i) ⊻ hi_d(i, n) #hi_f(i, n) = hi_e(i) ⊻ (one(i)<<hi_d(i, n)) """ page 12. directions d(i) = 0 if i=0 = g(i-1) mod n if i=0 mod 2 = g(i) mod n if i=1 mod 2. Domain is 0 <= i <= 2^n - 1. """ function hi_d(i, n) i == zero(i) && return zero(i) ((i & 1) == 0) && return hi_g(i - one(i)) % n hi_g(i) % n end # bitrotate is a left shift, so negate d+1. # T_{(e,d)}(b), so read right-to-left. # The paper means to bit rotate over the n bits that are in use, # not all n bits. This is not the usual bitrotate! # This had a +1 in the paper. hi_T(b, d, e, n) = rotateright(b ⊻ e, d, n) # The author's code differs with his paper. It doesn't add one. # https://github.com/pdebuyl/libhilbert/blob/master/include/Hilbert/Algorithm.hpp hi_T_inv(b, d, e, n) = rotateleft(b, d, n) ⊻ e # Lemma 2.12, page 15. # Is it -2 or -1? # function hi_T_inv(b, d, e, n) # hi_T(b, n - d - one(b) - one(b), bitrotate(e, -(d + one(b)), n), n) # end """ ith_bit_of_indices(n, p, i) Given `n` indices in `p`, take the `i`-th bit of each one and place it so that the first vector's value is at the 0-th place, the second vector's value at the 1st place, and so-on. `i` is zero-indexed. """ function ith_bit_of_indices(n, p, i) l = zero(eltype(p)) for j = 0:(n - 1) b = (p[j + 1] & (one(eltype(p))<<i)) >>i l |= b << j end l end # hamilton version of getting the ith bit, zero-indexed i. function get_location(p::Vector{T}, i) where {T} l = zero(T) for j = eachindex(p) if (p[j] & (one(T) << i)) != 0 l |= (one(T) << (j - 1)) end end l end """ set_indices_bits(p, l, m, i) Given bits in `l`, set each index in the array `p` according to the bit in `l`. Set the i-th bit of each index in `p`. """ function set_indices_bits!(p, l, m, i) for j in 0:(m - 1) v = (l & (1<<j)) >>j p[j + 1] = p[j + 1] | (v<<i) end end """ Return `m` bits from the `i`-th set of `m` bits in the integer `h`. `i` is zero-based. """ function bitrange(h, n, i) v = zero(h) for j in 0:(n - 1) v = v | (h & (1<<(i*n + j))) end v end function update1(l, t, w, n, e, d) e = l ⊻ (one(l) << d) d += one(d) + first_set_bit(t) while d >= n d -= n end if (w & one(w)) == zero(w) if d == zero(d) e ⊻= one(e) << (n - 1) else e ⊻= one(e) << (d - 1) end end e, d end function update2(l, t, w, n, e, d) e = l e ⊻= (one(e) << d) d += one(d) + first_set_bit(t) while d >= n d -= n end e, d end """ Algorithm.hpp: _coordsToIndex """ function hilbert_index_paper!(::Type{T}, n, m, p, ds) where {T <: Integer} h = zero(T) # hilbert index e = zero(T) # entry point d = one(T) # direction nmask = fbvn1s(T, n) for i = (m - 1):-1:0 # i is an index. Can be any type. ds[i + 1] = d l = T(ith_bit_of_indices(n, p, i)) t = hi_T(l, d, e, n) w = t if i < m - 1 w ⊻= (one(w) << (n - 1)) end # Concatenate to the index h |= (w & nmask) << (i * n) e, d = update2(l, t, w, n, e, d) end brgc_inv(h) end """ hilbert_index(n, m, p) Hilbert index for an `n`-dimensional vector `p`, with each component of extent less than 2^m. Algorithm 1 of Hamilton and Rau-Chaplin. """ function hilbert_index_paper(::Type{T}, n, m, p) where {T <: Integer} ds = zeros(Int, m) hilbert_index_paper!(T, n, m, p, ds) end function hilbert_index_inv_paper!(::Type{T}, n, m, h, p) where {T <: Integer} e = zero(T) d = one(T) l = zero(T) p .= zero(eltype(p)) nmask = fbvn1s(T, n) for i = (m - 1):-1:0 w = (h >> (i * n)) & nmask t = brgc(w) l = hi_T_inv(t, d, e, n) set_indices_bits!(p, l, n, i) e, d = update1(l, t, w, n, e, d) end end # Make d an argument because it determines the initial direction and maybe # it isn't initialized correctly. Maybe d and e need different initial values. function hilbert_index(n, m, p, d = zero(eltype(p))) h = zero(eltype(p)) # hilbert index e = zero(eltype(p)) # entry point for i = (m - 1):-1:0 # i is an index. Can be any type. l = ith_bit_of_indices(n, p, i) # @show l l = hi_T(l, d, e, n) # n or m? w = brgc_inv(l) h = (h << n) | w e = e ⊻ rotateleft(hi_e(w), d + one(d), n) d = (d + hi_d(w, n) + one(d)) % n # n or m for hi_d? end h end function hilbert_index_inv(n, m, h) e = zero(h) # entry point d = zero(h) # direction p = zeros(typeof(h), m) for i = (m - 1):-1:0 # i is an index. Can be any type. w = bitrange(h, n, i) l = brgc(w) l = hi_T_inv(l, d, e, n) set_indices_bits!(p, l, m, i) e = e ⊻ rotateleft(hi_e(w), d + one(d), n) d = (d + hi_d(w, n) + one(d)) % n # n or m for hi_d? end p end """ Calculates a bit-mask for excluding Gray code values when the level is below the resolution of the dimension. Bits free at iteration `i`. Vector of resolutions, in powers of two, `m`. Dimensions `n` so that `length(m)==n`. `i` is the level down in the Hilbert curve. `d` is the direction, called `hi_d` above. Returns both the mask and the number of bits set in the mask. """ function extract_mask(m::Vector, n, d, i) T = UInt64 mask = zero(T) b = 0 jm = one(T) j = d while true if m[j + 1] > i mask |= jm b += 1 end jm <<= one(T) if jm == zero(T) jm = one(T) end j += 1 if j == n j = 0 end if j == d break end end mask, b end function extract_mask_paper(m::Vector, n, d, i) T = UInt64 mask = zero(T) b = 0 for j = (n-1):-1:0 mask <<= one(T) jn = (j + d) % n if m[jn + 1] > i mask |= one(T) b += 1 end end mask, b end """ From GrayCodeRank.hpp: compactIndex. """ function compact_index(ms::Vector, ds::Vector, n, m, h::T) where {T} hc = zero(T) hr = 0 hcr = 0 hm = one(T) hcm = one(T) for i = 0:(m-1) j = ds[i + 1] while true if ms[j + 1] > i if hr > 0 error("hr on next rack") end if ((h & hm) != 0) if hcr == 0 hc |= hcm else error("should only be one rack") end end hcm <<= 1 if hcm == 0 hcm = one(T) hcr += 1 end end j += 1 if j == n j = 0 end hm <<= 1 if hm == zero(T) hm = one(T) hr += 1 end if j == ds[i + 1] break end end end hc end function coords_to_compact_index(::Type{T}, p::Vector{A}, ms::Vector, n) where {A,T} m = maximum(ms) M = sum(ms) mn = m * n ds = zeros(Int, m) h = hilbert_index_paper!(T, n, m, p, ds) compact_index(ms, ds, n, m, h) end function compact_index_to_coords!(p::Vector{A}, ms, n, hc::T) where {A, T} m = maximum(ms) M = sum(ms) bit_cnt = 8 * sizeof(T) e = zero(T) d = one(T) l = zero(T) p .= zero(A) # work from most significant bit to least significant bit for i = (m - 1):-1:0 mask, b = extract_mask(ms, n, d, i) # rotateright(val, shift_cnt, total_bits) ptrn = rotateright(e, d, n) # Get the Hilbert index bits. M -= b # b bits from hc at index M, into r r = get_bits(hc, b, M) t, w = brgc_rank_inv(mask, ptrn, r, n, b) l = hi_T_inv(t, d, e, n) set_indices_bits!(p, l, n, i) e, d = update1(l, t, w, n, e, d) end end """ SpaceGray(b, n) SpaceGray(::Type{T}, b, n) This is an n-dimensional Hilbert curve where all `n` dimensions must have `b` bits in size. It was described in the same paper and examples as the `Compact` algorithm. """ struct SpaceGray{T} <: HilbertAlgorithm{T} b::Int n::Int end axis_type(gg::SpaceGray) = large_enough_unsigned(gg.b) function SpaceGray(b, n) ttype = large_enough_unsigned(b * n) SpaceGray{ttype}(b, n) end function SpaceGray(::Type{T}, b, n) where {T} SpaceGray{T}(b, n) end function encode_hilbert_zero(g::SpaceGray{T}, X::Vector)::T where {T} hilbert_index_paper(T, g.n, g.b, X) end function decode_hilbert_zero!(g::SpaceGray{T}, X::Vector, h::T) where {T} hilbert_index_inv_paper!(T, g.n, g.b, h, X) end """ Compact(ms::Vector{Int}) Compact(::Type{T}, ms::Vector{Int}) This algorithm is n-dimensional and permits dimensions to use different numbers of bits, specified in the `ms` vector. The type `T` is an optional data type for the Hilbert index. It should be greater than or equal to the sum of the bits. This algorithm comes from three sources: * A technical report, "Compact Hilbert Indices" by Chris Hamilton. Technical Report CS-2006-07. 6059 University Ave., Halifax, Nova Scotia, B3H 1W5, Canada. This report is informative but has many errors. * A paper by Hamilton and Rau-Chaplin, "Compact Hilbert Indices for Multi-Dimensional Data," 2007. Nice paper. Also wrong. * The [libhilbert source code](https://github.com/pdebuyl/libhilbert) is a copy of Hamilton's work and has many corrections. This, ultimately, lead to the working code. """ struct Compact{T} <: HilbertAlgorithm{T} ms::Vector{Int} n::Int end axis_type(gg::Compact) = large_enough_unsigned(maximum(gg.ms)) function Compact(ms::Vector{Int}) n = length(ms) b = maximum(ms) ttype = large_enough_unsigned(b * n) Compact{ttype}(ms, n) end function Compact(::Type{T}, ms::Vector{Int}) where {T} Compact{T}(ms, length(ms)) end function encode_hilbert_zero(g::Compact{T}, X::Vector)::T where {T} coords_to_compact_index(index_type(g), X, g.ms, g.n) end function decode_hilbert_zero!(g::Compact{T}, X::Vector, h::T) where {T} compact_index_to_coords!(X, g.ms, g.n, h) end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
736
abstract type HilbertAlgorithm{T} end index_type(::HilbertAlgorithm{T}) where {T} = T """ encode_hilbert(ha::HilbertAlgorithm{T}, X::Vector{A}) A 1-based Hilbert encoding. Both the Hilbert index and the axes start counting at 1 instead of 0. """ function encode_hilbert(gg::HilbertAlgorithm{T}, X::Vector{A}) where {A, T} encode_hilbert_zero(gg, X .- one(A)) + one(T) end """ decode_hilbert!(ha::HilbertAlgorithm{T}, X::Vector{A}) A 1-based Hilbert decode, from [`decode_hilbert_zero!`](@ref). Both the Hilbert index and the axes start counting at 1 instead of 0. """ function decode_hilbert!(gg::HilbertAlgorithm{T}, X::Vector{A}, h::T) where {A,T} decode_hilbert_zero!(gg, X, h - one(T)) X .+= one(A) end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
2628
module Bijective import ..BijectiveHilbert: encode_hilbert_zero, decode_hilbert_zero!, HilbertAlgorithm, axis_type struct Simple2D{T} <: HilbertAlgorithm{T} end Simple2D(::Type{T}) where {T} = Simple2D{T}() axis_type(::Simple2D{T}) where {T} = Int function encode_hilbert_zero(::Simple2D{T}, X::Vector{A})::T where {A, T} x = X[1] y = X[2] z = zero(T) if x == zero(A) && y == zero(A) return z end rmin = convert(Int, floor(log2(max(x, y))) + 1) w = one(A) << (rmin - 1) while rmin > 0 z <<= 2 if rmin&1 == 1 # odd if x < w if y >= w # 1 x, y = (y - w, x) z += one(T) end # else x, y remain the same. else if y < w x, y = ((w<<1) - x - one(w), w - y - one(w)) # 3 z += T(3) else x, y = (y - w, x - w) z += T(2) # 2 end end else # even if x < w if y >= w # Quadrant 3 x, y = (w - x - one(w), (w << 1) - y - one(w)) z += T(3) end # else do nothing for quadrant 0. else if y < w # 1 x, y = (y, x-w) z += one(T) else # 2 x, y = (y-w, x-w) z += T(2) end end end rmin -= 1 w >>= 1 end z end function decode_hilbert_zero!(::Simple2D{T}, X::Vector{A}, z::T) where {A,T} r = z & T(3) x, y = [(zero(A), zero(A)), (zero(A), one(A)), (one(A), one(A)), (one(A), zero(A))][r + 1] z >>= 2 rmin = 2 w = one(A) << 1 while z > zero(T) r = z & T(3) parity = 2 - rmin&1 if rmin & 1 != 0 # Nothing to do for quadrant 0. if r == 1 x, y = (y, x + w) elseif r == 2 x, y = (y + w, x + w) elseif r == 3 x, y = ((w << 1) - x - one(A), w - y - one(A)) end else if r == 1 x, y = (y + w, x) elseif r == 2 x, y = (y + w, x + w) elseif r == 3 x, y = (w - x - one(A), (w << 1) - y - one(A)) end end z >>= 2 rmin += 1 w <<= 1 end X[1] = x X[2] = y end end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
989
using CSV function filename_to_hilbert_dims(fn) digits = parse.(Int, split(splitext(basename(fn))[1], "_")) popfirst!(digits), digits end function hamilton_example(fn) n, ms = filename_to_hilbert_dims(fn) cnt = prod(1 << x for x in ms) h = zeros(UInt32, cnt) X = zeros(UInt8, n, cnt) for (i, row) in enumerate(CSV.File(fn)) h[i] = convert(UInt32, row[1]) for j in 1:length(ms) X[j, i] = convert(UInt8, row[1 + j]) end end hsort = sortperm(h) h[hsort], X[:, hsort], ms end function steps_are_one_away(h, X) n = size(X, 1) Y = copy(X) Y .= zero(UInt8) for i in eachindex(h) tdiff = 0 for j in 1:n if X[j, i] > Y[j, i] tdiff += X[j, i] - Y[j, i] else Y[j] > X[j] tdiff += Y[j, i] - X[j, i] end end if tdiff > 1 @show tdiff, i, X[:, i], Y[:, i] end Y .= X end end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
292
using BijectiveHilbert using SafeTestsets using Test include("suite.jl") @testset "BijectiveHilbert.jl" begin include("test_bitops.jl") include("test_gray_code.jl") include("test_simple2d.jl") include("test_hamilton.jl") include("test_global_gray.jl") include("test_facecontinuous.jl") end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
2175
module HilbertTestSuite using BijectiveHilbert: HilbertAlgorithm, decode_hilbert_zero!, encode_hilbert_zero using BijectiveHilbert: index_type, axis_type function check_own_inverse(gg::HilbertAlgorithm, b::Int, n) success = true p = zeros(axis_type(gg), n) H = index_type(gg) for h in 0:(1<<(n*b) - 1) decode_hilbert_zero!(gg, p, H(h)) h2 = encode_hilbert_zero(gg, p) if h2 != H(h) success = false end end success end function check_own_inverse(gg::HilbertAlgorithm, ms::Vector{Int}, n) success = true A = axis_type(gg) p = zeros(A, n) H = index_type(gg) total = prod(ms) for i in 0:(1<<total - 1) h = encode_hilbert_zero(gg, p) q = similar(p) decode_hilbert_zero!(gg, q, h) if p != q success = false end for inc in 1:n p[inc] += one(A) if p[inc] == one(A)<<ms[inc] p[inc] = zero(A) else break end end @assert p != q end success end function check_complete_set(gg::HilbertAlgorithm{H}, b, n) where {H} dim_cnt = n m = b A = axis_type(gg) success = true indices = Base.IteratorsMD.CartesianIndices(tuple(collect(1<<m for i in 1:dim_cnt)...)) seen2 = Dict{H, Vector{A}}() for idx in indices # -1 for zero-based. vidx = convert(Vector{A}, [Tuple(idx)...] .- 1) h = encode_hilbert_zero(gg, vidx) seen2[h] = vidx if h < zero(H) success = false end if h >= one(H)<<(dim_cnt * m) success = false end end if length(seen2) != 1<<(dim_cnt * m) success = false end for ihidx in 0:(1<<(dim_cnt*m) - 2) # compare with next, so stop one early. hidx = H(ihidx) differ = seen2[hidx] .!= seen2[hidx + one(H)] if sum(differ) != 1 @show ihidx, seen2[hidx], seen2[hidx + one(H)] success = false end if sum(differ) == 1 a = seen2[hidx][differ][1] b = seen2[hidx + 1][differ][1] dx = (a > b) ? a - b : b - a if H(dx) != one(H) success = false break end end end success end end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
6087
@safetestset log_base_two_float = "log base two agrees with float version" begin using BijectiveHilbert for i in 1:100 m = BijectiveHilbert.log_base2(i) + 1 # println(i, " ", string(i, base = 2), " ", m, " ", ceil(Int, log(2, i))) @test((1<<(m - 1)) & i != 0) @test(1<<m & i == 0) end end @safetestset bitrotate_left = "rotateleft cases" begin using BijectiveHilbert tries = [ Any[0b1, 0b100, 2, 8], Any[0b1, 0b1000, 3, 8], Any[0b1, 0b1000, 3, 4], Any[0b10, 0b0001, 3, 4], Any[0b1000, 0b0001, 1, 4], Any[0b1000, 0b0010, 2, 4], Any[0b1110, 0b1011, 2, 4] ] for (try_idx, trial) in enumerate(tries) x, y, k, n = trial y1 = BijectiveHilbert.rotateleft(x, k, n) if y != y1 println("k ", k, " n ", n, " ", bitstring(y), " ", bitstring(y1)) end @test y == y1 end end @safetestset bitrotate_right = "rotateright cases" begin using BijectiveHilbert tries = [ Any[0b1, 0b10000000, 1, 8], Any[0b1, 0b01000000, 1, 7], Any[0b1, 0b01000000, 2, 8], Any[0b1, 0b00001000, 1, 4], Any[0b1, 0b00000100, 1, 3], Any[0b1, 0b00000010, 2, 3], ] for (try_idx, trial) in enumerate(tries) x, y, k, n = trial y1 = BijectiveHilbert.rotateright(x, k, n) if y != y1 println("k ", k, " n ", n, " ", bitstring(y), " ", bitstring(y1)) end @test y == y1 end end @safetestset rotateright_random = "rotateright random" begin using BijectiveHilbert: fbvn1s, rotateright, rotateright_naive using Random rng = MersenneTwister(9871879147) for T in [UInt8, UInt16, UInt32, UInt64] for trial in 1:1000 bit_max = 8 * sizeof(T) width = rand(rng, 2:bit_max) shift = rand(rng, 0:(width - 1)) val = rand(rng, zero(T):fbvn1s(T, width)) naive = rotateright_naive(val, shift, width) fancy = rotateright(val, shift, width) @test fancy == naive end end end @safetestset rotateleft_random = "rotateleft random" begin using BijectiveHilbert: fbvn1s, rotateleft, rotateleft_naive using Random rng = MersenneTwister(9871879147) for T in [UInt8, UInt16, UInt32, UInt64] for trial in 1:1000 bit_max = 8 * sizeof(T) width = rand(rng, 2:bit_max) shift = rand(rng, 0:(width - 1)) val = rand(rng, zero(T):fbvn1s(T, width)) naive = rotateleft_naive(val, shift, width) fancy = rotateleft(val, shift, width) @test fancy == naive end end end @safetestset reverse_trials = "reversebits trials" begin using BijectiveHilbert: reverse_bits trials = [ (0b11001, 5, 0b10011), (0b01001, 5, 0b10010), (0b00011, 5, 0b11000) ] for (a, n, b) in trials r = reverse_bits(a, n) @test bitstring(r) == bitstring(b) end end @safetestset setbits_trials = "setbits does some sets" begin using BijectiveHilbert: set_bits, set_bits_naive trials = [ [0b0, 2, 0, 0b11, 0b11], [0b0, 2, 1, 0b11, 0b1100], [0b0, 2, 1, 0b01, 0b0100], [0b0, 2, 1, 0b10, 0b1000], [0b0, 3, 1, 0b111, 0b111000], [0b0, 3, 1, 0b101, 0b101000], [0b0, 3, 1, 0b100, 0b100000], [0b1, 3, 1, 0b100, 0b100001] ] for (h, n, i, w, r) in trials a = set_bits_naive(h, n, i, w) @test bitstring(a) == bitstring(r) end end @safetestset setbits_agrees = "setbits is same as hamilton" begin using BijectiveHilbert: set_bits, set_bits_naive using Random rng = MersenneTwister(82147985) for i in 1:10000 a = rand(rng, UInt64) n = rand(rng, 1:7) i = rand(rng, 1:8) w = rand(rng, 0:(1<<n - 1)) h1 = set_bits(a, n, i, w) h2 = set_bits_naive(a, n, i, w) @test h1 == h2 end end @safetestset getbits_examples = "getbits trials" begin using BijectiveHilbert: get_bits trials = [ (0b1, 1, 0, 0b1), (0b1, 1, 1, 0b0), (0b1, 1, 2, 0b0), (0b1, 1, 7, 0b0), (0b1, 2, 0, 0b1), (0b1, 2, 1, 0b0), (0b100, 1, 0, 0b0), (0b100, 1, 1, 0b0), (0b100, 1, 2, 0b1), (0b100, 1, 3, 0b0), (0b100, 1, 4, 0b0), (0b10000000, 1, 7, 0b1), (0b10000000, 1, 6, 0b0), (0b10000000, 1, 5, 0b0), (0b111000, 1, 2, 0b0), (0b111000, 1, 3, 0b1), (0b111000, 1, 4, 0b1), (0b111000, 1, 5, 0b1), (0b111000, 1, 6, 0b0), (0b111000, 1, 7, 0b0), (0b111000, 2, 0, 0b0), (0b111000, 2, 1, 0b0), (0b111000, 2, 2, 0b10), (0b111000, 2, 3, 0b11), (0b111000, 2, 4, 0b11), (0b111000, 2, 5, 0b01), (0b111000, 2, 6, 0b0), (0b111000, 3, 0, 0b0), (0b111000, 3, 1, 0b100), (0b111000, 3, 2, 0b110), (0b111000, 3, 3, 0b111), (0b111000, 3, 4, 0b011), (0b111000, 3, 5, 0b001), (0b111000, 3, 6, 0b000) ] for (v, b, i, r) in trials a = get_bits(v, b, i) @test a == r end end @safetestset fsb_trials = "first_set_bit unsigned trials" begin using BijectiveHilbert: first_set_bit trials = [ (0b0, 0), (UInt64(0), 0), (UInt32(0), 0), (UInt16(0), 0), (UInt8(0), 0), (UInt64(1), 1), (UInt32(1), 1), (UInt16(1), 1), (UInt8(1), 1), (UInt128(0b1100), 3), (UInt64(0b1100), 3), (UInt32(0b1100), 3), (UInt16(0b1100), 3), (UInt8(0b1100), 3), (0x80, 8), (0x81, 1), (0x82, 2), (0x84, 3) ] for (v, i) in trials r = first_set_bit(v) @test r == i end end @safetestset fsb_unsigned = "first_set_bit signed matches signed" begin using BijectiveHilbert: first_set_bit using Random trials = [Int8, Int16, Int32, Int64] rng = MersenneTwister(349720) for T in trials for i in 1:100 v = rand(rng, T) a = first_set_bit(v) ui = parse(UInt64, "0b" * bitstring(v)) b = first_set_bit(ui) @test a == b end end end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
1904
@safetestset facecontinuous_smoke = "FaceContinuous basic test" begin # Test using the vector form of the Hilbert index so that we don't # introduce another layer of error. When this works, delete it. using BijectiveHilbert: FaceContinuous, H_encode!, H_decode!, msb # Works for UInt32 or UInt16. A = UInt32 H = UInt32 fc1 = FaceContinuous(H, 9, 3) fc2 = FaceContinuous(H, 8, 3) X1 = zeros(A, 3) X1[1] = A(0x8f) X1[2] = A(0x8f) X1[3] = A(0x8f) hvec1 = zeros(A, 3) hvec2 = zeros(A, 3) H_encode!(fc1, X1, hvec1) H_encode!(fc2, X1, hvec2) @assert hvec1 == hvec2 X2 = zeros(A, 3) H_decode!(fc1, hvec1, X1) H_decode!(fc2, hvec2, X2) @test X1 == X2 end @safetestset facecontinuous_api = "FaceContinuous api test" begin # Test using the vector form of the Hilbert index so that we don't # introduce another layer of error. When this works, delete it. using BijectiveHilbert: FaceContinuous, encode_hilbert_zero, decode_hilbert_zero! # Works for UInt32 or UInt16. A = UInt32 H = UInt32 fc = FaceContinuous(H, 9, 3) X = zeros(A, 3) X[1] = A(0x8f) X[2] = A(0x85) X[3] = A(0x43) h = encode_hilbert_zero(fc, X) X2 = zeros(A, 3) decode_hilbert_zero!(fc, X2, h) @test X == X2 X[1] = A(0x5) X[2] = A(0x8) X[3] = A(0x3) h = encode_hilbert_zero(fc, X) X3 = zeros(A, 3) decode_hilbert_zero!(fc, X3, h) @test X == X3 end @safetestset facecontinuous_own_inverse = "FaceContinuous is its own inverse" begin using BijectiveHilbert: FaceContinuous using ..HilbertTestSuite: check_own_inverse for n in [2, 3, 5] for b in [2, 3] fc = FaceContinuous(b, n) @test check_own_inverse(fc, b, n) end end end @safetestset facecontinuous_complete_set = "FaceContinuous is complete set" begin using BijectiveHilbert: FaceContinuous using ..HilbertTestSuite: check_complete_set for n in [2, 3, 5] for b in [2, 3] fc = FaceContinuous(b, n) @test check_complete_set(fc, b, n) end end end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
4922
@safetestset compare_with_cpp = "the c++ implementation is identical" begin if isfile("test/libskilling.so") function TransposetoAxes!(X::Vector{UInt}, b::Int, n::Int) ccall( (:TransposetoAxes, "test/libskilling"), Cvoid, (Ref{UInt}, Int, Int), X, b, n ) end function AxestoTranspose!(X::Vector{UInt32}, b::Int32, n::Int32) ccall( (:AxestoTranspose, "test/libskilling"), Cvoid, (Ref{UInt32}, Int32, Int32), X, b, n ) end using BijectiveHilbert: axes_to_transpose!, transpose_to_axes! using Random rng = MersenneTwister(29472349) for i in 1:100 n = Int32(rand(rng, 2:6)) b = Int32(rand(rng, 2:8)) X = convert(Vector{UInt32}, rand(rng, 0:(1<<b - 1), n)) H = copy(X) axes_to_transpose!(H, b, n) XC = copy(X) AxestoTranspose!(XC, b, n) @test H == XC end end end # Implementation test @safetestset interleave_single = "interleave single example" begin using BijectiveHilbert t = UInt8[0b1100, 0b0110, 0b0011] b = 4 n = length(t) h = BijectiveHilbert.interleave_transpose(UInt64, t, b, n) @test h == 0b100110011001 end # Implementation test @safetestset interleave_outerleave = "outerleave is opposite" begin using BijectiveHilbert n = 3 b = 4 X = zeros(UInt8, n) for h in 0:(1<<(n*b) - 1) BijectiveHilbert.outerleave_transpose!(X, UInt64(h), b, n) h2 = BijectiveHilbert.interleave_transpose(UInt64, X, b, n) @test h == h2 end end @safetestset inverse_of_itself = "GlobalGray is its own inverse" begin using BijectiveHilbert using Random rng = MersenneTwister(29472349) for i in 1:1000 n = rand(rng, 2:6) b = rand(rng, 2:8) gg = GlobalGray(b, n) AT = axis_type(gg) TT = index_type(gg) X = convert(Vector{AT}, rand(rng, 0:(1<<b - 1), n)) X0 = copy(X) h = encode_hilbert_zero(gg, X) decode_hilbert_zero!(gg, X, h) @test X == X0 end end @safetestset hilbert_one_diff = "GlobalGray values next to each other" begin using BijectiveHilbert: GlobalGray using ..HilbertTestSuite: check_complete_set n = 3 b = 4 gg = GlobalGray(b, n) @test check_complete_set(gg, b, n) end @safetestset globalgray_against_file = "globalgray agrees with C code" begin function read_skill(fn) lines = readlines(fn) xyz = zeros(Int, 3, length(lines)) hh = zeros(Int, 3, length(lines)) idx = 0 for ll in lines axmatch = r"^\((\d+), (\d+), (\d+)\)" hmatch = r"\) \((\d+), (\d+), (\d+)\)" if occursin(axmatch, ll) idx += 1 mm = match(axmatch, ll) xyz[:, idx] = parse.(Int, mm.captures) hh[:, idx] = parse.(Int, match(hmatch, ll).captures) end end return xyz, hh end fn = "test/skill3_4_4_4.txt" if !isfile(fn) fn = basename(fn) end if isfile(fn) xyz, hh = read_skill(fn) using BijectiveHilbert for check_idx in 1:size(xyz, 2) ax = convert(Vector{UInt8}, xyz[:, check_idx]) h = convert(Vector{UInt8}, hh[:, check_idx]) BijectiveHilbert.axes_to_transpose!(ax, 4, 3) @test ax == h end for check_idx in 1:size(xyz, 2) ax = convert(Vector{UInt8}, xyz[:, check_idx]) h = convert(Vector{UInt8}, hh[:, check_idx]) BijectiveHilbert.transpose_to_axes!(h, 4, 3) @test h == ax end end end @safetestset globalgray_type_interactions = "GlobalGray type interactions" begin using BijectiveHilbert using UnitTestDesign using Random rng = Random.MersenneTwister(9790323) for retrial in 1:5 AxisTypes = shuffle(rng, [Int8, Int, UInt, Int128, UInt8, UInt128]) IndexTypes = shuffle(rng, [Union{}, Int8, UInt8, Int, UInt, Int128, UInt128]) Count= shuffle(rng, [0, 1]) Dims = shuffle(rng, [2, 3, 4]) Bits = shuffle(rng, [2, 3, 4, 5]) test_set = all_pairs( AxisTypes, IndexTypes, Count, Dims, Bits; ) for (A, I, C, D, B) in test_set if I == Union{} gg = GlobalGray(B, D) I = index_type(gg) else gg = GlobalGray(I, B, D) end if B * D > log2(typemax(I)) continue end last = (one(I) << (B * D)) - one(I) + I(C) mid = one(I) << (B * D - 1) few = 5 X = zeros(A, D) hlarr = vcat(C:min(mid, few), max(mid + 1, last - few):last) for hl in hlarr hli = I(hl) if C == 0 decode_hilbert_zero!(gg, X, hli) hl2 = encode_hilbert_zero(gg, X) @test hl2 == hli @test typeof(hl2) == typeof(hli) else decode_hilbert!(gg, X, hli) hl2 = encode_hilbert(gg, X) @test hl2 == hli @test typeof(hl2) == typeof(hli) end end end end end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
1660
@safetestset gray_code_symmetry = "Gray code symmetry" begin using BijectiveHilbert # for i in 0:10 # println(lpad(i, 3, " "), " ", lpad(string(BijectiveHilbert.brgc(i), base = 2), 8, "0")) # end # Here's a test of the gray code. n = 5 for i in 0x0:(0x1 << n - 0x1) # println(BijectiveHilbert.brgc(1<<n - 1 - i), " ", BijectiveHilbert.brgc(i) ⊻ (1 << (n-1))) @test(BijectiveHilbert.brgc(1<<n - 1 - i) == BijectiveHilbert.brgc(i) ⊻ (1 << (n - 1))) end end @safetestset gray_code_single = "Gray code changes one bit" begin using BijectiveHilbert: brgc, is_power_of_two for i in 0x1:0x1000 @test is_power_of_two(brgc(i) ⊻ brgc(i + 1)) end end @safetestset brgc_own_inverse = "Gray code is own inverse" begin using BijectiveHilbert for i in 0x0:0x1000 @test(BijectiveHilbert.brgc_inv(BijectiveHilbert.brgc(i)) == i) end end @safetestset brgc_equals_naive = "Gray code matches paper description" begin using BijectiveHilbert: brgc_inv using Random rng = MersenneTwister(9719742) for T in [UInt8, UInt16, UInt32, UInt64] for trial in 1:10000 v = rand(rng, T) n = brgc_inv(Int128(v)) # The paper version is used for integers. i = brgc_inv(v) @test n == i end end end @safetestset brgc_ranks_equal = "the rank calculation is the same as the paper" begin using BijectiveHilbert: brgc_rank, brgc_rank2 using Random rng = MersenneTwister(974073242) for trial in 1:1000 n = rand(rng, 2:7) w = UInt8(rand(rng, 0:(1<<n - 1))) mask = UInt8(rand(rng, 0:(1<<n - 1))) a = brgc_rank(mask, w, n) b = brgc_rank2(mask, w, n) @test a == b end end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
17594
@safetestset hi_g_definition = "g is the direction of gray code" begin using BijectiveHilbert: brgc, hi_g for i in 0:1000 @test brgc(i) ⊻ brgc(i + 1) == 1<<hi_g(i) @test brgc(i) == brgc(i + 1) ⊻ 1<<hi_g(i) # xor. It's how it works. end end @safetestset binary_reflection_of_gc = "gray code is binary reflected" begin using BijectiveHilbert: brgc n = 10 for i in 0:(1<<n - 1) @test brgc(1<<n - 1 - i) == brgc(i) ⊻ 1<<(n-1) end end @safetestset hi_g_matches_long_form = "hi_g is the same as its definition" begin using BijectiveHilbert: hi_g, hi_g_orig for i = 0:100 @test hi_g(i) == hi_g_orig(i) end end @safetestset hi_g_symmetry = "hi_g symmetry invariant" begin using BijectiveHilbert: brgc, hi_g, bshow # n = 3 # for i in 0:(1<<n) # println( # bshow(brgc(i)), " ", # bshow(brgc(i + 1)), " ", # bshow(brgc(i) ⊻ brgc(i + 1)), " ", # bshow(1<<hi_g(i)), " ", # bshow(i) # ) # end # Test for the hi_g function. n = 5 for i in 0:(1<<n - 2) # println(hi_g(i), " ", hi_g(1<<n - 2 - i)) @test(hi_g(i) == hi_g(1<<n - 2 - i)) end end @safetestset efdg_match_table = "directions match figure 5 in hamilton report" begin using BijectiveHilbert: hi_e, hi_f, hi_d, hi_g n = 2 trials = [ #i e f d g [0, 0b00, 0b01, 0, 0], [1, 0b00, 0b10, 1, 1], [2, 0b00, 0b10, 1, 0], [3, 0b11, 0b10, 0, 2] ] for (i, e, f, d, g) in trials @test hi_e(i) == Int(e) @test hi_f(i, n) == Int(f) @test hi_d(i, n) == d if g != 42 @test hi_g(i) == g end end end # The 2d example in the paper has a simpler 1d equivalent, # which is two segments in a row. d=0 for both. f is 1. @safetestset efdg_match_1d = "directions match a one-dimensional equivalent" begin using BijectiveHilbert: hi_e, hi_f, hi_d, hi_g n = 1 trials = [ #i e f d g [0, 0, 1, 0, 0], # the first segment should match n=2 [1, 0, 1, 0, 1] # the second segment will be redirected for n=2 ] for (i, e, f, d, g) in trials @test hi_e(i) == e @test hi_f(i, n) == f @test hi_d(i, n) == d @test hi_g(i) == g end end # A 3d example. @safetestset efdg_match_3d = "directions match a three-dimensional equivalent" begin using BijectiveHilbert: hi_e, hi_f, hi_d, hi_g n = 3 trials = [ #i e f d g [0, 0b000, 0b001, 0, 0], # segments 0-2 match n=2 [1, 0b000, 0b010, 1, 1], [2, 0b000, 0b010, 1, 0], [3, 0b011, 0b111, 2, 2], # segment 3 gets redirected in z-direction [4, 0b011, 0b111, 2, 0], # segment 4 also in z direction [5, 0b110, 0b100, 1, 1], # then we repeat the 2d plane in reverse. [6, 0b110, 0b100, 1, 0], [7, 0b101, 0b100, 0, 3] ] for (i, e, f, d, g) in trials @test hi_e(i) == Int(e) @test hi_f(i, n) == Int(f) @test hi_d(i, n) == d @test hi_g(i) == g end end @safetestset hi_e_matches_float_version = "hi_e matches its floating point version" begin using BijectiveHilbert: hi_e, hi_e_orig # Show our implementation for hi_e matches the specification. for i = 1:100 @test(hi_e(i) == hi_e_orig(i)) end end @safetestset cubes_neighbor_along_g_coord = "cubes are neighbors along gth coordinate" begin # From page 12, just below the figure. The definition of the directions. using BijectiveHilbert: hi_e, hi_f, hi_g for n in 2:5 # Goes to 2^n-2, not 2^n-1 because there is no neighbor for the last point. for i in 0:(1<<n - 2) fside = hi_f(i, n) ⊻ (1<<hi_g(i)) eside = hi_e(i + 1) @test fside == eside if fside != eside @show n, i, fside, eside break end end end end @safetestset hi_d_symmetry_invariant = "hi_d symmetry invariant works corollary 2.7" begin using BijectiveHilbert: hi_d, bshow # n = 3 # for i = 0:(1<<n) # println(i, " ", bshow(hi_d(i, n))) # end # invariant for d on page 12. Corollary 2.7. # Does not hold true for i=0 and i=1<<n - 1. n = 5 for i = 0:(1<<n - 1) #println(hi_d(i, n), " ", hi_d((1<<n)-1-i, n)) d = hi_d(i, n) dflip = hi_d((1<<n) - 1 - i, n) @test(d == dflip) end end @safetestset hi_d_compare_g = "hi_d equals hi_g at 2n-1 lemma 2.8" begin using BijectiveHilbert: hi_d, hi_g for n = 1:5 d = hi_d(1<<n - 1, n) g = hi_g(1<<n - 1) @test d % n == g % n end end @safetestset hi_d_compares_with_g = "hi_d equals g for mod 2" begin using BijectiveHilbert: hi_d, hi_g for n = 2:5 for i = 0:(1<<n - 1) d = hi_d(i, n) if i == 0 @test d == 0 elseif i % 2 == 0 g = hi_g(i - 1) @test d == (g % n) else g = hi_g(i) @test d == (g % n) end end end end @safetestset hi_edg_invariant = "hi e, d, g invariant is consistent" begin using BijectiveHilbert: hi_d, hi_e, hi_g # invariant for e, d, and g. pg. 11. Eq. 1. # Contrary to the tech report, this is NOT true for 2^n-1. n = 5 for i = 0:(1<<n - 2) @test(hi_e(i + 1) == hi_e(i) ⊻ (1 << hi_d(i, n)) ⊻ (1 << hi_g(i))) end end @safetestset hi_e_reflection = "hi_e reflects to f" begin using BijectiveHilbert: hi_d, hi_e, hi_f n = 5 for i = 0:(1<<n - 1) e = hi_e(i) d = hi_d(i, n) f = hi_f(i, n) # Corollary 2.7, pg 12, states that e ⊻ d = f, but that's not true. # Page 11, first paragraph, says e(i) \xor f(i) = 2^d(i). That's this. @test e ⊻ (1<<d) == f end end @safetestset rotation_invariant_zero = "rotation invariant on hi_e is zero" begin using BijectiveHilbert: hi_T, hi_e, hi_d # lemma 2.11, page 15 # Assert T_{e,d}(e) == 0 n = 3 for i = 0:(1<<n - 1) # println(hi_T(hi_e(i), hi_d(i, n), hi_e(i), n)) @test(0 == hi_T(hi_e(i), hi_d(i, n), hi_e(i), n)) end end # "rotation invariant on hi_f is power of two" begin # lemma 2.11, page 15 # Assert T_{e,d}(f) == 2^(n-1) # Contrary to the tech report, this is NOT true. # @test(0x1<<(n-1) == hi_T(hi_f(i, n), hi_d(i, n), hi_e(i), n)) # Top of page 16, stated invariant: # (T_(e,d)(a) rotleft (d + 1)) ⊻ e == a # Also NOT true @safetestset ef_invariant = "ef relationship holds" begin using BijectiveHilbert: hi_e, hi_f # invariant bottom of pg. 11. Lemma 2.6. # fails for i=0 and i=2^n n = 5 for i = 0b1:(0b1<<(n - 1)) e = hi_e(i) ff = hi_f((0b1<<n) - 0b1 - i, n) ⊻ (0b1<<(n-1)) # println(e, " ", ff) @test(e == ff) @test typeof(e) == UInt8 @test typeof(ff) == UInt8 end end @safetestset inverse_t_itself = "transform is its own inverse" begin using BijectiveHilbert: hi_d, hi_e, hi_T, hi_T_inv # Check that the inverse of T is an inverse. n = 3 for i = 0x0:(0x1<<n - 0x1) for b = 0x0:(0x1<<n - 0x1) @test(typeof(i) == UInt8) d = UInt8(hi_d(i, n)) e = UInt8(hi_e(i)) a = hi_T(b, d, e, n) b1 = hi_T_inv(a, d, e, n) # println(join(string.(typeof.((i, b, a, b1))), " ")) # println("b ", bitstring(b), " a ", bitstring(a), " b1 ", bitstring(b1)) @test(b == b1) end end end @safetestset get_ith_bit_trials = "trials show can get ith bit of vectors" begin using BijectiveHilbert: ith_bit_of_indices, get_location v = [0b01110100, 0b01101010, 0b01011001] trials = [ [0, "00000100"], [1, "00000010"], [2, "00000001"], [3, "00000110"], [4, "00000101"], [5, "00000011"], [6, "00000111"], [7, "00000000"] ] for (idx, t0) in trials @test bitstring(ith_bit_of_indices(3, v, idx)) == t0 # Look, Hamilton's version matches. @test bitstring(get_location(v, idx)) == t0 end end @safetestset ith_bit_types = "ith_bit ops use all types" begin using BijectiveHilbert: ith_bit_of_indices, set_indices_bits! using Random rng = MersenneTwister(4972433234) tt = [Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128] for T in tt for j in 1:10 n = 1 p = zeros(T, 1) p[1] = T(rand(rng, 0:typemax(T))) q = zeros(T, 1) for i in 0:(8*sizeof(T) - 1) b = ith_bit_of_indices(n, p, i) set_indices_bits!(q, b, n, i) end @test q[1] == p[1] end end end @safetestset hilbert_index_complete4d = "hilbert index is a complete set for 4d" begin using BijectiveHilbert: SpaceGray using ..HilbertTestSuite: check_complete_set b = 3 n = 4 gg = SpaceGray(b, n) @test check_complete_set(gg, b, n) end # @safetestset hilbert_index_paper_tr = "paper and techreport agree" begin # using BijectiveHilbert: hilbert_index, hilbert_index_paper # They do NOT agree. # m = 0x4 # One larger won't fit into a byte and must fail. # for i in 0:(1<<m - 1) # for j in 0:(1<<m - 1) # h_tr = hilbert_index(0x2, m, UInt8[i, j]) # h_p = hilbert_index_paper(0x2, m, UInt8[i, j]) # @test typeof(h_tr) == typeof(h_p) # @test h_p == h_tr # if h_p != h_tr # break # end # end # end # end @safetestset libhilbert_matches = "libhilbert output matches" begin using BijectiveHilbert: SpaceGray, encode_hilbert_zero n = 4 b = 5 gg = SpaceGray(b, n) trials = [ [10, 1, 1, 1, 1], [11, 1, 0, 1, 1], [12, 1, 0, 1, 0], [13, 1, 1, 1, 0], [14, 1, 1, 0, 0], [15, 1, 0, 0, 0], [16, 2, 0, 0, 0], [17, 2, 0, 1, 0], [18, 2, 0, 1, 1], [19, 2, 0, 0, 1] ] for trial in trials v = convert(Vector{UInt8}, trial[2:end]) result = Int(encode_hilbert_zero(gg, v)) @test result == trial[1] end end @safetestset correct_bits_set_in_indices = "indices bits match" begin using BijectiveHilbert: set_indices_bits! m = 3 i = 4 l = 0b110 p = zeros(Int, 3) set_indices_bits!(p, l, m, i) @test p == [0, 1<<i, 1<<i] end @safetestset paper_inv = "paper hilbert is own inverse" begin using BijectiveHilbert: SpaceGray using ..HilbertTestSuite: check_own_inverse for n in 2:5 for b in 2:4 gg = SpaceGray(b, n) @test check_own_inverse(gg, b, n) end end end @safetestset brgc_mask_equal = "mask calculation matches paper" begin using BijectiveHilbert: extract_mask, extract_mask_paper, hi_d using Random rng = MersenneTwister(974073242) for trial in 1:1000 n = rand(rng, 2:7) m = rand(rng, 2:5, n) i = rand(rng, 0:(n - 1)) d = hi_d(i, n) a = extract_mask(m, n, d, i) b = extract_mask_paper(m, n, d, i) @test a == b end end @safetestset libhilbert_hc_matches = "libhilbert compressed output matches" begin using BijectiveHilbert: encode_hilbert_zero, Compact n = 4 b = 5 trials = [ [10, 1, 1, 1, 1], [11, 1, 0, 1, 1], [12, 1, 0, 1, 0], [13, 1, 1, 1, 0], [14, 1, 1, 0, 0], [15, 1, 0, 0, 0], [16, 2, 0, 0, 0], [17, 2, 0, 1, 0], [18, 2, 0, 1, 1], [19, 2, 0, 0, 1] ] for trial in trials v = convert(Vector{UInt8}, trial[2:end]) ms = [b, b, b, b] gg = Compact(ms) result = Int(encode_hilbert_zero(gg, v)) @test result == trial[1] end end @safetestset compact_index_is_its_inverse = "compact index is its inverse" begin using BijectiveHilbert: Compact using ..HilbertTestSuite: check_own_inverse using Random rng = MersenneTwister(432479874) for n = [5] for i in 1:1 ms = rand(rng, 2:5, n) gg = Compact(ms) @test check_own_inverse(gg, ms, n) end end end @safetestset compact_index_matches_examples = "compact index matches examples" begin include(joinpath(dirname(@__FILE__), "check_hamilton.jl")) using BijectiveHilbert: Compact, decode_hilbert_zero!, index_type, axis_type fns = ["test/3_2_5_7.txt", "test/2_5_3.txt", "test/3_4_2_3.txt", "test/3_5_2_3.txt", "test/4_5_5_5.txt"] for fn in fns if !isfile(fn) fn = basename(fn) end if isfile(fn) h, X, ms = hamilton_example(fn) n = size(X, 1) gg = Compact(ms) p = zeros(axis_type(gg), n) H = index_type(gg) for i in eachindex(h) decode_hilbert_zero!(gg, p, H(h[i])) @test convert(Vector{UInt8}, p) == X[:, i] end end end end @safetestset compact_index_inv_matches_examples = "inverse compact index matches examples" begin include(joinpath(dirname(@__FILE__), "check_hamilton.jl")) using BijectiveHilbert: Compact, encode_hilbert_zero, axis_type, index_type fns = ["test/3_2_5_7.txt", "test/2_5_3.txt", "test/3_4_2_3.txt", "test/3_5_2_3.txt", "test/4_5_5_5.txt"] for fn in fns if !isfile(fn) fn = basename(fn) end if isfile(fn) h, X, ms = hamilton_example(fn) n = size(X, 1) gg = Compact(ms) H = index_type(gg) for i in eachindex(h) XX = convert(Vector{axis_type(gg)}, X[:, i]) hc = encode_hilbert_zero(gg, XX) @test hc == H(h[i]) if hc != H(h[i]) @show n, ms, i, h[i], hc, X[:, i] break end end end end end @safetestset compact_for_signed = "compact hilbert for signed integers" begin using BijectiveHilbert using Random rng = MersenneTwister(9742439) for i in 1:1000 n = rand(rng, 3:5) ms = rand(rng, 2:7, n) gg = Compact(Int, ms) gg2 = Compact(ms) x = zeros(Int, n) A = axis_type(gg2) y = zeros(A, n) for i in 1:n x[i] = rand(rng, 0:(1<<ms[i] - 1)) y[i] = A(x[i]) end a = encode_hilbert_zero(gg, x) b = Int(encode_hilbert_zero(gg2, y)) @test a == b end end @safetestset hamilton_zero_based = "hamilton works for zero based" begin using BijectiveHilbert gg = Compact(UInt, [4, 3, 3]) X = [9, 4, 5] h = encode_hilbert(gg, X) Y = zeros(Int, 3) decode_hilbert!(gg, Y, h) @test X == Y end @safetestset spacegray_type_interactions = "SpaceGray type interactions" begin using BijectiveHilbert using UnitTestDesign using Random rng = Random.MersenneTwister(9790323) for retrial in 1:5 AxisTypes = shuffle(rng, [Int8, Int, UInt, Int128, UInt8, UInt128]) IndexTypes = shuffle(rng, [Union{}, Int8, UInt8, Int, UInt, Int128, UInt128]) Count= shuffle(rng, [0, 1]) Dims = shuffle(rng, [2, 3, 4]) Bits = shuffle(rng, [2, 3, 4, 5]) test_set = all_pairs( AxisTypes, IndexTypes, Count, Dims, Bits; ) for (A, I, C, D, B) in test_set if I == Union{} gg = SpaceGray(B, D) I = index_type(gg) else gg = SpaceGray(I, B, D) end if B * D > log2(typemax(I)) continue end last = (one(I) << (B * D)) - one(I) + I(C) mid = one(I) << (B * D - 1) few = 5 X = zeros(A, D) hlarr = vcat(C:min(mid, few), max(mid + 1, last - few):last) for hl in hlarr hli = I(hl) if C == 0 decode_hilbert_zero!(gg, X, hli) hl2 = encode_hilbert_zero(gg, X) if hl2 != hli @show A, I, C, D, B, X @test hl2 == hli end @test typeof(hl2) == typeof(hli) else decode_hilbert!(gg, X, hli) hl3 = encode_hilbert(gg, X) @test hl3 == hli @test typeof(hl3) == typeof(hli) end end end end end @safetestset spacegray_random = "spacegray random" begin using BijectiveHilbert aas = [Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128] tts = [UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128] ggbase = SpaceGray(UInt32, 4, 4) hli = UInt32(2) Xbase = zeros(UInt8, 4) decode_hilbert_zero!(ggbase, Xbase, hli) for idx in Base.IteratorsMD.CartesianIndices((length(aas), length(tts))) i, j = Tuple(idx) A = aas[i] T = tts[j] gg = SpaceGray(T, 4, 4) X = zeros(A, 4) hli = T(2) decode_hilbert_zero!(gg, X, hli) @test X == Xbase hl2 = encode_hilbert_zero(gg, X) @test hl2 == hli end end @safetestset compact_type_interactions = "Compact type interactions" begin using BijectiveHilbert using UnitTestDesign using Random rng = Random.MersenneTwister(9790323) for retrial in 1:5 AxisTypes = shuffle(rng, [Int8, Int, UInt, Int128, UInt8, UInt128]) IndexTypes = shuffle(rng, [Union{}, Int8, UInt8, Int, UInt, Int128, UInt128]) Count= shuffle(rng, [0, 1]) Dims = shuffle(rng, [2, 3, 4]) Bits = shuffle(rng, [2, 3, 4, 5]) test_set = all_pairs( AxisTypes, IndexTypes, Count, Dims, Bits; ) for (A, I, C, D, B) in test_set if I == Union{} gg = Compact(fill(B, D)) I = index_type(gg) else gg = Compact(I, fill(B, D)) end if B * D > log2(typemax(I)) continue end last = (one(I) << (B * D)) - one(I) + I(C) mid = one(I) << (B * D - 1) few = 5 X = zeros(A, D) hlarr = vcat(C:min(mid, few), max(mid + 1, last - few):last) for hl in hlarr hli = I(hl) if C == 0 decode_hilbert_zero!(gg, X, hli) hl2 = encode_hilbert_zero(gg, X) if hl2 != hli @show A, I, C, D, B, X @test hl2 == hli end @test typeof(hl2) == typeof(hli) else decode_hilbert!(gg, X, hli) hl3 = encode_hilbert(gg, X) @test hl3 == hli @test typeof(hl3) == typeof(hli) end end end end end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
code
2731
@safetestset hilbert_decode_zero = "hilbert decode zero" begin using BijectiveHilbert table2 = [ 15 12 11 10 14 13 8 9 1 2 7 6 0 3 4 5 ] table2 = table2[end:-1:1, :] table2ind = CartesianIndices(table2) gg = Simple2D(Int) X = zeros(Int, 2) for z in 0:15 BijectiveHilbert.decode_hilbert_zero!(gg, X, z) found = table2ind[table2 .== z][1] @test found[2] - 1 == X[1] @test found[1] - 1 == X[2] end end @safetestset simple2d_own_inverse = "simple2d is its own inverse" begin using BijectiveHilbert: Simple2D using ..HilbertTestSuite: check_own_inverse gg = Simple2D(Int) for b in 2:7 @test check_own_inverse(gg, b, 2) end end @safetestset simple2d_complete_set = "simple2d is a complete set" begin using BijectiveHilbert: Simple2D using ..HilbertTestSuite: check_complete_set gg = Simple2D(Int) for b in 2:7 @test check_complete_set(gg, b, 2) end end @safetestset simple2d_type_interactions = "Simple2D type interactions" begin using BijectiveHilbert using UnitTestDesign using Random rng = Random.MersenneTwister(9790323) for retrial in 1:5 AxisTypes = shuffle(rng, [Int8, Int, UInt, Int128, UInt8, UInt128]) IndexTypes = shuffle(rng, [Int8, UInt8, Int, UInt, Int128, UInt128]) Count= shuffle(rng, [0, 1]) Dims = shuffle(rng, [2, 3, 4]) Bits = shuffle(rng, [2, 3, 4, 5]) test_set = all_pairs( AxisTypes, IndexTypes, Count, Dims, Bits; ) for (A, I, C, D, B) in test_set gg = Simple2D(I) if B * D > log2(typemax(I)) continue end # Add this because these values aren't in Hilbert order because # It's an asymmetrical space. if B * D > log2(typemax(A)) continue end last = (one(I) << (B * D)) - one(I) + I(C) mid = one(I) << (B * D - 1) few = 5 X = zeros(A, D) hlarr = vcat(C:min(mid, few), max(mid + 1, last - few):last) for hl in hlarr hli = I(hl) if C == 0 decode_hilbert_zero!(gg, X, hli) hl2 = encode_hilbert_zero(gg, X) if hl2 != hli @show A, I, C, D, B, X @test hl2 == hli end @test typeof(hl2) == typeof(hli) else decode_hilbert!(gg, X, hli) hl3 = encode_hilbert(gg, X) @test hl3 == hli @test typeof(hl3) == typeof(hli) end end end end end
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
docs
3048
# BijectiveHilbert [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://adolgert.github.io/BijectiveHilbert.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://adolgert.github.io/BijectiveHilbert.jl/dev) [![Build Status](https://github.com/adolgert/BijectiveHilbert.jl/workflows/CI/badge.svg)](https://github.com/adolgert/BijectiveHilbert.jl/actions) [![Coverage](https://codecov.io/gh/adolgert/BijectiveHilbert.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/adolgert/BijectiveHilbert.jl) Data in two or more dimensions is stored linearly, so places nearby in the data can be far in memory or on disk. This package offers functions that make multi-dimensional data storage and retrieval more efficient by sorting them so that nearby data is nearby in memory. ```julia julia> using Pkg; Pkg.add("BijectiveHilbert") julia> using BijectiveHilbert julia> xy = zeros(Int, 8, 8) julia> for y in 1:size(xy, 2) for x in 1:size(xy, 1) z = encode_hilbert(Simple2D(Int), [x, y]) xy[x, y] = z end end julia> X = zeros(Int, 2) julia> decode_hilbert!(Simple2D(Int), X, xy[5, 7]) julia> X == [5, 7] julia> xy 8×8 Array{Int64,2}: 1 2 15 16 17 20 21 22 4 3 14 13 18 19 24 23 5 8 9 12 31 30 25 26 6 7 10 11 32 29 28 27 59 58 55 54 33 36 37 38 60 57 56 53 34 35 40 39 61 62 51 52 47 46 41 42 64 63 50 49 48 45 44 43 ``` This function, called a [Hilbert curve](https://en.wikipedia.org/wiki/Hilbert_curve), is used most often for geospatial work or database implementation but is equally appropriate for dealing with large TIFF files. It belongs to the class of space-filling, self-avoiding, simple, and self-similar (FASS) curves, which includes Peano curves, and Morton z-curves. Included are several variations of the Hilbert curve. They are type-stable and thoroughly tested, including bug fixes on three of the implementations. * [`Simple2D`](https://computingkitchen.com/BijectiveHilbert.jl/stable/simple2d/), shown above, two-dimensional. Doesn't need to know axis dimensions, from Chen, Wang, and Shi. * [`GlobalGray`](https://computingkitchen.com/BijectiveHilbert.jl/stable/globalgray/), an n-dimensional curve where all axis dimensions must be equal, from Skilling. * [`SpaceGray`](https://computingkitchen.com/BijectiveHilbert.jl/stable/compact/), an n-dimensional curve with a different path. All axis dimensions must be equal, from Hamilton and Rau-Chaplin. * [`Compact`](https://computingkitchen.com/BijectiveHilbert.jl/stable/compact/), an n-dimensional curve the permits each axis to be a different size, from Hamilton and Rau-Chaplin. * [`FaceContinuous`](https://computingkitchen.com/BijectiveHilbert.jl/stable/facecontinuous/), an n-dimensional curve, the oldest version from Butz and Lawder. ## Hilbert curves for computation A video about using Hilbert curves: [![Hilbert curves for computation](docs/src/hilbert_thumb.jpg)](https://youtu.be/MlfS7xo2L7w)
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
docs
95
# How to build docs From the repository root, run: ``` julia --project=docs/ docs/make.jl ```
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
docs
2184
# Compact and SpaceGray This algorithm is used for professional database implementation because it focuses on how to pack dimensions of different sizes into the smallest-possible Hilbert index. If the data is high-dimensional and one of the indices is larger than the others, then the usual Hilbert curve encodes all indices at the same size as the largest one. This means the Hilbert index needs to use a larger data type, which means it needs more storage. Hamilton and Rau-Chaplin used mathematical manipulation to drop unused bits from the Hilbert index while keeping its central feature, that nearby data remains nearby. Both the [`Compact`](@ref) and [`SpaceGray`](@ref) algorithms use what's called the space key algorithm for Hilbert curves. It's not recursive. It follows four steps. Quoting their paper [^1]: 1. Find the cell containing the point of interest. 2. Update the key (index) value appropriately. 3. Transform as necessary; and 4. Continue until sufficient precision has been obtained. This is a very typical way to generate Hilbert curves, and the algorithm, which I labeled SpaceGray, it their implementation of a classic space key algorithm that relies on Gray codes. They then layer the space key algorithm with a bit-packing algorithm that relies on Gray code rank. This is a mask, to exclude unused bits, and an ordering on the remaining bits that preserves the Hilbert structure. As a note for developers, Hamilton's original tech report [^2] has errors that look, to me, like he developed the work for two dimensions and expanded it, incompletely, for n dimensions. It's impressively-detailed math that leads to a concise formulation. I wouldn't have figured out the problems, except that there is a copy of [Hamilton's code](https://github.com/pdebuyl/libhilbert), that he, himself, corrected. [^1]: Hamilton, Chris H., and Andrew Rau-Chaplin. "Compact Hilbert indices for multi-dimensional data." First International Conference on Complex, Intelligent and Software Intensive Systems (CISIS'07). IEEE, 2007. [^2]: Hamilton, Chris. "Compact hilbert indices." Dalhousie University, Faculty of Computer Science, Technical Report CS-2006-07 (2006).
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
docs
1534
# Face Continuous This is the OG Hilbert code, where the first implementation of encoding came from a paper by Butz [^1] and, later, Lawder [^2] provided the decoding algorithm. It's called `FaceContinuous` because that was its main cited property in a review of Hilbert curves [^3]. For developers, there are two errors in the [code that Lawder corrected](http://www.dcs.bbk.ac.uk/~jkl/publications.html). The first is that there is a single-bit mask, called `mask`, that should be initialized from the number of levels, not from the size of the data type. This is true for both encoding and decoding. The second is that, during decoding, the first assignment, to the highest bit of the coordinates, assigns directly from P, the highest Hilbert index bits. It should assign from `A`, which is the binary-reflected Gray code of the highest bits. These problems wouldn't show up in testing unless the highest bits in the type were used, which is an understandable oversight. [^1]: Butz, Arthur R. "Alternative algorithm for Hilbert's space-filling curve." IEEE Transactions on Computers 100.4 (1971): 424-426. [^2]: Lawder, Jonathan K. "Calculation of mappings between one and n-dimensional values using the hilbert space-filling curve." School of Computer Science and Information Systems, Birkbeck College, University of London, London Research Report BBKCS-00-01 August (2000). [^3]: Haverkort, Herman. "Sixteen space-filling curves and traversals for d-dimensional cubes and simplices." arXiv preprint arXiv:1711.04473 (2017).
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
docs
1152
# Global Gray This is a very concise algorithm for Hilbert curve generation. It works in `n`-dimensions. It requires little code. It comes from a little paper [^1] behind a paywall, sadly. Most algorithms for the Hilbert curve use Gray codes to generate the shape. He observed that, instead of using the space key algorithm, which dives to each level deeper and rotates the Gray code, the algorithm could use a global transformation of all values with a Gray code and then do a minor fix-up, afterwards, so untwist it. The resulting code is much simpler than earlier efforts. For developers, note that this algorithm relies on encoding the Hilbert index in what, to me, was a surprising order. To understand the interleaving of the Hilbert index for this algorithm, start with a 2D value where higher bits are larger subscripts, ``(a_4a_3a_2a_1, b_4b_3b_2b_1)``. Skilling encodes this as ``a_4b_4a_3b_3a_2b_2a_1b_1``, which looks good on paper, but it means the first element of the vector has the higher bits. [^1]: Skilling, John. "Programming the Hilbert curve." AIP Conference Proceedings. Vol. 707. No. 1. American Institute of Physics, 2004.
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
docs
6546
# Pseudo-Hilbert Curves for Computational Science ## Introduction The Pseudo-Hilbert curve sorts regular arrays of points into a linear order that keeps nearby points in the array close to each other in the linear order. Scientific computing algorithms use this capability in a few ways. 1. An easy form of clustering. 2. Speed up queries for databases. 3. Allocate work for distributed computing. 4. Visualize correlation of large one-dimensional datasets. 5. Visualize change over time of two-dimensional datasets. 6. Apply a one-dimensional global optimization algorithm to a multi-dimensional dataset. 7. An R-tree algorithm that uses Hilbert curves to pick node locations. These widely different applications all use the Hilbert curve, not for drawing, but to convert indices from multiple dimensions to a single dimension and to convert them back to multiple dimensions, as needed. For high performance computing, it's not a drawn curve but an algorithm. ## The algorithm There are two functions. One accepts an array of natural numbers as input and returns a single Hilbert index as output. We call that encoding. The other function decodes the single Hilbert index into the original natural numbers. There are a lot of pairs of functions that can do this. For instance, you may recall from your earliest math class that we use such a pair of functions to prove that the number of integers in the first quadrant of a two-dimensional graph are countably infinite. Starting from (0, 0), move to (0, 1) and then (1, 0). Then move from (2, 0) to (1, 1) to (0, 2). This weaves along diagonals (in boustrophedon order), sweeping out a one-dimensional covering of two dimensions. Each point in 2D has a corresponding, countable point in 1D. Nor is this the only example, by far. Julia stores its matrices in column-major order. C stores its matrices in row-major order. Both are orderings of two-dimensional rectangles according to a linear storage order. So, too, is block storage of data. These are functions like the Hilbert curve because we can automatically translate from (i, j) to a single index in memory, if we know the dimensions of the matrix. The Hilbert algorithm is equivalent to the use of column-major order with one addition. Two points near each other according to the Hilbert index will tend to be closer to each other if we measure the Euclidean distance between their two-dimensional indices. There isn't a guaranteed upper bound on how far apart two points can be, but experiments comparing nearness, called spatial locality, confirm that the Hilbert curve tends to arrange points closer to each other than does column-major storage, block storage, or other self-similar space-filling curves, such as the Peano curve. That's why this algorithm is useful. Given a bunch of (i, j) indices, the Hilbert index helps to arrange them in a single vector such that nearby indices tend to be closer to each other. Using a Hilbert algorithm can be a little more complicated than that, only because tradition asks that you focus on counts of bits. Let's look at why this is an easy, if important, requirement. ## Counting bits Like a column-major order for a matrix, a Hilbert algorithm needs to know, before doing a conversion, what extent the data might have. Most implementations of Hilbert curves assume that every dimension of the input coordinates will have the same size and will be a power of two. If your data is 25 x 38, that means you need a 64 x 64 grid on which to work. That means the i-axis requires 6 bits and the j-axis requires 6-bits. As a result, the Hilbert index will run from 0 to 4095, needing 12-bits in which to store its result. If we don't use the full size of the allocated axes, are we not going to get as good spatial locality from the Hilbert curve? This is only approximate to start with. The way to use this algorithm is to create axes that are large enough and not worry about the unused bits of information. The bit count matters for choosing types of function arguments. It's usually easy for the coordinates to hold their integer data, but higher dimensions can make the resulting Hilbert index too large for most data types. Eight dimensions of ten bits is 80 bits, which exceeds a typical Int64. That's fine in Julia, which has both Int128 and BigInt types. In addition, most of the math is defined for unsigned integers, but the algorithms in this library are tested to work up to the last sign-bit for signed integers, so they are OK to use. ## Properties of different Hilbert curves There are multiple Hilbert curves. There is even a paper called, "How many three-dimensional Hilbert curves are there?" by Haverkort (2017). The different curves have different orientataions relative to their axes. They can be symmetric or asymmetric. They fill space in slightly different ways, (almost) all of which require domains that are powers of two in each direction. Haverkort also wrote a lovely paper describing these differences, in "Sixteen space-filling curves and traversals for d-dimensional cubes and simplices." For use in scientific computing, it may be more important to judge different Hilbert curve algorithms on capability, speed, and relaxation of constraints. * The [`Compact`](@ref) algorithm creates a Hilbert curve where each axis can have a size that's a different power of two. * The [`Simple2D`](@ref) algorithm doesn't need to know how large the axes may be before you use it, but it only works in 2D. * The [`GlobalGray`](@ref) algorithm is fast for an n-dimensional algorithm. * The [`FaceContinuous`](@ref) algorithm is slower and is included because it has a different shape and is historically important as the first non-recursive n-dimensional algorithm. In general, algorithms that are written explicitly for 2D are faster than n-dimensional equivalents. ## Other work around Hilbert curves This library provides two functions for each algorithm, one to encode and one to decode. There is considerable work around making more-efficient queries of data stored in Hilbert order. These algorithms take a single Hilbert index and return the Hilbert index in any coordinate direction. They don't need to convert to coordinates, find the neighbor in that space, and convert back to the Hilbert index. There is also work to make rectangular queries faster, in general. These find sequences of Hilbert indexes that fall within a rectangular region in coordinate space. None of those are implemented here. They would be useful for advanced database work.
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
docs
2048
# BijectiveHilbert Data in two or more dimensions is stored linearly, so places nearby in the data can be far in memory or on disk. This package offers functions that make multi-dimensional data storage and retrieval more efficient by sorting them so that nearby data is nearby in memory. ```julia julia> using Pkg; Pkg.add("BijectiveHilbert") julia> using BijectiveHilbert julia> xy = zeros(Int, 8, 8) julia> for y in 1:size(xy, 2) for x in 1:size(xy, 1) z = encode_hilbert(Simple2D(Int), [x, y]) xy[x, y] = z end end julia> X = zeros(Int, 2) julia> decode_hilbert!(Simple2D(Int), X, xy[5, 7]) julia> X == [5, 7] julia> xy 8×8 Array{Int64,2}: 1 2 15 16 17 20 21 22 4 3 14 13 18 19 24 23 5 8 9 12 31 30 25 26 6 7 10 11 32 29 28 27 59 58 55 54 33 36 37 38 60 57 56 53 34 35 40 39 61 62 51 52 47 46 41 42 64 63 50 49 48 45 44 43 ``` This function, called a [Hilbert curve](https://en.wikipedia.org/wiki/Hilbert_curve), is used most often for geospatial work or database implementation but is equally appropriate for dealing with large TIFF files. It belongs to the class of space-filling, self-avoiding, simple, and self-similar (FASS) curves, which includes Peano curves, and Morton z-curves. Included are several variations of the Hilbert curve. They are type-stable and thoroughly tested, including bug fixes on three of the implementations. * [`Simple2D`](@ref), shown above, two-dimensional. Doesn't need to know axis dimensions, from Chen, Wang, and Shi. * [`GlobalGray`](@ref), an n-dimensional curve where all axis dimensions must be equal, from Skilling. * [`SpaceGray`](@ref), an n-dimensional curve with a different path. All axis dimensions must be equal, from Hamilton and Rau-Chaplin. * [`Compact`](@ref), an n-dimensional curve the permits each axis to be a different size, from Hamilton and Rau-Chaplin. * [`FaceContinuous`](@ref), an n-dimensional curve, the oldest version from Butz and Lawder.
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
docs
705
# Simple2D If you want to sort some axes, then this Hilbert curve algorithm is the easiest to use. It doesn't need to know ahead of time how many bits it will need to generate a Hilbert index [^1]. As the length along each spatial axis grows, it creates gradually larger Hilbert indices to match it. All of the algorithms use slightly different Hilbert curves. This one uses an asymmetric curve that shifts so that its endpoint is always an outside corder of each ``2^n`` x ``2^n`` tile. The next outer layer builds on the last. [^1]: Chen, Ningtau; Wang, Nengchao; Shi, Baochang, "A new algorithm for encoding and decoding the Hilbert order," in Software---Practice and Experience, 2007, 37, 897-908.
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.3.0
c41395f963963f3352d789e0103915ce8ad0db61
docs
2947
```@meta CurrentModule = BijectiveHilbert ``` # Usage All of the Hilbert algorithms have the same interface. ## Decide dimensions of the spatial axes All of the algorithms, except [`Simple2D`](@ref), need to know ahead of time the extent of the coordinate system. If the Hilbert curve will be in a 32 x 32 space, then the dimension is 2, and it needs `log2(32)=5` bits of resolution in both directions. For [`GlobalGray`](@ref), that's `b=5`, `n=2`. If the sizes aren't powers of two or are uneven, then set the bits to cover the largest side, so (12 x 12 x 12 x 800) would be `b=10`, `n=4` because ``800 < 2^{10}``. There is one algorithm that deals better with uneven sides. The [`Compact`](@ref) algorithm can pack bits together so that the resulting Hilbert index takes less storage space. This is usually used for database storage. It could take (12 x 12 x 12 x 800) as `Compact([4, 4, 4, 10])` which results in a 24-bit integer that can be stored in a UInt32. ## Create an algorithm For most Hilbert curve algorithms, you have to say, beforehand, how large the multidimensional coordinates are, in powers of two. For instance, a three-dimensional grid can have values from 1 to 16 in each dimension, so `n = 3` and `b = 4` because `16 = 2^b`. ```julia using BijectiveHilbert dimensions = 3 bits = 4 simple = Simple2D(Int) gg = GlobalGray(UInt, bits, dimensions) sg = SpaceGray(UInt, bits, dimensions) compact = Compact(UInt, fill(bits, dimensions)) ``` The first argument is a datatype for the Hilbert index. It should be large enough to hold all of the bits from the n-dimensional axes. If you don't specify one, it will use the smallest unsigned integer that can hold them. Note that the [`Compact`](@ref) algorithm can have different sizes for each dimension, but they are all powers of two. It produces a Hilbert index that uses only as many bits as necessary. ## Encode and decode You can encode from n-dimensions to the Hilbert index, or you can decode from a Hilbert index to n-dimensions. ```julia for algorithm in [simple, gg, sg, compact] for k in 1:(1<<bits) for j in 1:(1<<bits) for i in 1:(1<<bits) X = [i, j, k] h = encode_hilbert(algorithm, X) X .= 0 decode_hilbert!(algorithm, X, h) end end end end ``` ## Encode and decode with a zero-based value The underlying algorithms use a zero-based axis and a zero-based Hilbert index. These are available, too. ```julia for algorithm in [simple, gg, sg, compact] for k in 0:(1<<bits - 1) for j in 0:(1<<bits - 1) for i in 0:(1<<bits - 1) X = [i, j, k] h = encode_hilbert_zero(algorithm, X) X .= 0 decode_hilbert_zero!(algorithm, X, h) end end end end ``` # Index ```@index ``` ```@autodocs Modules = [BijectiveHilbert] Private = false ```
BijectiveHilbert
https://github.com/adolgert/BijectiveHilbert.jl.git
[ "MIT" ]
0.1.0
636d4f898c96dbdb27411cbdba0ffcd3a2313d60
code
469
module JupyterFormatter using IJulia using JuliaFormatter function format_current_cell() current_cell = IJulia.In[IJulia.n] formatted = JuliaFormatter.format_text(current_cell) if formatted != current_cell IJulia.load_string(formatted, true) end end enable_autoformat() = IJulia.push_preexecute_hook(format_current_cell) disable_autoformat() = IJulia.pop_preexecute_hook(format_current_cell) export enable_autoformat, disable_autoformat end
JupyterFormatter
https://github.com/jlamberts/JupyterFormatter.jl.git
[ "MIT" ]
0.1.0
636d4f898c96dbdb27411cbdba0ffcd3a2313d60
code
371
using JupyterFormatter using IJulia using Test @testset "UnitTests" begin # test that we succesfully add and remove our formatting hook starting_hooks = length(IJulia.preexecute_hooks) enable_autoformat() @test length(IJulia.preexecute_hooks) == starting_hooks + 1 disable_autoformat() @test length(IJulia.preexecute_hooks) == starting_hooks end
JupyterFormatter
https://github.com/jlamberts/JupyterFormatter.jl.git
[ "MIT" ]
0.1.0
636d4f898c96dbdb27411cbdba0ffcd3a2313d60
docs
1428
# JupyterFormatter.jl A simple package to add [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl) autoformatting support to Jupyter lab and notebooks running [IJulia.](https://github.com/JuliaLang/IJulia.jl) Inspired by my favorite Jupyter extension, [nb_black.](https://github.com/dnanhkhoa/nb_black) ## Usage In your notebook, ```julia using JupyterFormatter enable_autoformat() ``` Afterwards, whenever you run a cell, it will automatically be formatted. If you want to turn off auto-formatting, run ``` disable_autoformat() ``` ## Jupyter Notebook and Lab Compatibility While this package works with both legacy Jupyter Notebooks and Jupyter Lab, it does have some issues in Jupyter Notebooks. **On legacy notebooks only**, when a cell is formatted its output will be suppressed and it will lose its `In[]` and `Out[]`. This will only happen if the cell is not already formatted properly. For example, running this already-formatted cell will output as normal: ![Running With Formatted Cell](assets/preformatted_works_properly.png) However, running this unformatted cell will not print properly; running this cell ![Running With Formatted Cell](assets/unformatted_will_suppress.png) Results in this formatted cell with no output ![Running With Formatted Cell](assets/unformatted_suppresses_output.png) It is recommended that you run in Jupyter Lab if possible, since it does not have this issue.
JupyterFormatter
https://github.com/jlamberts/JupyterFormatter.jl.git
[ "MIT" ]
0.3.3
97780f3c70deeb128526e31238b958f7acbe4ada
code
2419
""" Sorting networks for 1,2,..16 and 17,18..25 values are given. These sorting networks should minimize conditional swaps. The first sixteen are known to minimize conditional swaps. Functions are a sequence of internally parallelizable blocks. Functions are written using empty lines as block delmiters. `swapsort(x1::T, .., xn::T)::NTuple{n,T}` `swapsort(tup::NTuple{n,T})::NTuple{n,T}` """ module SortingNetworks export swapsort, ExchangeSort """ ExchangeSort Indicate that a sorting function should use the exchange sort algorithm. Exchange sort orders elements pairwise, over groups that are accessible in parallel. At the conclusion of the application of the relevant sorting network, each element is positioned in its correct, sorted postion in the output. Characteristics: * *stable*: preserves the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case). * *in-place* in memory. * *quadratic performance* in the number of elements to be sorted: it is well-suited to small collections but should not be used for large ones. """ struct ExchangeSortAlg <: Base.Sort.Algorithm end const ExchangeSort = ExchangeSortAlg() const MIN_MAX = :boolean # {:boolean, :ifelse, :minmax, :lessthan} if MIN_MAX == :boolean @inline function min_max(a::T, b::T) where {T<:Real} return (b < a ? (b, a) : (a, b)) end @inline function max_min(a::T, b::T) where {T<:Real} return (b < a ? (a, b) : (b, a)) end elseif MIN_MAX == :ifelse @inline function min_max(a::T, b::T) where {T<:Real} return ifelse(b < a, (b, a), (a, b)) end @inline function max_min(a::T, b::T) where {T<:Real} return ifelse(b < a, (a, b), (b, a)) end elseif MIN_MAX == :minmax @inline function min_max(a::T, b::T) where {T<:Real} return min(a,b), max(a,b) end @inline function max_min(a::T, b::T) where {T<:Real} return max(a,b), min(a,b) end elseif MIN_MAX == :lessthan @inline function min_max(a::T, b::T) where {T} a<b && return (a,b) return (b,a) end @inline function max_min(a::T, b::T) where {T} a<b && return (b,a) return (a,b) end end const ITEMS_MAX = 25 include("swapsort.jl") include("swapsort_17to25.jl") include("swapsortr.jl") include("swapsortr_17to25.jl") end # module
SortingNetworks
https://github.com/JeffreySarnoff/SortingNetworks.jl.git
[ "MIT" ]
0.3.3
97780f3c70deeb128526e31238b958f7acbe4ada
code
18260
#= Sorting networks that process 1,2,..16 values are given. Sorting networks that process 17..25 values are given in "swapsort_17to25.jl". These sorting networks should minimize conditional swaps. The first sixteen are known to minimize conditional swaps. Functions are written with groups of internally parallelizable statements given together and sequential steps are separated. `swapsort(x1::T, .., xn::T)::NTuple{n,T}` `swapsort(tup::NTuple{n,T})::NTuple{n,T}` `swapsort(vec::AbstractVector{T})::NTuple{N,T}` networks were selected using software by John Gamble http://pages.ripco.net/~jgamble/nw.html http://search.cpan.org/dist/Algorithm-Networksort/ =# const VALS = ([Val{i} for i=1:ITEMS_MAX]...,) @inline function swapsort(vec::AbstractVector{T}) where {T} n = length(vec) n > ITEMS_MAX && throw(ErrorException("swapsort(vector) not defined where length(vector) > $ITEMS_MAX")) return swapsort(VALS[length(vec)], vec) end # sort 1 value with 0 minmaxs in 1 stage function swapsort(a::T) where {T} return (a,) end @inline swapsort(x::NTuple{1,T}) where {T} = swapsort(x[1]) @inline swapsort(::Type{Val{1}}, x::AbstractVector{T}) where {T} = swapsort(x[1]) # sort 2 values with 1 minmaxs in 1 stage function swapsort(a::T, b::T) where {T} a, b = min_max(a, b) return a,b end @inline swapsort(x::NTuple{2,T}) where {T} = swapsort(x[1], x[2]) @inline swapsort(::Type{Val{2}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2]) # sort 3 values with 3 minmaxs in 3 parallel stages function swapsort(a::T, b::T, c::T) where {T} b, c = min_max(b, c) a, c = min_max(a, c) a, b = min_max(a, b) return a, b, c end @inline swapsort(x::NTuple{3,T}) where {T} = swapsort(x[1], x[2], x[3]) @inline swapsort(::Type{Val{3}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3]) # sort 4 values with 5 minmaxs in 3 parallel stages function swapsort(a::T, b::T, c::T, d::T) where {T} a, b = min_max(a, b) c, d = min_max(c, d) a, c = min_max(a, c) b, d = min_max(b, d) b, c = min_max(b, c) return a, b, c, d end @inline swapsort(x::NTuple{4,T}) where {T} = swapsort(x[1], x[2], x[3], x[4]) @inline swapsort(::Type{Val{4}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4]) # sort 5 values with 9 minmaxs in 5 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T) where {T} b, c = min_max(b, c) d, e = min_max(d, e) b, d = min_max(b, d) a, c = min_max(a, c) c, e = min_max(c, e) a, d = min_max(a, d) a, b = min_max(a, b) c, d = min_max(c, d) b, c = min_max(b, c) return a, b, c, d, e end @inline swapsort(x::NTuple{5,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5]) @inline swapsort(::Type{Val{5}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5]) # sort 6 values with 12 minmaxs in 6 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T) where {T} b, c = min_max(b, c) e, f = min_max(e, f) a, c = min_max(a, c) d, f = min_max(d, f) a, b = min_max(a, b) d, e = min_max(d, e) c, f = min_max(c, f) a, d = min_max(a, d) b, e = min_max(b, e) c, e = min_max(c, e) b, d = min_max(b, d) c, d = min_max(c, d) return a, b, c, d, e, f end @inline swapsort(x::NTuple{6,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6]) @inline swapsort(::Type{Val{6}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6]) # sort 7 values with 16 minmaxs in 6 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T) where {T} a, e = min_max(a, e) b, f = min_max(b, f) c, g = min_max(c, g) a, c = min_max(a, c) b, d = min_max(b, d) e, g = min_max(e, g) c, e = min_max(c, e) d, f = min_max(d, f) a, b = min_max(a, b) c, d = min_max(c, d) e, f = min_max(e, f) b, e = min_max(b, e) d, g = min_max(d, g) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) return a, b, c, d, e, f, g end @inline swapsort(x::NTuple{7,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7]) @inline swapsort(::Type{Val{7}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7]) # sort 8 values with 19 minmaxs in 7 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T) where {T} a, b = min_max(a, b) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) a, c = min_max(a, c) b, d = min_max(b, d) e, g = min_max(e, g) f, h = min_max(f, h) b, c = min_max(b, c) f, g = min_max(f, g) a, e = min_max(a, e) d, h = min_max(d, h) b, f = min_max(b, f) c, g = min_max(c, g) b, e = min_max(b, e) d, g = min_max(d, g) c, e = min_max(c, e) d, f = min_max(d, f) d, e = min_max(d, e) return a, b, c, d, e, f, g, h end @inline swapsort(x::NTuple{8,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8]) @inline swapsort(::Type{Val{8}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8]) # sort 9 values with 25 minmaxs in 9 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T) where {T} a, b = min_max(a, b) d, e = min_max(d, e) g, h = min_max(g, h) b, c = min_max(b, c) e, f = min_max(e, f) h, i = min_max(h, i) a, b = min_max(a, b) d, e = min_max(d, e) g, h = min_max(g, h) c, f = min_max(c, f) a, d = min_max(a, d) b, e = min_max(b, e) f, i = min_max(f, i) d, g = min_max(d, g) e, h = min_max(e, h) c, f = min_max(c, f) a, d = min_max(a, d) b, e = min_max(b, e) f, h = min_max(f, h) c, g = min_max(c, g) b, d = min_max(b, d) e, g = min_max(e, g) c, e = min_max(c, e) f, g = min_max(f, g) c, d = min_max(c, d) return a, b, c, d, e, f, g, h, i end @inline swapsort(x::NTuple{9,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9]) @inline swapsort(::Type{Val{9}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9]) # sort 10 values with 29 minmaxs in 9 parallel stages function swapsort(a::T,b::T,c::T,d::T,e::T, f::T,g::T,h::T,i::T,j::T) where {T} e, j = min_max(e, j) d, i = min_max(d, i) c, h = min_max(c, h) b, g = min_max(b, g) a, f = min_max(a, f) b, e = min_max(b, e) g, j = min_max(g, j) a, d = min_max(a, d) f, i = min_max(f, i) a, c = min_max(a, c) d, g = min_max(d, g) h, j = min_max(h, j) a, b = min_max(a, b) c, e = min_max(c, e) f, h = min_max(f, h) i, j = min_max(i, j) b, c = min_max(b, c) e, g = min_max(e, g) h, i = min_max(h, i) d, f = min_max(d, f) c, f = min_max(c, f) g, i = min_max(g, i) b, d = min_max(b, d) e, h = min_max(e, h) c, d = min_max(c, d) g, h = min_max(g, h) d, e = min_max(d, e) f, g = min_max(f, g) e, f = min_max(e, f) return a,b,c,d,e,f,g,h,i,j end @inline swapsort(x::NTuple{10,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10]) @inline swapsort(::Type{Val{10}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10]) # sort 11 values with 35 minmaxs in 9 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T) where {T} a, b = min_max(a, b) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) b, d = min_max(b, d) f, h = min_max(f, h) a, c = min_max(a, c) e, g = min_max(e, g) i, k = min_max(i, k) b, c = min_max(b, c) f, g = min_max(f, g) j, k = min_max(j, k) a, e = min_max(a, e) d, h = min_max(d, h) b, f = min_max(b, f) g, k = min_max(g, k) e, i = min_max(e, i) f, j = min_max(f, j) c, g = min_max(c, g) a, e = min_max(a, e) d, i = min_max(d, i) b, f = min_max(b, f) g, k = min_max(g, k) c, d = min_max(c, d) i, j = min_max(i, j) b, e = min_max(b, e) h, k = min_max(h, k) d, f = min_max(d, f) g, i = min_max(g, i) c, e = min_max(c, e) h, j = min_max(h, j) f, g = min_max(f, g) d, e = min_max(d, e) h, i = min_max(h, i) return a,b,c,d,e,f,g,h,i,j,k end @inline swapsort(x::NTuple{11,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11]) @inline swapsort(::Type{Val{11}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11]) # sort 12 values with 39 minmaxs in 9 parallel stages function swapsort(a::T,b::T,c::T,d::T,e::T, f::T,g::T,h::T,i::T,j::T, k::T,l::T) where {T} a, b = min_max(a, b) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) b, d = min_max(b, d) f, h = min_max(f, h) j, l = min_max(j, l) a, c = min_max(a, c) e, g = min_max(e, g) i, k = min_max(i, k) b, c = min_max(b, c) f, g = min_max(f, g) j, k = min_max(j, k) a, e = min_max(a, e) h, l = min_max(h, l) b, f = min_max(b, f) g, k = min_max(g, k) d, h = min_max(d, h) e, i = min_max(e, i) f, j = min_max(f, j) c, g = min_max(c, g) a, e = min_max(a, e) h, l = min_max(h, l) d, i = min_max(d, i) b, f = min_max(b, f) g, k = min_max(g, k) c, d = min_max(c, d) i, j = min_max(i, j) b, e = min_max(b, e) h, k = min_max(h, k) d, f = min_max(d, f) g, i = min_max(g, i) c, e = min_max(c, e) h, j = min_max(h, j) f, g = min_max(f, g) d, e = min_max(d, e) h, i = min_max(h, i) return a,b,c,d,e,f,g,h,i,j,k,l end @inline swapsort(x::NTuple{12,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12]) @inline swapsort(::Type{Val{12}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12]) # sort 13 values with 45 minmaxs in 10 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T) where {T} b, h = min_max(b, h) j, l = min_max(j, l) d, e = min_max(d, e) f, i = min_max(f, i) a, m = min_max(a, m) c, g = min_max(c, g) a, b = min_max(a, b) c, d = min_max(c, d) e, g = min_max(e, g) i, l = min_max(i, l) h, m = min_max(h, m) f, j = min_max(f, j) a, c = min_max(a, c) d, h = min_max(d, h) k, l = min_max(k, l) b, e = min_max(b, e) g, m = min_max(g, m) h, i = min_max(h, i) l, m = min_max(l, m) e, j = min_max(e, j) g, k = min_max(g, k) d, e = min_max(d, e) f, g = min_max(f, g) i, j = min_max(i, j) k, l = min_max(k, l) b, h = min_max(b, h) c, g = min_max(c, g) j, l = min_max(j, l) b, d = min_max(b, d) e, h = min_max(e, h) i, k = min_max(i, k) a, f = min_max(a, f) c, f = min_max(c, f) g, i = min_max(g, i) j, k = min_max(j, k) b, c = min_max(b, c) d, f = min_max(d, f) h, i = min_max(h, i) e, g = min_max(e, g) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) d, e = min_max(d, e) f, g = min_max(f, g) return a,b,c,d,e,f,g,h,i,j,k,l,m end @inline swapsort(x::NTuple{13,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13]) @inline swapsort(::Type{Val{13}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13]) # sort 14 values with 51 minmaxs in 10 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T) where {T} a, b = min_max(a, b) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) a, c = min_max(a, c) e, g = min_max(e, g) i, k = min_max(i, k) b, d = min_max(b, d) f, h = min_max(f, h) j, l = min_max(j, l) a, e = min_max(a, e) i, m = min_max(i, m) b, f = min_max(b, f) j, n = min_max(j, n) c, g = min_max(c, g) d, h = min_max(d, h) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) f, k = min_max(f, k) g, j = min_max(g, j) d, m = min_max(d, m) h, l = min_max(h, l) b, c = min_max(b, c) e, i = min_max(e, i) b, e = min_max(b, e) h, n = min_max(h, n) c, i = min_max(c, i) f, g = min_max(f, g) j, k = min_max(j, k) c, e = min_max(c, e) l, n = min_max(l, n) d, i = min_max(d, i) h, m = min_max(h, m) g, i = min_max(g, i) k, m = min_max(k, m) d, f = min_max(d, f) h, j = min_max(h, j) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) g, h = min_max(g, h) i, j = min_max(i, j) return a,b,c,d,e,f,g,h,i,j,k,l,m,n end @inline swapsort(x::NTuple{14,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14]) @inline swapsort(::Type{Val{14}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14]) # sort 15 values with 56 minmaxs in 10 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T) where {T} a, b = min_max(a, b) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) a, c = min_max(a, c) e, g = min_max(e, g) i, k = min_max(i, k) m, o = min_max(m, o) b, d = min_max(b, d) f, h = min_max(f, h) j, l = min_max(j, l) a, e = min_max(a, e) i, m = min_max(i, m) b, f = min_max(b, f) j, n = min_max(j, n) c, g = min_max(c, g) k, o = min_max(k, o) d, h = min_max(d, h) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) g, o = min_max(g, o) f, k = min_max(f, k) g, j = min_max(g, j) d, m = min_max(d, m) n, o = min_max(n, o) h, l = min_max(h, l) b, c = min_max(b, c) e, i = min_max(e, i) b, e = min_max(b, e) h, n = min_max(h, n) c, i = min_max(c, i) l, o = min_max(l, o) f, g = min_max(f, g) j, k = min_max(j, k) c, e = min_max(c, e) l, n = min_max(l, n) d, i = min_max(d, i) h, m = min_max(h, m) g, i = min_max(g, i) k, m = min_max(k, m) d, f = min_max(d, f) h, j = min_max(h, j) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) g, h = min_max(g, h) i, j = min_max(i, j) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o end @inline swapsort(x::NTuple{15,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15]) @inline swapsort(::Type{Val{15}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15]) # sort 16 values with 60 minmaxs in 10 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T) where {T} a, b = min_max(a, b) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) a, c = min_max(a, c) e, g = min_max(e, g) i, k = min_max(i, k) m, o = min_max(m, o) b, d = min_max(b, d) f, h = min_max(f, h) j, l = min_max(j, l) n, p = min_max(n, p) a, e = min_max(a, e) i, m = min_max(i, m) b, f = min_max(b, f) j, n = min_max(j, n) c, g = min_max(c, g) k, o = min_max(k, o) d, h = min_max(d, h) l, p = min_max(l, p) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) g, o = min_max(g, o) h, p = min_max(h, p) f, k = min_max(f, k) g, j = min_max(g, j) d, m = min_max(d, m) n, o = min_max(n, o) h, l = min_max(h, l) b, c = min_max(b, c) e, i = min_max(e, i) b, e = min_max(b, e) h, n = min_max(h, n) c, i = min_max(c, i) l, o = min_max(l, o) f, g = min_max(f, g) j, k = min_max(j, k) c, e = min_max(c, e) l, n = min_max(l, n) d, i = min_max(d, i) h, m = min_max(h, m) g, i = min_max(g, i) k, m = min_max(k, m) d, f = min_max(d, f) h, j = min_max(h, j) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) g, h = min_max(g, h) i, j = min_max(i, j) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p end @inline swapsort(x::NTuple{16,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16]) @inline swapsort(::Type{Val{16}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16])
SortingNetworks
https://github.com/JeffreySarnoff/SortingNetworks.jl.git
[ "MIT" ]
0.3.3
97780f3c70deeb128526e31238b958f7acbe4ada
code
28341
#= Sorting networks that process 17,..25 values are given. These sorting networks should minimize conditional swaps. There may exist one or more comparable alternative solutions; those may perform marginally better for some kinds of hardware. Functions are written with groups of internally paralleli1zable statements given together and sequential steps are separated. `swapsort(x1::T, .., xn::T)::NTuple{n,T}` `swapsort(tup::NTuple{n,T})::NTuple{n,T}` networks were selected using software by John Gamble http://pages.ripco.net/~jgamble/nw.html http://search.cpan.org/dist/Algorithm-Networksort/ =# const MORE_ARGS_MIN = 18 const MORE_ARGS_MAX = 25 #= sort NTuples of 17..25 values =# @inline swapsort(x::NTuple{17,T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16], x[17]) @inline swapsort(::Type{Val{17}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16], x[17]) for N in collect(MORE_ARGS_MIN:MORE_ARGS_MAX) @eval swapsort(x::NTuple{$N, T}) where T = swapsort(x...) end #= sorting networks for 17..25 values using known compact realizations =# # sort 17 values with 74 minmaxs in 12 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T) where {T} a, q = min_max(a, q) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) g, o = min_max(g, o) h, p = min_max(h, p) a, i = min_max(a, i) b, f = min_max(b, f) c, g = min_max(c, g) d, h = min_max(d, h) j, n = min_max(j, n) k, o = min_max(k, o) l, p = min_max(l, p) i, q = min_max(i, q) a, e = min_max(a, e) f, j = min_max(f, j) g, k = min_max(g, k) h, l = min_max(h, l) b, d = min_max(b, d) n, p = min_max(n, p) i, m = min_max(i, m) e, q = min_max(e, q) a, c = min_max(a, c) f, h = min_max(f, h) j, l = min_max(j, l) e, i = min_max(e, i) m, q = min_max(m, q) d, j = min_max(d, j) h, n = min_max(h, n) a, b = min_max(a, b) e, g = min_max(e, g) i, k = min_max(i, k) m, o = min_max(m, o) c, q = min_max(c, q) d, f = min_max(d, f) h, j = min_max(h, j) l, n = min_max(l, n) c, i = min_max(c, i) g, m = min_max(g, m) k, q = min_max(k, q) c, e = min_max(c, e) g, i = min_max(g, i) k, m = min_max(k, m) o, q = min_max(o, q) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) b, q = min_max(b, q) b, i = min_max(b, i) d, k = min_max(d, k) f, m = min_max(f, m) h, o = min_max(h, o) j, q = min_max(j, q) b, e = min_max(b, e) d, g = min_max(d, g) f, i = min_max(f, i) h, k = min_max(h, k) j, m = min_max(j, m) l, o = min_max(l, o) n, q = min_max(n, q) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) n, o = min_max(n, o) p, q = min_max(p, q) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q end @inline swapsort(::Type{Val{17}}, x::AbstractVector{T}) where {T} = swapsort(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16], x[17]) # sort 18 values with 82 minmaxs in 13 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T) where {T} a, q = min_max(a, q) b, r = min_max(b, r) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) g, o = min_max(g, o) h, p = min_max(h, p) a, i = min_max(a, i) b, j = min_max(b, j) c, g = min_max(c, g) d, h = min_max(d, h) k, o = min_max(k, o) l, p = min_max(l, p) i, q = min_max(i, q) j, r = min_max(j, r) a, e = min_max(a, e) b, f = min_max(b, f) g, k = min_max(g, k) h, l = min_max(h, l) i, m = min_max(i, m) j, n = min_max(j, n) e, q = min_max(e, q) f, r = min_max(f, r) a, c = min_max(a, c) b, d = min_max(b, d) e, i = min_max(e, i) f, j = min_max(f, j) m, q = min_max(m, q) n, r = min_max(n, r) a, b = min_max(a, b) e, g = min_max(e, g) f, h = min_max(f, h) i, k = min_max(i, k) j, l = min_max(j, l) m, o = min_max(m, o) n, p = min_max(n, p) c, q = min_max(c, q) d, r = min_max(d, r) c, i = min_max(c, i) d, j = min_max(d, j) g, m = min_max(g, m) h, n = min_max(h, n) k, q = min_max(k, q) l, r = min_max(l, r) c, e = min_max(c, e) d, f = min_max(d, f) g, i = min_max(g, i) h, j = min_max(h, j) k, m = min_max(k, m) l, n = min_max(l, n) o, q = min_max(o, q) p, r = min_max(p, r) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) q, r = min_max(q, r) b, q = min_max(b, q) d, k = min_max(d, k) f, m = min_max(f, m) h, o = min_max(h, o) b, i = min_max(b, i) j, q = min_max(j, q) d, g = min_max(d, g) h, k = min_max(h, k) l, o = min_max(l, o) b, e = min_max(b, e) f, i = min_max(f, i) j, m = min_max(j, m) n, q = min_max(n, q) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) n, o = min_max(n, o) p, q = min_max(p, q) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r end # sort 19 values with 91 minmaxs in 14 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T) where {T} a, q = min_max(a, q) b, r = min_max(b, r) c, s = min_max(c, s) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) g, o = min_max(g, o) h, p = min_max(h, p) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, h = min_max(d, h) l, p = min_max(l, p) i, q = min_max(i, q) j, r = min_max(j, r) k, s = min_max(k, s) a, e = min_max(a, e) b, f = min_max(b, f) c, g = min_max(c, g) h, l = min_max(h, l) i, m = min_max(i, m) j, n = min_max(j, n) k, o = min_max(k, o) e, q = min_max(e, q) f, r = min_max(f, r) g, s = min_max(g, s) a, c = min_max(a, c) b, d = min_max(b, d) e, i = min_max(e, i) f, j = min_max(f, j) g, k = min_max(g, k) m, q = min_max(m, q) n, r = min_max(n, r) o, s = min_max(o, s) a, b = min_max(a, b) e, g = min_max(e, g) f, h = min_max(f, h) i, k = min_max(i, k) j, l = min_max(j, l) m, o = min_max(m, o) n, p = min_max(n, p) q, s = min_max(q, s) d, r = min_max(d, r) c, q = min_max(c, q) d, j = min_max(d, j) g, m = min_max(g, m) h, n = min_max(h, n) l, r = min_max(l, r) c, i = min_max(c, i) k, q = min_max(k, q) d, f = min_max(d, f) h, j = min_max(h, j) l, n = min_max(l, n) p, r = min_max(p, r) c, e = min_max(c, e) g, i = min_max(g, i) k, m = min_max(k, m) o, q = min_max(o, q) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) q, r = min_max(q, r) b, q = min_max(b, q) d, s = min_max(d, s) f, m = min_max(f, m) h, o = min_max(h, o) b, i = min_max(b, i) d, k = min_max(d, k) j, q = min_max(j, q) l, s = min_max(l, s) b, e = min_max(b, e) d, g = min_max(d, g) f, i = min_max(f, i) h, k = min_max(h, k) j, m = min_max(j, m) l, o = min_max(l, o) n, q = min_max(n, q) p, s = min_max(p, s) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) n, o = min_max(n, o) p, q = min_max(p, q) r, s = min_max(r, s) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s end # sort 20 values with 97 minmaxs in 14 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T) where {T} a, q = min_max(a, q) b, r = min_max(b, r) c, s = min_max(c, s) d, t = min_max(d, t) e, m = min_max(e, m) f, n = min_max(f, n) g, o = min_max(g, o) h, p = min_max(h, p) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) i, q = min_max(i, q) j, r = min_max(j, r) k, s = min_max(k, s) l, t = min_max(l, t) a, e = min_max(a, e) b, f = min_max(b, f) c, g = min_max(c, g) d, h = min_max(d, h) i, m = min_max(i, m) j, n = min_max(j, n) k, o = min_max(k, o) l, p = min_max(l, p) e, q = min_max(e, q) f, r = min_max(f, r) g, s = min_max(g, s) h, t = min_max(h, t) a, c = min_max(a, c) b, d = min_max(b, d) e, i = min_max(e, i) f, j = min_max(f, j) g, k = min_max(g, k) h, l = min_max(h, l) m, q = min_max(m, q) n, r = min_max(n, r) o, s = min_max(o, s) p, t = min_max(p, t) a, b = min_max(a, b) e, g = min_max(e, g) f, h = min_max(f, h) i, k = min_max(i, k) j, l = min_max(j, l) m, o = min_max(m, o) n, p = min_max(n, p) q, s = min_max(q, s) r, t = min_max(r, t) c, q = min_max(c, q) d, r = min_max(d, r) g, m = min_max(g, m) h, n = min_max(h, n) s, t = min_max(s, t) c, i = min_max(c, i) d, j = min_max(d, j) k, q = min_max(k, q) l, r = min_max(l, r) c, e = min_max(c, e) d, f = min_max(d, f) g, i = min_max(g, i) h, j = min_max(h, j) k, m = min_max(k, m) l, n = min_max(l, n) o, q = min_max(o, q) p, r = min_max(p, r) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) q, r = min_max(q, r) b, q = min_max(b, q) d, s = min_max(d, s) f, m = min_max(f, m) h, o = min_max(h, o) b, i = min_max(b, i) d, k = min_max(d, k) j, q = min_max(j, q) l, s = min_max(l, s) b, e = min_max(b, e) d, g = min_max(d, g) f, i = min_max(f, i) h, k = min_max(h, k) j, m = min_max(j, m) l, o = min_max(l, o) n, q = min_max(n, q) p, s = min_max(p, s) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) n, o = min_max(n, o) p, q = min_max(p, q) r, s = min_max(r, s) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t end # sort 21 values with 107 minmaxs in 15 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T) where {T} a, q = min_max(a, q) b, r = min_max(b, r) c, s = min_max(c, s) d, t = min_max(d, t) e, u = min_max(e, u) f, n = min_max(f, n) g, o = min_max(g, o) h, p = min_max(h, p) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) i, q = min_max(i, q) j, r = min_max(j, r) k, s = min_max(k, s) l, t = min_max(l, t) m, u = min_max(m, u) a, e = min_max(a, e) b, f = min_max(b, f) c, g = min_max(c, g) d, h = min_max(d, h) i, m = min_max(i, m) j, n = min_max(j, n) k, o = min_max(k, o) l, p = min_max(l, p) q, u = min_max(q, u) f, r = min_max(f, r) g, s = min_max(g, s) h, t = min_max(h, t) a, c = min_max(a, c) b, d = min_max(b, d) e, q = min_max(e, q) f, j = min_max(f, j) g, k = min_max(g, k) h, l = min_max(h, l) n, r = min_max(n, r) o, s = min_max(o, s) p, t = min_max(p, t) a, b = min_max(a, b) e, i = min_max(e, i) m, q = min_max(m, q) f, h = min_max(f, h) j, l = min_max(j, l) n, p = min_max(n, p) r, t = min_max(r, t) e, g = min_max(e, g) i, k = min_max(i, k) m, o = min_max(m, o) q, s = min_max(q, s) d, r = min_max(d, r) h, n = min_max(h, n) c, q = min_max(c, q) g, u = min_max(g, u) d, j = min_max(d, j) l, r = min_max(l, r) c, i = min_max(c, i) g, m = min_max(g, m) k, q = min_max(k, q) o, u = min_max(o, u) d, f = min_max(d, f) h, j = min_max(h, j) l, n = min_max(l, n) p, r = min_max(p, r) c, e = min_max(c, e) g, i = min_max(g, i) k, m = min_max(k, m) o, q = min_max(o, q) s, u = min_max(s, u) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) q, r = min_max(q, r) s, t = min_max(s, t) b, q = min_max(b, q) d, s = min_max(d, s) f, u = min_max(f, u) h, o = min_max(h, o) b, i = min_max(b, i) d, k = min_max(d, k) f, m = min_max(f, m) j, q = min_max(j, q) l, s = min_max(l, s) n, u = min_max(n, u) b, e = min_max(b, e) d, g = min_max(d, g) f, i = min_max(f, i) h, k = min_max(h, k) j, m = min_max(j, m) l, o = min_max(l, o) n, q = min_max(n, q) p, s = min_max(p, s) r, u = min_max(r, u) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) n, o = min_max(n, o) p, q = min_max(p, q) r, s = min_max(r, s) t, u = min_max(t, u) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u end # sort 22 values with 114 minmaxs in 15 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T, v::T) where {T} a, q = min_max(a, q) b, r = min_max(b, r) c, s = min_max(c, s) d, t = min_max(d, t) e, u = min_max(e, u) f, v = min_max(f, v) g, o = min_max(g, o) h, p = min_max(h, p) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) i, q = min_max(i, q) j, r = min_max(j, r) k, s = min_max(k, s) l, t = min_max(l, t) m, u = min_max(m, u) n, v = min_max(n, v) a, e = min_max(a, e) b, f = min_max(b, f) c, g = min_max(c, g) d, h = min_max(d, h) i, m = min_max(i, m) j, n = min_max(j, n) k, o = min_max(k, o) l, p = min_max(l, p) q, u = min_max(q, u) r, v = min_max(r, v) g, s = min_max(g, s) h, t = min_max(h, t) a, c = min_max(a, c) b, d = min_max(b, d) e, q = min_max(e, q) f, r = min_max(f, r) g, k = min_max(g, k) h, l = min_max(h, l) o, s = min_max(o, s) p, t = min_max(p, t) a, b = min_max(a, b) e, i = min_max(e, i) f, j = min_max(f, j) m, q = min_max(m, q) n, r = min_max(n, r) e, g = min_max(e, g) f, h = min_max(f, h) i, k = min_max(i, k) j, l = min_max(j, l) m, o = min_max(m, o) n, p = min_max(n, p) q, s = min_max(q, s) r, t = min_max(r, t) c, q = min_max(c, q) d, r = min_max(d, r) g, u = min_max(g, u) h, v = min_max(h, v) c, i = min_max(c, i) d, j = min_max(d, j) g, m = min_max(g, m) h, n = min_max(h, n) k, q = min_max(k, q) l, r = min_max(l, r) o, u = min_max(o, u) p, v = min_max(p, v) c, e = min_max(c, e) d, f = min_max(d, f) g, i = min_max(g, i) h, j = min_max(h, j) k, m = min_max(k, m) l, n = min_max(l, n) o, q = min_max(o, q) p, r = min_max(p, r) s, u = min_max(s, u) t, v = min_max(t, v) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) q, r = min_max(q, r) s, t = min_max(s, t) u, v = min_max(u, v) b, q = min_max(b, q) d, s = min_max(d, s) f, u = min_max(f, u) h, o = min_max(h, o) b, i = min_max(b, i) d, k = min_max(d, k) f, m = min_max(f, m) j, q = min_max(j, q) l, s = min_max(l, s) n, u = min_max(n, u) b, e = min_max(b, e) d, g = min_max(d, g) f, i = min_max(f, i) h, k = min_max(h, k) j, m = min_max(j, m) l, o = min_max(l, o) n, q = min_max(n, q) p, s = min_max(p, s) r, u = min_max(r, u) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) n, o = min_max(n, o) p, q = min_max(p, q) r, s = min_max(r, s) t, u = min_max(t, u) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v end # sort 23 values with 122 minmaxs in 15 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T, v::T, w::T) where {T} a, q = min_max(a, q) b, r = min_max(b, r) c, s = min_max(c, s) d, t = min_max(d, t) e, u = min_max(e, u) f, v = min_max(f, v) g, w = min_max(g, w) h, p = min_max(h, p) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) g, o = min_max(g, o) i, q = min_max(i, q) j, r = min_max(j, r) k, s = min_max(k, s) l, t = min_max(l, t) m, u = min_max(m, u) n, v = min_max(n, v) o, w = min_max(o, w) a, e = min_max(a, e) b, f = min_max(b, f) c, g = min_max(c, g) d, h = min_max(d, h) i, m = min_max(i, m) j, n = min_max(j, n) k, o = min_max(k, o) l, p = min_max(l, p) q, u = min_max(q, u) r, v = min_max(r, v) s, w = min_max(s, w) h, t = min_max(h, t) a, c = min_max(a, c) b, d = min_max(b, d) e, q = min_max(e, q) f, r = min_max(f, r) g, s = min_max(g, s) h, l = min_max(h, l) p, t = min_max(p, t) u, w = min_max(u, w) a, b = min_max(a, b) e, i = min_max(e, i) f, j = min_max(f, j) g, k = min_max(g, k) m, q = min_max(m, q) n, r = min_max(n, r) o, s = min_max(o, s) e, g = min_max(e, g) f, h = min_max(f, h) i, k = min_max(i, k) j, l = min_max(j, l) m, o = min_max(m, o) n, p = min_max(n, p) q, s = min_max(q, s) r, t = min_max(r, t) c, q = min_max(c, q) d, r = min_max(d, r) g, u = min_max(g, u) h, v = min_max(h, v) c, i = min_max(c, i) d, j = min_max(d, j) g, m = min_max(g, m) h, n = min_max(h, n) k, q = min_max(k, q) l, r = min_max(l, r) o, u = min_max(o, u) p, v = min_max(p, v) c, e = min_max(c, e) d, f = min_max(d, f) g, i = min_max(g, i) h, j = min_max(h, j) k, m = min_max(k, m) l, n = min_max(l, n) o, q = min_max(o, q) p, r = min_max(p, r) s, u = min_max(s, u) t, v = min_max(t, v) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) q, r = min_max(q, r) s, t = min_max(s, t) u, v = min_max(u, v) b, q = min_max(b, q) d, s = min_max(d, s) f, u = min_max(f, u) h, w = min_max(h, w) b, i = min_max(b, i) d, k = min_max(d, k) f, m = min_max(f, m) h, o = min_max(h, o) j, q = min_max(j, q) l, s = min_max(l, s) n, u = min_max(n, u) p, w = min_max(p, w) b, e = min_max(b, e) d, g = min_max(d, g) f, i = min_max(f, i) h, k = min_max(h, k) j, m = min_max(j, m) l, o = min_max(l, o) n, q = min_max(n, q) p, s = min_max(p, s) r, u = min_max(r, u) t, w = min_max(t, w) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) n, o = min_max(n, o) p, q = min_max(p, q) r, s = min_max(r, s) t, u = min_max(t, u) v, w = min_max(v, w) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w end # sort 24 values with 127 minmaxs in 15 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T, v::T, w::T, x::T) where {T} a, q = min_max(a, q) b, r = min_max(b, r) c, s = min_max(c, s) d, t = min_max(d, t) e, u = min_max(e, u) f, v = min_max(f, v) g, w = min_max(g, w) h, x = min_max(h, x) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) g, o = min_max(g, o) h, p = min_max(h, p) i, q = min_max(i, q) j, r = min_max(j, r) k, s = min_max(k, s) l, t = min_max(l, t) m, u = min_max(m, u) n, v = min_max(n, v) o, w = min_max(o, w) p, x = min_max(p, x) a, e = min_max(a, e) b, f = min_max(b, f) c, g = min_max(c, g) d, h = min_max(d, h) i, m = min_max(i, m) j, n = min_max(j, n) k, o = min_max(k, o) l, p = min_max(l, p) q, u = min_max(q, u) r, v = min_max(r, v) s, w = min_max(s, w) t, x = min_max(t, x) a, c = min_max(a, c) b, d = min_max(b, d) e, q = min_max(e, q) f, r = min_max(f, r) g, s = min_max(g, s) h, t = min_max(h, t) u, w = min_max(u, w) v, x = min_max(v, x) a, b = min_max(a, b) e, i = min_max(e, i) f, j = min_max(f, j) g, k = min_max(g, k) h, l = min_max(h, l) m, q = min_max(m, q) n, r = min_max(n, r) o, s = min_max(o, s) p, t = min_max(p, t) w, x = min_max(w, x) e, g = min_max(e, g) f, h = min_max(f, h) i, k = min_max(i, k) j, l = min_max(j, l) m, o = min_max(m, o) n, p = min_max(n, p) q, s = min_max(q, s) r, t = min_max(r, t) c, q = min_max(c, q) d, r = min_max(d, r) g, u = min_max(g, u) h, v = min_max(h, v) c, i = min_max(c, i) d, j = min_max(d, j) g, m = min_max(g, m) h, n = min_max(h, n) k, q = min_max(k, q) l, r = min_max(l, r) o, u = min_max(o, u) p, v = min_max(p, v) c, e = min_max(c, e) d, f = min_max(d, f) g, i = min_max(g, i) h, j = min_max(h, j) k, m = min_max(k, m) l, n = min_max(l, n) o, q = min_max(o, q) p, r = min_max(p, r) s, u = min_max(s, u) t, v = min_max(t, v) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) q, r = min_max(q, r) s, t = min_max(s, t) u, v = min_max(u, v) b, q = min_max(b, q) d, s = min_max(d, s) f, u = min_max(f, u) h, w = min_max(h, w) b, i = min_max(b, i) d, k = min_max(d, k) f, m = min_max(f, m) h, o = min_max(h, o) j, q = min_max(j, q) l, s = min_max(l, s) n, u = min_max(n, u) p, w = min_max(p, w) b, e = min_max(b, e) d, g = min_max(d, g) f, i = min_max(f, i) h, k = min_max(h, k) j, m = min_max(j, m) l, o = min_max(l, o) n, q = min_max(n, q) p, s = min_max(p, s) r, u = min_max(r, u) t, w = min_max(t, w) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) n, o = min_max(n, o) p, q = min_max(p, q) r, s = min_max(r, s) t, u = min_max(t, u) v, w = min_max(v, w) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x end # sort 25 values with 138 minmaxs in 15 parallel stages function swapsort(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T, v::T, w::T, x::T, y::T) where {T} a, q = min_max(a, q) b, r = min_max(b, r) c, s = min_max(c, s) d, t = min_max(d, t) e, u = min_max(e, u) f, v = min_max(f, v) g, w = min_max(g, w) h, x = min_max(h, x) i, y = min_max(i, y) a, i = min_max(a, i) b, j = min_max(b, j) c, k = min_max(c, k) d, l = min_max(d, l) e, m = min_max(e, m) f, n = min_max(f, n) g, o = min_max(g, o) h, p = min_max(h, p) q, y = min_max(q, y) i, q = min_max(i, q) j, r = min_max(j, r) k, s = min_max(k, s) l, t = min_max(l, t) m, u = min_max(m, u) n, v = min_max(n, v) o, w = min_max(o, w) p, x = min_max(p, x) a, e = min_max(a, e) b, f = min_max(b, f) c, g = min_max(c, g) d, h = min_max(d, h) i, m = min_max(i, m) j, n = min_max(j, n) k, o = min_max(k, o) l, p = min_max(l, p) q, u = min_max(q, u) r, v = min_max(r, v) s, w = min_max(s, w) t, x = min_max(t, x) a, c = min_max(a, c) b, d = min_max(b, d) e, q = min_max(e, q) f, r = min_max(f, r) g, s = min_max(g, s) h, t = min_max(h, t) m, y = min_max(m, y) v, x = min_max(v, x) a, b = min_max(a, b) e, i = min_max(e, i) f, j = min_max(f, j) g, k = min_max(g, k) h, l = min_max(h, l) m, q = min_max(m, q) n, r = min_max(n, r) o, s = min_max(o, s) p, t = min_max(p, t) u, y = min_max(u, y) e, g = min_max(e, g) f, h = min_max(f, h) i, k = min_max(i, k) j, l = min_max(j, l) m, o = min_max(m, o) n, p = min_max(n, p) q, s = min_max(q, s) r, t = min_max(r, t) u, w = min_max(u, w) c, q = min_max(c, q) d, r = min_max(d, r) g, u = min_max(g, u) h, v = min_max(h, v) k, y = min_max(k, y) c, i = min_max(c, i) d, j = min_max(d, j) g, m = min_max(g, m) h, n = min_max(h, n) k, q = min_max(k, q) l, r = min_max(l, r) o, u = min_max(o, u) p, v = min_max(p, v) s, y = min_max(s, y) c, e = min_max(c, e) d, f = min_max(d, f) g, i = min_max(g, i) h, j = min_max(h, j) k, m = min_max(k, m) l, n = min_max(l, n) o, q = min_max(o, q) p, r = min_max(p, r) s, u = min_max(s, u) t, v = min_max(t, v) w, y = min_max(w, y) c, d = min_max(c, d) e, f = min_max(e, f) g, h = min_max(g, h) i, j = min_max(i, j) k, l = min_max(k, l) m, n = min_max(m, n) o, p = min_max(o, p) q, r = min_max(q, r) s, t = min_max(s, t) u, v = min_max(u, v) w, x = min_max(w, x) b, q = min_max(b, q) d, s = min_max(d, s) f, u = min_max(f, u) h, w = min_max(h, w) j, y = min_max(j, y) b, i = min_max(b, i) d, k = min_max(d, k) f, m = min_max(f, m) h, o = min_max(h, o) j, q = min_max(j, q) l, s = min_max(l, s) n, u = min_max(n, u) p, w = min_max(p, w) r, y = min_max(r, y) b, e = min_max(b, e) d, g = min_max(d, g) f, i = min_max(f, i) h, k = min_max(h, k) j, m = min_max(j, m) l, o = min_max(l, o) n, q = min_max(n, q) p, s = min_max(p, s) r, u = min_max(r, u) t, w = min_max(t, w) v, y = min_max(v, y) b, c = min_max(b, c) d, e = min_max(d, e) f, g = min_max(f, g) h, i = min_max(h, i) j, k = min_max(j, k) l, m = min_max(l, m) n, o = min_max(n, o) p, q = min_max(p, q) r, s = min_max(r, s) t, u = min_max(t, u) v, w = min_max(v, w) x, y = min_max(x, y) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y end
SortingNetworks
https://github.com/JeffreySarnoff/SortingNetworks.jl.git
[ "MIT" ]
0.3.3
97780f3c70deeb128526e31238b958f7acbe4ada
code
18347
#= Sorting networks that process 1,2,..16 values are given. Sorting networks that process 17..25 values are given in "swapsortr_17to25.jl". These sorting networks should minimize conditional swaps. The first sixteen are known to minimize conditional swaps. Functions are written with groups of internally parallelizable statements given together and sequential steps are separated. `swapsortr(x1::T, .., xn::T)::NTuple{n,T}` `swapsortr(tup::NTuple{n,T})::NTuple{n,T}` `swapsortr(vec::AbstractVector{T})::NTuple{N,T}` networks were selected using software by John Gamble http://pages.ripco.net/~jgamble/nw.html http://search.cpan.org/dist/Algorithm-Networksort/ =# const VALS = ([Val{i} for i=1:ITEMS_MAX]...,) @inline function swapsortr(vec::AbstractVector{T}) where {T} n = length(vec) n > ITEMS_MAX && throw(ErrorException("swapsortr(vector) not defined where length(vector) > $ITEMS_MAX")) return swapsortr(VALS[length(vec)], vec) end # sort 1 value with 0 minmaxs in 1 stage function swapsortr(a::T) where {T} return (a,) end @inline swapsortr(x::NTuple{1,T}) where {T} = swapsortr(x[1]) @inline swapsortr(::Type{Val{1}}, x::AbstractVector{T}) where {T} = swapsortr(x[1]) # sort 2 values with 1 minmaxs in 1 stage function swapsortr(a::T, b::T) where {T} a, b = max_min(a, b) return a,b end @inline swapsortr(x::NTuple{2,T}) where {T} = swapsortr(x[1], x[2]) @inline swapsortr(::Type{Val{2}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2]) # sort 3 values with 3 minmaxs in 3 parallel stages function swapsortr(a::T, b::T, c::T) where {T} b, c = max_min(b, c) a, c = max_min(a, c) a, b = max_min(a, b) return a, b, c end @inline swapsortr(x::NTuple{3,T}) where {T} = swapsortr(x[1], x[2], x[3]) @inline swapsortr(::Type{Val{3}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3]) # sort 4 values with 5 minmaxs in 3 parallel stages function swapsortr(a::T, b::T, c::T, d::T) where {T} a, b = max_min(a, b) c, d = max_min(c, d) a, c = max_min(a, c) b, d = max_min(b, d) b, c = max_min(b, c) return a, b, c, d end @inline swapsortr(x::NTuple{4,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4]) @inline swapsortr(::Type{Val{4}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4]) # sort 5 values with 9 minmaxs in 5 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T) where {T} b, c = max_min(b, c) d, e = max_min(d, e) b, d = max_min(b, d) a, c = max_min(a, c) c, e = max_min(c, e) a, d = max_min(a, d) a, b = max_min(a, b) c, d = max_min(c, d) b, c = max_min(b, c) return a, b, c, d, e end @inline swapsortr(x::NTuple{5,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5]) @inline swapsortr(::Type{Val{5}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5]) # sort 6 values with 12 minmaxs in 6 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T) where {T} b, c = max_min(b, c) e, f = max_min(e, f) a, c = max_min(a, c) d, f = max_min(d, f) a, b = max_min(a, b) d, e = max_min(d, e) c, f = max_min(c, f) a, d = max_min(a, d) b, e = max_min(b, e) c, e = max_min(c, e) b, d = max_min(b, d) c, d = max_min(c, d) return a, b, c, d, e, f end @inline swapsortr(x::NTuple{6,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6]) @inline swapsortr(::Type{Val{6}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6]) # sort 7 values with 16 minmaxs in 6 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T) where {T} a, e = max_min(a, e) b, f = max_min(b, f) c, g = max_min(c, g) a, c = max_min(a, c) b, d = max_min(b, d) e, g = max_min(e, g) c, e = max_min(c, e) d, f = max_min(d, f) a, b = max_min(a, b) c, d = max_min(c, d) e, f = max_min(e, f) b, e = max_min(b, e) d, g = max_min(d, g) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) return a, b, c, d, e, f, g end @inline swapsortr(x::NTuple{7,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7]) @inline swapsortr(::Type{Val{7}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7]) # sort 8 values with 19 minmaxs in 7 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T) where {T} a, b = max_min(a, b) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) a, c = max_min(a, c) b, d = max_min(b, d) e, g = max_min(e, g) f, h = max_min(f, h) b, c = max_min(b, c) f, g = max_min(f, g) a, e = max_min(a, e) d, h = max_min(d, h) b, f = max_min(b, f) c, g = max_min(c, g) b, e = max_min(b, e) d, g = max_min(d, g) c, e = max_min(c, e) d, f = max_min(d, f) d, e = max_min(d, e) return a, b, c, d, e, f, g, h end @inline swapsortr(x::NTuple{8,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8]) @inline swapsortr(::Type{Val{8}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8]) # sort 9 values with 25 minmaxs in 9 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T) where {T} a, b = max_min(a, b) d, e = max_min(d, e) g, h = max_min(g, h) b, c = max_min(b, c) e, f = max_min(e, f) h, i = max_min(h, i) a, b = max_min(a, b) d, e = max_min(d, e) g, h = max_min(g, h) c, f = max_min(c, f) a, d = max_min(a, d) b, e = max_min(b, e) f, i = max_min(f, i) d, g = max_min(d, g) e, h = max_min(e, h) c, f = max_min(c, f) a, d = max_min(a, d) b, e = max_min(b, e) f, h = max_min(f, h) c, g = max_min(c, g) b, d = max_min(b, d) e, g = max_min(e, g) c, e = max_min(c, e) f, g = max_min(f, g) c, d = max_min(c, d) return a, b, c, d, e, f, g, h, i end @inline swapsortr(x::NTuple{9,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9]) @inline swapsortr(::Type{Val{9}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9]) # sort 10 values with 29 minmaxs in 9 parallel stages function swapsortr(a::T,b::T,c::T,d::T,e::T, f::T,g::T,h::T,i::T,j::T) where {T} e, j = max_min(e, j) d, i = max_min(d, i) c, h = max_min(c, h) b, g = max_min(b, g) a, f = max_min(a, f) b, e = max_min(b, e) g, j = max_min(g, j) a, d = max_min(a, d) f, i = max_min(f, i) a, c = max_min(a, c) d, g = max_min(d, g) h, j = max_min(h, j) a, b = max_min(a, b) c, e = max_min(c, e) f, h = max_min(f, h) i, j = max_min(i, j) b, c = max_min(b, c) e, g = max_min(e, g) h, i = max_min(h, i) d, f = max_min(d, f) c, f = max_min(c, f) g, i = max_min(g, i) b, d = max_min(b, d) e, h = max_min(e, h) c, d = max_min(c, d) g, h = max_min(g, h) d, e = max_min(d, e) f, g = max_min(f, g) e, f = max_min(e, f) return a,b,c,d,e,f,g,h,i,j end @inline swapsortr(x::NTuple{10,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10]) @inline swapsortr(::Type{Val{10}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10]) # sort 11 values with 35 minmaxs in 9 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T) where {T} a, b = max_min(a, b) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) b, d = max_min(b, d) f, h = max_min(f, h) a, c = max_min(a, c) e, g = max_min(e, g) i, k = max_min(i, k) b, c = max_min(b, c) f, g = max_min(f, g) j, k = max_min(j, k) a, e = max_min(a, e) d, h = max_min(d, h) b, f = max_min(b, f) g, k = max_min(g, k) e, i = max_min(e, i) f, j = max_min(f, j) c, g = max_min(c, g) a, e = max_min(a, e) d, i = max_min(d, i) b, f = max_min(b, f) g, k = max_min(g, k) c, d = max_min(c, d) i, j = max_min(i, j) b, e = max_min(b, e) h, k = max_min(h, k) d, f = max_min(d, f) g, i = max_min(g, i) c, e = max_min(c, e) h, j = max_min(h, j) f, g = max_min(f, g) d, e = max_min(d, e) h, i = max_min(h, i) return a,b,c,d,e,f,g,h,i,j,k end @inline swapsortr(x::NTuple{11,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11]) @inline swapsortr(::Type{Val{11}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11]) # sort 12 values with 39 minmaxs in 9 parallel stages function swapsortr(a::T,b::T,c::T,d::T,e::T, f::T,g::T,h::T,i::T,j::T, k::T,l::T) where {T} a, b = max_min(a, b) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) b, d = max_min(b, d) f, h = max_min(f, h) j, l = max_min(j, l) a, c = max_min(a, c) e, g = max_min(e, g) i, k = max_min(i, k) b, c = max_min(b, c) f, g = max_min(f, g) j, k = max_min(j, k) a, e = max_min(a, e) h, l = max_min(h, l) b, f = max_min(b, f) g, k = max_min(g, k) d, h = max_min(d, h) e, i = max_min(e, i) f, j = max_min(f, j) c, g = max_min(c, g) a, e = max_min(a, e) h, l = max_min(h, l) d, i = max_min(d, i) b, f = max_min(b, f) g, k = max_min(g, k) c, d = max_min(c, d) i, j = max_min(i, j) b, e = max_min(b, e) h, k = max_min(h, k) d, f = max_min(d, f) g, i = max_min(g, i) c, e = max_min(c, e) h, j = max_min(h, j) f, g = max_min(f, g) d, e = max_min(d, e) h, i = max_min(h, i) return a,b,c,d,e,f,g,h,i,j,k,l end @inline swapsortr(x::NTuple{12,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12]) @inline swapsortr(::Type{Val{12}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12]) # sort 13 values with 45 minmaxs in 10 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T) where {T} b, h = max_min(b, h) j, l = max_min(j, l) d, e = max_min(d, e) f, i = max_min(f, i) a, m = max_min(a, m) c, g = max_min(c, g) a, b = max_min(a, b) c, d = max_min(c, d) e, g = max_min(e, g) i, l = max_min(i, l) h, m = max_min(h, m) f, j = max_min(f, j) a, c = max_min(a, c) d, h = max_min(d, h) k, l = max_min(k, l) b, e = max_min(b, e) g, m = max_min(g, m) h, i = max_min(h, i) l, m = max_min(l, m) e, j = max_min(e, j) g, k = max_min(g, k) d, e = max_min(d, e) f, g = max_min(f, g) i, j = max_min(i, j) k, l = max_min(k, l) b, h = max_min(b, h) c, g = max_min(c, g) j, l = max_min(j, l) b, d = max_min(b, d) e, h = max_min(e, h) i, k = max_min(i, k) a, f = max_min(a, f) c, f = max_min(c, f) g, i = max_min(g, i) j, k = max_min(j, k) b, c = max_min(b, c) d, f = max_min(d, f) h, i = max_min(h, i) e, g = max_min(e, g) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) d, e = max_min(d, e) f, g = max_min(f, g) return a,b,c,d,e,f,g,h,i,j,k,l,m end @inline swapsortr(x::NTuple{13,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13]) @inline swapsortr(::Type{Val{13}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13]) # sort 14 values with 51 minmaxs in 10 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T) where {T} a, b = max_min(a, b) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) a, c = max_min(a, c) e, g = max_min(e, g) i, k = max_min(i, k) b, d = max_min(b, d) f, h = max_min(f, h) j, l = max_min(j, l) a, e = max_min(a, e) i, m = max_min(i, m) b, f = max_min(b, f) j, n = max_min(j, n) c, g = max_min(c, g) d, h = max_min(d, h) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) f, k = max_min(f, k) g, j = max_min(g, j) d, m = max_min(d, m) h, l = max_min(h, l) b, c = max_min(b, c) e, i = max_min(e, i) b, e = max_min(b, e) h, n = max_min(h, n) c, i = max_min(c, i) f, g = max_min(f, g) j, k = max_min(j, k) c, e = max_min(c, e) l, n = max_min(l, n) d, i = max_min(d, i) h, m = max_min(h, m) g, i = max_min(g, i) k, m = max_min(k, m) d, f = max_min(d, f) h, j = max_min(h, j) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) g, h = max_min(g, h) i, j = max_min(i, j) return a,b,c,d,e,f,g,h,i,j,k,l,m,n end @inline swapsortr(x::NTuple{14,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14]) @inline swapsortr(::Type{Val{14}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14]) # sort 15 values with 56 minmaxs in 10 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T) where {T} a, b = max_min(a, b) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) a, c = max_min(a, c) e, g = max_min(e, g) i, k = max_min(i, k) m, o = max_min(m, o) b, d = max_min(b, d) f, h = max_min(f, h) j, l = max_min(j, l) a, e = max_min(a, e) i, m = max_min(i, m) b, f = max_min(b, f) j, n = max_min(j, n) c, g = max_min(c, g) k, o = max_min(k, o) d, h = max_min(d, h) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) g, o = max_min(g, o) f, k = max_min(f, k) g, j = max_min(g, j) d, m = max_min(d, m) n, o = max_min(n, o) h, l = max_min(h, l) b, c = max_min(b, c) e, i = max_min(e, i) b, e = max_min(b, e) h, n = max_min(h, n) c, i = max_min(c, i) l, o = max_min(l, o) f, g = max_min(f, g) j, k = max_min(j, k) c, e = max_min(c, e) l, n = max_min(l, n) d, i = max_min(d, i) h, m = max_min(h, m) g, i = max_min(g, i) k, m = max_min(k, m) d, f = max_min(d, f) h, j = max_min(h, j) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) g, h = max_min(g, h) i, j = max_min(i, j) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o end @inline swapsortr(x::NTuple{15,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15]) @inline swapsortr(::Type{Val{15}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15]) # sort 16 values with 60 minmaxs in 10 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T) where {T} a, b = max_min(a, b) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) a, c = max_min(a, c) e, g = max_min(e, g) i, k = max_min(i, k) m, o = max_min(m, o) b, d = max_min(b, d) f, h = max_min(f, h) j, l = max_min(j, l) n, p = max_min(n, p) a, e = max_min(a, e) i, m = max_min(i, m) b, f = max_min(b, f) j, n = max_min(j, n) c, g = max_min(c, g) k, o = max_min(k, o) d, h = max_min(d, h) l, p = max_min(l, p) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) g, o = max_min(g, o) h, p = max_min(h, p) f, k = max_min(f, k) g, j = max_min(g, j) d, m = max_min(d, m) n, o = max_min(n, o) h, l = max_min(h, l) b, c = max_min(b, c) e, i = max_min(e, i) b, e = max_min(b, e) h, n = max_min(h, n) c, i = max_min(c, i) l, o = max_min(l, o) f, g = max_min(f, g) j, k = max_min(j, k) c, e = max_min(c, e) l, n = max_min(l, n) d, i = max_min(d, i) h, m = max_min(h, m) g, i = max_min(g, i) k, m = max_min(k, m) d, f = max_min(d, f) h, j = max_min(h, j) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) g, h = max_min(g, h) i, j = max_min(i, j) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p end @inline swapsortr(x::NTuple{16,T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16]) @inline swapsortr(::Type{Val{16}}, x::AbstractVector{T}) where {T} = swapsortr(x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16])
SortingNetworks
https://github.com/JeffreySarnoff/SortingNetworks.jl.git
[ "MIT" ]
0.3.3
97780f3c70deeb128526e31238b958f7acbe4ada
code
27813
#= Sorting networks that process 17,..25 values are given. These sorting networks should minimize conditional swaps. There may exist one or more comparable alternative solutions; those may perform marginally better for some kinds of hardware. Functions are written with groups of internally paralleli1zable statements given together and sequential steps are separated. `swapsortr(x1::T, .., xn::T)::NTuple{n,T}` `swapsortr(tup::NTuple{n,T})::NTuple{n,T}` networks were selected using software by John Gamble http://pages.ripco.net/~jgamble/nw.html http://search.cpan.org/dist/Algorithm-Networksort/ =# const MORE_ARGS_MIN = 17 const MORE_ARGS_MAX = 25 #= sort NTuples of 17..25 values =# for N in collect(MORE_ARGS_MIN:MORE_ARGS_MAX) @eval swapsortr(x::NTuple{$N, T}) where T = swapsortr(x...) end #= sorting networks for 17..25 values using known compact realizations =# # sort 17 values with 74 maxmins in 12 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T) where {T} a, q = max_min(a, q) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) g, o = max_min(g, o) h, p = max_min(h, p) a, i = max_min(a, i) b, f = max_min(b, f) c, g = max_min(c, g) d, h = max_min(d, h) j, n = max_min(j, n) k, o = max_min(k, o) l, p = max_min(l, p) i, q = max_min(i, q) a, e = max_min(a, e) f, j = max_min(f, j) g, k = max_min(g, k) h, l = max_min(h, l) b, d = max_min(b, d) n, p = max_min(n, p) i, m = max_min(i, m) e, q = max_min(e, q) a, c = max_min(a, c) f, h = max_min(f, h) j, l = max_min(j, l) e, i = max_min(e, i) m, q = max_min(m, q) d, j = max_min(d, j) h, n = max_min(h, n) a, b = max_min(a, b) e, g = max_min(e, g) i, k = max_min(i, k) m, o = max_min(m, o) c, q = max_min(c, q) d, f = max_min(d, f) h, j = max_min(h, j) l, n = max_min(l, n) c, i = max_min(c, i) g, m = max_min(g, m) k, q = max_min(k, q) c, e = max_min(c, e) g, i = max_min(g, i) k, m = max_min(k, m) o, q = max_min(o, q) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) b, q = max_min(b, q) b, i = max_min(b, i) d, k = max_min(d, k) f, m = max_min(f, m) h, o = max_min(h, o) j, q = max_min(j, q) b, e = max_min(b, e) d, g = max_min(d, g) f, i = max_min(f, i) h, k = max_min(h, k) j, m = max_min(j, m) l, o = max_min(l, o) n, q = max_min(n, q) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) n, o = max_min(n, o) p, q = max_min(p, q) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q end # sort 18 values with 82 maxmins in 13 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T) where {T} a, q = max_min(a, q) b, r = max_min(b, r) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) g, o = max_min(g, o) h, p = max_min(h, p) a, i = max_min(a, i) b, j = max_min(b, j) c, g = max_min(c, g) d, h = max_min(d, h) k, o = max_min(k, o) l, p = max_min(l, p) i, q = max_min(i, q) j, r = max_min(j, r) a, e = max_min(a, e) b, f = max_min(b, f) g, k = max_min(g, k) h, l = max_min(h, l) i, m = max_min(i, m) j, n = max_min(j, n) e, q = max_min(e, q) f, r = max_min(f, r) a, c = max_min(a, c) b, d = max_min(b, d) e, i = max_min(e, i) f, j = max_min(f, j) m, q = max_min(m, q) n, r = max_min(n, r) a, b = max_min(a, b) e, g = max_min(e, g) f, h = max_min(f, h) i, k = max_min(i, k) j, l = max_min(j, l) m, o = max_min(m, o) n, p = max_min(n, p) c, q = max_min(c, q) d, r = max_min(d, r) c, i = max_min(c, i) d, j = max_min(d, j) g, m = max_min(g, m) h, n = max_min(h, n) k, q = max_min(k, q) l, r = max_min(l, r) c, e = max_min(c, e) d, f = max_min(d, f) g, i = max_min(g, i) h, j = max_min(h, j) k, m = max_min(k, m) l, n = max_min(l, n) o, q = max_min(o, q) p, r = max_min(p, r) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) q, r = max_min(q, r) b, q = max_min(b, q) d, k = max_min(d, k) f, m = max_min(f, m) h, o = max_min(h, o) b, i = max_min(b, i) j, q = max_min(j, q) d, g = max_min(d, g) h, k = max_min(h, k) l, o = max_min(l, o) b, e = max_min(b, e) f, i = max_min(f, i) j, m = max_min(j, m) n, q = max_min(n, q) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) n, o = max_min(n, o) p, q = max_min(p, q) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r end # sort 19 values with 91 maxmins in 14 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T) where {T} a, q = max_min(a, q) b, r = max_min(b, r) c, s = max_min(c, s) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) g, o = max_min(g, o) h, p = max_min(h, p) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, h = max_min(d, h) l, p = max_min(l, p) i, q = max_min(i, q) j, r = max_min(j, r) k, s = max_min(k, s) a, e = max_min(a, e) b, f = max_min(b, f) c, g = max_min(c, g) h, l = max_min(h, l) i, m = max_min(i, m) j, n = max_min(j, n) k, o = max_min(k, o) e, q = max_min(e, q) f, r = max_min(f, r) g, s = max_min(g, s) a, c = max_min(a, c) b, d = max_min(b, d) e, i = max_min(e, i) f, j = max_min(f, j) g, k = max_min(g, k) m, q = max_min(m, q) n, r = max_min(n, r) o, s = max_min(o, s) a, b = max_min(a, b) e, g = max_min(e, g) f, h = max_min(f, h) i, k = max_min(i, k) j, l = max_min(j, l) m, o = max_min(m, o) n, p = max_min(n, p) q, s = max_min(q, s) d, r = max_min(d, r) c, q = max_min(c, q) d, j = max_min(d, j) g, m = max_min(g, m) h, n = max_min(h, n) l, r = max_min(l, r) c, i = max_min(c, i) k, q = max_min(k, q) d, f = max_min(d, f) h, j = max_min(h, j) l, n = max_min(l, n) p, r = max_min(p, r) c, e = max_min(c, e) g, i = max_min(g, i) k, m = max_min(k, m) o, q = max_min(o, q) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) q, r = max_min(q, r) b, q = max_min(b, q) d, s = max_min(d, s) f, m = max_min(f, m) h, o = max_min(h, o) b, i = max_min(b, i) d, k = max_min(d, k) j, q = max_min(j, q) l, s = max_min(l, s) b, e = max_min(b, e) d, g = max_min(d, g) f, i = max_min(f, i) h, k = max_min(h, k) j, m = max_min(j, m) l, o = max_min(l, o) n, q = max_min(n, q) p, s = max_min(p, s) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) n, o = max_min(n, o) p, q = max_min(p, q) r, s = max_min(r, s) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s end # sort 20 values with 97 maxmins in 14 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T) where {T} a, q = max_min(a, q) b, r = max_min(b, r) c, s = max_min(c, s) d, t = max_min(d, t) e, m = max_min(e, m) f, n = max_min(f, n) g, o = max_min(g, o) h, p = max_min(h, p) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) i, q = max_min(i, q) j, r = max_min(j, r) k, s = max_min(k, s) l, t = max_min(l, t) a, e = max_min(a, e) b, f = max_min(b, f) c, g = max_min(c, g) d, h = max_min(d, h) i, m = max_min(i, m) j, n = max_min(j, n) k, o = max_min(k, o) l, p = max_min(l, p) e, q = max_min(e, q) f, r = max_min(f, r) g, s = max_min(g, s) h, t = max_min(h, t) a, c = max_min(a, c) b, d = max_min(b, d) e, i = max_min(e, i) f, j = max_min(f, j) g, k = max_min(g, k) h, l = max_min(h, l) m, q = max_min(m, q) n, r = max_min(n, r) o, s = max_min(o, s) p, t = max_min(p, t) a, b = max_min(a, b) e, g = max_min(e, g) f, h = max_min(f, h) i, k = max_min(i, k) j, l = max_min(j, l) m, o = max_min(m, o) n, p = max_min(n, p) q, s = max_min(q, s) r, t = max_min(r, t) c, q = max_min(c, q) d, r = max_min(d, r) g, m = max_min(g, m) h, n = max_min(h, n) s, t = max_min(s, t) c, i = max_min(c, i) d, j = max_min(d, j) k, q = max_min(k, q) l, r = max_min(l, r) c, e = max_min(c, e) d, f = max_min(d, f) g, i = max_min(g, i) h, j = max_min(h, j) k, m = max_min(k, m) l, n = max_min(l, n) o, q = max_min(o, q) p, r = max_min(p, r) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) q, r = max_min(q, r) b, q = max_min(b, q) d, s = max_min(d, s) f, m = max_min(f, m) h, o = max_min(h, o) b, i = max_min(b, i) d, k = max_min(d, k) j, q = max_min(j, q) l, s = max_min(l, s) b, e = max_min(b, e) d, g = max_min(d, g) f, i = max_min(f, i) h, k = max_min(h, k) j, m = max_min(j, m) l, o = max_min(l, o) n, q = max_min(n, q) p, s = max_min(p, s) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) n, o = max_min(n, o) p, q = max_min(p, q) r, s = max_min(r, s) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t end # sort 21 values with 107 maxmins in 15 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T) where {T} a, q = max_min(a, q) b, r = max_min(b, r) c, s = max_min(c, s) d, t = max_min(d, t) e, u = max_min(e, u) f, n = max_min(f, n) g, o = max_min(g, o) h, p = max_min(h, p) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) i, q = max_min(i, q) j, r = max_min(j, r) k, s = max_min(k, s) l, t = max_min(l, t) m, u = max_min(m, u) a, e = max_min(a, e) b, f = max_min(b, f) c, g = max_min(c, g) d, h = max_min(d, h) i, m = max_min(i, m) j, n = max_min(j, n) k, o = max_min(k, o) l, p = max_min(l, p) q, u = max_min(q, u) f, r = max_min(f, r) g, s = max_min(g, s) h, t = max_min(h, t) a, c = max_min(a, c) b, d = max_min(b, d) e, q = max_min(e, q) f, j = max_min(f, j) g, k = max_min(g, k) h, l = max_min(h, l) n, r = max_min(n, r) o, s = max_min(o, s) p, t = max_min(p, t) a, b = max_min(a, b) e, i = max_min(e, i) m, q = max_min(m, q) f, h = max_min(f, h) j, l = max_min(j, l) n, p = max_min(n, p) r, t = max_min(r, t) e, g = max_min(e, g) i, k = max_min(i, k) m, o = max_min(m, o) q, s = max_min(q, s) d, r = max_min(d, r) h, n = max_min(h, n) c, q = max_min(c, q) g, u = max_min(g, u) d, j = max_min(d, j) l, r = max_min(l, r) c, i = max_min(c, i) g, m = max_min(g, m) k, q = max_min(k, q) o, u = max_min(o, u) d, f = max_min(d, f) h, j = max_min(h, j) l, n = max_min(l, n) p, r = max_min(p, r) c, e = max_min(c, e) g, i = max_min(g, i) k, m = max_min(k, m) o, q = max_min(o, q) s, u = max_min(s, u) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) q, r = max_min(q, r) s, t = max_min(s, t) b, q = max_min(b, q) d, s = max_min(d, s) f, u = max_min(f, u) h, o = max_min(h, o) b, i = max_min(b, i) d, k = max_min(d, k) f, m = max_min(f, m) j, q = max_min(j, q) l, s = max_min(l, s) n, u = max_min(n, u) b, e = max_min(b, e) d, g = max_min(d, g) f, i = max_min(f, i) h, k = max_min(h, k) j, m = max_min(j, m) l, o = max_min(l, o) n, q = max_min(n, q) p, s = max_min(p, s) r, u = max_min(r, u) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) n, o = max_min(n, o) p, q = max_min(p, q) r, s = max_min(r, s) t, u = max_min(t, u) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u end # sort 22 values with 114 maxmins in 15 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T, v::T) where {T} a, q = max_min(a, q) b, r = max_min(b, r) c, s = max_min(c, s) d, t = max_min(d, t) e, u = max_min(e, u) f, v = max_min(f, v) g, o = max_min(g, o) h, p = max_min(h, p) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) i, q = max_min(i, q) j, r = max_min(j, r) k, s = max_min(k, s) l, t = max_min(l, t) m, u = max_min(m, u) n, v = max_min(n, v) a, e = max_min(a, e) b, f = max_min(b, f) c, g = max_min(c, g) d, h = max_min(d, h) i, m = max_min(i, m) j, n = max_min(j, n) k, o = max_min(k, o) l, p = max_min(l, p) q, u = max_min(q, u) r, v = max_min(r, v) g, s = max_min(g, s) h, t = max_min(h, t) a, c = max_min(a, c) b, d = max_min(b, d) e, q = max_min(e, q) f, r = max_min(f, r) g, k = max_min(g, k) h, l = max_min(h, l) o, s = max_min(o, s) p, t = max_min(p, t) a, b = max_min(a, b) e, i = max_min(e, i) f, j = max_min(f, j) m, q = max_min(m, q) n, r = max_min(n, r) e, g = max_min(e, g) f, h = max_min(f, h) i, k = max_min(i, k) j, l = max_min(j, l) m, o = max_min(m, o) n, p = max_min(n, p) q, s = max_min(q, s) r, t = max_min(r, t) c, q = max_min(c, q) d, r = max_min(d, r) g, u = max_min(g, u) h, v = max_min(h, v) c, i = max_min(c, i) d, j = max_min(d, j) g, m = max_min(g, m) h, n = max_min(h, n) k, q = max_min(k, q) l, r = max_min(l, r) o, u = max_min(o, u) p, v = max_min(p, v) c, e = max_min(c, e) d, f = max_min(d, f) g, i = max_min(g, i) h, j = max_min(h, j) k, m = max_min(k, m) l, n = max_min(l, n) o, q = max_min(o, q) p, r = max_min(p, r) s, u = max_min(s, u) t, v = max_min(t, v) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) q, r = max_min(q, r) s, t = max_min(s, t) u, v = max_min(u, v) b, q = max_min(b, q) d, s = max_min(d, s) f, u = max_min(f, u) h, o = max_min(h, o) b, i = max_min(b, i) d, k = max_min(d, k) f, m = max_min(f, m) j, q = max_min(j, q) l, s = max_min(l, s) n, u = max_min(n, u) b, e = max_min(b, e) d, g = max_min(d, g) f, i = max_min(f, i) h, k = max_min(h, k) j, m = max_min(j, m) l, o = max_min(l, o) n, q = max_min(n, q) p, s = max_min(p, s) r, u = max_min(r, u) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) n, o = max_min(n, o) p, q = max_min(p, q) r, s = max_min(r, s) t, u = max_min(t, u) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v end # sort 23 values with 122 maxmins in 15 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T, v::T, w::T) where {T} a, q = max_min(a, q) b, r = max_min(b, r) c, s = max_min(c, s) d, t = max_min(d, t) e, u = max_min(e, u) f, v = max_min(f, v) g, w = max_min(g, w) h, p = max_min(h, p) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) g, o = max_min(g, o) i, q = max_min(i, q) j, r = max_min(j, r) k, s = max_min(k, s) l, t = max_min(l, t) m, u = max_min(m, u) n, v = max_min(n, v) o, w = max_min(o, w) a, e = max_min(a, e) b, f = max_min(b, f) c, g = max_min(c, g) d, h = max_min(d, h) i, m = max_min(i, m) j, n = max_min(j, n) k, o = max_min(k, o) l, p = max_min(l, p) q, u = max_min(q, u) r, v = max_min(r, v) s, w = max_min(s, w) h, t = max_min(h, t) a, c = max_min(a, c) b, d = max_min(b, d) e, q = max_min(e, q) f, r = max_min(f, r) g, s = max_min(g, s) h, l = max_min(h, l) p, t = max_min(p, t) u, w = max_min(u, w) a, b = max_min(a, b) e, i = max_min(e, i) f, j = max_min(f, j) g, k = max_min(g, k) m, q = max_min(m, q) n, r = max_min(n, r) o, s = max_min(o, s) e, g = max_min(e, g) f, h = max_min(f, h) i, k = max_min(i, k) j, l = max_min(j, l) m, o = max_min(m, o) n, p = max_min(n, p) q, s = max_min(q, s) r, t = max_min(r, t) c, q = max_min(c, q) d, r = max_min(d, r) g, u = max_min(g, u) h, v = max_min(h, v) c, i = max_min(c, i) d, j = max_min(d, j) g, m = max_min(g, m) h, n = max_min(h, n) k, q = max_min(k, q) l, r = max_min(l, r) o, u = max_min(o, u) p, v = max_min(p, v) c, e = max_min(c, e) d, f = max_min(d, f) g, i = max_min(g, i) h, j = max_min(h, j) k, m = max_min(k, m) l, n = max_min(l, n) o, q = max_min(o, q) p, r = max_min(p, r) s, u = max_min(s, u) t, v = max_min(t, v) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) q, r = max_min(q, r) s, t = max_min(s, t) u, v = max_min(u, v) b, q = max_min(b, q) d, s = max_min(d, s) f, u = max_min(f, u) h, w = max_min(h, w) b, i = max_min(b, i) d, k = max_min(d, k) f, m = max_min(f, m) h, o = max_min(h, o) j, q = max_min(j, q) l, s = max_min(l, s) n, u = max_min(n, u) p, w = max_min(p, w) b, e = max_min(b, e) d, g = max_min(d, g) f, i = max_min(f, i) h, k = max_min(h, k) j, m = max_min(j, m) l, o = max_min(l, o) n, q = max_min(n, q) p, s = max_min(p, s) r, u = max_min(r, u) t, w = max_min(t, w) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) n, o = max_min(n, o) p, q = max_min(p, q) r, s = max_min(r, s) t, u = max_min(t, u) v, w = max_min(v, w) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w end # sort 24 values with 127 maxmins in 15 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T, v::T, w::T, x::T) where {T} a, q = max_min(a, q) b, r = max_min(b, r) c, s = max_min(c, s) d, t = max_min(d, t) e, u = max_min(e, u) f, v = max_min(f, v) g, w = max_min(g, w) h, x = max_min(h, x) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) g, o = max_min(g, o) h, p = max_min(h, p) i, q = max_min(i, q) j, r = max_min(j, r) k, s = max_min(k, s) l, t = max_min(l, t) m, u = max_min(m, u) n, v = max_min(n, v) o, w = max_min(o, w) p, x = max_min(p, x) a, e = max_min(a, e) b, f = max_min(b, f) c, g = max_min(c, g) d, h = max_min(d, h) i, m = max_min(i, m) j, n = max_min(j, n) k, o = max_min(k, o) l, p = max_min(l, p) q, u = max_min(q, u) r, v = max_min(r, v) s, w = max_min(s, w) t, x = max_min(t, x) a, c = max_min(a, c) b, d = max_min(b, d) e, q = max_min(e, q) f, r = max_min(f, r) g, s = max_min(g, s) h, t = max_min(h, t) u, w = max_min(u, w) v, x = max_min(v, x) a, b = max_min(a, b) e, i = max_min(e, i) f, j = max_min(f, j) g, k = max_min(g, k) h, l = max_min(h, l) m, q = max_min(m, q) n, r = max_min(n, r) o, s = max_min(o, s) p, t = max_min(p, t) w, x = max_min(w, x) e, g = max_min(e, g) f, h = max_min(f, h) i, k = max_min(i, k) j, l = max_min(j, l) m, o = max_min(m, o) n, p = max_min(n, p) q, s = max_min(q, s) r, t = max_min(r, t) c, q = max_min(c, q) d, r = max_min(d, r) g, u = max_min(g, u) h, v = max_min(h, v) c, i = max_min(c, i) d, j = max_min(d, j) g, m = max_min(g, m) h, n = max_min(h, n) k, q = max_min(k, q) l, r = max_min(l, r) o, u = max_min(o, u) p, v = max_min(p, v) c, e = max_min(c, e) d, f = max_min(d, f) g, i = max_min(g, i) h, j = max_min(h, j) k, m = max_min(k, m) l, n = max_min(l, n) o, q = max_min(o, q) p, r = max_min(p, r) s, u = max_min(s, u) t, v = max_min(t, v) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) q, r = max_min(q, r) s, t = max_min(s, t) u, v = max_min(u, v) b, q = max_min(b, q) d, s = max_min(d, s) f, u = max_min(f, u) h, w = max_min(h, w) b, i = max_min(b, i) d, k = max_min(d, k) f, m = max_min(f, m) h, o = max_min(h, o) j, q = max_min(j, q) l, s = max_min(l, s) n, u = max_min(n, u) p, w = max_min(p, w) b, e = max_min(b, e) d, g = max_min(d, g) f, i = max_min(f, i) h, k = max_min(h, k) j, m = max_min(j, m) l, o = max_min(l, o) n, q = max_min(n, q) p, s = max_min(p, s) r, u = max_min(r, u) t, w = max_min(t, w) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) n, o = max_min(n, o) p, q = max_min(p, q) r, s = max_min(r, s) t, u = max_min(t, u) v, w = max_min(v, w) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x end # sort 25 values with 138 maxmins in 15 parallel stages function swapsortr(a::T, b::T, c::T, d::T, e::T, f::T, g::T, h::T, i::T, j::T, k::T, l::T, m::T, n::T, o::T, p::T, q::T, r::T, s::T, t::T, u::T, v::T, w::T, x::T, y::T) where {T} a, q = max_min(a, q) b, r = max_min(b, r) c, s = max_min(c, s) d, t = max_min(d, t) e, u = max_min(e, u) f, v = max_min(f, v) g, w = max_min(g, w) h, x = max_min(h, x) i, y = max_min(i, y) a, i = max_min(a, i) b, j = max_min(b, j) c, k = max_min(c, k) d, l = max_min(d, l) e, m = max_min(e, m) f, n = max_min(f, n) g, o = max_min(g, o) h, p = max_min(h, p) q, y = max_min(q, y) i, q = max_min(i, q) j, r = max_min(j, r) k, s = max_min(k, s) l, t = max_min(l, t) m, u = max_min(m, u) n, v = max_min(n, v) o, w = max_min(o, w) p, x = max_min(p, x) a, e = max_min(a, e) b, f = max_min(b, f) c, g = max_min(c, g) d, h = max_min(d, h) i, m = max_min(i, m) j, n = max_min(j, n) k, o = max_min(k, o) l, p = max_min(l, p) q, u = max_min(q, u) r, v = max_min(r, v) s, w = max_min(s, w) t, x = max_min(t, x) a, c = max_min(a, c) b, d = max_min(b, d) e, q = max_min(e, q) f, r = max_min(f, r) g, s = max_min(g, s) h, t = max_min(h, t) m, y = max_min(m, y) v, x = max_min(v, x) a, b = max_min(a, b) e, i = max_min(e, i) f, j = max_min(f, j) g, k = max_min(g, k) h, l = max_min(h, l) m, q = max_min(m, q) n, r = max_min(n, r) o, s = max_min(o, s) p, t = max_min(p, t) u, y = max_min(u, y) e, g = max_min(e, g) f, h = max_min(f, h) i, k = max_min(i, k) j, l = max_min(j, l) m, o = max_min(m, o) n, p = max_min(n, p) q, s = max_min(q, s) r, t = max_min(r, t) u, w = max_min(u, w) c, q = max_min(c, q) d, r = max_min(d, r) g, u = max_min(g, u) h, v = max_min(h, v) k, y = max_min(k, y) c, i = max_min(c, i) d, j = max_min(d, j) g, m = max_min(g, m) h, n = max_min(h, n) k, q = max_min(k, q) l, r = max_min(l, r) o, u = max_min(o, u) p, v = max_min(p, v) s, y = max_min(s, y) c, e = max_min(c, e) d, f = max_min(d, f) g, i = max_min(g, i) h, j = max_min(h, j) k, m = max_min(k, m) l, n = max_min(l, n) o, q = max_min(o, q) p, r = max_min(p, r) s, u = max_min(s, u) t, v = max_min(t, v) w, y = max_min(w, y) c, d = max_min(c, d) e, f = max_min(e, f) g, h = max_min(g, h) i, j = max_min(i, j) k, l = max_min(k, l) m, n = max_min(m, n) o, p = max_min(o, p) q, r = max_min(q, r) s, t = max_min(s, t) u, v = max_min(u, v) w, x = max_min(w, x) b, q = max_min(b, q) d, s = max_min(d, s) f, u = max_min(f, u) h, w = max_min(h, w) j, y = max_min(j, y) b, i = max_min(b, i) d, k = max_min(d, k) f, m = max_min(f, m) h, o = max_min(h, o) j, q = max_min(j, q) l, s = max_min(l, s) n, u = max_min(n, u) p, w = max_min(p, w) r, y = max_min(r, y) b, e = max_min(b, e) d, g = max_min(d, g) f, i = max_min(f, i) h, k = max_min(h, k) j, m = max_min(j, m) l, o = max_min(l, o) n, q = max_min(n, q) p, s = max_min(p, s) r, u = max_min(r, u) t, w = max_min(t, w) v, y = max_min(v, y) b, c = max_min(b, c) d, e = max_min(d, e) f, g = max_min(f, g) h, i = max_min(h, i) j, k = max_min(j, k) l, m = max_min(l, m) n, o = max_min(n, o) p, q = max_min(p, q) r, s = max_min(r, s) t, u = max_min(t, u) v, w = max_min(v, w) x, y = max_min(x, y) return a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y end
SortingNetworks
https://github.com/JeffreySarnoff/SortingNetworks.jl.git
[ "MIT" ]
0.3.3
97780f3c70deeb128526e31238b958f7acbe4ada
code
796
using SortingNetworks using Test function bittuple_impl(::Val{N}) where {N} args = [:(ithbit(x, $i)) for i in 0:N-1] :(tuple($(args...))) end ithbit(x, i) = Bool((x >> i) & true) @generated bittuple(x, N) = bittuple_impl(N()) function bittuples(vN::Val{N}) where {N} @assert N <= 25 xs = UInt64(1):UInt64(2)^N [bittuple(x, vN) for x in xs] end @noinline function test_swapsort(vN::Val) for cba ∈ bittuples(vN) abc = swapsort(cba) @test issorted(abc) end end test_swapsort(n) = test_swapsort(Val{n}()) @testset "test 0-1 principle implementation" begin N = 8 tups = @inferred bittuples(Val{N}()) @test length(tups) == 2^N @test length(unique(tups)) == length(tups) end @testset "0-1 principle" for n ∈ 1:25 test_swapsort(n) end
SortingNetworks
https://github.com/JeffreySarnoff/SortingNetworks.jl.git
[ "MIT" ]
0.3.3
97780f3c70deeb128526e31238b958f7acbe4ada
docs
1158
# SortingNetworks.jl Sort 1..25 values with conditional swaps.&nbsp;&nbsp; [![Build Status](https://travis-ci.org/JeffreySarnoff/SortingNetworks.jl.svg?branch=master)](https://travis-ci.org/JeffreySarnoff/SortingNetworks.jl) ##### Copyright ©2017-2022 by Jeffrey Sarnoff. ------ Sorting networks that process 1,2,..25 values are given. These sorting networks should minimize conditional swaps. The first sixteen are known to minimize conditional swaps. Values may be given with the args `swapsort(x1::T, .., xn::T)::NTuple{n,T}` Values may be given using a tuple `swapsort(tup::NTuple{n,T})::NTuple{n,T}` These sorts return a tuple of values sorted in ascending order. #### Install `Pkg.add("SortingNetworks")` #### Use ```julia using SortingNetworks jumble = (5,3,1,4,2) sorted = (1,2,3,4,5) ascending = swapsort(5,3,1,4,2) ascending == sorted ascending == swapsort(jumble) ascending == sorted ``` With v0.6-dev, timing sort([a,b,..]) relative to swapsort(a,b,...), I got 15x for 4 Ints, 11x for 8 Ints, 5.75x for 16 Ints ##### acknowlegement Jan Weidner provided **provably correct** code to test each implementation.
SortingNetworks
https://github.com/JeffreySarnoff/SortingNetworks.jl.git
[ "MIT" ]
0.3.3
97780f3c70deeb128526e31238b958f7acbe4ada
docs
174
https://bertdobbelaere.github.io/sorting_networks.html https://bertdobbelaere.github.io/sorting_networks_extended.html https://bertdobbelaere.github.io/median_networks.html
SortingNetworks
https://github.com/JeffreySarnoff/SortingNetworks.jl.git
[ "MIT" ]
1.1.0
ea84a3fc5acae82883d2c3ce3579d461d26a47e2
code
672
using LibAwsCal using Documenter DocMeta.setdocmeta!(LibAwsCal, :DocTestSetup, :(using LibAwsCal); recursive=true) makedocs(; modules=[LibAwsCal], repo="https://github.com/JuliaServices/LibAwsCal.jl/blob/{commit}{path}#{line}", sitename="LibAwsCal.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://github.com/JuliaServices/LibAwsCal.jl", assets=String[], size_threshold=2_000_000, # 2 MB, we generate about 1 MB page size_threshold_warn=2_000_000, ), pages=["Home" => "index.md"], ) deploydocs(; repo="github.com/JuliaServices/LibAwsCal.jl", devbranch="main")
LibAwsCal
https://github.com/JuliaServices/LibAwsCal.jl.git
[ "MIT" ]
1.1.0
ea84a3fc5acae82883d2c3ce3579d461d26a47e2
code
2993
using Clang.Generators using Clang.JLLEnvs using JLLPrefixes import aws_c_common_jll, aws_c_cal_jll using LibAwsCommon cd(@__DIR__) # This is called if the docs generated from the extract_c_comment_style method did not generate any lines. # We need to generate at least some docs so that cross-references work with Documenter.jl. function get_docs(node, docs) # The macro node types (except for MacroDefault) seem to not generate code, but they will still emit docs and then # you end up with docs stacked on top of each other, which is a Julia LoadError. if node.type isa Generators.AbstractMacroNodeType && !(node.type isa Generators.MacroDefault) return String[] end # don't generate empty docs because it makes Documenter.jl mad if isempty(docs) return ["Documentation not found."] end return docs end function should_skip_target(target) # aws_c_common_jll does not support i686 windows https://github.com/JuliaPackaging/Yggdrasil/blob/bbab3a916ae5543902b025a4a873cf9ee4a7de68/A/aws_c_common/build_tarballs.jl#L48-L49 return target == "i686-w64-mingw32" end const deps_jlls = [aws_c_common_jll] const deps = [LibAwsCommon] const deps_names = sort(collect(Iterators.flatten(names.(deps)))) # clang can emit code for forward declarations of structs defined in our dependencies. we need to skip those, otherwise # we'll have duplicate struct definitions. function skip_nodes_in_dependencies!(dag::ExprDAG) replace!(get_nodes(dag)) do node if insorted(node.id, deps_names) return ExprNode(node.id, Generators.Skip(), node.cursor, Expr[], node.adj) end return node end end # download toolchains in parallel Threads.@threads for target in JLLEnvs.JLL_ENV_TRIPLES if should_skip_target(target) continue end get_default_args(target) # downloads the toolchain end for target in JLLEnvs.JLL_ENV_TRIPLES if should_skip_target(target) continue end options = load_options(joinpath(@__DIR__, "generator.toml")) options["general"]["output_file_path"] = joinpath(@__DIR__, "..", "lib", "$target.jl") options["general"]["callback_documentation"] = get_docs args = get_default_args(target) for dep in deps_jlls inc = JLLEnvs.get_pkg_include_dir(dep, target) push!(args, "-isystem$inc") end header_dirs = [] inc = JLLEnvs.get_pkg_include_dir(aws_c_cal_jll, target) push!(args, "-I$inc") push!(header_dirs, inc) headers = String[] for header_dir in header_dirs for (root, dirs, files) in walkdir(header_dir) for file in files if endswith(file, ".h") push!(headers, joinpath(root, file)) end end end end unique!(headers) ctx = create_context(headers, args, options) build!(ctx, BUILDSTAGE_NO_PRINTING) skip_nodes_in_dependencies!(ctx.dag) build!(ctx, BUILDSTAGE_PRINTING_ONLY) end
LibAwsCal
https://github.com/JuliaServices/LibAwsCal.jl.git
[ "MIT" ]
1.1.0
ea84a3fc5acae82883d2c3ce3579d461d26a47e2
code
48610
using CEnum """ aws_cal_errors Documentation not found. """ @cenum aws_cal_errors::UInt32 begin AWS_ERROR_CAL_SIGNATURE_VALIDATION_FAILED = 7168 AWS_ERROR_CAL_MISSING_REQUIRED_KEY_COMPONENT = 7169 AWS_ERROR_CAL_INVALID_KEY_LENGTH_FOR_ALGORITHM = 7170 AWS_ERROR_CAL_UNKNOWN_OBJECT_IDENTIFIER = 7171 AWS_ERROR_CAL_MALFORMED_ASN1_ENCOUNTERED = 7172 AWS_ERROR_CAL_MISMATCHED_DER_TYPE = 7173 AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM = 7174 AWS_ERROR_CAL_BUFFER_TOO_LARGE_FOR_ALGORITHM = 7175 AWS_ERROR_CAL_INVALID_CIPHER_MATERIAL_SIZE_FOR_ALGORITHM = 7176 AWS_ERROR_CAL_DER_UNSUPPORTED_NEGATIVE_INT = 7177 AWS_ERROR_CAL_UNSUPPORTED_KEY_FORMAT = 7178 AWS_ERROR_CAL_CRYPTO_OPERATION_FAILED = 7179 AWS_ERROR_CAL_END_RANGE = 8191 end """ aws_cal_log_subject Documentation not found. """ @cenum aws_cal_log_subject::UInt32 begin AWS_LS_CAL_GENERAL = 7168 AWS_LS_CAL_ECC = 7169 AWS_LS_CAL_HASH = 7170 AWS_LS_CAL_HMAC = 7171 AWS_LS_CAL_DER = 7172 AWS_LS_CAL_LIBCRYPTO_RESOLVE = 7173 AWS_LS_CAL_RSA = 7174 AWS_LS_CAL_LAST = 8191 end """ aws_cal_library_init(allocator) Documentation not found. ### Prototype ```c void aws_cal_library_init(struct aws_allocator *allocator); ``` """ function aws_cal_library_init(allocator) ccall((:aws_cal_library_init, libaws_c_cal), Cvoid, (Ptr{aws_allocator},), allocator) end """ aws_cal_library_clean_up() Documentation not found. ### Prototype ```c void aws_cal_library_clean_up(void); ``` """ function aws_cal_library_clean_up() ccall((:aws_cal_library_clean_up, libaws_c_cal), Cvoid, ()) end """ aws_cal_thread_clean_up() Documentation not found. ### Prototype ```c void aws_cal_thread_clean_up(void); ``` """ function aws_cal_thread_clean_up() ccall((:aws_cal_thread_clean_up, libaws_c_cal), Cvoid, ()) end """ aws_ecc_curve_name Documentation not found. """ @cenum aws_ecc_curve_name::UInt32 begin AWS_CAL_ECDSA_P256 = 0 AWS_CAL_ECDSA_P384 = 1 end # typedef void aws_ecc_key_pair_destroy_fn ( struct aws_ecc_key_pair * key_pair ) """ Documentation not found. """ const aws_ecc_key_pair_destroy_fn = Cvoid # typedef int aws_ecc_key_pair_sign_message_fn ( const struct aws_ecc_key_pair * key_pair , const struct aws_byte_cursor * message , struct aws_byte_buf * signature_output ) """ Documentation not found. """ const aws_ecc_key_pair_sign_message_fn = Cvoid # typedef int aws_ecc_key_pair_derive_public_key_fn ( struct aws_ecc_key_pair * key_pair ) """ Documentation not found. """ const aws_ecc_key_pair_derive_public_key_fn = Cvoid # typedef int aws_ecc_key_pair_verify_signature_fn ( const struct aws_ecc_key_pair * signer , const struct aws_byte_cursor * message , const struct aws_byte_cursor * signature ) """ Documentation not found. """ const aws_ecc_key_pair_verify_signature_fn = Cvoid # typedef size_t aws_ecc_key_pair_signature_length_fn ( const struct aws_ecc_key_pair * signer ) """ Documentation not found. """ const aws_ecc_key_pair_signature_length_fn = Cvoid """ aws_ecc_key_pair_vtable Documentation not found. """ struct aws_ecc_key_pair_vtable destroy::Ptr{aws_ecc_key_pair_destroy_fn} derive_pub_key::Ptr{aws_ecc_key_pair_derive_public_key_fn} sign_message::Ptr{aws_ecc_key_pair_sign_message_fn} verify_signature::Ptr{aws_ecc_key_pair_verify_signature_fn} signature_length::Ptr{aws_ecc_key_pair_signature_length_fn} end """ aws_ecc_key_pair Documentation not found. """ struct aws_ecc_key_pair allocator::Ptr{aws_allocator} ref_count::aws_atomic_var curve_name::aws_ecc_curve_name key_buf::aws_byte_buf pub_x::aws_byte_buf pub_y::aws_byte_buf priv_d::aws_byte_buf vtable::Ptr{aws_ecc_key_pair_vtable} impl::Ptr{Cvoid} end """ aws_ecc_key_pair_acquire(key_pair) Adds one to an ecc key pair's ref count. ### Prototype ```c void aws_ecc_key_pair_acquire(struct aws_ecc_key_pair *key_pair); ``` """ function aws_ecc_key_pair_acquire(key_pair) ccall((:aws_ecc_key_pair_acquire, libaws_c_cal), Cvoid, (Ptr{aws_ecc_key_pair},), key_pair) end """ aws_ecc_key_pair_release(key_pair) Subtracts one from an ecc key pair's ref count. If ref count reaches zero, the key pair is destroyed. ### Prototype ```c void aws_ecc_key_pair_release(struct aws_ecc_key_pair *key_pair); ``` """ function aws_ecc_key_pair_release(key_pair) ccall((:aws_ecc_key_pair_release, libaws_c_cal), Cvoid, (Ptr{aws_ecc_key_pair},), key_pair) end """ aws_ecc_key_pair_new_from_private_key(allocator, curve_name, priv_key) Creates an Elliptic Curve private key that can be used for signing. Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. Note: priv\\_key::len must match the appropriate length for the selected curve\\_name. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_pair_new_from_private_key( struct aws_allocator *allocator, enum aws_ecc_curve_name curve_name, const struct aws_byte_cursor *priv_key); ``` """ function aws_ecc_key_pair_new_from_private_key(allocator, curve_name, priv_key) ccall((:aws_ecc_key_pair_new_from_private_key, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, aws_ecc_curve_name, Ptr{aws_byte_cursor}), allocator, curve_name, priv_key) end """ aws_ecc_key_pair_new_generate_random(allocator, curve_name) Creates an Elliptic Curve public/private key pair that can be used for signing and verifying. Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. Note: On Apple platforms this function is only supported on MacOS. This is due to usage of SecItemExport, which is only available on MacOS 10.7+ (yes, MacOS only and no other Apple platforms). There are alternatives for ios and other platforms, but they are ugly to use. Hence for now it only supports this call on MacOS. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_pair_new_generate_random( struct aws_allocator *allocator, enum aws_ecc_curve_name curve_name); ``` """ function aws_ecc_key_pair_new_generate_random(allocator, curve_name) ccall((:aws_ecc_key_pair_new_generate_random, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, aws_ecc_curve_name), allocator, curve_name) end """ aws_ecc_key_pair_new_from_public_key(allocator, curve_name, public_key_x, public_key_y) Creates an Elliptic Curve public key that can be used for verifying. Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. Note: public\\_key\\_x::len and public\\_key\\_y::len must match the appropriate length for the selected curve\\_name. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_pair_new_from_public_key( struct aws_allocator *allocator, enum aws_ecc_curve_name curve_name, const struct aws_byte_cursor *public_key_x, const struct aws_byte_cursor *public_key_y); ``` """ function aws_ecc_key_pair_new_from_public_key(allocator, curve_name, public_key_x, public_key_y) ccall((:aws_ecc_key_pair_new_from_public_key, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, aws_ecc_curve_name, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), allocator, curve_name, public_key_x, public_key_y) end """ aws_ecc_key_pair_new_from_asn1(allocator, encoded_keys) Creates an Elliptic Curve public/private key pair from a DER encoded key pair. Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. Whether or not signing or verification can be perform depends on if encoded\\_keys is a public/private pair or a public key. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_pair_new_from_asn1( struct aws_allocator *allocator, const struct aws_byte_cursor *encoded_keys); ``` """ function aws_ecc_key_pair_new_from_asn1(allocator, encoded_keys) ccall((:aws_ecc_key_pair_new_from_asn1, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}), allocator, encoded_keys) end """ aws_ecc_key_new_from_hex_coordinates(allocator, curve_name, pub_x_hex_cursor, pub_y_hex_cursor) Creates an Elliptic curve public key from x and y coordinates encoded as hex strings Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_new_from_hex_coordinates( struct aws_allocator *allocator, enum aws_ecc_curve_name curve_name, struct aws_byte_cursor pub_x_hex_cursor, struct aws_byte_cursor pub_y_hex_cursor); ``` """ function aws_ecc_key_new_from_hex_coordinates(allocator, curve_name, pub_x_hex_cursor, pub_y_hex_cursor) ccall((:aws_ecc_key_new_from_hex_coordinates, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, aws_ecc_curve_name, aws_byte_cursor, aws_byte_cursor), allocator, curve_name, pub_x_hex_cursor, pub_y_hex_cursor) end """ aws_ecc_key_pair_derive_public_key(key_pair) Derives a public key from the private key if supported by this operating system (not supported on OSX). key\\_pair::pub\\_x and key\\_pair::pub\\_y will be set with the raw key buffers. ### Prototype ```c int aws_ecc_key_pair_derive_public_key(struct aws_ecc_key_pair *key_pair); ``` """ function aws_ecc_key_pair_derive_public_key(key_pair) ccall((:aws_ecc_key_pair_derive_public_key, libaws_c_cal), Cint, (Ptr{aws_ecc_key_pair},), key_pair) end """ aws_ecc_curve_name_from_oid(oid, curve_name) Get the curve name from the oid. OID here is the payload of the DER encoded ASN.1 part (doesn't include type specifier or length. On success, the value of curve\\_name will be set. ### Prototype ```c int aws_ecc_curve_name_from_oid(struct aws_byte_cursor *oid, enum aws_ecc_curve_name *curve_name); ``` """ function aws_ecc_curve_name_from_oid(oid, curve_name) ccall((:aws_ecc_curve_name_from_oid, libaws_c_cal), Cint, (Ptr{aws_byte_cursor}, Ptr{aws_ecc_curve_name}), oid, curve_name) end """ aws_ecc_oid_from_curve_name(curve_name, oid) Get the DER encoded OID from the curve\\_name. The OID in this case will not contain the type or the length specifier. ### Prototype ```c int aws_ecc_oid_from_curve_name(enum aws_ecc_curve_name curve_name, struct aws_byte_cursor *oid); ``` """ function aws_ecc_oid_from_curve_name(curve_name, oid) ccall((:aws_ecc_oid_from_curve_name, libaws_c_cal), Cint, (aws_ecc_curve_name, Ptr{aws_byte_cursor}), curve_name, oid) end """ aws_ecc_key_pair_sign_message(key_pair, message, signature) Uses the key\\_pair's private key to sign message. The output will be in signature. Signature must be large enough to hold the signature. Check [`aws_ecc_key_pair_signature_length`](@ref)() for the appropriate size. Signature will be DER encoded. It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually something like a SHA256. ### Prototype ```c int aws_ecc_key_pair_sign_message( const struct aws_ecc_key_pair *key_pair, const struct aws_byte_cursor *message, struct aws_byte_buf *signature); ``` """ function aws_ecc_key_pair_sign_message(key_pair, message, signature) ccall((:aws_ecc_key_pair_sign_message, libaws_c_cal), Cint, (Ptr{aws_ecc_key_pair}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}), key_pair, message, signature) end """ aws_ecc_key_pair_verify_signature(key_pair, message, signature) Uses the key\\_pair's public key to verify signature of message. Signature should be DER encoded. It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually something like a SHA256. returns AWS\\_OP\\_SUCCESS if the signature is valid. ### Prototype ```c int aws_ecc_key_pair_verify_signature( const struct aws_ecc_key_pair *key_pair, const struct aws_byte_cursor *message, const struct aws_byte_cursor *signature); ``` """ function aws_ecc_key_pair_verify_signature(key_pair, message, signature) ccall((:aws_ecc_key_pair_verify_signature, libaws_c_cal), Cint, (Ptr{aws_ecc_key_pair}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), key_pair, message, signature) end """ aws_ecc_key_pair_signature_length(key_pair) Documentation not found. ### Prototype ```c size_t aws_ecc_key_pair_signature_length(const struct aws_ecc_key_pair *key_pair); ``` """ function aws_ecc_key_pair_signature_length(key_pair) ccall((:aws_ecc_key_pair_signature_length, libaws_c_cal), Csize_t, (Ptr{aws_ecc_key_pair},), key_pair) end """ aws_ecc_key_pair_get_public_key(key_pair, pub_x, pub_y) Documentation not found. ### Prototype ```c void aws_ecc_key_pair_get_public_key( const struct aws_ecc_key_pair *key_pair, struct aws_byte_cursor *pub_x, struct aws_byte_cursor *pub_y); ``` """ function aws_ecc_key_pair_get_public_key(key_pair, pub_x, pub_y) ccall((:aws_ecc_key_pair_get_public_key, libaws_c_cal), Cvoid, (Ptr{aws_ecc_key_pair}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), key_pair, pub_x, pub_y) end """ aws_ecc_key_pair_get_private_key(key_pair, private_d) Documentation not found. ### Prototype ```c void aws_ecc_key_pair_get_private_key( const struct aws_ecc_key_pair *key_pair, struct aws_byte_cursor *private_d); ``` """ function aws_ecc_key_pair_get_private_key(key_pair, private_d) ccall((:aws_ecc_key_pair_get_private_key, libaws_c_cal), Cvoid, (Ptr{aws_ecc_key_pair}, Ptr{aws_byte_cursor}), key_pair, private_d) end """ aws_ecc_key_coordinate_byte_size_from_curve_name(curve_name) Documentation not found. ### Prototype ```c size_t aws_ecc_key_coordinate_byte_size_from_curve_name(enum aws_ecc_curve_name curve_name); ``` """ function aws_ecc_key_coordinate_byte_size_from_curve_name(curve_name) ccall((:aws_ecc_key_coordinate_byte_size_from_curve_name, libaws_c_cal), Csize_t, (aws_ecc_curve_name,), curve_name) end """ aws_hash_vtable Documentation not found. """ struct aws_hash_vtable alg_name::Ptr{Cchar} provider::Ptr{Cchar} destroy::Ptr{Cvoid} update::Ptr{Cvoid} finalize::Ptr{Cvoid} end """ aws_hash Documentation not found. """ struct aws_hash allocator::Ptr{aws_allocator} vtable::Ptr{aws_hash_vtable} digest_size::Csize_t good::Bool impl::Ptr{Cvoid} end # typedef struct aws_hash * ( aws_hash_new_fn ) ( struct aws_allocator * allocator ) """ Documentation not found. """ const aws_hash_new_fn = Cvoid """ aws_sha256_new(allocator) Allocates and initializes a sha256 hash instance. ### Prototype ```c struct aws_hash *aws_sha256_new(struct aws_allocator *allocator); ``` """ function aws_sha256_new(allocator) ccall((:aws_sha256_new, libaws_c_cal), Ptr{aws_hash}, (Ptr{aws_allocator},), allocator) end """ aws_sha1_new(allocator) Allocates and initializes a sha1 hash instance. ### Prototype ```c struct aws_hash *aws_sha1_new(struct aws_allocator *allocator); ``` """ function aws_sha1_new(allocator) ccall((:aws_sha1_new, libaws_c_cal), Ptr{aws_hash}, (Ptr{aws_allocator},), allocator) end """ aws_md5_new(allocator) Allocates and initializes an md5 hash instance. ### Prototype ```c struct aws_hash *aws_md5_new(struct aws_allocator *allocator); ``` """ function aws_md5_new(allocator) ccall((:aws_md5_new, libaws_c_cal), Ptr{aws_hash}, (Ptr{aws_allocator},), allocator) end """ aws_hash_destroy(hash) Cleans up and deallocates hash. ### Prototype ```c void aws_hash_destroy(struct aws_hash *hash); ``` """ function aws_hash_destroy(hash) ccall((:aws_hash_destroy, libaws_c_cal), Cvoid, (Ptr{aws_hash},), hash) end """ aws_hash_update(hash, to_hash) Updates the running hash with to\\_hash. this can be called multiple times. ### Prototype ```c int aws_hash_update(struct aws_hash *hash, const struct aws_byte_cursor *to_hash); ``` """ function aws_hash_update(hash, to_hash) ccall((:aws_hash_update, libaws_c_cal), Cint, (Ptr{aws_hash}, Ptr{aws_byte_cursor}), hash, to_hash) end """ aws_hash_finalize(hash, output, truncate_to) Completes the hash computation and writes the final digest to output. Allocation of output is the caller's responsibility. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example, if you want a SHA256 digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_hash_finalize(struct aws_hash *hash, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_hash_finalize(hash, output, truncate_to) ccall((:aws_hash_finalize, libaws_c_cal), Cint, (Ptr{aws_hash}, Ptr{aws_byte_buf}, Csize_t), hash, output, truncate_to) end """ aws_md5_compute(allocator, input, output, truncate_to) Computes the md5 hash over input and writes the digest output to 'output'. Use this if you don't need to stream the data you're hashing and you can load the entire input to hash into memory. ### Prototype ```c int aws_md5_compute( struct aws_allocator *allocator, const struct aws_byte_cursor *input, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_md5_compute(allocator, input, output, truncate_to) ccall((:aws_md5_compute, libaws_c_cal), Cint, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}, Csize_t), allocator, input, output, truncate_to) end """ aws_sha256_compute(allocator, input, output, truncate_to) Computes the sha256 hash over input and writes the digest output to 'output'. Use this if you don't need to stream the data you're hashing and you can load the entire input to hash into memory. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example, if you want a SHA256 digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_sha256_compute( struct aws_allocator *allocator, const struct aws_byte_cursor *input, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_sha256_compute(allocator, input, output, truncate_to) ccall((:aws_sha256_compute, libaws_c_cal), Cint, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}, Csize_t), allocator, input, output, truncate_to) end """ aws_sha1_compute(allocator, input, output, truncate_to) Computes the sha1 hash over input and writes the digest output to 'output'. Use this if you don't need to stream the data you're hashing and you can load the entire input to hash into memory. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example, if you want a SHA1 digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_sha1_compute( struct aws_allocator *allocator, const struct aws_byte_cursor *input, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_sha1_compute(allocator, input, output, truncate_to) ccall((:aws_sha1_compute, libaws_c_cal), Cint, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}, Csize_t), allocator, input, output, truncate_to) end """ aws_set_md5_new_fn(fn) Set the implementation of md5 to use. If you compiled without BYO\\_CRYPTO, you do not need to call this. However, if use this, we will honor it, regardless of compile options. This may be useful for testing purposes. If you did set BYO\\_CRYPTO, and you do not call this function you will segfault. ### Prototype ```c void aws_set_md5_new_fn(aws_hash_new_fn *fn); ``` """ function aws_set_md5_new_fn(fn) ccall((:aws_set_md5_new_fn, libaws_c_cal), Cvoid, (Ptr{aws_hash_new_fn},), fn) end """ aws_set_sha256_new_fn(fn) Set the implementation of sha256 to use. If you compiled without BYO\\_CRYPTO, you do not need to call this. However, if use this, we will honor it, regardless of compile options. This may be useful for testing purposes. If you did set BYO\\_CRYPTO, and you do not call this function you will segfault. ### Prototype ```c void aws_set_sha256_new_fn(aws_hash_new_fn *fn); ``` """ function aws_set_sha256_new_fn(fn) ccall((:aws_set_sha256_new_fn, libaws_c_cal), Cvoid, (Ptr{aws_hash_new_fn},), fn) end """ aws_set_sha1_new_fn(fn) Set the implementation of sha1 to use. If you compiled without BYO\\_CRYPTO, you do not need to call this. However, if use this, we will honor it, regardless of compile options. This may be useful for testing purposes. If you did set BYO\\_CRYPTO, and you do not call this function you will segfault. ### Prototype ```c void aws_set_sha1_new_fn(aws_hash_new_fn *fn); ``` """ function aws_set_sha1_new_fn(fn) ccall((:aws_set_sha1_new_fn, libaws_c_cal), Cvoid, (Ptr{aws_hash_new_fn},), fn) end """ aws_hmac_vtable Documentation not found. """ struct aws_hmac_vtable alg_name::Ptr{Cchar} provider::Ptr{Cchar} destroy::Ptr{Cvoid} update::Ptr{Cvoid} finalize::Ptr{Cvoid} end """ aws_hmac Documentation not found. """ struct aws_hmac allocator::Ptr{aws_allocator} vtable::Ptr{aws_hmac_vtable} digest_size::Csize_t good::Bool impl::Ptr{Cvoid} end # typedef struct aws_hmac * ( aws_hmac_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * secret ) """ Documentation not found. """ const aws_hmac_new_fn = Cvoid """ aws_sha256_hmac_new(allocator, secret) Allocates and initializes a sha256 hmac instance. Secret is the key to be used for the hmac process. ### Prototype ```c struct aws_hmac *aws_sha256_hmac_new(struct aws_allocator *allocator, const struct aws_byte_cursor *secret); ``` """ function aws_sha256_hmac_new(allocator, secret) ccall((:aws_sha256_hmac_new, libaws_c_cal), Ptr{aws_hmac}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}), allocator, secret) end """ aws_hmac_destroy(hmac) Cleans up and deallocates hmac. ### Prototype ```c void aws_hmac_destroy(struct aws_hmac *hmac); ``` """ function aws_hmac_destroy(hmac) ccall((:aws_hmac_destroy, libaws_c_cal), Cvoid, (Ptr{aws_hmac},), hmac) end """ aws_hmac_update(hmac, to_hmac) Updates the running hmac with to\\_hash. this can be called multiple times. ### Prototype ```c int aws_hmac_update(struct aws_hmac *hmac, const struct aws_byte_cursor *to_hmac); ``` """ function aws_hmac_update(hmac, to_hmac) ccall((:aws_hmac_update, libaws_c_cal), Cint, (Ptr{aws_hmac}, Ptr{aws_byte_cursor}), hmac, to_hmac) end """ aws_hmac_finalize(hmac, output, truncate_to) Completes the hmac computation and writes the final digest to output. Allocation of output is the caller's responsibility. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example if you want a SHA256 digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_hmac_finalize(struct aws_hmac *hmac, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_hmac_finalize(hmac, output, truncate_to) ccall((:aws_hmac_finalize, libaws_c_cal), Cint, (Ptr{aws_hmac}, Ptr{aws_byte_buf}, Csize_t), hmac, output, truncate_to) end """ aws_sha256_hmac_compute(allocator, secret, to_hmac, output, truncate_to) Computes the sha256 hmac over input and writes the digest output to 'output'. Use this if you don't need to stream the data you're hashing and you can load the entire input to hash into memory. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example if you want a SHA256 HMAC digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_sha256_hmac_compute( struct aws_allocator *allocator, const struct aws_byte_cursor *secret, const struct aws_byte_cursor *to_hmac, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_sha256_hmac_compute(allocator, secret, to_hmac, output, truncate_to) ccall((:aws_sha256_hmac_compute, libaws_c_cal), Cint, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}, Csize_t), allocator, secret, to_hmac, output, truncate_to) end """ aws_set_sha256_hmac_new_fn(fn) Set the implementation of sha256 hmac to use. If you compiled without BYO\\_CRYPTO, you do not need to call this. However, if use this, we will honor it, regardless of compile options. This may be useful for testing purposes. If you did set BYO\\_CRYPTO, and you do not call this function you will segfault. ### Prototype ```c void aws_set_sha256_hmac_new_fn(aws_hmac_new_fn *fn); ``` """ function aws_set_sha256_hmac_new_fn(fn) ccall((:aws_set_sha256_hmac_new_fn, libaws_c_cal), Cvoid, (Ptr{aws_hmac_new_fn},), fn) end """ Documentation not found. """ mutable struct aws_rsa_key_pair end """ aws_rsa_encryption_algorithm Documentation not found. """ @cenum aws_rsa_encryption_algorithm::UInt32 begin AWS_CAL_RSA_ENCRYPTION_PKCS1_5 = 0 AWS_CAL_RSA_ENCRYPTION_OAEP_SHA256 = 1 AWS_CAL_RSA_ENCRYPTION_OAEP_SHA512 = 2 end """ aws_rsa_signature_algorithm Documentation not found. """ @cenum aws_rsa_signature_algorithm::UInt32 begin AWS_CAL_RSA_SIGNATURE_PKCS1_5_SHA256 = 0 AWS_CAL_RSA_SIGNATURE_PSS_SHA256 = 1 end """ __JL_Ctag_55 Documentation not found. """ @cenum __JL_Ctag_55::UInt32 begin AWS_CAL_RSA_MIN_SUPPORTED_KEY_SIZE_IN_BITS = 1024 AWS_CAL_RSA_MAX_SUPPORTED_KEY_SIZE_IN_BITS = 4096 end """ aws_rsa_key_pair_new_from_public_key_pkcs1(allocator, key) Creates an RSA public key from RSAPublicKey as defined in rfc 8017 (aka PKCS1). Returns a new instance of [`aws_rsa_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. ### Prototype ```c struct aws_rsa_key_pair *aws_rsa_key_pair_new_from_public_key_pkcs1( struct aws_allocator *allocator, struct aws_byte_cursor key); ``` """ function aws_rsa_key_pair_new_from_public_key_pkcs1(allocator, key) ccall((:aws_rsa_key_pair_new_from_public_key_pkcs1, libaws_c_cal), Ptr{aws_rsa_key_pair}, (Ptr{aws_allocator}, aws_byte_cursor), allocator, key) end """ aws_rsa_key_pair_new_from_private_key_pkcs1(allocator, key) Creates an RSA private key from RSAPrivateKey as defined in rfc 8017 (aka PKCS1). Returns a new instance of [`aws_rsa_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. ### Prototype ```c struct aws_rsa_key_pair *aws_rsa_key_pair_new_from_private_key_pkcs1( struct aws_allocator *allocator, struct aws_byte_cursor key); ``` """ function aws_rsa_key_pair_new_from_private_key_pkcs1(allocator, key) ccall((:aws_rsa_key_pair_new_from_private_key_pkcs1, libaws_c_cal), Ptr{aws_rsa_key_pair}, (Ptr{aws_allocator}, aws_byte_cursor), allocator, key) end """ aws_rsa_key_pair_acquire(key_pair) Adds one to an RSA key pair's ref count. Returns key\\_pair pointer. ### Prototype ```c struct aws_rsa_key_pair *aws_rsa_key_pair_acquire(struct aws_rsa_key_pair *key_pair); ``` """ function aws_rsa_key_pair_acquire(key_pair) ccall((:aws_rsa_key_pair_acquire, libaws_c_cal), Ptr{aws_rsa_key_pair}, (Ptr{aws_rsa_key_pair},), key_pair) end """ aws_rsa_key_pair_release(key_pair) Subtracts one from an RSA key pair's ref count. If ref count reaches zero, the key pair is destroyed. Always returns NULL. ### Prototype ```c struct aws_rsa_key_pair *aws_rsa_key_pair_release(struct aws_rsa_key_pair *key_pair); ``` """ function aws_rsa_key_pair_release(key_pair) ccall((:aws_rsa_key_pair_release, libaws_c_cal), Ptr{aws_rsa_key_pair}, (Ptr{aws_rsa_key_pair},), key_pair) end """ aws_rsa_key_pair_max_encrypt_plaintext_size(key_pair, algorithm) Max plaintext size that can be encrypted by the key (i.e. max data size supported by the key - bytes needed for padding). ### Prototype ```c size_t aws_rsa_key_pair_max_encrypt_plaintext_size( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_encryption_algorithm algorithm); ``` """ function aws_rsa_key_pair_max_encrypt_plaintext_size(key_pair, algorithm) ccall((:aws_rsa_key_pair_max_encrypt_plaintext_size, libaws_c_cal), Csize_t, (Ptr{aws_rsa_key_pair}, aws_rsa_encryption_algorithm), key_pair, algorithm) end """ aws_rsa_key_pair_encrypt(key_pair, algorithm, plaintext, out) Documentation not found. ### Prototype ```c int aws_rsa_key_pair_encrypt( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_encryption_algorithm algorithm, struct aws_byte_cursor plaintext, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_encrypt(key_pair, algorithm, plaintext, out) ccall((:aws_rsa_key_pair_encrypt, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_encryption_algorithm, aws_byte_cursor, Ptr{aws_byte_buf}), key_pair, algorithm, plaintext, out) end """ aws_rsa_key_pair_decrypt(key_pair, algorithm, ciphertext, out) Documentation not found. ### Prototype ```c int aws_rsa_key_pair_decrypt( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_encryption_algorithm algorithm, struct aws_byte_cursor ciphertext, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_decrypt(key_pair, algorithm, ciphertext, out) ccall((:aws_rsa_key_pair_decrypt, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_encryption_algorithm, aws_byte_cursor, Ptr{aws_byte_buf}), key_pair, algorithm, ciphertext, out) end """ aws_rsa_key_pair_block_length(key_pair) Documentation not found. ### Prototype ```c size_t aws_rsa_key_pair_block_length(const struct aws_rsa_key_pair *key_pair); ``` """ function aws_rsa_key_pair_block_length(key_pair) ccall((:aws_rsa_key_pair_block_length, libaws_c_cal), Csize_t, (Ptr{aws_rsa_key_pair},), key_pair) end """ aws_rsa_key_pair_sign_message(key_pair, algorithm, digest, out) Uses the key\\_pair's private key to sign message. The output will be in out. out must be large enough to hold the signature. Check [`aws_rsa_key_pair_signature_length`](@ref)() for the appropriate size. It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually something like a SHA256. ### Prototype ```c int aws_rsa_key_pair_sign_message( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_signature_algorithm algorithm, struct aws_byte_cursor digest, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_sign_message(key_pair, algorithm, digest, out) ccall((:aws_rsa_key_pair_sign_message, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_signature_algorithm, aws_byte_cursor, Ptr{aws_byte_buf}), key_pair, algorithm, digest, out) end """ aws_rsa_key_pair_verify_signature(key_pair, algorithm, digest, signature) Uses the key\\_pair's public key to verify signature of message. It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually something like a SHA256. returns AWS\\_OP\\_SUCCESS if the signature is valid. raises AWS\\_ERROR\\_CAL\\_SIGNATURE\\_VALIDATION\\_FAILED if signature validation failed ### Prototype ```c int aws_rsa_key_pair_verify_signature( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_signature_algorithm algorithm, struct aws_byte_cursor digest, struct aws_byte_cursor signature); ``` """ function aws_rsa_key_pair_verify_signature(key_pair, algorithm, digest, signature) ccall((:aws_rsa_key_pair_verify_signature, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_signature_algorithm, aws_byte_cursor, aws_byte_cursor), key_pair, algorithm, digest, signature) end """ aws_rsa_key_pair_signature_length(key_pair) Documentation not found. ### Prototype ```c size_t aws_rsa_key_pair_signature_length(const struct aws_rsa_key_pair *key_pair); ``` """ function aws_rsa_key_pair_signature_length(key_pair) ccall((:aws_rsa_key_pair_signature_length, libaws_c_cal), Csize_t, (Ptr{aws_rsa_key_pair},), key_pair) end """ aws_rsa_key_export_format Documentation not found. """ @cenum aws_rsa_key_export_format::UInt32 begin AWS_CAL_RSA_KEY_EXPORT_PKCS1 = 0 end """ aws_rsa_key_pair_get_public_key(key_pair, format, out) Documentation not found. ### Prototype ```c int aws_rsa_key_pair_get_public_key( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_key_export_format format, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_get_public_key(key_pair, format, out) ccall((:aws_rsa_key_pair_get_public_key, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_key_export_format, Ptr{aws_byte_buf}), key_pair, format, out) end """ aws_rsa_key_pair_get_private_key(key_pair, format, out) Documentation not found. ### Prototype ```c int aws_rsa_key_pair_get_private_key( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_key_export_format format, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_get_private_key(key_pair, format, out) ccall((:aws_rsa_key_pair_get_private_key, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_key_export_format, Ptr{aws_byte_buf}), key_pair, format, out) end """ Documentation not found. """ mutable struct aws_symmetric_cipher end # typedef struct aws_symmetric_cipher * ( aws_aes_cbc_256_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * key , const struct aws_byte_cursor * iv ) """ Documentation not found. """ const aws_aes_cbc_256_new_fn = Cvoid # typedef struct aws_symmetric_cipher * ( aws_aes_ctr_256_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * key , const struct aws_byte_cursor * iv ) """ Documentation not found. """ const aws_aes_ctr_256_new_fn = Cvoid # typedef struct aws_symmetric_cipher * ( aws_aes_gcm_256_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * key , const struct aws_byte_cursor * iv , const struct aws_byte_cursor * aad ) """ Documentation not found. """ const aws_aes_gcm_256_new_fn = Cvoid # typedef struct aws_symmetric_cipher * ( aws_aes_keywrap_256_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * key ) """ Documentation not found. """ const aws_aes_keywrap_256_new_fn = Cvoid """ aws_symmetric_cipher_state Documentation not found. """ @cenum aws_symmetric_cipher_state::UInt32 begin AWS_SYMMETRIC_CIPHER_READY = 0 AWS_SYMMETRIC_CIPHER_FINALIZED = 1 AWS_SYMMETRIC_CIPHER_ERROR = 2 end """ aws_aes_cbc_256_new(allocator, key, iv) Creates an instance of AES CBC with 256-bit key. If key and iv are NULL, they will be generated internally. You can get the generated key and iv back by calling: [`aws_symmetric_cipher_get_key`](@ref)() and [`aws_symmetric_cipher_get_initialization_vector`](@ref)() respectively. If they are set, that key and iv will be copied internally and used by the cipher. Returns NULL on failure. You can check aws\\_last\\_error() to get the error code indicating the failure cause. ### Prototype ```c struct aws_symmetric_cipher *aws_aes_cbc_256_new( struct aws_allocator *allocator, const struct aws_byte_cursor *key, const struct aws_byte_cursor *iv); ``` """ function aws_aes_cbc_256_new(allocator, key, iv) ccall((:aws_aes_cbc_256_new, libaws_c_cal), Ptr{aws_symmetric_cipher}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), allocator, key, iv) end """ aws_aes_ctr_256_new(allocator, key, iv) Creates an instance of AES CTR with 256-bit key. If key and iv are NULL, they will be generated internally. You can get the generated key and iv back by calling: [`aws_symmetric_cipher_get_key`](@ref)() and [`aws_symmetric_cipher_get_initialization_vector`](@ref)() respectively. If they are set, that key and iv will be copied internally and used by the cipher. Returns NULL on failure. You can check aws\\_last\\_error() to get the error code indicating the failure cause. ### Prototype ```c struct aws_symmetric_cipher *aws_aes_ctr_256_new( struct aws_allocator *allocator, const struct aws_byte_cursor *key, const struct aws_byte_cursor *iv); ``` """ function aws_aes_ctr_256_new(allocator, key, iv) ccall((:aws_aes_ctr_256_new, libaws_c_cal), Ptr{aws_symmetric_cipher}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), allocator, key, iv) end """ aws_aes_gcm_256_new(allocator, key, iv, aad) Creates an instance of AES GCM with 256-bit key. If key, iv are NULL, they will be generated internally. You can get the generated key and iv back by calling: [`aws_symmetric_cipher_get_key`](@ref)() and [`aws_symmetric_cipher_get_initialization_vector`](@ref)() respectively. If aad is set it will be copied and applied to the cipher. If they are set, that key and iv will be copied internally and used by the cipher. For decryption purposes tag can be provided via [`aws_symmetric_cipher_set_tag`](@ref) method. Note: for decrypt operations, tag must be provided before first decrypt is called. (this is a windows bcrypt limitations, but for consistency sake same limitation is extended to other platforms) Tag generated during encryption can be retrieved using [`aws_symmetric_cipher_get_tag`](@ref) method after finalize is called. Returns NULL on failure. You can check aws\\_last\\_error() to get the error code indicating the failure cause. ### Prototype ```c struct aws_symmetric_cipher *aws_aes_gcm_256_new( struct aws_allocator *allocator, const struct aws_byte_cursor *key, const struct aws_byte_cursor *iv, const struct aws_byte_cursor *aad); ``` """ function aws_aes_gcm_256_new(allocator, key, iv, aad) ccall((:aws_aes_gcm_256_new, libaws_c_cal), Ptr{aws_symmetric_cipher}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), allocator, key, iv, aad) end """ aws_aes_keywrap_256_new(allocator, key) Creates an instance of AES Keywrap with 256-bit key. If key is NULL, it will be generated internally. You can get the generated key back by calling: [`aws_symmetric_cipher_get_key`](@ref)() If key is set, that key will be copied internally and used by the cipher. Returns NULL on failure. You can check aws\\_last\\_error() to get the error code indicating the failure cause. ### Prototype ```c struct aws_symmetric_cipher *aws_aes_keywrap_256_new( struct aws_allocator *allocator, const struct aws_byte_cursor *key); ``` """ function aws_aes_keywrap_256_new(allocator, key) ccall((:aws_aes_keywrap_256_new, libaws_c_cal), Ptr{aws_symmetric_cipher}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}), allocator, key) end """ aws_symmetric_cipher_destroy(cipher) Cleans up internal resources and state for cipher and then deallocates it. ### Prototype ```c void aws_symmetric_cipher_destroy(struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_destroy(cipher) ccall((:aws_symmetric_cipher_destroy, libaws_c_cal), Cvoid, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_encrypt(cipher, to_encrypt, out) Encrypts the value in to\\_encrypt and writes the encrypted data into out. If out is dynamic it will be expanded. If it is not, and out is not large enough to handle the encrypted output, the call will fail. If you're trying to optimize to use a stack based array or something, make sure it's at least as large as the size of to\\_encrypt + an extra BLOCK to account for padding etc... returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_encrypt( struct aws_symmetric_cipher *cipher, struct aws_byte_cursor to_encrypt, struct aws_byte_buf *out); ``` """ function aws_symmetric_cipher_encrypt(cipher, to_encrypt, out) ccall((:aws_symmetric_cipher_encrypt, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher}, aws_byte_cursor, Ptr{aws_byte_buf}), cipher, to_encrypt, out) end """ aws_symmetric_cipher_decrypt(cipher, to_decrypt, out) Decrypts the value in to\\_decrypt and writes the decrypted data into out. If out is dynamic it will be expanded. If it is not, and out is not large enough to handle the decrypted output, the call will fail. If you're trying to optimize to use a stack based array or something, make sure it's at least as large as the size of to\\_decrypt + an extra BLOCK to account for padding etc... returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_decrypt( struct aws_symmetric_cipher *cipher, struct aws_byte_cursor to_decrypt, struct aws_byte_buf *out); ``` """ function aws_symmetric_cipher_decrypt(cipher, to_decrypt, out) ccall((:aws_symmetric_cipher_decrypt, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher}, aws_byte_cursor, Ptr{aws_byte_buf}), cipher, to_decrypt, out) end """ aws_symmetric_cipher_finalize_encryption(cipher, out) Encrypts any remaining data that was reserved for final padding, loads GMACs etc... and if there is any writes any remaining encrypted data to out. If out is dynamic it will be expanded. If it is not, and out is not large enough to handle the decrypted output, the call will fail. If you're trying to optimize to use a stack based array or something, make sure it's at least as large as the size of 2 BLOCKs to account for padding etc... After invoking this function, you MUST call [`aws_symmetric_cipher_reset`](@ref)() before invoking any encrypt/decrypt operations on this cipher again. returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_finalize_encryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out); ``` """ function aws_symmetric_cipher_finalize_encryption(cipher, out) ccall((:aws_symmetric_cipher_finalize_encryption, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher}, Ptr{aws_byte_buf}), cipher, out) end """ aws_symmetric_cipher_finalize_decryption(cipher, out) Decrypts any remaining data that was reserved for final padding, loads GMACs etc... and if there is any writes any remaining decrypted data to out. If out is dynamic it will be expanded. If it is not, and out is not large enough to handle the decrypted output, the call will fail. If you're trying to optimize to use a stack based array or something, make sure it's at least as large as the size of 2 BLOCKs to account for padding etc... After invoking this function, you MUST call [`aws_symmetric_cipher_reset`](@ref)() before invoking any encrypt/decrypt operations on this cipher again. returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_finalize_decryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out); ``` """ function aws_symmetric_cipher_finalize_decryption(cipher, out) ccall((:aws_symmetric_cipher_finalize_decryption, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher}, Ptr{aws_byte_buf}), cipher, out) end """ aws_symmetric_cipher_reset(cipher) Resets the cipher state for starting a new encrypt or decrypt operation. Note encrypt/decrypt cannot be mixed on the same cipher without a call to reset in between them. However, this leaves the key, iv etc... materials setup for immediate reuse. Note: GCM tag is not preserved between operations. If you intend to do encrypt followed directly by decrypt, make sure to make a copy of tag before reseting the cipher and pass that copy for decryption. Warning: In most cases it's a really bad idea to reset a cipher and perform another operation using that cipher. Key and IV should not be reused for different operations. Instead of reseting the cipher, destroy the cipher and create new one with a new key/iv pair. Use reset at your own risk, and only after careful consideration. returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_reset(struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_reset(cipher) ccall((:aws_symmetric_cipher_reset, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_get_tag(cipher) Gets the current GMAC tag. If not AES GCM, this function will just return an empty cursor. The memory in this cursor is unsafe as it refers to the internal buffer. This was done because the use case doesn't require fetching these during an encryption or decryption operation and it dramatically simplifies the API. Only use this function between other calls to this API as any function call can alter the value of this tag. If you need to access it in a different pattern, copy the values to your own buffer first. ### Prototype ```c struct aws_byte_cursor aws_symmetric_cipher_get_tag(const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_get_tag(cipher) ccall((:aws_symmetric_cipher_get_tag, libaws_c_cal), aws_byte_cursor, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_set_tag(cipher, tag) Sets the GMAC tag on the cipher. Does nothing for ciphers that do not support tag. ### Prototype ```c void aws_symmetric_cipher_set_tag(struct aws_symmetric_cipher *cipher, struct aws_byte_cursor tag); ``` """ function aws_symmetric_cipher_set_tag(cipher, tag) ccall((:aws_symmetric_cipher_set_tag, libaws_c_cal), Cvoid, (Ptr{aws_symmetric_cipher}, aws_byte_cursor), cipher, tag) end """ aws_symmetric_cipher_get_initialization_vector(cipher) Gets the original initialization vector as a cursor. The memory in this cursor is unsafe as it refers to the internal buffer. This was done because the use case doesn't require fetching these during an encryption or decryption operation and it dramatically simplifies the API. Unlike some other fields, this value does not change after the inital construction of the cipher. For some algorithms, such as AES Keywrap, this will return an empty cursor. ### Prototype ```c struct aws_byte_cursor aws_symmetric_cipher_get_initialization_vector( const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_get_initialization_vector(cipher) ccall((:aws_symmetric_cipher_get_initialization_vector, libaws_c_cal), aws_byte_cursor, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_get_key(cipher) Gets the original key. The memory in this cursor is unsafe as it refers to the internal buffer. This was done because the use case doesn't require fetching these during an encryption or decryption operation and it dramatically simplifies the API. Unlike some other fields, this value does not change after the inital construction of the cipher. ### Prototype ```c struct aws_byte_cursor aws_symmetric_cipher_get_key(const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_get_key(cipher) ccall((:aws_symmetric_cipher_get_key, libaws_c_cal), aws_byte_cursor, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_is_good(cipher) Returns true if the state of the cipher is good, and otherwise returns false. Most operations, other than [`aws_symmetric_cipher_reset`](@ref)() will fail if this function is returning false. [`aws_symmetric_cipher_reset`](@ref)() will reset the state to a good state if possible. ### Prototype ```c bool aws_symmetric_cipher_is_good(const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_is_good(cipher) ccall((:aws_symmetric_cipher_is_good, libaws_c_cal), Bool, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_get_state(cipher) Retuns the current state of the cipher. Ther state of the cipher can be ready for use, finalized, or has encountered an error. if the cipher is in a finished or error state, it must be reset before further use. ### Prototype ```c enum aws_symmetric_cipher_state aws_symmetric_cipher_get_state(const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_get_state(cipher) ccall((:aws_symmetric_cipher_get_state, libaws_c_cal), aws_symmetric_cipher_state, (Ptr{aws_symmetric_cipher},), cipher) end """ Documentation not found. """ const AWS_C_CAL_PACKAGE_ID = 7 """ Documentation not found. """ const AWS_SHA256_LEN = 32 """ Documentation not found. """ const AWS_SHA1_LEN = 20 """ Documentation not found. """ const AWS_MD5_LEN = 16 """ Documentation not found. """ const AWS_SHA256_HMAC_LEN = 32 """ Documentation not found. """ const AWS_AES_256_CIPHER_BLOCK_SIZE = 16 """ Documentation not found. """ const AWS_AES_256_KEY_BIT_LEN = 256 """ Documentation not found. """ const AWS_AES_256_KEY_BYTE_LEN = AWS_AES_256_KEY_BIT_LEN ÷ 8
LibAwsCal
https://github.com/JuliaServices/LibAwsCal.jl.git
[ "MIT" ]
1.1.0
ea84a3fc5acae82883d2c3ce3579d461d26a47e2
code
48612
using CEnum """ aws_cal_errors Documentation not found. """ @cenum aws_cal_errors::UInt32 begin AWS_ERROR_CAL_SIGNATURE_VALIDATION_FAILED = 7168 AWS_ERROR_CAL_MISSING_REQUIRED_KEY_COMPONENT = 7169 AWS_ERROR_CAL_INVALID_KEY_LENGTH_FOR_ALGORITHM = 7170 AWS_ERROR_CAL_UNKNOWN_OBJECT_IDENTIFIER = 7171 AWS_ERROR_CAL_MALFORMED_ASN1_ENCOUNTERED = 7172 AWS_ERROR_CAL_MISMATCHED_DER_TYPE = 7173 AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM = 7174 AWS_ERROR_CAL_BUFFER_TOO_LARGE_FOR_ALGORITHM = 7175 AWS_ERROR_CAL_INVALID_CIPHER_MATERIAL_SIZE_FOR_ALGORITHM = 7176 AWS_ERROR_CAL_DER_UNSUPPORTED_NEGATIVE_INT = 7177 AWS_ERROR_CAL_UNSUPPORTED_KEY_FORMAT = 7178 AWS_ERROR_CAL_CRYPTO_OPERATION_FAILED = 7179 AWS_ERROR_CAL_END_RANGE = 8191 end """ aws_cal_log_subject Documentation not found. """ @cenum aws_cal_log_subject::UInt32 begin AWS_LS_CAL_GENERAL = 7168 AWS_LS_CAL_ECC = 7169 AWS_LS_CAL_HASH = 7170 AWS_LS_CAL_HMAC = 7171 AWS_LS_CAL_DER = 7172 AWS_LS_CAL_LIBCRYPTO_RESOLVE = 7173 AWS_LS_CAL_RSA = 7174 AWS_LS_CAL_LAST = 8191 end """ aws_cal_library_init(allocator) Documentation not found. ### Prototype ```c void aws_cal_library_init(struct aws_allocator *allocator); ``` """ function aws_cal_library_init(allocator) ccall((:aws_cal_library_init, libaws_c_cal), Cvoid, (Ptr{aws_allocator},), allocator) end """ aws_cal_library_clean_up() Documentation not found. ### Prototype ```c void aws_cal_library_clean_up(void); ``` """ function aws_cal_library_clean_up() ccall((:aws_cal_library_clean_up, libaws_c_cal), Cvoid, ()) end """ aws_cal_thread_clean_up() Documentation not found. ### Prototype ```c void aws_cal_thread_clean_up(void); ``` """ function aws_cal_thread_clean_up() ccall((:aws_cal_thread_clean_up, libaws_c_cal), Cvoid, ()) end """ aws_ecc_curve_name Documentation not found. """ @cenum aws_ecc_curve_name::UInt32 begin AWS_CAL_ECDSA_P256 = 0 AWS_CAL_ECDSA_P384 = 1 end # typedef void aws_ecc_key_pair_destroy_fn ( struct aws_ecc_key_pair * key_pair ) """ Documentation not found. """ const aws_ecc_key_pair_destroy_fn = Cvoid # typedef int aws_ecc_key_pair_sign_message_fn ( const struct aws_ecc_key_pair * key_pair , const struct aws_byte_cursor * message , struct aws_byte_buf * signature_output ) """ Documentation not found. """ const aws_ecc_key_pair_sign_message_fn = Cvoid # typedef int aws_ecc_key_pair_derive_public_key_fn ( struct aws_ecc_key_pair * key_pair ) """ Documentation not found. """ const aws_ecc_key_pair_derive_public_key_fn = Cvoid # typedef int aws_ecc_key_pair_verify_signature_fn ( const struct aws_ecc_key_pair * signer , const struct aws_byte_cursor * message , const struct aws_byte_cursor * signature ) """ Documentation not found. """ const aws_ecc_key_pair_verify_signature_fn = Cvoid # typedef size_t aws_ecc_key_pair_signature_length_fn ( const struct aws_ecc_key_pair * signer ) """ Documentation not found. """ const aws_ecc_key_pair_signature_length_fn = Cvoid """ aws_ecc_key_pair_vtable Documentation not found. """ struct aws_ecc_key_pair_vtable destroy::Ptr{aws_ecc_key_pair_destroy_fn} derive_pub_key::Ptr{aws_ecc_key_pair_derive_public_key_fn} sign_message::Ptr{aws_ecc_key_pair_sign_message_fn} verify_signature::Ptr{aws_ecc_key_pair_verify_signature_fn} signature_length::Ptr{aws_ecc_key_pair_signature_length_fn} end """ aws_ecc_key_pair Documentation not found. """ struct aws_ecc_key_pair allocator::Ptr{aws_allocator} ref_count::aws_atomic_var curve_name::aws_ecc_curve_name key_buf::aws_byte_buf pub_x::aws_byte_buf pub_y::aws_byte_buf priv_d::aws_byte_buf vtable::Ptr{aws_ecc_key_pair_vtable} impl::Ptr{Cvoid} end """ aws_ecc_key_pair_acquire(key_pair) Adds one to an ecc key pair's ref count. ### Prototype ```c void aws_ecc_key_pair_acquire(struct aws_ecc_key_pair *key_pair); ``` """ function aws_ecc_key_pair_acquire(key_pair) ccall((:aws_ecc_key_pair_acquire, libaws_c_cal), Cvoid, (Ptr{aws_ecc_key_pair},), key_pair) end """ aws_ecc_key_pair_release(key_pair) Subtracts one from an ecc key pair's ref count. If ref count reaches zero, the key pair is destroyed. ### Prototype ```c void aws_ecc_key_pair_release(struct aws_ecc_key_pair *key_pair); ``` """ function aws_ecc_key_pair_release(key_pair) ccall((:aws_ecc_key_pair_release, libaws_c_cal), Cvoid, (Ptr{aws_ecc_key_pair},), key_pair) end """ aws_ecc_key_pair_new_from_private_key(allocator, curve_name, priv_key) Creates an Elliptic Curve private key that can be used for signing. Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. Note: priv\\_key::len must match the appropriate length for the selected curve\\_name. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_pair_new_from_private_key( struct aws_allocator *allocator, enum aws_ecc_curve_name curve_name, const struct aws_byte_cursor *priv_key); ``` """ function aws_ecc_key_pair_new_from_private_key(allocator, curve_name, priv_key) ccall((:aws_ecc_key_pair_new_from_private_key, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, aws_ecc_curve_name, Ptr{aws_byte_cursor}), allocator, curve_name, priv_key) end """ aws_ecc_key_pair_new_generate_random(allocator, curve_name) Creates an Elliptic Curve public/private key pair that can be used for signing and verifying. Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. Note: On Apple platforms this function is only supported on MacOS. This is due to usage of SecItemExport, which is only available on MacOS 10.7+ (yes, MacOS only and no other Apple platforms). There are alternatives for ios and other platforms, but they are ugly to use. Hence for now it only supports this call on MacOS. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_pair_new_generate_random( struct aws_allocator *allocator, enum aws_ecc_curve_name curve_name); ``` """ function aws_ecc_key_pair_new_generate_random(allocator, curve_name) ccall((:aws_ecc_key_pair_new_generate_random, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, aws_ecc_curve_name), allocator, curve_name) end """ aws_ecc_key_pair_new_from_public_key(allocator, curve_name, public_key_x, public_key_y) Creates an Elliptic Curve public key that can be used for verifying. Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. Note: public\\_key\\_x::len and public\\_key\\_y::len must match the appropriate length for the selected curve\\_name. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_pair_new_from_public_key( struct aws_allocator *allocator, enum aws_ecc_curve_name curve_name, const struct aws_byte_cursor *public_key_x, const struct aws_byte_cursor *public_key_y); ``` """ function aws_ecc_key_pair_new_from_public_key(allocator, curve_name, public_key_x, public_key_y) ccall((:aws_ecc_key_pair_new_from_public_key, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, aws_ecc_curve_name, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), allocator, curve_name, public_key_x, public_key_y) end """ aws_ecc_key_pair_new_from_asn1(allocator, encoded_keys) Creates an Elliptic Curve public/private key pair from a DER encoded key pair. Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. Whether or not signing or verification can be perform depends on if encoded\\_keys is a public/private pair or a public key. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_pair_new_from_asn1( struct aws_allocator *allocator, const struct aws_byte_cursor *encoded_keys); ``` """ function aws_ecc_key_pair_new_from_asn1(allocator, encoded_keys) ccall((:aws_ecc_key_pair_new_from_asn1, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}), allocator, encoded_keys) end """ aws_ecc_key_new_from_hex_coordinates(allocator, curve_name, pub_x_hex_cursor, pub_y_hex_cursor) Creates an Elliptic curve public key from x and y coordinates encoded as hex strings Returns a new instance of [`aws_ecc_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. ### Prototype ```c struct aws_ecc_key_pair *aws_ecc_key_new_from_hex_coordinates( struct aws_allocator *allocator, enum aws_ecc_curve_name curve_name, struct aws_byte_cursor pub_x_hex_cursor, struct aws_byte_cursor pub_y_hex_cursor); ``` """ function aws_ecc_key_new_from_hex_coordinates(allocator, curve_name, pub_x_hex_cursor, pub_y_hex_cursor) ccall((:aws_ecc_key_new_from_hex_coordinates, libaws_c_cal), Ptr{aws_ecc_key_pair}, (Ptr{aws_allocator}, aws_ecc_curve_name, aws_byte_cursor, aws_byte_cursor), allocator, curve_name, pub_x_hex_cursor, pub_y_hex_cursor) end """ aws_ecc_key_pair_derive_public_key(key_pair) Derives a public key from the private key if supported by this operating system (not supported on OSX). key\\_pair::pub\\_x and key\\_pair::pub\\_y will be set with the raw key buffers. ### Prototype ```c int aws_ecc_key_pair_derive_public_key(struct aws_ecc_key_pair *key_pair); ``` """ function aws_ecc_key_pair_derive_public_key(key_pair) ccall((:aws_ecc_key_pair_derive_public_key, libaws_c_cal), Cint, (Ptr{aws_ecc_key_pair},), key_pair) end """ aws_ecc_curve_name_from_oid(oid, curve_name) Get the curve name from the oid. OID here is the payload of the DER encoded ASN.1 part (doesn't include type specifier or length. On success, the value of curve\\_name will be set. ### Prototype ```c int aws_ecc_curve_name_from_oid(struct aws_byte_cursor *oid, enum aws_ecc_curve_name *curve_name); ``` """ function aws_ecc_curve_name_from_oid(oid, curve_name) ccall((:aws_ecc_curve_name_from_oid, libaws_c_cal), Cint, (Ptr{aws_byte_cursor}, Ptr{aws_ecc_curve_name}), oid, curve_name) end """ aws_ecc_oid_from_curve_name(curve_name, oid) Get the DER encoded OID from the curve\\_name. The OID in this case will not contain the type or the length specifier. ### Prototype ```c int aws_ecc_oid_from_curve_name(enum aws_ecc_curve_name curve_name, struct aws_byte_cursor *oid); ``` """ function aws_ecc_oid_from_curve_name(curve_name, oid) ccall((:aws_ecc_oid_from_curve_name, libaws_c_cal), Cint, (aws_ecc_curve_name, Ptr{aws_byte_cursor}), curve_name, oid) end """ aws_ecc_key_pair_sign_message(key_pair, message, signature) Uses the key\\_pair's private key to sign message. The output will be in signature. Signature must be large enough to hold the signature. Check [`aws_ecc_key_pair_signature_length`](@ref)() for the appropriate size. Signature will be DER encoded. It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually something like a SHA256. ### Prototype ```c int aws_ecc_key_pair_sign_message( const struct aws_ecc_key_pair *key_pair, const struct aws_byte_cursor *message, struct aws_byte_buf *signature); ``` """ function aws_ecc_key_pair_sign_message(key_pair, message, signature) ccall((:aws_ecc_key_pair_sign_message, libaws_c_cal), Cint, (Ptr{aws_ecc_key_pair}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}), key_pair, message, signature) end """ aws_ecc_key_pair_verify_signature(key_pair, message, signature) Uses the key\\_pair's public key to verify signature of message. Signature should be DER encoded. It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually something like a SHA256. returns AWS\\_OP\\_SUCCESS if the signature is valid. ### Prototype ```c int aws_ecc_key_pair_verify_signature( const struct aws_ecc_key_pair *key_pair, const struct aws_byte_cursor *message, const struct aws_byte_cursor *signature); ``` """ function aws_ecc_key_pair_verify_signature(key_pair, message, signature) ccall((:aws_ecc_key_pair_verify_signature, libaws_c_cal), Cint, (Ptr{aws_ecc_key_pair}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), key_pair, message, signature) end """ aws_ecc_key_pair_signature_length(key_pair) Documentation not found. ### Prototype ```c size_t aws_ecc_key_pair_signature_length(const struct aws_ecc_key_pair *key_pair); ``` """ function aws_ecc_key_pair_signature_length(key_pair) ccall((:aws_ecc_key_pair_signature_length, libaws_c_cal), Csize_t, (Ptr{aws_ecc_key_pair},), key_pair) end """ aws_ecc_key_pair_get_public_key(key_pair, pub_x, pub_y) Documentation not found. ### Prototype ```c void aws_ecc_key_pair_get_public_key( const struct aws_ecc_key_pair *key_pair, struct aws_byte_cursor *pub_x, struct aws_byte_cursor *pub_y); ``` """ function aws_ecc_key_pair_get_public_key(key_pair, pub_x, pub_y) ccall((:aws_ecc_key_pair_get_public_key, libaws_c_cal), Cvoid, (Ptr{aws_ecc_key_pair}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), key_pair, pub_x, pub_y) end """ aws_ecc_key_pair_get_private_key(key_pair, private_d) Documentation not found. ### Prototype ```c void aws_ecc_key_pair_get_private_key( const struct aws_ecc_key_pair *key_pair, struct aws_byte_cursor *private_d); ``` """ function aws_ecc_key_pair_get_private_key(key_pair, private_d) ccall((:aws_ecc_key_pair_get_private_key, libaws_c_cal), Cvoid, (Ptr{aws_ecc_key_pair}, Ptr{aws_byte_cursor}), key_pair, private_d) end """ aws_ecc_key_coordinate_byte_size_from_curve_name(curve_name) Documentation not found. ### Prototype ```c size_t aws_ecc_key_coordinate_byte_size_from_curve_name(enum aws_ecc_curve_name curve_name); ``` """ function aws_ecc_key_coordinate_byte_size_from_curve_name(curve_name) ccall((:aws_ecc_key_coordinate_byte_size_from_curve_name, libaws_c_cal), Csize_t, (aws_ecc_curve_name,), curve_name) end """ aws_hash_vtable Documentation not found. """ struct aws_hash_vtable alg_name::Ptr{Cchar} provider::Ptr{Cchar} destroy::Ptr{Cvoid} update::Ptr{Cvoid} finalize::Ptr{Cvoid} end """ aws_hash Documentation not found. """ struct aws_hash allocator::Ptr{aws_allocator} vtable::Ptr{aws_hash_vtable} digest_size::Csize_t good::Bool impl::Ptr{Cvoid} end # typedef struct aws_hash * ( aws_hash_new_fn ) ( struct aws_allocator * allocator ) """ Documentation not found. """ const aws_hash_new_fn = Cvoid """ aws_sha256_new(allocator) Allocates and initializes a sha256 hash instance. ### Prototype ```c struct aws_hash *aws_sha256_new(struct aws_allocator *allocator); ``` """ function aws_sha256_new(allocator) ccall((:aws_sha256_new, libaws_c_cal), Ptr{aws_hash}, (Ptr{aws_allocator},), allocator) end """ aws_sha1_new(allocator) Allocates and initializes a sha1 hash instance. ### Prototype ```c struct aws_hash *aws_sha1_new(struct aws_allocator *allocator); ``` """ function aws_sha1_new(allocator) ccall((:aws_sha1_new, libaws_c_cal), Ptr{aws_hash}, (Ptr{aws_allocator},), allocator) end """ aws_md5_new(allocator) Allocates and initializes an md5 hash instance. ### Prototype ```c struct aws_hash *aws_md5_new(struct aws_allocator *allocator); ``` """ function aws_md5_new(allocator) ccall((:aws_md5_new, libaws_c_cal), Ptr{aws_hash}, (Ptr{aws_allocator},), allocator) end """ aws_hash_destroy(hash) Cleans up and deallocates hash. ### Prototype ```c void aws_hash_destroy(struct aws_hash *hash); ``` """ function aws_hash_destroy(hash) ccall((:aws_hash_destroy, libaws_c_cal), Cvoid, (Ptr{aws_hash},), hash) end """ aws_hash_update(hash, to_hash) Updates the running hash with to\\_hash. this can be called multiple times. ### Prototype ```c int aws_hash_update(struct aws_hash *hash, const struct aws_byte_cursor *to_hash); ``` """ function aws_hash_update(hash, to_hash) ccall((:aws_hash_update, libaws_c_cal), Cint, (Ptr{aws_hash}, Ptr{aws_byte_cursor}), hash, to_hash) end """ aws_hash_finalize(hash, output, truncate_to) Completes the hash computation and writes the final digest to output. Allocation of output is the caller's responsibility. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example, if you want a SHA256 digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_hash_finalize(struct aws_hash *hash, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_hash_finalize(hash, output, truncate_to) ccall((:aws_hash_finalize, libaws_c_cal), Cint, (Ptr{aws_hash}, Ptr{aws_byte_buf}, Csize_t), hash, output, truncate_to) end """ aws_md5_compute(allocator, input, output, truncate_to) Computes the md5 hash over input and writes the digest output to 'output'. Use this if you don't need to stream the data you're hashing and you can load the entire input to hash into memory. ### Prototype ```c int aws_md5_compute( struct aws_allocator *allocator, const struct aws_byte_cursor *input, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_md5_compute(allocator, input, output, truncate_to) ccall((:aws_md5_compute, libaws_c_cal), Cint, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}, Csize_t), allocator, input, output, truncate_to) end """ aws_sha256_compute(allocator, input, output, truncate_to) Computes the sha256 hash over input and writes the digest output to 'output'. Use this if you don't need to stream the data you're hashing and you can load the entire input to hash into memory. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example, if you want a SHA256 digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_sha256_compute( struct aws_allocator *allocator, const struct aws_byte_cursor *input, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_sha256_compute(allocator, input, output, truncate_to) ccall((:aws_sha256_compute, libaws_c_cal), Cint, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}, Csize_t), allocator, input, output, truncate_to) end """ aws_sha1_compute(allocator, input, output, truncate_to) Computes the sha1 hash over input and writes the digest output to 'output'. Use this if you don't need to stream the data you're hashing and you can load the entire input to hash into memory. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example, if you want a SHA1 digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_sha1_compute( struct aws_allocator *allocator, const struct aws_byte_cursor *input, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_sha1_compute(allocator, input, output, truncate_to) ccall((:aws_sha1_compute, libaws_c_cal), Cint, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}, Csize_t), allocator, input, output, truncate_to) end """ aws_set_md5_new_fn(fn) Set the implementation of md5 to use. If you compiled without BYO\\_CRYPTO, you do not need to call this. However, if use this, we will honor it, regardless of compile options. This may be useful for testing purposes. If you did set BYO\\_CRYPTO, and you do not call this function you will segfault. ### Prototype ```c void aws_set_md5_new_fn(aws_hash_new_fn *fn); ``` """ function aws_set_md5_new_fn(fn) ccall((:aws_set_md5_new_fn, libaws_c_cal), Cvoid, (Ptr{aws_hash_new_fn},), fn) end """ aws_set_sha256_new_fn(fn) Set the implementation of sha256 to use. If you compiled without BYO\\_CRYPTO, you do not need to call this. However, if use this, we will honor it, regardless of compile options. This may be useful for testing purposes. If you did set BYO\\_CRYPTO, and you do not call this function you will segfault. ### Prototype ```c void aws_set_sha256_new_fn(aws_hash_new_fn *fn); ``` """ function aws_set_sha256_new_fn(fn) ccall((:aws_set_sha256_new_fn, libaws_c_cal), Cvoid, (Ptr{aws_hash_new_fn},), fn) end """ aws_set_sha1_new_fn(fn) Set the implementation of sha1 to use. If you compiled without BYO\\_CRYPTO, you do not need to call this. However, if use this, we will honor it, regardless of compile options. This may be useful for testing purposes. If you did set BYO\\_CRYPTO, and you do not call this function you will segfault. ### Prototype ```c void aws_set_sha1_new_fn(aws_hash_new_fn *fn); ``` """ function aws_set_sha1_new_fn(fn) ccall((:aws_set_sha1_new_fn, libaws_c_cal), Cvoid, (Ptr{aws_hash_new_fn},), fn) end """ aws_hmac_vtable Documentation not found. """ struct aws_hmac_vtable alg_name::Ptr{Cchar} provider::Ptr{Cchar} destroy::Ptr{Cvoid} update::Ptr{Cvoid} finalize::Ptr{Cvoid} end """ aws_hmac Documentation not found. """ struct aws_hmac allocator::Ptr{aws_allocator} vtable::Ptr{aws_hmac_vtable} digest_size::Csize_t good::Bool impl::Ptr{Cvoid} end # typedef struct aws_hmac * ( aws_hmac_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * secret ) """ Documentation not found. """ const aws_hmac_new_fn = Cvoid """ aws_sha256_hmac_new(allocator, secret) Allocates and initializes a sha256 hmac instance. Secret is the key to be used for the hmac process. ### Prototype ```c struct aws_hmac *aws_sha256_hmac_new(struct aws_allocator *allocator, const struct aws_byte_cursor *secret); ``` """ function aws_sha256_hmac_new(allocator, secret) ccall((:aws_sha256_hmac_new, libaws_c_cal), Ptr{aws_hmac}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}), allocator, secret) end """ aws_hmac_destroy(hmac) Cleans up and deallocates hmac. ### Prototype ```c void aws_hmac_destroy(struct aws_hmac *hmac); ``` """ function aws_hmac_destroy(hmac) ccall((:aws_hmac_destroy, libaws_c_cal), Cvoid, (Ptr{aws_hmac},), hmac) end """ aws_hmac_update(hmac, to_hmac) Updates the running hmac with to\\_hash. this can be called multiple times. ### Prototype ```c int aws_hmac_update(struct aws_hmac *hmac, const struct aws_byte_cursor *to_hmac); ``` """ function aws_hmac_update(hmac, to_hmac) ccall((:aws_hmac_update, libaws_c_cal), Cint, (Ptr{aws_hmac}, Ptr{aws_byte_cursor}), hmac, to_hmac) end """ aws_hmac_finalize(hmac, output, truncate_to) Completes the hmac computation and writes the final digest to output. Allocation of output is the caller's responsibility. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example if you want a SHA256 digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_hmac_finalize(struct aws_hmac *hmac, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_hmac_finalize(hmac, output, truncate_to) ccall((:aws_hmac_finalize, libaws_c_cal), Cint, (Ptr{aws_hmac}, Ptr{aws_byte_buf}, Csize_t), hmac, output, truncate_to) end """ aws_sha256_hmac_compute(allocator, secret, to_hmac, output, truncate_to) Computes the sha256 hmac over input and writes the digest output to 'output'. Use this if you don't need to stream the data you're hashing and you can load the entire input to hash into memory. If you specify truncate\\_to to something other than 0, the output will be truncated to that number of bytes. For example if you want a SHA256 HMAC digest as the first 16 bytes, set truncate\\_to to 16. If you want the full digest size, just set this to 0. ### Prototype ```c int aws_sha256_hmac_compute( struct aws_allocator *allocator, const struct aws_byte_cursor *secret, const struct aws_byte_cursor *to_hmac, struct aws_byte_buf *output, size_t truncate_to); ``` """ function aws_sha256_hmac_compute(allocator, secret, to_hmac, output, truncate_to) ccall((:aws_sha256_hmac_compute, libaws_c_cal), Cint, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}, Ptr{aws_byte_buf}, Csize_t), allocator, secret, to_hmac, output, truncate_to) end """ aws_set_sha256_hmac_new_fn(fn) Set the implementation of sha256 hmac to use. If you compiled without BYO\\_CRYPTO, you do not need to call this. However, if use this, we will honor it, regardless of compile options. This may be useful for testing purposes. If you did set BYO\\_CRYPTO, and you do not call this function you will segfault. ### Prototype ```c void aws_set_sha256_hmac_new_fn(aws_hmac_new_fn *fn); ``` """ function aws_set_sha256_hmac_new_fn(fn) ccall((:aws_set_sha256_hmac_new_fn, libaws_c_cal), Cvoid, (Ptr{aws_hmac_new_fn},), fn) end """ Documentation not found. """ mutable struct aws_rsa_key_pair end """ aws_rsa_encryption_algorithm Documentation not found. """ @cenum aws_rsa_encryption_algorithm::UInt32 begin AWS_CAL_RSA_ENCRYPTION_PKCS1_5 = 0 AWS_CAL_RSA_ENCRYPTION_OAEP_SHA256 = 1 AWS_CAL_RSA_ENCRYPTION_OAEP_SHA512 = 2 end """ aws_rsa_signature_algorithm Documentation not found. """ @cenum aws_rsa_signature_algorithm::UInt32 begin AWS_CAL_RSA_SIGNATURE_PKCS1_5_SHA256 = 0 AWS_CAL_RSA_SIGNATURE_PSS_SHA256 = 1 end """ __JL_Ctag_164 Documentation not found. """ @cenum __JL_Ctag_164::UInt32 begin AWS_CAL_RSA_MIN_SUPPORTED_KEY_SIZE_IN_BITS = 1024 AWS_CAL_RSA_MAX_SUPPORTED_KEY_SIZE_IN_BITS = 4096 end """ aws_rsa_key_pair_new_from_public_key_pkcs1(allocator, key) Creates an RSA public key from RSAPublicKey as defined in rfc 8017 (aka PKCS1). Returns a new instance of [`aws_rsa_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. ### Prototype ```c struct aws_rsa_key_pair *aws_rsa_key_pair_new_from_public_key_pkcs1( struct aws_allocator *allocator, struct aws_byte_cursor key); ``` """ function aws_rsa_key_pair_new_from_public_key_pkcs1(allocator, key) ccall((:aws_rsa_key_pair_new_from_public_key_pkcs1, libaws_c_cal), Ptr{aws_rsa_key_pair}, (Ptr{aws_allocator}, aws_byte_cursor), allocator, key) end """ aws_rsa_key_pair_new_from_private_key_pkcs1(allocator, key) Creates an RSA private key from RSAPrivateKey as defined in rfc 8017 (aka PKCS1). Returns a new instance of [`aws_rsa_key_pair`](@ref) if the key was successfully built. Otherwise returns NULL. ### Prototype ```c struct aws_rsa_key_pair *aws_rsa_key_pair_new_from_private_key_pkcs1( struct aws_allocator *allocator, struct aws_byte_cursor key); ``` """ function aws_rsa_key_pair_new_from_private_key_pkcs1(allocator, key) ccall((:aws_rsa_key_pair_new_from_private_key_pkcs1, libaws_c_cal), Ptr{aws_rsa_key_pair}, (Ptr{aws_allocator}, aws_byte_cursor), allocator, key) end """ aws_rsa_key_pair_acquire(key_pair) Adds one to an RSA key pair's ref count. Returns key\\_pair pointer. ### Prototype ```c struct aws_rsa_key_pair *aws_rsa_key_pair_acquire(struct aws_rsa_key_pair *key_pair); ``` """ function aws_rsa_key_pair_acquire(key_pair) ccall((:aws_rsa_key_pair_acquire, libaws_c_cal), Ptr{aws_rsa_key_pair}, (Ptr{aws_rsa_key_pair},), key_pair) end """ aws_rsa_key_pair_release(key_pair) Subtracts one from an RSA key pair's ref count. If ref count reaches zero, the key pair is destroyed. Always returns NULL. ### Prototype ```c struct aws_rsa_key_pair *aws_rsa_key_pair_release(struct aws_rsa_key_pair *key_pair); ``` """ function aws_rsa_key_pair_release(key_pair) ccall((:aws_rsa_key_pair_release, libaws_c_cal), Ptr{aws_rsa_key_pair}, (Ptr{aws_rsa_key_pair},), key_pair) end """ aws_rsa_key_pair_max_encrypt_plaintext_size(key_pair, algorithm) Max plaintext size that can be encrypted by the key (i.e. max data size supported by the key - bytes needed for padding). ### Prototype ```c size_t aws_rsa_key_pair_max_encrypt_plaintext_size( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_encryption_algorithm algorithm); ``` """ function aws_rsa_key_pair_max_encrypt_plaintext_size(key_pair, algorithm) ccall((:aws_rsa_key_pair_max_encrypt_plaintext_size, libaws_c_cal), Csize_t, (Ptr{aws_rsa_key_pair}, aws_rsa_encryption_algorithm), key_pair, algorithm) end """ aws_rsa_key_pair_encrypt(key_pair, algorithm, plaintext, out) Documentation not found. ### Prototype ```c int aws_rsa_key_pair_encrypt( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_encryption_algorithm algorithm, struct aws_byte_cursor plaintext, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_encrypt(key_pair, algorithm, plaintext, out) ccall((:aws_rsa_key_pair_encrypt, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_encryption_algorithm, aws_byte_cursor, Ptr{aws_byte_buf}), key_pair, algorithm, plaintext, out) end """ aws_rsa_key_pair_decrypt(key_pair, algorithm, ciphertext, out) Documentation not found. ### Prototype ```c int aws_rsa_key_pair_decrypt( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_encryption_algorithm algorithm, struct aws_byte_cursor ciphertext, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_decrypt(key_pair, algorithm, ciphertext, out) ccall((:aws_rsa_key_pair_decrypt, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_encryption_algorithm, aws_byte_cursor, Ptr{aws_byte_buf}), key_pair, algorithm, ciphertext, out) end """ aws_rsa_key_pair_block_length(key_pair) Documentation not found. ### Prototype ```c size_t aws_rsa_key_pair_block_length(const struct aws_rsa_key_pair *key_pair); ``` """ function aws_rsa_key_pair_block_length(key_pair) ccall((:aws_rsa_key_pair_block_length, libaws_c_cal), Csize_t, (Ptr{aws_rsa_key_pair},), key_pair) end """ aws_rsa_key_pair_sign_message(key_pair, algorithm, digest, out) Uses the key\\_pair's private key to sign message. The output will be in out. out must be large enough to hold the signature. Check [`aws_rsa_key_pair_signature_length`](@ref)() for the appropriate size. It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually something like a SHA256. ### Prototype ```c int aws_rsa_key_pair_sign_message( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_signature_algorithm algorithm, struct aws_byte_cursor digest, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_sign_message(key_pair, algorithm, digest, out) ccall((:aws_rsa_key_pair_sign_message, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_signature_algorithm, aws_byte_cursor, Ptr{aws_byte_buf}), key_pair, algorithm, digest, out) end """ aws_rsa_key_pair_verify_signature(key_pair, algorithm, digest, signature) Uses the key\\_pair's public key to verify signature of message. It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually something like a SHA256. returns AWS\\_OP\\_SUCCESS if the signature is valid. raises AWS\\_ERROR\\_CAL\\_SIGNATURE\\_VALIDATION\\_FAILED if signature validation failed ### Prototype ```c int aws_rsa_key_pair_verify_signature( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_signature_algorithm algorithm, struct aws_byte_cursor digest, struct aws_byte_cursor signature); ``` """ function aws_rsa_key_pair_verify_signature(key_pair, algorithm, digest, signature) ccall((:aws_rsa_key_pair_verify_signature, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_signature_algorithm, aws_byte_cursor, aws_byte_cursor), key_pair, algorithm, digest, signature) end """ aws_rsa_key_pair_signature_length(key_pair) Documentation not found. ### Prototype ```c size_t aws_rsa_key_pair_signature_length(const struct aws_rsa_key_pair *key_pair); ``` """ function aws_rsa_key_pair_signature_length(key_pair) ccall((:aws_rsa_key_pair_signature_length, libaws_c_cal), Csize_t, (Ptr{aws_rsa_key_pair},), key_pair) end """ aws_rsa_key_export_format Documentation not found. """ @cenum aws_rsa_key_export_format::UInt32 begin AWS_CAL_RSA_KEY_EXPORT_PKCS1 = 0 end """ aws_rsa_key_pair_get_public_key(key_pair, format, out) Documentation not found. ### Prototype ```c int aws_rsa_key_pair_get_public_key( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_key_export_format format, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_get_public_key(key_pair, format, out) ccall((:aws_rsa_key_pair_get_public_key, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_key_export_format, Ptr{aws_byte_buf}), key_pair, format, out) end """ aws_rsa_key_pair_get_private_key(key_pair, format, out) Documentation not found. ### Prototype ```c int aws_rsa_key_pair_get_private_key( const struct aws_rsa_key_pair *key_pair, enum aws_rsa_key_export_format format, struct aws_byte_buf *out); ``` """ function aws_rsa_key_pair_get_private_key(key_pair, format, out) ccall((:aws_rsa_key_pair_get_private_key, libaws_c_cal), Cint, (Ptr{aws_rsa_key_pair}, aws_rsa_key_export_format, Ptr{aws_byte_buf}), key_pair, format, out) end """ Documentation not found. """ mutable struct aws_symmetric_cipher end # typedef struct aws_symmetric_cipher * ( aws_aes_cbc_256_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * key , const struct aws_byte_cursor * iv ) """ Documentation not found. """ const aws_aes_cbc_256_new_fn = Cvoid # typedef struct aws_symmetric_cipher * ( aws_aes_ctr_256_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * key , const struct aws_byte_cursor * iv ) """ Documentation not found. """ const aws_aes_ctr_256_new_fn = Cvoid # typedef struct aws_symmetric_cipher * ( aws_aes_gcm_256_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * key , const struct aws_byte_cursor * iv , const struct aws_byte_cursor * aad ) """ Documentation not found. """ const aws_aes_gcm_256_new_fn = Cvoid # typedef struct aws_symmetric_cipher * ( aws_aes_keywrap_256_new_fn ) ( struct aws_allocator * allocator , const struct aws_byte_cursor * key ) """ Documentation not found. """ const aws_aes_keywrap_256_new_fn = Cvoid """ aws_symmetric_cipher_state Documentation not found. """ @cenum aws_symmetric_cipher_state::UInt32 begin AWS_SYMMETRIC_CIPHER_READY = 0 AWS_SYMMETRIC_CIPHER_FINALIZED = 1 AWS_SYMMETRIC_CIPHER_ERROR = 2 end """ aws_aes_cbc_256_new(allocator, key, iv) Creates an instance of AES CBC with 256-bit key. If key and iv are NULL, they will be generated internally. You can get the generated key and iv back by calling: [`aws_symmetric_cipher_get_key`](@ref)() and [`aws_symmetric_cipher_get_initialization_vector`](@ref)() respectively. If they are set, that key and iv will be copied internally and used by the cipher. Returns NULL on failure. You can check aws\\_last\\_error() to get the error code indicating the failure cause. ### Prototype ```c struct aws_symmetric_cipher *aws_aes_cbc_256_new( struct aws_allocator *allocator, const struct aws_byte_cursor *key, const struct aws_byte_cursor *iv); ``` """ function aws_aes_cbc_256_new(allocator, key, iv) ccall((:aws_aes_cbc_256_new, libaws_c_cal), Ptr{aws_symmetric_cipher}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), allocator, key, iv) end """ aws_aes_ctr_256_new(allocator, key, iv) Creates an instance of AES CTR with 256-bit key. If key and iv are NULL, they will be generated internally. You can get the generated key and iv back by calling: [`aws_symmetric_cipher_get_key`](@ref)() and [`aws_symmetric_cipher_get_initialization_vector`](@ref)() respectively. If they are set, that key and iv will be copied internally and used by the cipher. Returns NULL on failure. You can check aws\\_last\\_error() to get the error code indicating the failure cause. ### Prototype ```c struct aws_symmetric_cipher *aws_aes_ctr_256_new( struct aws_allocator *allocator, const struct aws_byte_cursor *key, const struct aws_byte_cursor *iv); ``` """ function aws_aes_ctr_256_new(allocator, key, iv) ccall((:aws_aes_ctr_256_new, libaws_c_cal), Ptr{aws_symmetric_cipher}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), allocator, key, iv) end """ aws_aes_gcm_256_new(allocator, key, iv, aad) Creates an instance of AES GCM with 256-bit key. If key, iv are NULL, they will be generated internally. You can get the generated key and iv back by calling: [`aws_symmetric_cipher_get_key`](@ref)() and [`aws_symmetric_cipher_get_initialization_vector`](@ref)() respectively. If aad is set it will be copied and applied to the cipher. If they are set, that key and iv will be copied internally and used by the cipher. For decryption purposes tag can be provided via [`aws_symmetric_cipher_set_tag`](@ref) method. Note: for decrypt operations, tag must be provided before first decrypt is called. (this is a windows bcrypt limitations, but for consistency sake same limitation is extended to other platforms) Tag generated during encryption can be retrieved using [`aws_symmetric_cipher_get_tag`](@ref) method after finalize is called. Returns NULL on failure. You can check aws\\_last\\_error() to get the error code indicating the failure cause. ### Prototype ```c struct aws_symmetric_cipher *aws_aes_gcm_256_new( struct aws_allocator *allocator, const struct aws_byte_cursor *key, const struct aws_byte_cursor *iv, const struct aws_byte_cursor *aad); ``` """ function aws_aes_gcm_256_new(allocator, key, iv, aad) ccall((:aws_aes_gcm_256_new, libaws_c_cal), Ptr{aws_symmetric_cipher}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}, Ptr{aws_byte_cursor}), allocator, key, iv, aad) end """ aws_aes_keywrap_256_new(allocator, key) Creates an instance of AES Keywrap with 256-bit key. If key is NULL, it will be generated internally. You can get the generated key back by calling: [`aws_symmetric_cipher_get_key`](@ref)() If key is set, that key will be copied internally and used by the cipher. Returns NULL on failure. You can check aws\\_last\\_error() to get the error code indicating the failure cause. ### Prototype ```c struct aws_symmetric_cipher *aws_aes_keywrap_256_new( struct aws_allocator *allocator, const struct aws_byte_cursor *key); ``` """ function aws_aes_keywrap_256_new(allocator, key) ccall((:aws_aes_keywrap_256_new, libaws_c_cal), Ptr{aws_symmetric_cipher}, (Ptr{aws_allocator}, Ptr{aws_byte_cursor}), allocator, key) end """ aws_symmetric_cipher_destroy(cipher) Cleans up internal resources and state for cipher and then deallocates it. ### Prototype ```c void aws_symmetric_cipher_destroy(struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_destroy(cipher) ccall((:aws_symmetric_cipher_destroy, libaws_c_cal), Cvoid, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_encrypt(cipher, to_encrypt, out) Encrypts the value in to\\_encrypt and writes the encrypted data into out. If out is dynamic it will be expanded. If it is not, and out is not large enough to handle the encrypted output, the call will fail. If you're trying to optimize to use a stack based array or something, make sure it's at least as large as the size of to\\_encrypt + an extra BLOCK to account for padding etc... returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_encrypt( struct aws_symmetric_cipher *cipher, struct aws_byte_cursor to_encrypt, struct aws_byte_buf *out); ``` """ function aws_symmetric_cipher_encrypt(cipher, to_encrypt, out) ccall((:aws_symmetric_cipher_encrypt, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher}, aws_byte_cursor, Ptr{aws_byte_buf}), cipher, to_encrypt, out) end """ aws_symmetric_cipher_decrypt(cipher, to_decrypt, out) Decrypts the value in to\\_decrypt and writes the decrypted data into out. If out is dynamic it will be expanded. If it is not, and out is not large enough to handle the decrypted output, the call will fail. If you're trying to optimize to use a stack based array or something, make sure it's at least as large as the size of to\\_decrypt + an extra BLOCK to account for padding etc... returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_decrypt( struct aws_symmetric_cipher *cipher, struct aws_byte_cursor to_decrypt, struct aws_byte_buf *out); ``` """ function aws_symmetric_cipher_decrypt(cipher, to_decrypt, out) ccall((:aws_symmetric_cipher_decrypt, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher}, aws_byte_cursor, Ptr{aws_byte_buf}), cipher, to_decrypt, out) end """ aws_symmetric_cipher_finalize_encryption(cipher, out) Encrypts any remaining data that was reserved for final padding, loads GMACs etc... and if there is any writes any remaining encrypted data to out. If out is dynamic it will be expanded. If it is not, and out is not large enough to handle the decrypted output, the call will fail. If you're trying to optimize to use a stack based array or something, make sure it's at least as large as the size of 2 BLOCKs to account for padding etc... After invoking this function, you MUST call [`aws_symmetric_cipher_reset`](@ref)() before invoking any encrypt/decrypt operations on this cipher again. returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_finalize_encryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out); ``` """ function aws_symmetric_cipher_finalize_encryption(cipher, out) ccall((:aws_symmetric_cipher_finalize_encryption, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher}, Ptr{aws_byte_buf}), cipher, out) end """ aws_symmetric_cipher_finalize_decryption(cipher, out) Decrypts any remaining data that was reserved for final padding, loads GMACs etc... and if there is any writes any remaining decrypted data to out. If out is dynamic it will be expanded. If it is not, and out is not large enough to handle the decrypted output, the call will fail. If you're trying to optimize to use a stack based array or something, make sure it's at least as large as the size of 2 BLOCKs to account for padding etc... After invoking this function, you MUST call [`aws_symmetric_cipher_reset`](@ref)() before invoking any encrypt/decrypt operations on this cipher again. returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_finalize_decryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out); ``` """ function aws_symmetric_cipher_finalize_decryption(cipher, out) ccall((:aws_symmetric_cipher_finalize_decryption, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher}, Ptr{aws_byte_buf}), cipher, out) end """ aws_symmetric_cipher_reset(cipher) Resets the cipher state for starting a new encrypt or decrypt operation. Note encrypt/decrypt cannot be mixed on the same cipher without a call to reset in between them. However, this leaves the key, iv etc... materials setup for immediate reuse. Note: GCM tag is not preserved between operations. If you intend to do encrypt followed directly by decrypt, make sure to make a copy of tag before reseting the cipher and pass that copy for decryption. Warning: In most cases it's a really bad idea to reset a cipher and perform another operation using that cipher. Key and IV should not be reused for different operations. Instead of reseting the cipher, destroy the cipher and create new one with a new key/iv pair. Use reset at your own risk, and only after careful consideration. returns AWS\\_OP\\_SUCCESS on success. Call aws\\_last\\_error() to determine the failure cause if it returns AWS\\_OP\\_ERR; ### Prototype ```c int aws_symmetric_cipher_reset(struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_reset(cipher) ccall((:aws_symmetric_cipher_reset, libaws_c_cal), Cint, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_get_tag(cipher) Gets the current GMAC tag. If not AES GCM, this function will just return an empty cursor. The memory in this cursor is unsafe as it refers to the internal buffer. This was done because the use case doesn't require fetching these during an encryption or decryption operation and it dramatically simplifies the API. Only use this function between other calls to this API as any function call can alter the value of this tag. If you need to access it in a different pattern, copy the values to your own buffer first. ### Prototype ```c struct aws_byte_cursor aws_symmetric_cipher_get_tag(const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_get_tag(cipher) ccall((:aws_symmetric_cipher_get_tag, libaws_c_cal), aws_byte_cursor, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_set_tag(cipher, tag) Sets the GMAC tag on the cipher. Does nothing for ciphers that do not support tag. ### Prototype ```c void aws_symmetric_cipher_set_tag(struct aws_symmetric_cipher *cipher, struct aws_byte_cursor tag); ``` """ function aws_symmetric_cipher_set_tag(cipher, tag) ccall((:aws_symmetric_cipher_set_tag, libaws_c_cal), Cvoid, (Ptr{aws_symmetric_cipher}, aws_byte_cursor), cipher, tag) end """ aws_symmetric_cipher_get_initialization_vector(cipher) Gets the original initialization vector as a cursor. The memory in this cursor is unsafe as it refers to the internal buffer. This was done because the use case doesn't require fetching these during an encryption or decryption operation and it dramatically simplifies the API. Unlike some other fields, this value does not change after the inital construction of the cipher. For some algorithms, such as AES Keywrap, this will return an empty cursor. ### Prototype ```c struct aws_byte_cursor aws_symmetric_cipher_get_initialization_vector( const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_get_initialization_vector(cipher) ccall((:aws_symmetric_cipher_get_initialization_vector, libaws_c_cal), aws_byte_cursor, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_get_key(cipher) Gets the original key. The memory in this cursor is unsafe as it refers to the internal buffer. This was done because the use case doesn't require fetching these during an encryption or decryption operation and it dramatically simplifies the API. Unlike some other fields, this value does not change after the inital construction of the cipher. ### Prototype ```c struct aws_byte_cursor aws_symmetric_cipher_get_key(const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_get_key(cipher) ccall((:aws_symmetric_cipher_get_key, libaws_c_cal), aws_byte_cursor, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_is_good(cipher) Returns true if the state of the cipher is good, and otherwise returns false. Most operations, other than [`aws_symmetric_cipher_reset`](@ref)() will fail if this function is returning false. [`aws_symmetric_cipher_reset`](@ref)() will reset the state to a good state if possible. ### Prototype ```c bool aws_symmetric_cipher_is_good(const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_is_good(cipher) ccall((:aws_symmetric_cipher_is_good, libaws_c_cal), Bool, (Ptr{aws_symmetric_cipher},), cipher) end """ aws_symmetric_cipher_get_state(cipher) Retuns the current state of the cipher. Ther state of the cipher can be ready for use, finalized, or has encountered an error. if the cipher is in a finished or error state, it must be reset before further use. ### Prototype ```c enum aws_symmetric_cipher_state aws_symmetric_cipher_get_state(const struct aws_symmetric_cipher *cipher); ``` """ function aws_symmetric_cipher_get_state(cipher) ccall((:aws_symmetric_cipher_get_state, libaws_c_cal), aws_symmetric_cipher_state, (Ptr{aws_symmetric_cipher},), cipher) end """ Documentation not found. """ const AWS_C_CAL_PACKAGE_ID = 7 """ Documentation not found. """ const AWS_SHA256_LEN = 32 """ Documentation not found. """ const AWS_SHA1_LEN = 20 """ Documentation not found. """ const AWS_MD5_LEN = 16 """ Documentation not found. """ const AWS_SHA256_HMAC_LEN = 32 """ Documentation not found. """ const AWS_AES_256_CIPHER_BLOCK_SIZE = 16 """ Documentation not found. """ const AWS_AES_256_KEY_BIT_LEN = 256 """ Documentation not found. """ const AWS_AES_256_KEY_BYTE_LEN = AWS_AES_256_KEY_BIT_LEN ÷ 8
LibAwsCal
https://github.com/JuliaServices/LibAwsCal.jl.git