text:
# Automatically generated using Clang.jl

const MAGMA_API = 2

# Skipping MacroDefinition: magma_free ( ptr ) magma_free_internal ( ptr , __func__ , __FILE__ , __LINE__ )
# Skipping MacroDefinition: magma_free_pinned ( ptr ) magma_free_pinned_internal ( ptr , __func__ , __FILE__ , __LINE__ )
# Skipping MacroDefinition: magma_queue_create ( device , queue_ptr ) magma_queue_create_internal ( device , queue_ptr , __func__ , __FILE__ , __LINE__ )
# Skipping MacroDefinition: magma_queue_create_from_cuda ( device , cuda_stream , cublas_handle , cusparse_handle , queue_ptr ) magma_queue_create_from_cuda_internal ( device , cuda_stream , cublas_handle , cusparse_handle , queue_ptr , __func__ , __FILE__ , __LINE__ )
# Skipping MacroDefinition: magma_queue_create_from_opencl ( device , cl_queue , queue_ptr ) magma_queue_create_from_opencl_internal ( device , cl_queue , queue_ptr , __func__ , __FILE__ , __LINE__ )
# Skipping MacroDefinition: magma_queue_destroy ( queue ) magma_queue_destroy_internal ( queue , __func__ , __FILE__ , __LINE__ )
# Skipping MacroDefinition: magma_queue_sync ( queue ) magma_queue_sync_internal ( queue , __func__ , __FILE__ , __LINE__ )

const MAX_THREADS_BLG = 256
const magmaFloatComplex = Int

@cenum magma_side_t::UInt begin
    MagmaLeft = 141
    MagmaRight = 142
    MagmaBothSides = 143
end

const real_Double_t = Cdouble

struct gbstrct_blg
    dQ1::PtrOrCuPtr{magmaFloatComplex}
    dT1::PtrOrCuPtr{magmaFloatComplex}
    dT2::PtrOrCuPtr{magmaFloatComplex}
    dV2::PtrOrCuPtr{magmaFloatComplex}
    dE::PtrOrCuPtr{magmaFloatComplex}
    T::PtrOrCuPtr{magmaFloatComplex}
    A::PtrOrCuPtr{magmaFloatComplex}
    V::PtrOrCuPtr{magmaFloatComplex}
    TAU::PtrOrCuPtr{magmaFloatComplex}
    E::PtrOrCuPtr{magmaFloatComplex}
    E_CPU::PtrOrCuPtr{magmaFloatComplex}
    cores_num::Int
    locores_num::Int
    overlapQ1::Int
    usemulticpu::Int
    NB::Int
    NBTILES::Int
    N::Int
    NE::Int
    N_CPU::Int
    N_GPU::Int
    LDA::Int
    LDE::Int
    BAND::Int
    grsiz::Int
    Vblksiz::Int
    WANTZ::Int
    SIDE::magma_side_t
    timeblg::PtrOrCuPtr{real_Double_t}
    timeaplQ::PtrOrCuPtr{real_Double_t}
    ss_prog::PtrOrCuPtr{Int}
end

const magma_int_t = Int
const magmaFloatComplex_ptr = PtrOrCuPtr{magmaFloatComplex}
const magma_queue = Cvoid
const magma_queue_t = PtrOrCuPtr{magma_queue}

struct cgehrd_data
    ngpu::magma_int_t
    ldda::magma_int_t
    ldv::magma_int_t
    ldvd::magma_int_t
    dA::NTuple{8, magmaFloatComplex_ptr}
    dV::NTuple{8, magmaFloatComplex_ptr}
    dVd::NTuple{8, magmaFloatComplex_ptr}
    dY::NTuple{8, magmaFloatComplex_ptr}
    dW::NTuple{8, magmaFloatComplex_ptr}
    dTi::NTuple{8, magmaFloatComplex_ptr}
    queues::NTuple{8, magma_queue_t}
end

const magmaDouble_ptr = PtrOrCuPtr{Cdouble}

struct dgehrd_data
    ngpu::magma_int_t
    ldda::magma_int_t
    ldv::magma_int_t
    ldvd::magma_int_t
    dA::NTuple{8, magmaDouble_ptr}
    dV::NTuple{8, magmaDouble_ptr}
    dVd::NTuple{8, magmaDouble_ptr}
    dY::NTuple{8, magmaDouble_ptr}
    dW::NTuple{8, magmaDouble_ptr}
    dTi::NTuple{8, magmaDouble_ptr}
    queues::NTuple{8, magma_queue_t}
end

const magmaFloat_ptr = PtrOrCuPtr{Cfloat}

struct sgehrd_data
    ngpu::magma_int_t
    ldda::magma_int_t
    ldv::magma_int_t
    ldvd::magma_int_t
    dA::NTuple{8, magmaFloat_ptr}
    dV::NTuple{8, magmaFloat_ptr}
    dVd::NTuple{8, magmaFloat_ptr}
    dY::NTuple{8, magmaFloat_ptr}
    dW::NTuple{8, magmaFloat_ptr}
    dTi::NTuple{8, magmaFloat_ptr}
    queues::NTuple{8, magma_queue_t}
end

const MAGMA_D_ZERO = 0.0
const MAGMA_D_ONE = 1.0
const MAGMA_D_HALF = 0.5
const MAGMA_D_NEG_ONE = -1.0
const MAGMA_D_NEG_HALF = -0.5
const MAGMA_S_ZERO = 0.0
const MAGMA_S_ONE = 1.0
const MAGMA_S_HALF = 0.5
const MAGMA_S_NEG_ONE = -1.0
const MAGMA_S_NEG_HALF = -0.5

const MAGMA_VERSION_MAJOR = 2
const MAGMA_VERSION_MINOR = 5
const MAGMA_VERSION_MICRO = 1
const MAGMA_VERSION_STAGE = "alpha1"
const MagmaMaxGPUs = 8
const MagmaMaxAccelerators = 8
const MagmaMaxSubs = 16
const MagmaBigTileSize = 1000000
const MAGMA_SUCCESS = 0
const MAGMA_ERR = -100
const MAGMA_ERR_NOT_INITIALIZED = -101
const MAGMA_ERR_REINITIALIZED = -102
const MAGMA_ERR_NOT_SUPPORTED = -103
const MAGMA_ERR_ILLEGAL_VALUE = -104
const MAGMA_ERR_NOT_FOUND = -105
const MAGMA_ERR_ALLOCATION = -106
const MAGMA_ERR_INTERNAL_LIMIT = -107
const MAGMA_ERR_UNALLOCATED = -108
const MAGMA_ERR_FILESYSTEM = -109
const MAGMA_ERR_UNEXPECTED = -110
const MAGMA_ERR_SEQUENCE_FLUSHED = -111
const MAGMA_ERR_HOST_ALLOC = -112
const MAGMA_ERR_DEVICE_ALLOC = -113
const MAGMA_ERR_CUDASTREAM = -114
const MAGMA_ERR_INVALID_PTR = -115
const MAGMA_ERR_UNKNOWN = -116
const MAGMA_ERR_NOT_IMPLEMENTED = -117
const MAGMA_ERR_NAN = -118
const MAGMA_SLOW_CONVERGENCE = -201
const MAGMA_DIVERGENCE = -202
const MAGMA_NONSPD = -203
const MAGMA_ERR_BADPRECOND = -204
const MAGMA_NOTCONVERGED = -205
const MAGMA_ERR_CUSPARSE = -3000
const MAGMA_ERR_CUSPARSE_NOT_INITIALIZED = -3001
const MAGMA_ERR_CUSPARSE_ALLOC_FAILED = -3002
const MAGMA_ERR_CUSPARSE_INVALID_VALUE = -3003
const MAGMA_ERR_CUSPARSE_ARCH_MISMATCH = -3004
const MAGMA_ERR_CUSPARSE_MAPPING_ERROR = -3005
const MAGMA_ERR_CUSPARSE_EXECUTION_FAILED = -3006
const MAGMA_ERR_CUSPARSE_INTERNAL_ERROR = -3007
const MAGMA_ERR_CUSPARSE_MATRIX_TYPE_NOT_SUPPORTED = -3008
const MAGMA_ERR_CUSPARSE_ZERO_PIVOT = -3009

@cenum magma_bool_t::UInt begin
    MagmaFalse = 0
    MagmaTrue = 1
end

const Magma2lapack_Min = MagmaFalse

@cenum magma_storev_t::UInt begin
    MagmaColumnwise = 401
    MagmaRowwise = 402
end

const Magma2lapack_Max = MagmaRowwise
const MagmaRowMajorStr = "Row"
const MagmaColMajorStr = "Col"
const MagmaNoTransStr = "NoTrans"
const MagmaTransStr = "Trans"
const MagmaConjTransStr = "ConjTrans"
const Magma_ConjTransStr = "ConjTrans"
const MagmaUpperStr = "Upper"
const MagmaLowerStr = "Lower"
const MagmaFullStr = "Full"
const MagmaNonUnitStr = "NonUnit"
const MagmaUnitStr = "Unit"
const MagmaLeftStr = "Left"
const MagmaRightStr = "Right"
const MagmaBothSidesStr = "Both"
const MagmaOneNormStr = "1"
const MagmaTwoNormStr = "2"
const MagmaFrobeniusNormStr = "Fro"
const MagmaInfNormStr = "Inf"
const MagmaMaxNormStr = "Max"
const MagmaForwardStr = "Forward"
const MagmaBackwardStr = "Backward"
const MagmaColumnwiseStr = "Columnwise"
const MagmaRowwiseStr = "Rowwise"
const MagmaNoVecStr = "NoVec"
const MagmaVecStr = "Vec"
const MagmaIVecStr = "IVec"
const MagmaAllVecStr = "All"
const MagmaSomeVecStr = "Some"
const MagmaOverwriteVecStr = "Overwrite"
const magma_index_t = Int
const magma_uindex_t = UInt
const magma_event_t = Int
const magma_device_t = magma_int_t
const magmaHalf = Int16
const magmaDoubleComplex = Int
const magma_ptr = PtrOrCuPtr{Cvoid}
const magmaInt_ptr = PtrOrCuPtr{magma_int_t}
const magmaIndex_ptr = PtrOrCuPtr{magma_index_t}
const magmaUIndex_ptr = PtrOrCuPtr{magma_uindex_t}
const magmaDoubleComplex_ptr = PtrOrCuPtr{magmaDoubleComplex}
const magmaHalf_ptr = PtrOrCuPtr{magmaHalf}
const magma_const_ptr = PtrOrCuPtr{Cvoid}
const magmaInt_const_ptr = PtrOrCuPtr{magma_int_t}
const magmaIndex_const_ptr = PtrOrCuPtr{magma_index_t}
const magmaUIndex_const_ptr = PtrOrCuPtr{magma_uindex_t}
const magmaFloat_const_ptr = PtrOrCuPtr{Cfloat}
const magmaDouble_const_ptr = PtrOrCuPtr{Cdouble}
const magmaFloatComplex_const_ptr = PtrOrCuPtr{magmaFloatComplex}
const magmaDoubleComplex_const_ptr = PtrOrCuPtr{magmaDoubleComplex}
const magmaHalf_const_ptr = PtrOrCuPtr{magmaHalf}

@cenum magma_order_t::UInt begin
    MagmaRowMajor = 101
    MagmaColMajor = 102
end

@cenum magma_trans_t::UInt begin
    MagmaNoTrans = 111
    MagmaTrans = 112
    MagmaConjTrans = 113
    Magma_ConjTrans = 113
end

@cenum magma_uplo_t::UInt begin
    MagmaUpper = 121
    MagmaLower = 122
    MagmaFull = 123
    MagmaHessenberg = 124
end

const magma_type_t = magma_uplo_t

@cenum magma_diag_t::UInt begin
    MagmaNonUnit = 131
    MagmaUnit = 132
end

@cenum magma_norm_t::UInt begin
    MagmaOneNorm = 171
    MagmaRealOneNorm = 172
    MagmaTwoNorm = 173
    MagmaFrobeniusNorm = 174
    MagmaInfNorm = 175
    MagmaRealInfNorm = 176
    MagmaMaxNorm = 177
    MagmaRealMaxNorm = 178
end

@cenum magma_dist_t::UInt begin
    MagmaDistUniform = 201
    MagmaDistSymmetric = 202
    MagmaDistNormal = 203
end

@cenum magma_sym_t::UInt begin
    MagmaHermGeev = 241
    MagmaHermPoev = 242
    MagmaNonsymPosv = 243
    MagmaSymPosv = 244
end

@cenum magma_pack_t::UInt begin
    MagmaNoPacking = 291
    MagmaPackSubdiag = 292
    MagmaPackSupdiag = 293
    MagmaPackColumn = 294
    MagmaPackRow = 295
    MagmaPackLowerBand = 296
    MagmaPackUpeprBand = 297
    MagmaPackAll = 298
end

@cenum magma_vec_t::UInt begin
    MagmaNoVec = 301
    MagmaVec = 302
    MagmaIVec = 303
    MagmaAllVec = 304
    MagmaSomeVec = 305
    MagmaOverwriteVec = 306
    MagmaBacktransVec = 307
end

@cenum magma_range_t::UInt begin
    MagmaRangeAll = 311
    MagmaRangeV = 312
    MagmaRangeI = 313
end

@cenum magma_vect_t::UInt begin
    MagmaQ = 322
    MagmaP = 323
end

@cenum magma_direct_t::UInt begin
    MagmaForward = 391
    MagmaBackward = 392
end

@cenum magma_mode_t::UInt begin
    MagmaHybrid = 701
    MagmaNative = 702
end

@cenum magma_storage_t::UInt begin
    Magma_CSR = 611
    Magma_ELLPACKT = 612
    Magma_ELL = 613
    Magma_DENSE = 614
    Magma_BCSR = 615
    Magma_CSC = 616
    Magma_HYB = 617
    Magma_COO = 618
    Magma_ELLRT = 619
    Magma_SPMVFUNCTION = 620
    Magma_SELLP = 621
    Magma_ELLD = 622
    Magma_CSRLIST = 623
    Magma_CSRD = 624
    Magma_CSRL = 627
    Magma_CSRU = 628
    Magma_CSRCOO = 629
    Magma_CUCSR = 630
    Magma_COOLIST = 631
    Magma_CSR5 = 632
end

@cenum magma_solver_type::UInt begin
    Magma_CG = 431
    Magma_CGMERGE = 432
    Magma_GMRES = 433
    Magma_BICGSTAB = 434
    Magma_BICGSTABMERGE = 435
    Magma_BICGSTABMERGE2 = 436
    Magma_JACOBI = 437
    Magma_GS = 438
    Magma_ITERREF = 439
    Magma_BCSRLU = 440
    Magma_PCG = 441
    Magma_PGMRES = 442
    Magma_PBICGSTAB = 443
    Magma_PASTIX = 444
    Magma_ILU = 445
    Magma_ICC = 446
    Magma_PARILU = 447
    Magma_PARIC = 448
    Magma_BAITER = 449
    Magma_LOBPCG = 450
    Magma_NONE = 451
    Magma_FUNCTION = 452
    Magma_IDR = 453
    Magma_PIDR = 454
    Magma_CGS = 455
    Magma_PCGS = 456
    Magma_CGSMERGE = 457
    Magma_PCGSMERGE = 458
    Magma_TFQMR = 459
    Magma_PTFQMR = 460
    Magma_TFQMRMERGE = 461
    Magma_PTFQMRMERGE = 462
    Magma_QMR = 463
    Magma_PQMR = 464
    Magma_QMRMERGE = 465
    Magma_PQMRMERGE = 466
    Magma_BOMBARD = 490
    Magma_BOMBARDMERGE = 491
    Magma_PCGMERGE = 492
    Magma_BAITERO = 493
    Magma_IDRMERGE = 494
    Magma_PBICGSTABMERGE = 495
    Magma_PARICT = 496
    Magma_CUSTOMIC = 497
    Magma_CUSTOMILU = 498
    Magma_PIDRMERGE = 499
    Magma_BICG = 500
    Magma_BICGMERGE = 501
    Magma_PBICG = 502
    Magma_PBICGMERGE = 503
    Magma_LSQR = 504
    Magma_PARILUT = 505
    Magma_ISAI = 506
    Magma_CUSOLVE = 507
    Magma_VBJACOBI = 508
    Magma_PARDISO = 509
    Magma_SYNCFREESOLVE = 510
    Magma_ILUT = 511
end

@cenum magma_ortho_t::UInt begin
    Magma_CGSO = 561
    Magma_FUSED_CGSO = 562
    Magma_MGSO = 563
end

@cenum magma_location_t::UInt begin
    Magma_CPU = 571
    Magma_DEV = 572
end

@cenum magma_symmetry_t::UInt begin
    Magma_GENERAL = 581
    Magma_SYMMETRIC = 582
end

@cenum magma_diagorder_t::UInt begin
    Magma_ORDERED = 591
    Magma_DIAGFIRST = 592
    Magma_UNITY = 593
    Magma_VALUE = 594
end

@cenum magma_precision::UInt begin
    Magma_DCOMPLEX = 501
    Magma_FCOMPLEX = 502
    Magma_DOUBLE = 503
    Magma_FLOAT = 504
end

@cenum magma_scale_t::UInt begin
    Magma_NOSCALE = 511
    Magma_UNITROW = 512
    Magma_UNITDIAG = 513
    Magma_UNITCOL = 514
    Magma_UNITROWCOL = 515
    Magma_UNITDIAGCOL = 516
end

@cenum magma_operation_t::UInt begin
    Magma_SOLVE = 801
    Magma_SETUPSOLVE = 802
    Magma_APPLYSOLVE = 803
    Magma_DESTROYSOLVE = 804
    Magma_INFOSOLVE = 805
    Magma_GENERATEPREC = 806
    Magma_PRECONDLEFT = 807
    Magma_PRECONDRIGHT = 808
    Magma_TRANSPOSE = 809
    Magma_SPMV = 810
end

@cenum magma_refinement_t::UInt begin
    Magma_PREC_SS = 900
    Magma_PREC_SST = 901
    Magma_PREC_HS = 902
    Magma_PREC_HST = 903
    Magma_PREC_SH = 904
    Magma_PREC_SHT = 905
    Magma_PREC_XHS_H = 910
    Magma_PREC_XHS_HTC = 911
    Magma_PREC_XHS_161616 = 912
    Magma_PREC_XHS_161616TC = 913
    Magma_PREC_XHS_161632TC = 914
    Magma_PREC_XSH_S = 915
    Magma_PREC_XSH_STC = 916
    Magma_PREC_XSH_163232TC = 917
    Magma_PREC_XSH_323232TC = 918
    Magma_REFINE_IRSTRS = 920
    Magma_REFINE_IRDTRS = 921
    Magma_REFINE_IRGMSTRS = 922
    Magma_REFINE_IRGMDTRS = 923
    Magma_REFINE_GMSTRS = 924
    Magma_REFINE_GMDTRS = 925
    Magma_REFINE_GMGMSTRS = 926
    Magma_REFINE_GMGMDTRS = 927
    Magma_PREC_HD = 930
end

@cenum magma_mp_type_t::UInt begin
    Magma_MP_BASE_SS = 950
    Magma_MP_BASE_DD = 951
    Magma_MP_BASE_XHS = 952
    Magma_MP_BASE_XSH = 953
    Magma_MP_BASE_XHD = 954
    Magma_MP_BASE_XDH = 955
    Magma_MP_ENABLE_DFLT_MATH = 960
    Magma_MP_ENABLE_TC_MATH = 961
    Magma_MP_SGEMM = 962
    Magma_MP_HGEMM = 963
    Magma_MP_GEMEX_I32_O32_C32 = 964
    Magma_MP_GEMEX_I16_O32_C32 = 965
    Magma_MP_GEMEX_I16_O16_C32 = 966
    Magma_MP_GEMEX_I16_O16_C16 = 967
    Magma_MP_TC_SGEMM = 968
    Magma_MP_TC_HGEMM = 969
    Magma_MP_TC_GEMEX_I32_O32_C32 = 970
    Magma_MP_TC_GEMEX_I16_O32_C32 = 971
    Magma_MP_TC_GEMEX_I16_O16_C32 = 972
    Magma_MP_TC_GEMEX_I16_O16_C16 = 973
end

struct zgehrd_data
    ngpu::magma_int_t
    ldda::magma_int_t
    ldv::magma_int_t
    ldvd::magma_int_t
    dA::NTuple{8, magmaDoubleComplex_ptr}
    dV::NTuple{8, magmaDoubleComplex_ptr}
    dVd::NTuple{8, magmaDoubleComplex_ptr}
    dY::NTuple{8, magmaDoubleComplex_ptr}
    dW::NTuple{8, magmaDoubleComplex_ptr}
    dTi::NTuple{8, magmaDoubleComplex_ptr}
    queues::NTuple{8, magma_queue_t}
end
#
# const magmablas_ctranspose_inplace = magmablas_ctranspose_inplace_v1
# const magmablas_ctranspose_conj_inplace = magmablas_ctranspose_conj_inplace_v1
# const magmablas_ctranspose = magmablas_ctranspose_v1
# const magmablas_ctranspose_conj = magmablas_ctranspose_conj_v1
# const magmablas_cgetmatrix_transpose = magmablas_cgetmatrix_transpose_v1
# const magmablas_csetmatrix_transpose = magmablas_csetmatrix_transpose_v1
# const magmablas_cprbt = magmablas_cprbt_v1
# const magmablas_cprbt_mv = magmablas_cprbt_mv_v1
# const magmablas_cprbt_mtv = magmablas_cprbt_mtv_v1
# const magma_cgetmatrix_1D_col_bcyclic = magma_cgetmatrix_1D_col_bcyclic_v1
# const magma_csetmatrix_1D_col_bcyclic = magma_csetmatrix_1D_col_bcyclic_v1
# const magma_cgetmatrix_1D_row_bcyclic = magma_cgetmatrix_1D_row_bcyclic_v1
# const magma_csetmatrix_1D_row_bcyclic = magma_csetmatrix_1D_row_bcyclic_v1
# const magmablas_cgeadd = magmablas_cgeadd_v1
# const magmablas_cgeadd2 = magmablas_cgeadd2_v1
# const magmablas_clacpy = magmablas_clacpy_v1
# const magmablas_clacpy_conj = magmablas_clacpy_conj_v1
# const magmablas_clacpy_sym_in = magmablas_clacpy_sym_in_v1
# const magmablas_clacpy_sym_out = magmablas_clacpy_sym_out_v1
# const magmablas_clange = magmablas_clange_v1
# const magmablas_clanhe = magmablas_clanhe_v1
# const magmablas_clansy = magmablas_clansy_v1
# const magmablas_clarfg = magmablas_clarfg_v1
# const magmablas_clascl = magmablas_clascl_v1
# const magmablas_clascl_2x2 = magmablas_clascl_2x2_v1
# const magmablas_clascl2 = magmablas_clascl2_v1
# const magmablas_clascl_diag = magmablas_clascl_diag_v1
# const magmablas_claset = magmablas_claset_v1
# const magmablas_claset_band = magmablas_claset_band_v1
# const magmablas_claswp = magmablas_claswp_v1
# const magmablas_claswp2 = magmablas_claswp2_v1
# const magmablas_claswp_sym = magmablas_claswp_sym_v1
# const magmablas_claswpx = magmablas_claswpx_v1
# const magmablas_csymmetrize = magmablas_csymmetrize_v1
# const magmablas_csymmetrize_tiles = magmablas_csymmetrize_tiles_v1
# const magmablas_ctrtri_diag = magmablas_ctrtri_diag_v1
# const magmablas_scnrm2_adjust = magmablas_scnrm2_adjust_v1
# const magmablas_scnrm2_check = magmablas_scnrm2_check_v1
# const magmablas_scnrm2_cols = magmablas_scnrm2_cols_v1
# const magmablas_scnrm2_row_check_adjust = magmablas_scnrm2_row_check_adjust_v1
# const magma_clarfb_gpu = magma_clarfb_gpu_v1
# const magma_clarfb_gpu_gemm = magma_clarfb_gpu_gemm_v1
# const magma_clarfbx_gpu = magma_clarfbx_gpu_v1
# const magma_clarfg_gpu = magma_clarfg_gpu_v1
# const magma_clarfgtx_gpu = magma_clarfgtx_gpu_v1
# const magma_clarfgx_gpu = magma_clarfgx_gpu_v1
# const magma_clarfx_gpu = magma_clarfx_gpu_v1
# const magmablas_caxpycp = magmablas_caxpycp_v1
# const magmablas_cswap = magmablas_cswap_v1
# const magmablas_cswapblk = magmablas_cswapblk_v1
# const magmablas_cswapdblk = magmablas_cswapdblk_v1
# const magmablas_cgemv = magmablas_cgemv_v1
# const magmablas_cgemv_conj = magmablas_cgemv_conj_v1
# const magmablas_chemv = magmablas_chemv_v1
# const magmablas_csymv = magmablas_csymv_v1
# const magmablas_cgemm = magmablas_cgemm_v1
# const magmablas_cgemm_reduce = magmablas_cgemm_reduce_v1
# const magmablas_chemm = magmablas_chemm_v1
# const magmablas_csymm = magmablas_csymm_v1
# const magmablas_csyr2k = magmablas_csyr2k_v1
# const magmablas_cher2k = magmablas_cher2k_v1
# const magmablas_csyrk = magmablas_csyrk_v1
# const magmablas_cherk = magmablas_cherk_v1
# const magmablas_ctrsm = magmablas_ctrsm_v1
# const magmablas_ctrsm_outofplace = magmablas_ctrsm_outofplace_v1
# const magmablas_ctrsm_work = magmablas_ctrsm_work_v1
# const magma_csetvector = magma_csetvector_v1
# const magma_cgetvector = magma_cgetvector_v1
# const magma_ccopyvector = magma_ccopyvector_v1
# const magma_csetmatrix = magma_csetmatrix_v1
# const magma_cgetmatrix = magma_cgetmatrix_v1
# const magma_ccopymatrix = magma_ccopymatrix_v1
# const magma_icamax = magma_icamax_v1
# const magma_icamin = magma_icamin_v1
# const magma_scasum = magma_scasum_v1
# const magma_caxpy = magma_caxpy_v1
# const magma_ccopy = magma_ccopy_v1
# const magma_cdotc = magma_cdotc_v1
# const magma_cdotu = magma_cdotu_v1
# const magma_scnrm2 = magma_scnrm2_v1
# const magma_crot = magma_crot_v1
# const magma_csrot = magma_csrot_v1
# const magma_crotm = magma_crotm_v1
# const magma_crotmg = magma_crotmg_v1
# const magma_cscal = magma_cscal_v1
# const magma_csscal = magma_csscal_v1
# const magma_cswap = magma_cswap_v1
# const magma_cgemv = magma_cgemv_v1
# const magma_cgerc = magma_cgerc_v1
# const magma_cgeru = magma_cgeru_v1
# const magma_chemv = magma_chemv_v1
# const magma_cher = magma_cher_v1
# const magma_cher2 = magma_cher2_v1
# const magma_ctrmv = magma_ctrmv_v1
# const magma_ctrsv = magma_ctrsv_v1
# const magma_cgemm = magma_cgemm_v1
# const magma_csymm = magma_csymm_v1
# const magma_chemm = magma_chemm_v1
# const magma_csyr2k = magma_csyr2k_v1
# const magma_cher2k = magma_cher2k_v1
# const magma_csyrk = magma_csyrk_v1
# const magma_cherk = magma_cherk_v1
# const magma_ctrmm = magma_ctrmm_v1
# const magma_ctrsm = magma_ctrsm_v1
#
# # Skipping MacroDefinition: magma_dsetvector ( n , hx_src , incx , dy_dst , incy , queue ) magma_dsetvector_internal ( n , hx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dgetvector ( n , dx_src , incx , hy_dst , incy , queue ) magma_dgetvector_internal ( n , dx_src , incx , hy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dcopyvector ( n , dx_src , incx , dy_dst , incy , queue ) magma_dcopyvector_internal ( n , dx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dsetvector_async ( n , hx_src , incx , dy_dst , incy , queue ) magma_dsetvector_async_internal ( n , hx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dgetvector_async ( n , dx_src , incx , hy_dst , incy , queue ) magma_dgetvector_async_internal ( n , dx_src , incx , hy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dcopyvector_async ( n , dx_src , incx , dy_dst , incy , queue ) magma_dcopyvector_async_internal ( n , dx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dsetmatrix ( m , n , hA_src , lda , dB_dst , lddb , queue ) magma_dsetmatrix_internal ( m , n , hA_src , lda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dgetmatrix ( m , n , dA_src , ldda , hB_dst , ldb , queue ) magma_dgetmatrix_internal ( m , n , dA_src , ldda , hB_dst , ldb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dcopymatrix ( m , n , dA_src , ldda , dB_dst , lddb , queue ) magma_dcopymatrix_internal ( m , n , dA_src , ldda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dsetmatrix_async ( m , n , hA_src , lda , dB_dst , lddb , queue ) magma_dsetmatrix_async_internal ( m , n , hA_src , lda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dgetmatrix_async ( m , n , dA_src , ldda , hB_dst , ldb , queue ) magma_dgetmatrix_async_internal ( m , n , dA_src , ldda , hB_dst , ldb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dcopymatrix_async ( m , n , dA_src , ldda , dB_dst , lddb , queue ) magma_dcopymatrix_async_internal ( m , n , dA_src , ldda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dsetvector_v1 ( n , hx_src , incx , dy_dst , incy ) magma_dsetvector_v1_internal ( n , hx_src , incx , dy_dst , incy , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dgetvector_v1 ( n , dx_src , incx , hy_dst , incy ) magma_dgetvector_v1_internal ( n , dx_src , incx , hy_dst , incy , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dcopyvector_v1 ( n , dx_src , incx , dy_dst , incy ) magma_dcopyvector_v1_internal ( n , dx_src , incx , dy_dst , incy , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dsetmatrix_v1 ( m , n , hA_src , lda , dB_dst , lddb ) magma_dsetmatrix_v1_internal ( m , n , hA_src , lda , dB_dst , lddb , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dgetmatrix_v1 ( m , n , dA_src , ldda , hB_dst , ldb ) magma_dgetmatrix_v1_internal ( m , n , dA_src , ldda , hB_dst , ldb , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_dcopymatrix_v1 ( m , n , dA_src , ldda , dB_dst , lddb ) magma_dcopymatrix_v1_internal ( m , n , dA_src , ldda , dB_dst , lddb , __func__ , __FILE__ , __LINE__ )
#
# const magmablas_dtranspose_inplace = magmablas_dtranspose_inplace_v1
# const magmablas_dtranspose = magmablas_dtranspose_v1
# const magmablas_dgetmatrix_transpose = magmablas_dgetmatrix_transpose_v1
# const magmablas_dsetmatrix_transpose = magmablas_dsetmatrix_transpose_v1
# const magmablas_dprbt = magmablas_dprbt_v1
# const magmablas_dprbt_mv = magmablas_dprbt_mv_v1
# const magmablas_dprbt_mtv = magmablas_dprbt_mtv_v1
# const magma_dgetmatrix_1D_col_bcyclic = magma_dgetmatrix_1D_col_bcyclic_v1
# const magma_dsetmatrix_1D_col_bcyclic = magma_dsetmatrix_1D_col_bcyclic_v1
# const magma_dgetmatrix_1D_row_bcyclic = magma_dgetmatrix_1D_row_bcyclic_v1
# const magma_dsetmatrix_1D_row_bcyclic = magma_dsetmatrix_1D_row_bcyclic_v1
# const magmablas_dgeadd = magmablas_dgeadd_v1
# const magmablas_dgeadd2 = magmablas_dgeadd2_v1
# const magmablas_dlacpy = magmablas_dlacpy_v1
# const magmablas_dlacpy_conj = magmablas_dlacpy_conj_v1
# const magmablas_dlacpy_sym_in = magmablas_dlacpy_sym_in_v1
# const magmablas_dlacpy_sym_out = magmablas_dlacpy_sym_out_v1
# const magmablas_dlange = magmablas_dlange_v1
# const magmablas_dlansy = magmablas_dlansy_v1
# const magmablas_dlarfg = magmablas_dlarfg_v1
# const magmablas_dlascl = magmablas_dlascl_v1
# const magmablas_dlascl_2x2 = magmablas_dlascl_2x2_v1
# const magmablas_dlascl2 = magmablas_dlascl2_v1
# const magmablas_dlascl_diag = magmablas_dlascl_diag_v1
# const magmablas_dlaset = magmablas_dlaset_v1
# const magmablas_dlaset_band = magmablas_dlaset_band_v1
# const magmablas_dlaswp = magmablas_dlaswp_v1
# const magmablas_dlaswp2 = magmablas_dlaswp2_v1
# const magmablas_dlaswp_sym = magmablas_dlaswp_sym_v1
# const magmablas_dlaswpx = magmablas_dlaswpx_v1
# const magmablas_dsymmetrize = magmablas_dsymmetrize_v1
# const magmablas_dsymmetrize_tiles = magmablas_dsymmetrize_tiles_v1
# const magmablas_dtrtri_diag = magmablas_dtrtri_diag_v1
# const magmablas_dnrm2_adjust = magmablas_dnrm2_adjust_v1
# const magmablas_dnrm2_check = magmablas_dnrm2_check_v1
# const magmablas_dnrm2_cols = magmablas_dnrm2_cols_v1
# const magmablas_dnrm2_row_check_adjust = magmablas_dnrm2_row_check_adjust_v1
# const magma_dlarfb_gpu = magma_dlarfb_gpu_v1
# const magma_dlarfb_gpu_gemm = magma_dlarfb_gpu_gemm_v1
# const magma_dlarfbx_gpu = magma_dlarfbx_gpu_v1
# const magma_dlarfg_gpu = magma_dlarfg_gpu_v1
# const magma_dlarfgtx_gpu = magma_dlarfgtx_gpu_v1
# const magma_dlarfgx_gpu = magma_dlarfgx_gpu_v1
# const magma_dlarfx_gpu = magma_dlarfx_gpu_v1
# const magmablas_daxpycp = magmablas_daxpycp_v1
# const magmablas_dswap = magmablas_dswap_v1
# const magmablas_dswapblk = magmablas_dswapblk_v1
# const magmablas_dswapdblk = magmablas_dswapdblk_v1
# const magmablas_dgemv = magmablas_dgemv_v1
# const magmablas_dgemv_conj = magmablas_dgemv_conj_v1
# const magmablas_dsymv = magmablas_dsymv_v1
# const magmablas_dgemm = magmablas_dgemm_v1
# const magmablas_dgemm_reduce = magmablas_dgemm_reduce_v1
# const magmablas_dsymm = magmablas_dsymm_v1
# const magmablas_dsyr2k = magmablas_dsyr2k_v1
# const magmablas_dsyrk = magmablas_dsyrk_v1
# const magmablas_dtrsm = magmablas_dtrsm_v1
# const magmablas_dtrsm_outofplace = magmablas_dtrsm_outofplace_v1
# const magmablas_dtrsm_work = magmablas_dtrsm_work_v1
# const magma_dsetvector = magma_dsetvector_v1
# const magma_dgetvector = magma_dgetvector_v1
# const magma_dcopyvector = magma_dcopyvector_v1
# const magma_dsetmatrix = magma_dsetmatrix_v1
# const magma_dgetmatrix = magma_dgetmatrix_v1
# const magma_dcopymatrix = magma_dcopymatrix_v1
# const magma_idamax = magma_idamax_v1
# const magma_idamin = magma_idamin_v1
# const magma_dasum = magma_dasum_v1
# const magma_daxpy = magma_daxpy_v1
# const magma_dcopy = magma_dcopy_v1
# const magma_ddot = magma_ddot_v1
# const magma_dnrm2 = magma_dnrm2_v1
# const magma_drot = magma_drot_v1
# const magma_drotm = magma_drotm_v1
# const magma_drotmg = magma_drotmg_v1
# const magma_dscal = magma_dscal_v1
# const magma_dswap = magma_dswap_v1
# const magma_dgemv = magma_dgemv_v1
# const magma_dger = magma_dger_v1
# const magma_dsymv = magma_dsymv_v1
# const magma_dsyr = magma_dsyr_v1
# const magma_dsyr2 = magma_dsyr2_v1
# const magma_dtrmv = magma_dtrmv_v1
# const magma_dtrsv = magma_dtrsv_v1
# const magma_dgemm = magma_dgemm_v1
# const magma_dsymm = magma_dsymm_v1
# const magma_dsyr2k = magma_dsyr2k_v1
# const magma_dsyrk = magma_dsyrk_v1
# const magma_dtrmm = magma_dtrmm_v1
# const magma_dtrsm = magma_dtrsm_v1
# const magmablas_dsaxpycp = magmablas_dsaxpycp_v1
# const magmablas_dslaswp = magmablas_dslaswp_v1
# const magmablas_dlag2s = magmablas_dlag2s_v1
# const magmablas_slag2d = magmablas_slag2d_v1
# const magmablas_dlat2s = magmablas_dlat2s_v1
# const magmablas_slat2d = magmablas_slat2d_v1
#
# # Skipping MacroDefinition: magma_ssetvector ( n , hx_src , incx , dy_dst , incy , queue ) magma_ssetvector_internal ( n , hx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_sgetvector ( n , dx_src , incx , hy_dst , incy , queue ) magma_sgetvector_internal ( n , dx_src , incx , hy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_scopyvector ( n , dx_src , incx , dy_dst , incy , queue ) magma_scopyvector_internal ( n , dx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_ssetvector_async ( n , hx_src , incx , dy_dst , incy , queue ) magma_ssetvector_async_internal ( n , hx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_sgetvector_async ( n , dx_src , incx , hy_dst , incy , queue ) magma_sgetvector_async_internal ( n , dx_src , incx , hy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_scopyvector_async ( n , dx_src , incx , dy_dst , incy , queue ) magma_scopyvector_async_internal ( n , dx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_ssetmatrix ( m , n , hA_src , lda , dB_dst , lddb , queue ) magma_ssetmatrix_internal ( m , n , hA_src , lda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_sgetmatrix ( m , n , dA_src , ldda , hB_dst , ldb , queue ) magma_sgetmatrix_internal ( m , n , dA_src , ldda , hB_dst , ldb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_scopymatrix ( m , n , dA_src , ldda , dB_dst , lddb , queue ) magma_scopymatrix_internal ( m , n , dA_src , ldda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_ssetmatrix_async ( m , n , hA_src , lda , dB_dst , lddb , queue ) magma_ssetmatrix_async_internal ( m , n , hA_src , lda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_sgetmatrix_async ( m , n , dA_src , ldda , hB_dst , ldb , queue ) magma_sgetmatrix_async_internal ( m , n , dA_src , ldda , hB_dst , ldb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_scopymatrix_async ( m , n , dA_src , ldda , dB_dst , lddb , queue ) magma_scopymatrix_async_internal ( m , n , dA_src , ldda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_ssetvector_v1 ( n , hx_src , incx , dy_dst , incy ) magma_ssetvector_v1_internal ( n , hx_src , incx , dy_dst , incy , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_sgetvector_v1 ( n , dx_src , incx , hy_dst , incy ) magma_sgetvector_v1_internal ( n , dx_src , incx , hy_dst , incy , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_scopyvector_v1 ( n , dx_src , incx , dy_dst , incy ) magma_scopyvector_v1_internal ( n , dx_src , incx , dy_dst , incy , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_ssetmatrix_v1 ( m , n , hA_src , lda , dB_dst , lddb ) magma_ssetmatrix_v1_internal ( m , n , hA_src , lda , dB_dst , lddb , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_sgetmatrix_v1 ( m , n , dA_src , ldda , hB_dst , ldb ) magma_sgetmatrix_v1_internal ( m , n , dA_src , ldda , hB_dst , ldb , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_scopymatrix_v1 ( m , n , dA_src , ldda , dB_dst , lddb ) magma_scopymatrix_v1_internal ( m , n , dA_src , ldda , dB_dst , lddb , __func__ , __FILE__ , __LINE__ )
#
# const magmablas_stranspose_inplace = magmablas_stranspose_inplace_v1
# const magmablas_stranspose = magmablas_stranspose_v1
# const magmablas_sgetmatrix_transpose = magmablas_sgetmatrix_transpose_v1
# const magmablas_ssetmatrix_transpose = magmablas_ssetmatrix_transpose_v1
# const magmablas_sprbt = magmablas_sprbt_v1
# const magmablas_sprbt_mv = magmablas_sprbt_mv_v1
# const magmablas_sprbt_mtv = magmablas_sprbt_mtv_v1
# const magma_sgetmatrix_1D_col_bcyclic = magma_sgetmatrix_1D_col_bcyclic_v1
# const magma_ssetmatrix_1D_col_bcyclic = magma_ssetmatrix_1D_col_bcyclic_v1
# const magma_sgetmatrix_1D_row_bcyclic = magma_sgetmatrix_1D_row_bcyclic_v1
# const magma_ssetmatrix_1D_row_bcyclic = magma_ssetmatrix_1D_row_bcyclic_v1
# const magmablas_sgeadd = magmablas_sgeadd_v1
# const magmablas_sgeadd2 = magmablas_sgeadd2_v1
# const magmablas_slacpy = magmablas_slacpy_v1
# const magmablas_slacpy_conj = magmablas_slacpy_conj_v1
# const magmablas_slacpy_sym_in = magmablas_slacpy_sym_in_v1
# const magmablas_slacpy_sym_out = magmablas_slacpy_sym_out_v1
# const magmablas_slange = magmablas_slange_v1
# const magmablas_slansy = magmablas_slansy_v1
# const magmablas_slarfg = magmablas_slarfg_v1
# const magmablas_slascl = magmablas_slascl_v1
# const magmablas_slascl_2x2 = magmablas_slascl_2x2_v1
# const magmablas_slascl2 = magmablas_slascl2_v1
# const magmablas_slascl_diag = magmablas_slascl_diag_v1
# const magmablas_slaset = magmablas_slaset_v1
# const magmablas_slaset_band = magmablas_slaset_band_v1
# const magmablas_slaswp = magmablas_slaswp_v1
# const magmablas_slaswp2 = magmablas_slaswp2_v1
# const magmablas_slaswp_sym = magmablas_slaswp_sym_v1
# const magmablas_slaswpx = magmablas_slaswpx_v1
# const magmablas_ssymmetrize = magmablas_ssymmetrize_v1
# const magmablas_ssymmetrize_tiles = magmablas_ssymmetrize_tiles_v1
# const magmablas_strtri_diag = magmablas_strtri_diag_v1
# const magmablas_snrm2_adjust = magmablas_snrm2_adjust_v1
# const magmablas_snrm2_check = magmablas_snrm2_check_v1
# const magmablas_snrm2_cols = magmablas_snrm2_cols_v1
# const magmablas_snrm2_row_check_adjust = magmablas_snrm2_row_check_adjust_v1
# const magma_slarfb_gpu = magma_slarfb_gpu_v1
# const magma_slarfb_gpu_gemm = magma_slarfb_gpu_gemm_v1
# const magma_slarfbx_gpu = magma_slarfbx_gpu_v1
# const magma_slarfg_gpu = magma_slarfg_gpu_v1
# const magma_slarfgtx_gpu = magma_slarfgtx_gpu_v1
# const magma_slarfgx_gpu = magma_slarfgx_gpu_v1
# const magma_slarfx_gpu = magma_slarfx_gpu_v1
# const magmablas_saxpycp = magmablas_saxpycp_v1
# const magmablas_sswap = magmablas_sswap_v1
# const magmablas_sswapblk = magmablas_sswapblk_v1
# const magmablas_sswapdblk = magmablas_sswapdblk_v1
# const magmablas_sgemv = magmablas_sgemv_v1
# const magmablas_sgemv_conj = magmablas_sgemv_conj_v1
# const magmablas_ssymv = magmablas_ssymv_v1
# const magmablas_sgemm = magmablas_sgemm_v1
# const magmablas_sgemm_reduce = magmablas_sgemm_reduce_v1
# const magmablas_ssymm = magmablas_ssymm_v1
# const magmablas_ssyr2k = magmablas_ssyr2k_v1
# const magmablas_ssyrk = magmablas_ssyrk_v1
# const magmablas_strsm = magmablas_strsm_v1
# const magmablas_strsm_outofplace = magmablas_strsm_outofplace_v1
# const magmablas_strsm_work = magmablas_strsm_work_v1
# const magma_ssetvector = magma_ssetvector_v1
# const magma_sgetvector = magma_sgetvector_v1
# const magma_scopyvector = magma_scopyvector_v1
# const magma_ssetmatrix = magma_ssetmatrix_v1
# const magma_sgetmatrix = magma_sgetmatrix_v1
# const magma_scopymatrix = magma_scopymatrix_v1
# const magma_isamax = magma_isamax_v1
# const magma_isamin = magma_isamin_v1
# const magma_sasum = magma_sasum_v1
# const magma_saxpy = magma_saxpy_v1
# const magma_scopy = magma_scopy_v1
# const magma_sdot = magma_sdot_v1
# const magma_snrm2 = magma_snrm2_v1
# const magma_srot = magma_srot_v1
# const magma_srotm = magma_srotm_v1
# const magma_srotmg = magma_srotmg_v1
# const magma_sscal = magma_sscal_v1
# const magma_sswap = magma_sswap_v1
# const magma_sgemv = magma_sgemv_v1
# const magma_sger = magma_sger_v1
# const magma_ssymv = magma_ssymv_v1
# const magma_ssyr = magma_ssyr_v1
# const magma_ssyr2 = magma_ssyr2_v1
# const magma_strmv = magma_strmv_v1
# const magma_strsv = magma_strsv_v1
# const magma_sgemm = magma_sgemm_v1
# const magma_ssymm = magma_ssymm_v1
# const magma_ssyr2k = magma_ssyr2k_v1
# const magma_ssyrk = magma_ssyrk_v1
# const magma_strmm = magma_strmm_v1
# const magma_strsm = magma_strsm_v1
#
# # Skipping MacroDefinition: magma_queue_create_v1 ( queue_ptr ) magma_queue_create_v1_internal ( queue_ptr , __func__ , __FILE__ , __LINE__ )
#
# const MagmaUpperLower = MagmaFull
# const MagmaUpperLowerStr = MagmaFullStr
#
# # Skipping MacroDefinition: MAGMA_Z_CNJG ( a ) MAGMA_Z_CONJ ( a )
# # Skipping MacroDefinition: MAGMA_C_CNJG ( a ) MAGMA_C_CONJ ( a )
# # Skipping MacroDefinition: MAGMA_D_CNJG ( a ) MAGMA_D_CONJ ( a )
# # Skipping MacroDefinition: MAGMA_S_CNJG ( a ) MAGMA_S_CONJ ( a )
#
# const magma_queue_create = magma_queue_create_v1
# const magma_setvector = magma_setvector_v1
# const magma_getvector = magma_getvector_v1
# const magma_copyvector = magma_copyvector_v1
# const magma_setmatrix = magma_setmatrix_v1
# const magma_getmatrix = magma_getmatrix_v1
# const magma_copymatrix = magma_copymatrix_v1
# const magma_isetvector = magma_isetvector_v1
# const magma_igetvector = magma_igetvector_v1
# const magma_icopyvector = magma_icopyvector_v1
# const magma_isetmatrix = magma_isetmatrix_v1
# const magma_igetmatrix = magma_igetmatrix_v1
# const magma_icopymatrix = magma_icopymatrix_v1
# const magma_index_setvector = magma_index_setvector_v1
# const magma_index_getvector = magma_index_getvector_v1
# const magma_index_copyvector = magma_index_copyvector_v1
# const magma_index_setmatrix = magma_index_setmatrix_v1
# const magma_index_getmatrix = magma_index_getmatrix_v1
# const magma_index_copymatrix = magma_index_copymatrix_v1
#
# # Skipping MacroDefinition: magma_zsetvector ( n , hx_src , incx , dy_dst , incy , queue ) magma_zsetvector_internal ( n , hx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zgetvector ( n , dx_src , incx , hy_dst , incy , queue ) magma_zgetvector_internal ( n , dx_src , incx , hy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zcopyvector ( n , dx_src , incx , dy_dst , incy , queue ) magma_zcopyvector_internal ( n , dx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zsetvector_async ( n , hx_src , incx , dy_dst , incy , queue ) magma_zsetvector_async_internal ( n , hx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zgetvector_async ( n , dx_src , incx , hy_dst , incy , queue ) magma_zgetvector_async_internal ( n , dx_src , incx , hy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zcopyvector_async ( n , dx_src , incx , dy_dst , incy , queue ) magma_zcopyvector_async_internal ( n , dx_src , incx , dy_dst , incy , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zsetmatrix ( m , n , hA_src , lda , dB_dst , lddb , queue ) magma_zsetmatrix_internal ( m , n , hA_src , lda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zgetmatrix ( m , n , dA_src , ldda , hB_dst , ldb , queue ) magma_zgetmatrix_internal ( m , n , dA_src , ldda , hB_dst , ldb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zcopymatrix ( m , n , dA_src , ldda , dB_dst , lddb , queue ) magma_zcopymatrix_internal ( m , n , dA_src , ldda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zsetmatrix_async ( m , n , hA_src , lda , dB_dst , lddb , queue ) magma_zsetmatrix_async_internal ( m , n , hA_src , lda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zgetmatrix_async ( m , n , dA_src , ldda , hB_dst , ldb , queue ) magma_zgetmatrix_async_internal ( m , n , dA_src , ldda , hB_dst , ldb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zcopymatrix_async ( m , n , dA_src , ldda , dB_dst , lddb , queue ) magma_zcopymatrix_async_internal ( m , n , dA_src , ldda , dB_dst , lddb , queue , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zsetvector_v1 ( n , hx_src , incx , dy_dst , incy ) magma_zsetvector_v1_internal ( n , hx_src , incx , dy_dst , incy , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zgetvector_v1 ( n , dx_src , incx , hy_dst , incy ) magma_zgetvector_v1_internal ( n , dx_src , incx , hy_dst , incy , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zcopyvector_v1 ( n , dx_src , incx , dy_dst , incy ) magma_zcopyvector_v1_internal ( n , dx_src , incx , dy_dst , incy , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zsetmatrix_v1 ( m , n , hA_src , lda , dB_dst , lddb ) magma_zsetmatrix_v1_internal ( m , n , hA_src , lda , dB_dst , lddb , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zgetmatrix_v1 ( m , n , dA_src , ldda , hB_dst , ldb ) magma_zgetmatrix_v1_internal ( m , n , dA_src , ldda , hB_dst , ldb , __func__ , __FILE__ , __LINE__ )
# # Skipping MacroDefinition: magma_zcopymatrix_v1 ( m , n , dA_src , ldda , dB_dst , lddb ) magma_zcopymatrix_v1_internal ( m , n , dA_src , ldda , dB_dst , lddb , __func__ , __FILE__ , __LINE__ )
#
# const magmablas_ztranspose_inplace = magmablas_ztranspose_inplace_v1
# const magmablas_ztranspose_conj_inplace = magmablas_ztranspose_conj_inplace_v1
# const magmablas_ztranspose = magmablas_ztranspose_v1
# const magmablas_ztranspose_conj = magmablas_ztranspose_conj_v1
# const magmablas_zgetmatrix_transpose = magmablas_zgetmatrix_transpose_v1
# const magmablas_zsetmatrix_transpose = magmablas_zsetmatrix_transpose_v1
# const magmablas_zprbt = magmablas_zprbt_v1
# const magmablas_zprbt_mv = magmablas_zprbt_mv_v1
# const magmablas_zprbt_mtv = magmablas_zprbt_mtv_v1
# const magma_zgetmatrix_1D_col_bcyclic = magma_zgetmatrix_1D_col_bcyclic_v1
# const magma_zsetmatrix_1D_col_bcyclic = magma_zsetmatrix_1D_col_bcyclic_v1
# const magma_zgetmatrix_1D_row_bcyclic = magma_zgetmatrix_1D_row_bcyclic_v1
# const magma_zsetmatrix_1D_row_bcyclic = magma_zsetmatrix_1D_row_bcyclic_v1
# const magmablas_zgeadd = magmablas_zgeadd_v1
# const magmablas_zgeadd2 = magmablas_zgeadd2_v1
# const magmablas_zlacpy = magmablas_zlacpy_v1
# const magmablas_zlacpy_conj = magmablas_zlacpy_conj_v1
# const magmablas_zlacpy_sym_in = magmablas_zlacpy_sym_in_v1
# const magmablas_zlacpy_sym_out = magmablas_zlacpy_sym_out_v1
# const magmablas_zlange = magmablas_zlange_v1
# const magmablas_zlanhe = magmablas_zlanhe_v1
# const magmablas_zlansy = magmablas_zlansy_v1
# const magmablas_zlarfg = magmablas_zlarfg_v1
# const magmablas_zlascl = magmablas_zlascl_v1
# const magmablas_zlascl_2x2 = magmablas_zlascl_2x2_v1
# const magmablas_zlascl2 = magmablas_zlascl2_v1
# const magmablas_zlascl_diag = magmablas_zlascl_diag_v1
# const magmablas_zlaset = magmablas_zlaset_v1
# const magmablas_zlaset_band = magmablas_zlaset_band_v1
# const magmablas_zlaswp = magmablas_zlaswp_v1
# const magmablas_zlaswp2 = magmablas_zlaswp2_v1
# const magmablas_zlaswp_sym = magmablas_zlaswp_sym_v1
# const magmablas_zlaswpx = magmablas_zlaswpx_v1
# const magmablas_zsymmetrize = magmablas_zsymmetrize_v1
# const magmablas_zsymmetrize_tiles = magmablas_zsymmetrize_tiles_v1
# const magmablas_ztrtri_diag = magmablas_ztrtri_diag_v1
# const magmablas_dznrm2_adjust = magmablas_dznrm2_adjust_v1
# const magmablas_dznrm2_check = magmablas_dznrm2_check_v1
# const magmablas_dznrm2_cols = magmablas_dznrm2_cols_v1
# const magmablas_dznrm2_row_check_adjust = magmablas_dznrm2_row_check_adjust_v1
# const magma_zlarfb_gpu = magma_zlarfb_gpu_v1
# const magma_zlarfb_gpu_gemm = magma_zlarfb_gpu_gemm_v1
# const magma_zlarfbx_gpu = magma_zlarfbx_gpu_v1
# const magma_zlarfg_gpu = magma_zlarfg_gpu_v1
# const magma_zlarfgtx_gpu = magma_zlarfgtx_gpu_v1
# const magma_zlarfgx_gpu = magma_zlarfgx_gpu_v1
# const magma_zlarfx_gpu = magma_zlarfx_gpu_v1
# const magmablas_zaxpycp = magmablas_zaxpycp_v1
# const magmablas_zswap = magmablas_zswap_v1
# const magmablas_zswapblk = magmablas_zswapblk_v1
# const magmablas_zswapdblk = magmablas_zswapdblk_v1
# const magmablas_zgemv = magmablas_zgemv_v1
# const magmablas_zgemv_conj = magmablas_zgemv_conj_v1
# const magmablas_zhemv = magmablas_zhemv_v1
# const magmablas_zsymv = magmablas_zsymv_v1
# const magmablas_zgemm = magmablas_zgemm_v1
# const magmablas_zgemm_reduce = magmablas_zgemm_reduce_v1
# const magmablas_zhemm = magmablas_zhemm_v1
# const magmablas_zsymm = magmablas_zsymm_v1
# const magmablas_zsyr2k = magmablas_zsyr2k_v1
# const magmablas_zher2k = magmablas_zher2k_v1
# const magmablas_zsyrk = magmablas_zsyrk_v1
# const magmablas_zherk = magmablas_zherk_v1
# const magmablas_ztrsm = magmablas_ztrsm_v1
# const magmablas_ztrsm_outofplace = magmablas_ztrsm_outofplace_v1
# const magmablas_ztrsm_work = magmablas_ztrsm_work_v1
# const magma_zsetvector = magma_zsetvector_v1
# const magma_zgetvector = magma_zgetvector_v1
# const magma_zcopyvector = magma_zcopyvector_v1
# const magma_zsetmatrix = magma_zsetmatrix_v1
# const magma_zgetmatrix = magma_zgetmatrix_v1
# const magma_zcopymatrix = magma_zcopymatrix_v1
# const magma_izamax = magma_izamax_v1
# const magma_izamin = magma_izamin_v1
# const magma_dzasum = magma_dzasum_v1
# const magma_zaxpy = magma_zaxpy_v1
# const magma_zcopy = magma_zcopy_v1
# const magma_zdotc = magma_zdotc_v1
# const magma_zdotu = magma_zdotu_v1
# const magma_dznrm2 = magma_dznrm2_v1
# const magma_zrot = magma_zrot_v1
# const magma_zdrot = magma_zdrot_v1
# const magma_zrotm = magma_zrotm_v1
# const magma_zrotmg = magma_zrotmg_v1
# const magma_zscal = magma_zscal_v1
# const magma_zdscal = magma_zdscal_v1
# const magma_zswap = magma_zswap_v1
# const magma_zgemv = magma_zgemv_v1
# const magma_zgerc = magma_zgerc_v1
# const magma_zgeru = magma_zgeru_v1
# const magma_zhemv = magma_zhemv_v1
# const magma_zher = magma_zher_v1
# const magma_zher2 = magma_zher2_v1
# const magma_ztrmv = magma_ztrmv_v1
# const magma_ztrsv = magma_ztrsv_v1
# const magma_zgemm = magma_zgemm_v1
# const magma_zsymm = magma_zsymm_v1
# const magma_zhemm = magma_zhemm_v1
# const magma_zsyr2k = magma_zsyr2k_v1
# const magma_zher2k = magma_zher2k_v1
# const magma_zsyrk = magma_zsyrk_v1
# const magma_zherk = magma_zherk_v1
# const magma_ztrmm = magma_ztrmm_v1
# const magma_ztrsm = magma_ztrsm_v1
# const magmablas_zcaxpycp = magmablas_zcaxpycp_v1
# const magmablas_zclaswp = magmablas_zclaswp_v1
# const magmablas_zlag2c = magmablas_zlag2c_v1
# const magmablas_clag2z = magmablas_clag2z_v1
# const magmablas_zlat2c = magmablas_zlat2c_v1
# const magmablas_clat2z = magmablas_clat2z_v1


text:
#=
Constants for PCRE2 library API

Copyright 2018 Gandalf Software, Inc., Scott P. Jones, and contributors to pcre2.h
(based on pcre2.h (copyright University of Cambridge), see PCRE2_LICENSE)
Licensed under MIT License, see LICENSE.md
=#

# The following option bits can be passed to pcre2_compile(), pcre2_match(), or pcre2_dfa_match().
# PCRE2_NO_UTF_CHECK affects only the function to which it is passed. Put these bits at the most
# significant end of the options word so others can be added next to them

const ANCHORED            = 0x80000000
const NO_UTF_CHECK        = 0x40000000
const ENDANCHORED         = 0x20000000

# The following option bits can be passed only to pcre2_compile().
# However, they may affect compilation, JIT compilation, and/or interpretive execution.
# The following tags indicate which:

# C   alters what is compiled by pcre2_compile()
# J   alters what is compiled by pcre2_jit_compile()
# M   is inspected during pcre2_match() execution
# D   is inspected during pcre2_dfa_match() execution

const ALLOW_EMPTY_CLASS   = 0x00000001  # C
const ALT_BSUX            = 0x00000002  # C
const AUTO_CALLOUT        = 0x00000004  # C
const CASELESS            = 0x00000008  # C
const DOLLAR_ENDONLY      = 0x00000010  #   J M D
const DOTALL              = 0x00000020  # C
const DUPNAMES            = 0x00000040  # C
const EXTENDED            = 0x00000080  # C
const FIRSTLINE           = 0x00000100  #   J M D
const MATCH_UNSET_BACKREF = 0x00000200  # C J M
const MULTILINE           = 0x00000400  # C
const NEVER_UCP           = 0x00000800  # C
const NEVER_UTF           = 0x00001000  # C
const NO_AUTO_CAPTURE     = 0x00002000  # C
const NO_AUTO_POSSESS     = 0x00004000  # C
const NO_DOTSTAR_ANCHOR   = 0x00008000  # C
const NO_START_OPTIMIZE   = 0x00010000  #   J M D
const UCP                 = 0x00020000  # C J M D
const UNGREEDY            = 0x00040000  # C
const UTF                 = 0x00080000  # C J M D
const NEVER_BACKSLASH_C   = 0x00100000  # C
const ALT_CIRCUMFLEX      = 0x00200000  #   J M D
const ALT_VERBNAMES       = 0x00400000  # C
const USE_OFFSET_LIMIT    = 0x00800000  #   J M D
const EXTENDED_MORE       = 0x01000000  # C
const LITERAL             = 0x02000000  # C

## An additional compile options word is available in the compile context.

const EXTRA_ALLOW_SURROGATE_ESCAPES  = 0x00000001  # C
const EXTRA_BAD_ESCAPE_IS_LITERAL    = 0x00000002  # C
const EXTRA_MATCH_WORD               = 0x00000004  # C
const EXTRA_MATCH_LINE               = 0x00000008  # C

## These are for pcre2_jit_compile().

const JIT_COMPLETE        = 0x00000001  # For full matching */
const JIT_PARTIAL_SOFT    = 0x00000002
const JIT_PARTIAL_HARD    = 0x00000004

## These are for pcre2_match(), pcre2_dfa_match(), and pcre2_jit_match().
## Note that PCRE2_ANCHORED and PCRE2_NO_UTF_CHECK can also be passed to these functions
## (though pcre2_jit_match() ignores the latter since it bypasses all sanity checks).

const NOTBOL              = 0x00000001
const NOTEOL              = 0x00000002
const NOTEMPTY            = 0x00000004  # ) These two must be kept
const NOTEMPTY_ATSTART    = 0x00000008  # ) adjacent to each other
const PARTIAL_SOFT        = 0x00000010
const PARTIAL_HARD        = 0x00000020

## These are additional options for pcre2_dfa_match()

const DFA_RESTART         = 0x00000040
const DFA_SHORTEST        = 0x00000080

## These are additional options for substitute(), which passes any others through to match()

const SUBSTITUTE_GLOBAL           = 0x00000100
const SUBSTITUTE_EXTENDED         = 0x00000200
const SUBSTITUTE_UNSET_EMPTY      = 0x00000400
const SUBSTITUTE_UNKNOWN_UNSET    = 0x00000800
const SUBSTITUTE_OVERFLOW_LENGTH  = 0x00001000

## A further option for match(), not allowed for dfa_match(), ignored for jit_match()

const NO_JIT              = 0x00002000

## Options for pattern_convert()

const CONVERT_UTF                    = 0x00000001
const CONVERT_NO_UTF_CHECK           = 0x00000002
const CONVERT_POSIX_BASIC            = 0x00000004
const CONVERT_POSIX_EXTENDED         = 0x00000008
const CONVERT_GLOB                   = 0x00000010
const CONVERT_GLOB_NO_WILD_SEPARATOR = 0x00000030
const CONVERT_GLOB_NO_STARSTAR       = 0x00000050

## Newline and \R settings, for use in compile contexts. The newline values must be kept in step
## with values set in config.h and both sets must all be greater than zero.

const NEWLINE_CR          = 1
const NEWLINE_LF          = 2
const NEWLINE_CRLF        = 3
const NEWLINE_ANY         = 4
const NEWLINE_ANYCRLF     = 5
const NEWLINE_NUL         = 6

const BSR_UNICODE         = 1
const BSR_ANYCRLF         = 2

## Request types for pattern_info()

@enum(INFO::Int32,
      INFO_ALLOPTIONS = 0,
      INFO_ARGOPTIONS,
      INFO_BACKREFMAX,
      INFO_BSR,
      INFO_CAPTURECOUNT,
      INFO_FIRSTCODEUNIT,
      INFO_FIRSTCODETYPE,
      INFO_FIRSTBITMAP,
      INFO_HASCRORLF,
      INFO_JCHANGED,
      INFO_JITSIZE,
      INFO_LASTCODEUNIT,
      INFO_LASTCODETYPE,
      INFO_MATCHEMPTY,
      INFO_MATCHLIMIT,
      INFO_MAXLOOKBEHIND,
      INFO_MINLENGTH,
      INFO_NAMECOUNT,
      INFO_NAMEENTRYSIZE,
      INFO_NAMETABLE,
      INFO_NEWLINE,
      INFO_DEPTHLIMIT,
      INFO_SIZE,
      INFO_HASBACKSLASHC,
      INFO_FRAMESIZE,
      INFO_HEAPLIMIT,
      INFO_EXTRAOPTIONS)

## Request types for config()

@enum(CONFIG::Int32,
      CONFIG_BSR = 0,
      CONFIG_JIT,
      CONFIG_JITTARGET,
      CONFIG_LINKSIZE,
      CONFIG_MATCHLIMIT,
      CONFIG_NEWLINE,
      CONFIG_PARENSLIMIT,
      CONFIG_DEPTHLIMIT,
      CONFIG_STACKRECURSE,  # Obsolete
      CONFIG_UNICODE,
      CONFIG_UNICODE_VERSION,
      CONFIG_VERSION,
      CONFIG_HEAPLIMIT,
      CONFIG_NEVER_BACKSLASH_C,
      CONFIG_COMPILED_WIDTHS)

# supported options for different use cases

const NL_MASK =
    NEWLINE_ANY | NEWLINE_ANYCRLF | NEWLINE_CR | NEWLINE_CRLF | NEWLINE_LF

const COMMON_MASK = ANCHORED | ENDANCHORED | NO_UTF_CHECK

const COMPILE_MASK =
    (COMMON_MASK
     | ALLOW_EMPTY_CLASS
     | ALT_BSUX
     | AUTO_CALLOUT
     | CASELESS
     | DOLLAR_ENDONLY
     | DOTALL
     | DUPNAMES
     | EXTENDED
     | FIRSTLINE
     | MATCH_UNSET_BACKREF
     | MULTILINE
     | NEVER_UCP
     | NEVER_UTF
     | NO_AUTO_CAPTURE
     | NO_AUTO_POSSESS
     | NO_DOTSTAR_ANCHOR
     | NO_START_OPTIMIZE
     | UCP
     | UNGREEDY
     | UTF
     | NEVER_BACKSLASH_C
     | ALT_CIRCUMFLEX
     | ALT_VERBNAMES
     | USE_OFFSET_LIMIT
     | EXTENDED_MORE
     | LITERAL
     )

const MATCH_MASK =
    (COMMON_MASK
     | NOTBOL
     | NOTEOL
     | NOTEMPTY
     | NOTEMPTY_ATSTART
     | PARTIAL_HARD
     | PARTIAL_SOFT
     )

ext: jl


text:
# collection of quantum models to be solved by continuous tensor network methods

# cmpo representation for quantum models

"""
    cmpo_ising(Γ::Real)
"""
function cmpo_ising(Γ::Real)
    Q = TensorMap(zeros, ComplexF64, ℂ^2, ℂ^2)
    L = TensorMap(zeros, ComplexF64, ℂ^2*ℂ^1, ℂ^2)
    R = TensorMap(zeros, ComplexF64, ℂ^2*ℂ^1, ℂ^2)
    P = TensorMap(zeros, ComplexF64, ℂ^1*ℂ^2, ℂ^2*ℂ^1)

    Q[1, 2] = Γ
    Q[2, 1] = Γ
    L[1, 1, 1] = 1.0
    L[2, 1, 2] = -1.0
    R[1, 1, 1] = 1.0
    R[2, 1, 2] = -1.0

    return cmpo(Q, L, R, P)
end

"""
    cmpo_xy()
"""
function cmpo_xy()
    Q = zeros(ComplexF64, (2, 2))
    L = zeros(ComplexF64, (2, 2, 2))
    R = zeros(ComplexF64, (2, 2, 2))
    P = zeros(ComplexF64, (2, 2, 2, 2))

    σp = zeros(ComplexF64, (2, 2))
    σm = zeros(ComplexF64, (2, 2))
    σp[1, 2] = 1
    σm[2, 1] = 1

    L[:, 1, :] = σp
    L[:, 2, :] = σm

    R[:, 1, :] = σp
    R[:, 2, :] = σm

    Q = convert_to_tensormap(Q, 1)
    L = convert_to_tensormap(L, 2)
    R = convert_to_tensormap(R, 2)
    P = convert_to_tensormap(P, 2)

    return cmpo(Q, L, R, P)
end

"""
    cmpo_xz()
"""
function cmpo_xz()
    Q = zeros(ComplexF64, (2, 2))
    L = zeros(ComplexF64, (2, 2, 2))
    R = zeros(ComplexF64, (2, 2, 2))
    P = zeros(ComplexF64, (2, 2, 2, 2))

    σx = zeros(ComplexF64, (2, 2))
    σz = zeros(ComplexF64, (2, 2))
    σx[1, 2] = 0.5
    σx[2, 1] = 0.5
    σz[1, 1] = 0.5
    σz[2, 2] = -0.5

    L[:, 1, :] = σx
    L[:, 2, :] = σz

    R[:, 1, :] = σx
    R[:, 2, :] = σz

    Q = convert_to_tensormap(Q, 1)
    L = convert_to_tensormap(L, 2)
    R = convert_to_tensormap(R, 2)
    P = convert_to_tensormap(P, 2)

    return cmpo(Q, L, R, P)
end

"""
    energy_quantum_ising(psi::TensorMap{ComplexSpace, 2, 1}, Γ::Number)
"""
function energy_quantum_ising(psi::TensorMap{ComplexSpace, 2, 1}, Γ::Number)
    σx = TensorMap(zeros, ComplexF64, ℂ^2, ℂ^2)
    σz = TensorMap(zeros, ComplexF64, ℂ^2, ℂ^2)

    σx[1, 2] = 1
    σx[2, 1] = 1

    σz[1, 1] = 1
    σz[2, 2] = -1

    lop = transf_mat(psi, psi)
    lopT = transf_mat_T(psi, psi)
    chi = get_chi(psi)
    v0 = TensorMap(rand, ComplexF64, ℂ^chi, ℂ^chi)

    w, vr = eigsolve(lop, v0, 1)
    _, vl = eigsolve(lopT, v0, 1)
    w = w[1]
    vr = vr[1]
    vl = vl[1]
    vr = vr / tr(vl' * vr)

    @tensor term_1site[:] := vl'[1, 2] * psi'[5, 1, 3] * σx[3, 4] * psi[2, 4, 6] * vr[6, 5]
    @tensor term_2site[:] := vl'[1, 2] * psi'[5, 1, 3] * σz[3, 4] * psi[2, 4, 6] * psi'[9, 5, 7] * σz[7, 8] * psi[6, 8, 10] * vr[10, 9]

    term_1site = term_1site / w * (-Γ)
    term_2site = term_2site / w^2 * (-1)

    return (term_1site + term_2site)[1]
end

"""
    cmpo_xxz(Δ::Number)
"""
function cmpo_xxz(Δ::Number)
    Q = TensorMap(zeros, ComplexF64, ℂ^2, ℂ^2)
    L = TensorMap(zeros, ComplexF64, ℂ^2*ℂ^3, ℂ^2)
    R = TensorMap(zeros, ComplexF64, ℂ^2*ℂ^3, ℂ^2)
    P = TensorMap(zeros, ComplexF64, ℂ^3*ℂ^2, ℂ^2*ℂ^3)

    L[1, 1, 2] = 1 / sqrt(2)
    L[2, 2, 1] = 1 / sqrt(2)
    L[1, 3, 1] = -0.5*sqrt(abs(Δ))
    L[2, 3, 2] = 0.5*sqrt(abs(Δ))

    R[1, 1, 2] = 1 / sqrt(2)
    R[2, 2, 1] = 1 / sqrt(2)
    R[1, 3, 1] = 0.5*sqrt(abs(Δ))*sign(Δ)
    R[2, 3, 2] = -0.5*sqrt(abs(Δ))*sign(Δ)

    return cmpo(Q, L, R, P)
end

"""
    energy_quantum_xxz(psi::TensorMap{ComplexSpace, 2, 1}, Δ::Real)
"""
function energy_quantum_xxz(psi::TensorMap{ComplexSpace, 2, 1}, Δ::Real)
    sx = TensorMap(zeros, ComplexF64, ℂ^2, ℂ^2)
    sy = TensorMap(zeros, ComplexF64, ℂ^2, ℂ^2)
    sz = TensorMap(zeros, ComplexF64, ℂ^2, ℂ^2)

    sx[1, 2] = 0.5
    sx[2, 1] = 0.5
    sy[1, 2] = 0.5im
    sy[2, 1] = -0.5im
    sz[1, 1] = 0.5
    sz[2, 2] = -0.5

    lop = transf_mat(psi, psi)
    lopT = transf_mat_T(psi, psi)
    chi = get_chi(psi)
    v0 = TensorMap(rand, ComplexF64, ℂ^chi, ℂ^chi)

    w, vr = eigsolve(lop, v0, 1)
    _, vl = eigsolve(lopT, v0, 1)
    w = w[1]
    vr = vr[1]
    vl = vl[1]
    vr = vr / tr(vl' * vr)

    @tensor term_xx[:] := vl'[1, 2] * psi'[5, 1, 3] * sx[3, 4] * psi[2, 4, 6] * psi'[9, 5, 7] * sx[7, 8] * psi[6, 8, 10] * vr[10, 9]
    @tensor term_yy[:] := vl'[1, 2] * psi'[5, 1, 3] * sy[3, 4] * psi[2, 4, 6] * psi'[9, 5, 7] * sy[7, 8] * psi[6, 8, 10] * vr[10, 9]
    @tensor term_zz[:] := vl'[1, 2] * psi'[5, 1, 3] * sz[3, 4] * psi[2, 4, 6] * psi'[9, 5, 7] * sz[7, 8] * psi[6, 8, 10] * vr[10, 9]

    result = term_xx / w^2 * (-1) + term_yy / w^2 * (-1) + term_zz / w^2 * Δ

    return result[1]
end

"""
    cmpo_ising_realtime(Γ::Real)
"""
function cmpo_ising_realtime(Γ::Real)
    Q = TensorMap(zeros, ComplexF64, ℂ^2, ℂ^2)
    L = TensorMap(zeros, ComplexF64, ℂ^2*ℂ^1, ℂ^2)
    R = TensorMap(zeros, ComplexF64, ℂ^2*ℂ^1, ℂ^2)
    P = TensorMap(zeros, ComplexF64, ℂ^1*ℂ^2, ℂ^2*ℂ^1)

    Q[1, 2] = Γ * -1im
    Q[2, 1] = Γ * -1im
    L[1, 1, 1] = 1.0
    L[2, 1, 2] = -1.0
    R[1, 1, 1] = 1.0 * (-1im)
    R[2, 1, 2] = -1.0 * (-1im)

    return cmpo(Q, L, R, P)
end

"""
    energy_lieb_lingerenergy_lieb_liniger(ψ::cmps, c::Real, L::Real, μ::Real)

    Calculate the energy density of Lieb Linger model for cMPS `ψ` with system size `L`.
    `c` is the parameter in the Hamiltonian.
    The Hamiltonian of Lieb Liniger model
    ```
        H = ∫dx [(dψ† / dx)(dψ / dx) + cψ†ψ†ψψ - μψ†ψ]
    ```
    Note L can be set to `Inf`, which means the thermodynamic limit.
"""
function energy_lieb_liniger(ψ::cmps, c::Real, L::Real, μ::Real)
    tensorK = kinetic(ψ)
    tensorD = particle_density(ψ)
    tensorP = point_interaction(ψ)
    tensorE = tensorK + c * tensorP - μ * tensorD

    # calculate environment
    lop = K_mat(ψ, ψ)
    env = finite_env(lop, L)
    env = permute(env, (2, 3), (4, 1))

    return real(tr(env * tensorE))
end

"""
    energy_pairing_boson(ψ::cmps, ν::Real, μ::Real, L::Real)

    Calculate the energy density of "pairing boson" model for cMPS `ψ` with system size `L`.
    `μ` and `ν` are the parameters in the Hamiltonian.
    The Hamiltonian of Lieb Liniger model
    ```
        H = ∫dx [(dψ† / dx)(dψ / dx) - ν(ψ†ψ† + ψψ)  - μψ†ψ]
    ```
"""
function energy_pairing_boson(ψ::cmps, ν::Real, μ::Real, L::Real)
    tensorK = kinetic(ψ)
    tensorD = particle_density(ψ)
    tensorP = pairing(ψ)
    tensorE = tensorK - ν * tensorP - μ * tensorD

    # calculate environment
    lop = K_mat(ψ, ψ)
    env = finite_env(lop, L)
    env = permute(env, (2, 3), (4, 1))

    return real(tr(env * tensorE))
end


text:
csvfileAbsname =joinpath(@__DIR__ ,"csvfile.csv" )
println(csvfileAbsname )

max_stars_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_issues_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_forks_repo_name: wangzhongtian/fiberAlarmAnalyseTool


text:
# S2C: sequence to class model

import Knet: params, forw, back
using Knet: initback

immutable S2C <: Model; net1; net2; params;
    S2C(a,b)=new(a,b,vcat(params(a),params(b)))
end

params(r::S2C)=r.params

function forw(r::S2C, x::Vector, yout=nothing; ygold=nothing, a...)
    forw(r.net1, x; a...)
    forw(r.net2, r.net1.out[end], yout; ygold=ygold, a...)
    # TODO: implement lastout or direct write from net1 out to net2 input
    # You can do the latter if net2 is initialized first or just overwrite its buf0
    # and check for === before copy
end

function back(r::S2C, y; a...)
    dy = similar(r.net1.out[end])
    back(r.net2, y, dy; a...)
    initback(r.net1, dy; seq=true, a...)
    back(r.net1, dy; seq=true, a...)
    while r.net1.sp > 0; back(r.net1, nothing; seq=true, a...); end
end


text:
using Base.Test, GLM, DataFrames

## Formaldehyde data from the R Datasets package
form = DataFrame(Carb=[0.1,0.3,0.5,0.6,0.7,0.9],OptDen=[0.086,0.269,0.446,0.538,0.626,0.782])
lm1 = fit(LinearModel, OptDen ~ Carb, form)
@test_approx_eq coef(lm1) linreg(array(form[:Carb]),array(form[:OptDen]))

dobson = DataFrame(Counts=[18.,17,15,20,10,20,25,13,12], Outcome=gl(3,1,9), Treatment=gl(3,3))
gm1 = fit(GeneralizedLinearModel, Counts ~ Outcome + Treatment, dobson, Poisson());
@test_approx_eq deviance(gm1) 5.12914107700115
@test_approx_eq coef(gm1)[1:3] [3.044522437723423,-0.45425527227759555,-0.29298712468147375]

## Example from http://www.ats.ucla.edu/stat/r/dae/logit.htm
df = readtable(Pkg.dir("GLM","data","admit.csv.gz"))
df[:rank] = pool(df[:rank])

gm2 = fit(GeneralizedLinearModel, admit ~ gre + gpa + rank, df, Binomial())
@test_approx_eq deviance(gm2) 458.5174924758994
@test_approx_eq coef(gm2) [-3.9899786606380734,0.0022644256521549043,0.8040374535155766,-0.6754428594116577,-1.3402038117481079,-1.5514636444657492]

gm3 = fit(GeneralizedLinearModel, admit ~ gre + gpa + rank, df, Binomial(), ProbitLink())
@test_approx_eq deviance(gm3) 458.4131713833386
@test_approx_eq coef(gm3) [-2.3867922998680786,0.0013755394922972369,0.47772908362647015,-0.4154125854823675,-0.8121458010130356,-0.9359047862425298]

gm4 = fit(GeneralizedLinearModel, admit ~ gre + gpa + rank, df, Binomial(), CauchitLink())
@test_approx_eq deviance(gm4) 459.3401112751141

gm5 = fit(GeneralizedLinearModel, admit ~ gre + gpa + rank, df, Binomial(), CloglogLink())
@test_approx_eq deviance(gm5) 458.89439629612616

## Example with offsets from Venables & Ripley (2002, p.189)
df = readtable(Pkg.dir("GLM","data","anorexia.csv.gz"))
df[:Treat] = pool(df[:Treat])

gm6 = fit(GeneralizedLinearModel, Postwt ~ Prewt + Treat, df, Normal(), IdentityLink(), offset=array(df[:Prewt]))
@test_approx_eq deviance(gm6) 3311.262619919613
@test_approx_eq coef(gm6) [49.7711090149846,-0.5655388496391,-4.0970655280729,4.5630626529188]
@test_approx_eq scale(gm6.model, true) 48.6950385282296
@test_approx_eq stderr(gm6) [13.3909581420259,0.1611823618518,1.8934926069669,2.1333359226431]

gm7 = fit(GeneralizedLinearModel, Postwt ~ Prewt + Treat, df, Normal(), LogLink(), offset=array(df[:Prewt]),
	      convTol=1e-8)
@test_approx_eq deviance(gm7) 3265.207242977156
@test_approx_eq coef(gm7) [3.992326787835955,-0.994452693131178,-0.050698258703974,0.051494029957641]
@test_approx_eq scale(gm7.model, true) 48.01787789178518
@test_approx_eq stderr(gm7) [0.157167944259695,0.001886285986164,0.022584069426311,0.023882826190166]

## Gamma example from McCullagh & Nelder (1989, pp. 300-2)
clotting = DataFrame(u = log([5,10,15,20,30,40,60,80,100]),
                     lot1 = [118,58,42,35,27,25,21,19,18])
gm8 = fit(GeneralizedLinearModel, lot1 ~ u, clotting, Gamma())
@test_approx_eq deviance(gm8) 0.01672971517848353
@test_approx_eq coef(gm8) [-0.01655438172784895,0.01534311491072141]
@test_approx_eq scale(gm8.model, true) 0.002446059333495581
@test_approx_eq stderr(gm8) [0.0009275466067257,0.0004149596425600]

gm9 = fit(GeneralizedLinearModel, lot1 ~ u, clotting, Gamma(), LogLink(), convTol=1e-8)
@test_approx_eq deviance(gm9) 0.16260829451739
@test_approx_eq coef(gm9) [5.50322528458221,-0.60191617825971]
@test_approx_eq scale(gm9.model, true) 0.02435442293561081
@test_approx_eq stderr(gm9) [0.19030107482720,0.05530784660144]

gm10 = fit(GeneralizedLinearModel, lot1 ~ u, clotting, Gamma(), IdentityLink(), convTol=1e-8)
@test_approx_eq deviance(gm10) 0.60845414895344
@test_approx_eq coef(gm10) [99.250446880986,-18.374324929002]
@test_approx_eq scale(gm10.model, true) 0.1041772704067886
@test_approx_eq stderr(gm10) [17.864388462865,4.297968703823]


text:
const IODIM = Tuple{Int,Tuple{Int,Int}}
might_reshape!(iodims::Vector{IODIM}) = begin
    len, dims = 1, length(iodims)
    szs = @view reinterpret(Int, iodims)[1:3:3dims]
    for j in 2:dims
        iodimʲ = szʲ, stsʲ = iodims[j]
        ind = findprev(x -> .*(x...) == stsʲ, iodims, len)
        if isnothing(ind)
            iodims[len += 1] = iodimʲ
        else
            szs[ind] *= szʲ
        end
    end
    resize!(iodims, len)
end

dims_howmany_loop(X::StridedArray, Y::StridedArray, sz, region) = begin
    reg = unique(region)
    length(reg) != length(region) &&
        throw(ArgumentError("each dimension can be transformed at most once"))
    iodims = [(x,(y,z)) for (x,y,z) in zip(sz, strides(X), strides(Y))]
    oreg = (1:ndims(X)) .* sz .> 1
    oreg[reg] .= 0
    oreg = findall(>(0), oreg)
    dims = iodims[reg]
    howmany = iodims[oreg]
    length(howmany) <= 1 && return dims, howmany, IODIM[]
    sort!(howmany, by = x -> x[2][1])
    howmany = might_reshape!(howmany)
    sort!(howmany, by = x -> (x[2], -x[1]))
    dims, [popfirst!(howmany)], howmany
end

# MKL's fft has no alignment limitation, and flags has no influence
# but the check is preseved to keep consistency with FFTW
mutable struct cLoopPlan{T,K,inplace,N,G} <: FFTWPlan{T,K,inplace}
    plan::PlanPtr
    sz::NTuple{N,Int} # size of array on which plan operates (Int tuple)
    osz::NTuple{N,Int} # size of output array (Int tuple)
    istride::NTuple{N,Int} # strides of input
    ostride::NTuple{N,Int} # strides of output
    ialign::Int32 # alignment mod 16 of input
    oalign::Int32 # alignment mod 16 of input
    flags::UInt32 # planner flags
    region::G # region (iterable) of dims that are transormed
    loop::Vector{IODIM} # keep the loop size if needed
    pinv::ScaledPlan
    function cLoopPlan{T,K,inplace}(plan::PlanPtr, X, Y, flags, region, loop) where {T,K,inplace}
        N, G = ndims(X), typeof(region)
        p = new{T,K,inplace,N,G}(plan, size(X), size(Y), strides(X), strides(Y),
                                    alignment_of(X), alignment_of(Y), flags,
                                    region, loop)
        finalizer(maybe_destroy_plan, p)
        p
    end
end

for (Tr,Tc,fftw,lib) in ((:Float64,:(Complex{Float64}),"fftw",:libfftw3),
                         (:Float32,:(Complex{Float32}),"fftwf",:libfftw3f))
    @eval @exclusive function cLoopPlan{$Tc,K,inplace}(X::StridedArray{$Tc,N},
                                        Y::StridedArray{$Tc,N}, region, flags, timelimit) where {K,inplace,N}
        unsafe_set_timelimit($Tr, timelimit)
        dims, howmany, loop = dims_howmany_loop(X, Y, size(X), region)
        plan = ccall(($(string(fftw,"_plan_guru64_dft")),$lib[]),
                     PlanPtr,
                     (Int32, Ptr{Int}, Int32, Ptr{Int},
                      Ptr{$Tc}, Ptr{$Tc}, Int32, UInt32),
                     length(dims), dims, length(howmany), howmany,
                     X, Y, K, UNALIGNED) ## flags is useless
        unsafe_set_timelimit($Tr, NO_TIMELIMIT)
        plan == C_NULL && error("FFTW could not create plan") # shouldn't normally happen
        return cLoopPlan{$Tc,K,inplace}(plan, X, Y, flags, region, loop)
    end
end

show(io::IO, p::cLoopPlan{T,K,inplace}) where {T,K,inplace} = begin
    print(io, inplace ? "FFTW in-place " : "FFTW ",
          K < 0 ? "forward" : "backward", " plan for ")
    showfftdims(io, p.sz, p.istride, T)
    #has_sprint_plan && print(io, "\n", sprint_plan(p))
end

_unsafe_execute!(p::cLoopPlan{T}, X::Ptr{T}, Y::Ptr{T}) where {T <: fftwSingle} =
    @ccall libfftw3f[].fftwf_execute_dft(p::PlanPtr, X::Ptr{T}, Y::Ptr{T})::Cvoid

_unsafe_execute!(p::cLoopPlan{T}, X::Ptr{T}, Y::Ptr{T}) where {T <: fftwDouble} =
    @ccall libfftw3[].fftw_execute_dft(p::PlanPtr, X::Ptr{T}, Y::Ptr{T})::Cvoid

@noinline function unsafe_execute!(p::cLoopPlan{T}, X::Ptr{T}, Y::Ptr{T}, iodims) where {T <: fftwComplex}
    #TODO: Parallel loop is better than a parallel plan if the problem size is small.
    steps = map(io -> sizeof(T) .* io[2], iodims)
    iter = CartesianIndices(map(io -> 0:io[1] - 1, iodims))
    for I in iter
        X′, Y′ = mapreduce(.*, .+, I.I, steps; init = (X, Y))
        _unsafe_execute!(p, X′, Y′)
    end
end

function unsafe_execute!(p::cLoopPlan{T}, x::StridedArray{T}, y::StridedArray{T}) where {T <: fftwComplex}
    X, Y = pointer(x), pointer(y)
    loop = p.loop
    GC.@preserve x y begin
        length(loop) == 0 && return unsafe_execute!(p, X, Y, ())
        length(loop) == 1 && return unsafe_execute!(p, X, Y, (loop[1],))
        length(loop) == 2 && return unsafe_execute!(p, X, Y, (loop[1], loop[2]))
        unsafe_execute!(p, X, Y, (loop...,))
    end
end

function mul!(y::StridedArray{T,N}, p::cLoopPlan{T}, x::StridedArray{T,N}) where {T,N}
    assert_applicable(p, x, y)
    unsafe_execute!(p, x, y)
    y
end

function *(p::cLoopPlan{T,K,inplace}, x::StridedArray{T,N}) where {T,K,N,inplace}
    assert_applicable(p, x)
    y = inplace ? x : Array{T,N}(undef, p.osz)
    unsafe_execute!(p, x, y)
    y
end

MightNeedLoop{T} = Union{StridedArray{T,3}, StridedArray{T,4}, StridedArray{T,5}, StridedArray{T,6}, StridedArray{T,7}}
for inplace in (false,true)
    for (f,direction) in ((:fft,FORWARD), (:bfft,BACKWARD))
        plan_f = inplace ? Symbol("plan_",f,"!") : Symbol("plan_",f)
        @eval $plan_f(X::MightNeedLoop{<:fftwComplex}, region;
                    flags::Integer=ESTIMATE,
                    timelimit::Real=NO_TIMELIMIT) = begin
            T, N = eltype(X), ndims(X)
            Y = $inplace ? X : FakeArray{T}(size(X))
            cLoopPlan{T,$direction,$inplace}(X, Y, region, flags, timelimit)
        end
        idirection = -direction
        @eval function plan_inv(p::cLoopPlan{T,$direction,$inplace}) where {T<:fftwComplex}
            X = Array{T}(undef, p.sz)
            Y = $inplace ? X : FakeArray{T}(size(X))
            ScaledPlan(cLoopPlan{T,$idirection,$inplace}(X, Y, p.region,
                                                          p.flags, NO_TIMELIMIT),
                       normalization(X, p.region))
        end
    end
end


text:
idsingletons(obj::AbstractVector) = filter(elem -> length(elem) == 1, obj)
idsingletons(obj::AbstractVector{T}) where T <: AbstractVector = first.(filter(elem -> length(elem) == 1, obj))
function dropsingletons!(obj::Vector{Vector{Vector{Int64}}})
	todrop = Vector{Int64}()
	m = sum(length.(first(obj)))
	while true
		tmp = reduce(union, idsingletons.(obj))
		if isempty(tmp)
			return m, todrop
		else
			for dimension ∈ obj
				for fixedeffect ∈ dimension
					filter!(elem -> elem ∉ tmp, fixedeffect)
				end
				filter!(!isempty, dimension)
			end
			append!(todrop, tmp)
		end
	end
end
function remapping!(obj::Vector{Vector{Vector{Int64}}},
	remapper::Dict{Int64,Int64})
	for dimension ∈ obj
		for fixedeffect ∈ dimension
			fixedeffect[:] = get.(remapper, fixedeffect, 0)
		end
	end
end
function makeremapper(m::Integer, singletons::Vector{Int64})
	mapper = Int.(hcat(setdiff(1:m, singletons), 1:(m - length(singletons))))
	output = Dict{Int64,Int64}()
	for i ∈ 1:size(mapper,1)
		output[mapper[i,1]] = mapper[i,2]
	end
	return output
end


text:
#
# Perform multiple trials to find gloal minimum
#
function find_best_fit(model, X, Y, np, options, lower, upper)
  local best_fit
  local fit
  best = +Inf
  nbest = 0
  ntrial = 1
  p0 = Vector{Float64}(undef,np)
  while nbest <= options.nbest && ntrial <= options.maxtrials
    ntrial += 1
    try
      initP!(p0,options,lower,upper)
      fit = curve_fit(model, X, Y, p0, lower=lower, upper=upper)
      sum_residues = sum(fit.resid.^2)
      if abs(sum_residues - best) < options.besttol
        nbest = nbest + 1
        if sum_residues < best
          best = sum_residues
          best_fit = deepcopy(fit)
        end
      elseif sum_residues < best
        nbest = 1
        best = sum_residues
        best_fit = deepcopy(fit)
      end
    catch msg
      if options.debug
        error("ERROR: $msg \n $fit")
      end
    end
  end
  if nbest == 0
error(" Could not obtain any successful fit, probably the data is not well posed.
        Further information can be obtained by adding Option(debug=true) to the input.")
  end
  return best_fit
end


text:
######################################################################
# observations.jl
#
# Contains everything needed for the observation function.
######################################################################

"""
`O(m::SearchDomain, x::Vehicle, theta, o::Obs)`

Arguments:

 * `m` is a `SearchDomain`
 * `x` is a `Vehicle`
 * `theta` is a possible jammer location
 * `o` is an observation, 0 to 35

Returns probability of observing `o` from `(xp, theta)` in domain `m`.
"""
function O(m::SearchDomain, x::Vehicle, theta, o::Obs)

	# Calculate true bearing, and find distance to bin edges
	xp = (x.x, x.y)
	ang_deg = true_bearing(xp, theta)
	rel_start, rel_end = rel_bin_edges(ang_deg, o)

	# now look at probability
	#p = cdf(m.d, deg2rad(rel_end)) - cdf(m.d, deg2rad(rel_start))
	p = cdf(m.d, rel_end) - cdf(m.d, rel_start)
	return p
end

function O(m::SearchDomain, xv::Float64, yv::Float64, theta, o::Obs)

	# Calculate true bearing, and find distance to bin edges
	xp = (xv, yv)
	ang_deg = true_bearing(xp, theta)
	rel_start, rel_end = rel_bin_edges(ang_deg, o)

	# now look at probability
	#p = cdf(m.d, deg2rad(rel_end)) - cdf(m.d, deg2rad(rel_start))
	p = cdf(m.d, rel_end) - cdf(m.d, rel_start)
	return p
end

"""
`observe(m::SearchDomain, X::VehicleSet)`

Returns a set of possible observations for vehicles in set `X`.
	The output is a vector of observations, one per vehicle.
"""
function observe(m::SearchDomain, X::VehicleSet)
	n = length(X)
	Z = Array(Obs, 0)
	for xi in X
		obs_probs = Array(Float64, 0)
		for o in 0:35
			push!(obs_probs, O(m, xi, m.theta, o))
		end
		push!(Z, sample(0:35, WeightVec(obs_probs)))
	end
	return Z
end

# Find the relative offset
function rel_bin_edges(bearing_deg, o::Obs)

	# calculate start, end degrees of bin
	start_deg, end_deg = bin2deg(o)

	# compute relative distance to true bearing
	rel_start = fit_180(bearing_deg - start_deg)
	rel_end = fit_180(bearing_deg - end_deg)

	# Make sure start is further left on number line
	if rel_end < rel_start
		temp = rel_start
		rel_start = rel_end
		rel_end = temp
	end

	# Handle odd case where we stradle 180 degrees off
	if (rel_start < 0) && (rel_end > 100)
		rel_start = rel_end
		rel_end += 10
	end

	return rel_start, rel_end
end

# Fits an angle into -180 to 180
# Assume the angle is within -360 to 360
function fit_180(angle)
	if angle > 180
		angle = 360 - angle
	elseif angle < -180
		angle += 360
	end
	return angle
end

# Find the true angle between UAV and jammer.
#
# Parameters:
#  xp - location of vehicle
#  theta - location of jammer
#
# Returns true angle, measured from north, in degrees.
function true_bearing(xp, theta)

	xr = theta[1] - xp[1]
	yr = theta[2] - xp[2]
	return mod(rad2deg(atan2(xr,yr)), 360)
end

# What bin does degree fall into?
function findbin(degree)
	deg_bin = round(Int, degree / 10, RoundNearestTiesAway)
	if deg_bin == 36
		deg_bin = 0
	end
	return deg_bin
end

# returns (start_deg, end_deg) integer tuple
function bin2deg(bin_deg::Int64)
	if bin_deg == 0
		start_val = -5
		end_val = 5
	else
		start_val = 10bin_deg - 5
		end_val  = 10bin_deg + 5
	end
	return (start_val, end_val)
end


text:
module Configurations

using TOML
using ExproniconLite
using OrderedCollections

export @option,
    @type_alias,
    # main interface
    from_dict,
    from_kwargs,
    from_toml,
    to_dict,
    to_toml,
    # builtin types
    no_default,
    Maybe,
    Reflect,
    OptionField,
    # reflection
    field_default,
    # field_alias,
    type_alias,
    # traits
    is_option,
    # parse
    from_dict,
    from_kwargs,
    from_toml,
    from_toml_if_exists,
    # serialize
    to_dict,
    DuplicatedFieldError,
    DuplicatedAliasError,
    InvalidKeyError,
    TOMLStyle,
    YAMLStyle,
    JSONStyle

include("compat.jl")
include("errors.jl")
include("types.jl")
include("convert.jl")
include("reflection.jl")
include("utils.jl")
include("codegen.jl")

include("from_dict.jl")
include("from_kwargs.jl")
include("from_toml.jl")
# include("parse.jl")
include("serialize.jl")

end


text:
import Base: +, length, size, ==

#-------------------------------------------------------------------------------
#   MODEL STRUCT DEFINITION
#-------------------------------------------------------------------------------

mutable struct Model
    G::Lar.Points
    T::Array{Lar.ChainOp, 1}

    function Model(V::Lar.Points, T::Array{Lar.ChainOp, 1})
        dim, npts = size(V)
        dim > 0 ||
            throw(ArgumentError("At least one point is needed."))
        length(T) == dim ||
            throw(ArgumentError("Topology is not coherent with Geometry."))

        isempty(T[1]) || size(T[1], 2) == npts ||
            throw(ArgumentError("Topology not coherent with Geometry."))
        for i = 2 : dim
            isempty(T[i-1]) || isempty(T[i]) ||
                size(T[i], 2) == size(T[i-1],1) ||
                throw(ArgumentError("Topology not coherent with Topology."))
        end

        new(V, T)
    end

    function Model(V::Lar.Points)
        T = convert(Array{Lar.ChainOp,1},
            [SparseArrays.spzeros(Int8, 0, 0) for i = 1 : size(V, 1)]
        )
        T[1] = convert(Lar.ChainOp, SparseArrays.spzeros(Int8, 0, size(V,2)))
        Lar.Model(V, T)
    end

    function Model()
        nothing
    end
end

#-------------------------------------------------------------------------------
#   BASIC PROPERTIES
#-------------------------------------------------------------------------------

length(m::Lar.Model)               = size(m.G, 1)
size(m::Lar.Model)		           = size(m.G)
size(m::Lar.Model, i::Int)         = i == 0 ? size(m.G   ) : size(m.T[i]   )
size(m::Lar.Model, i::Int, j::Int) = i == 0 ? size(m.G, j) : size(m.T[i], j)
==(m1::Lar.Model, m2::Lar.Model)   = m1.G == m2.G && m1.T == m2.T

#-------------------------------------------------------------------------------
#   OTHER BASE REIMPLEMENTATIONS
#-------------------------------------------------------------------------------

Base.copy(m::Lar.Model)     = Lar.Model(m.G, m.T)
Base.deepcopy(m::Lar.Model) = Lar.Model(Base.deepcopy(m.G), Base.deepcopy(m.T))

#-------------------------------------------------------------------------------
#   GEOMETRY MANIPULATION
#-------------------------------------------------------------------------------

function addModelVertex!(m::Lar.Model, v::Array{Float64, 1})::Nothing
    length(V) == length(v) ||
        throw(ArgumentError("Point dimension mismatch."))
    m.G = [m.G v];

    if isempty(m.T[1])
        m.T[1] = SparseArrays.spzeros(size(G, 0, 2), 0)
        m.T[1] = [m.T[1] SparseArrays.pzeros(Int8, m.T[1].m, 1)]
    end

end

function deleteModelVertex!(m::Lar.Model, v::Int)::Nothing
    deleteModelVertices!(m, [v])
end

function deleteModelVertices!(m::Lar.Model, vs::Array{Int,1})::Nothing
    tokeepV = setdiff(collect(1 : size(m, 0, 2)), vs);
    m.G     = m.G[:, tokeepV]

    if !isempty(m.T[1])
        # From EV must be deleted all the columns linked to a deleted vertex
        #  and all rows related to a dangling edge
        todelE = abs.(m.T[1][:, vs])
        todelE = [l for l = 1 : todelE.m if sum(todelE[l, :]) != 0]
        m.T[1] = m.T[1][:, tokeepV]
        if !isempty(todelE) Lar.deleteModelCells!(m, 1, todelE) end
    end

    return
end

#-------------------------------------------------------------------------------
#   TOPOLOGY MANIPULATION
#-------------------------------------------------------------------------------

function addModelCells!(m::Lar.Model, deg::Int, cs::Lar.ChainOp)::Nothing
    deg > 0 || throw(ArgumentError("Degree must be a non negative value"))
    deg ≤ length(m) || throw(ArgumentError("The model do not have degree $deg"))
    (cs.n == size(m, deg - 1, 1) && deg > 1) ||
        (cs.n == size(m, deg - 1, 2) && deg == 1) ||
        throw(ArgumentError("Incoherent Chain Operator size"))

    # Adding input cells to the topological structure
    m.T[deg] = [m.T[deg]; cs]

    # Adding slot for the new cells to the higher order cells
    if deg < length(m)
        m.T[deg + 1] = [
            m.T[deg + 1] SparseArrays.spzeros(Int8, size(m, deg + 1, 1), cs.m)
        ]
    end

    return
end
function addModelCell!(m::Lar.Model, deg::Int, c::Lar.Cell)::Nothing
    Lar.addModelCells!(m, deg, convert(Lar.ChainOp, c))
end
function addModelCells!(m::Lar.Model, deg::Int, cs::Lar.Cells)::Nothing
    I = Array{Int,1}()
    J = Array{Int,1}()
    K = Array{Int8,1}()
    for i = 1 : length(cs)
        for j = 1 : length(cs[i])
            push!(I, i)
            push!(J, cs[i][j])
            push!(K, 1)
        end
    end

    scs = SparseArrays.sparse(I, J, K, length(cs), size(m, deg, 2));

    return addModelCells!(m, deg, scs);
end

function deleteModelCells!(m::Lar.Model, deg::Int, cs::Array{Int, 1})::Nothing
    deg > 0 || throw(ArgumentError("Degree must be a non negative value"))
    deg ≤ length(m) || throw(ArgumentError("The model do not have degree $deg"))
    !isempty(m.T[deg]) ||
        throw(ArgumentError("There are no cells of degree $deg"))
    max(cs...) ≤ size(m, deg, 1) ||
        throw(ArgumentError("There are not $(max(cs...)) cells of degree $deg"))

    # Removing `cs` rows from `m.T[deg]`
    tokeep     = setdiff(collect(1 : size(m, deg, 1)), cs)
    m.T[deg]   = m.T[deg][tokeep, :]

    if deg == length(m) return end

    # Removing `cs` cols from `m.T[deg+1]` by checking if some `deg+1` cell
    #  has to be removed too.
    # An higher ord cell must be removed if it contains a removed lower ord cell
    todelHo    = m.T[deg + 1][:, cs]
    m.T[deg+1] = m.T[deg + 1][:, tokeep]
    if isempty(m.T[deg+1]) return end
    todelHo    = [l for l = 1 : todel.m if sum(todelE[l, :]) != 0]
    if !isempty(todelHo) Lar.deleteModelCells!(m, deg+1, todelHo) end
    return
end

function deleteModelCell!(m::Lar.Model, deg::Int, c::Int)::Nothing
    Lar.deleteModelCells!(m, deg, [c])
end

function getModelLoCell(m::Lar.Model, deg::Int, c::Int)::Array{Int, 1}
    deg > 0 || throw(ArgumentError("Degree must be a non negative value"))
    deg ≤ length(m) || throw(ArgumentError("The model do not have degree $deg"))
    return m.T[deg][c, :].nzind
end

function getModelCellVertices(m::Lar.Model, deg::Int, c::Int)
    deg > 0 || throw(ArgumentError("Degree must be a non negative value"))
    deg ≤ length(m) || throw(ArgumentError("The model do not have degree $deg"))
    set = [c]
    for d = deg : -1 : 1
        set = ∪([m.T[d][el, :].nzind for el in set]...)
    end

    return map(i -> m.G[:, set[i]], 1:length(set))
end

#-------------------------------------------------------------------------------
#   MODEL MANIPULATION
#-------------------------------------------------------------------------------

"""
    modelPurge!(m::Lar.Model, [depth::Int = 0])::Nothing

Purges the model Geometry from unused elements.

Purges each Geometry element that is not related to a topological Cell.
If the optional argument `depth` is specified than it also purges all the
topological cells of degree lower or equal to depth that are not related
to an higher order topological cell.
"""
function modelPurge!(m::Lar.Model, depth::Int = 0)::Nothing
    depth < length(m) ||
        throw(ArgumentError("The model do not have degree $(depth+1)"))

    for d = depth : -1 : 1
        todel = [i for i = 1 : size(m, d+1, 2) if sum(abs.(m.T[d+1][:,i])) == 0]
        if !isempty(todel) Lar.deleteModelCells!(m, d, todel) end
    end
    todel = [i for i = 1 : size(m, 1, 2) if sum(abs.(m.T[1][:, i])) == 0]
    if !isempty(todel) Lar.deleteModelVertices!(m, todel) end
    return
end

#-------------------------------------------------------------------------------
#   MODEL CONVERSION TOPOLOGICAL ↔ GEOMETRICAL
#-------------------------------------------------------------------------------

#=
function getGeometricalModel(tm::Lar.Model)::Lar.Model
    tm.topological || throw(ArgumentError("Model must be Topological"))
    gm = deepcopy(tm)
    gm.topological = false
    for i = 2 : length(gm)
        for j = i-1 : -1 : 1
            gm.T[i] = abs.(gm.T[i])*gm.T[j]
        end
    end
    return gm
end

function getTopologicalModel(gm::Lar.Model)::Lar.Model
    !gm.topological || throw(ArgumentError("Model must be Geometrical"))
    tm = deepcopy(gm)
    tm.topological = true
    for i = 2 : length(tm)
        for j = i-1 : -1 : 1
            #...
            throw(Error("Not Coded"))
        end
    end
    return tm
end
=#

#TODO check if removing sparse zeros is necessary

function viewModel(model::Lar.Model, exp::Float64 = 1.)
    # visualization of numbered arrangement
    VV = [[k] for k = 1 : size(model, 0, 2)]
    EV = LAR.cop2lar(model.T[1]);
    FE = LAR.cop2lar(model.T[2]);
    FV = cat([[EV[e] for e in face] for face in FE])

    # final solid visualization
    triangulated_faces = LAR.triangulate2D(
        convert(Lar.Points, model.G'), [model.T[1], model.T[2]]
    )
    FVs = convert(Array{Lar.Cells}, triangulated_faces)
    GL.VIEW(GL.GLExplode(model.G,FVs,exp,exp,exp,99,1));

    # polygonal face boundaries
    EVs = LAR.FV2EVs(model.T[1], model.T[2])
    EVs = convert(Array{Array{Array{Int64,1},1},1}, EVs)
    GL.VIEW(GL.GLExplode(model.G,EVs,exp,exp,exp,1,1));
end


text:
using FileIO
using Parameters
using Statistics
include("LS_calculations.jl")

#=
Change these parameters to inform the analysis which eta values to check,
which directory to search in, how many network realizations to expect,
and also information about timesteps and dt.
=#
etas = -1.0:0.1:1.0
dir = "results1"
outdir = "results1-analysis"
trials = 20
N = 3000
dt = 0.01
maxlag_steps = 100000

# Allocate space to store the autocorrelation and Lyapunov spectrum data
avg_autocorrs = Array{Float64,3}(undef, maxlag_steps + 1, trials, length(etas))
PCA_dims = Array{Float64,2}(undef, trials, length(etas))
Lspecs = Array{Float64,3}(undef, N, trials, length(etas))
max_LEs = Array{Float64,2}(undef, trials, length(etas))

avg_autocorrs_trial_counts = zeros(Int64, length(etas))
Lspecs_trial_counts = zeros(Int64, length(etas))

#=
Finds and loads all jld2 files, then checks their keys to see if
they contain the data that we need to plot stuff
=#
for (path, dirname, filenames) in walkdir(dir)
    for fn in filenames
        if endswith(fn, ".jld2") && startswith(fn, "AC_PCAdim")
            # Next experiment, save the eta parameter. Regexes are annoying
            eta = parse(Float64, match(r",eta=[0-9.-]+,", fn).match[6:end-1])
            match_indices = isapprox.(etas, eta)
            sum(match_indices) != 1 && @warn "Multiple eta values for file $fn found"
            if any(match_indices)
                etaind = findlast(match_indices)
                # Increment the trial counts
                avg_autocorrs_trial_counts[etaind] += 1
                trial_count = avg_autocorrs_trial_counts[etaind]
                # Fill the appropriate vector in the data array
                avg_autocorrs[:,trial_count,etaind] = load(joinpath(path, fn),
                        "avg_C")
                PCA_dims[trial_count,etaind] = load(joinpath(path, fn), "PR")
            else
                @warn "File $fn with invalid eta value found"
            end
        elseif endswith(fn, ".jld2") && startswith(fn, "Lspec")
            eta = load(joinpath(path, fn), "eta")
            match_indices = isapprox.(etas, eta)
            sum(match_indices) != 1 && @warn "Multiple eta values for file $fn found"
            if any(match_indices)
                etaind = findlast(match_indices)
                # Increment the trial counts
                Lspecs_trial_counts[etaind] += 1
                trial_count = Lspecs_trial_counts[etaind]
                # Fill the appropriate vector in the data array
                Lspecs[:,trial_count,etaind] = load(joinpath(path, fn),
                        "Lspec")
                max_LEs[trial_count,etaind] = load(joinpath(path, fn),
                        "max_LE")
            else
                @warn "File $fn with invalid eta value found"
            end
        end
    end
end

# Validate that we got all the data
for (index, count1, count2) in zip(1:length(etas), avg_autocorrs_trial_counts, Lspecs_trial_counts)
    if count1 != trials
        @warn "Found only $count1 of $trials autocorr data files for eta=$(etas[index])"
    end
    if count2 != trials
        @warn "Found only $count2 of $trials Lspec data files for eta=$(etas[index])"
    end
end

# Autocorrelation stats
ensbl_avg_Cs = reshape(mean(avg_autocorrs, dims=2),
        (maxlag_steps+1, length(etas)))
ensbl_std_Cs = reshape(std(avg_autocorrs, dims=2),
        (maxlag_steps+1, length(etas)))
timelags = dt .* collect(0:maxlag_steps)

# PCA dimension stats
avg_PCA_dims = vec(mean(PCA_dims, dims=1))
std_PCA_dims = vec(std(PCA_dims, dims=1))

# Lyapunov spectrum & max Lyapunov exponent stats
ensbl_avg_Lspecs = reshape(mean(Lspecs, dims=2), (N, length(etas)))
ensbl_std_Lspecs = reshape(std(Lspecs, dims=2), (N, length(etas)))
ensbl_avg_max_LE = vec(mean(max_LEs, dims=1))
ensbl_std_max_LE = vec(std(max_LEs, dims=1))

# Dimensionality and entropy rate stats
entropy_rates = reshape(mapslices(KS_entropy_rate, Lspecs, dims=1),
        (trials, length(etas)))
attractor_dims = reshape(mapslices(KY_attractor_dim, Lspecs, dims=1),
        (trials, length(etas)))
avg_entropy_rates = vec(mean(entropy_rates, dims=1))
std_entropy_rates = vec(std(entropy_rates, dims=1))
avg_attractor_dims = vec(mean(attractor_dims, dims=1))
std_attractor_dims = vec(std(attractor_dims, dims=1))

# Save all the statistics that we calculated
out = Dict{String,Any}()
@pack! out = ensbl_avg_Cs, ensbl_std_Cs, timelags, ensbl_avg_Lspecs,
        ensbl_std_Lspecs, ensbl_avg_max_LE, ensbl_std_max_LE, avg_PCA_dims,
        std_PCA_dims, avg_entropy_rates, std_entropy_rates,
        avg_attractor_dims, std_attractor_dims
output_fn = "summary_stats_for_plotting_results1.jld2"
save(joinpath(outdir, output_fn), out)


text:
"""
    SquareEuclideanDistance(X)

Returns the squared Grahm aka the euclidean distance matrix of `X`.
"""
SquareEuclideanDistance(X) = ( sum(X .^ 2, dims = 2) .+ sum(X .^ 2, dims = 2)') .- (2 * X * X')

"""
    EuclideanDistance(X)

Returns the Grahm aka the euclidean distance matrix of `X`.
"""
EuclideanDistance(X) = sqrt.(abs.(SquareEuclideanDistance(X)))

"""
    SquareEuclideanDistance(X, Y)

Returns the squared euclidean distance matrix of X and Y such that the columns are the samples in Y.
"""
SquareEuclideanDistance(X, Y) = ( sum(X .^ 2, dims = 2) .+ sum(Y .^ 2, dims = 2)') .- (2 * X * Y')

"""
    EuclideanDistance(X, Y)

Returns the euclidean distance matrix of X and Y such that the columns are the samples in Y.
"""
EuclideanDistance(X, Y) = sqrt.(abs.(SquareEuclideanDistance(X, Y)))

"""
    ManhattanDistance(X)

Returns the Manhattan distance matrix of `X`.
"""
function ManhattanDistance(X)
    Result = zeros(size(X)[1], size(X)[1])
    for rowx in 2 : (size(X)[1]), rowy in 1 : (rowx-1)
        Result[rowx, rowy] = sum( abs.( X[rowx,:] - X[rowy,:]  ) )
        Result[rowy, rowx] = Result[rowx, rowy]
    end
    return Result
end

"""
    ManhattanDistance(X, Y)

Returns the Manhattan distance matrix of X and Y such that the columns are the samples in Y.
"""
function ManhattanDistance(X, Y)
    Result = zeros(size(X)[1], size(Y)[1])
    for rowx in 1 : (size(X)[1]), rowy in 1 : size(Y)[1]
        Result[rowx, rowy] = sum( abs.( X[rowx,:] - Y[rowy,:] ) )
    end
    return Result
end

"""
    MinkowskiDistance(X, p)

Returns the Manhattan distance matrix of `X` using order `p`.
"""
function MinkowskiDistance(X, p)
    Result = zeros(size(X)[1], size(X)[1])
    for rowx in 2 : (size(X)[1]), rowy in 1 : (rowx-1)
        Result[rowx, rowy] = sum( abs.( X[rowx,:] - X[rowy,:] ) .^ p ) .^ (1.0 / p)
        Result[rowy, rowx] = Result[rowx, rowy]
    end
    return Result
end

"""
    MinkowskiDistance(X, Y, p)

Returns the Minkowski distance matrix of `X` and `Y` using order `p` such that the columns are the samples in `Y`.
"""
function MinkowskiDistance(X, Y, p)
    Result = zeros(size(X)[1], size(Y)[1])
    for rowx in 1 : (size(X)[1]), rowy in 1 : size(Y)[1]
        Result[rowx, rowy] = sum( abs.( X[rowx,:] - Y[rowy,:] ) .^ p ) .^ ( 1.0 / p )
    end
    return Result
end

"""
    LevenshteinDistance(s::AbstractString, t::AbstractString)

Calculates the LevenshteinDistance aka the edit distance between 2 strings.

Borrowed from: https://rosettacode.org/wiki/Levenshtein_distance#Julia
"""
function LevenshteinDistance(s::AbstractString, t::AbstractString)
    ls, lt = length.((s, t))
    ls == 0 && return lt
    lt == 0 && return ls

    s₁, t₁ = s[2:end], t[2:end]
    ld₁ = LevenshteinDistance(s₁, t₁)
    s[1] == t[1] ? ld₁ : 1 + min(ld₁, LevenshteinDistance(s, t₁), LevenshteinDistance(s₁, t))
end

"""
    NearestNeighbors(DistanceMatrix, N)

Returns a matrix of dimensions DistanceMatrix rows, by N columns. Basically this
goes through each row and finds the ones corresponding column which has the smallest distance.
"""
function NearestNeighbors(DistanceMatrix, N)
    Result = zeros( size( DistanceMatrix )[ 1 ], N )
    for rowx in 1 : ( size( DistanceMatrix )[ 1 ] )
        Result[rowx, :] = sortperm( DistanceMatrix[ rowx, : ] )[ 1 : N ]
    end
    return Result
end

"""
    NearestNeighbors(DistanceMatrix)

Returns the nearest neighbor adjacency matrix from a given `DistanceMatrix`.
"""
function AdjacencyMatrix(DistanceMatrix)
    Result = zeros( size( DistanceMatrix )[ 1 ], N )
    for rowx in 1 : ( size( DistanceMatrix )[ 1 ] )
        NN = sortperm( DistanceMatrix[ rowx, : ] )[ 1 : N ]
        Result[ rowx, : ] = NN
        #Result[ : , rowx] = NN
    end
    return Result
end

"""
    InClassAdjacencyMatrix(DistanceMatrix, YHOT, K = 1)

Computes the in class Adjacency matrix with K nearest neighbors.
"""
function InClassAdjacencyMatrix(DistanceMatrix, YHOT, K = 1)
    Result = zeros( size( DistanceMatrix ) )
    for rowx in 1 : ( size( DistanceMatrix )[ 1 ] )
        ClassNumber = findfirst( yh -> yh == 1, YHOT[ rowx, : ] )
        ClassInstances = findall( YHOT[ :, ClassNumber ] .== 1 )
        ClassInstances = setdiff(ClassInstances, rowx)
        k = K
        if length(ClassInstances) < K
            k = length(ClassInstances)
        end
        NN = sortperm( DistanceMatrix[ rowx, ClassInstances ] )[ 1 : k ]
        Result[ rowx, NN ] .= 1#.+= 1
    end
    return Result
end

"""
    OutOfClassAdjacencyMatrix(DistanceMatrix, YHOT, K = 1)

Computes the out of class Adjacency matrix with K nearest neighbors.
"""
function OutOfClassAdjacencyMatrix(DistanceMatrix, YHOT, K = 1)
    Result = zeros( size( DistanceMatrix ) )
    for rowx in 1 : ( size( DistanceMatrix )[ 1 ] )
        ClassNumber = findfirst( yh -> yh == 1, YHOT[ rowx, : ] )
        ClassInstances = findall( YHOT[ :, ClassNumber ] .== 0 )
        k = K
        if length(ClassInstances) < K
            k = length(ClassInstances)
        end
        NN = sortperm( DistanceMatrix[ rowx, ClassInstances ] )[ 1 : k ]
        Result[ rowx, NN ] .= 1#.+= 1
    end
    return Result
end

struct Kernel
    params::Union{Float64, Tuple}
    ktype::String
    original::Array
end

"""
    Kernel(X::Array)

Default constructor for Kernel object. Returns the linear kernel of `X`.
"""
Kernel( X::Array ) = Kernel(0.0, "linear", X)

"""
    (K::Kernel)(X)

This is a convenience function to allow for one-line construction of kernels from a Kernel object `K` and new data `X`.
"""
function (K::Kernel)(X)
    if K.ktype == "linear"
        return LinearKernel(K.original, X, K.params)
    elseif K.ktype == "gaussian" || K.ktype == "rbf"
        return GaussianKernel(K.original , X, K.params)
    end
end

"""
    LinearKernel(X, c)

Creates a Linear kernel from Array `X` and hyperparameter `C`.
"""
LinearKernel(X, c) =  (X * X') .+ c

"""
    LinearKernel(X, Y, c)

Creates a Linear kernel from Arrays `X` and `Y` with hyperparameter `C`.
"""
LinearKernel( X, Y, c ) = (Y * X') .+ c

"""
    GaussianKernel(X, sigma)

Creates a Gaussian/RBF kernel from Array `X` using hyperparameter `sigma`.
"""
function GaussianKernel( X, sigma )
    Gamma = -1.0 / (2.0 * sigma^2)
    return exp.( SquareEuclideanDistance(X) .* Gamma  )
end

"""
    GaussianKernel(X, Y, sigma)

Creates a Gaussian/RBF kernel from Arrays `X` and `Y` with hyperparameter `sigma`.
"""
function GaussianKernel(X, Y, sigma)
    Gamma = -1.0 / (2.0 * sigma^2)
    return exp.( SquareEuclideanDistance(Y, X) .* Gamma  )
end

"""
    CauchyKernel(X, sigma)

Creates a Cauchy kernel from Array `X` using hyperparameters `sigma`.
"""
function CauchyKernel(X, sigma)
    return 1.0 ./ ( (pi * sigma) .* (1.0 .+ ( SquareEuclideanDistance(X) ./ sigma) .^ 2  ) )
end

"""
    CauchyKernel(X, Y, sigma)

Creates a Cauchy kernel from Arrays `X` and `Y` using hyperparameters `sigma`.
"""
function CauchyKernel(X, Y, sigma)
    return 1.0 ./ ( (pi * sigma) .* (1.0 .+ ( SquareEuclideanDistance(Y, X) ./ sigma) .^ 2  ) )
end

"""
    CenterKernelMatrix(X)

Returns a centered kernel matrix.
"""
function CenterKernelMatrix(K, n = first( size( K ) ) )
    Obs = first( size( X ) )
    Ones = ones(Obs, Obs) / n
    return (LinearAlgebra.I - Ones) * K * (LinearAlgebra.I - Ones)
end


text:
run(`ls`)
run(`echo hello world`)
cd("test")
run(`ls`)
cd("..")
run(`ls`)