text:
# Automatically generated using Clang.jl wrap_c, version 0.0.0

#using Compat

const cuDeviceTotalMem = cuDeviceTotalMem_v2
const cuCtxCreate = cuCtxCreate_v2
const cuModuleGetGlobal = cuModuleGetGlobal_v2
const cuMemGetInfo = cuMemGetInfo_v2
const cuMemAlloc = cuMemAlloc_v2
const cuMemAllocPitch = cuMemAllocPitch_v2
const cuMemFree = cuMemFree_v2
const cuMemGetAddressRange = cuMemGetAddressRange_v2
const cuMemAllocHost = cuMemAllocHost_v2
const cuMemHostGetDevicePointer = cuMemHostGetDevicePointer_v2

# Skipping MacroDefinition: cuMemcpyHtoD __CUDA_API_PTDS ( cuMemcpyHtoD_v2 )
# Skipping MacroDefinition: cuMemcpyDtoH __CUDA_API_PTDS ( cuMemcpyDtoH_v2 )
# Skipping MacroDefinition: cuMemcpyDtoD __CUDA_API_PTDS ( cuMemcpyDtoD_v2 )
# Skipping MacroDefinition: cuMemcpyDtoA __CUDA_API_PTDS ( cuMemcpyDtoA_v2 )
# Skipping MacroDefinition: cuMemcpyAtoD __CUDA_API_PTDS ( cuMemcpyAtoD_v2 )
# Skipping MacroDefinition: cuMemcpyHtoA __CUDA_API_PTDS ( cuMemcpyHtoA_v2 )
# Skipping MacroDefinition: cuMemcpyAtoH __CUDA_API_PTDS ( cuMemcpyAtoH_v2 )
# Skipping MacroDefinition: cuMemcpyAtoA __CUDA_API_PTDS ( cuMemcpyAtoA_v2 )
# Skipping MacroDefinition: cuMemcpyHtoAAsync __CUDA_API_PTSZ ( cuMemcpyHtoAAsync_v2 )
# Skipping MacroDefinition: cuMemcpyAtoHAsync __CUDA_API_PTSZ ( cuMemcpyAtoHAsync_v2 )
# Skipping MacroDefinition: cuMemcpy2D __CUDA_API_PTDS ( cuMemcpy2D_v2 )
# Skipping MacroDefinition: cuMemcpy2DUnaligned __CUDA_API_PTDS ( cuMemcpy2DUnaligned_v2 )
# Skipping MacroDefinition: cuMemcpy3D __CUDA_API_PTDS ( cuMemcpy3D_v2 )
# Skipping MacroDefinition: cuMemcpyHtoDAsync __CUDA_API_PTSZ ( cuMemcpyHtoDAsync_v2 )
# Skipping MacroDefinition: cuMemcpyDtoHAsync __CUDA_API_PTSZ ( cuMemcpyDtoHAsync_v2 )
# Skipping MacroDefinition: cuMemcpyDtoDAsync __CUDA_API_PTSZ ( cuMemcpyDtoDAsync_v2 )
# Skipping MacroDefinition: cuMemcpy2DAsync __CUDA_API_PTSZ ( cuMemcpy2DAsync_v2 )
# Skipping MacroDefinition: cuMemcpy3DAsync __CUDA_API_PTSZ ( cuMemcpy3DAsync_v2 )
# Skipping MacroDefinition: cuMemsetD8 __CUDA_API_PTDS ( cuMemsetD8_v2 )
# Skipping MacroDefinition: cuMemsetD16 __CUDA_API_PTDS ( cuMemsetD16_v2 )
# Skipping MacroDefinition: cuMemsetD32 __CUDA_API_PTDS ( cuMemsetD32_v2 )
# Skipping MacroDefinition: cuMemsetD2D8 __CUDA_API_PTDS ( cuMemsetD2D8_v2 )
# Skipping MacroDefinition: cuMemsetD2D16 __CUDA_API_PTDS ( cuMemsetD2D16_v2 )
# Skipping MacroDefinition: cuMemsetD2D32 __CUDA_API_PTDS ( cuMemsetD2D32_v2 )

const cuMemcpyHtoDAsync = cuMemcpyHtoDAsync_v2
const cuMemcpyDtoHAsync = cuMemcpyDtoHAsync_v2
const cuMemcpyDtoDAsync = cuMemcpyDtoDAsync_v2

const cuArrayCreate = cuArrayCreate_v2
const cuArrayGetDescriptor = cuArrayGetDescriptor_v2
const cuArray3DCreate = cuArray3DCreate_v2
const cuArray3DGetDescriptor = cuArray3DGetDescriptor_v2
const cuTexRefSetAddress = cuTexRefSetAddress_v2
const cuTexRefGetAddress = cuTexRefGetAddress_v2
const cuGraphicsResourceGetMappedPointer = cuGraphicsResourceGetMappedPointer_v2
const cuCtxDestroy = cuCtxDestroy_v2
const cuCtxPopCurrent = cuCtxPopCurrent_v2
const cuCtxPushCurrent = cuCtxPushCurrent_v2
const cuStreamDestroy = cuStreamDestroy_v2
const cuEventDestroy = cuEventDestroy_v2
const cuTexRefSetAddress2D = cuTexRefSetAddress2D_v3
const cuLinkCreate = cuLinkCreate_v2
const cuLinkAddData = cuLinkAddData_v2
const cuLinkAddFile = cuLinkAddFile_v2
const cuMemHostRegister = cuMemHostRegister_v2
const cuGraphicsResourceSetMapFlags = cuGraphicsResourceSetMapFlags_v2
const CUDA_VERSION = 7050
const CU_IPC_HANDLE_SIZE = 64

# Skipping MacroDefinition: CU_STREAM_LEGACY ( ( CUstream ) 0x1 )
# Skipping MacroDefinition: CU_STREAM_PER_THREAD ( ( CUstream ) 0x2 )

const CU_MEMHOSTALLOC_PORTABLE = 0x01
const CU_MEMHOSTALLOC_DEVICEMAP = 0x02
const CU_MEMHOSTALLOC_WRITECOMBINED = 0x04
const CU_MEMHOSTREGISTER_PORTABLE = 0x01
const CU_MEMHOSTREGISTER_DEVICEMAP = 0x02
const CU_MEMHOSTREGISTER_IOMEMORY = 0x04
const CUDA_ARRAY3D_LAYERED = 0x01
const CUDA_ARRAY3D_2DARRAY = 0x01
const CUDA_ARRAY3D_SURFACE_LDST = 0x02
const CUDA_ARRAY3D_CUBEMAP = 0x04
const CUDA_ARRAY3D_TEXTURE_GATHER = 0x08
const CUDA_ARRAY3D_DEPTH_TEXTURE = 0x10
const CU_TRSA_OVERRIDE_FORMAT = 0x01
const CU_TRSF_READ_AS_INTEGER = 0x01
const CU_TRSF_NORMALIZED_COORDINATES = 0x02
const CU_TRSF_SRGB = 0x10

# Skipping MacroDefinition: CU_LAUNCH_PARAM_END ( ( void * ) 0x00 )
# Skipping MacroDefinition: CU_LAUNCH_PARAM_BUFFER_POINTER ( ( void * ) 0x01 )
# Skipping MacroDefinition: CU_LAUNCH_PARAM_BUFFER_SIZE ( ( void * ) 0x02 )

const CU_PARAM_TR_DEFAULT = -1

typealias CUdeviceptr Culonglong
typealias CUdevice Cint
typealias CUctx_st Void
typealias CUcontext Ptr{CUctx_st}
typealias CUmod_st Void
typealias CUmodule Ptr{CUmod_st}
typealias CUfunc_st Void
typealias CUfunction Ptr{CUfunc_st}
typealias CUarray_st Void
typealias CUarray Ptr{CUarray_st}
typealias CUmipmappedArray_st Void
typealias CUmipmappedArray Ptr{CUmipmappedArray_st}
typealias CUtexref_st Void
typealias CUtexref Ptr{CUtexref_st}
typealias CUsurfref_st Void
typealias CUsurfref Ptr{CUsurfref_st}
typealias CUevent_st Void
typealias CUevent Ptr{CUevent_st}
typealias CUstream_st Void
typealias CUstream Ptr{CUstream_st}
typealias CUgraphicsResource_st Void
typealias CUgraphicsResource Ptr{CUgraphicsResource_st}
typealias CUtexObject Culonglong
typealias CUsurfObject Culonglong

immutable Array_16_UInt8
    d1::UInt8
    d2::UInt8
    d3::UInt8
    d4::UInt8
    d5::UInt8
    d6::UInt8
    d7::UInt8
    d8::UInt8
    d9::UInt8
    d10::UInt8
    d11::UInt8
    d12::UInt8
    d13::UInt8
    d14::UInt8
    d15::UInt8
    d16::UInt8
end

zero(::Type{Array_16_UInt8}) = begin  # /home/shindo/.julia/v0.4/Clang/src/wrap_c.jl, line 266:
        Array_16_UInt8(fill(zero(UInt8),16)...)
    end

immutable CUuuid_st
    bytes::Array_16_UInt8
end

immutable CUuuid
    bytes::Array_16_UInt8
end

immutable Array_64_UInt8
    d1::UInt8
    d2::UInt8
    d3::UInt8
    d4::UInt8
    d5::UInt8
    d6::UInt8
    d7::UInt8
    d8::UInt8
    d9::UInt8
    d10::UInt8
    d11::UInt8
    d12::UInt8
    d13::UInt8
    d14::UInt8
    d15::UInt8
    d16::UInt8
    d17::UInt8
    d18::UInt8
    d19::UInt8
    d20::UInt8
    d21::UInt8
    d22::UInt8
    d23::UInt8
    d24::UInt8
    d25::UInt8
    d26::UInt8
    d27::UInt8
    d28::UInt8
    d29::UInt8
    d30::UInt8
    d31::UInt8
    d32::UInt8
    d33::UInt8
    d34::UInt8
    d35::UInt8
    d36::UInt8
    d37::UInt8
    d38::UInt8
    d39::UInt8
    d40::UInt8
    d41::UInt8
    d42::UInt8
    d43::UInt8
    d44::UInt8
    d45::UInt8
    d46::UInt8
    d47::UInt8
    d48::UInt8
    d49::UInt8
    d50::UInt8
    d51::UInt8
    d52::UInt8
    d53::UInt8
    d54::UInt8
    d55::UInt8
    d56::UInt8
    d57::UInt8
    d58::UInt8
    d59::UInt8
    d60::UInt8
    d61::UInt8
    d62::UInt8
    d63::UInt8
    d64::UInt8
end

zero(::Type{Array_64_UInt8}) = begin  # /home/shindo/.julia/v0.4/Clang/src/wrap_c.jl, line 266:
        Array_64_UInt8(fill(zero(UInt8),64)...)
    end

immutable CUipcEventHandle_st
    reserved::Array_64_UInt8
end

immutable CUipcEventHandle
    reserved::Array_64_UInt8
end

immutable CUipcMemHandle_st
    reserved::Array_64_UInt8
end

immutable CUipcMemHandle
    reserved::Array_64_UInt8
end

# begin enum CUipcMem_flags_enum
typealias CUipcMem_flags_enum UInt32
const CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS = (UInt32)(1)
# end enum CUipcMem_flags_enum

# begin enum CUipcMem_flags
typealias CUipcMem_flags UInt32
const CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS = (UInt32)(1)
# end enum CUipcMem_flags

# begin enum CUmemAttach_flags_enum
typealias CUmemAttach_flags_enum UInt32
const CU_MEM_ATTACH_GLOBAL = (UInt32)(1)
const CU_MEM_ATTACH_HOST = (UInt32)(2)
const CU_MEM_ATTACH_SINGLE = (UInt32)(4)
# end enum CUmemAttach_flags_enum

# begin enum CUmemAttach_flags
typealias CUmemAttach_flags UInt32
const CU_MEM_ATTACH_GLOBAL = (UInt32)(1)
const CU_MEM_ATTACH_HOST = (UInt32)(2)
const CU_MEM_ATTACH_SINGLE = (UInt32)(4)
# end enum CUmemAttach_flags

# begin enum CUctx_flags_enum
typealias CUctx_flags_enum UInt32
const CU_CTX_SCHED_AUTO = (UInt32)(0)
const CU_CTX_SCHED_SPIN = (UInt32)(1)
const CU_CTX_SCHED_YIELD = (UInt32)(2)
const CU_CTX_SCHED_BLOCKING_SYNC = (UInt32)(4)
const CU_CTX_BLOCKING_SYNC = (UInt32)(4)
const CU_CTX_SCHED_MASK = (UInt32)(7)
const CU_CTX_MAP_HOST = (UInt32)(8)
const CU_CTX_LMEM_RESIZE_TO_MAX = (UInt32)(16)
const CU_CTX_FLAGS_MASK = (UInt32)(31)
# end enum CUctx_flags_enum

# begin enum CUctx_flags
typealias CUctx_flags UInt32
const CU_CTX_SCHED_AUTO = (UInt32)(0)
const CU_CTX_SCHED_SPIN = (UInt32)(1)
const CU_CTX_SCHED_YIELD = (UInt32)(2)
const CU_CTX_SCHED_BLOCKING_SYNC = (UInt32)(4)
const CU_CTX_BLOCKING_SYNC = (UInt32)(4)
const CU_CTX_SCHED_MASK = (UInt32)(7)
const CU_CTX_MAP_HOST = (UInt32)(8)
const CU_CTX_LMEM_RESIZE_TO_MAX = (UInt32)(16)
const CU_CTX_FLAGS_MASK = (UInt32)(31)
# end enum CUctx_flags

# begin enum CUstream_flags_enum
typealias CUstream_flags_enum UInt32
const CU_STREAM_DEFAULT = (UInt32)(0)
const CU_STREAM_NON_BLOCKING = (UInt32)(1)
# end enum CUstream_flags_enum

# begin enum CUstream_flags
typealias CUstream_flags UInt32
const CU_STREAM_DEFAULT = (UInt32)(0)
const CU_STREAM_NON_BLOCKING = (UInt32)(1)
# end enum CUstream_flags

# begin enum CUevent_flags_enum
typealias CUevent_flags_enum UInt32
const CU_EVENT_DEFAULT = (UInt32)(0)
const CU_EVENT_BLOCKING_SYNC = (UInt32)(1)
const CU_EVENT_DISABLE_TIMING = (UInt32)(2)
const CU_EVENT_INTERPROCESS = (UInt32)(4)
# end enum CUevent_flags_enum

# begin enum CUevent_flags
typealias CUevent_flags UInt32
const CU_EVENT_DEFAULT = (UInt32)(0)
const CU_EVENT_BLOCKING_SYNC = (UInt32)(1)
const CU_EVENT_DISABLE_TIMING = (UInt32)(2)
const CU_EVENT_INTERPROCESS = (UInt32)(4)
# end enum CUevent_flags

# begin enum CUoccupancy_flags_enum
typealias CUoccupancy_flags_enum UInt32
const CU_OCCUPANCY_DEFAULT = (UInt32)(0)
const CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE = (UInt32)(1)
# end enum CUoccupancy_flags_enum

# begin enum CUoccupancy_flags
typealias CUoccupancy_flags UInt32
const CU_OCCUPANCY_DEFAULT = (UInt32)(0)
const CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE = (UInt32)(1)
# end enum CUoccupancy_flags

# begin enum CUarray_format_enum
typealias CUarray_format_enum UInt32
const CU_AD_FORMAT_UNSIGNED_INT8 = (UInt32)(1)
const CU_AD_FORMAT_UNSIGNED_INT16 = (UInt32)(2)
const CU_AD_FORMAT_UNSIGNED_INT32 = (UInt32)(3)
const CU_AD_FORMAT_SIGNED_INT8 = (UInt32)(8)
const CU_AD_FORMAT_SIGNED_INT16 = (UInt32)(9)
const CU_AD_FORMAT_SIGNED_INT32 = (UInt32)(10)
const CU_AD_FORMAT_HALF = (UInt32)(16)
const CU_AD_FORMAT_FLOAT = (UInt32)(32)
# end enum CUarray_format_enum

# begin enum CUarray_format
typealias CUarray_format UInt32
const CU_AD_FORMAT_UNSIGNED_INT8 = (UInt32)(1)
const CU_AD_FORMAT_UNSIGNED_INT16 = (UInt32)(2)
const CU_AD_FORMAT_UNSIGNED_INT32 = (UInt32)(3)
const CU_AD_FORMAT_SIGNED_INT8 = (UInt32)(8)
const CU_AD_FORMAT_SIGNED_INT16 = (UInt32)(9)
const CU_AD_FORMAT_SIGNED_INT32 = (UInt32)(10)
const CU_AD_FORMAT_HALF = (UInt32)(16)
const CU_AD_FORMAT_FLOAT = (UInt32)(32)
# end enum CUarray_format

# begin enum CUaddress_mode_enum
typealias CUaddress_mode_enum UInt32
const CU_TR_ADDRESS_MODE_WRAP = (UInt32)(0)
const CU_TR_ADDRESS_MODE_CLAMP = (UInt32)(1)
const CU_TR_ADDRESS_MODE_MIRROR = (UInt32)(2)
const CU_TR_ADDRESS_MODE_BORDER = (UInt32)(3)
# end enum CUaddress_mode_enum

# begin enum CUaddress_mode
typealias CUaddress_mode UInt32
const CU_TR_ADDRESS_MODE_WRAP = (UInt32)(0)
const CU_TR_ADDRESS_MODE_CLAMP = (UInt32)(1)
const CU_TR_ADDRESS_MODE_MIRROR = (UInt32)(2)
const CU_TR_ADDRESS_MODE_BORDER = (UInt32)(3)
# end enum CUaddress_mode

# begin enum CUfilter_mode_enum
typealias CUfilter_mode_enum UInt32
const CU_TR_FILTER_MODE_POINT = (UInt32)(0)
const CU_TR_FILTER_MODE_LINEAR = (UInt32)(1)
# end enum CUfilter_mode_enum

# begin enum CUfilter_mode
typealias CUfilter_mode UInt32
const CU_TR_FILTER_MODE_POINT = (UInt32)(0)
const CU_TR_FILTER_MODE_LINEAR = (UInt32)(1)
# end enum CUfilter_mode

# begin enum CUdevice_attribute_enum
typealias CUdevice_attribute_enum UInt32
const CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = (UInt32)(1)
const CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X = (UInt32)(2)
const CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y = (UInt32)(3)
const CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z = (UInt32)(4)
const CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = (UInt32)(5)
const CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y = (UInt32)(6)
const CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z = (UInt32)(7)
const CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = (UInt32)(8)
const CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK = (UInt32)(8)
const CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY = (UInt32)(9)
const CU_DEVICE_ATTRIBUTE_WARP_SIZE = (UInt32)(10)
const CU_DEVICE_ATTRIBUTE_MAX_PITCH = (UInt32)(11)
const CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = (UInt32)(12)
const CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK = (UInt32)(12)
const CU_DEVICE_ATTRIBUTE_CLOCK_RATE = (UInt32)(13)
const CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT = (UInt32)(14)
const CU_DEVICE_ATTRIBUTE_GPU_OVERLAP = (UInt32)(15)
const CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = (UInt32)(16)
const CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT = (UInt32)(17)
const CU_DEVICE_ATTRIBUTE_INTEGRATED = (UInt32)(18)
const CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY = (UInt32)(19)
const CU_DEVICE_ATTRIBUTE_COMPUTE_MODE = (UInt32)(20)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH = (UInt32)(21)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH = (UInt32)(22)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT = (UInt32)(23)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH = (UInt32)(24)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT = (UInt32)(25)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH = (UInt32)(26)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH = (UInt32)(27)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT = (UInt32)(28)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS = (UInt32)(29)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH = (UInt32)(27)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT = (UInt32)(28)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES = (UInt32)(29)
const CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT = (UInt32)(30)
const CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS = (UInt32)(31)
const CU_DEVICE_ATTRIBUTE_ECC_ENABLED = (UInt32)(32)
const CU_DEVICE_ATTRIBUTE_PCI_BUS_ID = (UInt32)(33)
const CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID = (UInt32)(34)
const CU_DEVICE_ATTRIBUTE_TCC_DRIVER = (UInt32)(35)
const CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE = (UInt32)(36)
const CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = (UInt32)(37)
const CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE = (UInt32)(38)
const CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR = (UInt32)(39)
const CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT = (UInt32)(40)
const CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING = (UInt32)(41)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH = (UInt32)(42)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS = (UInt32)(43)
const CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER = (UInt32)(44)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH = (UInt32)(45)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT = (UInt32)(46)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE = (UInt32)(47)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE = (UInt32)(48)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE = (UInt32)(49)
const CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID = (UInt32)(50)
const CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT = (UInt32)(51)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH = (UInt32)(52)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH = (UInt32)(53)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS = (UInt32)(54)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH = (UInt32)(55)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH = (UInt32)(56)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT = (UInt32)(57)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH = (UInt32)(58)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT = (UInt32)(59)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH = (UInt32)(60)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH = (UInt32)(61)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS = (UInt32)(62)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH = (UInt32)(63)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT = (UInt32)(64)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS = (UInt32)(65)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH = (UInt32)(66)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH = (UInt32)(67)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS = (UInt32)(68)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH = (UInt32)(69)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH = (UInt32)(70)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT = (UInt32)(71)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH = (UInt32)(72)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH = (UInt32)(73)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT = (UInt32)(74)
const CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = (UInt32)(75)
const CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = (UInt32)(76)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH = (UInt32)(77)
const CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED = (UInt32)(78)
const CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED = (UInt32)(79)
const CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED = (UInt32)(80)
const CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR = (UInt32)(81)
const CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR = (UInt32)(82)
const CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY = (UInt32)(83)
const CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD = (UInt32)(84)
const CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID = (UInt32)(85)
const CU_DEVICE_ATTRIBUTE_MAX = (UInt32)(86)
# end enum CUdevice_attribute_enum

# begin enum CUdevice_attribute
typealias CUdevice_attribute UInt32
const CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = (UInt32)(1)
const CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X = (UInt32)(2)
const CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y = (UInt32)(3)
const CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z = (UInt32)(4)
const CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = (UInt32)(5)
const CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y = (UInt32)(6)
const CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z = (UInt32)(7)
const CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = (UInt32)(8)
const CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK = (UInt32)(8)
const CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY = (UInt32)(9)
const CU_DEVICE_ATTRIBUTE_WARP_SIZE = (UInt32)(10)
const CU_DEVICE_ATTRIBUTE_MAX_PITCH = (UInt32)(11)
const CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = (UInt32)(12)
const CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK = (UInt32)(12)
const CU_DEVICE_ATTRIBUTE_CLOCK_RATE = (UInt32)(13)
const CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT = (UInt32)(14)
const CU_DEVICE_ATTRIBUTE_GPU_OVERLAP = (UInt32)(15)
const CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = (UInt32)(16)
const CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT = (UInt32)(17)
const CU_DEVICE_ATTRIBUTE_INTEGRATED = (UInt32)(18)
const CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY = (UInt32)(19)
const CU_DEVICE_ATTRIBUTE_COMPUTE_MODE = (UInt32)(20)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH = (UInt32)(21)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH = (UInt32)(22)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT = (UInt32)(23)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH = (UInt32)(24)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT = (UInt32)(25)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH = (UInt32)(26)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH = (UInt32)(27)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT = (UInt32)(28)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS = (UInt32)(29)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH = (UInt32)(27)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT = (UInt32)(28)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES = (UInt32)(29)
const CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT = (UInt32)(30)
const CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS = (UInt32)(31)
const CU_DEVICE_ATTRIBUTE_ECC_ENABLED = (UInt32)(32)
const CU_DEVICE_ATTRIBUTE_PCI_BUS_ID = (UInt32)(33)
const CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID = (UInt32)(34)
const CU_DEVICE_ATTRIBUTE_TCC_DRIVER = (UInt32)(35)
const CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE = (UInt32)(36)
const CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = (UInt32)(37)
const CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE = (UInt32)(38)
const CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR = (UInt32)(39)
const CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT = (UInt32)(40)
const CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING = (UInt32)(41)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH = (UInt32)(42)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS = (UInt32)(43)
const CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER = (UInt32)(44)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH = (UInt32)(45)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT = (UInt32)(46)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE = (UInt32)(47)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE = (UInt32)(48)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE = (UInt32)(49)
const CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID = (UInt32)(50)
const CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT = (UInt32)(51)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH = (UInt32)(52)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH = (UInt32)(53)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS = (UInt32)(54)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH = (UInt32)(55)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH = (UInt32)(56)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT = (UInt32)(57)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH = (UInt32)(58)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT = (UInt32)(59)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH = (UInt32)(60)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH = (UInt32)(61)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS = (UInt32)(62)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH = (UInt32)(63)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT = (UInt32)(64)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS = (UInt32)(65)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH = (UInt32)(66)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH = (UInt32)(67)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS = (UInt32)(68)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH = (UInt32)(69)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH = (UInt32)(70)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT = (UInt32)(71)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH = (UInt32)(72)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH = (UInt32)(73)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT = (UInt32)(74)
const CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = (UInt32)(75)
const CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = (UInt32)(76)
const CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH = (UInt32)(77)
const CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED = (UInt32)(78)
const CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED = (UInt32)(79)
const CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED = (UInt32)(80)
const CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR = (UInt32)(81)
const CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR = (UInt32)(82)
const CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY = (UInt32)(83)
const CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD = (UInt32)(84)
const CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID = (UInt32)(85)
const CU_DEVICE_ATTRIBUTE_MAX = (UInt32)(86)
# end enum CUdevice_attribute

immutable Array_3_Cint
    d1::Cint
    d2::Cint
    d3::Cint
end

zero(::Type{Array_3_Cint}) = begin  # /home/shindo/.julia/v0.4/Clang/src/wrap_c.jl, line 266:
        Array_3_Cint(fill(zero(Cint),3)...)
    end

immutable CUdevprop_st
    maxThreadsPerBlock::Cint
    maxThreadsDim::Array_3_Cint
    maxGridSize::Array_3_Cint
    sharedMemPerBlock::Cint
    totalConstantMemory::Cint
    SIMDWidth::Cint
    memPitch::Cint
    regsPerBlock::Cint
    clockRate::Cint
    textureAlign::Cint
end

immutable CUdevprop
    maxThreadsPerBlock::Cint
    maxThreadsDim::Array_3_Cint
    maxGridSize::Array_3_Cint
    sharedMemPerBlock::Cint
    totalConstantMemory::Cint
    SIMDWidth::Cint
    memPitch::Cint
    regsPerBlock::Cint
    clockRate::Cint
    textureAlign::Cint
end

# begin enum CUpointer_attribute_enum
typealias CUpointer_attribute_enum UInt32
const CU_POINTER_ATTRIBUTE_CONTEXT = (UInt32)(1)
const CU_POINTER_ATTRIBUTE_MEMORY_TYPE = (UInt32)(2)
const CU_POINTER_ATTRIBUTE_DEVICE_POINTER = (UInt32)(3)
const CU_POINTER_ATTRIBUTE_HOST_POINTER = (UInt32)(4)
const CU_POINTER_ATTRIBUTE_P2P_TOKENS = (UInt32)(5)
const CU_POINTER_ATTRIBUTE_SYNC_MEMOPS = (UInt32)(6)
const CU_POINTER_ATTRIBUTE_BUFFER_ID = (UInt32)(7)
const CU_POINTER_ATTRIBUTE_IS_MANAGED = (UInt32)(8)
# end enum CUpointer_attribute_enum

# begin enum CUpointer_attribute
typealias CUpointer_attribute UInt32
const CU_POINTER_ATTRIBUTE_CONTEXT = (UInt32)(1)
const CU_POINTER_ATTRIBUTE_MEMORY_TYPE = (UInt32)(2)
const CU_POINTER_ATTRIBUTE_DEVICE_POINTER = (UInt32)(3)
const CU_POINTER_ATTRIBUTE_HOST_POINTER = (UInt32)(4)
const CU_POINTER_ATTRIBUTE_P2P_TOKENS = (UInt32)(5)
const CU_POINTER_ATTRIBUTE_SYNC_MEMOPS = (UInt32)(6)
const CU_POINTER_ATTRIBUTE_BUFFER_ID = (UInt32)(7)
const CU_POINTER_ATTRIBUTE_IS_MANAGED = (UInt32)(8)
# end enum CUpointer_attribute

# begin enum CUfunction_attribute_enum
typealias CUfunction_attribute_enum UInt32
const CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK = (UInt32)(0)
const CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES = (UInt32)(1)
const CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES = (UInt32)(2)
const CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES = (UInt32)(3)
const CU_FUNC_ATTRIBUTE_NUM_REGS = (UInt32)(4)
const CU_FUNC_ATTRIBUTE_PTX_VERSION = (UInt32)(5)
const CU_FUNC_ATTRIBUTE_BINARY_VERSION = (UInt32)(6)
const CU_FUNC_ATTRIBUTE_CACHE_MODE_CA = (UInt32)(7)
const CU_FUNC_ATTRIBUTE_MAX = (UInt32)(8)
# end enum CUfunction_attribute_enum

# begin enum CUfunction_attribute
typealias CUfunction_attribute UInt32
const CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK = (UInt32)(0)
const CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES = (UInt32)(1)
const CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES = (UInt32)(2)
const CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES = (UInt32)(3)
const CU_FUNC_ATTRIBUTE_NUM_REGS = (UInt32)(4)
const CU_FUNC_ATTRIBUTE_PTX_VERSION = (UInt32)(5)
const CU_FUNC_ATTRIBUTE_BINARY_VERSION = (UInt32)(6)
const CU_FUNC_ATTRIBUTE_CACHE_MODE_CA = (UInt32)(7)
const CU_FUNC_ATTRIBUTE_MAX = (UInt32)(8)
# end enum CUfunction_attribute

# begin enum CUfunc_cache_enum
typealias CUfunc_cache_enum UInt32
const CU_FUNC_CACHE_PREFER_NONE = (UInt32)(0)
const CU_FUNC_CACHE_PREFER_SHARED = (UInt32)(1)
const CU_FUNC_CACHE_PREFER_L1 = (UInt32)(2)
const CU_FUNC_CACHE_PREFER_EQUAL = (UInt32)(3)
# end enum CUfunc_cache_enum

# begin enum CUfunc_cache
typealias CUfunc_cache UInt32
const CU_FUNC_CACHE_PREFER_NONE = (UInt32)(0)
const CU_FUNC_CACHE_PREFER_SHARED = (UInt32)(1)
const CU_FUNC_CACHE_PREFER_L1 = (UInt32)(2)
const CU_FUNC_CACHE_PREFER_EQUAL = (UInt32)(3)
# end enum CUfunc_cache

# begin enum CUsharedconfig_enum
typealias CUsharedconfig_enum UInt32
const CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE = (UInt32)(0)
const CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE = (UInt32)(1)
const CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE = (UInt32)(2)
# end enum CUsharedconfig_enum

# begin enum CUsharedconfig
typealias CUsharedconfig UInt32
const CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE = (UInt32)(0)
const CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE = (UInt32)(1)
const CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE = (UInt32)(2)
# end enum CUsharedconfig

# begin enum CUmemorytype_enum
typealias CUmemorytype_enum UInt32
const CU_MEMORYTYPE_HOST = (UInt32)(1)
const CU_MEMORYTYPE_DEVICE = (UInt32)(2)
const CU_MEMORYTYPE_ARRAY = (UInt32)(3)
const CU_MEMORYTYPE_UNIFIED = (UInt32)(4)
# end enum CUmemorytype_enum

# begin enum CUmemorytype
typealias CUmemorytype UInt32
const CU_MEMORYTYPE_HOST = (UInt32)(1)
const CU_MEMORYTYPE_DEVICE = (UInt32)(2)
const CU_MEMORYTYPE_ARRAY = (UInt32)(3)
const CU_MEMORYTYPE_UNIFIED = (UInt32)(4)
# end enum CUmemorytype

# begin enum CUcomputemode_enum
typealias CUcomputemode_enum UInt32
const CU_COMPUTEMODE_DEFAULT = (UInt32)(0)
const CU_COMPUTEMODE_EXCLUSIVE = (UInt32)(1)
const CU_COMPUTEMODE_PROHIBITED = (UInt32)(2)
const CU_COMPUTEMODE_EXCLUSIVE_PROCESS = (UInt32)(3)
# end enum CUcomputemode_enum

# begin enum CUcomputemode
typealias CUcomputemode UInt32
const CU_COMPUTEMODE_DEFAULT = (UInt32)(0)
const CU_COMPUTEMODE_EXCLUSIVE = (UInt32)(1)
const CU_COMPUTEMODE_PROHIBITED = (UInt32)(2)
const CU_COMPUTEMODE_EXCLUSIVE_PROCESS = (UInt32)(3)
# end enum CUcomputemode

# begin enum CUjit_option_enum
typealias CUjit_option_enum UInt32
const CU_JIT_MAX_REGISTERS = (UInt32)(0)
const CU_JIT_THREADS_PER_BLOCK = (UInt32)(1)
const CU_JIT_WALL_TIME = (UInt32)(2)
const CU_JIT_INFO_LOG_BUFFER = (UInt32)(3)
const CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES = (UInt32)(4)
const CU_JIT_ERROR_LOG_BUFFER = (UInt32)(5)
const CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES = (UInt32)(6)
const CU_JIT_OPTIMIZATION_LEVEL = (UInt32)(7)
const CU_JIT_TARGET_FROM_CUCONTEXT = (UInt32)(8)
const CU_JIT_TARGET = (UInt32)(9)
const CU_JIT_FALLBACK_STRATEGY = (UInt32)(10)
const CU_JIT_GENERATE_DEBUG_INFO = (UInt32)(11)
const CU_JIT_LOG_VERBOSE = (UInt32)(12)
const CU_JIT_GENERATE_LINE_INFO = (UInt32)(13)
const CU_JIT_CACHE_MODE = (UInt32)(14)
const CU_JIT_NUM_OPTIONS = (UInt32)(15)
# end enum CUjit_option_enum

# begin enum CUjit_option
typealias CUjit_option UInt32
const CU_JIT_MAX_REGISTERS = (UInt32)(0)
const CU_JIT_THREADS_PER_BLOCK = (UInt32)(1)
const CU_JIT_WALL_TIME = (UInt32)(2)
const CU_JIT_INFO_LOG_BUFFER = (UInt32)(3)
const CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES = (UInt32)(4)
const CU_JIT_ERROR_LOG_BUFFER = (UInt32)(5)
const CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES = (UInt32)(6)
const CU_JIT_OPTIMIZATION_LEVEL = (UInt32)(7)
const CU_JIT_TARGET_FROM_CUCONTEXT = (UInt32)(8)
const CU_JIT_TARGET = (UInt32)(9)
const CU_JIT_FALLBACK_STRATEGY = (UInt32)(10)
const CU_JIT_GENERATE_DEBUG_INFO = (UInt32)(11)
const CU_JIT_LOG_VERBOSE = (UInt32)(12)
const CU_JIT_GENERATE_LINE_INFO = (UInt32)(13)
const CU_JIT_CACHE_MODE = (UInt32)(14)
const CU_JIT_NUM_OPTIONS = (UInt32)(15)
# end enum CUjit_option

# begin enum CUjit_target_enum
typealias CUjit_target_enum UInt32
const CU_TARGET_COMPUTE_10 = (UInt32)(10)
const CU_TARGET_COMPUTE_11 = (UInt32)(11)
const CU_TARGET_COMPUTE_12 = (UInt32)(12)
const CU_TARGET_COMPUTE_13 = (UInt32)(13)
const CU_TARGET_COMPUTE_20 = (UInt32)(20)
const CU_TARGET_COMPUTE_21 = (UInt32)(21)
const CU_TARGET_COMPUTE_30 = (UInt32)(30)
const CU_TARGET_COMPUTE_32 = (UInt32)(32)
const CU_TARGET_COMPUTE_35 = (UInt32)(35)
const CU_TARGET_COMPUTE_37 = (UInt32)(37)
const CU_TARGET_COMPUTE_50 = (UInt32)(50)
const CU_TARGET_COMPUTE_52 = (UInt32)(52)
# end enum CUjit_target_enum

# begin enum CUjit_target
typealias CUjit_target UInt32
const CU_TARGET_COMPUTE_10 = (UInt32)(10)
const CU_TARGET_COMPUTE_11 = (UInt32)(11)
const CU_TARGET_COMPUTE_12 = (UInt32)(12)
const CU_TARGET_COMPUTE_13 = (UInt32)(13)
const CU_TARGET_COMPUTE_20 = (UInt32)(20)
const CU_TARGET_COMPUTE_21 = (UInt32)(21)
const CU_TARGET_COMPUTE_30 = (UInt32)(30)
const CU_TARGET_COMPUTE_32 = (UInt32)(32)
const CU_TARGET_COMPUTE_35 = (UInt32)(35)
const CU_TARGET_COMPUTE_37 = (UInt32)(37)
const CU_TARGET_COMPUTE_50 = (UInt32)(50)
const CU_TARGET_COMPUTE_52 = (UInt32)(52)
# end enum CUjit_target

# begin enum CUjit_fallback_enum
typealias CUjit_fallback_enum UInt32
const CU_PREFER_PTX = (UInt32)(0)
const CU_PREFER_BINARY = (UInt32)(1)
# end enum CUjit_fallback_enum

# begin enum CUjit_fallback
typealias CUjit_fallback UInt32
const CU_PREFER_PTX = (UInt32)(0)
const CU_PREFER_BINARY = (UInt32)(1)
# end enum CUjit_fallback

# begin enum CUjit_cacheMode_enum
typealias CUjit_cacheMode_enum UInt32
const CU_JIT_CACHE_OPTION_NONE = (UInt32)(0)
const CU_JIT_CACHE_OPTION_CG = (UInt32)(1)
const CU_JIT_CACHE_OPTION_CA = (UInt32)(2)
# end enum CUjit_cacheMode_enum

# begin enum CUjit_cacheMode
typealias CUjit_cacheMode UInt32
const CU_JIT_CACHE_OPTION_NONE = (UInt32)(0)
const CU_JIT_CACHE_OPTION_CG = (UInt32)(1)
const CU_JIT_CACHE_OPTION_CA = (UInt32)(2)
# end enum CUjit_cacheMode

# begin enum CUjitInputType_enum
typealias CUjitInputType_enum UInt32
const CU_JIT_INPUT_CUBIN = (UInt32)(0)
const CU_JIT_INPUT_PTX = (UInt32)(1)
const CU_JIT_INPUT_FATBINARY = (UInt32)(2)
const CU_JIT_INPUT_OBJECT = (UInt32)(3)
const CU_JIT_INPUT_LIBRARY = (UInt32)(4)
const CU_JIT_NUM_INPUT_TYPES = (UInt32)(5)
# end enum CUjitInputType_enum

# begin enum CUjitInputType
typealias CUjitInputType UInt32
const CU_JIT_INPUT_CUBIN = (UInt32)(0)
const CU_JIT_INPUT_PTX = (UInt32)(1)
const CU_JIT_INPUT_FATBINARY = (UInt32)(2)
const CU_JIT_INPUT_OBJECT = (UInt32)(3)
const CU_JIT_INPUT_LIBRARY = (UInt32)(4)
const CU_JIT_NUM_INPUT_TYPES = (UInt32)(5)
# end enum CUjitInputType

typealias CUlinkState_st Void
typealias CUlinkState Ptr{CUlinkState_st}

# begin enum CUgraphicsRegisterFlags_enum
typealias CUgraphicsRegisterFlags_enum UInt32
const CU_GRAPHICS_REGISTER_FLAGS_NONE = (UInt32)(0)
const CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY = (UInt32)(1)
const CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD = (UInt32)(2)
const CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST = (UInt32)(4)
const CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER = (UInt32)(8)
# end enum CUgraphicsRegisterFlags_enum

# begin enum CUgraphicsRegisterFlags
typealias CUgraphicsRegisterFlags UInt32
const CU_GRAPHICS_REGISTER_FLAGS_NONE = (UInt32)(0)
const CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY = (UInt32)(1)
const CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD = (UInt32)(2)
const CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST = (UInt32)(4)
const CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER = (UInt32)(8)
# end enum CUgraphicsRegisterFlags

# begin enum CUgraphicsMapResourceFlags_enum
typealias CUgraphicsMapResourceFlags_enum UInt32
const CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE = (UInt32)(0)
const CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY = (UInt32)(1)
const CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD = (UInt32)(2)
# end enum CUgraphicsMapResourceFlags_enum

# begin enum CUgraphicsMapResourceFlags
typealias CUgraphicsMapResourceFlags UInt32
const CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE = (UInt32)(0)
const CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY = (UInt32)(1)
const CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD = (UInt32)(2)
# end enum CUgraphicsMapResourceFlags

# begin enum CUarray_cubemap_face_enum
typealias CUarray_cubemap_face_enum UInt32
const CU_CUBEMAP_FACE_POSITIVE_X = (UInt32)(0)
const CU_CUBEMAP_FACE_NEGATIVE_X = (UInt32)(1)
const CU_CUBEMAP_FACE_POSITIVE_Y = (UInt32)(2)
const CU_CUBEMAP_FACE_NEGATIVE_Y = (UInt32)(3)
const CU_CUBEMAP_FACE_POSITIVE_Z = (UInt32)(4)
const CU_CUBEMAP_FACE_NEGATIVE_Z = (UInt32)(5)
# end enum CUarray_cubemap_face_enum

# begin enum CUarray_cubemap_face
typealias CUarray_cubemap_face UInt32
const CU_CUBEMAP_FACE_POSITIVE_X = (UInt32)(0)
const CU_CUBEMAP_FACE_NEGATIVE_X = (UInt32)(1)
const CU_CUBEMAP_FACE_POSITIVE_Y = (UInt32)(2)
const CU_CUBEMAP_FACE_NEGATIVE_Y = (UInt32)(3)
const CU_CUBEMAP_FACE_POSITIVE_Z = (UInt32)(4)
const CU_CUBEMAP_FACE_NEGATIVE_Z = (UInt32)(5)
# end enum CUarray_cubemap_face

# begin enum CUlimit_enum
typealias CUlimit_enum UInt32
const CU_LIMIT_STACK_SIZE = (UInt32)(0)
const CU_LIMIT_PRINTF_FIFO_SIZE = (UInt32)(1)
const CU_LIMIT_MALLOC_HEAP_SIZE = (UInt32)(2)
const CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH = (UInt32)(3)
const CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT = (UInt32)(4)
const CU_LIMIT_MAX = (UInt32)(5)
# end enum CUlimit_enum

# begin enum CUlimit
typealias CUlimit UInt32
const CU_LIMIT_STACK_SIZE = (UInt32)(0)
const CU_LIMIT_PRINTF_FIFO_SIZE = (UInt32)(1)
const CU_LIMIT_MALLOC_HEAP_SIZE = (UInt32)(2)
const CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH = (UInt32)(3)
const CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT = (UInt32)(4)
const CU_LIMIT_MAX = (UInt32)(5)
# end enum CUlimit

# begin enum CUresourcetype_enum
typealias CUresourcetype_enum UInt32
const CU_RESOURCE_TYPE_ARRAY = (UInt32)(0)
const CU_RESOURCE_TYPE_MIPMAPPED_ARRAY = (UInt32)(1)
const CU_RESOURCE_TYPE_LINEAR = (UInt32)(2)
const CU_RESOURCE_TYPE_PITCH2D = (UInt32)(3)
# end enum CUresourcetype_enum

# begin enum CUresourcetype
typealias CUresourcetype UInt32
const CU_RESOURCE_TYPE_ARRAY = (UInt32)(0)
const CU_RESOURCE_TYPE_MIPMAPPED_ARRAY = (UInt32)(1)
const CU_RESOURCE_TYPE_LINEAR = (UInt32)(2)
const CU_RESOURCE_TYPE_PITCH2D = (UInt32)(3)
# end enum CUresourcetype

# begin enum cudaError_enum
typealias cudaError_enum UInt32
const CUDA_SUCCESS = (UInt32)(0)
const CUDA_ERROR_INVALID_VALUE = (UInt32)(1)
const CUDA_ERROR_OUT_OF_MEMORY = (UInt32)(2)
const CUDA_ERROR_NOT_INITIALIZED = (UInt32)(3)
const CUDA_ERROR_DEINITIALIZED = (UInt32)(4)
const CUDA_ERROR_PROFILER_DISABLED = (UInt32)(5)
const CUDA_ERROR_PROFILER_NOT_INITIALIZED = (UInt32)(6)
const CUDA_ERROR_PROFILER_ALREADY_STARTED = (UInt32)(7)
const CUDA_ERROR_PROFILER_ALREADY_STOPPED = (UInt32)(8)
const CUDA_ERROR_NO_DEVICE = (UInt32)(100)
const CUDA_ERROR_INVALID_DEVICE = (UInt32)(101)
const CUDA_ERROR_INVALID_IMAGE = (UInt32)(200)
const CUDA_ERROR_INVALID_CONTEXT = (UInt32)(201)
const CUDA_ERROR_CONTEXT_ALREADY_CURRENT = (UInt32)(202)
const CUDA_ERROR_MAP_FAILED = (UInt32)(205)
const CUDA_ERROR_UNMAP_FAILED = (UInt32)(206)
const CUDA_ERROR_ARRAY_IS_MAPPED = (UInt32)(207)
const CUDA_ERROR_ALREADY_MAPPED = (UInt32)(208)
const CUDA_ERROR_NO_BINARY_FOR_GPU = (UInt32)(209)
const CUDA_ERROR_ALREADY_ACQUIRED = (UInt32)(210)
const CUDA_ERROR_NOT_MAPPED = (UInt32)(211)
const CUDA_ERROR_NOT_MAPPED_AS_ARRAY = (UInt32)(212)
const CUDA_ERROR_NOT_MAPPED_AS_POINTER = (UInt32)(213)
const CUDA_ERROR_ECC_UNCORRECTABLE = (UInt32)(214)
const CUDA_ERROR_UNSUPPORTED_LIMIT = (UInt32)(215)
const CUDA_ERROR_CONTEXT_ALREADY_IN_USE = (UInt32)(216)
const CUDA_ERROR_PEER_ACCESS_UNSUPPORTED = (UInt32)(217)
const CUDA_ERROR_INVALID_PTX = (UInt32)(218)
const CUDA_ERROR_INVALID_GRAPHICS_CONTEXT = (UInt32)(219)
const CUDA_ERROR_INVALID_SOURCE = (UInt32)(300)
const CUDA_ERROR_FILE_NOT_FOUND = (UInt32)(301)
const CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND = (UInt32)(302)
const CUDA_ERROR_SHARED_OBJECT_INIT_FAILED = (UInt32)(303)
const CUDA_ERROR_OPERATING_SYSTEM = (UInt32)(304)
const CUDA_ERROR_INVALID_HANDLE = (UInt32)(400)
const CUDA_ERROR_NOT_FOUND = (UInt32)(500)
const CUDA_ERROR_NOT_READY = (UInt32)(600)
const CUDA_ERROR_ILLEGAL_ADDRESS = (UInt32)(700)
const CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES = (UInt32)(701)
const CUDA_ERROR_LAUNCH_TIMEOUT = (UInt32)(702)
const CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING = (UInt32)(703)
const CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED = (UInt32)(704)
const CUDA_ERROR_PEER_ACCESS_NOT_ENABLED = (UInt32)(705)
const CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE = (UInt32)(708)
const CUDA_ERROR_CONTEXT_IS_DESTROYED = (UInt32)(709)
const CUDA_ERROR_ASSERT = (UInt32)(710)
const CUDA_ERROR_TOO_MANY_PEERS = (UInt32)(711)
const CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED = (UInt32)(712)
const CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED = (UInt32)(713)
const CUDA_ERROR_HARDWARE_STACK_ERROR = (UInt32)(714)
const CUDA_ERROR_ILLEGAL_INSTRUCTION = (UInt32)(715)
const CUDA_ERROR_MISALIGNED_ADDRESS = (UInt32)(716)
const CUDA_ERROR_INVALID_ADDRESS_SPACE = (UInt32)(717)
const CUDA_ERROR_INVALID_PC = (UInt32)(718)
const CUDA_ERROR_LAUNCH_FAILED = (UInt32)(719)
const CUDA_ERROR_NOT_PERMITTED = (UInt32)(800)
const CUDA_ERROR_NOT_SUPPORTED = (UInt32)(801)
const CUDA_ERROR_UNKNOWN = (UInt32)(999)
# end enum cudaError_enum

# begin enum CUresult
typealias CUresult UInt32
const CUDA_SUCCESS = (UInt32)(0)
const CUDA_ERROR_INVALID_VALUE = (UInt32)(1)
const CUDA_ERROR_OUT_OF_MEMORY = (UInt32)(2)
const CUDA_ERROR_NOT_INITIALIZED = (UInt32)(3)
const CUDA_ERROR_DEINITIALIZED = (UInt32)(4)
const CUDA_ERROR_PROFILER_DISABLED = (UInt32)(5)
const CUDA_ERROR_PROFILER_NOT_INITIALIZED = (UInt32)(6)
const CUDA_ERROR_PROFILER_ALREADY_STARTED = (UInt32)(7)
const CUDA_ERROR_PROFILER_ALREADY_STOPPED = (UInt32)(8)
const CUDA_ERROR_NO_DEVICE = (UInt32)(100)
const CUDA_ERROR_INVALID_DEVICE = (UInt32)(101)
const CUDA_ERROR_INVALID_IMAGE = (UInt32)(200)
const CUDA_ERROR_INVALID_CONTEXT = (UInt32)(201)
const CUDA_ERROR_CONTEXT_ALREADY_CURRENT = (UInt32)(202)
const CUDA_ERROR_MAP_FAILED = (UInt32)(205)
const CUDA_ERROR_UNMAP_FAILED = (UInt32)(206)
const CUDA_ERROR_ARRAY_IS_MAPPED = (UInt32)(207)
const CUDA_ERROR_ALREADY_MAPPED = (UInt32)(208)
const CUDA_ERROR_NO_BINARY_FOR_GPU = (UInt32)(209)
const CUDA_ERROR_ALREADY_ACQUIRED = (UInt32)(210)
const CUDA_ERROR_NOT_MAPPED = (UInt32)(211)
const CUDA_ERROR_NOT_MAPPED_AS_ARRAY = (UInt32)(212)
const CUDA_ERROR_NOT_MAPPED_AS_POINTER = (UInt32)(213)
const CUDA_ERROR_ECC_UNCORRECTABLE = (UInt32)(214)
const CUDA_ERROR_UNSUPPORTED_LIMIT = (UInt32)(215)
const CUDA_ERROR_CONTEXT_ALREADY_IN_USE = (UInt32)(216)
const CUDA_ERROR_PEER_ACCESS_UNSUPPORTED = (UInt32)(217)
const CUDA_ERROR_INVALID_PTX = (UInt32)(218)
const CUDA_ERROR_INVALID_GRAPHICS_CONTEXT = (UInt32)(219)
const CUDA_ERROR_INVALID_SOURCE = (UInt32)(300)
const CUDA_ERROR_FILE_NOT_FOUND = (UInt32)(301)
const CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND = (UInt32)(302)
const CUDA_ERROR_SHARED_OBJECT_INIT_FAILED = (UInt32)(303)
const CUDA_ERROR_OPERATING_SYSTEM = (UInt32)(304)
const CUDA_ERROR_INVALID_HANDLE = (UInt32)(400)
const CUDA_ERROR_NOT_FOUND = (UInt32)(500)
const CUDA_ERROR_NOT_READY = (UInt32)(600)
const CUDA_ERROR_ILLEGAL_ADDRESS = (UInt32)(700)
const CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES = (UInt32)(701)
const CUDA_ERROR_LAUNCH_TIMEOUT = (UInt32)(702)
const CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING = (UInt32)(703)
const CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED = (UInt32)(704)
const CUDA_ERROR_PEER_ACCESS_NOT_ENABLED = (UInt32)(705)
const CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE = (UInt32)(708)
const CUDA_ERROR_CONTEXT_IS_DESTROYED = (UInt32)(709)
const CUDA_ERROR_ASSERT = (UInt32)(710)
const CUDA_ERROR_TOO_MANY_PEERS = (UInt32)(711)
const CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED = (UInt32)(712)
const CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED = (UInt32)(713)
const CUDA_ERROR_HARDWARE_STACK_ERROR = (UInt32)(714)
const CUDA_ERROR_ILLEGAL_INSTRUCTION = (UInt32)(715)
const CUDA_ERROR_MISALIGNED_ADDRESS = (UInt32)(716)
const CUDA_ERROR_INVALID_ADDRESS_SPACE = (UInt32)(717)
const CUDA_ERROR_INVALID_PC = (UInt32)(718)
const CUDA_ERROR_LAUNCH_FAILED = (UInt32)(719)
const CUDA_ERROR_NOT_PERMITTED = (UInt32)(800)
const CUDA_ERROR_NOT_SUPPORTED = (UInt32)(801)
const CUDA_ERROR_UNKNOWN = (UInt32)(999)
# end enum CUresult

typealias CUstreamCallback Ptr{Void}
typealias CUoccupancyB2DSize Ptr{Void}

immutable CUDA_MEMCPY2D_st
    srcXInBytes::Csize_t
    srcY::Csize_t
    srcMemoryType::CUmemorytype
    srcHost::Ptr{Void}
    srcDevice::CUdeviceptr
    srcArray::CUarray
    srcPitch::Csize_t
    dstXInBytes::Csize_t
    dstY::Csize_t
    dstMemoryType::CUmemorytype
    dstHost::Ptr{Void}
    dstDevice::CUdeviceptr
    dstArray::CUarray
    dstPitch::Csize_t
    WidthInBytes::Csize_t
    Height::Csize_t
end

immutable CUDA_MEMCPY2D
    srcXInBytes::Csize_t
    srcY::Csize_t
    srcMemoryType::CUmemorytype
    srcHost::Ptr{Void}
    srcDevice::CUdeviceptr
    srcArray::CUarray
    srcPitch::Csize_t
    dstXInBytes::Csize_t
    dstY::Csize_t
    dstMemoryType::CUmemorytype
    dstHost::Ptr{Void}
    dstDevice::CUdeviceptr
    dstArray::CUarray
    dstPitch::Csize_t
    WidthInBytes::Csize_t
    Height::Csize_t
end

immutable CUDA_MEMCPY3D_st
    srcXInBytes::Csize_t
    srcY::Csize_t
    srcZ::Csize_t
    srcLOD::Csize_t
    srcMemoryType::CUmemorytype
    srcHost::Ptr{Void}
    srcDevice::CUdeviceptr
    srcArray::CUarray
    reserved0::Ptr{Void}
    srcPitch::Csize_t
    srcHeight::Csize_t
    dstXInBytes::Csize_t
    dstY::Csize_t
    dstZ::Csize_t
    dstLOD::Csize_t
    dstMemoryType::CUmemorytype
    dstHost::Ptr{Void}
    dstDevice::CUdeviceptr
    dstArray::CUarray
    reserved1::Ptr{Void}
    dstPitch::Csize_t
    dstHeight::Csize_t
    WidthInBytes::Csize_t
    Height::Csize_t
    Depth::Csize_t
end

immutable CUDA_MEMCPY3D
    srcXInBytes::Csize_t
    srcY::Csize_t
    srcZ::Csize_t
    srcLOD::Csize_t
    srcMemoryType::CUmemorytype
    srcHost::Ptr{Void}
    srcDevice::CUdeviceptr
    srcArray::CUarray
    reserved0::Ptr{Void}
    srcPitch::Csize_t
    srcHeight::Csize_t
    dstXInBytes::Csize_t
    dstY::Csize_t
    dstZ::Csize_t
    dstLOD::Csize_t
    dstMemoryType::CUmemorytype
    dstHost::Ptr{Void}
    dstDevice::CUdeviceptr
    dstArray::CUarray
    reserved1::Ptr{Void}
    dstPitch::Csize_t
    dstHeight::Csize_t
    WidthInBytes::Csize_t
    Height::Csize_t
    Depth::Csize_t
end

immutable CUDA_MEMCPY3D_PEER_st
    srcXInBytes::Csize_t
    srcY::Csize_t
    srcZ::Csize_t
    srcLOD::Csize_t
    srcMemoryType::CUmemorytype
    srcHost::Ptr{Void}
    srcDevice::CUdeviceptr
    srcArray::CUarray
    srcContext::CUcontext
    srcPitch::Csize_t
    srcHeight::Csize_t
    dstXInBytes::Csize_t
    dstY::Csize_t
    dstZ::Csize_t
    dstLOD::Csize_t
    dstMemoryType::CUmemorytype
    dstHost::Ptr{Void}
    dstDevice::CUdeviceptr
    dstArray::CUarray
    dstContext::CUcontext
    dstPitch::Csize_t
    dstHeight::Csize_t
    WidthInBytes::Csize_t
    Height::Csize_t
    Depth::Csize_t
end

immutable CUDA_MEMCPY3D_PEER
    srcXInBytes::Csize_t
    srcY::Csize_t
    srcZ::Csize_t
    srcLOD::Csize_t
    srcMemoryType::CUmemorytype
    srcHost::Ptr{Void}
    srcDevice::CUdeviceptr
    srcArray::CUarray
    srcContext::CUcontext
    srcPitch::Csize_t
    srcHeight::Csize_t
    dstXInBytes::Csize_t
    dstY::Csize_t
    dstZ::Csize_t
    dstLOD::Csize_t
    dstMemoryType::CUmemorytype
    dstHost::Ptr{Void}
    dstDevice::CUdeviceptr
    dstArray::CUarray
    dstContext::CUcontext
    dstPitch::Csize_t
    dstHeight::Csize_t
    WidthInBytes::Csize_t
    Height::Csize_t
    Depth::Csize_t
end

immutable CUDA_ARRAY_DESCRIPTOR_st
    Width::Csize_t
    Height::Csize_t
    Format::CUarray_format
    NumChannels::UInt32
end

immutable CUDA_ARRAY_DESCRIPTOR
    Width::Csize_t
    Height::Csize_t
    Format::CUarray_format
    NumChannels::UInt32
end

immutable CUDA_ARRAY3D_DESCRIPTOR_st
    Width::Csize_t
    Height::Csize_t
    Depth::Csize_t
    Format::CUarray_format
    NumChannels::UInt32
    Flags::UInt32
end

immutable CUDA_ARRAY3D_DESCRIPTOR
    Width::Csize_t
    Height::Csize_t
    Depth::Csize_t
    Format::CUarray_format
    NumChannels::UInt32
    Flags::UInt32
end

immutable CUDA_RESOURCE_DESC_st
    resType::CUresourcetype
    res::Void
    flags::UInt32
end

immutable CUDA_RESOURCE_DESC
    resType::CUresourcetype
    res::Void
    flags::UInt32
end

immutable Array_3_CUaddress_mode
    d1::CUaddress_mode
    d2::CUaddress_mode
    d3::CUaddress_mode
end

zero(::Type{Array_3_CUaddress_mode}) = begin  # /home/shindo/.julia/v0.4/Clang/src/wrap_c.jl, line 266:
        Array_3_CUaddress_mode(fill(zero(CUaddress_mode),3)...)
    end

immutable Array_16_Cint
    d1::Cint
    d2::Cint
    d3::Cint
    d4::Cint
    d5::Cint
    d6::Cint
    d7::Cint
    d8::Cint
    d9::Cint
    d10::Cint
    d11::Cint
    d12::Cint
    d13::Cint
    d14::Cint
    d15::Cint
    d16::Cint
end

zero(::Type{Array_16_Cint}) = begin  # /home/shindo/.julia/v0.4/Clang/src/wrap_c.jl, line 266:
        Array_16_Cint(fill(zero(Cint),16)...)
    end

immutable CUDA_TEXTURE_DESC_st
    addressMode::Array_3_CUaddress_mode
    filterMode::CUfilter_mode
    flags::UInt32
    maxAnisotropy::UInt32
    mipmapFilterMode::CUfilter_mode
    mipmapLevelBias::Cfloat
    minMipmapLevelClamp::Cfloat
    maxMipmapLevelClamp::Cfloat
    reserved::Array_16_Cint
end

immutable CUDA_TEXTURE_DESC
    addressMode::Array_3_CUaddress_mode
    filterMode::CUfilter_mode
    flags::UInt32
    maxAnisotropy::UInt32
    mipmapFilterMode::CUfilter_mode
    mipmapLevelBias::Cfloat
    minMipmapLevelClamp::Cfloat
    maxMipmapLevelClamp::Cfloat
    reserved::Array_16_Cint
end

# begin enum CUresourceViewFormat_enum
typealias CUresourceViewFormat_enum UInt32
const CU_RES_VIEW_FORMAT_NONE = (UInt32)(0)
const CU_RES_VIEW_FORMAT_UINT_1X8 = (UInt32)(1)
const CU_RES_VIEW_FORMAT_UINT_2X8 = (UInt32)(2)
const CU_RES_VIEW_FORMAT_UINT_4X8 = (UInt32)(3)
const CU_RES_VIEW_FORMAT_SINT_1X8 = (UInt32)(4)
const CU_RES_VIEW_FORMAT_SINT_2X8 = (UInt32)(5)
const CU_RES_VIEW_FORMAT_SINT_4X8 = (UInt32)(6)
const CU_RES_VIEW_FORMAT_UINT_1X16 = (UInt32)(7)
const CU_RES_VIEW_FORMAT_UINT_2X16 = (UInt32)(8)
const CU_RES_VIEW_FORMAT_UINT_4X16 = (UInt32)(9)
const CU_RES_VIEW_FORMAT_SINT_1X16 = (UInt32)(10)
const CU_RES_VIEW_FORMAT_SINT_2X16 = (UInt32)(11)
const CU_RES_VIEW_FORMAT_SINT_4X16 = (UInt32)(12)
const CU_RES_VIEW_FORMAT_UINT_1X32 = (UInt32)(13)
const CU_RES_VIEW_FORMAT_UINT_2X32 = (UInt32)(14)
const CU_RES_VIEW_FORMAT_UINT_4X32 = (UInt32)(15)
const CU_RES_VIEW_FORMAT_SINT_1X32 = (UInt32)(16)
const CU_RES_VIEW_FORMAT_SINT_2X32 = (UInt32)(17)
const CU_RES_VIEW_FORMAT_SINT_4X32 = (UInt32)(18)
const CU_RES_VIEW_FORMAT_FLOAT_1X16 = (UInt32)(19)
const CU_RES_VIEW_FORMAT_FLOAT_2X16 = (UInt32)(20)
const CU_RES_VIEW_FORMAT_FLOAT_4X16 = (UInt32)(21)
const CU_RES_VIEW_FORMAT_FLOAT_1X32 = (UInt32)(22)
const CU_RES_VIEW_FORMAT_FLOAT_2X32 = (UInt32)(23)
const CU_RES_VIEW_FORMAT_FLOAT_4X32 = (UInt32)(24)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC1 = (UInt32)(25)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC2 = (UInt32)(26)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC3 = (UInt32)(27)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC4 = (UInt32)(28)
const CU_RES_VIEW_FORMAT_SIGNED_BC4 = (UInt32)(29)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC5 = (UInt32)(30)
const CU_RES_VIEW_FORMAT_SIGNED_BC5 = (UInt32)(31)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC6H = (UInt32)(32)
const CU_RES_VIEW_FORMAT_SIGNED_BC6H = (UInt32)(33)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC7 = (UInt32)(34)
# end enum CUresourceViewFormat_enum

# begin enum CUresourceViewFormat
typealias CUresourceViewFormat UInt32
const CU_RES_VIEW_FORMAT_NONE = (UInt32)(0)
const CU_RES_VIEW_FORMAT_UINT_1X8 = (UInt32)(1)
const CU_RES_VIEW_FORMAT_UINT_2X8 = (UInt32)(2)
const CU_RES_VIEW_FORMAT_UINT_4X8 = (UInt32)(3)
const CU_RES_VIEW_FORMAT_SINT_1X8 = (UInt32)(4)
const CU_RES_VIEW_FORMAT_SINT_2X8 = (UInt32)(5)
const CU_RES_VIEW_FORMAT_SINT_4X8 = (UInt32)(6)
const CU_RES_VIEW_FORMAT_UINT_1X16 = (UInt32)(7)
const CU_RES_VIEW_FORMAT_UINT_2X16 = (UInt32)(8)
const CU_RES_VIEW_FORMAT_UINT_4X16 = (UInt32)(9)
const CU_RES_VIEW_FORMAT_SINT_1X16 = (UInt32)(10)
const CU_RES_VIEW_FORMAT_SINT_2X16 = (UInt32)(11)
const CU_RES_VIEW_FORMAT_SINT_4X16 = (UInt32)(12)
const CU_RES_VIEW_FORMAT_UINT_1X32 = (UInt32)(13)
const CU_RES_VIEW_FORMAT_UINT_2X32 = (UInt32)(14)
const CU_RES_VIEW_FORMAT_UINT_4X32 = (UInt32)(15)
const CU_RES_VIEW_FORMAT_SINT_1X32 = (UInt32)(16)
const CU_RES_VIEW_FORMAT_SINT_2X32 = (UInt32)(17)
const CU_RES_VIEW_FORMAT_SINT_4X32 = (UInt32)(18)
const CU_RES_VIEW_FORMAT_FLOAT_1X16 = (UInt32)(19)
const CU_RES_VIEW_FORMAT_FLOAT_2X16 = (UInt32)(20)
const CU_RES_VIEW_FORMAT_FLOAT_4X16 = (UInt32)(21)
const CU_RES_VIEW_FORMAT_FLOAT_1X32 = (UInt32)(22)
const CU_RES_VIEW_FORMAT_FLOAT_2X32 = (UInt32)(23)
const CU_RES_VIEW_FORMAT_FLOAT_4X32 = (UInt32)(24)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC1 = (UInt32)(25)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC2 = (UInt32)(26)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC3 = (UInt32)(27)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC4 = (UInt32)(28)
const CU_RES_VIEW_FORMAT_SIGNED_BC4 = (UInt32)(29)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC5 = (UInt32)(30)
const CU_RES_VIEW_FORMAT_SIGNED_BC5 = (UInt32)(31)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC6H = (UInt32)(32)
const CU_RES_VIEW_FORMAT_SIGNED_BC6H = (UInt32)(33)
const CU_RES_VIEW_FORMAT_UNSIGNED_BC7 = (UInt32)(34)
# end enum CUresourceViewFormat

immutable Array_16_UInt32
    d1::UInt32
    d2::UInt32
    d3::UInt32
    d4::UInt32
    d5::UInt32
    d6::UInt32
    d7::UInt32
    d8::UInt32
    d9::UInt32
    d10::UInt32
    d11::UInt32
    d12::UInt32
    d13::UInt32
    d14::UInt32
    d15::UInt32
    d16::UInt32
end

zero(::Type{Array_16_UInt32}) = begin  # /home/shindo/.julia/v0.4/Clang/src/wrap_c.jl, line 266:
        Array_16_UInt32(fill(zero(UInt32),16)...)
    end

immutable CUDA_RESOURCE_VIEW_DESC_st
    format::CUresourceViewFormat
    width::Csize_t
    height::Csize_t
    depth::Csize_t
    firstMipmapLevel::UInt32
    lastMipmapLevel::UInt32
    firstLayer::UInt32
    lastLayer::UInt32
    reserved::Array_16_UInt32
end

immutable CUDA_RESOURCE_VIEW_DESC
    format::CUresourceViewFormat
    width::Csize_t
    height::Csize_t
    depth::Csize_t
    firstMipmapLevel::UInt32
    lastMipmapLevel::UInt32
    firstLayer::UInt32
    lastLayer::UInt32
    reserved::Array_16_UInt32
end

immutable CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_st
    p2pToken::Culonglong
    vaSpaceToken::UInt32
end

immutable CUDA_POINTER_ATTRIBUTE_P2P_TOKENS
    p2pToken::Culonglong
    vaSpaceToken::UInt32
end


text:
module Sim
include("./name2idx/parameters.jl")
include("./name2idx/species.jl")
include("./set_model.jl")
include("./observable.jl")

using .C
using .V
import .Main

using Sundials
using SteadyStateDiffEq

# Options for ODE solver
const ABSTOL = 1e-9
const RELTOL = 1e-9
const DTMIN = 1e-8

const dt = 1.0
const tspan = (0.0,7200.0)
const t2 = collect(tspan[1]:dt:tspan[end])
const t = collect(tspan[1]:1.0:tspan[end])./60.0

const conditions = [
    "MCF7_EGF", "MCF7_HRG",
    "BT474_EGF", "BT474_HRG",
    "MDAMB231_EGF", "MDAMB231_HRG"
]

simulations = Array{Float64,3}(
    undef, length(observables), length(t), length(conditions)
)

function solveode(
        f::Function,
        u0::Vector{Float64},
        t::Vector{Float64},
        p::Vector{Float64})
    local sol::ODESolution{}, is_successful::Bool
    try
        prob = ODEProblem(f,u0,(t[1],t[end]),p)
        sol = solve(
            prob,CVODE_BDF(),
            abstol=ABSTOL,reltol=RELTOL,dtmin=DTMIN,saveat=dt,verbose=false
        )
        is_successful = ifelse(sol.retcode === :Success, true, false)
    catch
        is_successful = false
    finally
        if !is_successful
            GC.gc()
        end
    end
    return is_successful ? sol : nothing
end

function get_steady_state(
        f::Function,
        u0::Vector{Float64},
        p::Vector{Float64})::Vector{Float64}
    local sol::SteadyStateSolution{}, is_successful::Bool
    try
        prob = ODEProblem(diffeq,u0,(0.0,Inf),p)
        prob = SteadyStateProblem(prob)
        sol = solve(
            prob,
            DynamicSS(
                CVODE_BDF();abstol=ABSTOL,reltol=RELTOL
            ),
            dt=dt,dtmin=DTMIN,verbose=false
        )
        is_successful = ifelse(sol.retcode === :Success, true, false)
    catch
        is_successful = false
    finally
        if !is_successful
            GC.gc()
        end
    end
    return is_successful ? sol.u : []
end

function simulate!(p::Vector{Float64}, u0::Vector{Float64})
    p_in_mcf7::Vector{Float64} = copy(p)
    u0_in_mcf7::Vector{Float64} = copy(u0)
    for (i, condition) in enumerate(conditions)
        if condition == "MCF7_EGF"
            p .= p_in_mcf7
            u0 .= u0_in_mcf7
            u0 = get_steady_state(diffeq,u0,p)
            if isempty(u0)
                return false
            else
                u0[V.E] = 10.0
                u0[V.H] = 0.0
            end
        elseif condition == "MCF7_HRG"
            p .= p_in_mcf7
            u0 .= u0_in_mcf7
            u0 = get_steady_state(diffeq,u0,p)
            if isempty(u0)
                return false
            else
                u0[V.E] = 0.0
                u0[V.H] = 10.0
            end
        elseif condition == "BT474_EGF"
            p .= p_in_mcf7
            u0 .= u0_in_mcf7
            (p,u0) = Main.mul_ratio2mcf7!(p,u0,"BT-474")
            u0 = get_steady_state(diffeq,u0,p)
            if isempty(u0)
                return false
            else
                u0[V.E] = 10.0
                u0[V.H] = 0.0
            end
        elseif condition == "BT474_HRG"
            p .= p_in_mcf7
            u0 .= u0_in_mcf7
            (p,u0) = Main.mul_ratio2mcf7!(p,u0,"BT-474")
            u0 = get_steady_state(diffeq,u0,p)
            if isempty(u0)
                return false
            else
                u0[V.E] = 0.0
                u0[V.H] = 10.0
            end
        elseif condition == "MDAMB231_EGF"
            p .= p_in_mcf7
            u0 .= u0_in_mcf7
            (p,u0) = Main.mul_ratio2mcf7!(p,u0,"MDA-MB-231")
            u0 = get_steady_state(diffeq,u0,p)
            if isempty(u0)
                return false
            else
                u0[V.E] = 10.0
                u0[V.H] = 0.0
            end
        elseif condition == "MDAMB231_HRG"
            p .= p_in_mcf7
            u0 .= u0_in_mcf7
            (p,u0) = Main.mul_ratio2mcf7!(p,u0,"MDA-MB-231")
            u0 = get_steady_state(diffeq,u0,p)
            if isempty(u0)
                return false
            else
                u0[V.E] = 0.0
                u0[V.H] = 10.0
            end
        end
        sol = solveode(diffeq,u0,t2,p)
        if sol === nothing
            return false
        else
            @inbounds @simd for j in eachindex(t)
                simulations[observables_index("Phosphorylated_Akt"),j,i] = (
                    sol.u[j][V.Aktstar]
                )
                simulations[observables_index("Phosphorylated_ERK"),j,i] = (
                    (sol.u[j][V.pERKn] + sol.u[j][V.ppERKn]) * (p[C.Vn]/p[C.Vc])
                    + sol.u[j][V.pERKc] + sol.u[j][V.ppERKc]
                )
                simulations[observables_index("Phosphorylated_cFos"),j,i] = (
                    sol.u[j][V.pcFOSn]*(p[C.Vn]/p[C.Vc]) + sol.u[j][V.pcFOSc]
                )
            end
        end
    end
end
end # module

ext: jl


text:
include("setupFWItests.jl");

using jInvVis
using PyPlot
figure(20)
imshow(m');

figure(21);
imshow(reshape(gamma,(nx,nz))')

Dp,pFor = getData(vec(m),pFor,false)
nfreq = length(omega);

Dobs = fetch(Dp);
Wd = 1.0./(Dobs .+ 1e-2*maximum(abs(Dobs[:])));

# Wd   = Array{Array{Float64,2}}(undef,length(omega))
# Dobs = Array{Array{Float64,2}}(undef,length(omega))

# for k=1:nfreq
	# Dobs[k] = fetch(Dp[k]);
	# Wd[k] = 1.0./(Dobs[k] .+ 1e-2*maximum(abs(Dobs[k][:])));
	# figure(k);
	# imshow(Dobs[k])
# end
#||W_d*(D(m) - Dobs)||

N = prod(Mr.n);
Iact = sparse(I,N,N);
mback   = zeros(Float64,N);

########################################################################################################
##### Set up remote workers ############################################################################
########################################################################################################

Ainv = getJuliaSolver();
## Choose the workers for FWI (here, its a single worker)
misfun = SSDFun;
pMis = getMisfitParam(pFor, Wd, Dobs, misfun, Iact,mback);


text:
module TestECOS

using Test
import ECOS
import MathOptInterface

const MOI = MathOptInterface

function runtests()
    for name in names(@__MODULE__; all = true)
        if startswith("$(name)", "test_")
            @testset "$(name)" begin
                getfield(@__MODULE__, name)()
            end
        end
    end
    return
end

function test_runtests()
    model = MOI.Utilities.CachingOptimizer(
        MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
        MOI.instantiate(ECOS.Optimizer; with_bridge_type = Float64),
    )
    @test model.optimizer.model.model_cache isa
          MOI.Utilities.UniversalFallback{ECOS.OptimizerCache}
    MOI.set(model, MOI.Silent(), true)
    exclude = String[
        # ZerosBridge does not support ConstraintDual. These are tested below in
        # test_runtests_ZerosBridge
        "test_conic_RotatedSecondOrderCone_INFEASIBLE_2",
        "test_conic_linear_VectorOfVariables_2",
        "test_linear_integration",
        "test_quadratic_constraint_GreaterThan",
        "test_quadratic_constraint_LessThan",
    ]
    if Sys.WORD_SIZE == 32
        # These tests fail on x86 Linux, returning ITERATION_LIMIT instead of
        # proving {primal,dual}_INFEASIBLE.
        push!(exclude, "test_conic_linear_INFEASIBLE")
        push!(exclude, "test_solve_TerminationStatus_DUAL_INFEASIBLE")
    end
    MOI.Test.runtests(
        model,
        MOI.Test.Config(
            atol = 1e-3,
            rtol = 1e-3,
            exclude = Any[
                MOI.ConstraintBasisStatus,
                MOI.VariableBasisStatus,
                MOI.ObjectiveBound,
            ],
        ),
        exclude = exclude,
    )
    return
end

function test_runtests_ZerosBridge()
    optimizer = MOI.instantiate(ECOS.Optimizer; with_bridge_type = Float64)
    MOI.Bridges.remove_bridge(
        optimizer,
        MOI.Bridges.Variable.ZerosBridge{Float64},
    )
    model = MOI.Utilities.CachingOptimizer(
        MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
        optimizer,
    )
    MOI.Test.runtests(
        model,
        MOI.Test.Config(
            atol = 1e-3,
            rtol = 1e-3,
            exclude = Any[
                MOI.ConstraintBasisStatus,
                MOI.VariableBasisStatus,
                MOI.ObjectiveBound,
            ],
        ),
        include = String[
            # ZerosBridge does not support ConstraintDual
            "test_conic_RotatedSecondOrderCone_INFEASIBLE_2",
            "test_conic_linear_VectorOfVariables_2",
            "test_linear_integration",
            "test_quadratic_constraint_GreaterThan",
            "test_quadratic_constraint_LessThan",
        ],
    )
    return
end

function test_RawOptimizerAttribute()
    model = ECOS.Optimizer()
    MOI.set(model, MOI.RawOptimizerAttribute("abstol"), 1e-5)
    @test MOI.get(model, MOI.RawOptimizerAttribute("abstol")) ≈ 1e-5
    MOI.set(model, MOI.RawOptimizerAttribute("abstol"), 2e-5)
    @test MOI.get(model, MOI.RawOptimizerAttribute("abstol")) == 2e-5
    return
end

function test_iteration_limit()
    v = [5.0, 3.0, 1.0]
    w = [2.0, 1.5, 0.3]
    solver = MOI.OptimizerWithAttributes(ECOS.Optimizer, MOI.Silent() => true)
    model = MOI.instantiate(solver, with_bridge_type = Float64)
    maxit = 1
    MOI.set(model, MOI.RawOptimizerAttribute("maxit"), maxit)
    MOI.set(model, MOI.Silent(), true)
    x = MOI.add_variables(model, 3)
    MOI.add_constraint.(model, x, MOI.Interval(0.0, 1.0))
    MOI.add_constraint(
        model,
        MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(w, x), 0.0),
        MOI.LessThan(3.0),
    )
    MOI.set(
        model,
        MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(),
        MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(v, x), 0.0),
    )
    MOI.set(model, MOI.ObjectiveSense(), MOI.MAX_SENSE)
    MOI.optimize!(model)
    @test MOI.get(model, MOI.TerminationStatus()) == MOI.ITERATION_LIMIT
    @test MOI.get(model, MOI.BarrierIterations()) == maxit
    return
end

function test_empty_problem()
    model = MOI.Utilities.Model{Float64}()
    ecos = ECOS.Optimizer()
    MOI.optimize!(ecos, model)
    @test MOI.get(ecos, MOI.TerminationStatus()) == MOI.INVALID_MODEL
    @test MOI.get(ecos, MOI.PrimalStatus()) == MOI.NO_SOLUTION
    @test MOI.get(ecos, MOI.DualStatus()) == MOI.NO_SOLUTION
    return
end

function test_conic_no_variables()
    model = MOI.Utilities.Model{Float64}()
    ecos = ECOS.Optimizer()
    f = MOI.VectorAffineFunction(
        MOI.VectorAffineTerm{Float64}[],
        [1.0, 0.5, 0.5],
    )
    MOI.add_constraint(model, f, MOI.SecondOrderCone(3))
    MOI.optimize!(ecos, model)
    @test MOI.get(ecos, MOI.TerminationStatus()) == MOI.INVALID_MODEL
    @test MOI.get(ecos, MOI.PrimalStatus()) == MOI.NO_SOLUTION
    @test MOI.get(ecos, MOI.DualStatus()) == MOI.NO_SOLUTION
    return
end

end  # module

TestECOS.runtests()


text:
#=
   Car buyer - Neapolital

   From the Netica model Car_Buyer Neapolital.dne
   """
   This decision network is from Neapolitan90 (p.373), which is a simpler version of the car
   buyer example of Howard62.  Eliminating the rationale given there of how the numbers are
   arrived at, we have the following story:

   Joe is going to buy a used car, which could be good with probability 0.8 or a lemon with
   probability 0.2.  After accounting for repairs, Joe's profit will be $60 if the car is
   good, and $-100 if it is bad.  Before buying the car he has the option of having one test
   or two tests done on it.  The first test costs $9, and both together cost $13.  The first
   test has a 90% chance of returning positive if the car is good, and a 40% chance if it's
   a lemon.  If the first test returns positive, then the second test has a 88.89% chance of
   returning positive if the car is good, and a 33.33% chance if it's a lemon.  If the first
   test returns negative, then the second test has a 100% chance of returning positive if
   the car is good, and a 44.44% chance if it's a lemon.

   Joe has 2 decisions to make: whether to do the tests, and whether to buy the car.  These
   are represented by the "Do Tests?" and "Buy It?" decision nodes.  The outcome of the tests
   are given by nodes "First Test" and "Second Test".  The costs of the tests are represented
   by utility node U, and the profits after repairs (not including test costs) by utility
   node V.

   When Joe decides whether to do the tests, he doesn't know the value of any of these
   variables, so there are no links entering the "Do Tests?" node.  When he decides whether
   to buy, he will know the outcome of both tests (the outcomes may be "not done"), and so
   there are links from those two nodes to "Buy It?".  He will also know the value of
   "Do Tests?" since he has already made that decision, so you could put a link from that
   node to "Buy It?", but it is not necessary since it is a no-forgetting link and there is
   already a directed path from "Do Tests?" to "Buy It?".
   """

   Distributions of variable condition
   lemon      =>    5813  (0.581300)
   good       =>    4187  (0.418700)

   Distributions of variable do_tests
   both       =>   10000  (1.000000)

   Distributions of variable first_test
   negative   =>   10000  (1.000000)

   Distributions of variable second_test
   notDone    =>    4187  (0.418700)
   negative   =>    3276  (0.327600)
   positive   =>    2537  (0.253700)

   Distributions of variable buy_it
   dont_buy   =>    5813  (0.581300)
   buy        =>    4187  (0.418700)

   Distributions of variable v (num:0)
   0.00000 =>    5813  (0.581300)
   60.00000 =>    4187  (0.418700)

   Distributions of variable u (num:0)
  -13.00000 =>   10000  (1.000000)

   do_tests, first_test, second_test, buy_it, v, u, v+y:
   Distributions of variable (num:0)
   [3, 3, 1, 1, 60, -13, 47]	=>	4187 (0.4187)
   [3, 3, 3, 2, 0, -13, -13]	=>	3276 (0.3276)
   [3, 3, 2, 2, 0, -13, -13]	=>	2537 (0.2537)

  Cf ~/blog/car_buyer.blog
     ~/webppl/car_buyer.wppl

=#

using Turing, StatsPlots, DataFrames
include("jl_utils.jl")

@model function car_buyer()
    good = 1
    lemon = 2
    # conditions = [good, lemon]

    none = 1
    first = 2
    both = 3
    # doTests = [none", first", both"]

    notDone = 1
    positive = 2
    negative = 3
    # tests = [notDone, positive, negative]

    buy = 1
    dont_buy = 2

    condition ~ Categorical(simplex([80,20])) # [good, lemon]
    do_tests ~ Categorical(simplex([28,26.2,22.7333])) # [none,first,both]

    # [notDone,positive,negative]
    first_test ~
        (condition==good && do_tests==none)  ? Categorical(simplex([100,0,0])) :
        (condition==good && do_tests==first) ? Categorical(simplex([0,90,10])) :
        (condition==good && do_tests==both)  ? Categorical(simplex([0,90,10])) :
        (condition==lemon&& do_tests==none)  ? Categorical(simplex([100,0,0])) :
        (condition==lemon&& do_tests==first) ? Categorical(simplex([0,40,60])) :
        (condition==lemon&& do_tests==both)  ? Categorical(simplex([0,40,60])) : Dirac(0)

    second_test ~ (first_test==notDone && condition==good && do_tests==none)    ? Categorical(simplex([100, 0, 0])) :
        (first_test==notDone && condition==lemon && do_tests==none)   ? Categorical(simplex([100, 0, 0])) :

        (first_test==positive && condition==good && do_tests==first)  ? Categorical(simplex([100, 0, 0])) :
        (first_test==positive && condition==good && do_tests==both)   ? Categorical(simplex([0, 88.889, 11.111])) :

        (first_test==positive && condition==lemon && do_tests==first) ? Categorical(simplex([100, 0, 0])) :
        (first_test==positive && condition==lemon && do_tests==both)  ? Categorical(simplex([100, 33.3333, 66.6667])) :

        (first_test==negative && condition==good && do_tests==first)  ? Categorical(simplex([100, 0, 0])) :
        (first_test==negative && condition==good && do_tests==both)   ? Categorical(simplex([100, 0, 0])) :

        (first_test==negative && condition==lemon && do_tests==first) ? Categorical(simplex([100, 0, 0])) :
        (first_test==negative && condition==lemon && do_tests==both)  ? Categorical(simplex([0, 44.4444, 55.5556])) : Dirac(0)

    buy_it ~ Dirac(
            (do_tests == first && second_test == notDone && first_test == negative)
            ||
            (do_tests == both && second_test == positive && first_test == negative)
            ||
            (do_tests == both && second_test == negative && first_test == positive)
            ||
            (do_tests == both && second_test == negative && first_test == negative) ? dont_buy : buy)

    v ~ Dirac(
        (condition==good  && buy_it==buy)      ? 60   :
        (condition==good  && buy_it==dont_buy) ? 0    :
        (condition==lemon && buy_it==buy)      ? -100 :
        (condition==lemon && buy_it==dont_buy) ?  0   : -1
        )

    u ~ Dirac(
        do_tests == none  ?  0  :
        do_tests == first ? -9  :
        do_tests == both  ? -13 : -1
    )

    true ~ Dirac(do_tests == both)
    true ~ Dirac(first_test == negative)
    # true ~ Dirac(second_test == negative)

    # true ~ Dirac(do_tests == first)
    # true ~ Dirac(first_test == negative)
    # true ~ Dirac(buy_it==buy)
    # true ~ Dirac(v>0)
    return [do_tests,first_test,second_test,buy_it,v,u,v+u]
end

model = car_buyer()

num_chains = 4

# chns = sample(model, Prior(), 10_000)
# chns = sample(model, MH(), 10_000)
# chns = sample(model, PG(15), 10_000)
chns = sample(model, SMC(10_000), 10_000)
# chns = sample(model, IS(), 10_000)

# chns = sample(model, NUTS(), 10_000)
# chns = sample(model, HMC(0.1,10), 10_000)

display(chns)
# display(plot(chns))

println("\ngood = 1 lemon = 2")
show_var_dist_pct(chns, :condition,["good","lemon"])

println("\nnone = 1 first = 2  both = 3")
show_var_dist_pct(chns, :do_tests,["none","first","both"])

println("\nnotDone = 1 positive = 2 negative = 3")
show_var_dist_pct(chns, :first_test,["notDone","positive","negative"])

show_var_dist_pct(chns, :second_test,["notDone","positive","negative"])

println("\nbuy = 1 dont_buy = 2\n")
show_var_dist_pct(chns, :buy_it,["buy","dont_buy"])

println()
show_var_dist_pct(chns, :v)

println()
show_var_dist_pct(chns, :u)

println()
chains_params = Turing.MCMCChains.get_sections(chns, :parameters)
genq = generated_quantities(model, chains_params)
println("do_tests, first_test, second_test, buy_it, v, u, v+y:")
show_var_dist_pct(genq)

max_stars_repo_name: tias/hakank

max_issues_repo_name: tias/hakank

max_forks_repo_name: tias/hakank


text:
println("First line of the script")
time_start = time()
using ViewerGL
using Distributed
if nprocs() == 1
    addprocs(3)
end
# using Revise
using Test
using Logging
using SparseArrays
using ExSup
# using ExSup

fn = "exp_surface_extraction_cube_times.csv"
data = Dict()

@info "before everywhere using"
@info "time from start: $(time()-time_start) [s]"
# using Plasm
@everywhere using LarSurf
# @everywhere using Distributed

# block_size = [64, 64, 64]
block_size = [32, 32, 32]
data_size1 = 128
# data_size1 = 256
# data_size1 = 512

LarSurf.set_time_data(data)

# data["nprocs"] = nprocs()
# data["fcn"] = String(Symbol(fcni))
data["nprocs"] = nprocs()
data["nworkers"] = nworkers()
data["jlfile"] = @__FILE__
data["hostname"] = gethostname()
data["ncores"] = length(Sys.cpu_info())
data["data size"] = data_size1
data["block size"] = block_size[1]

data["using done"] = time()-time_start
# segmentation = LarSurf.data234()
@info "Generate data..."
@info "time from start: $(time()-time_start) [s]"
segmentation = LarSurf.generate_cube(data_size1; remove_one_pixel=true)
@info "==== using done, data generated time from start: $(time()-time_start) [s]"
data["data generated"] = time()-time_start

@info "Setup..."
setup_time = @elapsed LarSurf.lsp_setup(block_size;reference_time=time_start)
println("setup time: $setup_time")
@info "==== setup done, time from start: $(time()-time_start) [s]"
data["setup done"] = time()-time_start
# for wid in workers()
#     # println("testing on $wid")
#     ftr = @spawnat wid LarSurf._single_boundary3
#     @test fetch(ftr) != nothing
# end

# @debug "Setup done"
tmd = @timed larmodel = LarSurf.lsp_get_surface(segmentation)
val, tm, mem, gc = tmd
println("Total time: $tm")
@info "==== finished, time from start: $(time()-time_start) [s]"
data["finished"] = time()-time_start
ExSup.datetime_to_dict!(data)
ExSup.add_to_csv(data, fn)

V, FV = larmodel

ViewerGL.VIEW([
    ViewerGL.GLGrid(V,FV,ViewerGL.Point4d(1,1,1,0.1))
	ViewerGL.GLAxis(ViewerGL.Point3d(-1,-1,-1),ViewerGL.Point3d(1,1,1))
])
Vs = LarSurf.Smoothing.smoothing(V)
# Plasm.view(val)
ViewerGL.VIEW([
    ViewerGL.GLGrid(Vsm,FV,ViewerGL.Point4d(1,1,1,0.1))
	ViewerGL.GLAxis(ViewerGL.Point3d(-1,-1,-1),ViewerGL.Point3d(1,1,1))
])


text:
## Define the datastructures that are only used by the generic SCoBA solver

"""
Every task has three modes in terms of its time window - start, finish success
"""
@enum MODE START=1 FINISH=2 SUCCESS=3

"""
An event between an agent and a task, and the planned time for the same.
N.B. Using integer IDs instead of strings would probably be more efficient.
"""
struct InteractionEvent
    agent_name::String
    task_name::String
    timestamps::Dict{MODE,Float64}
end

"""
Represents a decision node of the policy tree
"""
@with_kw mutable struct DecisionNode
    agent_name::String  = String("")
    task_name::String   = String("")
    attempt::Bool       = false
    timeval::Float64    = 0.0
    util::Float64       = -Inf
    idx::Int64          = 0
    utilset::Bool       = false
end

"""
Represents an outcome node of the policy tree
"""
@with_kw mutable struct OutcomeNode
    agent_name::String      = String("")
    task_name::String       = String("")
    outcome::MODE           = START
    timeval::Float64        = 0.0
    probability::Float64    = 0.0
    util::Float64           = -Inf
    idx::Int64              = 0
    utilset::Bool           = false
end

"""
The policy tree structure is a list of decision or outcome nodes.
"""
@with_kw mutable struct SearchTree
    nodes::Vector{Union{DecisionNode,OutcomeNode}}  = Vector{Union{DecisionNode,OutcomeNode}}(undef, 0)
    child_ids::Dict{Int64,Vector{Int64}}            = Dict{Int64,Vector{Int64}}()
    parent_id::Dict{Int64,Int64}                    = Dict{Int64,Int64}()
end

function Base.empty!(st::SearchTree)
    empty!(st.nodes)
    empty!(st.child_ids)
    empty!(st.parent_id)
end
Base.isempty(st::SearchTree) = (isempty(st.nodes) || isempty(st.child_ids))

# A for Agent Type (immutable), AP for AgentProperties (mutable)
@with_kw mutable struct GenericAllocation{A,AP}
    current_time::Float64       = 0.0
    agent_set::Dict{String,A}   = Dict{String,A}()
    agent_prop_set::Dict{String,AP} = Dict{String,AP}()
    agent_task_windows::Dict{Tuple{String,String}, SVector{3,Float64}}  = Dict{Tuple{String,String}, SVector{3,Float64}}()
    agent_task_allocation::Dict{String, NamedTuple{(:name, :time), Tuple{String, Float64}}} = Dict{String, NamedTuple{(:name, :time), Tuple{String, Float64}}}()
    agent_ordering::Vector{String}  = String[]
    max_tasks_to_consider::Int64    = 100000
    conflict_threshold::Int64        = 100
end

abstract type MRTAEnvironment end


text:
syms lon lat
syms x1 y1 z1

x=cos(lon)*cos(lat);
y=sin(lon)*cos(lat);
z=sin(lat);
%x/y=cos(lon)/sin(lon);

x=cos(lon);
y=sin(lon);
z=sin(lat)/cos(lat);

lon1=atan2(y1,x1);
lat1=asin(z1);

D(1,1)=diff(x,lon);
D(2,1)=diff(y,lon);
D(3,1)=diff(z,lon);
D(1,2)=diff(x,lat);
D(2,2)=diff(y,lat);
D(3,2)=diff(z,lat);

D1(1,1)=diff(lon1,x1);
D1(1,2)=diff(lon1,y1);
D1(1,3)=diff(lon1,z1);
D1(2,1)=diff(lat1,x1);
D1(2,2)=diff(lat1,y1);
D1(2,3)=diff(lat1,z1);

DPen=inv(transpose(D)*D)*transpose(D);
DPen=simplify(DPen);
A(1,1)=cos(lat);
A(1,2)=0;
A(2,1)=0;
A(2,2)=1;
DD=A*DPen;
aa=3;


text:
module QuantumAlgebra

include("tools.jl")
include("operator_defs.jl")
include("index_handling.jl")
include("operator_baseops.jl")
include("alias.jl")
include("output.jl")
include("correlations.jl")
include("vacuum_expvals.jl")
include("convert_to_expression.jl")

include("precompile.jl")
_precompile_()

function __init__()
    # WARNING: This does not work since using @eval in __init__ means the module
    # cannot be used inside any other module. The error upon precompilation of
    # the other module is:
    # ERROR: LoadError: InitError: Evaluation into the closed module
    # `QuantumAlgebra` breaks incremental compilation because the side effects
    # will not be permanent. This is likely due to some other module mutating
    # `QuantumAlgebra` with `eval` during precompilation - don't do this.

    # default_ops = parse(Bool,get(ENV,"QUANTUMALGEBRA_DEFAULT_OPS","true"))
    # if default_ops
    #     @eval begin
    #         @boson_ops a
    #         @fermion_ops f
    #         @tlspm_ops σ
    #         @tlsxyz_ops σ
    #         export σx, σy, σz, σp, σm
    #         export a, adag, f, fdag
    #     end
    # end

    auto_normal = parse(Bool,get(ENV,"QUANTUMALGEBRA_AUTO_NORMAL_FORM","false"))
    auto_normal_form(auto_normal)
end

end # module


text:
# Join works on collections of collections (e.g. a table is a collection of
# rows).

innerjoin(left, right) = innerjoin(identity, identity, left, right)
innerjoin(lkey, rkey, left, right) = innerjoin(lkey, rkey, merge, left, right)
innerjoin(lkey, rkey, f, left, right) = innerjoin(lkey, rkey, f, isequal, left, right)

const ⨝ = innerjoin

"""
    innerjoin(lkey, rkey, f, comparison, left, right)

Performs a relational-style join operation between iterables `left` and `right`, returning
a collection of elements `f(l, r)` for which `comparison(lkey(l), rkey(r))` is `true` where
`l ∈ left`, `r ∈ right.`

# Example

```jldoctest
julia> innerjoin(iseven, iseven, tuple, ==, [1,2,3,4], [0,1,2])
6-element Array{Tuple{Int64,Int64},1}:
 (1, 1)
 (2, 0)
 (2, 2)
 (3, 1)
 (4, 0)
 (4, 2)
```
"""
function innerjoin(lkey, rkey, f, comparison, left, right)
    # TODO Do this inference-free, like comprehensions...
    T = promote_op(f, eltype(left), eltype(right))
    out = empty(left, T)

    innerjoin!(out, lkey, rkey, f, comparison, left, right)
    return out
end

function innerjoin!(out, lkey, rkey, f, comparison, left, right)
    # The O(length(left)*length(right)) generic method when nothing about `comparison` is known
    for a ∈ left
        for b ∈ right
            if comparison(lkey(a), rkey(b))
                push!(out, f(a, b))
            end
        end
    end
    return out
end

function innerjoin!(out, lkey, rkey, f, ::typeof(isequal), left, right)
    # isequal heralds a hash-based approach, roughly O(length(left) * log(length(right)))

    K = promote_op(rkey, eltype(right))
    V = eltype(right)
    dict = Dict{K,Vector{V}}() # maybe a different stategy if right is unique
    for b ∈ right
        key = rkey(b)
        push!(get!(()->Vector{V}(), dict, key), b)
    end

    for a ∈ left
        key = lkey(a)
        dict_index = Base.ht_keyindex(dict, key)
        if dict_index > 0 # -1 if key not found
            for b ∈ dict.vals[dict_index]
                push!(out, f(a, b))
            end
        end
    end
    return out
end

# For arrays, the assumptions around the below are
#  * Accessing arrays via indices and mapviews should be similar in speed to the above
#  * We can specialize these methods on particular arrays - works well for TypedTables.Table
#    of AcceleratedArrays.AcceleratedArray

function innerjoin!(out, lkey, rkey, f, comparison, left::AbstractArray, right::AbstractArray)
    _innerjoin!(out, mapview(lkey, left), mapview(rkey, right), productview(f, left, right), comparison)
end

function innerjoin!(out, lkey, rkey, f, ::typeof(isequal), left::AbstractArray, right::AbstractArray)
    _innerjoin!(out, mapview(lkey, left), mapview(rkey, right), productview(f, left, right), isequal)
end

function _innerjoin!(out, l::AbstractArray, r::AbstractArray, v::AbstractArray, comparison)
    @boundscheck if (axes(l)..., axes(r)...) != axes(v)
        throw(DimensionMismatch("innerjoin arrays do not have matching dimensions"))
    end

    @inbounds for i_l in keys(l)
        for i_r in keys(r)
            if comparison(l[i_l], r[i_r])
                push!(out, v[Tuple(i_l)..., Tuple(i_r)...])
            end
        end
    end

    return out
end

function _innerjoin!(out, l::AbstractArray, r::AbstractArray, v::AbstractArray, ::typeof(isequal))
    @boundscheck if (axes(l)..., axes(r)...) != axes(v)
        throw(DimensionMismatch("innerjoin arrays do not have matching dimensions"))
    end

    rkeys = keys(r)
    V = eltype(rkeys)
    dict = Dict{eltype(r), Vector{V}}()
    @inbounds for i_r ∈ rkeys
        push!(get!(()->Vector{V}(), dict, r[i_r]), i_r)
    end

    @inbounds for i_l in keys(l)
        l_value = l[i_l]
        dict_index = Base.ht_keyindex(dict, l_value)
        if dict_index > 0 # -1 if key not found
            for i_r ∈ dict.vals[dict_index]
                push!(out, v[Tuple(i_l)..., Tuple(i_r)...])
            end
        end
    end

    return out
end

# TODO more specialized methods for comparisons: ==, <, isless, etc - via sorting strategies

# TODO perhaps a better version would be:
# function innerjoin(left, right; lkey = identity, rkey = identity, f = tuple, comparison = isequal)
#     ...
# end


text:
"""
`SmoothedDisplacement <: ImageTransformation`

Description
============

Distorts the given image using a randomly (uniform) generated
`DisplacementField` of the given grid size. This field will be
streched over the given image and converted into a `DisplacementMesh`.
which in turn will morph the original image into a new image using
piecewise affine transformations.

In contrast to `RandomDisplacement`, the resulting vector field is
also smoothed using a gaussian filter with of parameter `sigma`.
This will result in a less chaotic displacement field and be much
more similar to an elastic distortion.

Usage
======

    SmoothedDisplacement(gridwidth, gridheight[, scale=0.2, sigma=2, iterations=1, static_border=true, normalize=true])

Arguments
==========

- **`gridwidth`** : The width of the displacment field. Effectively
specifies the number of vertices along the X dimension used as
landmarks during the deformation process

- **`gridheight`** : The height of the displacment field. Effectively
specifies the number of vertices along the Y dimension used as
landmarks during the deformation process

- **`scale`** : The scaling factor applied to all displacement
vectors in the field. This effectively defines the "strength" of the
deformation. There is no theoretical upper limit to this factor, but
a value somewhere between `0.01` and `1.0` seem to be the most reasonable
choices. Default to `0.2`.

- **`sigma`** : Sigma parameter of the gaussian filter.
This parameter effectively controls the strength of the smoothing.

- **`iterations`** : The number of times the smoothing operation
is applied to the `DisplacementField`. This is especially useful
if `static_border == true` because the border will be reset to
zero after each pass. Thus the displacement is a little less
aggressive towards the borders of the image than it is towards
its center.

- **`static_border`** : If true, the borders of the image will be
preserved. This effectively pins the outermost verticies on their
original position and the operation thus only deforms the inner
content of the image.

- **`normalize`** : If true, the field will be normalized its norm.
This will have the effect that the `scale` factor should be more or
less independent of the grid size.

Methods
========

- **`transform`** : Applies the transformation to the given Image
or set of images

Author(s)
==========

- Christof Stocker (Github: https://github.com/Evizero)

Examples
========

    using Augmentor
    using TestImages

    # load an example image
    img = testimage("lena")

    # Randomly distort the image using a smoothed 10x15 displacement field
    img_new = transform(SmoothedDisplacement(10, 15; scale = .1, sigma = 3), img)

see also
=========

`RandomDisplacement`

`uniform_displacement`, `ImageTransformation`, `transform`
"""
immutable SmoothedDisplacement <: ImageTransformation
    gridwidth::Int
    gridheight::Int
    scale::Float64
    sigma::Float64
    iterations::Int
    static_border::Bool
    normalize::Bool
end

function SmoothedDisplacement(gridwidth::Real, gridheight::Real; scale = .2, sigma = 2, iterations = 1, static_border::Bool = true, normalize::Bool = true)
    (gridwidth > 2 && gridheight > 2) || throw(ArgumentError("gridwidth and gridheight need to be greater than 2"))
    sigma > 0 || throw(ArgumentError("sigma needs to be greater than 0"))
    iterations > 0 || throw(ArgumentError("iterations needs to be greater than 0"))
    SmoothedDisplacement(Int(gridwidth), Int(gridheight), Float64(scale), Float64(sigma), Int(iterations), static_border, normalize)
end

Base.showcompact(io::IO, op::SmoothedDisplacement) = print(io, "Displace randomly with smoothed $(op.gridwidth)x$(op.gridheight) displacement field (σ = $(op.sigma)).")
multiplier(::SmoothedDisplacement) = 1 # not true, basically infinity...

function transform{T<:AbstractImage}(op::SmoothedDisplacement, img::T)
    df = gaussian_displacement(op.gridwidth, op.gridheight, op.scale, op.sigma, op.iterations, op.static_border, op.normalize)
    transform(df, img)::T
end


text:
module PyTest

include("exceptions.jl")

export @fixture, @pytest,
       PyTestException,
       tempdir_fixture, request

using Base.Test
using ResumableFunctions

include("types.jl")
include("fixture.jl")
include("runner_args.jl")

include("macros.jl")

include("request.jl")
include("builtin.jl")

end # module


text:
export krr_train, krr

#using PERK: RFFTrainingData, RFFKernel
#using PERK: ExactTrainingData, ExactKernel
using ForwardDiff: ForwardDiff

"""
    krr_train([rng], xtrain, ytrain, kernel, ρ)
    krr_train(xtrain, ytrain, kernel, ρ, f, phase)

Train kernel ridge regression.

# Arguments
- `rng::AbstractRNG = Random.GLOBAL_RNG`: Random number generator to use
  (only used when `kernel isa RFFKernel`)
- `xtrain::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}}`: Latent
  parameters for training data [L,T] or \\[T\\] (if L = 1)
- `ytrain::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}}`: Features
  for training data [Q,T] or \\[T\\] (if Q = 1)
- `kernel::Kernel`: Kernel to use
- `ρ::Real`: Tikhonov regularization parameter
- `f::Union{<:AbstractVector{<:Real},AbstractMatrix{<:Real}} = randn(kernel.H, Q)`:
  Unscaled random frequency values [H,Q] or \\[H\\] (if Q = 1) (used when
  `kernel isa RFFKernel`)
- `phase::AbstractVector{<:Real} = rand(kernel.H)`: Random phase values \\[H\\]
  (used when `kernel isa RFFKernel`)

## Note
- L is the number of unknown or latent parameters to be predicted
- Q is the number of observed features per training sample
- T is the number of training samples
- H is approximation order for kernels that use random Fourier features

# Return
- `trainData::TrainingData`: `TrainingData` object to be passed to `krr`
"""
function krr_train(
    xtrain::AbstractVector{<:Real},
    ytrain::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}},
    kernel::ExactKernel,
    ρ::Real
)

    # Grab the number of training points
    T = length(xtrain)

    # Evaluate the kernel on the training features
    K = kernel(ytrain, ytrain) # [T,T]

    # Calculate the sample mean and de-mean the latent parameters
    xm = mean(xtrain) # scalar (L = 1)
    xtrain = xtrain .- xm # [T]

    # De-mean the rows and columns of the kernel output
    Km = dropdims(mean(K, dims = 2), dims = 2) # [T]
    K = K .- Km # [T,T]
    K = K .- mean(K, dims = 1) # [T,T]

    # Compute the (regularized) inverse of K and multiply by xtrain
    xKinv = transpose(K + T * ρ * I) \ xtrain # [T]

    return ExactTrainingData(ytrain, xtrain, xm, K, Km, xKinv)

end

function krr_train(
    xtrain::AbstractMatrix{<:Real},
    ytrain::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}},
    kernel::ExactKernel,
    ρ::Real
)

    # Grab the number of training points
    T = size(xtrain, 2)

    # Evaluate the kernel on the training features
    K = kernel(ytrain, ytrain) # [T,T]

    # Calculate the sample mean and de-mean the latent parameters
    xm = dropdims(mean(xtrain, dims = 2), dims = 2) # [L]
    xtrain = xtrain .- xm # [L,T]

    # De-mean the rows and columns of the kernel output
    Km = dropdims(mean(K, dims = 2), dims = 2) # [T]
    K = K .- Km # [T,T]
    K = K .- mean(K, dims = 1) # [T,T]

    # Compute the (regularized) inverse of K and multiply by xtrain
    xKinv = xtrain / (K + T * ρ * I) # [L,T]

    return ExactTrainingData(ytrain, xtrain, xm, K, Km, xKinv)

end

# rng not used with ExactKernels
# This method exists only to mirror how krr_train can be called with a RFFKernel
function krr_train(
    ::AbstractRNG,
    xtrain,
    ytrain,
    kernel::ExactKernel,
    ρ
)

    return krr_train(xtrain, ytrain, kernel, ρ)

end

function krr_train(
    rng::AbstractRNG,
    xtrain::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}},
    ytrain::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}},
    kernel::RFFKernel,
    ρ::Real
)

    # Use random Fourier features to approximate the kernel
    (z, freq, phase) = kernel(rng, ytrain)

    return _krr_train(xtrain, z, ρ, freq, phase)

end

function krr_train(
    xtrain,
    ytrain,
    kernel::RFFKernel,
    ρ
)

    return krr_train(Random.GLOBAL_RNG, xtrain, ytrain, kernel, ρ)

end

function krr_train(
    xtrain::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}},
    ytrain::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}},
    kernel::RFFKernel,
    ρ::Real,
    f::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}},
    phase::AbstractVector{<:Real}
)

    # Use random Fourier features to approximate the kernel
    (z, freq, phase) = kernel(ytrain, f, phase)

    return _krr_train(xtrain, z, ρ, freq, phase)

end

function _krr_train(
    xtrain::AbstractVector{<:Real}, # [T]
    z::AbstractMatrix{<:Real}, # [H,T]
    ρ::Real,
    freq::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}}, # [H,Q] or [H]
    phase::AbstractVector{<:Real} # [H]
)

    # Grab the number of training points
    T = size(z, 2)

    # Calculate sample means
    xm = mean(xtrain) # scalar (L = 1)
    zm = dropdims(mean(z, dims = 2), dims = 2) # [H]

    # Calculate sample covariances
    xtrain = xtrain .- xm # [T]
    z = z .- zm # [H,T]
    Czz = div0.(A_mul_A′(z), T) # [H,H]
    Cxz = div0.(z * xtrain, T) # [H]

    # Calculate the (regularized) inverse of Czz and multiply by Cxz
    CxzCzzinv = transpose(Czz + ρ * I) \ Cxz # [H]

    return RFFTrainingData(freq, phase, zm, xm, Czz, Cxz, CxzCzzinv)

end

function _krr_train(
    xtrain::AbstractMatrix{<:Real}, # [L,T]
    z::AbstractMatrix{<:Real}, # [H,T]
    ρ::Real,
    freq::Union{<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}}, # [H,Q] or [H]
    phase::AbstractVector{<:Real} # [H]
)

    # Grab the number of training points
    T = size(z, 2)

    # Calculate sample means
    xm = dropdims(mean(xtrain, dims = 2), dims = 2) # [L]
    zm = dropdims(mean(z, dims = 2), dims = 2) # [H]

    # Calculate sample covariances
    xtrain = xtrain .- xm # [L,T]
    z = z .- zm # [H,T]
    Czz = div0.(A_mul_A′(z), T) # [H,H]
    Cxz = div0.(xtrain * z', T) # [L,H]

    # Calculate the (regularized) inverse of Czz and multiply by Cxz
    CxzCzzinv = Cxz / (Czz + ρ * I) # [L,H]

    return RFFTrainingData(freq, phase, zm, xm, Czz, Cxz, CxzCzzinv)

end

A_mul_A′(A) = A * A'

# See https://people.maths.ox.ac.uk/gilesm/files/NA-08-01.pdf
function A_mul_A′(D::AbstractMatrix{<:ForwardDiff.Dual{T}}) where T

    A = ForwardDiff.value.(D)
    AA′ = A_mul_A′(A)
    Δ = ForwardDiff.partials.(D)
    # dAA′ = Δ * A' + A * Δ'
    ΔA′ = Δ * A'
    dAA′ = [ΔA′[i,j] + conj(ΔA′[j,i]) for i in axes(ΔA′, 1), j in axes(ΔA′, 2)]
    return ForwardDiff.Dual{T}.(AA′, dAA′)

end

"""
    krr(ytest, trainData, kernel)

Predict latent parameters that generated `ytest` using kernel ridge regression.

# Arguments
- `ytest::Union{<:Real,<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}}`:
  Observed test data [Q,N] or \\[N\\] (if Q = 1) or scalar (if Q = N = 1)
- `trainData::TrainingData`: Training data
- `kernel::Kernel`: Kernel to use

## Notes
- Q is the number of observed features per test sample
- N is the number of test samples

# Return
- `xhat::Union{<:Real,<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}}`:
  Estimated latent parameters [L,N] or \\[N\\] (if L = 1) or \\[L\\] (if N = 1) or
  scalar (if L = N = 1)
"""
function krr(
    ytest::Union{<:Real,<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}},
    trainData::ExactTrainingData,
    kernel::ExactKernel
)

    k = kernel(trainData.y, ytest) # [T,N] or [T]
    k = k .- trainData.Km # [T,N] or [T]

    # Check if L = 1
    if trainData isa ExactTrainingData{<:Any,<:AbstractVector,<:Any,<:Any,<:Any,<:Any}
        xhat = trainData.xm .+ transpose(k) * trainData.xKinv # [N] or scalar
    else
        xhat = trainData.xm .+ trainData.xKinv * k # [L,N] or [L]
    end

    return xhat

end

function krr(
    ytest::Union{<:Real,<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}},
    trainData::RFFTrainingData,
    ::RFFKernel
)

    z = rffmap(ytest, trainData.freq, trainData.phase) # [H,N] or [H]
    z = z .- trainData.zm # [H,N] or [H]

    # Check if L = 1
    if trainData isa RFFTrainingData{<:Any,<:Any,<:Any,<:Any,<:Any,<:AbstractVector,<:Any}
        xhat = trainData.xm .+ transpose(z) * trainData.CxzCzzinv # [N] or scalar
    else
        xhat = trainData.xm .+ trainData.CxzCzzinv * z # [L,N] or [L]
    end

    return xhat

end


text:
import Mosek
import MosekTools

include("LPBenchmark.jl")

"""
    run_mosek

Run benchmark for Tulip.
"""
function run_mosek(fname::String)

    # Read file
    mosek = Mosek.Optimizer()
    load_problem!(mosek, fname)

    MOI.set(mosek, MOI.Silent(), false)
    MOI.set(mosek, MOI.TimeLimitSec(), 10_000)
    MOI.set(mosek, MOI.RawParameter("MSK_IPAR_NUM_THREADS"), 1)
    MOI.set(mosek, MOI.RawParameter("MSK_IPAR_INTPNT_BASIS"), 0)
    MOI.set(mosek, MOI.RawParameter("MSK_IPAR_OPTIMIZER"), 4)  # Use the interior-point

    # Solve instance
    run(mosek)

    return nothing
end

if abspath(PROGRAM_FILE) == @__FILE__
    run_mosek(ARGS[1])
end

max_stars_repo_name: mtanneau/LPBenchmarks

max_issues_repo_name: mtanneau/LPBenchmarks

max_forks_repo_name: mtanneau/LPBenchmarks


text:
# Example for basic 2D modeling:
# The receiver positions and the source wavelets are the same for each of the four experiments.
# Author: Philipp Witte, pwitte@eos.ubc.ca
# Date: January 2017
#

using LinearAlgebra, Random
using JUDI, SegyIO

# Set up model structure
n = (120, 100)   # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)

# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v0 = ones(Float32,n) .+ 0.4f0
v[:,Int(round(end/2)):end] .= 3f0

# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
dm = vec(m - m0)

# Setup model structure
nsrc = 2	# number of sources
model = Model(n, d, o, m)
model0 = Model(n, d, o, m0)

# Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)

# receiver sampling and recording time
timeR = 1000f0   # receiver recording time [ms]
dtR = 4f0    # receiver sampling interval [ms]

# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR, nsrc=nsrc)

# Set up source geometry (cell array with source locations for each shot)
xsrc = convertToCell([400f0, 800f0])
ysrc = convertToCell([0f0, 0f0])
zsrc = convertToCell([20f0, 20f0])

# source sampling and number of time steps
timeS = 1000f0  # ms
dtS = 4f0   # ms

# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)

# setup wavelet
f0 = 0.01f0     # kHz
wavelet = ricker_wavelet(timeS, dtS, f0)
q = judiVector(srcGeometry, wavelet)
###################################################################################################

# Write shots as segy files to disk
opt = Options()

# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model; options=opt)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(srcGeometry)
J = judiJacobian(Pr*F0*adjoint(Ps), q)

# Nonlinear modeling
dobs = Pr*F*adjoint(Ps)*q
qad = Ps*adjoint(F)*adjoint(Pr)*dobs

# Return wavefields
u = F*adjoint(Ps)*q
v = adjoint(F)*adjoint(Pr)*dobs

# Modify wavefields
v = abs(v)  # take absolute value
u = 2*u # multiple by scalar

# Wavefields as source
dnew = Pr*F*v
qnew = Ps*adjoint(F)*u

# Create custom wavefield as source (needs to be on computational time axis and contain padding)
dtComp = get_dt(model)
ntComp = get_computational_nt(q.geometry, model)
u0 = zeros(Float32, ntComp[1], model.n[1] + 2*model.nb, model.n[2] + 2*model.nb)
u0[:, 100, 45] = wavelet = -ricker_wavelet(timeS, dtComp, f0)
uf = judiWavefield(dtComp, u0)
dobs2 = Pr*F*uf # same as dobs

# Wavefields as source + return wavefields
u2 = F*u
v2 = F*v

# Supported algebraic operations
u_add = u + u
u_sub = u - v
u_mult = u * 2f0
u_div = u / 2f0
u_norm = norm(u)
u_dot = dot(u, u)
u_abs = abs(u)