text:
"""
    AbstractVTKDataset

Abstract type representing any structured or unstructured VTK dataset.

The dataset classification is described in the
[VTK file format
specification](https://vtk.org/wp-content/uploads/2015/04/file-formats.pdf),
page 12.
"""
abstract type AbstractVTKDataset end

"""
    StructuredVTKDataset <: AbstractVTKDataset

Abstract type representing a structured VTK dataset.

Subtypes are [`VTKImageData`](@ref), [`VTKRectilinearGrid`](@ref) and
[`VTKStructuredGrid`](@ref).
"""
abstract type StructuredVTKDataset <: AbstractVTKDataset end

"""
    VTKImageData <: StructuredVTKDataset

Represents the VTK image data format (`.vti` extension).

This corresponds to rectangular grids with uniform spacing in all directions.
"""
struct VTKImageData <: StructuredVTKDataset end

"""
    VTKRectilinearGrid <: StructuredVTKDataset

Represents the VTK rectilinear grid format (`.vtr` extension).

This corresponds to rectangular grids with non-uniform spacing.
"""
struct VTKRectilinearGrid <: StructuredVTKDataset end

"""
    VTKStructuredGrid <: StructuredVTKDataset

Represents the VTK structured grid format (`.vts` extension).

This corresponds to curvilinear grids, the most general kind of structured grid.
"""
struct VTKStructuredGrid <: StructuredVTKDataset end

"""
    UnstructuredVTKDataset <: AbstractVTKDataset

Abstract type representing an unstructured VTK dataset.

Subtypes are [`VTKPolyData`](@ref) and [`VTKUnstructuredGrid`](@ref).
"""
abstract type UnstructuredVTKDataset <: AbstractVTKDataset end

"""
    VTKPolyData <: UnstructuredVTKDataset

Represents the VTK polydata format (`.vtp` extension).

These are unstructured datasets that accept a limited set of cells types,
defined in the [`PolyData`](@ref) module.
"""
struct VTKPolyData <: UnstructuredVTKDataset end

"""
    VTKUnstructuredGrid <: UnstructuredVTKDataset

Represents the VTK unstructured format (`.vtu` extension).

This is the most general kind of unstructured grid, which accepts all cell types
defined in the [`VTKCellTypes`](@ref) module.
"""
struct VTKUnstructuredGrid <: UnstructuredVTKDataset end

file_extension(::VTKImageData) = ".vti"
file_extension(::VTKRectilinearGrid) = ".vtr"
file_extension(::VTKStructuredGrid) = ".vts"
file_extension(::VTKPolyData) = ".vtp"
file_extension(::VTKUnstructuredGrid) = ".vtu"

xml_name(::VTKImageData) = "ImageData"
xml_name(::VTKRectilinearGrid) = "RectilinearGrid"
xml_name(::VTKStructuredGrid) = "StructuredGrid"
xml_name(::VTKPolyData) = "PolyData"
xml_name(::VTKUnstructuredGrid) = "UnstructuredGrid"


text:
"""
nk_pde(n)

Solve the Elliptic PDE using nsoli.jl on an n x n grid.
"""
function nk_pde(n=15)
    # Get some room for the residual
    rtol = 1.e-7
    atol = 1.e-10
    u0 = zeros(n * n)
    FV = copy(u0)
    FVS = copy(u0)
    # Get the precomputed data from pdeinit
    pdata = pdeinit(n)
    # Storage for the Jacobian-vector products
    JV = zeros(n * n, 100)
    # Call the solver with a finite-difference Jac-Vec
    hout = nsoli(
        pdeF!,
        u0,
        FV,
        JV;
        rtol = rtol,
        atol = atol,
        pdata = pdata,
        eta = .1,
        fixedeta = false,
        maxit = 20,
    )
houtb = nsoli(
        pdeF!,
        u0,
        FV,
        FVS;
        rtol = rtol,
        atol = atol,
        pdata = pdata,
        eta = .1,
        fixedeta = false,
        maxit = 20,
        lmaxit = 20,
        lsolver="bicgstab"
    )

    # Call the solver a few times with an analytic Jac-Vec
    hout2 = NsoliPDE(n; fixedeta=false)
    hout3 = NsoliPDE(n; fixedeta=true)
    hout4 = NsoliPDE(n; fixedeta=false, lsolver="bicgstab")
    soldiff = (
        norm(hout3.solution - hout.solution, Inf) +
        norm(hout3.solution - hout.solution, Inf) +
        norm(houtb.solution - hout.solution, Inf) +
        norm(hout4.solution - hout.solution, Inf)
    )
    solpass = (soldiff < 1.e-6)
    solpass || println("solution compare fails in nk_pde, ",soldiff)
    histdiffv = (hout.history - hout2.history) ./ hout.history[1]
    histdiff = norm(histdiffv, Inf)
    histpass = (histdiff < .1)
    histpass || println("history compare fails in nk_pde, ",histdiff)
    cost1 = sum(hout.stats.ijac)
    cost2 = sum(hout2.stats.ijac)
    cost3 = sum(hout3.stats.ijac)
    costpass = (cost1 > 80) && (cost2 > 30) && (cost3 > cost2)
    costpass || println(cost1," ", cost2, "  ", cost3)
    return costpass
end

ext: jl


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/FEMBase.jl/blob/master/LICENSE

using FEMBase
using Test

## Elements - field sets

# Each element have two kind of fields, dynamically defined and statically
# defined.

### Dynamically defined fields (dfields)

using FEMBase: has_dfield, get_dfield, create_dfield!, update_dfield!,
               interpolate_dfield

# Like name suggests, dynamically defined fields can be defined on fly.
# For example, to define a fields called *geometry* and *displacement*:

element = Element(Quad4, (1, 2, 3, 4))

@test has_dfield(element, :geometry) == false

X = ([0.0,0.0], [1.0,0.0], [1.0,1.0], [0.0,1.0])
u0 = ([0.0,0.0], [0.0,0.0], [0.0,0.0], [0.0,0.0])
u1 = ([0.0,0.0], [0.0,0.0], [1.0,0.0], [0.0,0.0])

create_dfield!(element, :geometry, X)
@test has_dfield(element, :geometry) == true

create_dfield!(element, :displacement, 0.0 => u0)
update_dfield!(element, :displacement, 1.0 => u1)

# The main property of the dynamic fields are that they can be defined
# abolutely in what state of simulation ever, without any predefined
# initialization steps. `update_dfield!` is creating field on fly, if
# it doesn't exists before hand.

update_dfield!(element, :youngs_modulus, 288.0)
@test has_dfield(element, :youngs_modulus)

# If field depends from time (DVTV, DCTV, DVTVd, ...), interpolation
# works as expected:

um = interpolate_dfield(element, :displacement, 0.5)
@test um[3] == [0.5, 0.0]

### Statically defined fields (sfields)

# The problem of the dynamically defined fields are that they have a poor
# performance. Julia is JIT compiled language and from performance perspective,
# knowing concrete types in compile time leads to fast implementation. For that
# reason, we also have another fieldset, which must be given when a new element
# is created, allowing high performance.

using FEMBase: has_sfield, get_sfield, update_sfield!, interpolate_sfield, AbstractFieldSet

struct MyFieldSet{N} <: AbstractFieldSet{N}
    geometry :: DVTI{N, Vector{Float64}}
    displacement :: DVTV{N, Vector{Float64}}
end

function MyFieldSet{N}() where N
    # create tuple of length N with zeros(3): ([0.0,0.0,0.0], ..., )
    data = ntuple(i -> zeros(3), N)
    geometry = DVTI(data)
    displacement = DVTV(0.0 => data)
    return MyFieldSet{N}(geometry, displacement)
end

# When constructing new element, one must pass now the field set:

element = Element(Quad4, MyFieldSet, (1, 2, 3, 4))

@test has_sfield(element, :geometry) == true

X = ([0.0,0.0], [1.0,0.0], [1.0,1.0], [0.0,1.0])
u0 = ([0.0,0.0], [0.0,0.0], [0.0,0.0], [0.0,0.0])
u1 = ([0.0,0.0], [0.0,0.0], [1.0,0.0], [0.0,0.0])

# Indeed using sfield does not mean that they cannot be changed. The only
# difference is that they cannot be created on the fly, thus there is no
# `create_dfield!` at all. But `update_dfield!` works as expected.

@test has_sfield(element, :geometry) == true

update_sfield!(element, :geometry, X)
update_sfield!(element, :displacement, 0.0 => u0)
update_sfield!(element, :displacement, 1.0 => u1)

# Interpolating fields etc. works as expected:

um = interpolate_sfield(element, :displacement, 0.5)
@test um[3] == [0.5, 0.0]

### Common routines to dfields and sfields

using FEMBase: has_field, get_field, update_field!, interpolate_field

# There is common routines `has_field`, `update_field!`, `interpolate_field`
# and so on, which tries to be clever. We prefer statically defined fields
# as they outperform dynamically defined ones in access time, but then e.g.
# if field is not statically defined, `update_field!` is creating a new dfield.

element = Element(Quad4, MyFieldSet, (1, 2, 3, 4))

update_field!(element, :geometry, X)
update_field!(element, :displacement, 0.0 => u0)
update_field!(element, :youngs_modulus, 288.0)
update_field!(element, :poissons_ratio, 1/3)

# For example, geometry and displacement are here sfields because they are
# predefined using fieldset, but youngs modulus is dfield and created on-the-fly:

@test has_field(element, :geometry) == true
@test has_dfield(element, :geometry) == false
@test has_sfield(element, :geometry) == true
@test has_dfield(element, :youngs_modulus) == true
@test has_sfield(element, :youngs_modulus) == false
@test get_field(element, :youngs_modulus) === get_dfield(element, :youngs_modulus)
@test interpolate_field(element, :poissons_ratio, 0.0) == 1/3
@test interpolate_field(element, :geometry, 0.0) == X

### Creating and updating DVTI and DVTV fields using dictionaries

# It's a very convenient way to update fields using dictionaries.

element = Element(Seg2, (1, 2))
update!(element, :temperature, 0.0 => (0.0, 0.0))

# Let say that one wants to update the following temperature data:

T = Dict(1 => 1.0, 2 => 2.0, 3 => 3.0)

# to a element, can be done using that dictionary:

update!(element, :temperature, 1.0 => T)

# Internally, we pick the data from dictionary based on the node numbers and
# update only that data to element.

@test interpolate(element, :temperature, 1.0) == (T[1], T[2])

### Performance difference between fields

# The reason, like explained, for having two kinds of fields comes from the
# performance. We need certain fields, like geometry, displacement, connectivity
# and so on, work with maximum performance, because they are accessed all the
# time. To make a short timing, we create geometry and geometry2, where the
# first one is statically defined and latter one dynamically.

#=
X = ([0.0,0.0], [1.0,0.0], [1.0,1.0], [0.0,1.0])
element = Element(Quad4, MyFieldSet, (1, 2, 3, 4))
update!(element, :geometry, X)
update!(element, :geometry2, X)
using BenchmarkTools
@btime interpolate($element, :geometry, 0.0)
@btime interpolate($element, :geometry2, 0.0)
=#

# The following code will give in first case 1.466 ns and 0 memory allocations,
# where the latter case is 37.755 ns with 1 memory allocation:
#
#  1.466 ns (0 allocations: 0 bytes)
#  37.755 ns (1 allocation: 16 bytes)


text:
using SparseCCSA
using SparseCCSA: inner_iterations
using Test
using LinearAlgebra
using SparseArrays

@testset "constructor" begin
    nvar = 30
    ncon = 40
    function test_constructor(T::DataType)
        function f_and_∇f(x)
            rand(T, ncon + 1, nvar) * x, rand(T, ncon + 1, nvar)
        end
        ρ = ones(T, nvar + 1)
        σ = ones(T, ncon)
        x₀ = zeros(T, nvar)
        lower_bound = -rand(T, nvar)
        upper_bound = rand(T, nvar)
        xtol_rel = T(1e-4)

        opt₁ = CCSAState(nvar, ncon, f_and_∇f, x₀)
        @test typeof(opt₁) == CCSAState{T}
        @test opt₁.n == nvar
        @test opt₁.m == ncon
        @test opt₁.x == x₀
        @test opt₁.lb == fill(typemin(T), nvar)
        @test opt₁.ub == fill(typemax(T), nvar)
        @test opt₁.xtol_rel == T(1e-5)
        opt₂ = CCSAState(nvar, ncon, f_and_∇f, x₀, ρ=ρ, σ=σ, lb=lower_bound)
        @test opt₂.lb == lower_bound
        @test opt₂.ub == fill(typemax(T), nvar)
        @test opt₂.xtol_rel == T(1e-5)
        opt₃ = CCSAState(nvar, ncon, f_and_∇f, x₀, ρ=ρ, σ=σ, lb=lower_bound, ub=upper_bound)
        @test opt₃.lb == lower_bound
        @test opt₃.ub == upper_bound
        @test opt₃.xtol_rel == T(1e-5)
        opt₄ = CCSAState(nvar, ncon, f_and_∇f, x₀, ρ=ρ, σ=σ, xtol_rel=xtol_rel)
        @test opt₄.lb == fill(typemin(T), nvar)
        @test opt₄.ub == fill(typemax(T), nvar)
        @test opt₄.xtol_rel == xtol_rel
    end
    test_constructor(Float16)
    test_constructor(Float32)
    test_constructor(Float64)
end

@testset "sparse Jacobian constuctor" begin
    nvar = 100
    ncon = 200
    function f_and_∇f(x)
        sprand(Float64, ncon + 1, nvar, 0.3) * x, sprand(Float64, ncon + 1, nvar, 0.2)
    end
    ρ = ones(nvar + 1)
    σ = ones(ncon)
    x₀ = zeros(nvar)
    sparse_opt = CCSAState(nvar, ncon, f_and_∇f, x₀, ρ=ρ, σ=σ)
    # Dense Jacobian should not be allocated if sparsity is provided
    @test typeof(sparse_opt.∇fx) <: AbstractSparseMatrix
end

@testset "integration" begin
    function test1(bound)
        function f_and_∇f(x)
            f = [abs2(x[1]), x[1] - bound]
            ∇f = [2x[1]; 1.0]
            return f, ∇f
        end
        n = 1
        m = 1
        σ = [30.0] # n
        ρ = [2.0, 0.0001] * σ[1]^2 # m + 1
        x = [-10.0]
        lb = [-100.0]
        ub = [100.0]
        opt = CCSAState(n, m, f_and_∇f, x, ρ=ρ, σ=σ, lb=lb, ub=ub)
        optimize(opt)
        return opt.x
    end
    @test test1(-1.0) ≈ [-1.0] atol = 1e-5
    @test test1(1.0) ≈ [0.0] atol = 1e-5

    function test2()
        function f_and_grad(x)
            fx = [x[1]^2 * x[2], x[1] - 3, x[1] + 4, x[2] - 4]
            gradx = [2*x[1]*x[2] x[1]^2; 1 0; 1 0; 0 1]
            fx, gradx
        end
        n = 2
        m = 3
        ρ = [1000.0, 1000.0, 1000.0, 1000.0] #m+1
        σ = [100.0, 100.0] #n
        lb = [-100.0, -100.0]
        ub = [100.0, 100.0]
        x = [0.0, 0.0]
        xtol_rel = 1e-6
        st = CCSAState(n, m, f_and_grad, x, ρ=ρ, σ=σ, lb=lb, ub=ub, xtol_rel=xtol_rel)
        optimize(st)
        return st.x
    end
    @test norm(test1(-1) - [-1.0]) < 0.001 # the constraint is tight
    @test norm(test1(1) - [0.0]) < 0.001 # the constraint is tight
    @test norm(test2() - [-100.0, -100.0]) < 1.0 # the box constraint is tight
end

@testset "no constraint" begin
    function fundamental_no_constraints_test(n)
        function f(x)
            return [sum(abs2, x)]
        end
        function ∇f(x) # (m + 1) × n
            return 2 * x'
        end
        function f_and_∇f(x)
            return f(x), ∇f(x)
        end
        m = 0
        ρ0 = [101.0] # m + 1
        σ0 = fill(0.1, n) # n
        x0 = fill(50.0, n) # n
        st = CCSAState(n, m, f_and_∇f, x0, ρ=ρ0, σ=σ0)
        optimize(st)
        return st.x
    end
    @test fundamental_no_constraints_test(6) ≈ fill(0.0, 6) atol = 1e-4
end


text:
using TensorCast

using Test
using LinearAlgebra
using Logging

using StaticArrays
using OffsetArrays
using Einsum
using Strided
using LazyArrays
using LoopVectorization

@testset "ex-@shape" begin include("shape.jl") end
@testset "@reduce" begin include("reduce.jl")  end
@testset "@cast"   begin include("casting.jl") end
@testset "@matmul" begin include("mul.jl")     end

@testset "slice/view"  begin include("cat.jl") end
@testset "old readmes" begin include("old.jl") end
@testset "new in 0.2"  begin include("two.jl") end
@testset "new in 0.4" begin include("four.jl") end


text:
module MaxHelpingHandActivateTimedTouchSwitchesTimerTrigger

using ..Ahorn, Maple

@mapdef Trigger "MaxHelpingHand/ActivateTimedTouchSwitchesTimerTrigger" ActivateTimedTouchSwitchesTimerTrigger(x::Integer, y::Integer, width::Integer=Maple.defaultTriggerWidth, height::Integer=Maple.defaultTriggerHeight)

const placements = Ahorn.PlacementDict(
    "Activate Timed Touch Switches Timer\n(max480's Helping Hand + Outback Helper)" => Ahorn.EntityPlacement(
        ActivateTimedTouchSwitchesTimerTrigger,
        "rectangle"
    )
)

end

max_stars_repo_name: Kitty-Cats/MaxHelpingHand

max_issues_repo_name: Kitty-Cats/MaxHelpingHand

max_forks_repo_name: Kitty-Cats/MaxHelpingHand