licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
546
@enum CLBlastLayout CLBlastLayoutRowMajor=101 CLBlastLayoutColMajor=102 @enum CLBlastTranspose CLBlastTransposeNo=111 CLBlastTransposeYes=112 CLBlastTransposeConjugate=113 @enum CLBlastTriangle CLBlastTriangleUpper=121 CLBlastTriangleLower=122 @enum CLBlastDiagonal CLBlastDiagonalNonUnit=131 CLBlastDiagonalUnit=132 @enum CLBlastSide CLBlastSideLeft=141 CLBlastSideRight=142 @enum CLBlastPrecision CLBlastPrecisionHalf=16 CLBlastPrecisionSingle=32 CLBlastPrecisionDouble=64 CLBlastPrecisionComplexSingle=3232 CLBlastPrecisionComplexDouble=6464
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
5464
const _clblast_status_codes = Dict{Int, Symbol}( # Status codes in common with the OpenCL standard 0=>:CLBlastSuccess , # CL_SUCCESS -3=>:CLBlastOpenCLCompilerNotAvailable, # CL_COMPILER_NOT_AVAILABLE -4=>:CLBlastTempBufferAllocFailure , # CL_MEM_OBJECT_ALLOCATION_FAILURE -5=>:CLBlastOpenCLOutOfResources , # CL_OUT_OF_RESOURCES -6=>:CLBlastOpenCLOutOfHostMemory , # CL_OUT_OF_HOST_MEMORY -11=>:CLBlastOpenCLBuildProgramFailure , # CL_BUILD_PROGRAM_FAILURE: OpenCL compilation error -30=>:CLBlastInvalidValue , # CL_INVALID_VALUE -36=>:CLBlastInvalidCommandQueue , # CL_INVALID_COMMAND_QUEUE -38=>:CLBlastInvalidMemObject , # CL_INVALID_MEM_OBJECT -42=>:CLBlastInvalidBinary , # CL_INVALID_BINARY -43=>:CLBlastInvalidBuildOptions , # CL_INVALID_BUILD_OPTIONS -44=>:CLBlastInvalidProgram , # CL_INVALID_PROGRAM -45=>:CLBlastInvalidProgramExecutable , # CL_INVALID_PROGRAM_EXECUTABLE -46=>:CLBlastInvalidKernelName , # CL_INVALID_KERNEL_NAME -47=>:CLBlastInvalidKernelDefinition , # CL_INVALID_KERNEL_DEFINITION -48=>:CLBlastInvalidKernel , # CL_INVALID_KERNEL -49=>:CLBlastInvalidArgIndex , # CL_INVALID_ARG_INDEX -50=>:CLBlastInvalidArgValue , # CL_INVALID_ARG_VALUE -51=>:CLBlastInvalidArgSize , # CL_INVALID_ARG_SIZE -52=>:CLBlastInvalidKernelArgs , # CL_INVALID_KERNEL_ARGS -53=>:CLBlastInvalidLocalNumDimensions , # CL_INVALID_WORK_DIMENSION: Too many thread dimensions -54=>:CLBlastInvalidLocalThreadsTotal , # CL_INVALID_WORK_GROUP_SIZE: Too many threads in total -55=>:CLBlastInvalidLocalThreadsDim , # CL_INVALID_WORK_ITEM_SIZE: ... or for a specific dimension -56=>:CLBlastInvalidGlobalOffset , # CL_INVALID_GLOBAL_OFFSET -57=>:CLBlastInvalidEventWaitList , # CL_INVALID_EVENT_WAIT_LIST -58=>:CLBlastInvalidEvent , # CL_INVALID_EVENT -59=>:CLBlastInvalidOperation , # CL_INVALID_OPERATION -61=>:CLBlastInvalidBufferSize , # CL_INVALID_BUFFER_SIZE -63=>:CLBlastInvalidGlobalWorkSize , # CL_INVALID_GLOBAL_WORK_SIZE # # Status codes in common with the clBLAS library -1024=>:CLBlastNotImplemented , # Routine or functionality not implemented yet -1022=>:CLBlastInvalidMatrixA , # Matrix A is not a valid OpenCL buffer -1021=>:CLBlastInvalidMatrixB , # Matrix B is not a valid OpenCL buffer -1020=>:CLBlastInvalidMatrixC , # Matrix C is not a valid OpenCL buffer -1019=>:CLBlastInvalidVectorX , # Vector X is not a valid OpenCL buffer -1018=>:CLBlastInvalidVectorY , # Vector Y is not a valid OpenCL buffer -1017=>:CLBlastInvalidDimension , # Dimensions M, N, and K have to be larger than zero -1016=>:CLBlastInvalidLeadDimA , # LD of A is smaller than the matrix's first dimension -1015=>:CLBlastInvalidLeadDimB , # LD of B is smaller than the matrix's first dimension -1014=>:CLBlastInvalidLeadDimC , # LD of C is smaller than the matrix's first dimension -1013=>:CLBlastInvalidIncrementX , # Increment of vector X cannot be zero -1012=>:CLBlastInvalidIncrementY , # Increment of vector Y cannot be zero -1011=>:CLBlastInsufficientMemoryA , # Matrix A's OpenCL buffer is too small -1010=>:CLBlastInsufficientMemoryB , # Matrix B's OpenCL buffer is too small -1009=>:CLBlastInsufficientMemoryC , # Matrix C's OpenCL buffer is too small -1008=>:CLBlastInsufficientMemoryX , # Vector X's OpenCL buffer is too small -1007=>:CLBlastInsufficientMemoryY , # Vector Y's OpenCL buffer is too small # # Custom additional status codes for CLBlast -2050=>:CLBlastInsufficientMemoryTemp , # Temporary buffer provided to GEMM routine is too small -2049=>:CLBlastInvalidBatchCount , # The batch count needs to be positive -2048=>:CLBlastInvalidOverrideKernel , # Trying to override parameters for an invalid kernel -2047=>:CLBlastMissingOverrideParameter , # Missing override parameter(s) for the target kernel -2046=>:CLBlastInvalidLocalMemUsage , # Not enough local memory available on this device -2045=>:CLBlastNoHalfPrecision , # Half precision (16-bits) not supported by the device -2044=>:CLBlastNoDoublePrecision , # Double precision (64-bits) not supported by the device -2043=>:CLBlastInvalidVectorScalar , # The unit-sized vector is not a valid OpenCL buffer -2042=>:CLBlastInsufficientMemoryScalar , # The unit-sized vector's OpenCL buffer is too small -2041=>:CLBlastDatabaseError , # Entry for the device was not found in the database -2040=>:CLBlastUnknownError , # A catch-all error code representing an unspecified error -2039=>:CLBlastUnexpectedError # A catch-all error code representing an unexpected exception ) struct CLBlastError <: Exception code::Int desc::Symbol function CLBlastError(c::Integer) new(c, get(_clblast_status_codes, Int(c), :CL_UNKNOWN_ERROR_CODE)) end end Base.show(io::IO, err::CLBlastError) = print(io, "CLBlastError(code=$(err.code), $(err.desc))")
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
246
include("swap.jl") include("scal.jl") include("copy.jl") include("axpy.jl") include("dot.jl") include("dotu.jl") include("dotc.jl") include("nrm2.jl") include("asum.jl") include("sum.jl") include("iamax.jl") include("iamin.jl") include("had.jl")
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1586
#import Base.LinAlg.BLAS: asum @compat for (func, elty) in [(:CLBlastSasum, Float32), (:CLBlastDasum, Float64), (:CLBlastScasum, ComplexF32), (:CLBlastDzasum, ComplexF64)] #TODO: (:CLBlastHasum, Float16) @eval function $func(n::Integer, out_buffer::cl.CL_mem, out_offset::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, out_buffer, out_offset, x_buffer, x_offset, x_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function asum(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output buffer and event ctx = cl.context(queue) out = zeros($elty, 1) out_buffer = cl.Buffer($elty, ctx, (:rw, :copy), hostbuf=out) event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(out_buffer), Csize_t(0), pointer(x), Csize_t(0), Csize_t(x_inc), queue, event) # wait for kernel and read return value cl.wait(event) cl.enqueue_read_buffer(queue, out_buffer, out, Csize_t(0), nothing, true) return real(first(out)) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1929
@compat for (func, elty) in [(:CLBlastSaxpy, Float32), (:CLBlastDaxpy, Float64), (:CLBlastCaxpy, ComplexF32), (:CLBlastZaxpy, ComplexF64)] #TODO: (:CLBlastHaxpy, Float16) @eval function $func(n::Integer, alpha::$elty, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, alpha, x_buffer, x_offset, x_inc, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function axpy!(n::Integer, α::Number, x::cl.CLArray{$elty}, x_inc::Integer, y::cl.CLArray{$elty}, y_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output event event::cl.Event = cl.Event(C_NULL) alpha = convert($elty, α) $func(Csize_t(n), alpha, pointer(x), Csize_t(0), Csize_t(x_inc), pointer(y), Csize_t(0), Csize_t(y_inc), queue, event) # wait for kernel cl.wait(event) y end @eval function axpy!(α::Number, x::cl.CLArray{$elty}, y::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(x)) n = length(x) if n != length(y) throw(DimensionMismatch("x has length $n while y has length $(length(y))!")) end axpy!(n, α, x, 1, y, 1, queue=queue) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1458
@compat for (func, elty) in [(:CLBlastScopy, Float32), (:CLBlastDcopy, Float64), (:CLBlastCcopy, ComplexF32), (:CLBlastZcopy, ComplexF64)] #TODO: (:CLBlastHcopy, Float16) @eval function $func(n::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, x_buffer, x_offset, x_inc, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function copy!(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer, y::cl.CLArray{$elty}, y_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output event event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(x), Csize_t(0), Csize_t(x_inc), pointer(y), Csize_t(0), Csize_t(y_inc), queue, event) # wait for kernel cl.wait(event) y end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1753
@compat for (func, elty) in [(:CLBlastSdot, Float32), (:CLBlastDdot, Float64)] #TODO: (:CLBlastHdot, Float16) @eval function $func(n::Integer, out_buffer::cl.CL_mem, out_offset::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, out_buffer, out_offset, x_buffer, x_offset, x_inc, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function dot(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer, y::cl.CLArray{$elty}, y_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output buffer and event ctx = cl.context(queue) out = zeros($elty, 1) out_buffer = cl.Buffer($elty, ctx, (:rw, :copy), hostbuf=out) event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(out_buffer), Csize_t(0), pointer(x), Csize_t(0), Csize_t(x_inc), pointer(y), Csize_t(0), Csize_t(y_inc), queue, event) # wait for kernel and read return value cl.wait(event) cl.enqueue_read_buffer(queue, out_buffer, out, Csize_t(0), nothing, true) return first(out) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1730
@compat for (func, elty) in [(:CLBlastCdotc, ComplexF32), (:CLBlastZdotc, ComplexF64)] @eval function $func(n::Integer, out_buffer::cl.CL_mem, out_offset::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, out_buffer, out_offset, x_buffer, x_offset, x_inc, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function dotc(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer, y::cl.CLArray{$elty}, y_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output buffer and event ctx = cl.context(queue) out = zeros($elty, 1) out_buffer = cl.Buffer($elty, ctx, (:rw, :copy), hostbuf=out) event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(out_buffer), Csize_t(0), pointer(x), Csize_t(0), Csize_t(x_inc), pointer(y), Csize_t(0), Csize_t(y_inc), queue, event) # wait for kernel and read return value cl.wait(event) cl.enqueue_read_buffer(queue, out_buffer, out, Csize_t(0), nothing, true) return first(out) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1730
@compat for (func, elty) in [(:CLBlastCdotu, ComplexF32), (:CLBlastZdotu, ComplexF64)] @eval function $func(n::Integer, out_buffer::cl.CL_mem, out_offset::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, out_buffer, out_offset, x_buffer, x_offset, x_inc, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function dotu(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer, y::cl.CLArray{$elty}, y_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output buffer and event ctx = cl.context(queue) out = zeros($elty, 1) out_buffer = cl.Buffer($elty, ctx, (:rw, :copy), hostbuf=out) event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(out_buffer), Csize_t(0), pointer(x), Csize_t(0), Csize_t(x_inc), pointer(y), Csize_t(0), Csize_t(y_inc), queue, event) # wait for kernel and read return value cl.wait(event) cl.enqueue_read_buffer(queue, out_buffer, out, Csize_t(0), nothing, true) return first(out) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1922
@compat for (func, elty) in [(:CLBlastShad, Float32), (:CLBlastDhad, Float64), (:CLBlastChad, ComplexF32), (:CLBlastZhad, ComplexF64)] #TODO: (:CLBlastHhad, Float16) @eval function $func(n::Integer, alpha::$elty, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, beta::$elty, z_buffer::cl.CL_mem, z_offset::Integer, z_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, alpha, x_buffer, x_offset, x_inc, y_buffer, y_offset, y_inc, beta, z_buffer, z_offset, z_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function had!(n::Integer, α::Number, x::cl.CLArray{$elty}, x_inc::Integer, y::cl.CLArray{$elty}, y_inc::Integer, β::Number, z::cl.CLArray{$elty}, z_inc::Integer; queue::cl.CmdQueue=cl.queue(z)) # output event event::cl.Event = cl.Event(C_NULL) alpha = convert($elty, α) beta = convert($elty, β) $func(Csize_t(n), alpha, pointer(x), Csize_t(0), Csize_t(x_inc), pointer(y), Csize_t(0), Csize_t(y_inc), beta, pointer(z), Csize_t(0), Csize_t(z_inc), queue, event) # wait for kernel cl.wait(event) z end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1581
#import Base.LinAlg.BLAS: iamax @compat for (func, elty) in [(:CLBlastiSamax, Float32), (:CLBlastiDamax, Float64), (:CLBlastiCamax, ComplexF32), (:CLBlastiZamax, ComplexF64)] #TODO: (:CLBlastiHamax, Float16) @eval function $func(n::Integer, out_buffer::cl.CL_mem, out_offset::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, out_buffer, out_offset, x_buffer, x_offset, x_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function iamax(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output buffer and event ctx = cl.context(queue) out = zeros(Int, 1) out_buffer = cl.Buffer(Int, ctx, (:rw, :copy), hostbuf=out) event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(out_buffer), Csize_t(0), pointer(x), Csize_t(0), Csize_t(x_inc), queue, event) # wait for kernel and read return value cl.wait(event) cl.enqueue_read_buffer(queue, out_buffer, out, Csize_t(0), nothing, true) return first(out) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1549
@compat for (func, elty) in [(:CLBlastiSamin, Float32), (:CLBlastiDamin, Float64), (:CLBlastiCamin, ComplexF32), (:CLBlastiZamin, ComplexF64)] #TODO: (:CLBlastiHamin, Float16) @eval function $func(n::Integer, out_buffer::cl.CL_mem, out_offset::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, out_buffer, out_offset, x_buffer, x_offset, x_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function iamin(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output buffer and event ctx = cl.context(queue) out = zeros(Int, 1) out_buffer = cl.Buffer(Int, ctx, (:rw, :copy), hostbuf=out) event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(out_buffer), Csize_t(0), pointer(x), Csize_t(0), Csize_t(x_inc), queue, event) # wait for kernel and read return value cl.wait(event) cl.enqueue_read_buffer(queue, out_buffer, out, Csize_t(0), nothing, true) return first(out) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1586
#import Base.LinAlg.BLAS: nrm2 @compat for (func, elty) in [(:CLBlastSnrm2, Float32), (:CLBlastDnrm2, Float64), (:CLBlastScnrm2, ComplexF32), (:CLBlastDznrm2, ComplexF64)] #TODO: (:CLBlastHnrm2, Float16) @eval function $func(n::Integer, out_buffer::cl.CL_mem, out_offset::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, out_buffer, out_offset, x_buffer, x_offset, x_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function nrm2(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output buffer and event ctx = cl.context(queue) out = zeros($elty, 1) out_buffer = cl.Buffer($elty, ctx, (:rw, :copy), hostbuf=out) event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(out_buffer), Csize_t(0), pointer(x), Csize_t(0), Csize_t(x_inc), queue, event) # wait for kernel and read return value cl.wait(event) cl.enqueue_read_buffer(queue, out_buffer, out, Csize_t(0), nothing, true) return real(first(out)) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1479
@compat for (func, elty) in [(:CLBlastSscal, Float32), (:CLBlastDscal, Float64), (:CLBlastCscal, ComplexF32), (:CLBlastZscal, ComplexF64)] #TODO: (:CLBlastHscal, Float16) @eval function $func(n::Integer, alpha::$elty, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, alpha, x_buffer, x_offset, x_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function scal!(n::Integer, α::Number, x::cl.CLArray{$elty}, x_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output event event::cl.Event = cl.Event(C_NULL) alpha = convert($elty, α) $func(Csize_t(n), alpha, pointer(x), Csize_t(0), Csize_t(x_inc), queue, event) # wait for kernel cl.wait(event) x end @eval function scal!(α::Number, x::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(x)) scal!(length(x), α, x, 1, queue=queue) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1542
@compat for (func, elty) in [(:CLBlastSsum, Float32), (:CLBlastDsum, Float64), (:CLBlastScsum, ComplexF32), (:CLBlastDzsum, ComplexF64)] #TODO: (:CLBlastHsum, Float16) @eval function $func(n::Integer, out_buffer::cl.CL_mem, out_offset::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, out_buffer, out_offset, x_buffer, x_offset, x_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function sum(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output buffer and event ctx = cl.context(queue) out = zeros($elty, 1) out_buffer = cl.Buffer($elty, ctx, (:rw, :copy), hostbuf=out) event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(out_buffer), Csize_t(0), pointer(x), Csize_t(0), Csize_t(x_inc), queue, event) # wait for kernel and read return value cl.wait(event) cl.enqueue_read_buffer(queue, out_buffer, out, Csize_t(0), nothing, true) return first(out) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
1464
@compat for (func, elty) in [(:CLBlastSswap, Float32), (:CLBlastDswap, Float64), (:CLBlastCswap, ComplexF32), (:CLBlastZswap, ComplexF64)] #TODO: (:CLBlastHswap, Float16) @eval function $func(n::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), n, x_buffer, x_offset, x_inc, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(cl.CLError(err)) end return err end @eval function swap!(n::Integer, x::cl.CLArray{$elty}, x_inc::Integer, y::cl.CLArray{$elty}, y_inc::Integer; queue::cl.CmdQueue=cl.queue(x)) # output event event::cl.Event = cl.Event(C_NULL) $func(Csize_t(n), pointer(x), Csize_t(0), Csize_t(x_inc), pointer(y), Csize_t(0), Csize_t(y_inc), queue, event) # wait for kernel cl.wait(event) nothing end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
206
include("gemv.jl") include("gbmv.jl") include("hemv.jl") include("hbmv.jl") include("symv.jl") include("sbmv.jl") include("trmv.jl") include("trsv.jl") include("ger.jl") include("her.jl") include("syr.jl")
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2604
@compat for (func, elty) in [(:CLBlastSgbmv, Float32), (:CLBlastDgbmv, Float64), (:CLBlastCgbmv, ComplexF32), (:CLBlastZgbmv, ComplexF64)] #TODO: (:CLBlastHgbmv, Float16) @eval function $func(layout::CLBlastLayout, a_transpose::CLBlastTranspose, m::Integer, n::Integer, kl::Integer, ku::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, beta::$elty, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Csize_t, Csize_t, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(a_transpose), m, n, kl, ku, alpha, a_buffer, a_offset, a_ld, x_buffer, x_offset, x_inc, beta, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function gbmv!(tA::Char, m::Integer, kl::Integer, ku::Integer, α::Number, A::cl.CLArray{$elty,2}, x::cl.CLArray{$elty}, β::Number, y::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(y)) # check and convert arguments if tA == 'N' a_transpose = CLBlastTransposeNo elseif tA == 'T' || (tA == 'C' && $elty <: Real) a_transpose = CLBlastTransposeYes elseif tA == 'C' && $elty <: Complex a_transpose = CLBlastTransposeConjugate else throw(ArgumentError("Transpose marker `tA` is $(tA) but only 'N', 'T', and 'C' are allowed.")) end alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, a_transpose, m, size(A,2), kl, ku, alpha, pointer(A), 0, size(A,1), pointer(x), 0, 1, beta, pointer(y), 0, 1, queue, event) # wait for kernel cl.wait(event) y end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3101
@compat for (func, elty) in [(:CLBlastSgemv, Float32), (:CLBlastDgemv, Float64), (:CLBlastCgemv, ComplexF32), (:CLBlastZgemv, ComplexF64)] #TODO: (:CLBlastHgemv, Float16) @eval function $func(layout::CLBlastLayout, a_transpose::CLBlastTranspose, m::Integer, n::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, beta::$elty, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(a_transpose), m, n, alpha, a_buffer, a_offset, a_ld, x_buffer, x_offset, x_inc, beta, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function gemv!(tA::Char, α::Number, A::cl.CLArray{$elty,2}, x::cl.CLArray{$elty}, β::Number, y::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(y)) # check and convert arguments m, n = size(A) if tA == 'N' a_transpose = CLBlastTransposeNo if length(x) != n || length(y) != m throw(DimensionMismatch("A has dimensions $(size(A)), x has length $(length(x)) and y has length $(length(y)).")) end elseif tA == 'T' || (tA == 'C' && $elty <: Real) a_transpose = CLBlastTransposeYes if length(x) != m || length(y) != n throw(DimensionMismatch("The adjoint of A has dimensions $n, $m, x has length $(length(x)) and y has length $(length(y))")) end elseif tA == 'C' && $elty <: Complex a_transpose = CLBlastTransposeConjugate if length(x) != m || length(y) != n throw(DimensionMismatch("The transpose of A has dimensions $n, $m, x has length $(length(x)) and y has length $(length(y)).")) end else throw(ArgumentError("Transpose marker `tA` is $(tA) but only 'N', 'T', and 'C' are allowed.")) end alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, a_transpose, m, n, alpha, pointer(A), 0, size(A,1), pointer(x), 0, 1, beta, pointer(y), 0, 1, queue, event) # wait for kernel cl.wait(event) y end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2086
@compat for (func, elty) in [(:CLBlastSger, Float32), (:CLBlastDger, Float64), (:CLBlastCgerc, ComplexF32), (:CLBlastZgerc, ComplexF64)] #TODO: (:CLBlastHger, Float16) @eval function $func(layout::CLBlastLayout, m::Integer, n::Integer, alpha::$elty, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), m, n, alpha, x_buffer, x_offset, x_inc, y_buffer, y_offset, y_inc, a_buffer, a_offset, a_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function ger!(α::Number, x::cl.CLArray{$elty}, y::cl.CLArray{$elty}, A::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(A)) # check and convert arguments m, n = size(A) if length(x) != m || length(y) != n throw(DimensionMismatch("`A` has dimensions $(size(A)), `x` has length $(length(x)) and `y` has length $(length(y)).")) end alpha = convert($elty, α) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, m, n, alpha, pointer(x), 0, 1, pointer(y), 0, 1, pointer(A), 0, size(A,1), queue, event) # wait for kernel cl.wait(event) A end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2497
@compat for (func, elty) in [(:CLBlastChbmv, ComplexF32), (:CLBlastZhbmv, ComplexF64)] #TODO: (:CLBlastHhbmv, Float16) @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, n::Integer, k::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, beta::$elty, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), n, k, alpha, a_buffer, a_offset, a_ld, x_buffer, x_offset, x_inc, beta, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function hbmv!(uplo::Char, k::Integer, α::Number, A::cl.CLArray{$elty,2}, x::cl.CLArray{$elty}, β::Number, y::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(y)) # check and convert arguments n = size(A,2) if length(x) != n || length(y) != n throw(DimensionMismatch("x has length $(length(x)) and y has length $(length(y)) while $n is required.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, n, k, alpha, pointer(A), 0, size(A,1), pointer(x), 0, 1, beta, pointer(y), 0, 1, queue, event) # wait for kernel cl.wait(event) y end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2568
@compat for (func, elty) in [(:CLBlastChemv, ComplexF32), (:CLBlastZhemv, ComplexF64)] #TODO: (:CLBlastHhemv, Float16) @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, n::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, beta::$elty, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), n, alpha, a_buffer, a_offset, a_ld, x_buffer, x_offset, x_inc, beta, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function hemv!(uplo::Char, α::Number, A::cl.CLArray{$elty,2}, x::cl.CLArray{$elty}, β::Number, y::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(y)) # check and convert arguments m, n = size(A) if m != n throw(DimensionMismatch("`A` has dimensions $(size(A)) but must be square.")) end if length(x) != n || length(y) != n throw(DimensionMismatch("`A` has dimensions $(size(A)), `x` has length $(length(x)) and `y` has length $(length(y)).")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, n, alpha, pointer(A), 0, size(A,1), pointer(x), 0, 1, beta, pointer(y), 0, 1, queue, event) # wait for kernel cl.wait(event) y end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2201
@compat for (func, elty, relty) in [(:CLBlastCher, ComplexF32, Float32), (:CLBlastZher, ComplexF64, Float64)] @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, n::Integer, alpha::$relty, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Csize_t, $relty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), n, alpha, x_buffer, x_offset, x_inc, a_buffer, a_offset, a_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function her!(uplo::Char, α::Number, x::cl.CLArray{$elty}, A::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(A)) # check and convert arguments m, n = size(A) if m != n throw(DimensionMismatch("`A` has dimensions $(size(A)) but must be square.")) end if length(x) != n throw(DimensionMismatch("`A` has dimensions $(size(A)) and `x` has length $(length(x)).")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end alpha = convert($relty, α) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, n, alpha, pointer(x), 0, 1, pointer(A), 0, size(A,1), queue, event) # wait for kernel cl.wait(event) A end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2491
@compat for (func, elty) in [(:CLBlastSsbmv, Float32), (:CLBlastDsbmv, Float64)] #TODO: (:CLBlastHsbmv, Float16) @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, n::Integer, k::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, beta::$elty, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), n, k, alpha, a_buffer, a_offset, a_ld, x_buffer, x_offset, x_inc, beta, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function sbmv!(uplo::Char, k::Integer, α::Number, A::cl.CLArray{$elty,2}, x::cl.CLArray{$elty}, β::Number, y::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(y)) # check and convert arguments n = size(A,2) if length(x) != n || length(y) != n throw(DimensionMismatch("x has length $(length(x)) and y has length $(length(y)) while $n is required.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, n, k, alpha, pointer(A), 0, size(A,1), pointer(x), 0, 1, beta, pointer(y), 0, 1, queue, event) # wait for kernel cl.wait(event) y end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2554
@compat for (func, elty) in [(:CLBlastSsymv, Float32), (:CLBlastDsymv, Float64)] #TODO: (:CLBlastHsymv, Float16) @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, n::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, beta::$elty, y_buffer::cl.CL_mem, y_offset::Integer, y_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), n, alpha, a_buffer, a_offset, a_ld, x_buffer, x_offset, x_inc, beta, y_buffer, y_offset, y_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function symv!(uplo::Char, α::Number, A::cl.CLArray{$elty,2}, x::cl.CLArray{$elty}, β::Number, y::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(y)) # check and convert arguments m, n = size(A) if m != n throw(DimensionMismatch("A has dimensions $(size(A)) but must be square.")) end if length(x) != n || length(y) != n throw(DimensionMismatch("A has dimensions $(size(A)), x has length $(length(x)) and y has length $(length(y)).")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, n, alpha, pointer(A), 0, size(A,1), pointer(x), 0, 1, beta, pointer(y), 0, 1, queue, event) # wait for kernel cl.wait(event) y end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2202
@compat for (func, elty) in [(:CLBlastSsyr, Float32), (:CLBlastDsyr, Float64)] #TODO: (:CLBlastHsyr, Float16) @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, n::Integer, alpha::$elty, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), n, alpha, x_buffer, x_offset, x_inc, a_buffer, a_offset, a_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function syr!(uplo::Char, α::Number, x::cl.CLArray{$elty}, A::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(A)) # check and convert arguments m, n = size(A) if m != n throw(DimensionMismatch("`A` has dimensions $(size(A)) but must be square.")) end if length(x) != n throw(DimensionMismatch("`A` has dimensions $(size(A)) and `x` has length $(length(x)).")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end alpha = convert($elty, α) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, n, alpha, pointer(x), 0, 1, pointer(A), 0, size(A,1), queue, event) # wait for kernel cl.wait(event) A end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3015
@compat for (func, elty) in [(:CLBlastStrmv, Float32), (:CLBlastDtrmv, Float64), (:CLBlastCtrmv, ComplexF32), (:CLBlastZtrmv, ComplexF64)] #TODO: (:CLBlastHtrmv, Float16) @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, a_transpose::CLBlastTranspose, diagonal::CLBlastDiagonal, n::Integer, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Cint, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), Cint(a_transpose), Cint(diagonal), n, a_buffer, a_offset, a_ld, x_buffer, x_offset, x_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function trmv!(uplo::Char, trans::Char, diag::Char, A::cl.CLArray{$elty,2}, x::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(x)) # check and convert arguments m, n = size(A) if m != n throw(DimensionMismatch("`A` has dimensions $(size(A)) but must be square.")) end if length(x) != n throw(DimensionMismatch("`x` has length $(length(x)) while $n is required.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end if trans == 'N' a_transpose = CLBlastTransposeNo elseif trans == 'T' || (trans == 'C' && $elty <: Real) a_transpose = CLBlastTransposeYes elseif trans == 'C' && $elty <: Complex a_transpose = CLBlastTransposeConjugate else throw(ArgumentError("Transpose marker `trans` is $(uplo) but only 'N', 'T', and 'C' are allowed.")) end if diag == 'N' diagonal = CLBlastDiagonalNonUnit elseif diag == 'U' diagonal = CLBlastDiagonalUnit else throw(ArgumentError("Diagonal marker `diag` is $(diag) but only 'N' and 'U' are allowed.")) end layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, a_transpose, diagonal, n, pointer(A), 0, size(A,1), pointer(x), 0, 1, queue, event) # wait for kernel cl.wait(event) x end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3121
@compat for (func, elty) in [(:CLBlastStrsv, Float32), (:CLBlastDtrsv, Float64), (:CLBlastCtrsv, ComplexF32), (:CLBlastZtrsv, ComplexF64)] @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, a_transpose::CLBlastTranspose, diagonal::CLBlastDiagonal, n::Integer, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, x_buffer::cl.CL_mem, x_offset::Integer, x_inc::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Cint, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), Cint(a_transpose), Cint(diagonal), n, a_buffer, a_offset, a_ld, x_buffer, x_offset, x_inc, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function trsv!(uplo::Char, trans::Char, diag::Char, A::cl.CLArray{$elty,2}, x::cl.CLArray{$elty}; queue::cl.CmdQueue=cl.queue(x)) # check and convert arguments m, n = size(A) if m != n throw(DimensionMismatch("`A` has dimensions $(size(A)) but must be square.")) end if length(x) != n throw(DimensionMismatch("`x` has length $(length(x)) while $n is required.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end if trans == 'N' a_transpose = CLBlastTransposeNo elseif trans == 'T' || (trans == 'C' && $elty <: Real) a_transpose = CLBlastTransposeYes elseif trans == 'C' && $elty <: Complex a_transpose = CLBlastTransposeConjugate else throw(ArgumentError("Transpose marker `trans` is $(uplo) but only 'N', 'T', and 'C' are allowed.")) end if diag == 'N' diagonal = CLBlastDiagonalNonUnit elseif diag == 'U' diagonal = CLBlastDiagonalUnit else throw(ArgumentError("Diagonal marker `diag` is $(diag) but only 'N' and 'U' are allowed.")) end layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, a_transpose, diagonal, n, pointer(A), 0, size(A,1), pointer(x), 0, 1, queue, event) # wait for kernel # the additional check is due to https://github.com/CNugteren/CLBlast/issues/311 if event != cl.Event(C_NULL) cl.wait(event) end x end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
173
include("gemm.jl") include("symm.jl") include("hemm.jl") include("syrk.jl") include("herk.jl") include("syr2k.jl") include("her2k.jl") include("trmm.jl") include("trsm.jl")
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3428
@compat for (func, elty) in [(:CLBlastSgemm, Float32), (:CLBlastDgemm, Float64), (:CLBlastCgemm, ComplexF32), (:CLBlastZgemm, ComplexF64)] #TODO: (:CLBlastHgemm, Float16) @eval function $func(layout::CLBlastLayout, a_transpose::CLBlastTranspose, b_transpose::CLBlastTranspose, m::Integer, n::Integer, k::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, b_buffer::cl.CL_mem, b_offset::Integer, b_ld::Integer, beta::$elty, c_buffer::cl.CL_mem, c_offset::Integer, c_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Csize_t, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(a_transpose), Cint(b_transpose), m, n, k, alpha, a_buffer, a_offset, a_ld, b_buffer, b_offset, b_ld, beta, c_buffer, c_offset, c_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function gemm!(transA::Char, transB::Char, α::Number, A::cl.CLArray{$elty,2}, B::cl.CLArray{$elty,2}, β::Number, C::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(C)) # check and convert arguments if transA == 'N' a_transpose = CLBlastTransposeNo elseif transA == 'T' || (transA == 'C' && $elty <: Real) a_transpose = CLBlastTransposeYes elseif transA == 'C' && $elty <: Complex a_transpose = CLBlastTransposeConjugate else throw(ArgumentError("Transpose marker `transA` is $(transA) but only 'N', 'T', and 'C' are allowed.")) end if transB == 'N' b_transpose = CLBlastTransposeNo elseif transB == 'T' || (transB == 'C' && $elty <: Real) b_transpose = CLBlastTransposeYes elseif transB == 'C' && $elty <: Complex b_transpose = CLBlastTransposeConjugate else throw(ArgumentError("Transpose marker `transB` is $(transB) but only 'N', 'T', and 'C' are allowed.")) end m = size(A, transA == 'N' ? 1 : 2) ka = size(A, transA == 'N' ? 2 : 1) kb = size(B, transB == 'N' ? 1 : 2) n = size(B, transB == 'N' ? 2 : 1) if ka != kb || m != size(C,1) || n != size(C,2) throw(DimensionMismatch("`A` has size ($m,$ka), `B` has size ($kb,$n), `C` has size $(size(C)).")) end alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, a_transpose, b_transpose, m, n, ka, alpha, pointer(A), 0, size(A,1), pointer(B), 0, size(B,1), beta, pointer(C), 0, size(C,1), queue, event) # wait for kernel cl.wait(event) C end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3049
@compat for (func, elty) in [(:CLBlastChemm, ComplexF32), (:CLBlastZhemm, ComplexF64)] @eval function $func(layout::CLBlastLayout, side::CLBlastSide, triangle::CLBlastTriangle, m::Integer, n::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, b_buffer::cl.CL_mem, b_offset::Integer, b_ld::Integer, beta::$elty, c_buffer::cl.CL_mem, c_offset::Integer, c_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(side), Cint(triangle), m, n, alpha, a_buffer, a_offset, a_ld, b_buffer, b_offset, b_ld, beta, c_buffer, c_offset, c_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function hemm!(_side::Char, uplo::Char, α::Number, A::cl.CLArray{$elty,2}, B::cl.CLArray{$elty,2}, β::Number, C::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(C)) # check and convert arguments if _side == 'L' side = CLBlastSideLeft elseif _side == 'R' side = CLBlastSideRight else throw(ArgumentError("Side marker `side` is $(_side) but only 'L' and 'R' are allowed.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end m, n = size(C) j = size(A,1) if j != size(A,2) throw(DimensionMismatch("`A` has dimensions $(size(A)) but must be square.")) end if j != (_side == 'L' ? m : n) throw(DimensionMismatch("`A` has size $(size(A)), `C` has size ($m,$n).")) end if size(B,2) != n throw(DimensionMismatch("`B` has second dimension $(size(B,2)) but needs to match second dimension of `C`, $n.")) end alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, side, triangle, m, n, alpha, pointer(A), 0, size(A,1), pointer(B), 0, size(B,1), beta, pointer(C), 0, size(C,1), queue, event) # wait for kernel cl.wait(event) C end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3197
@compat for (func, elty, relty) in [(:CLBlastCher2k, ComplexF32, Float32), (:CLBlastZher2k, ComplexF64, Float64)] @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, ab_transpose::CLBlastTranspose, n::Integer, k::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, b_buffer::cl.CL_mem, b_offset::Integer, b_ld::Integer, beta::$relty, c_buffer::cl.CL_mem, c_offset::Integer, c_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), Cint(ab_transpose), n, k, alpha, a_buffer, a_offset, a_ld, b_buffer, b_offset, b_ld, beta, c_buffer, c_offset, c_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function her2k!(uplo::Char, trans::Char, α::Number, A::cl.CLArray{$elty,2}, B::cl.CLArray{$elty,2}, β::Number, C::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(C)) # check and convert arguments if trans == 'N' ab_transpose = CLBlastTransposeNo elseif trans == 'C' ab_transpose = CLBlastTransposeConjugate else throw(ArgumentError("Transpose marker `trans` is $(trans) but only 'N' and 'C' are allowed.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end n = size(C,1) if n != size(C,2) throw(DimensionMismatch("`C` has dimensions $(size(C)) but must be square.")) end nn = size(A, trans == 'N' ? 1 : 2) if nn != n throw(DimensionMismatch("`C` has size ($n,$n), corresponding dimension of `A` is $nn.")) end if size(A) != size(B) throw(DimensionMismatch("`A` has size $(size(A)), `B` has size $(size(B)).")) end k = size(A, trans == 'N' ? 2 : 1) alpha = convert($elty, α) beta = convert($relty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, ab_transpose, n, k, alpha, pointer(A), 0, size(A,1), pointer(B), 0, size(B,1), beta, pointer(C), 0, size(C,1), queue, event) # wait for kernel cl.wait(event) C end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2800
@compat for (func, elty) in [(:CLBlastCherk, ComplexF32), (:CLBlastZherk, ComplexF64)] @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, a_transpose::CLBlastTranspose, n::Integer, k::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, beta::$elty, c_buffer::cl.CL_mem, c_offset::Integer, c_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), Cint(a_transpose), n, k, alpha, a_buffer, a_offset, a_ld, beta, c_buffer, c_offset, c_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function herk!(uplo::Char, trans::Char, α::Number, A::cl.CLArray{$elty,2}, β::Number, C::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(C)) # check and convert arguments if trans == 'N' a_transpose = CLBlastTransposeNo elseif trans == 'C' a_transpose = CLBlastTransposeConjugate else throw(ArgumentError("Transpose marker `trans` is $(trans) but only 'N' and 'C' are allowed.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end n = size(C,1) if n != size(C,2) throw(DimensionMismatch("`C` has dimensions $(size(C)) but must be square.")) end nn = size(A, trans == 'N' ? 1 : 2) if nn != n throw(DimensionMismatch("`C` has size ($n,$n), corresponding dimension of `A` is $nn.")) end k = size(A, trans == 'N' ? 2 : 1) alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, a_transpose, n, k, alpha, pointer(A), 0, size(A,1), beta, pointer(C), 0, size(C,1), queue, event) # wait for kernel cl.wait(event) C end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3158
@compat for (func, elty) in [(:CLBlastSsymm, Float32), (:CLBlastDsymm, Float64), (:CLBlastCsymm, ComplexF32), (:CLBlastZsymm, ComplexF64)] #TODO: (:CLBlastHsymm, Float16) @eval function $func(layout::CLBlastLayout, side::CLBlastSide, triangle::CLBlastTriangle, m::Integer, n::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, b_buffer::cl.CL_mem, b_offset::Integer, b_ld::Integer, beta::$elty, c_buffer::cl.CL_mem, c_offset::Integer, c_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(side), Cint(triangle), m, n, alpha, a_buffer, a_offset, a_ld, b_buffer, b_offset, b_ld, beta, c_buffer, c_offset, c_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function symm!(_side::Char, uplo::Char, α::Number, A::cl.CLArray{$elty,2}, B::cl.CLArray{$elty,2}, β::Number, C::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(C)) # check and convert arguments if _side == 'L' side = CLBlastSideLeft elseif _side == 'R' side = CLBlastSideRight else throw(ArgumentError("Side marker `side` is $(_side) but only 'L' and 'R' are allowed.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end m, n = size(C) j = size(A,1) if j != size(A,2) throw(DimensionMismatch("`A` has dimensions $(size(A)) but must be square.")) end if j != (_side == 'L' ? m : n) throw(DimensionMismatch("`A` has size $(size(A)), `C` has size ($m,$n).")) end if size(B,2) != n throw(DimensionMismatch("`B` has second dimension $(size(B,2)) but needs to match second dimension of `C`, $n.")) end alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, side, triangle, m, n, alpha, pointer(A), 0, size(A,1), pointer(B), 0, size(B,1), beta, pointer(C), 0, size(C,1), queue, event) # wait for kernel cl.wait(event) C end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3248
@compat for (func, elty) in [(:CLBlastSsyr2k, Float32), (:CLBlastDsyr2k, Float64), (:CLBlastCsyr2k, ComplexF32), (:CLBlastZsyr2k, ComplexF64)] #TODO: (:CLBlastHsyr2k, Float16) @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, ab_transpose::CLBlastTranspose, n::Integer, k::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, b_buffer::cl.CL_mem, b_offset::Integer, b_ld::Integer, beta::$elty, c_buffer::cl.CL_mem, c_offset::Integer, c_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), Cint(ab_transpose), n, k, alpha, a_buffer, a_offset, a_ld, b_buffer, b_offset, b_ld, beta, c_buffer, c_offset, c_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function syr2k!(uplo::Char, trans::Char, α::Number, A::cl.CLArray{$elty,2}, B::cl.CLArray{$elty,2}, β::Number, C::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(C)) # check and convert arguments if trans == 'N' ab_transpose = CLBlastTransposeNo elseif trans == 'T' ab_transpose = CLBlastTransposeYes else throw(ArgumentError("Transpose marker `trans` is $(trans) but only 'N' and 'T' are allowed.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end n = size(C,1) if n != size(C,2) throw(DimensionMismatch("`C` has dimensions $(size(C)) but must be square.")) end nn = size(A, trans == 'N' ? 1 : 2) if nn != n throw(DimensionMismatch("`C` has size ($n,$n), corresponding dimension of `A` is $nn.")) end if size(A) != size(B) throw(DimensionMismatch("`A` has size $(size(A)), `B` has size $(size(B)).")) end k = size(A, trans == 'N' ? 2 : 1) alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, ab_transpose, n, k, alpha, pointer(A), 0, size(A,1), pointer(B), 0, size(B,1), beta, pointer(C), 0, size(C,1), queue, event) # wait for kernel cl.wait(event) C end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
2903
@compat for (func, elty) in [(:CLBlastSsyrk, Float32), (:CLBlastDsyrk, Float64), (:CLBlastCsyrk, ComplexF32), (:CLBlastZsyrk, ComplexF64)] #TODO: (:CLBlastHsyrk, Float16) @eval function $func(layout::CLBlastLayout, triangle::CLBlastTriangle, a_transpose::CLBlastTranspose, n::Integer, k::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, beta::$elty, c_buffer::cl.CL_mem, c_offset::Integer, c_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(triangle), Cint(a_transpose), n, k, alpha, a_buffer, a_offset, a_ld, beta, c_buffer, c_offset, c_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function syrk!(uplo::Char, trans::Char, α::Number, A::cl.CLArray{$elty,2}, β::Number, C::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(C)) # check and convert arguments if trans == 'N' a_transpose = CLBlastTransposeNo elseif trans == 'T' a_transpose = CLBlastTransposeYes else throw(ArgumentError("Transpose marker `trans` is $(trans) but only 'N' and 'T' are allowed.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end n = size(C,1) if n != size(C,2) throw(DimensionMismatch("`C` has dimensions $(size(C)) but must be square.")) end nn = size(A, trans == 'N' ? 1 : 2) if nn != n throw(DimensionMismatch("`C` has size ($n,$n), corresponding dimension of `A` is $nn.")) end k = size(A, trans == 'N' ? 2 : 1) alpha = convert($elty, α) beta = convert($elty, β) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, triangle, a_transpose, n, k, alpha, pointer(A), 0, size(A,1), beta, pointer(C), 0, size(C,1), queue, event) # wait for kernel cl.wait(event) C end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3555
@compat for (func, elty) in [(:CLBlastStrmm, Float32), (:CLBlastDtrmm, Float64), (:CLBlastCtrmm, ComplexF32), (:CLBlastZtrmm, ComplexF64)] #TODO: (:CLBlastHtrmm, Float16) @eval function $func(layout::CLBlastLayout, side::CLBlastSide, triangle::CLBlastTriangle, a_transpose::CLBlastTranspose, diagonal::CLBlastDiagonal, m::Integer, n::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, b_buffer::cl.CL_mem, b_offset::Integer, b_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(side), Cint(triangle), Cint(a_transpose), Cint(diagonal), m, n, alpha, a_buffer, a_offset, a_ld, b_buffer, b_offset, b_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function trmm!(_side::Char, uplo::Char, transA::Char, diag::Char, α::Number, A::cl.CLArray{$elty,2}, B::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(B)) # check and convert arguments if _side == 'L' side = CLBlastSideLeft elseif _side == 'R' side = CLBlastSideRight else throw(ArgumentError("Side marker `side` is $(_side) but only 'L' and 'R' are allowed.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end if transA == 'N' a_transpose = CLBlastTransposeNo elseif transA == 'T' || (transA == 'C' && $elty <: Real) a_transpose = CLBlastTransposeYes elseif transA == 'C' && $elty <: Complex a_transpose = CLBlastTransposeConjugate else throw(ArgumentError("Transpose marker `transA` is $(transA) but only 'N', 'T', and 'C' are allowed.")) end if diag == 'N' diagonal = CLBlastDiagonalNonUnit elseif diag == 'U' diagonal = CLBlastDiagonalUnit else throw(ArgumentError("Diagonal marker `diag` is $(diag) but only 'N' and 'U' are allowed.")) end m, n = size(B) nA = size(A,1) if nA != size(A,2) throw(DimensionMismatch("`A` has dimensions $(size(A)) but must be square.")) end if nA != (_side == 'L' ? m : n) throw(DimensionMismatch("Size of A, $(size(A)), doesn't match $_side size of B with dims, $(size(B)).")) end alpha = convert($elty, α) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, side, triangle, a_transpose, diagonal, m, n, alpha, pointer(A), 0, size(A,1), pointer(B), 0, size(B,1), queue, event) # wait for kernel cl.wait(event) B end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
3661
@compat for (func, elty) in [(:CLBlastStrsm, Float32), (:CLBlastDtrsm, Float64), (:CLBlastCtrsm, ComplexF32), (:CLBlastZtrsm, ComplexF64)] @eval function $func(layout::CLBlastLayout, side::CLBlastSide, triangle::CLBlastTriangle, a_transpose::CLBlastTranspose, diagonal::CLBlastDiagonal, m::Integer, n::Integer, alpha::$elty, a_buffer::cl.CL_mem, a_offset::Integer, a_ld::Integer, b_buffer::cl.CL_mem, b_offset::Integer, b_ld::Integer, queue::cl.CmdQueue, event::cl.Event) err = ccall( ($(string(func)), libCLBlast), cl.CL_int, (Cint, Cint, Cint, Cint, Cint, Csize_t, Csize_t, $elty, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}), Cint(layout), Cint(side), Cint(triangle), Cint(a_transpose), Cint(diagonal), m, n, alpha, a_buffer, a_offset, a_ld, b_buffer, b_offset, b_ld, Ref(queue), Ref(event) ) if err != cl.CL_SUCCESS println(stderr, "Calling function $(string($func)) failed!") throw(CLBlastError(err)) end return err end @eval function trsm!(_side::Char, uplo::Char, transA::Char, diag::Char, α::Number, A::cl.CLArray{$elty,2}, B::cl.CLArray{$elty,2}; queue::cl.CmdQueue=cl.queue(B)) # check and convert arguments if _side == 'L' side = CLBlastSideLeft elseif _side == 'R' side = CLBlastSideRight else throw(ArgumentError("Side marker `side` is $(_side) but only 'L' and 'R' are allowed.")) end if uplo == 'U' triangle = CLBlastTriangleUpper elseif uplo == 'L' triangle = CLBlastTriangleLower else throw(ArgumentError("Upper/lower marker `uplo` is $(uplo) but only 'U' and 'L' are allowed.")) end if transA == 'N' a_transpose = CLBlastTransposeNo elseif transA == 'T' || (transA == 'C' && $elty <: Real) a_transpose = CLBlastTransposeYes elseif transA == 'C' && $elty <: Complex a_transpose = CLBlastTransposeConjugate else throw(ArgumentError("Transpose marker `transA` is $(transA) but only 'N', 'T', and 'C' are allowed.")) end if diag == 'N' diagonal = CLBlastDiagonalNonUnit elseif diag == 'U' diagonal = CLBlastDiagonalUnit else throw(ArgumentError("Diagonal marker `diag` is $(diag) but only 'N' and 'U' are allowed.")) end m, n = size(B) nA = size(A,1) if nA != size(A,2) throw(DimensionMismatch("`A` has dimensions $(size(A)) but must be square.")) end if nA != (_side == 'L' ? m : n) throw(DimensionMismatch("Size of A, $(size(A)), doesn't match $_side size of B with dims, $(size(B)).")) end alpha = convert($elty, α) layout = CLBlastLayoutColMajor # output event event::cl.Event = cl.Event(C_NULL) $func(layout, side, triangle, a_transpose, diagonal, m, n, alpha, pointer(A), 0, size(A,1), pointer(B), 0, size(B,1), queue, event) # wait for kernel # the additional check is due to https://github.com/CNugteren/CLBlast/issues/311 if event != cl.Event(C_NULL) cl.wait(event) end B end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
5485
@static if VERSION < v"0.7-" srand(12345) else Random.seed!(12345) end @testset "swap!" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L1) y_cl = cl.CLArray(queue, y) CLBlast.swap!(length(x_cl), x_cl, 1, y_cl, 1, queue=queue) @test cl.to_host(y_cl, queue=queue) ≈ x @test cl.to_host(x_cl, queue=queue) ≈ y end end @testset "scal!" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) y_cl = cl.CLArray(queue, x) α = rand(elty) CLBlast.scal!(length(x_cl), α, x_cl, 1, queue=queue) Compat.LinearAlgebra.BLAS.scal!(length(x), α, x, 1) @test cl.to_host(x_cl, queue=queue) ≈ x CLBlast.scal!(α, y_cl, queue=queue) @test cl.to_host(y_cl, queue=queue) ≈ x for α in (2, 2.f0, 2.0, 2+0im) CLBlast.scal!(length(x_cl), α, x_cl, 1, queue=queue) x .= α .* x @test cl.to_host(x_cl, queue=queue) ≈ x end end end @testset "copy!" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L1) y_cl = cl.CLArray(queue, y) CLBlast.copy!(length(x_cl), x_cl, 1, y_cl, 1, queue=queue) @test cl.to_host(y_cl, queue=queue) ≈ x @test cl.to_host(x_cl, queue=queue) ≈ x end end @testset "axpy!" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L1) y_cl = cl.CLArray(queue, y) α = rand(elty) CLBlast.axpy!(length(x_cl), α, x_cl, 1, y_cl, 1, queue=queue) y_true = α .* x .+ y @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y_true x_cl = cl.CLArray(queue, x) y_cl = cl.CLArray(queue, y) CLBlast.axpy!(α, x_cl, y_cl, queue=queue) @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y_true x_cl = cl.CLArray(queue, x[1:n_L1-1]) @test_throws DimensionMismatch CLBlast.axpy!(α, x_cl, y_cl, queue=queue) end end @testset "dot" begin for elty in eltypes elty <: Real || continue x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L1) y_cl = cl.CLArray(queue, y) @test Compat.LinearAlgebra.BLAS.dot(length(x), x, 1, y, 1) ≈ CLBlast.dot(length(x_cl), x_cl, 1, y_cl, 1, queue=queue) end end @testset "dotu" begin for elty in eltypes elty <: Complex || continue x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L1) y_cl = cl.CLArray(queue, y) @test Compat.LinearAlgebra.BLAS.dotu(length(x), x, 1, y, 1) ≈ CLBlast.dotu(length(x_cl), x_cl, 1, y_cl, 1, queue=queue) end end @testset "dotc" begin for elty in eltypes elty <: Complex || continue x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L1) y_cl = cl.CLArray(queue, y) @test Compat.LinearAlgebra.BLAS.dotc(length(x), x, 1, y, 1) ≈ CLBlast.dotc(length(x_cl), x_cl, 1, y_cl, 1, queue=queue) end end @testset "nrm2" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) @test Compat.LinearAlgebra.BLAS.nrm2(length(x), x, 1) ≈ CLBlast.nrm2(length(x_cl), x_cl, 1, queue=queue) end end @testset "asum" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) @test Compat.LinearAlgebra.BLAS.asum(length(x), x, 1) ≈ CLBlast.asum(length(x_cl), x_cl, 1, queue=queue) end end @testset "sum" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) sumx = sum(x) @test real(sumx)+imag(sumx) ≈ CLBlast.sum(length(x_cl), x_cl, 1, queue=queue) end end _internalnorm(z) = abs(real(z)) + abs(imag(z)) @testset "iamax" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) #NOTE: +1 due to zero based indexing in OpenCL vs. 1 based indexing in Julia idx_CLBlast = CLBlast.iamax(length(x_cl), x_cl, 1, queue=queue) + 1 idx_BLAS = Compat.LinearAlgebra.BLAS.iamax(length(x), x, 1) if elty <: Real @test _internalnorm(x[idx_BLAS]) ≈ _internalnorm(x[idx_CLBlast]) else @test_broken _internalnorm(x[idx_BLAS]) ≈ _internalnorm(x[idx_CLBlast]) end end end @testset "iamin" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) #NOTE: +1 due to zero based indexing in OpenCL vs. 1 based indexing in Julia idx_CLBlast = CLBlast.iamin(length(x_cl), x_cl, 1, queue=queue) + 1 @test_broken minimum(_internalnorm, x) ≈ _internalnorm(x[idx_CLBlast]) end end @testset "had!" begin for elty in eltypes x = rand(elty, n_L1) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L1) y_cl = cl.CLArray(queue, y) z = rand(elty, n_L1) z_cl = cl.CLArray(queue, z) α = rand(elty) β = rand(elty) CLBlast.had!(length(x_cl), α, x_cl, 1, y_cl, 1, β, z_cl, 1, queue=queue) z .= α .* x .* y .+ β .* z @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test cl.to_host(z_cl, queue=queue) ≈ z end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
12379
@static if VERSION < v"0.7-" srand(12345) else Random.seed!(12345) end @testset "gemv!" begin for elty in eltypes A = rand(elty, m_L2, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) α = rand(elty) β = rand(elty) @test_throws DimensionMismatch CLBlast.gemv!('T', α, A_cl, x_cl, β, y_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemv!('C', α, A_cl, x_cl, β, y_cl, queue=queue) CLBlast.gemv!('N', α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemv!('N', α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test_throws DimensionMismatch CLBlast.gemv!('N', α, A_cl, y_cl, β, x_cl, queue=queue) CLBlast.gemv!('T', α, A_cl, y_cl, β, x_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemv!('T', α, A, y, β, x) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test_throws DimensionMismatch CLBlast.gemv!('N', α, A_cl, y_cl, β, x_cl, queue=queue) CLBlast.gemv!('C', α, A_cl, y_cl, β, x_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemv!('C', α, A, y, β, x) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test_throws ArgumentError CLBlast.gemv!('A', α, A_cl, y_cl, β, x_cl, queue=queue) end end @testset "gbmv!" begin for elty in eltypes A = rand(elty, kl+ku+1, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) α = rand(elty) β = rand(elty) CLBlast.gbmv!('N', m_L2, kl, ku, α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.gbmv!('N', m_L2, kl, ku, α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y CLBlast.gbmv!('T', m_L2, kl, ku, α, A_cl, y_cl, β, x_cl, queue=queue) Compat.LinearAlgebra.BLAS.gbmv!('T', m_L2, kl, ku, α, A, y, β, x) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y CLBlast.gbmv!('C', m_L2, kl, ku, α, A_cl, y_cl, β, x_cl, queue=queue) Compat.LinearAlgebra.BLAS.gbmv!('C', m_L2, kl, ku, α, A, y, β, x) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test_throws ArgumentError CLBlast.gbmv!('A', m_L2, kl, ku, α, A_cl, y_cl, β, x_cl, queue=queue) end end @testset "hemv!" begin for elty in eltypes elty <: Complex || continue A = rand(elty, n_L2, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L2) y_cl = cl.CLArray(queue, y) α = rand(elty) β = rand(elty) CLBlast.hemv!('U', α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.hemv!('U', α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y CLBlast.hemv!('L', α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.hemv!('L', α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test_throws ArgumentError CLBlast.hemv!('A', α, A_cl, y_cl, β, x_cl, queue=queue) y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) @test_throws DimensionMismatch CLBlast.hemv!('U', α, A_cl, x_cl, β, y_cl, queue=queue) @test_throws DimensionMismatch CLBlast.hemv!('U', α, A_cl, y_cl, β, x_cl, queue=queue) end end @testset "hbmv!" begin for elty in eltypes elty <: Complex || continue A = rand(elty, ku+1, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L2) y_cl = cl.CLArray(queue, y) α = rand(elty) β = rand(elty) CLBlast.hbmv!('U', ku, α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.hbmv!('U', ku, α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y CLBlast.hbmv!('L', ku, α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.hbmv!('L', ku, α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test_throws ArgumentError CLBlast.hbmv!('A', ku, α, A_cl, x_cl, β, y_cl, queue=queue) y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) @test_throws DimensionMismatch CLBlast.hbmv!('U', ku, α, A_cl, x_cl, β, y_cl, queue=queue) @test_throws DimensionMismatch CLBlast.hbmv!('U', ku, α, A_cl, y_cl, β, x_cl, queue=queue) end end @testset "symv!" begin for elty in eltypes elty <: Real || continue A = rand(elty, n_L2, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L2) y_cl = cl.CLArray(queue, y) α = rand(elty) β = rand(elty) CLBlast.symv!('U', α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.symv!('U', α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y CLBlast.symv!('L', α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.symv!('L', α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test_throws ArgumentError CLBlast.symv!('A', α, A_cl, y_cl, β, x_cl, queue=queue) y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) @test_throws DimensionMismatch CLBlast.symv!('U', α, A_cl, x_cl, β, y_cl, queue=queue) @test_throws DimensionMismatch CLBlast.symv!('U', α, A_cl, y_cl, β, x_cl, queue=queue) end end @testset "sbmv!" begin for elty in eltypes elty <: Real || continue A = rand(elty, ku+1, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L2) y_cl = cl.CLArray(queue, y) α = rand(elty) β = rand(elty) CLBlast.sbmv!('U', ku, α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.sbmv!('U', ku, α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y CLBlast.sbmv!('L', ku, α, A_cl, x_cl, β, y_cl, queue=queue) Compat.LinearAlgebra.BLAS.sbmv!('L', ku, α, A, x, β, y) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test_throws ArgumentError CLBlast.sbmv!('A', ku, α, A_cl, x_cl, β, y_cl, queue=queue) y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) @test_throws DimensionMismatch CLBlast.sbmv!('U', ku, α, A_cl, x_cl, β, y_cl, queue=queue) @test_throws DimensionMismatch CLBlast.sbmv!('U', ku, α, A_cl, y_cl, β, x_cl, queue=queue) end end @testset "trmv!" begin for elty in eltypes A = rand(elty, n_L2, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) for uplo in ['U','L'], trans in ['N','T','C'], diag in ['N','U'] CLBlast.trmv!(uplo, trans, diag, A_cl, x_cl, queue=queue) Compat.LinearAlgebra.BLAS.trmv!(uplo, trans, diag, A, x) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x end @test_throws ArgumentError CLBlast.trmv!('A', 'N', 'N', A_cl, x_cl, queue=queue) @test_throws ArgumentError CLBlast.trmv!('U', 'A', 'N', A_cl, x_cl, queue=queue) @test_throws ArgumentError CLBlast.trmv!('U', 'N', 'A', A_cl, x_cl, queue=queue) y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) @test_throws DimensionMismatch CLBlast.trmv!('U', 'N', 'N', A_cl, y_cl, queue=queue) A = rand(elty, m_L2, n_L2) A_cl = cl.CLArray(queue, A) @test_throws DimensionMismatch CLBlast.trmv!('U', 'N', 'N', A_cl, x_cl, queue=queue) end end @testset "trsv!" begin for elty in eltypes A = rand(elty, n_L2, n_L2) for i in 1:n_L2 A[i,i] = i end A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) for uplo in ['U','L'], trans in ['N','T','C'], diag in ['N','U'] CLBlast.trsv!(uplo, trans, diag, A_cl, x_cl, queue=queue) Compat.LinearAlgebra.BLAS.trsv!(uplo, trans, diag, A, x) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x end @test_throws ArgumentError CLBlast.trsv!('A', 'N', 'N', A_cl, x_cl, queue=queue) @test_throws ArgumentError CLBlast.trsv!('U', 'A', 'N', A_cl, x_cl, queue=queue) @test_throws ArgumentError CLBlast.trsv!('U', 'N', 'A', A_cl, x_cl, queue=queue) y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) @test_throws DimensionMismatch CLBlast.trsv!('U', 'N', 'N', A_cl, y_cl, queue=queue) A = rand(elty, m_L2, n_L2) A_cl = cl.CLArray(queue, A) @test_throws DimensionMismatch CLBlast.trsv!('U', 'N', 'N', A_cl, x_cl, queue=queue) end end @testset "ger!" begin for elty in eltypes A = rand(elty, m_L2, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, m_L2) x_cl = cl.CLArray(queue, x) y = rand(elty, n_L2) y_cl = cl.CLArray(queue, y) α = rand(elty) CLBlast.ger!(α, x_cl, y_cl, A_cl, queue=queue) Compat.LinearAlgebra.BLAS.ger!(α, x, y, A) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x @test cl.to_host(y_cl, queue=queue) ≈ y @test_throws DimensionMismatch CLBlast.ger!(α, x_cl, x_cl, A_cl, queue=queue) @test_throws DimensionMismatch CLBlast.ger!(α, y_cl, y_cl, A_cl, queue=queue) @test_throws DimensionMismatch CLBlast.ger!(α, y_cl, x_cl, A_cl, queue=queue) end end @testset "her!" begin for elty in eltypes elty <: Complex || continue A = rand(elty, n_L2, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) α = real(rand(elty)) for uplo in ['U', 'L'] CLBlast.her!(uplo, α, x_cl, A_cl, queue=queue) Compat.LinearAlgebra.BLAS.her!(uplo, α, x, A) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x end y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) @test_throws DimensionMismatch CLBlast.her!('U', α, y_cl, A_cl, queue=queue) end end @testset "syr!" begin for elty in eltypes elty <: Real || continue A = rand(elty, n_L2, n_L2) A_cl = cl.CLArray(queue, A) x = rand(elty, n_L2) x_cl = cl.CLArray(queue, x) α = real(rand(elty)) for uplo in ['U', 'L'] CLBlast.syr!(uplo, α, x_cl, A_cl, queue=queue) Compat.LinearAlgebra.BLAS.syr!(uplo, α, x, A) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(x_cl, queue=queue) ≈ x end y = rand(elty, m_L2) y_cl = cl.CLArray(queue, y) @test_throws DimensionMismatch CLBlast.syr!('U', α, y_cl, A_cl, queue=queue) end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
20384
@static if VERSION < v"0.7-" srand(12345) else Random.seed!(12345) end @testset "gemm!" begin for elty in eltypes # A_mul_B! A = rand(elty, m_L3, k_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, k_L3, n_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, m_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) CLBlast.gemm!('N', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemm!('N', 'N', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.gemm!('T', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('C', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('N', 'T', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('N', 'C', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws ArgumentError CLBlast.gemm!('A', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws ArgumentError CLBlast.gemm!('N', 'A', α, A_cl, B_cl, β, C_cl, queue=queue) # At_mul_B!, Ac_mul_B! A = rand(elty, k_L3, m_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, k_L3, n_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, m_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) CLBlast.gemm!('T', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemm!('T', 'N', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C CLBlast.gemm!('C', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemm!('C', 'N', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.gemm!('N', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('N', 'T', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('N', 'C', α, A_cl, B_cl, β, C_cl, queue=queue) # A_mul_Bt!, A_mul_Bc! A = rand(elty, m_L3, k_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, n_L3, k_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, m_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) CLBlast.gemm!('N', 'T', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemm!('N', 'T', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C CLBlast.gemm!('N', 'C', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemm!('N', 'C', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.gemm!('N', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('T', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('C', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) # At_mul_Bt!, Ac_mul_Bt!, At_mul_Bt!, Ac_mul_Bc! A = rand(elty, k_L3, m_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, n_L3, k_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, m_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) CLBlast.gemm!('T', 'T', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemm!('T', 'T', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C CLBlast.gemm!('C', 'T', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemm!('C', 'T', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C CLBlast.gemm!('T', 'C', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemm!('T', 'C', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C CLBlast.gemm!('C', 'C', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.gemm!('C', 'C', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.gemm!('N', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('T', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('C', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('N', 'T', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.gemm!('N', 'C', α, A_cl, B_cl, β, C_cl, queue=queue) end end @testset "symm!" begin for elty in eltypes # multiply from the left A = rand(elty, m_L3, m_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, m_L3, n_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, m_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) for uplo in ['U','L'] CLBlast.symm!('L', uplo, α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.symm!('L', uplo, α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.symm!('L', uplo, α, B_cl, A_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.symm!('R', uplo, α, A_cl, B_cl, β, C_cl, queue=queue) end @test_throws ArgumentError CLBlast.symm!('A', 'U', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws ArgumentError CLBlast.symm!('U', 'A', α, A_cl, B_cl, β, C_cl, queue=queue) # multiply from the right A = rand(elty, n_L3, n_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, m_L3, n_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, m_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) for uplo in ['U','L'] CLBlast.symm!('R', uplo, α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.symm!('R', uplo, α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.symm!('L', uplo, α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.symm!('R', uplo, α, B_cl, A_cl, β, C_cl, queue=queue) end end end @testset "hemm!" begin for elty in eltypes elty <: Complex || continue # multiply from the left A = rand(elty, m_L3, m_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, m_L3, n_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, m_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) for uplo in ['U','L'] CLBlast.hemm!('L', uplo, α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.hemm!('L', uplo, α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.hemm!('L', uplo, α, B_cl, A_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.hemm!('R', uplo, α, A_cl, B_cl, β, C_cl, queue=queue) end @test_throws ArgumentError CLBlast.hemm!('A', 'U', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws ArgumentError CLBlast.hemm!('U', 'A', α, A_cl, B_cl, β, C_cl, queue=queue) # multiply from the right A = rand(elty, n_L3, n_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, m_L3, n_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, m_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) for uplo in ['U','L'] CLBlast.hemm!('R', uplo, α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.hemm!('R', uplo, α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.hemm!('L', uplo, α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws DimensionMismatch CLBlast.hemm!('R', uplo, α, B_cl, A_cl, β, C_cl, queue=queue) end end end @testset "syrk!" begin for elty in eltypes # A*A' A = rand(elty, n_L3, k_L3) A_cl = cl.CLArray(queue, A) C = rand(elty, n_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) for uplo in ['U','L'] CLBlast.syrk!(uplo, 'N', α, A_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.syrk!(uplo, 'N', α, A, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.syrk!(uplo, 'T', α, A_cl, β, C_cl, queue=queue) end @test_throws ArgumentError CLBlast.syrk!('A', 'N', α, A_cl, β, C_cl, queue=queue) @test_throws ArgumentError CLBlast.syrk!('U', 'A', α, A_cl, β, C_cl, queue=queue) # A'*A A = rand(elty, k_L3, n_L3) A_cl = cl.CLArray(queue, A) C = rand(elty, n_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) for uplo in ['U','L'] CLBlast.syrk!(uplo, 'T', α, A_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.syrk!(uplo, 'T', α, A, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.syrk!(uplo, 'N', α, A_cl, β, C_cl, queue=queue) end @test_throws ArgumentError CLBlast.syrk!('U', 'C', α, A_cl, β, C_cl, queue=queue) end end @testset "herk!" begin for elty in eltypes elty <: Complex || continue # A*A' A = rand(elty, n_L3, k_L3) A_cl = cl.CLArray(queue, A) C = rand(elty, n_L3, n_L3) for i in 1:n_L3 C[i,i] = real(C[i,i]) end C_cl = cl.CLArray(queue, C) α = real(rand(elty)) β = real(rand(elty)) for uplo in ['U','L'] CLBlast.herk!(uplo, 'N', α, A_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.herk!(uplo, 'N', α, A, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test_skip cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.herk!(uplo, 'C', α, A_cl, β, C_cl, queue=queue) end @test_throws ArgumentError CLBlast.herk!('A', 'N', α, A_cl, β, C_cl, queue=queue) @test_throws ArgumentError CLBlast.herk!('U', 'A', α, A_cl, β, C_cl, queue=queue) # A'*A A = rand(elty, k_L3, n_L3) A_cl = cl.CLArray(queue, A) C = rand(elty, n_L3, n_L3) for i in 1:n_L3 C[i,i] = real(C[i,i]) end C_cl = cl.CLArray(queue, C) α = real(rand(elty)) β = real(rand(elty)) for uplo in ['U','L'] CLBlast.herk!(uplo, 'C', α, A_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.herk!(uplo, 'C', α, A, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test_skip cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.herk!(uplo, 'N', α, A_cl, β, C_cl, queue=queue) end @test_throws ArgumentError CLBlast.herk!('U', 'T', α, A_cl, β, C_cl, queue=queue) end end @testset "syr2k!" begin for elty in eltypes # A*B' A = rand(elty, n_L3, k_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, n_L3, k_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, n_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) for uplo in ['U','L'] CLBlast.syr2k!(uplo, 'N', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.syr2k!(uplo, 'N', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.syr2k!(uplo, 'T', α, A_cl, B_cl, β, C_cl, queue=queue) end @test_throws ArgumentError CLBlast.syr2k!('A', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws ArgumentError CLBlast.syr2k!('U', 'A', α, A_cl, B_cl, β, C_cl, queue=queue) # A'*B A = rand(elty, k_L3, n_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, k_L3, n_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, n_L3, n_L3) C_cl = cl.CLArray(queue, C) α = rand(elty) β = rand(elty) for uplo in ['U','L'] CLBlast.syr2k!(uplo, 'T', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.syr2k!(uplo, 'T', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.syr2k!(uplo, 'N', α, A_cl, B_cl, β, C_cl, queue=queue) end end end @testset "her2k!" begin for elty in eltypes elty <: Complex || continue # A*B' A = rand(elty, n_L3, k_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, n_L3, k_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, n_L3, n_L3) C_cl = cl.CLArray(queue, C) for i in 1:n_L3 C[i,i] = real(C[i,i]) end α = rand(elty) β = real(rand(elty)) for uplo in ['U','L'] CLBlast.her2k!(uplo, 'N', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.her2k!(uplo, 'N', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test_skip cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.her2k!(uplo, 'C', α, A_cl, B_cl, β, C_cl, queue=queue) end @test_throws ArgumentError CLBlast.her2k!('A', 'N', α, A_cl, B_cl, β, C_cl, queue=queue) @test_throws ArgumentError CLBlast.her2k!('U', 'A', α, A_cl, B_cl, β, C_cl, queue=queue) # A'*B A = rand(elty, k_L3, n_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, k_L3, n_L3) B_cl = cl.CLArray(queue, B) C = rand(elty, n_L3, n_L3) for i in 1:n_L3 C[i,i] = real(C[i,i]) end C_cl = cl.CLArray(queue, C) α = rand(elty) β = real(rand(elty)) for uplo in ['U','L'] CLBlast.her2k!(uplo, 'C', α, A_cl, B_cl, β, C_cl, queue=queue) Compat.LinearAlgebra.BLAS.her2k!(uplo, 'C', α, A, B, β, C) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test_skip cl.to_host(C_cl, queue=queue) ≈ C @test_throws DimensionMismatch CLBlast.her2k!(uplo, 'N', α, A_cl, B_cl, β, C_cl, queue=queue) end @test_throws ArgumentError CLBlast.her2k!('U', 'T', α, A_cl, B_cl, β, C_cl, queue=queue) end end @testset "trmm!" begin for elty in eltypes # multiply from the left A = rand(elty, m_L3, m_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, m_L3, n_L3) B_cl = cl.CLArray(queue, B) α = rand(elty) for uplo in ['U','L'], transA in ['N','T','C'], diag in ['N','U'] CLBlast.trmm!('L', uplo, transA, diag, α, A_cl, B_cl, queue=queue) Compat.LinearAlgebra.BLAS.trmm!('L', uplo, transA, diag, α, A, B) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test_throws DimensionMismatch CLBlast.trmm!('L', uplo, transA, diag, α, B_cl, A_cl, queue=queue) @test_throws DimensionMismatch CLBlast.trmm!('R', uplo, transA, diag, α, A_cl, B_cl, queue=queue) end @test_throws ArgumentError CLBlast.trmm!('A', 'U', 'N', 'N', α, A_cl, B_cl, queue=queue) @test_throws ArgumentError CLBlast.trmm!('U', 'A', 'N', 'N', α, A_cl, B_cl, queue=queue) # multiply from the right A = rand(elty, n_L3, n_L3) A_cl = cl.CLArray(queue, A) B = rand(elty, m_L3, n_L3) B_cl = cl.CLArray(queue, B) α = rand(elty) β = rand(elty) for uplo in ['U','L'], transA in ['N','T','C'], diag in ['N','U'] CLBlast.trmm!('R', uplo, transA, diag, α, A_cl, B_cl, queue=queue) Compat.LinearAlgebra.BLAS.trmm!('R', uplo, transA, diag, α, A, B) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test_throws DimensionMismatch CLBlast.trmm!('L', uplo, transA, diag, α, A_cl, B_cl, queue=queue) @test_throws DimensionMismatch CLBlast.trmm!('R', uplo, transA, diag, α, B_cl, A_cl, queue=queue) end end end @testset "trsm!" begin for elty in eltypes # On Travis, there is some strange error # https://travis-ci.org/JuliaGPU/CLBlast.jl/jobs/414395954#L347 @static if VERSION < v"0.7-" is_apple() && break else Sys.isapple() && break end # multiply from the left A = rand(elty, m_L3, m_L3) for i in 1:m_L3 A[i,i] = i end A_cl = cl.CLArray(queue, A) B = rand(elty, m_L3, n_L3) B_cl = cl.CLArray(queue, B) α = rand(elty) for uplo in ['U','L'], transA in ['N','T','C'], diag in ['N','U'] CLBlast.trsm!('L', uplo, transA, diag, α, A_cl, B_cl, queue=queue) Compat.LinearAlgebra.BLAS.trsm!('L', uplo, transA, diag, α, A, B) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test_throws DimensionMismatch CLBlast.trsm!('L', uplo, transA, diag, α, B_cl, A_cl, queue=queue) @test_throws DimensionMismatch CLBlast.trsm!('R', uplo, transA, diag, α, A_cl, B_cl, queue=queue) end @test_throws ArgumentError CLBlast.trsm!('A', 'U', 'N', 'N', α, A_cl, B_cl, queue=queue) @test_throws ArgumentError CLBlast.trsm!('U', 'A', 'N', 'N', α, A_cl, B_cl, queue=queue) # multiply from the right A = rand(elty, n_L3, n_L3) for i in 1:n_L3 A[i,i] = i end A_cl = cl.CLArray(queue, A) B = rand(elty, m_L3, n_L3) B_cl = cl.CLArray(queue, B) α = rand(elty) β = rand(elty) for uplo in ['U','L'], transA in ['N','T','C'], diag in ['N','U'] CLBlast.trsm!('R', uplo, transA, diag, α, A_cl, B_cl, queue=queue) Compat.LinearAlgebra.BLAS.trsm!('R', uplo, transA, diag, α, A, B) @test cl.to_host(A_cl, queue=queue) ≈ A @test cl.to_host(B_cl, queue=queue) ≈ B @test_throws DimensionMismatch CLBlast.trsm!('L', uplo, transA, diag, α, A_cl, B_cl, queue=queue) @test_throws DimensionMismatch CLBlast.trsm!('R', uplo, transA, diag, α, B_cl, A_cl, queue=queue) end end end
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
171
@compat for error_code in keys(CLBlast._clblast_status_codes) println(devnull, CLBlast.CLBlastError(error_code)) end CLBlast.clear_cache() CLBlast.fill_cache(device)
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
code
604
module TestCLBlast using Compat using Compat.Test using Compat.Random using CLBlast, OpenCL const n_L1 = 64 const m_L2 = 60 const n_L2 = 50 const kl = 2 const ku = 3 const m_L3 = 6 const n_L3 = 5 const k_L3 = 4 @compat const eltypes = (Float32, Float64, ComplexF32, ComplexF64) device, ctx, queue = cl.create_compute_context() @time @testset "BLAS Level 1" begin include("L1_test.jl") end @time @testset "BLAS Level 2" begin include("L2_test.jl") end @time @testset "BLAS Level 3" begin include("L3_test.jl") end @time @testset "Auxiliary Tests" begin include("auxiliary_test.jl") end end # module
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.2.0
48e5cfba99403037e35a4ca9eb6c56aaea9c8a12
docs
2131
# CLBlast [![Build Status](https://gitlab.com/JuliaGPU/CLArrays.jl/badges/master/pipeline.svg)](https://gitlab.com/JuliaGPU/CLArrays.jl/pipelines) [![Build Status](https://travis-ci.org/JuliaGPU/CLBlast.jl.svg?branch=master)](https://travis-ci.org/JuliaGPU/CLBlast.jl) [![Build status](https://ci.appveyor.com/api/projects/status/i1saoodeqrepiodl?svg=true)](https://ci.appveyor.com/project/ranocha/CLBlast-jl) [![Coverage Status](https://coveralls.io/repos/github/JuliaGPU/CLBlast.jl/badge.svg?branch=master)](https://coveralls.io/github/JuliaGPU/CLBlast.jl?branch=master) [![codecov.io](http://codecov.io/github/JuliaGPU/CLBlast.jl/coverage.svg?branch=master)](http://codecov.io/github/JuliaGPU/CLBlast.jl?branch=master) Wrapper of [CLBlast](https://github.com/CNugteren/CLBlast), a "tuned OpenCL BLAS library". This package has been inspired by [CLBLAS.jl](https://github.com/JuliaGPU/CLBLAS.jl) and the BLAS module of [Julia](https://github.com/JuliaLang/julia) and is designed similarly. ## Current Status Most low-level bindings and high-level wrappers of BLAS level 1, 2, and 3 routines are implemented. ## Example ```julia using CLBlast, OpenCL @static if VERSION < v"0.7-" LA = LinAlg else using Random, LinearAlgebra LA = LinearAlgebra end device, context, queue = cl.create_compute_context() # setup data α = 1.f0 β = 1.f0 A = rand(Float32, 10, 8) B = rand(Float32, 8, 6) C = zeros(Float32, 10, 6) # transfer data A_cl = cl.CLArray(queue, A) B_cl = cl.CLArray(queue, B) C_cl = cl.CLArray(queue, C) # compute LA.BLAS.gemm!('N', 'N', α, A, B, β, C) CLBlast.gemm!('N', 'N', α, A_cl, B_cl, β, C_cl) # compare results @assert cl.to_host(C_cl) ≈ C ``` ## Installation Since this package is registered, you can add it using `]` (activate package mode) and ```julia (v0.7) pkg> add CLBlast ``` on Julia `v0.7` or newer and using ```julia julia> Pkg.add("CLBlast") ``` on Julia `v0.6`. During the build process, a suitable version of CLBlast will be downloaded and build. On Linux, you have to install `clang`, since the available binaries of CLBlast will fail to work with complex numbers from Julia.
CLBlast
https://github.com/JuliaGPU/CLBlast.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
661
push!(LOAD_PATH,"../src/") using Firebase using Documenter DocMeta.setdocmeta!(Firebase, :DocTestSetup, :(using Firebase); recursive=true) makedocs(; modules=[Firebase], authors="Ashwani Rathee", repo="github.com/ashwani-rathee/Firebase.jl/blob/{commit}{path}#{line}", sitename="Firebase.jl", format=Documenter.HTML(; prettyurls=Base.get(ENV, "CI", "false") == "true", canonical="https://ashwani-rathee.github.io/Firebase.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/ashwani-rathee/Firebase.jl", devbranch="main", push_preview = true )
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
1644
module Firebase # Includes include("firestore.jl") include("firestore-token.jl") include("firebaseauth.jl") include("convert.jl") include("cloudstorage.jl") include("realtime.jl") # include("auth.jl") # Imported packages using HTTP, GoogleCloud, JSON # Exported Functions export get export get_collection, get_singlepage,get_document, get_request export convert_to_dict export convert_field export convert_timestamp export convert_map export convert_array # Firebase authentication related export set_webapikey export firebase_signup export firebase_signin export firebase_signinanon export firebase_signinoauth export firebase_fetchproviders export firebase_passwordreset export verify_passwordresetcode export confirm_passwordreset export firebase_changeemail export firebase_changepassword export firebase_updateprofile export firebase_getuserinfo export firebase_linkuserinfo export firebase_unlinkprovide export firebase_verifyemail export firebase_confirmemailverify export firebase_deleteuser # Firebase database related export init export projectid export get_token export auth_header export firestore_batchget export firestore_batchwrite export firestore_beginTransaction export firestore_createdoc export firestore_commit export firestore_deletedoc export firestore_getcollectionids export firestore_getdoclist export firestore_partitionquery export firestore_patch export firestore_rollback export firestore_runquery # Realtime database related export realdb_init export realdb_get export realdb_post export realdb_delete export realdb_put export realdb_patch # cloud Storage Functions export cloudstore_sendfile end # module
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
1356
STORE_URL = nothing function cloudstore_init() global STORE_URL = url println("Cloud Storage set:", STORE_URL) end """ """ function cloudstore_sendfile(file2upload="test/onedance.mp3") file_binary = open(file2upload, "r") s = read(file_binary, String) header = Dict("Content-Type" => "audio/mp3", auth_header()) project_id = projectid() final_url = "https://firebasestorage.googleapis.com/v0/b/fir-jl-457eb.appspot.com/o/audio%2Fdata.mp3" final_url = "https://firebasestorage.googleapis.com/v0/b/fir-jl-457eb.appspot.com/o/data.mp3" # body = JSON.json(s) # println("Body:", body) body = s println("FINAL_URL:", final_url) http_response = HTTP.post( final_url, header, body ) response_string = String(http_response.body) JSON.parse(response_string) end function cloudstorage_get() # res = HTTP.get("https://firebasestorage.googleapis.com/v0/b/fir-jl-457eb.appspot.com/o/242160__xserra__cello-phrase.wav?alt=media&token=878c7715-61cf-46b5-a9c0-a790300d8c43") # julia> out =open("data.mp3","w") # IOStream(<file data.mp3>) # julia> write(out,res.body) # 748202 # julia> close(abc) # ERROR: UndefVarError: abc not defined # Stacktrace: # [1] top-level scope # @ REPL[18]:1 # julia> close(out) end
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
1247
using Dates doc_id(doc) = split(doc["name"], '/')[end] function convert_to_dict(documents) y = Dict{String,Dict{String,Any}}() for doc in documents id = doc_id(doc) y[id] = doc["fields"] end y end function convert_field(x) y_type = collect(keys(x))[1] y = x[y_type] y_type == "nullValue" && return nothing y_type == "booleanValue" && return y y_type == "integerValue" && return parse(Int, y) y_type == "doubleValue" && return y y_type == "timestampValue" && return convert_timestamp(y) y_type == "stringValue" && return y y_type == "arrayValue" && return convert_array(y) y_type == "mapValue" && return convert_map(y) end function convert_timestamp(x) ix = findlast('.', x) isnothing(ix) && (ix = findlast('Z', x)) y = isnothing(ix) ? x : x[1:ix - 1] DateTime(y, dateformat"yyyy-mm-ddTHH:MM:SS") end function convert_array(x) isempty(x) && return [] y = [] for e in x["values"] push!(y, convert_field(e)) end y end function convert_map(x) y = Dict{String,Any}() haskey(x, "name") && (y["__id__"] = doc_id(x)) isempty(x) && return y for (k, v) in x["fields"] y[k] = convert_field(v) end y end
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
17181
# using HTTP,JSON,Firebase # # Firebase Auth backend a REST API # Firebase.init("test/fir-jl-457eb-firebase-adminsdk-40928-0efd6a89e7.json"); # header = Dict( # "Authorization" => # "Bearer ya29.c.Kp8BAwh19dsnHN7yPkhlb3toQleIQuAQ94YlV-aXs6ijDEvEKtvKmoNiXw9Fg7u-EjpHjusuu_k9nIaW7tFohhW97fPTx7G0KowT-R0nwI52XdvHrG-TrRAZOjC38eiu_eaPgXTh2wxHUDH-sVPpvA5Yzv8DgCoCRTUboxa3ajDVhRiyvM7uOiFcR27k6eoMrOmk_EBTabpODRLhtIeKG10O", # ); # body = """ # { # email: "[email protected]", # password: "helloworld!!", # returnSecureToken: true # } # """ # HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyAEeSloxz3EtXTm73EdSIWY_WRVPF51hhI",header,body) using HTTP,JSON WEB_API_KEY = nothing """ set_webapikey(key ="") sets WEB_API_KEY # Example ```julia set_webapikey("asjdlajsj1j32lj312") ``` """ function set_webapikey(key="AIzaSyAEeSloxz3EtXTm73EdSIWY_WRVPF51hhI") global WEB_API_KEY = key println("WEB_API_KEY set: ", WEB_API_KEY) end """ firebase_signup(email::String="", password::String="", returnSecureToken::Bool= true) Sign up with email / password You can create a new email and password user by issuing an HTTP POST request to the Auth signupNewUser endpoint. # Example ```julia set_webapikey("WEB_API_KEY") firebase_signup("[email protected]","hello!!") #= Dict{String, Any} with 6 entries: "refreshToken" => "AGEhc0AjgXJevwy_rkJ3r4VUHc4EEORngVF-rwEtOuO007AymRqbAzVnn1iAMCZNHqzwnCI1X8fkJ0OPE2fTuGN7ameU6P7SmibwIFs8sOZxUI8C_uklOkk1IG5DFdWXAC45mK_0Hy4tuJXJUvI8Kuy6LS-GERZ5Bc… "kind" => "identitytoolkit#SignupNewUserResponse" "localId" => "GRCBj28Pkhat0mYsJS0BVrlVmJd2" "expiresIn" => "3600" "idToken" => "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRjNGQwMGJjM2NiZWE4YjU0NTMzMWQxZjFjOTZmZDRlNjdjNTFlODkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vZmlyLWp… "email" => "[email protected]" =# ``` """ function firebase_signup(email::String="", password::String="", returnSecureToken::Bool=true) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"email": "$email","password":"$password","returnSecureToken":"$returnSecureToken"}""") response_string = String(http_response.body) JSON.parse(response_string) end """ firebase_signin(email::String="data", password::String="data", returnSecureToken::Bool= true) Sign in with email / password You can sign in a user with an email and password by issuing an HTTP POST request to the Auth verifyPassword endpoint. # Example ```julia firebase_signin("[email protected]" , "hello1231!!") #= Dict{String, Any} with 8 entries: "refreshToken" => "AGEhc0C1F9smilhBPdT5TYClumCwdzGI9q43s5r-MsqW-bJTeiIw1doG7zRF_VMX2a0WELR3zRB… "kind" => "identitytoolkit#VerifyPasswordResponse" "localId" => "zgrI4g3ualVJW7IEiRlPFg5jItA2" "displayName" => "" "idToken" => "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRjNGQwMGJjM2NiZWE4YjU0NTMzMWQxZjFjOTZmZDRlNjd… "registered" => true "expiresIn" => "3600" "email" => "[email protected]" =# ``` """ function firebase_signin(email::String="", password::String="", returnSecureToken::Bool=true) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"email": "$email","password":"$password","returnSecureToken":"$returnSecureToken"}""") response_string = String(http_response.body) JSON.parse(response_string) end """ firebase_signinanon(returnSecureToken::Bool= true) Sign in anonymously You can sign in a user anonymously by issuing an HTTP POST request to the Auth signupNewUser endpoint. # Exampleemail::String="", password::String="", ```julia julia> firebase_signinanon() #= Dict{String, Any} with 5 entries: "refreshToken" => "AGEhc0DiE1zelLdCW2KG9wMRwZKcZI6EuSef4hsIc6uOZp0I3SYUTf0Hib_XgvtgY1yeqgFNqJ0… "kind" => "identitytoolkit#SignupNewUserResponse" "localId" => "3T8r7DD99zO9qKL1k56boC2iiXF2" "expiresIn" => "3600" "idToken" => "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRjNGQwMGJjM2NiZWE4YjU0NTMzMWQxZjFjOTZmZDRlNjd… =# ``` """ function firebase_signinanon(returnSecureToken::Bool=true) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"returnSecureToken":"$returnSecureToken"}""") response_string = String(http_response.body) JSON.parse(response_string) end GOOGLE_ID_TOKEN = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRjNGQwMGJjM2NiZWE4YjU0NTMzMWQxZjFjOTZmZDRlNjdjNTFlODkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vZmlyLWpsLTQ1N2ViIiwiYXVkIjoiZmlyLWpsLTQ1N2ViIiwiYXV0aF90aW1lIjoxNjIzOTQwMzIwLCJ1c2VyX2lkIjoiemdySTRnM3VhbFZKVzdJRWlSbFBGZzVqSXRBMiIsInN1YiI6Inpnckk0ZzN1YWxWSlc3SUVpUmxQRmc1akl0QTIiLCJpYXQiOjE2MjM5NDAzMjAsImV4cCI6MTYyMzk0MzkyMCwiZW1haWwiOiJhc2h3YW5pMUBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsiYXNod2FuaTFAZ21haWwuY29tIl19LCJzaWduX2luX3Byb3ZpZGVyIjoicGFzc3dvcmQifX0.uDT2BFPXlJWXzartwx8t8iBwriZc3PTpwJ3_5biOTI8H9sHU4w46E-XwUvW45Qip0_2Cmf6JZjbfkAZhGHnzIl6b9C3j2iJ0nXY_tvr0cC8otGPp01J8vBSZCu24tI0BdPaymXrFek4ouGmnbFCdxO2D3eeB59ZVsJCm9JWzGjSlrO5m0KMIOhYAV5aq6BaT32AzkPZJDXWTjc3nEXrxF-5n8Nehek_QbxROh7pwJHqDul5xswlDYGqHAx3d2jrcrSehGhfetHfPx9IYOPttAT0mSeROz3Lgy9cLmfO5HvAZMNoJs0gif7ffr773TJMkbELEc-gyBFETnoY87LPvuA" """ firebase_signinoauth() Sign in with OAuth credential You can sign in a user with an OAuth credential by issuing an HTTP POST request to the Auth verifyAssertion endpoint. This doesn't work today # Example ```julia"oobCode":"[VERIFICATION_CODE]" firebase_signinoauth() ``` """ function firebase_signinoauth() http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"postBody":"{id_token=$GOOGLE_ID_TOKEN&providerId=[google.com]","requestUri":"http://localhost","returnIdpCredential":true,"returnSecureToken":true}""") response_string = String(http_response.body) JSON.parse(response_string) end """ firebase_fetchproviders(email="") Fetch providers for email You can look all providers associated with a specified email by issuing an HTTP POST request to the Auth createAuthUri endpoint. # Example ```julia julia> firebase_fetchproviders("[email protected]") #= Dict{String, Any} with 5 entries: "allProviders" => Any["password"] "kind" => "identitytoolkit#CreateAuthUriResponse" "sessionId" => "k8iBdCSLEeAbhhgKz6E4PC-ltCs" "signinMethods" => Any["password"] "registered" => true =# ``` """ function firebase_fetchproviders(email="[email protected]") http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:createAuthUri?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"identifier":"$email","continueUri":"http://localhost:8080/app"}""") response_string = String(http_response.body) JSON.parse(response_string) end """ firebase_passwordreset(email="[email protected]") Send password reset email You can send a password reset email by issuing an HTTP POST request to the Auth getOobConfirmationCode endpoint. # Example ```julia firebase_passwordreset(email="[email protected]") # email will recieve the reset password email ``` """ function firebase_passwordreset(email="[email protected]") http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"requestType":"PASSWORD_RESET","email":"$email"}""") response_string = String(http_response.body) JSON.parse(response_string) end """ verify_passwordresetcode() Verify password reset code You can verify a password reset code by issuing an HTTP POST request to the Auth resetPassword endpoint. # Example ```julia ``` """ function verify_passwordresetcode() http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:resetPassword?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"oobCode":"[PASSWORD_RESET_CODE]"}""") response_string = String(http_response.body) JSON.parse(response_string) end """ """ function confirm_passwordreset() http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:resetPassword?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"oobCode":"[PASSWORD_RESET_CODE]","newPassword":"[NEW_PASSWORD]"}""") response_string = String(http_response.body) JSON.parse(response_string) end FIREBASE_ID_TOKEN = nothing """ firebase_changeemail(newemail="",firebase_id_token= FIREBASE_ID_TOKEN) Change email You can change a user's email by issuing an HTTP POST request to the Auth setAccountInfo endpoint. # Example ```julia data = firebase_signin("[email protected],"helloworld!!") firebase_changeemail("[email protected]",data["idToken"]) data = firebase_signin("[email protected],"helloworld!!") firebase_changeemail("[email protected]",data["idToken"]) ```` """ function firebase_changeemail(newemail="", firebase_id_token=FIREBASE_ID_TOKEN) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:update?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"idToken":"$firebase_id_token","email":"$newemail","returnSecureToken":true}""") response_string = String(http_response.body) JSON.parse(response_string) end """ firebase_changepassword(newpassword="", firebase_id_token=FIREBASE_ID_TOKEN) Change password You can change a user's password by issuing an HTTP POST request to the Auth setAccountInfo endpoint. # Example ```julia data = firebase_signin("[email protected]","helloworld!!") firebase_changepassword("hellopaaji!!",data["idToken"]) data = firebase_signin("[email protected]","hellopaaji!!") firebase_changepassword("helloworld!!",data["idToken"]) ```` """ function firebase_changepassword(newpassword="", firebase_id_token=FIREBASE_ID_TOKEN) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:update?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"idToken":"$firebase_id_token","password":"$newpassword","returnSecureToken":true}""") response_string = String(http_response.body) JSON.parse(response_string) end """ Update profile You can update a user's profile (display name / photo URL) by issuing an HTTP POST request to the Auth setAccountInfo endpoint. # TODO: delete attribute # Example ```julia data = firebase_signin("[email protected]","helloworld!!") firebase_updateprofile("ash","https://i.imgur.com/zgDkgSR.jpeg",data["idToken"]) #= Dict{String, Any} with 8 entries: "kind" => "identitytoolkit#SetAccountInfoResponse" "photoUrl" => "https://i.imgur.com/zgDkgSR.jpeg" "localId" => "GovyExPqFWS70uynnuBzVnYgLAi2" "displayName" => "ash" "passwordHash" => "UkVEQUNURUQ=" "emailVerified" => false "providerUserInfo" => Any[Dict{String, Any}("rawId"=>"[email protected]", "photoUrl"=>"https:… "email" => "[email protected]" =# ``` """ function firebase_updateprofile(displayname="",photourl="",firebase_id_token=FIREBASE_ID_TOKEN) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:update?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"idToken":"$firebase_id_token","displayName":"$displayname","photoUrl":"$photourl","returnSecureToken":true}""") response_string = String(http_response.body) JSON.parse(response_string) end """ firebase_getuserinfo(firebase_id_token=FIREBASE_ID_TOKEN) Get user data You can get a user's data by issuing an HTTP POST request to the Auth getAccountInfo endpoint. # Example ```julia data = firebase_signin("[email protected]","helloworld!!") firebase_getuserinfo(data["idToken"]) ``` """ function firebase_getuserinfo(firebase_id_token=FIREBASE_ID_TOKEN) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"idToken":"$firebase_id_token"}""") response_string = String(http_response.body) JSON.parse(response_string) end """ Link with email/password You can link an email/password to a current user by issuing an HTTP POST request to the Auth setAccountInfo endpoint. # Example ```julia data = firebase_signin("[email protected]","helloworld!!") firebase_linkuserinfo("[email protected]", "hello!!123as",data["idToken"]) data = firebase_signin("[email protected]", "hello!!123as") firebase_linkuserinfo("[email protected]","helloworld!!",data["idToken"]) ``` """ function firebase_linkuserinfo(email::String="", password::String="",firebase_id_token=FIREBASE_ID_TOKEN) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:update?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"idToken":"$firebase_id_token","email":"$email","password":"$password","returnSecureToken":true}""") response_string = String(http_response.body) JSON.parse(response_string) end # implmene the linking a account with OAuth here """ Link with OAuth credential You can link an OAuth credential to a user by issuing an HTTP POST request to the Auth verifyAssertion endpoint. """ function firebase_linkoauth() end """ Unlink provider You can unlink a provider from a current user by issuing an HTTP POST request to the Auth setAccountInfo endpoint. # Example ```julia set_webapikey() data = firebase_signup("[email protected]","hello!!123") #= Dict{String, Any} with 6 entries: "refreshToken" => "AGEhc0A4Y-wFC0S2Cub-7TY2XNfZMYQf-YKzTdQWl9_SjrRpUW4d3QymQy5P1EN4Me8-SE695sPE_MBXoMoqTzKLy76nBvDGmybGmP4wnWLyrJql-HfoVPRtG1emeJ3E61DnDbUIZOvV-Y3GuzpJ57XZojHBM1aoMp… "kind" => "identitytoolkit#SignupNewUserResponse" "localId" => "neXn8Mg562VFgENRtA2SEC0NEBk1" "expiresIn" => "3600" "idToken" => "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRjNGQwMGJjM2NiZWE4YjU0NTMzMWQxZjFjOTZmZDRlNjdjNTFlODkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vZmlyLWp… "email" => "[email protected]" =# firebase_unlinkprovide(data["idToken"], "google.com") #= Dict{String, Any} with 6 entries: "kind" => "identitytoolkit#SetAccountInfoResponse" "localId" => "neXn8Mg562VFgENRtA2SEC0NEBk1" "passwordHash" => "UkVEQUNURUQ=" "emailVerified" => false "providerUserInfo" => Any[Dict{String, Any}("rawId"=>"[email protected]", "providerId"=>"password", "federatedId"=>"[email protected]", "email"=>"[email protected]")] "email" => "[email protected]" =# ``` """ function firebase_unlinkprovide(firebase_id_token=FIREBASE_ID_TOKEN, providerdelete="google.com") http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:update?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"idToken":"$firebase_id_token","deleteProvider":["[$providerdelete]"]}""") response_string = String(http_response.body) JSON.parse(response_string) end """ firebase_verifyemail(firebase_id_token=FIREBASE_ID_TOKEN) Send email verification You can send an email verification for the current user by issuing an HTTP POST request to the Auth getOobConfirmationCode endpoint. # Example ```julia data = firebase_signin("[email protected]","helloworld!!") firebase_verifyemail((data["idToken"]) ``` """ function firebase_verifyemail(firebase_id_token=FIREBASE_ID_TOKEN) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"requestType":"VERIFY_EMAIL","idToken":"$firebase_id_token"}""") response_string = String(http_response.body) JSON.parse(response_string) end test = "1dArHTOb-Xpb6QWO7f-SVjb4yRRXMmxGB87iMy_oAtMAAAF6GtCHig" """ TODO: This does work yet """ function firebase_confirmemailverify(verification_code="") http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:update?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"oobCode":"$verification_code"}""") response_string = String(http_response.body) JSON.parse(response_string) end """ firebase_deleteuser(firebase_id_token=FIREBASE_ID_TOKEN) Delete account You can delete a current user by issuing an HTTP POST request to the Auth deleteAccount endpoint. # Example ```julia data = firebase_signup("[email protected]","hello!!123") firebase_deleteuser(data["idToken"]) ``` """ function firebase_deleteuser(firebase_id_token=FIREBASE_ID_TOKEN) http_response = HTTP.post("https://identitytoolkit.googleapis.com/v1/accounts:delete?key=$WEB_API_KEY", header="""{Content-Type: application/json}""", body="""{"idToken":"$firebase_id_token"}""") response_string = String(http_response.body) JSON.parse(response_string) end
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
762
using GoogleCloud const FIRESTORE_URL = "https://firestore.googleapis.com/v1" function init(filepath) global CREDENTIALS CREDENTIALS = JSONCredentials(filepath) println(CREDENTIALS) end function projectid() global CREDENTIALS isnothing(CREDENTIALS) && throw("Run JuliaFirestore.init(filepath) to load credentials first") CREDENTIALS.project_id end function get_token() global CREDENTIALS isnothing(CREDENTIALS) && throw("Run JuliaFirestore.init(filepath) to load credentials first") session = GoogleSession(CREDENTIALS, ["datastore"]) GoogleCloud.authorize(session) end function auth_header() println(CREDENTIALS) token = get_token() "Authorization" => "$(token[:token_type]) $(token[:access_token])" end
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
15544
# function get_singlepage(documentpath; pagesize=300, pagetoken::String="") @show "Firestore.get_singlepage", documentpath, pagesize, pagetoken base_url = FIRESTORE_URL headers = Dict(auth_header()) project_id = projectid() firestore_path = "/projects/$project_id/databases/(default)/documents" url = "$base_url$firestore_path/$documentpath" query = Dict{String,Any}("pageSize" => pagesize) if !isempty(pagetoken) query["pageToken"] = pagetoken end http_response = HTTP.get(url, headers; query=query) response_string = String(http_response.body) JSON.parse(response_string) end function get_collection(documentpath; pagesize=300) @show "Firestore.get_collection", documentpath, pagesize docs = [] pagetoken = "" while true response = get_singlepage( documentpath, pagesize=pagesize, pagetoken=pagetoken, ) isempty(response) && return docs push!(docs, response["documents"]...) !haskey(response, "nextPageToken") && break pagetoken = response["nextPageToken"] end docs end get_document(documentpath) = get_singlepage(documentpath) function get(path...) @show "Firestore.get", path full_path = join(path, '/') length(path) % 2 == 0 && return convert_map(get_document(full_path)) map(convert_map, get_collection(full_path)) end """ get_request(url::String) # Get request which is general in nature and gets any document or collection # Example ```julia init("[FIREBASE_ADMIN_SDK].json") res = get_request("/firebase_test/firebase_get") # document get res = get_request("/firebase_test/firebase_get/firebase_get_collection") # collection fetch ``` """ function get_request(url::String) header = Dict(auth_header()) project_id = projectid() url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents$url" println(url) http_response = HTTP.get(url, header) response_string = String(http_response.body) JSON.parse(response_string) end body = Dict( "newTransaction" => Dict(), # "transaction" => "", # "readTime" => "", "documents" => [ "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get", "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get?collectionID=firebase_get_collection", "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get/firebase_get_collection/test", ], "mask" => Dict( "fieldPaths" => [ "first1", ]), ) # mask gets particular fields looks like # weird field in mask is just ignored and nothing happens """ firestore_batchget(batch=body) Gets multiple documents Documents returned by this method are not guaranteed to be returned in the same order that they were requested. # Example ```julia init("[FIREBASE_ADMIN_SDK].json") res = firestore_batchget() ``` """ function firestore_batchget(batch=body) header = Dict(auth_header()) project_id = projectid() println(batch) body = JSON.json(batch) println("Batch:", body) final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents:batchGet" http_response = HTTP.request( "POST", final_url, header, body, ) response_string = String(http_response.body) JSON.parse(response_string) end body = Dict( "writes" => [ Dict( "update" => Dict( "name" => "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get", "fields" => Dict( "first" => Dict( "stringValue" => "ashwani", ), "last" => Dict( "stringValue" => "rathee", ) ) ), "updateMask" => Dict( "fieldPaths" => [ "first", "last", ] ) ) ], "labels" => Dict( string => "ABC" ) ) # study types of writes from here https://firebase.google.com/docs/firestore/reference/rest/v1/Write # study the effect of labelss, and update masks # Labels associated with this batch write. # mask gets particular fields looks like # weird field in mask is just ignored and nothing happens """ firestore_batchwrite(batch=body) Applies a batch of write operations. The documents.batchWrite method does not apply the write operations atomically and can apply them out of order. Method does not allow more than one write per document. Each write succeeds or fails independently. See the BatchWriteResponse for the success status of each write. If you require an atomically applied set of writes, use documents.commit instead. # Example ```julia init("[FIREBASE_ADMIN_SDK].json") res = firestore_batchwrite() ``` """ function firestore_batchwrite(batch=body) header = Dict(auth_header()) project_id = projectid() println(batch) body = JSON.json(batch) println("Batch:", body) final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents:batchWrite" http_response = HTTP.request( "POST", final_url, header, body, ) response_string = String(http_response.body) JSON.parse(response_string) end body = Dict( "options" => Dict( ) ) # study transaction options and what is transactions used for here """ firestore_beginTransaction() Starts a new transaction. "options" The options for the transaction. Defaults to a read-write transaction. # Example ```julia init("[FIREBASE_ADMIN_SDK].json") firestore_beginTransaction() ``` """ function firestore_beginTransaction() header = Dict(auth_header()) project_id = projectid() # println(batch) # body = JSON.json(batch) # println("Batch:", body) final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents:beginTransaction" http_response = HTTP.request( "POST", final_url, header, # body, ) response_string = String(http_response.body) JSON.parse(response_string) end body = Dict( "writes" => [ Dict( "update" => Dict( "name" => "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get", "fields" => Dict( "first" => Dict( "stringValue" => "ashwani", ), "last" => Dict( "stringValue" => "rathee", ) ) ), "updateMask" => Dict( "fieldPaths" => [ "first", "last", ] ) ) ], "transaction" => "EZTktxl/jJ9GIlkA3ModskgtczlV2HUqlqGQbh6U8YClsJvU07MTX5/8q0Fhd3hAvi0aSvm4NLF2H8FNiEzspxJLVM4NOZVDsClQgpuLqwkA9uFrQM81VXxzYzGLLvU0hssZZg==" ) # commits a particular transaction that was started or is happening # this one is particularly interesting """ firestore_commit(transactionid="",body =body) Commits a transaction, while optionally updating documents. # Example ```julia init("[FIREBASE_ADMIN_SDK].json") data = firestore_beginTransaction() firestore_commit(data["transaction"]) ``` """ function firestore_commit(transactionid="", body=body) header = Dict(auth_header()) project_id = projectid() body["transaction"] = transactionid body = JSON.json(body) println("Body:", body) final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents:commit" http_response = HTTP.request( "POST", final_url, header, body, ) response_string = String(http_response.body) JSON.parse(response_string) end # Create Document # body = """{ # "fields": { # "test": { # "stringValue": "1" # } # } # } # """ body = Dict( "fields" => Dict( "test" => Dict( "stringValue" => "1" ) ) ) # above :The request body contains an instance of Document. # how two add field to the # dpcument id is supposed to be a query parameter as of now it's hardcoded """ firestore_createdoc(url, body) # Example ```julia init("[FIREBASE_ADMIN_SDK].json") firestore_createdoc("/firebase_test/firebase_post/two") firestore_createdoc("/firebase_test/firebase_post/three";query ="hello") # with document id name in query ``` """ function firestore_createdoc(url, body=body;query=query) header = Dict(auth_header()) project_id = projectid() body = JSON.json(body) println("Body:", body) query = Dict{String,Any}("documentId" => query) # mask part doesn't work yet # query = JSON.json(query) # println(query) final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents$url" http_response = HTTP.post( final_url, header, body;query=query ) response_string = String(http_response.body) JSON.parse(response_string) end # implement query properly for documentid and mask in here """ firestore_deletedoc(url) Deletes a document # Example ```julia init("[FIREBASE_ADMIN_SDK].json") firestore_createdoc("/firebase_test/firebase_post/three";query ="hello") # creates the document and then we delete it firestore_deletedoc("/firebase_test/firebase_post/three/hello") ``` """ function firestore_deletedoc(url) header = Dict(auth_header()) project_id = projectid() final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents$url?currentDocument.exists=true" http_response = HTTP.delete( final_url, header, ) response_string = String(http_response.body) JSON.parse(response_string) end """ firestore_getdoclist(url) Lists documents # Example ```julia init("[FIREBASE_ADMIN_SDK].json") firestore_getdoclist("/firebase_test") ``` """ function firestore_getdoclist(url) header = Dict(auth_header()) project_id = projectid() final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents$url" http_response = HTTP.get( final_url, header, ) response_string = String(http_response.body) JSON.parse(response_string) end """ firestore_getcollectionids(url;query="") Lists all the collection IDs underneath a document. # Example ```julia init("[FIREBASE_ADMIN_SDK].json") firestore_getcollectionids("/firebase_test/firebase_post") ``` """ function firestore_getcollectionids(url;query="") header = Dict(auth_header()) project_id = projectid() final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents$url:listCollectionIds" pagesize = 300 pagetoken = "" if !isempty(pagetoken) query["pageToken"] = pagetoken end query = Dict{String,Any}("pageSize" => pagesize, "pageToken" => pagetoken) # this query content is supposed to be request body http_response = HTTP.post( final_url, header; query=query, ) response_string = String(http_response.body) JSON.parse(response_string) end # Doesn't work really body = Dict( "partitionCount" => "1", "pageToken" => "", "pageSize" => 300, "structuredQuery" => Dict( "where" => Dict( "fieldFilter" => Dict( "field" => Dict("fieldPath" => "test"), "op" => "EQUAL", "value" => Dict("integerValue" => 1) ) ), "from" => [Dict("collectionId" => "new1")] ) ) """ firestore_partitionquery(url) Partitions a query by returning partition cursors that can be used to run the query in parallel. The returned partition cursors are split points that can be used by documents.runQuery as starting/end points for the query results. """ function firestore_partitionquery(url, body=body) header = Dict(auth_header()) project_id = projectid() final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents$url:partitionQuery" body = JSON.json(body) println("Body:", body) http_response = HTTP.post( final_url, header, body ; ) response_string = String(http_response.body) JSON.parse(response_string) end body = Dict( "fields" => Dict( "test1" => Dict( "stringValue" => "1" ) ) ) # need to implement query parameters like updatemask ,mask currentDocument """ firestore_patch() Updates or inserts a document. # Example ```julia init("[FIREBASE_ADMIN_SDK].json") firestore_patch("/firebase_test/firebase_patch") ``` """ function firestore_patch(url, body=body) header = Dict(auth_header()) project_id = projectid() final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents$url" body = JSON.json(body) println("Body:", body) # query = Dict{String,Any}("documentId" => query) # mask part doesn't work yet # query = JSON.json(query) # println(query) http_response = HTTP.patch( final_url, header, body ; ) response_string = String(http_response.body) JSON.parse(response_string) end """ firestore_rollback(transactionid,body=body) Rolls back a transaction. # Example ```julia init("[FIREBASE_ADMIN_SDK].json") data = firestore_beginTransaction() # firestore_commit(data["transaction"]) firestore_rollback(data["transaction"]) ``` # Output If successful, the response body will be empty. """ body = Dict("transaction" => "") function firestore_rollback(transactionid, body=body) header = Dict(auth_header()) project_id = projectid() final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents:rollback" body["transaction"] = transactionid body = JSON.json(body) println("Body:", body) http_response = HTTP.post( final_url, header, body ; ) response_string = String(http_response.body) JSON.parse(response_string) end body = Dict( "newTransaction" => Dict(), "structuredQuery" => Dict( "select" => Dict( "fields" => [ Dict( "fieldPath" => "test" ), ] ) ) ) body = Dict( "newTransaction" => Dict(), "structuredQuery" => Dict( "where" => Dict( "fieldFilter" => Dict( "field" => Dict("fieldPath" => "test"), "op" => "EQUAL", "value" => Dict("stringValue" => "1") ) ), "from" => [Dict("collectionId" => "new")] ) ) # very specific as shown above is successfully run and it works by choosing 1/3 or 2/3 as the variables are changed """ firestore_runquery() Runs a query. # Example ```julia init("[FIREBASE_ADMIN_SDK].json") firestore_runquery("/firebase_test/firebase_post") ``` """ function firestore_runquery(url, body=body) header = Dict(auth_header()) project_id = projectid() final_url = "$(FIRESTORE_URL)/projects/$project_id/databases/(default)/documents$url:runQuery" body = JSON.json(body) println("Body:", body) println("FINAL_URL:", final_url) http_response = HTTP.post( final_url, header, body ) response_string = String(http_response.body) JSON.parse(response_string) end
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
5381
# Realtime Database using HTTP, JSON BASE_URL = nothing """ In the examples on this page, you would replace [PROJECT_ID] with the identifier of your Firebase project. """ """ realdb_init(base_url; query = Dict()) Initialize the realtimedb with baseurl to make things easier # Example ```julia realdb_init("https://[PROJECT_ID].asia-southeast1.firebasedatabase.app") ``` """ function realdb_init(base_url; query = Dict()) global BASE_URL = base_url println("BASE_URL set:", BASE_URL) end """ realdb_get(url; query = Dict()) GET request to an endpoint. # Example ```julia realdb_init("https://[PROJECT_ID].asia-southeast1.firebasedatabase.app") realdb_get("/users/jack/name") ``` """ function realdb_get(url; query = Dict()) pagesize = 300 pagetoken = "" final_url = "$BASE_URL$url.json" println("FINAL URL:", final_url) query = Dict{String,Any}("pageSize" => pagesize, "pageToken" => pagetoken) res = HTTP.get(final_url; query = query) if res.status == 200 println("GET successful") else println("GET errored") end JSON.parse(String(res.body)) end """ realdb_post(url, body = "{"name": "real_db_test"}"; query = Dict()) POST request to an endpoint. # Example ```julia realdb_init("https://[PROJECT_ID].asia-southeast1.firebasedatabase.app") # realdb_post("/message_list") body =Dict("user_id" => "jack", "text" => "Ahoy!") realdb_post("/message_list",body) ``` ## Notes: According to the REST API documentation for Realtime Database, a POST is the equivalent of a "push" operation when using the client SDKs. This push operation always involves adding data under a random ID. There is no avoiding that for a push. If you know the name of the node where you want to add data, you should use a PUT instead. This is the equivalent of using "set" operation with the client SDKs. """ function realdb_post(url, body = Dict("name" => "real_db_test"); query = Dict()) pagesize = 300 pagetoken = "" final_url = "$BASE_URL$url.json" println("FINAL URL:", final_url) body = JSON.json(body) println("Body:", body) query = Dict{String,Any}("pageSize" => pagesize, "pageToken" => pagetoken) res = HTTP.post(final_url, "", body; query = query) if res.status == 200 println("POST successful") else println("POST errored") end JSON.parse(String(res.body)) end """ realdb_patch(url, body = Dict("name"=> "real_db_test"); query = Dict()) `PATCH` request to an endpoint. # Example ```julia realdb_init("https://[PROJECT_ID].asia-southeast1.firebasedatabase.app") body =Dict("last"=>"Jones") realdb_patch("/users/jack/name/",body) ``` """ function realdb_patch(url, body = Dict("name" => "real_db_test"); query = Dict()) pagesize = 300 pagetoken = "" final_url = "$BASE_URL$url.json" println("FINAL URL:", final_url) query = Dict{String,Any}("pageSize" => pagesize, "pageToken" => pagetoken) body = JSON.json(body) println("Body:", body) res = HTTP.patch(final_url, "", body; query = query) if res.status == 200 println("PATCH successful") else println("PATCH errored") end JSON.parse(String(res.body)) end """ realdb_delete(url, body = Dict("name"=> "real_db_test"); query = Dict()) `DELETE` request to an endpoint # Example ```julia realdb_init("https://[PROJECT_ID].asia-southeast1.firebasedatabase.app") realdb_delete("/users/jack/name/last") ``` """ function realdb_delete(url, body = Dict("name" => "real_db_test"); query = Dict()) pagesize = 300 pagetoken = "" final_url = "$BASE_URL$url.json" println("FINAL URL:", final_url) query = Dict{String,Any}("pageSize" => pagesize, "pageToken" => pagetoken) body = JSON.json(body) println("Body:", body) res = HTTP.delete(final_url, "", body; query = query) if res.status == 200 println("DELETE successful") else println("DELETE errored") end JSON.parse(String(res.body)) end """ realdb_put(url, body = Dict("name"=> "real_db_test"); query = Dict()) `PUT` request to a endpoint. # Example ```julia realdb_init("https://[PROJECT_ID].asia-southeast1.firebasedatabase.app") body = Dict("first"=>"Ash", "last"=>"Sparrow") realdb_put("/users/jack/name",body) ``` """ function realdb_put(url, body = Dict("name" => "real_db_test"); query = Dict()) pagesize = 300 pagetoken = "" final_url = "$BASE_URL$url.json" println("FINAL URL:", final_url) query = Dict{String,Any}("pageSize" => pagesize, "pageToken" => pagetoken) body = JSON.json(body) println("Body:", body) res = HTTP.put(final_url, "", body; query = query) if res.status == 200 println("PUT successful") else println("PUT errored") end JSON.parse(String(res.body)) end """ readdb_download(url, filename = "test"; query = Dict()) Download request # Example ```julia ``` """ function readdb_download(url, filename = "test"; query = Dict()) pagesize = 300 pagetoken = "" final_url = "$BASE_URL$url.json?download=$filename.txt" println("FINAL URL:", final_url) query = Dict{String,Any}("pageSize" => pagesize, "pageToken" => pagetoken) res = HTTP.get(final_url; query = query) if res.status == 200 println("GET successful") else println("GET errored") end JSON.parse(String(res.body)) end
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
8201
# using Firebase, Test # using HTTP, JSON init("fir-jl-457eb-firebase-adminsdk-40928-0efd6a89e7.json") headers = Dict(auth_header()); @testset "Firebase: GET" begin # using old functions # res = Firebase.get("firebase_test", "firebase_get") # expected = Dict{String,Any}( # "firebase_get1" => "1", # "firebase_get3" => "3", # "__id__" => "firebase_get", # "firebase_get2" => "2", # ) # @test res == expected # BATCH GET EXAMPLE # body = """ # { # "newTransaction": { # }, # "documents": [ # "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get", # "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get?collectionID=firebase_get_level2", # "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get/firebase_get_level2/firebase_get_level2_1", # ] # }""" # res = HTTP.request( # "POST", # "https://firestore.googleapis.com/v1beta1/projects/fir-jl-457eb/databases/(default)/documents:batchGet", # headers, # body, # ) # test1 = Dict{String,Any}( # "name" => # "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get", # "fields" => Dict{String,Any}( # "firebase_get1" => Dict{String,Any}("stringValue" => "1"), # "firebase_get3" => Dict{String,Any}("stringValue" => "3"), # "firebase_get2" => Dict{String,Any}("stringValue" => "2"), # ), # "createTime" => "2021-06-15T03:37:00.201709Z", # "updateTime" => "2021-06-15T03:37:00.201709Z", # ) # test2 = Dict{String,Any}( # "name" => # "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get/firebase_get_level2/firebase_get_level2_1", # "fields" => Dict{String,Any}( # "get_level2_3" => Dict{String,Any}("stringValue" => "3"), # "get_level2_1" => Dict{String,Any}("stringValue" => "1"), # "get_level2_2" => Dict{String,Any}("stringValue" => "2"), # ), # "createTime" => "2021-06-15T03:38:10.344593Z", # "updateTime" => "2021-06-15T03:38:10.344593Z", # ) # test3 = "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get?collectionID=firebase_get_level2" # # println("Start") # data = JSON.parse(String(res.body)) # # println(data) # @test res.status == 200 # @test data[2]["found"] == test1 # @test data[3]["found"] == test2 # @test data[4]["missing"] == test3 # Lists documents. # expected = Dict{String,Any}( # "documents" => Any[ # Dict{String,Any}( # "name" => # "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get/firebase_get_level2/firebase_get_level2_1", # "fields" => Dict{String,Any}( # "get_level2_3" => Dict{String,Any}("stringValue" => "3"), # "get_level2_1" => Dict{String,Any}("stringValue" => "1"), # "get_level2_2" => Dict{String,Any}("stringValue" => "2"), # ), # "createTime" => "2021-06-15T03:38:10.344593Z", # "updateTime" => "2021-06-15T03:38:10.344593Z", # ), # Dict{String,Any}( # "name" => # "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get/firebase_get_level2/firebase_get_level2_2", # "fields" => Dict{String,Any}( # "get_level2_2_1" => Dict{String,Any}("stringValue" => "1"), # "get_level2_2_2" => Dict{String,Any}("stringValue" => "2"), # ), # "createTime" => "2021-06-15T04:49:18.282446Z", # "updateTime" => "2021-06-15T04:49:18.282446Z", # ), # ], # ) # res = HTTP.get( # "https://firestore.googleapis.com/v1beta1/projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get/firebase_get_level2", # headers, # ) # res = JSON.parse(String(res.body)) # @test res == expected # #= Batch Write Doesn't work body = """ { "writes": [ { "update": { "name": "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_post", "fields": { "post_1": { "stringValue": "0657331995" } } }, } ] }""" res = HTTP.request("POST", "https://firestore.googleapis.com/v1beta1/projects/fir-jl-457eb/databases:batchWrite",headers,body) # println("Start") data = JSON.parse(String(res.body)); println(data) =# # create document # res # # Get document # res = HTTP.get("https://firestore.googleapis.com/v1/projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get/",headers) # data = JSON.parse(String(res.body)); # println(data) # expected = Dict{String, Any}("name" => "projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get", "fields" => Dict{String, Any}("firebase_get1" => Dict{String, Any}("stringValue" => "1"), "firebase_get3" => Dict{String, Any}("stringValue" => "3"), "firebase_get2" => Dict{String, Any}("stringValue" => "2")), "createTime" => "2021-06-15T03:37:00.201709Z", "updateTime" => "2021-06-15T03:37:00.201709Z") # @test res == expected # # Delete document # works just fine res = HTTP.delete( "https://firestore.googleapis.com/v1/projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_post/new/new1?currentDocument.exists=true", headers, ) # data = JSON.parse(String(res.body)); # println(data) @test res.status == 200 # # Create Document body = """{ "fields": { "test": { "stringValue": "1" } } } """ res = HTTP.post( "https://firestore.googleapis.com/v1/projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_post/new?documentId=new1", headers, body, ) @test res.status == 200 # # Lists all the collection IDs underneath a document. # pagesize = 300 # pagetoken = "" # if !isempty(pagetoken) # query["pageToken"] = pagetoken # end # query = Dict{String,Any}("pageSize" => pagesize, "pageToken" => pagetoken) # res = HTTP.post( # "https://firestore.googleapis.com/v1beta1/projects/fir-jl-457eb/databases/(default)/documents/firebase_test/firebase_get:listCollectionIds", # headers; # query = query, # ) # expected = Dict{String,Any}("collectionIds" => Any["firebase_get_level2"]) # res = JSON.parse(String(res.body)) # @test res == expected # Gets the metadata and configuration for a Field. res =HTTP.get("https://firestore.googleapis.com/v1/projects/fir-jl-457eb/databases/(default)/collectionGroups/firebase_test/fields/firebase_get1",headers) res = JSON.parse(String(res.body)) expected = Dict{String, Any}("name" => "projects/fir-jl-457eb/databases/(default)/collectionGroups/firebase_test/fields/firebase_get1", "indexConfig" => Dict{String, Any}("indexes" => Any[Dict{String, Any}("fields" => Any[Dict{String, Any}("order" => "ASCENDING", "fieldPath" => "firebase_get1")], "queryScope" => "COLLECTION", "state" => "READY"), Dict{String, Any}("fields" => Any[Dict{String, Any}("order" => "DESCENDING", "fieldPath" => "firebase_get1")], "queryScope" => "COLLECTION", "state" => "READY"), Dict{String, Any}("fields" => Any[Dict{String, Any}("arrayConfig" => "CONTAINS", "fieldPath" => "firebase_get1")], "queryScope" => "COLLECTION", "state" => "READY")], "usesAncestorConfig" => true, "ancestorField" => "projects/fir-jl-457eb/databases/(default)/collectionGroups/__default__/fields/*")) @test res == expected # # projects.databases.collectionGroups.fields.list # not able to make it work # end
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
1968
using Firebase @testset "Realtime" begin URL = "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app" BASE_URL = "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app" realdb_init(URL); # init method test res = realdb_init(URL); @test BASE_URL == URL # GET method test realdb_init(URL); res = realdb_get("/firebase_test/firebase_get"); expected = Dict{String,Any}("first" => "ashwani", "last" => "rathee") @test res == expected # POST method test realdb_init(URL) body = Dict("first" => "ashwani", "last" => "rathee") res = realdb_post("/firebase_test/firebase_post/post_test", body) test_id = res["name"] res = realdb_get("/firebase_test/firebase_post/post_test/$test_id"); expected = Dict{String,Any}("first" => "ashwani", "last" => "rathee") @test res == expected realdb_delete("/firebase_test/firebase_post/post_test/$test_id") # PUT method test realdb_init(URL) body = Dict("first" => "ashwani") res = realdb_put("/firebase_test/firebase_put", body) res = realdb_get("/firebase_test/firebase_put"); @test res == body body = Dict("first" => "ashwani", "last" => "rathee") realdb_put("/firebase_test/firebase_put", body) # PATCH method test realdb_init(URL) body = Dict("last" => "rathi") realdb_patch("/firebase_test/firebase_patch", body) res = realdb_get("/firebase_test/firebase_patch") expected = Dict("first" => "ashwani", "last" => "rathi") @test res == expected body = Dict("first" => "ashwani", "last" => "rathee") realdb_put("/firebase_test/firebase_patch", body) # DELETE method test realdb_init(URL) realdb_delete("/firebase_test/firebase_delete") res = realdb_get("/firebase_test/firebase_delete") @test res === nothing body = Dict("first" => "ashwani", "last" => "rathee") realdb_put("/firebase_test/firebase_delete", body) end
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
code
135
using Firebase using Test using HTTP, JSON @testset "Firebase" begin include("realtime.jl") include("firestore.jl") end
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
docs
3640
# Firebase.jl : Julia Firebase # Installation ```julia using Pkg Pkg.clone("github.com/ashwani-rathee/Firebase.jl.git") ``` # TODO Lot of work in these section: - [ ] Firebase Authentication - [ ] Cloud Firestore - [ ] Realtime Database # Cloud Firestore ```julia using Firestore Firestore.init(path_to_firestore_service_account_key_json) Firestore.get(collection_id,doc_id) # get single doc Firestore.get(collection_id) # get all docs in collection w/o sub_collections) Firestore.get(collection_id,doc_id,sub_collection_id_1,doc_id_2) # get doc in sub collection Firestore.get(collection_id,doc_id,sub_collection_id_1,doc_id_2,sub_collection_id_2) # get all docs in sub collection ``` # Realtime Database Initializing the realdb for the base url, reduces the effort later ```julia realdbinit("https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app") Base Url set:"https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app" ``` ## GET - Reading Data Data from your Realtime Database can be read by issuing an HTTP GET request to an endpoint. The following example demonstrates how you might retrieve a user's name that you had previously stored in Realtime Database. ```julia julia> realdb_get("/firebase_test") ulia> realdb_get("/firebase_test") FINAL URL: "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test.json" GET successful Dict{String, Any} with 3 entries: "firebase_get" => Dict{String, Any}("firebase_get_3"=>3, "firebase_get_2"=>2, "firebase_get_1"=>1) "firebase_new" => Dict{String, Any}("-McEjFxupzSbZwojItzL"=>Dict{String, Any}("name"=>"real_db_test"), "-McEjCHubimhfipKm2yo"=>Dict{String, Any}("name"=>"real_db_test"), "-McEjNy8-8VjqSH3P8dO"=>Dict{String, Any}… "firebase_post" => Dict{String, Any}("firebase_post_1"=>1, "firebase_post_3"=>3, "firebase_post_2"=>2, "input"=>Dict{String, Any}("-McEQ7vGcvji7Myab182"=>Dict{String, Any}("stockAmount"=>350, "price"=>"7.5 TL", "… ``` ## POST - Pushing Data To accomplish the equivalent of the JavaScript push() method (see Lists of Data), you can issue a POST request. A successful request is indicated by a 200 OK HTTP status code. The response contains the child name of the new data specified in the POST request. ```julia julia> realdb_post("/firebase_test/firebase_new") FINAL URL: "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test/firebase_new.json" POST successful Dict{String, Any} with 1 entry: "name" => "-McEkk8qvdT4UHSUQALx" julia> realdb_post("/firebase_test/firebase_new/","""{"hello":1}""") FINAL URL: "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test/firebase_new.json" POST successful Dict{String, Any} with 1 entry: "name" => "-McElRx3ZBP-l7pCF0LN" ``` ## DELETE - Removing Data You can delete data with a DELETE request A successful DELETE request is indicated by a 200 OK HTTP status code with a response containing JSON null. ```julia julia> realdb_delete("/firebase_test/firebase_new") https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test/firebase_new.json DELETE successful ``` ## PUT - Writing Data You can write data with a PUT request. A successful request is indicated by a 200 OK HTTP status code. The response contains the data specified in the PUT request. ```julia julia> realdb_put("/firebase_test/firebase_new/","""{"hello":1}""") FINAL URL: "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test/firebase_new.json" PUT successful Dict{String, Any} with 1 entry: "name" => "-McElRx3ZBP-l7pCF0LN" ``` # Reference
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.0.1
b55ca833b59ed30e2cef577016985c42cf6da26f
docs
3782
# Firebase.jl : Julia Firebase ```@meta CurrentModule = Firebase ``` Julia's Interface to Firebase REST API # Installation ```julia using Pkg Pkg.clone("https://github.com/ashwani-rathee/Firebase.jl.git") ``` # TODO Lot of work in these section: - [ ] Firebase Authentication - [ ] Cloud Firestore - [ ] Realtime Database # Cloud Firestore ```julia using Firestore Firestore.init(path_to_firestore_service_account_key_json) Firestore.get(collection_id,doc_id) # get single doc Firestore.get(collection_id) # get all docs in collection w/o sub_collections) Firestore.get(collection_id,doc_id,sub_collection_id_1,doc_id_2) # get doc in sub collection Firestore.get(collection_id,doc_id,sub_collection_id_1,doc_id_2,sub_collection_id_2) # get all docs in sub collection ``` # Realtime Database Initializing the realdb for the base url, reduces the effort later ```julia realdbinit("https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app") Base Url set:"https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app" ``` ## GET - Reading Data Data from your Realtime Database can be read by issuing an HTTP GET request to an endpoint. The following example demonstrates how you might retrieve a user's name that you had previously stored in Realtime Database. ```julia julia> realdb_get("/firebase_test") ulia> realdb_get("/firebase_test") FINAL URL: "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test.json" GET successful Dict{String, Any} with 3 entries: "firebase_get" => Dict{String, Any}("firebase_get_3"=>3, "firebase_get_2"=>2, "firebase_get_1"=>1) "firebase_new" => Dict{String, Any}("-McEjFxupzSbZwojItzL"=>Dict{String, Any}("name"=>"real_db_test"), "-McEjCHubimhfipKm2yo"=>Dict{String, Any}("name"=>"real_db_test"), "-McEjNy8-8VjqSH3P8dO"=>Dict{String, Any}… "firebase_post" => Dict{String, Any}("firebase_post_1"=>1, "firebase_post_3"=>3, "firebase_post_2"=>2, "input"=>Dict{String, Any}("-McEQ7vGcvji7Myab182"=>Dict{String, Any}("stockAmount"=>350, "price"=>"7.5 TL", "… ``` ## POST - Pushing Data To accomplish the equivalent of the JavaScript push() method (see Lists of Data), you can issue a POST request. A successful request is indicated by a 200 OK HTTP status code. The response contains the child name of the new data specified in the POST request. ```julia julia> realdb_post("/firebase_test/firebase_new") FINAL URL: "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test/firebase_new.json" POST successful Dict{String, Any} with 1 entry: "name" => "-McEkk8qvdT4UHSUQALx" julia> realdb_post("/firebase_test/firebase_new/","""{"hello":1}""") FINAL URL: "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test/firebase_new.json" POST successful Dict{String, Any} with 1 entry: "name" => "-McElRx3ZBP-l7pCF0LN" ``` ## DELETE - Removing Data You can delete data with a DELETE request A successful DELETE request is indicated by a 200 OK HTTP status code with a response containing JSON null. ```julia julia> realdb_delete("/firebase_test/firebase_new") https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test/firebase_new.json DELETE successful ``` ## PUT - Writing Data You can write data with a PUT request. A successful request is indicated by a 200 OK HTTP status code. The response contains the data specified in the PUT request. ```julia julia> realdb_put("/firebase_test/firebase_new/","""{"hello":1}""") FINAL URL: "https://fir-jl-457eb-default-rtdb.asia-southeast1.firebasedatabase.app/firebase_test/firebase_new.json" PUT successful Dict{String, Any} with 1 entry: "name" => "-McElRx3ZBP-l7pCF0LN" ``` ```@index ``` ```@autodocs Modules = [Firebase] ``` # Reference
Firebase
https://github.com/ashwani-rathee/Firebase.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1307
module FSimZoo import FSimBase: State, Params, Dynamics! import FSimBase: Command using FSimBase using ComponentArrays using ForwardDiff using MatrixEquations using LinearAlgebra using Convex, ECOS using Rotations, Quaternions ## basics export TwoDimensionalNonlinearPolynomialSystem, LinearSystem, ReferenceModel, MultipleEnvs export TwoDimensionalNonlinearOscillator, SingleIntegrator export TwoDimensionalNonlinearDTSystem ## controllers export LQR, PID, BacksteppingPositionController export GeometricTrackingController, OuterLoopGeometricTrackingController, InnerLoopGeometricTrackingController export InputAffinePositionCBF ## actuators export SecondOrderActuator ## fixedwings export AbstractWingRock, ElzebdaWingRock, TarnWingRock ## multicopters export Multicopter export Quadcopter, IslamQuadcopter, GoodarziQuadcopter, LeeQuadcopter, GoodarziAgileQuadcopter export Hexacopter, LeeHexacopter ## missiles export MissileLongitudinal # control allocator export AbstractAllocator, StaticAllocator export PseudoInverseAllocator # integrated environments export BacksteppingPositionController_StaticAllocator_Multicopter ## utils export ned2enu, enu2ned export euler2quat, quat2euler, dcm2euler, euler2dcm, quat2dcm, dcm2quat include("environments/environments.jl") include("utils/utils.jl") end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
456
### Envs ## Basic environments include("basics/basics.jl") ## Actuators include("actuators/actuators.jl") ## Fixed wings include("fixedwings/fixedwings.jl") ## Multicopters include("multicopters/multicopters.jl") ## Missiles include("missiles/missiles.jl") ## Control Allocators include("allocators/allocators.jl") ## Controllers include("controllers/controllers.jl") ## Integrated Envs include("integrated_environments/integrated_environments.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
474
Base.@kwdef struct SecondOrderActuator <: AbstractActuator ζ=0.7 ω=150.0 end function State(env::SecondOrderActuator) return function (δ=0.0, δ̇=0.0) ComponentArray(δ=δ, δ̇=δ̇) end end function Dynamics!(env::SecondOrderActuator) (; ζ, ω) = env @Loggable function dynamics!(dx, x, p, t; δ_cmd) (; δ, δ̇) = x @log state = x @log input = δ_cmd dx.δ = δ̇ dx.δ̇ = -2*ζ*ω*δ̇ + ω^2*(δ_cmd-δ) end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
86
abstract type AbstractActuator <: AbstractEnv end include("SecondOrderActuator.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
497
""" Moore-Penrose inverse control allocator. """ struct PseudoInverseAllocator <: StaticAllocator B_pinv function PseudoInverseAllocator(B) B_pinv = pinv(B) new(B_pinv) end end """ # Variables ν: virtual input # Notes ν = B*u where u: control input """ function Command(allocator::PseudoInverseAllocator) (; B_pinv) = allocator return function (ν, Λ=Diagonal(ones(size(B_pinv)[1]))) (pinv(Λ) * B_pinv) * ν # pinv(B*Λ) = pinv(Λ) * pinv(B) end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
151
abstract type AbstractAllocator <: AbstractController end abstract type StaticAllocator <: AbstractAllocator end include("PseudoInverseAllocator.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
445
struct LinearSystem <: AbstractEnv A B end function State(env::LinearSystem) (; B) = env n = size(B)[1] return function (x) @assert length(x) == n x end end function Params(env::LinearSystem) () -> nothing end function Dynamics!(env::LinearSystem) (; A, B) = env @Loggable function dynamics!(dx, x, p, t; u) @log state = x @log input = u dx .= A*x + B*u end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
848
struct MultipleEnvs{T <: AbstractEnv, S <: Union{Symbol, String}} <: AbstractEnv envs_dict::Dict{S, T} end function State(envs::MultipleEnvs) (; envs_dict) = envs function state(; state_pairs...) nt = (; state_pairs...) ComponentArray(nt) end end function Dynamics!(envs::MultipleEnvs) (; envs_dict) = envs @Loggable function dynamics!(dx, x, p, t; kwargs_pairs...) for (key, kwargs) in kwargs_pairs @nested_log key Dynamics!(envs_dict[key])(getproperty(dx, key), getproperty(x, key), hasproperty(p, key) ? getproperty(p, key) : p, t; kwargs...) end end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
2804
""" # References - Reference model (e.g., xd, vd, ad, ad_dot, ad_ddot) [1] S. J. Su, Y. Y. Zhu, H. R. Wang, and C. Yun, “A Method to Construct a Reference Model for Model Reference Adaptive Control,” Adv. Mech. Eng., vol. 11, no. 11, pp. 1–9, 2019. # Notes d: degree of the reference model auto_diff: auto_diff = true for tracking time-varying command; otherwise for set-point regulation x_cmd_func(t): function of time """ struct ReferenceModel <: AbstractEnv d::Int # degree Ks::AbstractArray auto_diff::Bool x_cmd_func::Union{Function, Nothing} end function ReferenceModel(d::Int; x_cmd_func=nothing) @assert d >= 0 Ks = [] if d == 4 # [1] push!(Ks, Diagonal(1.0*ones(3))) push!(Ks, Diagonal(3.4*ones(3))) push!(Ks, Diagonal(5.4*ones(3))) push!(Ks, Diagonal(4.9*ones(3))) push!(Ks, Diagonal(2.7*ones(3))) else error("Assign values of matrix `Kx` manually") end auto_diff = x_cmd_func == nothing ? false : true ReferenceModel(d, Ks, auto_diff, x_cmd_func) end """ `x_i` denotes `i`th (time) derivative of `x` """ function State(env::ReferenceModel) (; d) = env return function (x0) xs_dict = Dict(:x_0 => x0) for i in 1:d xs_dict[Symbol(:x_, i)] = zeros(size(x0)) # e.g., xs_dict[:x1] = zeros(3) end ComponentArray((; zip(keys(xs_dict), values(xs_dict))...)) end end function Dynamics!(env::ReferenceModel) (; d, Ks, auto_diff, x_cmd_func) = env # derivatives for auto_diff funcs = nothing if auto_diff _funcs = Function[x_cmd_func] for i in 1:d+1 push!(_funcs, (t) -> ForwardDiff.derivative(_funcs[i], t)) end end funcs(t) = [_func(t) for _func in _funcs] @Loggable function dynamics!(dX, X, p, t; x_cmd=nothing) @onlylog state = X xs = [getproperty(X, Symbol(:x_, 0))] # x_0, x_1, ... for i in 0:d-1 _x_next = getproperty(X, Symbol(:x_, i+1)) setproperty!(dX, Symbol(:x_, i), _x_next) # e.g., dX.x_0 = x_1 push!(xs, _x_next) end dx_d = nothing if auto_diff if x_cmd != nothing error("Do not provide a manual command for mode auto_diff=$(auto_diff)") end # dx_d = -sum(Ks .* xs) + sum([Ks..., I] .* funcs(t)) desired_cmds = funcs(t) dx_d = -sum(Ks .* xs) + sum([Ks..., I] .* desired_cmds) @log x_cmd = desired_cmds[1] else if x_cmd == nothing error("Provide a manual command for mode auto_diff=$(auto_diff)") end dx_d = -sum(Ks .* xs) + Ks[1]*x_cmd @log x_cmd end setproperty!(dX, Symbol(:x_, d), dx_d) end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
483
struct SingleIntegrator <: AbstractEnv end """ Even for scalar integrator, you should put an array of length 1; due to the limitation of in-place method `Dynamics!`. """ function State(env::SingleIntegrator) return function (x::AbstractArray) x end end function Dynamics!(env::SingleIntegrator) @Loggable function dynamics!(dx, x, p, t; u) @assert length(dx) == length(u) @log integral = x @log integrand = u dx .= u end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
2202
""" A two dimensional nonlinear discrete time (DT) system. """ Base.@kwdef struct TwoDimensionalNonlinearDTSystem <: AbstractEnv c = 0.5 d = 1.0 end function State(env::TwoDimensionalNonlinearDTSystem) return function (x1, x2) ComponentArray(x1=x1, x2=x2) end end function V1(env::TwoDimensionalNonlinearDTSystem) return function (x) if x > 0 ans = x^(1/4) else ans = x^4 end ans end end function Dynamics!(env::TwoDimensionalNonlinearDTSystem) (; c, d) = env @Loggable function dynamics!(dx, x, p, t; u) (; x1, x2) = x @log state = x @log input = u dx.x1 = c*(x1 + x2) # x1_next = dx.x1 dx.x2 = c*x2 + u[1] # x2_next = dx.x2 @onlylog next_state = dx end end function CubicSolution(env::TwoDimensionalNonlinearDTSystem) (; c, d) = env return function (x2) a = ( (cbrt(sqrt(3)*sqrt(27*c^2*x2^2 + 8) + 9*c*x2) / 3^(2/3)) - (2 / (cbrt(3) * cbrt(sqrt(3)*sqrt(27*c^2*x2^2 + 8) + 9*c*x2))) ) # solve a^3 + 2a - 2*c*x2 for a ∈ ℝ end end function RunningCost(env::TwoDimensionalNonlinearDTSystem) (; c, d) = env return function (x, u) (; x1, x2) = x dx = copy(x) # will be next state Dynamics!(env)(dx, x, nothing, nothing; u=u) a = CubicSolution(env)(x2) r̄ = ( (3/4)*a^4 + a^2 - d*V1(env)(dx.x1) + d*V1(env)(x1) + (1-c^2)*x2^2 ) # for V(x) = d*sqrt(abs(x1)) + x2^2 r = r̄ + (1/4)*u[1]^4 end end function OptimalValue(env::TwoDimensionalNonlinearDTSystem) (; c, d) = env return function (x) (; x1, x2) = x d*V1(env)(x1) + x2^2 end end function OptimalQValue(env::TwoDimensionalNonlinearDTSystem) return function (x, u) dx = copy(x) Dynamics!(env)(dx, x, nothing, nothing; u=u) OptimalValue(env)(dx) + RunningCost(env)(x, u) # V(x_next) + r(x, u) end end function OptimalControl(env::TwoDimensionalNonlinearDTSystem) return function (x) (; x2) = x a = CubicSolution(env)(x2) -a end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1589
""" A two dimensional nonlinear oscillator introduced in [1]. Note that the system is constructed by converse HJB method [2]. # References [1] J. A. Primbs, “Nonlinear Optimal Control: A Receding Horizon Approach,” California Institute of Technology, Pasadena, California, 1999. [2] J. Doyle, J. A. Primbs, B. Shapiro, and V. Nevistic, “Nonlinear Games: Examples and Counterexamples,” in Proceedings of 35th IEEE Conference on Decision and Control, Kobe, Japan, 1996, vol. 4, pp. 3915–3920. doi: 10.1109/CDC.1996.577292. """ struct TwoDimensionalNonlinearOscillator <: AbstractEnv end function State(env::TwoDimensionalNonlinearOscillator) return function (x1, x2) ComponentArray(x1=x1, x2=x2) end end function Dynamics!(env::TwoDimensionalNonlinearOscillator) @Loggable function dynamics!(dx, x, p, t; u) (; x1, x2) = x @log state = x @log input = u dx.x1 = x2 dx.x2 = ( -x1 * (π/2 + atan(5*x1)) - (5*x1^2)/(2*(1+25*x1^2)) + 4*x2 + 3*u[1] ) end end function RunningCost(env::TwoDimensionalNonlinearOscillator) return function (x, u) (; x1, x2) = x r = x2^2 + u[1]^2 end end function OptimalValue(env::TwoDimensionalNonlinearOscillator) return function (x) (; x1, x2) = x V_star = x1^2 * (π/2 + atan(5*x1)) + x2^2 end end function OptimalControl(env::TwoDimensionalNonlinearOscillator) return function (x) (; x1, x2) = x u_star = [-3*x2] # make it vector end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1450
""" # References [1] T. Bian and Z.-P. Jiang, “Value Iteration, Adaptive Dynamic Programming, and Optimal Control of Nonlinear Systems,” in 2016 IEEE 55th Conference on Decision and Control (CDC), Las Vegas, NV, USA, Dec. 2016, pp. 3375–3380. doi: 10.1109/CDC.2016.7798777. """ struct TwoDimensionalNonlinearPolynomialSystem <: AbstractEnv end function State(env::TwoDimensionalNonlinearPolynomialSystem) return function (x1::Real=-2.9, x2::Real=-2.9) ComponentArray(x1=x1, x2=x2) end end function Dynamics!(env::TwoDimensionalNonlinearPolynomialSystem) @Loggable function dynamics!(dx, x, p, t; u) @assert length(u) == 1 @log state = x @log input = u _u = u[1] # Real or Array (; x1, x2) = x dx.x1 = -(1/2)*x1^3 - x1 - 2*x2 dx.x2 = (1/8)*x2^3 - x2 + (1/2)*_u^3 nothing end end function OptimalControl(env::TwoDimensionalNonlinearPolynomialSystem) return function (x::ComponentArray, p, t) (; x1, x2) = x -x2 end end function OptimalValue(env::TwoDimensionalNonlinearPolynomialSystem) return function (x::ComponentArray) (; x1, x2) = x x1^2 + x2^2 end end function RunningCost(env::TwoDimensionalNonlinearPolynomialSystem) return function (x::ComponentArray, _u) @assert length(_u) == 1 u = _u[1] # Real or Array (; x1, x2) = x x1^4 + 2*(x1+x2)^2 + (3/4)*u^4 end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
262
include("SingleIntegrator.jl") include("LinearSystem.jl") include("MultipleEnvs.jl") include("ReferenceModel.jl") include("TwoDimensionalNonlinearOscillator.jl") include("TwoDimensionalNonlinearPolynomialSystem.jl") include("TwoDimensionalNonlinearDTSystem.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
4653
""" # References - Controller (it may be modified in this implementation) [1] G. P. Falconi and F. Holzapfel, “Adaptive Fault Tolerant Control Allocation for a Hexacopter System,” Proc. Am. Control Conf., vol. 2016-July, pp. 6760–6766, 2016. - Reference model (e.g., xd, vd, ad, ad_dot, ad_ddot) [2] S. J. Su, Y. Y. Zhu, H. R. Wang, and C. Yun, “A Method to Construct a Reference Model for Model Reference Adaptive Control,” Adv. Mech. Eng., vol. 11, no. 11, pp. 1–9, 2019. # NOTICE - (Tracking control) Add the argument `pos_cmd_func` (a function of time such that (t) -> position(t) ∈ ℝ^3) of constructor, please do not add the argument `pos_cmd` in the inner function of `Dynamics!(env::BacksteppingPositionController)`. - (Set-point control) Do not add the argument `pos_cmd_func` (a function of time such that (t) -> position(t) ∈ ℝ^3) of constructor, please add the argument `pos_cmd` in the inner function of `Dynamics!(env::BacksteppingPositionController)`. """ struct BacksteppingPositionController <: AbstractEnv Ref_model Ap Bp P Kp Kt Kω function BacksteppingPositionController( m::Real; pos_cmd_func=nothing, Kx=m*1*diagm(ones(3)), # position Kv=m*1*1.82*diagm(ones(3)), # velocity Kt=4*diagm(ones(3)), # thrust Kω=20*diagm(ones(3)), # angular velocity ) @assert m > 0 # from (s+5)^5 = s^5 + 25s^4 + ... (for **faster response**) Ks = [] push!(Ks, Diagonal(3125*ones(3))) push!(Ks, Diagonal(3125*ones(3))) push!(Ks, Diagonal(1250*ones(3))) push!(Ks, Diagonal(250*ones(3))) push!(Ks, Diagonal(25*ones(3))) auto_diff = pos_cmd_func == nothing ? false : true Ref_model = ReferenceModel(length(Ks)-1, Ks, auto_diff, pos_cmd_func) Kp = hcat(Kx, Kv) Q = diagm(1*ones(6)) # reference model Ap = [zeros(3, 3) Matrix(I, 3, 3); -(1/m)*Kx -(1/m)*Kv] Bp = [zeros(3, 3); (1/m)*Matrix(I, 3, 3)] P = MatrixEquations.lyapc(Ap, Q) new(Ref_model, Ap, Bp, P, Kp, Kt, Kω) end end """ # Notes ref_model.x_0 = xd ref_model.x_1 = vd ref_model.x_2 = ad ref_model.x_3 = ȧd ref_model.x_4 = äd """ function State(controller::BacksteppingPositionController) (; Ref_model) = controller return function (pos0, m, g) @assert m > 0 ref_model = State(Ref_model)(pos0) Td = m*g ComponentArray(ref_model=ref_model, Td=Td) end end function Dynamics!(controller::BacksteppingPositionController) (; Ref_model) = controller @Loggable function dynamics!(dX, X, p, t; pos_cmd=nothing, Ṫd) @log state = X Dynamics!(Ref_model)(dX.ref_model, X.ref_model, (), t; x_cmd=pos_cmd) # be careful; parameter = () dX.Td = Ṫd nothing end end """ Several functions are exported from `utils.jl`, e.g., T_u_inv(T). """ function Command(controller::BacksteppingPositionController) (; Ap, Bp, P, Kp, Kt, Kω) = controller T_u_inv(T) = [ 0 1/T 0; -1/T 0 0; 0 0 -1] T_u_inv_dot(T, Ṫ) = [ 0 -Ṫ/T^2 0; Ṫ/T^2 0 0; 0 0 0] T_ω(T) = [0 -T 0; T 0 0; 0 0 0] skew(x) = [ 0 -x[3] x[2]; x[3] 0 -x[1]; -x[2] x[1] 0] return function(p, v, R, ω, xd, vd, ad, ȧd, äd, Td, m::Real, J, g::Real,) ex = xd - p ev = vd - v ep = vcat(ex, ev) # u1 g_vec = [0, 0, g] u1 = m*(ad - g_vec) + Kp*ep zB = R * [0, 0, 1] td = -Td * zB et = u1 - td ėp = Ap*ep + Bp*et u̇1 = m*ȧd + Kp*ėp T = Td # TODO: no lag # u2 u2 = T_u_inv(T) * R' * (2*Bp' * P * ep + u̇1 + Kt*et) Ṫd = u2[end] # third element Ṫ = Ṫd # TODO: no lag żB = -R * T_ω(1.0) * ω ėt = u̇1 + u2[end]*zB + Td*żB ëp = Ap*ėp + Bp*ėt ü1 = m*äd + Kp*ëp Ṙ = -skew(ω) * R' u̇2 = ( (T_u_inv_dot(T, Ṫ)*R' + T_u_inv(T)*Ṙ) * (2*Bp'*P*ep + u̇1 + Kt*et) + T_u_inv(T) * R' * (2*Bp'*P*ėp + ü1 + Kt*ėt) ) ω̇d = [1 0 0; 0 1 0; 0 0 0] * u̇2 ωd = [u2[1:2]..., 0] eω = ωd - ω Md = cross(ω, J*ω) + J*(T_ω(T)'*R'*et + ω̇d + Kω*eω) νd = vcat(Td, Md) e = [ep; et; eω] νd, Ṫd, e, zB, T end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1033
struct InputAffinePositionCBF <: AbstractEnv f g h α1 α2 end """ p in R^3 v in R^3 u: Convex.Variable(m) """ function generate_constraint(cbf::InputAffinePositionCBF, p, v, u) (; f, g, h, α1, α2) = cbf ∇h = p -> ForwardDiff.gradient(h, p) h1 = (p, v) -> ∇h(p)' * v + α1(h(p)) ∇h1_p = (p, v) -> ForwardDiff.gradient(p -> h1(p, v), p) ∇h1_v = (p, v) -> ForwardDiff.gradient(v -> h1(p, v), v) h2 = (p, v) -> ∇h1_p(p, v)' * v + ∇h1_v(p, v)' * (f(p, v)+g(p, v)*u) + α2(h1(p, v)) constraint = h2(p, v) >= 0.0 end """ p in R^3 v in R^3 u_nom: nominal control input, in R^m """ function Command( cbf::InputAffinePositionCBF, u, p, v, u_nom, constraints; solver=ECOS.Optimizer, silent_solver=true, ) cbf_constraint = generate_constraint(cbf, p, v, u) constraints = [constraints..., cbf_constraint] problem = minimize(sumsquares(u - u_nom), constraints) solve!(problem, solver; silent_solver=silent_solver) return reshape(u.value, size(u_nom)...) end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
7609
""" Geometric tracking controller for multicopter [1]. # References [1] T. Lee, M. Leok, and N. H. McClamroch, “Geometric Tracking Control of a Quadrotor UAV on SE(3),” in 49th IEEE Conference on Decision and Control (CDC), Atlanta, GA, Dec. 2010. doi: 10.1109/CDC.2010.5717652. """ Base.@kwdef struct GeometricTrackingController <: AbstractEnv k_p = 5 k_v = 5 k_R = deg2rad(5) k_ω = deg2rad(5) ω_n_v = 5e2 ζ_v = 0.99 ω_n_a = 5e2 ζ_a = 0.99 end Base.@kwdef struct InnerLoopGeometricTrackingController <:AbstractEnv k_R = deg2rad(5) k_ω = deg2rad(5) ω_n_f = 1e2 ζ_f = 0.99 ω_n_f_dot = 1e2 ζ_f_dot = 0.99 end function FSimBase.State(controller::InnerLoopGeometricTrackingController) return function ( z1_f=zeros(3), z2_f=zeros(3), z1_f_dot=zeros(3), z2_f_dot=zeros(3), ) X0 = ComponentArray( z1_f=z1_f, z2_f=z2_f, z1_f_dot=z1_f_dot, z2_f_dot=z2_f_dot, ) return X0 end end function FSimBase.Dynamics!(controller::InnerLoopGeometricTrackingController) (; ω_n_f, ω_n_f_dot, ζ_f, ζ_f_dot) = controller @Loggable function dynamics!(dX, X, params, t; f) (; z1_f, z2_f, z1_f_dot, z2_f_dot) = X @log z1_f @log z2_f @log z1_f_dot @log z2_f_dot @log f dX.z1_f = ω_n_f * z2_f dX.z2_f = -2*ζ_f*ω_n_f*z2_f - ω_n_f*(z1_f-f) dX.z1_f_dot = ω_n_f_dot * z2_f_dot dX.z2_f_dot = -2*ζ_f_dot*ω_n_f_dot*z2_f_dot - ω_n_f_dot*(z1_f_dot-ω_n_f*z2_f) end end function Command( controller::InnerLoopGeometricTrackingController, R, ω; b_1_d, b_1_d_dot, b_1_d_ddot, _b_3_d, _b_3_d_dot, _b_3_d_ddot, J, ) (; k_R, k_ω) = controller e_3 = [0, 0, 1] b_3_d = _b_3_d / norm(_b_3_d) b_3_d_dot = _unit_vector_dot(_b_3_d, _b_3_d_dot) b_3_d_ddot = _unit_vector_ddot(_b_3_d, _b_3_d_dot, _b_3_d_ddot) _b_2_d = cross(b_3_d, b_1_d) _b_2_d_dot = cross(b_3_d_dot, b_1_d) + cross(b_3_d, b_1_d_dot) _b_2_d_ddot = cross(b_3_d_ddot, b_1_d) + cross(b_3_d_dot, b_1_d_dot) + cross(b_3_d, b_1_d_ddot) b_2_d = _b_2_d / norm(_b_2_d) b_2_d_dot = _unit_vector_dot(_b_2_d, _b_2_d_dot) b_2_d_ddot = _unit_vector_ddot(_b_2_d, _b_2_d_dot, _b_2_d_ddot) R_d = [cross(b_2_d, b_3_d) b_2_d b_3_d] R_d_dot = [(cross(b_2_d_dot, b_3_d) + cross(b_2_d, b_3_d_dot)) b_2_d_dot b_3_d_dot] R_d_ddot = [(cross(b_2_d_ddot, b_3_d) + cross(b_2_d_dot, b_3_d_dot) + cross(b_2_d, b_3_d_ddot)) b_2_d_ddot b_3_d_ddot] ω_d_hat = R_d' * R_d_dot # guessed from the equation between [1, Eq. (10)] and [1, Eq. (11)]. ω_d = _vee(ω_d_hat) ω_d_dot_hat = R_d_dot' * R_d_dot + R_d' * R_d_ddot ω_d_dot = _vee(ω_d_dot_hat) e_R = 0.5 * _vee(R_d'*R - R'*R_d) e_ω = ω - R'*R_d*ω_d f = dot(_b_3_d, R*e_3) M = -k_R*e_R - k_ω*e_ω + cross(ω, J*ω) - J*(_hat(ω) * R' * R_d * ω_d - R' * R_d * ω_d_dot) ν = [f, M...] return ν end Base.@kwdef struct OuterLoopGeometricTrackingController <:AbstractEnv k_p = 5 k_v = 5 end function Command( controller::OuterLoopGeometricTrackingController, p, v; p_d, v_d, a_d, m, g, ) (; k_p, k_v) = controller e_3 = [0, 0, 1] e_p = p - p_d e_v = v - v_d _b_3_d = -(-k_p*e_p - k_v*e_v - m*g*e_3 + m*a_d) # desired force vector return _b_3_d end """ cross(x, y) = _hat(x) * y """ function _hat(a) a1, a2, a3 = a return [0 -a3 a2; a3 0 -a1; -a2 a1 0] end """ Inverse map of _hat """ function _vee(A) a1 = A[3, 2] a2 = A[1, 3] a3 = A[2, 1] return [a1, a2, a3] end """ y = ||x|| y_dot = ? """ function _norm_dot(x, x_dot) y = norm(x) y_dot = (x'*x_dot) / y return y_dot end """ y = ||x|| y_ddot = ? """ function _norm_ddot(x, x_dot, x_ddot) y = norm(x) y_dot = _norm_dot(x, x_dot) y_ddot = (1/y) * (x_dot'*x_dot + x'*x_ddot - y_dot^2) return y_ddot end """ y = x / ||x|| y_dot = ? """ function _unit_vector_dot(x, x_dot) y = (1/norm(x)) * x y_dot = (1/norm(x)) * (x_dot - _norm_dot(x, x_dot)*y) return y_dot end """ y = x / ||x|| y_ddot = ? """ function _unit_vector_ddot(x, x_dot, x_ddot) y = (1/norm(x)) * x y_dot = _unit_vector_dot(x, x_dot) y_ddot = (1/norm(x)) * (x_ddot - _norm_ddot(x, x_dot, x_ddot)*y - 2*_norm_dot(x, x_dot)*y_dot) return y_ddot end function FSimBase.State(controller::GeometricTrackingController) return function ( z1_v=zeros(3), z2_v=zeros(3), z1_a=zeros(3), z2_a=zeros(3), ) X0 = ComponentArray( z1_v=z1_v, z2_v=z2_v, z1_a=z1_a, z2_a=z2_a, ) return X0 end end """ Time derivative estimator """ function FSimBase.Dynamics!(controller::GeometricTrackingController) (; ω_n_v, ω_n_a, ζ_v, ζ_a) = controller return function (dX, X, params, t; v) (; z1_v, z2_v, z1_a, z2_a) = X dX.z1_v = ω_n_v * z2_v dX.z2_v = -2*ζ_v*ω_n_v*z2_v - ω_n_v*(z1_v-v) dX.z1_a = ω_n_a * z2_a dX.z2_a = -2*ζ_a*ω_n_a*z2_a - ω_n_a*(z1_a-ω_n_v*z2_v) end end """ R is defined as the rotation matrix in [1, Eqs.(3), (4)]. Please check if it is the transpose of the rotation matrix defined in FSimZoo multicopters. # Notes When obtaining R_d_dot and ω_d_dot, one may need to obtain the derivative of b_3_d, which contains e_v. This implies that we need to obtain acceleration (a=v_dot) to get the control input f (total thrust), but the acceleration is induced by f, which results in algebraic loop. Therefore, the a_d and higher-order derivatives are obtained from derivative filters. """ function Command( controller::GeometricTrackingController, p, v, R, ω; a, a_dot, # estimated p_d, v_d, a_d, a_d_dot, a_d_ddot, b_1_d, b_1_d_dot, b_1_d_ddot, m, g, J, ) (; k_p, k_v, k_R, k_ω) = controller e_3 = [0, 0, 1] e_p = p - p_d e_v = v - v_d e_a = a - a_d # See Notes e_a_dot = a_dot - a_d_dot # See Notes _b_3_d = -(-k_p*e_p - k_v*e_v - m*g*e_3 + m*a_d) _b_3_d_dot = -(-k_p*e_v - k_v*e_a + m*a_d_dot) _b_3_d_ddot = -(-k_p*e_a - k_v*e_a_dot + m*a_d_ddot) b_3_d = _b_3_d / norm(_b_3_d) b_3_d_dot = _unit_vector_dot(_b_3_d, _b_3_d_dot) b_3_d_ddot = _unit_vector_ddot(_b_3_d, _b_3_d_dot, _b_3_d_ddot) _b_2_d = cross(b_3_d, b_1_d) _b_2_d_dot = cross(b_3_d_dot, b_1_d) + cross(b_3_d, b_1_d_dot) _b_2_d_ddot = cross(b_3_d_ddot, b_1_d) + cross(b_3_d_dot, b_1_d_dot) + cross(b_3_d, b_1_d_ddot) b_2_d = _b_2_d / norm(_b_2_d) b_2_d_dot = _unit_vector_dot(_b_2_d, _b_2_d_dot) b_2_d_ddot = _unit_vector_ddot(_b_2_d, _b_2_d_dot, _b_2_d_ddot) R_d = [cross(b_2_d, b_3_d) b_2_d b_3_d] R_d_dot = [(cross(b_2_d_dot, b_3_d) + cross(b_2_d, b_3_d_dot)) b_2_d_dot b_3_d_dot] R_d_ddot = [(cross(b_2_d_ddot, b_3_d) + cross(b_2_d_dot, b_3_d_dot) + cross(b_2_d, b_3_d_ddot)) b_2_d_ddot b_3_d_ddot] ω_d_hat = R_d' * R_d_dot # guessed from the equation between [1, Eq. (10)] and [1, Eq. (11)]. ω_d = _vee(ω_d_hat) ω_d_dot_hat = R_d_dot' * R_d_dot + R_d' * R_d_ddot ω_d_dot = _vee(ω_d_dot_hat) e_R = 0.5 * _vee(R_d'*R - R'*R_d) e_ω = ω - R'*R_d*ω_d f = dot(_b_3_d, R*e_3) M = -k_R*e_R - k_ω*e_ω + cross(ω, J*ω) - J*(_hat(ω) * R' * R_d * ω_d - R' * R_d * ω_d_dot) ν = [f, M...] end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
833
abstract type AbstractLQR <: AbstractController end """ Infinite-horizon continuous-time linear quadratic regulator (LQR). """ struct LQR <: AbstractLQR A B Q R end function RunningCost(lqr::LQR) (; Q, R) = lqr return function (x, u) x'*Q*x + u'*R*u end end function ARE_solution(lqr::LQR) (; A, B, Q, R) = lqr P, _, _ = MatrixEquations.arec(A, B*inv(R)*B', Q) P end function optimal_gain(lqr::LQR) (; B, R) = lqr P = ARE_solution(lqr) K = inv(R) * B' * P end """ Minimise J = ∫ (x' Q x + u' R u) from 0 to ∞ """ function Command(lqr::LQR) K = optimal_gain(lqr) return function (x) -K*x end end function solutions(lqr::LQR) P = ARE_solution(lqr) K = optimal_gain(lqr) optimal_controller = Command(lqr) P, K, optimal_controller end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1661
""" Proportional-integral-derivative (PID) controller. # Notes The derivative term is obtained via second-order filter. For more details, see [1] and singular perturbation theory. # References [1] J. A. Farrell, M. Polycarpou, M. Sharma, and W. Dong, “Command Filtered Backstepping,” IEEE Transactions on Automatic Control, vol. 54, no. 6, pp. 1391–1395, Jun. 2009, doi: 10.1109/TAC.2009.2015562. """ struct PID <: AbstractEnv K_P K_I K_D ω_n ζ windup_limit function PID(K_P, K_I, K_D; ω_n=1e1, ζ=5e-1, windup_limit=Inf) @assert windup_limit > 0.0 @assert ω_n > 0.0 @assert ζ > 0.0 new(K_P, K_I, K_D, ω_n, ζ, windup_limit) end end """ ∫e: integral of the error ê: the estimate of the error ė̂: the estimate of the error rate """ function State(controller::PID) function state(; ∫e=zeros(1), ê=zeros(1), ė̂=zeros(1)) ComponentArray(∫e=∫e, ê=ê, ė̂=ė̂) end end function Dynamics!(controller::PID) (; ω_n, ζ, windup_limit) = controller @Loggable function dynamics!(dx, x, p, t; e) @assert !(typeof(e) <: Number) # make sure that `e` is a 1-d array (; ∫e, ê, ė̂) = x @onlylog e, ∫e, ê, ė̂ if norm(∫e) < windup_limit dx.∫e .= e elseif norm(∫e) > windup_limit && all(sign.(e) .* sign.(∫e) .< zero.(e)) dx.∫e .= e else dx.∫e .= zero.(e) end dx.ê .= ω_n*ė̂ dx.ė̂ = -2*ζ*ω_n*ė̂ - ω_n*(ê - e) end end function Command(controller::PID) (; K_P, K_I, K_D) = controller function command(e, ∫e, ė̂) -(K_P*e + K_I*∫e + K_D*ė̂) end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
141
include("BacksteppingPositionController.jl") include("GeometricTrackingController.jl") include("LQR.jl") include("PID.jl") include("CBF.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
2129
""" Wing-rock phenomenon in the roll motion of slendar delta wings [1]. # Notes ## Nondimensional values According to [2], the time, state, and control input of this model are nondimensional. But here, it is used as time [s], state [rad, rad/s]. ## Input constraint Input constraint in [3] is used. ## Ideal parameters The default ideal parameters, W_true, are set as the specific model obtained at the angle of attack of 25 degrees in [1]. Note that the ideal parameters in [2] are (1000 x the ideal parameters in [1]). # Refs [1] J. M. Elzebda, A. H. Nayfeh, and D. T. Mook, “Development of an analyt- ical model of wing rock for slender delta wings,” J. Aircr., vol. 26, no. 8, pp. 737–743, 1989. [2] N. Cho, H.-S. Shin, Y. Kim, and A. Tsourdos, “Composite Model Reference Adaptive Control with Parameter Convergence Under Finite Excitation,” IEEE Trans. Automat. Contr., vol. 63, no. 3, pp. 811–818, Mar. 2018, doi: 10.1109/TAC.2017.2737324. [3] J. H. Tarn and F. Y. Hsu, “Fuzzy Control of Wing Rock for Slender Delta wings,” in 1993 American Control Conference, San Francisco, CA, USA: IEEE, Jun. 1993, pp. 1159–1161. doi: 10.23919/ACC.1993.4793048. """ Base.@kwdef struct ElzebdaWingRock <: AbstractWingRock W_true = 1e-3 * [-18.59521, 15.162375, -62.45153, 9.54708, 21.45291] u_min=-1.75 u_max=+1.75 end function State(env::ElzebdaWingRock) return function (x1=0.0, x2=0.0) ComponentArray(x1=x1, x2=x2) end end """ Out-of-place dynamics """ function Dynamics(env::ElzebdaWingRock) (; W_true) = env return function (x, p, t; u) (; x1, x2) = x basis = [x1, x2, abs(x1)*x2, abs(x2)*x2, x1^3] Δ = W_true' * basis dx1 = x2 dx2 = u + Δ dx = State(env)(dx1, dx2) return dx end end function Dynamics!(env::ElzebdaWingRock) (; u_min, u_max) = env @Loggable function dynamics!(dx, x, p, t; u) (; x1, x2) = x u_saturated = clamp.(u, u_min, u_max) @log state = x @log input = ComponentArray(u_cmd=u, u_applied=u_saturated) dx .= Dynamics(env)(x, p, t; u=u_saturated) end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1526
""" Wing-rock phenomenon in the roll motion of slendar delta wings at AoA=25 deg [1]. # Notes x = [x1, x2]^T x1 = ϕ (roll angle) x2 = ϕ̇ (roll rate) # Refs [1] J. H. Tarn and F. Y. Hsu, “Fuzzy Control of Wing Rock for Slender Delta wings,” in 1993 American Control Conference, San Francisco, CA, USA: IEEE, Jun. 1993, pp. 1159–1161. doi: 10.23919/ACC.1993.4793048. """ Base.@kwdef struct TarnWingRock <: AbstractWingRock a1=-0.05686 a2=+0.03254 a3=+0.07334 a4=-0.35970 a5=+1.46810 C1=0.354 C2=0.001 u_min=-1.75 u_max=+1.75 end function State(env::TarnWingRock) return function (x1=0.0, x2=0.0) ComponentArray(x1=x1, x2=x2) end end """ Out-of-place dynamics """ function Dynamics(env::TarnWingRock) (; a1, a2, a3, a4, a5, C1, C2) = env return function (x, p, t; u) (; x1, x2) = x ω_squares = -C1*a1 μ1 = C1*a2 - C2 b1 = C1*a3 μ2 = C1*a4 b2 = C1*a5 basis = [x1, x2, x1^2*x2, x1*x2^2, x1^3] coeff = [-ω_squares, μ1, μ2, b2, b1] Δ = coeff' * basis dx1 = x2 dx2 = u + Δ dx = State(env)(dx1, dx2) return dx end end function Dynamics!(env::TarnWingRock) (; u_min, u_max) = env @Loggable function dynamics!(dx, x, p, t; u) (; x1, x2) = x u_saturated = clamp.(u, u_min, u_max) @log state = x @log input = ComponentArray(u_cmd=u, u_applied=u_saturated) dx .= Dynamics(env)(x, p, t; u=u_saturated) end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
109
abstract type AbstractWingRock <: AbstractEnv end include("ElzebdaWingRock.jl") include("TarnWingRock.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
2089
struct BacksteppingPositionController_StaticAllocator_Multicopter <: AbstractEnv controller::BacksteppingPositionController allocator::StaticAllocator multicopter::Multicopter end # outer constructor function BacksteppingPositionController_StaticAllocator_Multicopter(pos_cmd_func=nothing; controller_kwargs...) multicopter = LeeHexacopter() (; m, B) = multicopter controller = BacksteppingPositionController(m; pos_cmd_func=pos_cmd_func, controller_kwargs...) allocator = PseudoInverseAllocator(B) env = BacksteppingPositionController_StaticAllocator_Multicopter(controller, allocator, multicopter) end function State(env::BacksteppingPositionController_StaticAllocator_Multicopter) (; controller, allocator, multicopter) = env (; m, g) = multicopter function state(; args_multicopter=()) x_multicopter = State(multicopter)(args_multicopter...) pos0 = copy(x_multicopter.p) x_controller = State(controller)(pos0, m, g) ComponentArray(multicopter=x_multicopter, controller=x_controller) end end function Dynamics!(env::BacksteppingPositionController_StaticAllocator_Multicopter) (; controller, allocator, multicopter) = env (; m, J, g) = multicopter @Loggable function dynamics!(dx, x, params, t; pos_cmd=nothing) (; p, v, q, ω) = x.multicopter (; ref_model, Td) = x.controller xd, vd, ad, ȧd, äd = ref_model.x_0, ref_model.x_1, ref_model.x_2, ref_model.x_3, ref_model.x_4 R = quat2dcm(q) νd, Ṫd, _... = Command(controller)( p, v, R, ω, xd, vd, ad, ȧd, äd, Td, m, J, g, ) u_cmd = Command(allocator)(νd) @nested_log :multicopter _Dynamics!(multicopter)(dx.multicopter, x.multicopter, (), t; u=u_cmd) @nested_log :controller Dynamics!(controller)(dx.controller, x.controller, (), t; pos_cmd=pos_cmd, Ṫd=Ṫd) @nested_log :controller νd end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
112
include("linear_and_integrator.jl") include("backstepping_position_controller_static_allocator_multicopter.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1001
""" LinearSystem + SingleIntegrator """ function LinearSystem_SingleIntegrator(args_linearsystem) linearsystem = LinearSystem(args_linearsystem...) integ = SingleIntegrator() linearsystem, integ end """ # Notes - `r` denotes integrand of `integ`. """ function State(linearsystem::LinearSystem, integ::SingleIntegrator) return function (x0_linearsystem, x0_integrator=[0.0]) x_linearsystem = State(linearsystem)(x0_linearsystem) x_integrator = State(integ)(x0_integrator) ComponentArray(x=x_linearsystem, ∫r=x_integrator) end end """ # Notes running_cost: integrand; function of (x, u) """ function Dynamics!(linearsystem::LinearSystem, integ::SingleIntegrator, running_cost::Function) @Loggable function dynamics!(dX, X, p, t; u) (; x) = X @nested_log :linearsystem Dynamics!(linearsystem)(dX.x, X.x, nothing, t; u=u) r = running_cost(x, u) @nested_log :integ Dynamics!(integ)(dX.∫r, X.∫r, nothing, t; u=r) end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
3583
""" # Refs [1] C. Mracek and J. Cloutier, “Full Envelope Missile Longitudinal Autopilot Design Using the State-Dependent Riccati Equation Method,” Guidance, Navigation, and Control Conference, Aug. 1997, pp. 1697-1705, doi:10.2514/6.1997-3767. """ Base.@kwdef struct MissileLongitudinal grav = 9.81 # Physical Configuration (Table 3) S_ref = 0.0409 # Reference Area [m] (0.44 ft^2) d_ref = 0.2286 # Reference Distance [m] (0.75 ft) mass = 204.02 # Mass [kg] (13.98 slug) I_yy = 247.438 # Moment of Inertia [kg * m^2] (182.5 sulg-ft^2) # Aerodynamic coefficients (Table 1 in Ref.) aₐ = 0.3 aₘ = 40.44 aₙ = 19.373 bₘ = -64.015 bₙ = -31.023 cₘ = 2.922 cₙ = -9.717 dₘ = -11.803 dₙ = -1.948 eₘ = -1.719 end """ α: Angle of attack [rad] q : Pitch rate [rad/s] mach : Mach number -] γ : Flight path angle [rad] """ function State(env::MissileLongitudinal) return function (α=deg2rad(0), q=deg2rad(0), M=4.0, γ=deg2rad(0), h=10_000) ComponentArray(α=α, q=q, M=M, γ=γ, h=h) end end function density(h) # Atmospheric coefficients (Table 2 in Ref.) tro_alt = 10972.8 # troposphere boundary [m] (36000.0 ft) str_alt = 20116.8 # stratosphere boundary [m] (66000.0 ft) ρ₀sl = 1.1455 # Air density at sea level [kg/m^3] (2.377e-3 lb-s^2/ft^2) ρ₀tr = 0.3415 # Air density at troposphere boundary [kg/m^3] (0.7086e-3 lb-s^2/ft^2) Kρsl = 1.1103e-4 # [1/m] (3.36174e-5 1/ft) Kρtr = 1.5760e-4 # [1/m] (4.80377e-5 1/ft) @assert h >= 0.0 #, "Altitude must be greater than zero" @assert h <= str_alt #, "Out of operating altitude range" if h <= tro_alt return ρ₀sl * exp(-Kρsl * h) else return ρ₀tr * exp(-Kρtr*(h - tro_alt)) end end function sonic_speed(h) # Atmospheric coefficients (Ttable 2 in Ref.) tro_alt = 10972.8 # troposphere boundary [m] (36000.0 ft) str_alt = 20116.8 # stratosphere boundary [m] (66000.0 ft) asl = 340.2787 # Sonic speed at the sea level [m/s] (1116.4 ft/sec) atr = 295.0769 # Sonic speed at the troposphere boundary [m/s] (968.1 ft/sec) Ka = 1.0358e-2 # [1/m] (0.00410833 1/ft) @assert h >= 0.0 #, "Altitude must be greater than zero" @assert h <= str_alt #, "Out of operating altitude range" if h <= tro_alt return asl - Ka * h else return atr end end function Dynamics(env::MissileLongitudinal) (; grav, S_ref, d_ref, mass, I_yy, aₐ, aₘ, aₙ, bₘ, bₙ, cₘ, cₙ, dₘ, dₙ, eₘ, ) = env function (x, params, t; δ) (; α, q, M, γ, h) = x Ca() = aₐ Cz(α, M, δ) = (aₙ*α^3 + bₙ* α * abs(α) + cₙ * (2.0 - M/3.0)*α +dₙ *δ) Cm(α, M, δ, q) = (aₘ*α^3 + bₘ* α * abs(α) + cₘ * (-7.0 + 8.0*M/3.0) *α +dₘ *δ + eₘ*q) Vₛ = sonic_speed(h) ρ = density(h) α_dot = ρ * Vₛ * M * S_ref / (2.0 * mass) * (Cz(α, M, δ) * cos(α) - Ca() * sin(α)) + grav/(Vₛ * M) *cos(γ)+ q q_dot = ρ * Vₛ^2 * M^2 * S_ref * d_ref / (2.0 * I_yy) * Cm(α, M, δ, q) M_dot = ρ * Vₛ * M^2 * S_ref / (2.0 * mass) * (Cz(α, M, δ) * sin(α) + Ca() * cos(α)) - grav/Vₛ * sin(γ) γ_dot = -ρ * Vₛ * M * S_ref / (2.0 * mass) * (Cz(α, M, δ) * cos(α) - Ca() * sin(α)) - grav/(Vₛ * M) * cos(γ) h_dot = M * Vₛ * sin(γ) dx = [α_dot, q_dot, M_dot, γ_dot, h_dot] end end function Dynamics!(env::MissileLongitudinal) dynamics = Dynamics(env) @Loggable function dynamics!(dx, x, params, t; δ) @log state = x @log input = δ dx .= dynamics(x, params, t; δ=δ) end end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
34
include("MissileLongitudinal.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1422
""" # Notes - [1] (quad-+ configuration); see [2]. # References [1] F. A. Goodarzi, D. Lee, and T. Lee, “Geometric Adaptive Tracking Control of a Quadrotor Unmanned Aerial Vehicle on SE(3) for Agile Maneuvers,” Journal of Dynamic Systems, Measurement, and Control, vol. 137, no. 9, p. 091007, Sep. 2015, doi: 10.1115/1.4030419. [2] PX4 Airframes Reference, https://docs.px4.io/master/en/airframes/airframe_reference.html. # Variables u ∈ R^4: rotor forces """ Base.@kwdef struct GoodarziAgileQuadcopter <: Quadcopter J = 1e-2 * [ 5.5711 0.0618 -0.0251; 0.06177 5.5757 0.0101; -0.02502 0.01007 1.05053; ] # kg m^2 l = 0.169 # m kM = 0.1056 # m m = 0.755 # kg g = 9.81 # m / s^2 B = [ 1 1 1 1; -l l 0 0; 0 0 l -l; kM kM -kM -kM] D = diagm(zeros(3)) # actuator limit dim_input = 4 u_min = zeros(dim_input) u_max = 3.2 * ones(dim_input) end function saturate(multicopter::GoodarziAgileQuadcopter, u) (; u_min, u_max) = multicopter u_saturated = clamp.(u, u_min, u_max) end function input_to_force_moment(multicopter::GoodarziAgileQuadcopter, u) (; B) = multicopter ν = B * u end function airframe_reference(multicopter::GoodarziAgileQuadcopter) :quad_plus end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
975
# Quadcopter """ # References [1] F. A. Goodarzi, D. Lee, and T. Lee, “Geometric stabilization of a quadrotor UAV with a payload connected by flexible cable,” in 2014 American Control Conference, Jun. 2014, pp. 4925–4930, doi: 10.1109/ACC.2014.6859419. # Variables p ∈ R^3: inertial position v ∈ R^3: inertial velocity R ∈ so(3): inertial-to-body rotation matrix (R_I2B) ω ∈ R^3: angular rate of body in inertial frame u ∈ R^4: [f, M...] where f ∈ R: total thrust, M ∈ R^3: moment """ Base.@kwdef struct GoodarziQuadcopter <: Quadcopter m = 0.5 # kg J = 1e-2 * Diagonal([0.557, 0.557, 1.050]) # kg m² J_inv = inv(J) g = 9.81 # m/s² D = diagm(zeros(3)) # input limits dim_input = 4 u_min = zeros(dim_input) u_max = (m*g) * ones(dim_input) end function saturate(env::GoodarziQuadcopter, u) (; u_min, u_max) = env u_saturated = clamp.(u, u_min, u_max) end function input_to_force_moment(env::GoodarziQuadcopter, u) ν = u end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1056
""" # References [1] M. Islam, M. Okasha, and M. M. Idres, “Dynamics and control of quadcopter using linear model predictive control approach,” IOP Conf. Ser.: Mater. Sci. Eng., vol. 270, p. 012007, Dec. 2017, doi: 10.1088/1757-899X/270/1/012007. # Variables u ∈ R^4: square of rotor angular speed """ Base.@kwdef struct IslamQuadcopter <: Quadcopter J = Diagonal([7.5e-3, 7.5e-3, 1.3e-2]) # kg m^2 l = 0.23 # m kf = 3.13e-5 # N s^2 kM = 7.5e-7 # N m s^2 m = 0.65 # kg g = 9.81 # m / s^2 B = [kf kf kf kf; 0 -kf 0 kf; kf 0 -kf 0; kM -kM kM -kM] D = diagm(zeros(3)) # drags # kt = Diagonal(0.1*ones(3)) # Ns / m # kr = Diagonal(0.1*ones(3)) # N m s # input limits dim_input = 4 u_min = zeros(dim_input) u_max = (m*g/kf) * ones(dim_input) end function saturate(env::IslamQuadcopter, u) (; u_min, u_max) = env u_saturated = clamp.(u, u_min, u_max) end function input_to_force_moment(env::IslamQuadcopter, u) (; B) = env ν = B * u end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1680
""" # Notes - [1] is modified for hexa-x configuration; see [2]. # References [1] T. Lee, M. Leok, and N. H. McClamroch, “Geometric Tracking Control of a Quadrotor UAV on SE(3),” in 49th IEEE Conference on Decision and Control (CDC), Atlanta, GA, Dec. 2010, pp. 5420–5425. doi: 10.1109/CDC.2010.5717652. [2] PX4 Airframes Reference, https://docs.px4.io/master/en/airframes/airframe_reference.html. [3] M. C. Achtelik, K. M. Doth, D. Gurdan, and J. Stumpf, “Design of a multi rotor MAV with regard to efficiency, dynamics and redundancy,” AIAA Guid. Navig. Control Conf. 2014, no. August, pp. 1–17, 2012, doi: 10.2514/6.2012-4779. [4] https://github.com/fdcl-ftc/fault-tolerant-control/issues/62 # Variables u ∈ R^6: rotor forces """ Base.@kwdef struct LeeHexacopter <: Hexacopter J = diagm([0.0820, 0.0845, 0.1377]) # kg m^2 l = 0.315 # m kM = 8.004e-4 # m m = 4.34 # kg g = 9.81 # m / s^2 B = [ 1 1 1 1 1 1; -l l 0.5*l -0.5*l -0.5*l 0.5*l; 0 0 0.5*sqrt(3)*l -0.5*sqrt(3)*l 0.5*sqrt(3)*l -0.5*sqrt(3)*l; -kM kM -kM kM kM -kM] D = diagm(zeros(3)) # actuator limit dim_input = 6 u_min = zeros(dim_input) u_max = 0.6371 * (m*g) * ones(dim_input) # [3] and [4] end function saturate(multicopter::LeeHexacopter, u) (; u_min, u_max) = multicopter u_saturated = clamp.(u, u_min, u_max) end function input_to_force_moment(multicopter::LeeHexacopter, u) (; B) = multicopter ν = B * u end function airframe_reference(multicopter::LeeHexacopter) :hexa_x end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
1586
""" # Notes - [1] (quad-+ configuration); see [2]. # References [1] T. Lee, M. Leok, and N. H. McClamroch, “Geometric Tracking Control of a Quadrotor UAV on SE(3),” in 49th IEEE Conference on Decision and Control (CDC), Atlanta, GA, Dec. 2010, pp. 5420–5425. doi: 10.1109/CDC.2010.5717652. [2] PX4 Airframes Reference, https://docs.px4.io/master/en/airframes/airframe_reference.html. [3] M. C. Achtelik, K. M. Doth, D. Gurdan, and J. Stumpf, “Design of a multi rotor MAV with regard to efficiency, dynamics and redundancy,” AIAA Guid. Navig. Control Conf. 2014, no. August, pp. 1–17, 2012, doi: 10.2514/6.2012-4779. [4] https://github.com/fdcl-ftc/fault-tolerant-control/issues/62 # Variables u ∈ R^6: rotor forces """ Base.@kwdef struct LeeQuadcopter <: Quadcopter J = diagm([0.0820, 0.0845, 0.1377]) # kg m^2 l = 0.315 # m kM = 8.004e-4 # m m = 4.34 # kg g = 9.81 # m / s^2 B = [ 1 1 1 1; -l l 0 0; 0 0 l -l; kM kM -kM -kM] D = diagm(zeros(3)) # actuator limit dim_input = 4 u_min = zeros(dim_input) u_max = (6/4) * 0.6371 * (m*g) * ones(dim_input) # [3] and [4]; modified for quadcopter end function saturate(multicopter::LeeQuadcopter, u) (; u_min, u_max) = multicopter u_saturated = clamp.(u, u_min, u_max) end function input_to_force_moment(multicopter::LeeQuadcopter, u) (; B) = multicopter ν = B * u end function airframe_reference(multicopter::LeeQuadcopter) :quad_plus end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
73
abstract type Hexacopter <: Multicopter end include("LeeHexacopter.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
4583
# multicopter abstract type Multicopter <: AbstractEnv end """ Common state structure of Multicopter. """ function State(multicopter::Multicopter) return function (p=zeros(3), v=zeros(3), q=[1, 0, 0, 0], ω=zeros(3)) ComponentArray(p=p, v=v, q=q, ω=ω) end end """ Common input saturation (default: not applied) """ function saturate(multicopter::Multicopter, u) # u error("Actuator saturation not applied: `saturate`") end """ Common input to force and moment transformation (default: not applied) """ function input_to_force_moment(multicopter::Multicopter, u) # ν = u error("Transformation of input to force and moment not defined: `input_to_force_moment`") end """ skew(x): ℝ³ → ℝ⁹ such that x×y = skew(x)*y """ function skew(x) [ 0 -x[3] x[2]; x[3] 0 -x[1]; -x[2] x[1] 0] end struct EulerAngleAttitude <: AbstractEnv end function State(env::EulerAngleAttitude) """ η = [ϕ, θ, ψ], ZYX rotation (i.e., DCM = R_X(ϕ)R_Y(θ)R_Z(ψ)) """ function (η=zeros(3)) η end end function Dynamics!(env::EulerAngleAttitude) @Loggable function dynamics!(dη, η, param, t; ω) @log η, ω dη .= euler_angle_dynamics(η; ω) end end function euler_angle_dynamics(η; ω) ϕ, θ, ψ = η H = [ 1 sin(ϕ)*tan(θ) cos(ϕ)*tan(θ); 0 cos(ϕ) -sin(ϕ); 0 sin(ϕ)/cos(θ) cos(ϕ)/cos(θ); ] dη = H * ω end """ [1] MATLAB, https://kr.mathworks.com/help/aeroblks/6dofquaternion.html#mw_f692de78-a895-4edc-a4a7-118228165a58 """ function unit_quaternion_dynamics(q; ω) q_s, q_v = q[1], q[2:4] _ω_s, _ω_v = 0, ω q_ω_s = q_s*_ω_s - dot(q_v, _ω_v) q_ω_v = q_s*_ω_v + _ω_s*q_v + cross(q_v, _ω_v) q_ω = [q_ω_s, q_ω_v...] q_dot = 0.5 * q_ω k = 1 eps = 1 - sum(q .^ 2) q_dot = q_dot + k*eps*q end function angular_velocity_dynamics(ω; J, M) Ω = skew(ω) ω_dot = inv(J) * (-Ω*J*ω + M) end function rotational_dynamics(q, ω; J, M) dq = unit_quaternion_dynamics(q; ω) dω = angular_velocity_dynamics(ω; J, M) vcat(dq, dω) end """ # Variables ## State p ∈ ℝ^3: (inertial) position v ∈ ℝ^3: (inertial) velocity R ∈ so(3): direction cosine matrix (DCM) that maps a vector read in Inertial (I)-coord. to the same vector read in Body (B)-coord. For example, v_B = R*v_I. Or, it can be interpreted as "inverse rotation" from I-frame to B-frame. For example, x̂_I = R'*[1, 0, 0] where x̂_I is the x-axis of B-frame read in I-coord. ω ∈ ℝ^3: angular rate of body frame w.r.t. inertial frame (I to B) ## (Virtual) input f ∈ ℝ: total thrust M ∈ ℝ^3: torque ## Parameters D denotes the drag coefficient matrix [2]. ## BE CAREFUL 1) The default state is changed to unit quaternion from rotation matrix. 2) The definition of rotation matrix (`R`) is now the same as the DCM introduced in [1] (it was the DCM's transpose until v0.10). This is for compatibility with Rotations.jl (rotation matrix from I to B frames). # Reference [1] T. Lee, M. Leok, and N. H. McClamroch, “Geometric Tracking Control of a Quadrotor UAV on SE(3),” in 49th IEEE Conference on Decision and Control (CDC), Atlanta, GA, Dec. 2010, pp. 5420–5425. doi: 10.1109/CDC.2010.5717652. [2] M. Faessler, A. Franchi, and D. Scaramuzza, “Differential Flatness of Quadrotor Dynamics Subject to Rotor Drag for Accurate Tracking of High-Speed Trajectories,” IEEE Robot. Autom. Lett., vol. 3, no. 2, pp. 620–626, Apr. 2018, doi: 10.1109/LRA.2017.2776353. """ function __Dynamics!(multicopter::Multicopter) (; m, g, J, D) = multicopter @Loggable function dynamics!(dX, X, p, t; f, M) e3 = [0, 0, 1] (; p, v, q, ω) = X @onlylog state = X @nested_log :input f, M R = quat2dcm(q) dX.p = v dX.v = -(1/m)*f*R*e3 + g*e3 - R*D*R'*v dqdω = rotational_dynamics(q, ω; J, M) dX.q = dqdω[1:4] dX.ω = dqdω[5:7] end end """ A basic example of dynamics for multicopter considering rotor inputs `u`. You can use the following closure or extend the above __Dynamics! for more general models, e.g., faulted multicopters. """ function _Dynamics!(multicopter::Multicopter) @Loggable function dynamics!(dx, x, p, t; u) @nested_onlylog :input u_cmd = u @nested_log :input u_saturated = saturate(multicopter, u) @nested_log :input ν = input_to_force_moment(multicopter, u_saturated) f, M = ν[1], ν[2:4] @nested_log __Dynamics!(multicopter)(dx, x, (), t; f=f, M=M) end end # multicopters include("quadcopters.jl") include("hexacopters.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
174
abstract type Quadcopter <: Multicopter end include("GoodarziQuadcopter.jl") include("IslamQuadcopter.jl") include("LeeQuadcopter.jl") include("GoodarziAgileQuadcopter.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
200
function ned2enu(p) if length(p) == 3 return [p[2], p[1], -p[3]] else return error("Invalid position") end end function enu2ned(p) ned2enu(p) # actually the same end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
702
""" Euler angle to unit quaternion, corresponding to ZYX rotation (here, RotXYZ). η = [roll, pitch, yaw] q = [s, v1, v2, v3] R ∈ ℝ^(3×3) """ function euler2quat(η) tmp = QuatRotation(RotXYZ(η...)).q q = [tmp.s, tmp.v1, tmp.v2, tmp.v3] end function quat2euler(q) tmp = RotXYZ(QuatRotation(q...)) η = [tmp.theta1, tmp.theta2, tmp.theta3] end function dcm2euler(R) tmp = RotXYZ(RotMatrix{3}(R)) η = [tmp.theta1, tmp.theta2, tmp.theta3] end function euler2dcm(η) RotMatrix{3}(RotXYZ(η...)).mat end function quat2dcm(q) RotMatrix{3}(QuatRotation(q)).mat end function dcm2quat(R) tmp = QuatRotation(RotMatrix{3}(R)).q q = [tmp.s, tmp.v1, tmp.v2, tmp.v3] end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
46
include("ned2enu.jl") include("rotations.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
514
using Test using FSimZoo using FSimBase using LinearAlgebra using Convex function test_InputAffinePositionCBF() f = (p, v) -> zeros(3) + [0, 0, 9.81] g = (p, v) -> I(3) h = p -> -p[3] - (-0.1) # >= 0 α1 = x -> 5*x α2 = x -> 5*x cbf = InputAffinePositionCBF(f, g, h, α1, α2) # filter p = zeros(3) v = zeros(3) u_nom = zeros(3) u = Convex.Variable(length(u_nom)) u = Command(cbf, u, p, v, u_nom, []) end @testset "cbf" begin test_InputAffinePositionCBF() end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
2404
using Test using FSimZoo using FSimBase using ForwardDiff using Plots using OrdinaryDiffEq function main() multicopter = LeeQuadcopter() (; m, g, J) = multicopter X0 = State(multicopter)() k_p, k_v, k_R, k_ω = 5, 5, 5, 5 controller = GeometricTrackingController(k_p=k_p, k_v=k_v, k_R=k_R, k_ω=k_ω) p_d = t -> [cos(t), sin(t), -t] b_1_d = t -> [1, 0, 0] (; p, v, q, ω) = X0 v_d = t -> ForwardDiff.derivative(p_d, t) a_d = t -> ForwardDiff.derivative(v_d, t) a_d_dot = t -> ForwardDiff.derivative(a_d, t) a_d_ddot = t -> ForwardDiff.derivative(a_d_dot, t) b_1_d_dot = t -> ForwardDiff.derivative(b_1_d, t) b_1_d_ddot = t -> ForwardDiff.derivative(b_1_d_dot, t) t = 0.0 R = quat2dcm(q) ν = Command( controller, p, v, R, ω; a=zeros(3), # IT SHOULD BE ESTIMATED! a_dot=zeros(3), # IT SHOULD BE ESTIMATED! p_d=p_d(t), v_d=v_d(t), a_d=a_d(t), a_d_dot=a_d_dot(t), a_d_ddot=a_d_ddot(t), b_1_d=b_1_d(t), b_1_d_dot=b_1_d_dot(t), b_1_d_ddot=b_1_d_ddot(t), m=m, g=g, J=J, ) @test length(ν) == 4 end function derivative_estimator(; t0=0.0, tf=3.0, Δt=0.05) k_p, k_v, k_R, k_ω = 5, 5, 5, 5 controller = GeometricTrackingController(k_p=k_p, k_v=k_v, k_R=k_R, k_ω=k_ω) X0 = State(controller)() v_cmd = t -> [sin(pi*t), cos(pi*t), t] a_cmd = t -> ForwardDiff.derivative(v_cmd, t) a_dot_cmd = t -> ForwardDiff.derivative(a_cmd, t) prob = ODEProblem((dX, X, params, t) -> FSimBase.Dynamics!(controller)(dX, X, params, t; v=v_cmd(t)), X0, (t0, tf)) sol = solve(prob, Tsit5()) fig = plot(layout=(2, 1)) ts = t0:Δt:tf âs = [controller.ω_n_v*sol(t).z2_v for t in ts] a_cmds = [a_cmd(t) for t in ts] â_dots = [controller.ω_n_a*sol(t).z2_a for t in ts] a_dot_cmds = [a_dot_cmd(t) for t in ts] plot!(fig, ts, hcat(âs...)', subplot=1, label="", lc=:blue) plot!(fig, ts, hcat(a_cmds...)', subplot=1, label="", lc=:red, ls=:dash) plot!(fig, ts, hcat(â_dots...)', subplot=2, label="", lc=:blue) plot!(fig, ts, hcat(a_dot_cmds...)', subplot=2, label="", lc=:red, ls=:dash) display(fig) end @testset "geometric_tracking" begin derivative_estimator() main() end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
2736
using Test using ForwardDiff using FSimZoo using FSimBase using OrdinaryDiffEq using Plots function outerloop() multicopter = LeeQuadcopter() (; m, g) = multicopter X0 = State(multicopter)() controller = OuterLoopGeometricTrackingController() p_d = t -> [cos(t), sin(t), -t] (; p, v) = X0 v_d = t -> ForwardDiff.derivative(p_d, t) a_d = t -> ForwardDiff.derivative(v_d, t) t = 0.0 _b_3_d = Command( controller, p, v; p_d=p_d(t), v_d=v_d(t), a_d=a_d(t), m=m, g=g, ) @test length(_b_3_d) == 3 end function innerloop() multicopter = LeeQuadcopter() (; J) = multicopter X0 = State(multicopter)() controller = InnerLoopGeometricTrackingController() (; q, ω) = X0 b_1_d = t -> [cos(t), sin(t), 0] b_1_d_dot = t -> ForwardDiff.derivative(b_1_d, t) b_1_d_ddot = t -> ForwardDiff.derivative(b_1_d_dot, t) _b_3_d = t -> [cos(t), sin(t), -t] # dummy _b_3_d_dot = t -> ForwardDiff.derivative(_b_3_d, t) _b_3_d_ddot = t -> ForwardDiff.derivative(_b_3_d_dot, t) t = 0.0 R = quat2dcm(q) ν = Command( controller, R, ω; b_1_d=b_1_d(t), b_1_d_dot=b_1_d_dot(t), b_1_d_ddot=b_1_d_ddot(t), _b_3_d=_b_3_d(t), _b_3_d_dot=_b_3_d_dot(t), _b_3_d_ddot=_b_3_d_ddot(t), J=J, ) @test length(ν) == 4 end function derivative_estimator(; t0=0.0, tf=3.0, Δt=0.05) controller = InnerLoopGeometricTrackingController() X0 = State(controller)() f_cmd = t -> [sin(pi*t), cos(pi*t), t] f_cmd_dot = t -> ForwardDiff.derivative(f_cmd, t) f_cmd_ddot = t -> ForwardDiff.derivative(f_cmd_dot, t) prob = ODEProblem((dX, X, params, t) -> FSimBase.Dynamics!(controller)(dX, X, params, t; f=f_cmd(t)), X0, (t0, tf)) sol = solve(prob, Tsit5()) fig = plot(layout=(2, 1)) ts = t0:Δt:tf estimated_f_dots = [controller.ω_n_f*sol(t).z2_f for t in ts] f_cmd_dots = [f_cmd_dot(t) for t in ts] estimated_f_ddots = [controller.ω_n_f_dot*sol(t).z2_f_dot for t in ts] f_cmd_ddots = [f_cmd_ddot(t) for t in ts] plot!(fig, ts, hcat(estimated_f_dots...)', subplot=1, label="", lc=:blue) plot!(fig, ts, hcat(f_cmd_dots...)', subplot=1, label="", lc=:red, ls=:dash) plot!(fig, ts, hcat(estimated_f_ddots...)', subplot=2, label="", lc=:blue) plot!(fig, ts, hcat(f_cmd_ddots...)', subplot=2, label="", lc=:red, ls=:dash) display(fig) end @testset "geometric_tracking_inner_outer" begin outerloop() innerloop() derivative_estimator() end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
210
using FSimZoo using Test @testset "FSimZoo.jl" begin include("geometric_tracking.jl") include("geometric_tracking_inner_outer.jl") include("cbf.jl") include("environments/environments.jl") end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git