text:
module GtkSourceWidget

using Gtk, GtkSourceView_jll

export GtkSourceLanguage, GtkSourceLanguageManager, GtkSourceBuffer,
       GtkSourceView, GtkSourceCompletionItem,
       GtkSourceStyleSchemeManager, GtkSourceStyleScheme, GtkSourceMap,
       GtkSourceSearchContext, GtkSourceSearchSettings

export scheme, language, show_line_numbers!, auto_indent!, style_scheme, style_scheme!,
       max_undo_levels, max_undo_levels!, undo!, redo!, canundo, canredo, undomanager,
       highlight_current_line!, highlight_matching_brackets, source_view_get_gutter,
       reset_undomanager, set_view, get_view, style_scheme_chooser, style_scheme_chooser_button,
       set_search_text, get_search_text, search_context_forward, highlight, search_context_replace

import ..Gtk: suffix, GObject, GtkTextIter, Mutable

mutable(it::GtkTextIter) = Gtk.GLib.MutableTypes.mutable(it)

### GtkSourceLanguage

Gtk.@Gtype GtkSourceLanguage libgtksourceview gtk_source_language

### GtkSourceLanguageManager

Gtk.@Gtype GtkSourceLanguageManager libgtksourceview gtk_source_language_manager
function GtkSourceLanguageManagerLeaf(default=true)
  if default
    GtkSourceLanguageManagerLeaf(
      ccall((:gtk_source_language_manager_get_default, libgtksourceview), Ptr{GObject}, ()))
  else
    GtkSourceLanguageManagerLeaf(
      ccall((:gtk_source_language_manager_new, libgtksourceview), Ptr{GObject}, ()))
  end
end

get_search_path(manager::GtkSourceLanguageManager) = ccall(
    (:gtk_source_language_manager_get_search_path, libgtksourceview), Ptr{Ptr{UInt8}},
    (Ptr{GObject}, ), manager
)

"""
    set_search_path(manager::GtkSourceLanguageManager, dir)

Implements `gtk_source_language_manager_set_search_path`.

Example :
    `GtkSourceWidget.set_search_path(sourceStyleManager, Any[path, C_NULL])`
"""
set_search_path(manager::GtkSourceLanguageManager, dir)  = ccall(
    (:gtk_source_language_manager_set_search_path, libgtksourceview), Nothing,
    (Ptr{GObject}, Ptr{Ptr{UInt8}}), manager, dir
)

"""
    language(manager::GtkSourceLanguageManager, id::String)

Implements `gtk_source_language_manager_get_language`.
"""
language(manager::GtkSourceLanguageManager, id::String) = GtkSourceLanguage(
    ccall((:gtk_source_language_manager_get_language, libgtksourceview), Ptr{GObject},
          (Ptr{GObject}, Ptr{UInt8}), manager, string(id)))

### GtkSourceStyle

Gtk.@Gtype GtkSourceStyle libgtksourceview gtk_source_style

### GtkSourceStyleScheme

Gtk.@Gtype GtkSourceStyleScheme libgtksourceview gtk_source_style_scheme

"""
    style(scheme::GtkSourceStyleScheme, style_id::String)

Implements `gtk_source_style_scheme_get_style`.
"""
style(scheme::GtkSourceStyleScheme, style_id::String)  = GtkSourceStyle(
    ccall((:gtk_source_style_scheme_get_style, libgtksourceview), Ptr{GObject},
    (Ptr{GObject}, Ptr{UInt8}), scheme, string(style_id)))

### GtkSourceStyleSchemeManager

Gtk.@Gtype GtkSourceStyleSchemeManager libgtksourceview gtk_source_style_scheme_manager
function GtkSourceStyleSchemeManagerLeaf(default=true)
  if default
    GtkSourceStyleSchemeManagerLeaf(
      ccall((:gtk_source_style_scheme_manager_get_default, libgtksourceview), Ptr{GObject}, ()))
  else
    GtkSourceStyleSchemeManagerLeaf(
      ccall((:gtk_source_style_scheme_manager_get_new, libgtksourceview), Ptr{GObject}, ()))
  end
end

"""
    style_scheme(manager::GtkSourceStyleSchemeManager, scheme_id::String)

Implements `gtk_source_style_scheme_manager_get_scheme`.
"""
style_scheme(manager::GtkSourceStyleSchemeManager, scheme_id::String) = GtkSourceStyleScheme(
    ccall((:gtk_source_style_scheme_manager_get_scheme, libgtksourceview), Ptr{GObject},
          (Ptr{GObject}, Ptr{UInt8}), manager, string(scheme_id)))

"""
    set_search_path(manager::GtkSourceStyleSchemeManager, dir)

Implements `gtk_source_style_scheme_manager_set_search_path`.
"""
set_search_path(manager::GtkSourceStyleSchemeManager, dir)  = ccall(
    (:gtk_source_style_scheme_manager_set_search_path, libgtksourceview), Nothing,
    (Ptr{GObject}, Ptr{Ptr{UInt8}}), manager, dir
)

### GtkSourceUndoManager

### This is a hack!!!
struct GtkSourceUndoManagerI end

undo!(manager::GtkSourceUndoManagerI) =
  ccall((:gtk_source_undo_manager_undo, libgtksourceview), Nothing,
        (Ptr{Nothing}, ), manager.handle)

redo!(manager::GtkSourceUndoManagerI) =
  ccall((:gtk_source_undo_manager_redo, libgtksourceview), Nothing,
        (Ptr{Nothing}, ), manager.handle)

canundo(manager::GtkSourceUndoManagerI) = Bool(
  ccall((:gtk_source_undo_manager_can_undo, libgtksourceview), Cint,
        (Ptr{Nothing}, ), manager.handle))

canredo(manager::GtkSourceUndoManagerI) = Bool(
  ccall((:gtk_source_undo_manager_can_redo, libgtksourceview), Cint,
        (Ptr{Nothing}, ), manager.handle))

### GtkSourceBuffer

Gtk.@Gtype GtkSourceBuffer libgtksourceview gtk_source_buffer
GtkSourceBufferLeaf() = GtkSourceBufferLeaf(
     ccall((:gtk_source_buffer_new, libgtksourceview), Ptr{GObject}, (Ptr{Nothing}, ), C_NULL) )

"""
    GtkSourceBuffer(lang::GtkSourceLanguage)

Implements `gtk_source_buffer_new_with_language`.
"""
GtkSourceBufferLeaf(lang::GtkSourceLanguage) = GtkSourceBufferLeaf(
     ccall((:gtk_source_buffer_new_with_language, libgtksourceview), Ptr{GObject},
           (Ptr{GObject}, ), lang) )

"""
    highlight_syntax(buffer::GtkSourceBuffer, highlight::Bool)

Implements `gtk_source_buffer_set_highlight_syntax`.
"""
highlight_syntax(buffer::GtkSourceBuffer, highlight::Bool) =
  ccall((:gtk_source_buffer_set_highlight_syntax, libgtksourceview), Ptr{GObject},
        (Ptr{GObject}, Cint), buffer, Int32(highlight))

"""
    highlight_matching_brackets(buffer::GtkSourceBuffer, highlight::Bool)

Implements `gtk_source_buffer_set_highlight_matching_brackets`.
"""
highlight_matching_brackets(buffer::GtkSourceBuffer, highlight::Bool) =
  ccall((:gtk_source_buffer_set_highlight_matching_brackets, libgtksourceview), Ptr{GObject},
        (Ptr{GObject}, Cint), buffer, Int32(highlight))

"""
    style_scheme!(buffer::GtkSourceBuffer, scheme::GtkSourceStyleScheme)

Implements `gtk_source_buffer_set_style_scheme`.
"""
style_scheme!(buffer::GtkSourceBuffer, scheme::GtkSourceStyleScheme) =
  ccall((:gtk_source_buffer_set_style_scheme, libgtksourceview), Nothing,
        (Ptr{GObject}, Ptr{GObject}), buffer, scheme)

max_undo_levels(buffer::GtkSourceBuffer) =
  ccall((:gtk_source_buffer_get_max_undo_levels, libgtksourceview), Cint,
        (Ptr{GObject}, ), buffer)

max_undo_levels!(buffer::GtkSourceBuffer, levels::Integer) =
  ccall((:gtk_source_buffer_set_max_undo_levels, libgtksourceview), Nothing,
        (Ptr{GObject}, Cint), buffer, levels)

"""
    undo!(buffer::GtkSourceBuffer)

Implements `gtk_source_buffer_undo`.
"""
undo!(buffer::GtkSourceBuffer) =
  ccall((:gtk_source_buffer_undo, libgtksourceview), Nothing,
        (Ptr{GObject}, ), buffer)

"""
    redo!(buffer::GtkSourceBuffer)

Implements `gtk_source_buffer_redo`.
"""
redo!(buffer::GtkSourceBuffer) =
  ccall((:gtk_source_buffer_redo, libgtksourceview), Nothing,
        (Ptr{GObject}, ), buffer)

canundo(buffer::GtkSourceBuffer) = Bool(
  ccall((:gtk_source_buffer_can_undo, libgtksourceview), Cint,
        (Ptr{GObject}, ), buffer))

canredo(buffer::GtkSourceBuffer) = Bool(
  ccall((:gtk_source_buffer_can_redo, libgtksourceview), Cint,
        (Ptr{GObject}, ), buffer))

undomanager(buffer::GtkSourceBuffer) = GtkSourceUndoManagerI(
  ccall((:gtk_source_buffer_get_undo_manager, libgtksourceview), Ptr{Nothing},
        (Ptr{GObject}, ), buffer))

reset_undomanager(buffer::GtkSourceBuffer) = ccall(
    (:gtk_source_buffer_set_undo_manager, libgtksourceview), Nothing,
    (Ptr{GObject}, Ptr{GObject}), buffer, C_NULL
)

### GtkSourceView

Gtk.@Gtype GtkSourceView libgtksourceview gtk_source_view
GtkSourceViewLeaf(buffer=GtkSourceBuffer()) = GtkSourceView(
    ccall((:gtk_source_view_new_with_buffer, libgtksourceview), Ptr{GObject}, (Ptr{GObject}, ), buffer))

"""
    show_line_numbers!(view::GtkSourceView, show::Bool)

Implements `gtk_source_view_set_show_line_numbers`.
"""
show_line_numbers!(view::GtkSourceView, show::Bool) =
  ccall((:gtk_source_view_set_show_line_numbers, libgtksourceview), Nothing,
        (Ptr{GObject}, Cint), view, Int32(show))

auto_indent!(view::GtkSourceView, auto::Bool) =
  ccall((:gtk_source_view_set_auto_indent, libgtksourceview), Nothing,
        (Ptr{GObject}, Cint), view, Int32(auto))

"""
    highlight_current_line!(view::GtkSourceView, hl::Bool)

Implements `gtk_source_view_set_highlight_current_line`.
"""
highlight_current_line!(view::GtkSourceView, hl::Bool) =
  ccall((:gtk_source_view_set_highlight_current_line, libgtksourceview), Nothing,
        (Ptr{GObject}, Cint), view, Int32(hl))

### GtkSourceCompletion

Gtk.@Gtype GtkSourceCompletion libgtksourceview gtk_source_completion

get_completion(view::GtkSourceView) =
    ccall((:gtk_source_view_get_completion, libgtksourceview), Ptr{GtkSourceCompletion},
        (Ptr{GObject}, ), view)

# Gtk.create_mark(buffer::GtkSourceBuffer, mark_name, it, left_gravity::Bool)  =
#     GtkTextMarkLeaf(ccall((:gtk_text_buffer_create_mark, Gtk.libgtk), Ptr{GObject},
#     (Ptr{Gtk.GObject}, Ptr{UInt8}, Ref{GtkTextIter}, Cint), buffer, mark_name, it, left_gravity))

# Gtk.create_mark(buffer::GtkTextBuffer, it)  = create_mark(buffer, C_NULL, it, false)

### GtkSourceCompletionContext

baremodule GtkSourceCompletionActivation
    const GTK_SOURCE_COMPLETION_ACTIVATION_NONE = 0
    const GTK_SOURCE_COMPLETION_ACTIVATION_INTERACTIVE = 1
    const GTK_SOURCE_COMPLETION_ACTIVATION_USER_REQUESTED = 2
end

Gtk.@Gtype GtkSourceCompletionContext libgtksourceview gtk_source_completion_context

#function add_proposals(context::GtkSourceCompletionContext, provider::GtkSourceCompletionProvider,
#                       proposals::GList, finished::Bool)
#  ccall((:gtk_source_completion_context_add_proposals, libgtksourceview), Nothing,
#        (Ptr{GObject}, Ptr{GObject}, Ptr{GList}, Cint), context, provider, &proposals, finished)
#end

#getiter(context::GtkSourceCompletionContext, iter::GtkTextIter) =
#   ccall((:gtk_source_completion_context_get_iter, libgtksourceview), Nothing,
#        (Ptr{GObject}, Ptr{Nothing}), context, iter)

getactivation(context::GtkSourceCompletionContext) =
   ccall((:gtk_source_completion_context_get_activation, libgtksourceview), Cint,
        (Ptr{GObject}, ), context)

### GtkSourceCompletionItem

Gtk.@Gtype GtkSourceCompletionItem libgtksourceview gtk_source_completion_item

GtkSourceCompletionItemLeaf(label::String, text::String) = GtkSourceCompletionItemLeaf(
    ccall((:gtk_source_completion_item_new, libgtksourceview), Ptr{GObject},
        (Ptr{UInt8}, Ptr{UInt8}, Ptr{Nothing}, Ptr{UInt8}),
        string(label), string(text), C_NULL, C_NULL))

### GtkSourceCompletionProvider

Gtk.GLib.@Giface GtkSourceCompletionProvider libgtksourceview gtk_source_completion_provider

## GtkSourceSearchSettings

Gtk.@Gtype GtkSourceSearchSettings libgtksourceview gtk_source_search_settings

GtkSourceSearchSettingsLeaf() = GtkSourceSearchSettingsLeaf(
    ccall((:gtk_source_search_settings_new, libgtksourceview), Ptr{GObject}, ())
)

set_search_text(settings::GtkSourceSearchSettings, text::String) =
    ccall((:gtk_source_search_settings_set_search_text, libgtksourceview), Nothing,
        (Ptr{GObject}, Ptr{UInt8}), settings, text)

function get_search_text(settings::GtkSourceSearchSettings)

    s = ccall((:gtk_source_search_settings_get_search_text, libgtksourceview), Ptr{UInt8},
    (Ptr{GObject}, ), settings)

    return s == C_NULL ? "" : string(s)
end

## GtkSourceSearchContext

Gtk.@Gtype GtkSourceSearchContext libgtksourceview gtk_source_search_context

GtkSourceSearchContextLeaf(buffer::GtkSourceBuffer, settings::GtkSourceSearchSettings) =
    GtkSourceSearchContextLeaf(
        ccall((:gtk_source_search_context_new, libgtksourceview), Ptr{GObject}, (Ptr{GObject}, Ptr{GObject}),
        buffer, settings)
    )

function search_context_forward(search::GtkSourceSearchContext, iter::GtkTextIter,
                                match_start::Mutable{GtkTextIter}, match_end::Mutable{GtkTextIter})

    Bool(ccall((:gtk_source_search_context_forward, libgtksourceview),
        Cint,
        (Ptr{GObject}, Ref{GtkTextIter}, Ptr{GtkTextIter}, Ptr{GtkTextIter}),
        search, iter, match_start, match_end
    ))
end

function search_context_forward(search::GtkSourceSearchContext, iter::GtkTextIter)

    buffer = search.buffer[GtkSourceBuffer]
    match_start = mutable(GtkTextIter(buffer))
    match_end   = mutable(GtkTextIter(buffer))

    found = search_context_forward(search, iter, match_start, match_end)
    return (found, match_start, match_end)
end

function search_context_replace(
    search::GtkSourceSearchContext,
    match_start::Mutable{GtkTextIter}, match_end::Mutable{GtkTextIter},
    replace::String)

    out = ccall((:gtk_source_search_context_replace, libgtksourceview), Cint,
        (Ptr{GObject}, Ref{GtkTextIter}, Ref{GtkTextIter}, Ptr{UInt8}, Cint, Ptr{Nothing}),
        search, match_start, match_end, string(replace), -1, C_NULL)

    return convert(Bool, out)
end

search_context_replace(
    search::GtkSourceSearchContext,
    match_start::GtkTextIter, match_end::GtkTextIter,
    replace::String) = search_context_replace(search, mutable(match_start), mutable(match_end), replace)

function search_context_replace_all(search::GtkSourceSearchContext, replace::String)

    out = ccall((:gtk_source_search_context_replace_all, libgtksourceview), Cint,
        (Ptr{GObject}, Ptr{UInt8}, Cint, Ptr{Nothing}),
        search, string(replace), -1, C_NULL)

    return out
end

highlight(search::GtkSourceSearchContext, highlight::Bool) =
    ccall((:gtk_source_search_context_set_highlight, libgtksourceview), Nothing,
        (Ptr{GObject}, Cint), search, highlight)

### GtkSourceGutter

source_view_get_gutter(view::GtkSourceView) =  ccall(
    (:gtk_source_view_get_gutter, libgtksourceview), Ptr{Nothing}, (Ptr{GObject}, Cint),
     view, Int32(1)
)

### GtkSourceMap

Gtk.@Gtype GtkSourceMap libgtksourceview gtk_source_map

GtkSourceMapLeaf() = GtkSourceMapLeaf( ccall((:gtk_source_map_new, libgtksourceview), Ptr{GObject}, ()) )

get_view(map::GtkSourceMap) =
    ccall((:gtk_source_map_get_view, libgtksourceview), Ptr{GtkSourceView},
        (Ptr{GObject}, ), map)

set_view(map::GtkSourceMap, view::GtkSourceView) =
    ccall((:gtk_source_map_set_view, libgtksourceview), Nothing,
        (Ptr{GObject}, Ptr{GObject}), map, view)

## GtkSourceStyleSchemeChooserWidget

style_scheme_chooser() = Gtk.GtkWidgetLeaf(
    ccall((:gtk_source_style_scheme_chooser_widget_new, libgtksourceview), Ptr{GObject}, ())
)
style_scheme_chooser_button() = Gtk.GtkWidgetLeaf(
    ccall((:gtk_source_style_scheme_chooser_button_new, libgtksourceview), Ptr{GObject}, ())
)
style_scheme(chooser::Gtk.GtkWidget) = GtkSourceStyleScheme(
    ccall((:gtk_source_style_scheme_chooser_get_style_scheme, libgtksourceview), Ptr{GObject},
    (Ptr{GObject}, ), chooser)
)

#? https://github.com/JuliaLang/Gtk.jl/blob/40f7442dea20919c5a7b137594fb6d7636fa2329/src/selectors.jl

function __init__()
    global sourceLanguageManager = GtkSourceLanguageManager()
    GtkSourceWidget.set_search_path(sourceLanguageManager,
      Any[joinpath(GtkSourceView_jll.artifact_dir, "share", "gtksourceview-4", "language-specs"), C_NULL])
end

end # module


text:
using Printf

@testset "Hermite 1D" begin

    for nx in 5:5:35

        ϵ, γ = 0.1, 3.0
        xmin, xmax = -1, 1

        interp = Hermite(Chebyshev(xmin, xmax, nx), 0.1, 3.0)

        xk = interp.nodes
        fk = cos.(xk.^2)

	nxe = 128
        xe  = collect(range(xmin, stop=xmax, length=nxe))
        dx  = xe[2]-xe[1]
        fe  = cos.(xe.^2)

        s   = interpolate( interp, fk, xe )

        l2_error = sqrt(trapz((s - fe).^2, dx))
        l1_error = maximum(abs.(s .- fe))
	@printf( "%02d points - L2 : %.3e - L∞ : %.3e \n",
	        nx, l2_error, l1_error )

	@test l2_error < max(1.0e-14, 10.0^(-nx÷2+1))
    end

end

@testset "Radial 1D" begin

    for nx in 5:5:35

        ϵ, γ = 0.1, 3.0
        xmin, xmax = -1, 1

        interp = Radial(Chebyshev(xmin, xmax, nx), 0.1)

        xk = interp.nodes
        fk = cos.(xk.^2)

	nxe = 128
        xe  = collect(range(xmin, stop=xmax, length=nxe))
        dx  = xe[2]-xe[1]
        fe  = cos.(xe.^2)

        @time s   = interpolate( interp, fk, xe )

        l2_error = sqrt(trapz((s - fe).^2, dx))
        l1_error = maximum(abs.(s .- fe))
	@printf( "%02d points - L2 : %.3e - L∞ : %.3e \n",
	        nx, l2_error, l1_error )

	@test true
    end

end

ext: jl


text:
"""
`to_array(ss::AbstractArray{<:AbstractArray{<:Any, N}}, I::Vararg{<:AbstractArray, N}) where N`

Collect a `AbstractArray` of `AbstractArrays` into a normal `Array` selecting indices `I` (can take negative values if inner `AbstractArrays` allow it).
The output `Array` first few dimensions will be indexed by `I` (though starting from `1`)
and the last one will correspond to the index of the inner `AbstractArray` within the `AbstractArray` of `AbstractArrays`.
"""
function to_array(ss::AbstractArray{<:AbstractArray{<:Any, N}}, I::Vararg{<:AbstractArray, N}) where N
    v = VectorOfArray([view(s, I...) for s in ss])
    Array(v)
end

"""
`to_offsetarray(ss::AbstractArray{<:AbstractArray{<:Any, N}}, I::Vararg{<:AbstractArray, N}) where N`

Collect a `AbstractArray` of `ShiftedArrays` into an `OffsetArray` selecting indices `I` (can take negative values if inner `AbstractArrays` allow it).
The output `OffsetArray` first few dimensions will be indexed by `I`
and the last one will correspond to the index of the inner `AbstractArray` within the `AbstractArray` of `AbstractArrays`.
"""
function to_offsetarray(ss::AbstractArray{<:AbstractArray{<:Any, N}}, I::Vararg{<:AbstractArray, N}) where N
    m = to_array(ss, I...)
    OffsetArray(m, I..., last(axes(m)))
end


text:
# Julia wrapper for header: Vulkan-Docs/src/vulkan/vk_platform.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

# Julia wrapper for header: Vulkan-Docs/src/vulkan/vulkan.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function vkCreateInstance(pCreateInfo,pAllocator,pInstance)
    ccall((:vkCreateInstance,libvulkan),VkResult,(Ptr{VkInstanceCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkInstance}),pCreateInfo,pAllocator,pInstance)
end

function vkDestroyInstance(instance,pAllocator)
    ccall((:vkDestroyInstance,libvulkan),Void,(VkInstance,Ptr{VkAllocationCallbacks}),instance,pAllocator)
end

function vkEnumeratePhysicalDevices(instance,pPhysicalDeviceCount,pPhysicalDevices)
    ccall((:vkEnumeratePhysicalDevices,libvulkan),VkResult,(VkInstance,Ptr{UInt32},Ptr{VkPhysicalDevice}),instance,pPhysicalDeviceCount,pPhysicalDevices)
end

function vkGetPhysicalDeviceFeatures(physicalDevice,pFeatures)
    ccall((:vkGetPhysicalDeviceFeatures,libvulkan),Void,(VkPhysicalDevice,Ptr{VkPhysicalDeviceFeatures}),physicalDevice,pFeatures)
end

function vkGetPhysicalDeviceFormatProperties(physicalDevice,format,pFormatProperties)
    ccall((:vkGetPhysicalDeviceFormatProperties,libvulkan),Void,(VkPhysicalDevice,VkFormat,Ptr{VkFormatProperties}),physicalDevice,format,pFormatProperties)
end

function vkGetPhysicalDeviceImageFormatProperties(physicalDevice,format,_type,tiling,usage,flags,pImageFormatProperties)
    ccall((:vkGetPhysicalDeviceImageFormatProperties,libvulkan),VkResult,(VkPhysicalDevice,VkFormat,VkImageType,VkImageTiling,VkImageUsageFlags,VkImageCreateFlags,Ptr{VkImageFormatProperties}),physicalDevice,format,_type,tiling,usage,flags,pImageFormatProperties)
end

function vkGetPhysicalDeviceProperties(physicalDevice,pProperties)
    ccall((:vkGetPhysicalDeviceProperties,libvulkan),Void,(VkPhysicalDevice,Ptr{VkPhysicalDeviceProperties}),physicalDevice,pProperties)
end

function vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice,pQueueFamilyPropertyCount,pQueueFamilyProperties)
    ccall((:vkGetPhysicalDeviceQueueFamilyProperties,libvulkan),Void,(VkPhysicalDevice,Ptr{UInt32},Ptr{VkQueueFamilyProperties}),physicalDevice,pQueueFamilyPropertyCount,pQueueFamilyProperties)
end

function vkGetPhysicalDeviceMemoryProperties(physicalDevice,pMemoryProperties)
    ccall((:vkGetPhysicalDeviceMemoryProperties,libvulkan),Void,(VkPhysicalDevice,Ptr{VkPhysicalDeviceMemoryProperties}),physicalDevice,pMemoryProperties)
end

function vkGetInstanceProcAddr(instance,pName)
    ccall((:vkGetInstanceProcAddr,libvulkan),PFN_vkVoidFunction,(VkInstance,Cstring),instance,pName)
end

function vkGetDeviceProcAddr(device,pName)
    ccall((:vkGetDeviceProcAddr,libvulkan),PFN_vkVoidFunction,(VkDevice,Cstring),device,pName)
end

function vkCreateDevice(physicalDevice,pCreateInfo,pAllocator,pDevice)
    ccall((:vkCreateDevice,libvulkan),VkResult,(VkPhysicalDevice,Ptr{VkDeviceCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkDevice}),physicalDevice,pCreateInfo,pAllocator,pDevice)
end

function vkDestroyDevice(device,pAllocator)
    ccall((:vkDestroyDevice,libvulkan),Void,(VkDevice,Ptr{VkAllocationCallbacks}),device,pAllocator)
end

function vkEnumerateInstanceExtensionProperties(pLayerName,pPropertyCount,pProperties)
    ccall((:vkEnumerateInstanceExtensionProperties,libvulkan),VkResult,(Cstring,Ptr{UInt32},Ptr{VkExtensionProperties}),pLayerName,pPropertyCount,pProperties)
end

function vkEnumerateDeviceExtensionProperties(physicalDevice,pLayerName,pPropertyCount,pProperties)
    ccall((:vkEnumerateDeviceExtensionProperties,libvulkan),VkResult,(VkPhysicalDevice,Cstring,Ptr{UInt32},Ptr{VkExtensionProperties}),physicalDevice,pLayerName,pPropertyCount,pProperties)
end

function vkEnumerateInstanceLayerProperties(pPropertyCount,pProperties)
    ccall((:vkEnumerateInstanceLayerProperties,libvulkan),VkResult,(Ptr{UInt32},Ptr{VkLayerProperties}),pPropertyCount,pProperties)
end

function vkEnumerateDeviceLayerProperties(physicalDevice,pPropertyCount,pProperties)
    ccall((:vkEnumerateDeviceLayerProperties,libvulkan),VkResult,(VkPhysicalDevice,Ptr{UInt32},Ptr{VkLayerProperties}),physicalDevice,pPropertyCount,pProperties)
end

function vkGetDeviceQueue(device,queueFamilyIndex,queueIndex,pQueue)
    ccall((:vkGetDeviceQueue,libvulkan),Void,(VkDevice,UInt32,UInt32,Ptr{VkQueue}),device,queueFamilyIndex,queueIndex,pQueue)
end

function vkQueueSubmit(queue,submitCount,pSubmits,fence)
    ccall((:vkQueueSubmit,libvulkan),VkResult,(VkQueue,UInt32,Ptr{VkSubmitInfo},VkFence),queue,submitCount,pSubmits,fence)
end

function vkQueueWaitIdle(queue)
    ccall((:vkQueueWaitIdle,libvulkan),VkResult,(VkQueue,),queue)
end

function vkDeviceWaitIdle(device)
    ccall((:vkDeviceWaitIdle,libvulkan),VkResult,(VkDevice,),device)
end

function vkAllocateMemory(device,pAllocateInfo,pAllocator,pMemory)
    ccall((:vkAllocateMemory,libvulkan),VkResult,(VkDevice,Ptr{VkMemoryAllocateInfo},Ptr{VkAllocationCallbacks},Ptr{VkDeviceMemory}),device,pAllocateInfo,pAllocator,pMemory)
end

function vkFreeMemory(device,memory,pAllocator)
    ccall((:vkFreeMemory,libvulkan),Void,(VkDevice,VkDeviceMemory,Ptr{VkAllocationCallbacks}),device,memory,pAllocator)
end

function vkMapMemory(device,memory,offset,size,flags,ppData)
    ccall((:vkMapMemory,libvulkan),VkResult,(VkDevice,VkDeviceMemory,VkDeviceSize,VkDeviceSize,VkMemoryMapFlags,Ptr{Ptr{Void}}),device,memory,offset,size,flags,ppData)
end

function vkUnmapMemory(device,memory)
    ccall((:vkUnmapMemory,libvulkan),Void,(VkDevice,VkDeviceMemory),device,memory)
end

function vkFlushMappedMemoryRanges(device,memoryRangeCount,pMemoryRanges)
    ccall((:vkFlushMappedMemoryRanges,libvulkan),VkResult,(VkDevice,UInt32,Ptr{VkMappedMemoryRange}),device,memoryRangeCount,pMemoryRanges)
end

function vkInvalidateMappedMemoryRanges(device,memoryRangeCount,pMemoryRanges)
    ccall((:vkInvalidateMappedMemoryRanges,libvulkan),VkResult,(VkDevice,UInt32,Ptr{VkMappedMemoryRange}),device,memoryRangeCount,pMemoryRanges)
end

function vkGetDeviceMemoryCommitment(device,memory,pCommittedMemoryInBytes)
    ccall((:vkGetDeviceMemoryCommitment,libvulkan),Void,(VkDevice,VkDeviceMemory,Ptr{VkDeviceSize}),device,memory,pCommittedMemoryInBytes)
end

function vkBindBufferMemory(device,buffer,memory,memoryOffset)
    ccall((:vkBindBufferMemory,libvulkan),VkResult,(VkDevice,VkBuffer,VkDeviceMemory,VkDeviceSize),device,buffer,memory,memoryOffset)
end

function vkBindImageMemory(device,image,memory,memoryOffset)
    ccall((:vkBindImageMemory,libvulkan),VkResult,(VkDevice,VkImage,VkDeviceMemory,VkDeviceSize),device,image,memory,memoryOffset)
end

function vkGetBufferMemoryRequirements(device,buffer,pMemoryRequirements)
    ccall((:vkGetBufferMemoryRequirements,libvulkan),Void,(VkDevice,VkBuffer,Ptr{VkMemoryRequirements}),device,buffer,pMemoryRequirements)
end

function vkGetImageMemoryRequirements(device,image,pMemoryRequirements)
    ccall((:vkGetImageMemoryRequirements,libvulkan),Void,(VkDevice,VkImage,Ptr{VkMemoryRequirements}),device,image,pMemoryRequirements)
end

function vkGetImageSparseMemoryRequirements(device,image,pSparseMemoryRequirementCount,pSparseMemoryRequirements)
    ccall((:vkGetImageSparseMemoryRequirements,libvulkan),Void,(VkDevice,VkImage,Ptr{UInt32},Ptr{VkSparseImageMemoryRequirements}),device,image,pSparseMemoryRequirementCount,pSparseMemoryRequirements)
end

function vkGetPhysicalDeviceSparseImageFormatProperties(physicalDevice,format,_type,samples,usage,tiling,pPropertyCount,pProperties)
    ccall((:vkGetPhysicalDeviceSparseImageFormatProperties,libvulkan),Void,(VkPhysicalDevice,VkFormat,VkImageType,VkSampleCountFlagBits,VkImageUsageFlags,VkImageTiling,Ptr{UInt32},Ptr{VkSparseImageFormatProperties}),physicalDevice,format,_type,samples,usage,tiling,pPropertyCount,pProperties)
end

function vkQueueBindSparse(queue,bindInfoCount,pBindInfo,fence)
    ccall((:vkQueueBindSparse,libvulkan),VkResult,(VkQueue,UInt32,Ptr{VkBindSparseInfo},VkFence),queue,bindInfoCount,pBindInfo,fence)
end

function vkCreateFence(device,pCreateInfo,pAllocator,pFence)
    ccall((:vkCreateFence,libvulkan),VkResult,(VkDevice,Ptr{VkFenceCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkFence}),device,pCreateInfo,pAllocator,pFence)
end

function vkDestroyFence(device,fence,pAllocator)
    ccall((:vkDestroyFence,libvulkan),Void,(VkDevice,VkFence,Ptr{VkAllocationCallbacks}),device,fence,pAllocator)
end

function vkResetFences(device,fenceCount,pFences)
    ccall((:vkResetFences,libvulkan),VkResult,(VkDevice,UInt32,Ptr{VkFence}),device,fenceCount,pFences)
end

function vkGetFenceStatus(device,fence)
    ccall((:vkGetFenceStatus,libvulkan),VkResult,(VkDevice,VkFence),device,fence)
end

function vkWaitForFences(device,fenceCount,pFences,waitAll,timeout)
    ccall((:vkWaitForFences,libvulkan),VkResult,(VkDevice,UInt32,Ptr{VkFence},VkBool32,UInt64),device,fenceCount,pFences,waitAll,timeout)
end

function vkCreateSemaphore(device,pCreateInfo,pAllocator,pSemaphore)
    ccall((:vkCreateSemaphore,libvulkan),VkResult,(VkDevice,Ptr{VkSemaphoreCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkSemaphore}),device,pCreateInfo,pAllocator,pSemaphore)
end

function vkDestroySemaphore(device,semaphore,pAllocator)
    ccall((:vkDestroySemaphore,libvulkan),Void,(VkDevice,VkSemaphore,Ptr{VkAllocationCallbacks}),device,semaphore,pAllocator)
end

function vkCreateEvent(device,pCreateInfo,pAllocator,pEvent)
    ccall((:vkCreateEvent,libvulkan),VkResult,(VkDevice,Ptr{VkEventCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkEvent}),device,pCreateInfo,pAllocator,pEvent)
end

function vkDestroyEvent(device,event,pAllocator)
    ccall((:vkDestroyEvent,libvulkan),Void,(VkDevice,VkEvent,Ptr{VkAllocationCallbacks}),device,event,pAllocator)
end

function vkGetEventStatus(device,event)
    ccall((:vkGetEventStatus,libvulkan),VkResult,(VkDevice,VkEvent),device,event)
end

function vkSetEvent(device,event)
    ccall((:vkSetEvent,libvulkan),VkResult,(VkDevice,VkEvent),device,event)
end

function vkResetEvent(device,event)
    ccall((:vkResetEvent,libvulkan),VkResult,(VkDevice,VkEvent),device,event)
end

function vkCreateQueryPool(device,pCreateInfo,pAllocator,pQueryPool)
    ccall((:vkCreateQueryPool,libvulkan),VkResult,(VkDevice,Ptr{VkQueryPoolCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkQueryPool}),device,pCreateInfo,pAllocator,pQueryPool)
end

function vkDestroyQueryPool(device,queryPool,pAllocator)
    ccall((:vkDestroyQueryPool,libvulkan),Void,(VkDevice,VkQueryPool,Ptr{VkAllocationCallbacks}),device,queryPool,pAllocator)
end

function vkGetQueryPoolResults(device,queryPool,firstQuery,queryCount,dataSize,pData,stride,flags)
    ccall((:vkGetQueryPoolResults,libvulkan),VkResult,(VkDevice,VkQueryPool,UInt32,UInt32,Csize_t,Ptr{Void},VkDeviceSize,VkQueryResultFlags),device,queryPool,firstQuery,queryCount,dataSize,pData,stride,flags)
end

function vkCreateBuffer(device,pCreateInfo,pAllocator,pBuffer)
    ccall((:vkCreateBuffer,libvulkan),VkResult,(VkDevice,Ptr{VkBufferCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkBuffer}),device,pCreateInfo,pAllocator,pBuffer)
end

function vkDestroyBuffer(device,buffer,pAllocator)
    ccall((:vkDestroyBuffer,libvulkan),Void,(VkDevice,VkBuffer,Ptr{VkAllocationCallbacks}),device,buffer,pAllocator)
end

function vkCreateBufferView(device,pCreateInfo,pAllocator,pView)
    ccall((:vkCreateBufferView,libvulkan),VkResult,(VkDevice,Ptr{VkBufferViewCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkBufferView}),device,pCreateInfo,pAllocator,pView)
end

function vkDestroyBufferView(device,bufferView,pAllocator)
    ccall((:vkDestroyBufferView,libvulkan),Void,(VkDevice,VkBufferView,Ptr{VkAllocationCallbacks}),device,bufferView,pAllocator)
end

function vkCreateImage(device,pCreateInfo,pAllocator,pImage)
    ccall((:vkCreateImage,libvulkan),VkResult,(VkDevice,Ptr{VkImageCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkImage}),device,pCreateInfo,pAllocator,pImage)
end

function vkDestroyImage(device,image,pAllocator)
    ccall((:vkDestroyImage,libvulkan),Void,(VkDevice,VkImage,Ptr{VkAllocationCallbacks}),device,image,pAllocator)
end

function vkGetImageSubresourceLayout(device,image,pSubresource,pLayout)
    ccall((:vkGetImageSubresourceLayout,libvulkan),Void,(VkDevice,VkImage,Ptr{VkImageSubresource},Ptr{VkSubresourceLayout}),device,image,pSubresource,pLayout)
end

function vkCreateImageView(device,pCreateInfo,pAllocator,pView)
    ccall((:vkCreateImageView,libvulkan),VkResult,(VkDevice,Ptr{VkImageViewCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkImageView}),device,pCreateInfo,pAllocator,pView)
end

function vkDestroyImageView(device,imageView,pAllocator)
    ccall((:vkDestroyImageView,libvulkan),Void,(VkDevice,VkImageView,Ptr{VkAllocationCallbacks}),device,imageView,pAllocator)
end

function vkCreateShaderModule(device,pCreateInfo,pAllocator,pShaderModule)
    ccall((:vkCreateShaderModule,libvulkan),VkResult,(VkDevice,Ptr{VkShaderModuleCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkShaderModule}),device,pCreateInfo,pAllocator,pShaderModule)
end

function vkDestroyShaderModule(device,shaderModule,pAllocator)
    ccall((:vkDestroyShaderModule,libvulkan),Void,(VkDevice,VkShaderModule,Ptr{VkAllocationCallbacks}),device,shaderModule,pAllocator)
end

function vkCreatePipelineCache(device,pCreateInfo,pAllocator,pPipelineCache)
    ccall((:vkCreatePipelineCache,libvulkan),VkResult,(VkDevice,Ptr{VkPipelineCacheCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkPipelineCache}),device,pCreateInfo,pAllocator,pPipelineCache)
end

function vkDestroyPipelineCache(device,pipelineCache,pAllocator)
    ccall((:vkDestroyPipelineCache,libvulkan),Void,(VkDevice,VkPipelineCache,Ptr{VkAllocationCallbacks}),device,pipelineCache,pAllocator)
end

function vkGetPipelineCacheData(device,pipelineCache,pDataSize,pData)
    ccall((:vkGetPipelineCacheData,libvulkan),VkResult,(VkDevice,VkPipelineCache,Ptr{Csize_t},Ptr{Void}),device,pipelineCache,pDataSize,pData)
end

function vkMergePipelineCaches(device,dstCache,srcCacheCount,pSrcCaches)
    ccall((:vkMergePipelineCaches,libvulkan),VkResult,(VkDevice,VkPipelineCache,UInt32,Ptr{VkPipelineCache}),device,dstCache,srcCacheCount,pSrcCaches)
end

function vkCreateGraphicsPipelines(device,pipelineCache,createInfoCount,pCreateInfos,pAllocator,pPipelines)
    ccall((:vkCreateGraphicsPipelines,libvulkan),VkResult,(VkDevice,VkPipelineCache,UInt32,Ptr{VkGraphicsPipelineCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkPipeline}),device,pipelineCache,createInfoCount,pCreateInfos,pAllocator,pPipelines)
end

function vkCreateComputePipelines(device,pipelineCache,createInfoCount,pCreateInfos,pAllocator,pPipelines)
    ccall((:vkCreateComputePipelines,libvulkan),VkResult,(VkDevice,VkPipelineCache,UInt32,Ptr{VkComputePipelineCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkPipeline}),device,pipelineCache,createInfoCount,pCreateInfos,pAllocator,pPipelines)
end

function vkDestroyPipeline(device,pipeline,pAllocator)
    ccall((:vkDestroyPipeline,libvulkan),Void,(VkDevice,VkPipeline,Ptr{VkAllocationCallbacks}),device,pipeline,pAllocator)
end

function vkCreatePipelineLayout(device,pCreateInfo,pAllocator,pPipelineLayout)
    ccall((:vkCreatePipelineLayout,libvulkan),VkResult,(VkDevice,Ptr{VkPipelineLayoutCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkPipelineLayout}),device,pCreateInfo,pAllocator,pPipelineLayout)
end

function vkDestroyPipelineLayout(device,pipelineLayout,pAllocator)
    ccall((:vkDestroyPipelineLayout,libvulkan),Void,(VkDevice,VkPipelineLayout,Ptr{VkAllocationCallbacks}),device,pipelineLayout,pAllocator)
end

function vkCreateSampler(device,pCreateInfo,pAllocator,pSampler)
    ccall((:vkCreateSampler,libvulkan),VkResult,(VkDevice,Ptr{VkSamplerCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkSampler}),device,pCreateInfo,pAllocator,pSampler)
end

function vkDestroySampler(device,sampler,pAllocator)
    ccall((:vkDestroySampler,libvulkan),Void,(VkDevice,VkSampler,Ptr{VkAllocationCallbacks}),device,sampler,pAllocator)
end

function vkCreateDescriptorSetLayout(device,pCreateInfo,pAllocator,pSetLayout)
    ccall((:vkCreateDescriptorSetLayout,libvulkan),VkResult,(VkDevice,Ptr{VkDescriptorSetLayoutCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkDescriptorSetLayout}),device,pCreateInfo,pAllocator,pSetLayout)
end

function vkDestroyDescriptorSetLayout(device,descriptorSetLayout,pAllocator)
    ccall((:vkDestroyDescriptorSetLayout,libvulkan),Void,(VkDevice,VkDescriptorSetLayout,Ptr{VkAllocationCallbacks}),device,descriptorSetLayout,pAllocator)
end

function vkCreateDescriptorPool(device,pCreateInfo,pAllocator,pDescriptorPool)
    ccall((:vkCreateDescriptorPool,libvulkan),VkResult,(VkDevice,Ptr{VkDescriptorPoolCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkDescriptorPool}),device,pCreateInfo,pAllocator,pDescriptorPool)
end

function vkDestroyDescriptorPool(device,descriptorPool,pAllocator)
    ccall((:vkDestroyDescriptorPool,libvulkan),Void,(VkDevice,VkDescriptorPool,Ptr{VkAllocationCallbacks}),device,descriptorPool,pAllocator)
end

function vkResetDescriptorPool(device,descriptorPool,flags)
    ccall((:vkResetDescriptorPool,libvulkan),VkResult,(VkDevice,VkDescriptorPool,VkDescriptorPoolResetFlags),device,descriptorPool,flags)
end

function vkAllocateDescriptorSets(device,pAllocateInfo,pDescriptorSets)
    ccall((:vkAllocateDescriptorSets,libvulkan),VkResult,(VkDevice,Ptr{VkDescriptorSetAllocateInfo},Ptr{VkDescriptorSet}),device,pAllocateInfo,pDescriptorSets)
end

function vkFreeDescriptorSets(device,descriptorPool,descriptorSetCount,pDescriptorSets)
    ccall((:vkFreeDescriptorSets,libvulkan),VkResult,(VkDevice,VkDescriptorPool,UInt32,Ptr{VkDescriptorSet}),device,descriptorPool,descriptorSetCount,pDescriptorSets)
end

function vkUpdateDescriptorSets(device,descriptorWriteCount,pDescriptorWrites,descriptorCopyCount,pDescriptorCopies)
    ccall((:vkUpdateDescriptorSets,libvulkan),Void,(VkDevice,UInt32,Ptr{VkWriteDescriptorSet},UInt32,Ptr{VkCopyDescriptorSet}),device,descriptorWriteCount,pDescriptorWrites,descriptorCopyCount,pDescriptorCopies)
end

function vkCreateFramebuffer(device,pCreateInfo,pAllocator,pFramebuffer)
    ccall((:vkCreateFramebuffer,libvulkan),VkResult,(VkDevice,Ptr{VkFramebufferCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkFramebuffer}),device,pCreateInfo,pAllocator,pFramebuffer)
end

function vkDestroyFramebuffer(device,framebuffer,pAllocator)
    ccall((:vkDestroyFramebuffer,libvulkan),Void,(VkDevice,VkFramebuffer,Ptr{VkAllocationCallbacks}),device,framebuffer,pAllocator)
end

function vkCreateRenderPass(device,pCreateInfo,pAllocator,pRenderPass)
    ccall((:vkCreateRenderPass,libvulkan),VkResult,(VkDevice,Ptr{VkRenderPassCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkRenderPass}),device,pCreateInfo,pAllocator,pRenderPass)
end

function vkDestroyRenderPass(device,renderPass,pAllocator)
    ccall((:vkDestroyRenderPass,libvulkan),Void,(VkDevice,VkRenderPass,Ptr{VkAllocationCallbacks}),device,renderPass,pAllocator)
end

function vkGetRenderAreaGranularity(device,renderPass,pGranularity)
    ccall((:vkGetRenderAreaGranularity,libvulkan),Void,(VkDevice,VkRenderPass,Ptr{VkExtent2D}),device,renderPass,pGranularity)
end

function vkCreateCommandPool(device,pCreateInfo,pAllocator,pCommandPool)
    ccall((:vkCreateCommandPool,libvulkan),VkResult,(VkDevice,Ptr{VkCommandPoolCreateInfo},Ptr{VkAllocationCallbacks},Ptr{VkCommandPool}),device,pCreateInfo,pAllocator,pCommandPool)
end

function vkDestroyCommandPool(device,commandPool,pAllocator)
    ccall((:vkDestroyCommandPool,libvulkan),Void,(VkDevice,VkCommandPool,Ptr{VkAllocationCallbacks}),device,commandPool,pAllocator)
end

function vkResetCommandPool(device,commandPool,flags)
    ccall((:vkResetCommandPool,libvulkan),VkResult,(VkDevice,VkCommandPool,VkCommandPoolResetFlags),device,commandPool,flags)
end

function vkAllocateCommandBuffers(device,pAllocateInfo,pCommandBuffers)
    ccall((:vkAllocateCommandBuffers,libvulkan),VkResult,(VkDevice,Ptr{VkCommandBufferAllocateInfo},Ptr{VkCommandBuffer}),device,pAllocateInfo,pCommandBuffers)
end

function vkFreeCommandBuffers(device,commandPool,commandBufferCount,pCommandBuffers)
    ccall((:vkFreeCommandBuffers,libvulkan),Void,(VkDevice,VkCommandPool,UInt32,Ptr{VkCommandBuffer}),device,commandPool,commandBufferCount,pCommandBuffers)
end

function vkBeginCommandBuffer(commandBuffer,pBeginInfo)
    ccall((:vkBeginCommandBuffer,libvulkan),VkResult,(VkCommandBuffer,Ptr{VkCommandBufferBeginInfo}),commandBuffer,pBeginInfo)
end

function vkEndCommandBuffer(commandBuffer)
    ccall((:vkEndCommandBuffer,libvulkan),VkResult,(VkCommandBuffer,),commandBuffer)
end

function vkResetCommandBuffer(commandBuffer,flags)
    ccall((:vkResetCommandBuffer,libvulkan),VkResult,(VkCommandBuffer,VkCommandBufferResetFlags),commandBuffer,flags)
end

function vkCmdBindPipeline(commandBuffer,pipelineBindPoint,pipeline)
    ccall((:vkCmdBindPipeline,libvulkan),Void,(VkCommandBuffer,VkPipelineBindPoint,VkPipeline),commandBuffer,pipelineBindPoint,pipeline)
end

function vkCmdSetViewport(commandBuffer,firstViewport,viewportCount,pViewports)
    ccall((:vkCmdSetViewport,libvulkan),Void,(VkCommandBuffer,UInt32,UInt32,Ptr{VkViewport}),commandBuffer,firstViewport,viewportCount,pViewports)
end

function vkCmdSetScissor(commandBuffer,firstScissor,scissorCount,pScissors)
    ccall((:vkCmdSetScissor,libvulkan),Void,(VkCommandBuffer,UInt32,UInt32,Ptr{VkRect2D}),commandBuffer,firstScissor,scissorCount,pScissors)
end

function vkCmdSetLineWidth(commandBuffer,lineWidth)
    ccall((:vkCmdSetLineWidth,libvulkan),Void,(VkCommandBuffer,Cfloat),commandBuffer,lineWidth)
end

function vkCmdSetDepthBias(commandBuffer,depthBiasConstantFactor,depthBiasClamp,depthBiasSlopeFactor)
    ccall((:vkCmdSetDepthBias,libvulkan),Void,(VkCommandBuffer,Cfloat,Cfloat,Cfloat),commandBuffer,depthBiasConstantFactor,depthBiasClamp,depthBiasSlopeFactor)
end

function vkCmdSetBlendConstants(commandBuffer,blendConstants)
    ccall((:vkCmdSetBlendConstants,libvulkan),Void,(VkCommandBuffer,NTuple{4,Cfloat}),commandBuffer,blendConstants)
end

function vkCmdSetDepthBounds(commandBuffer,minDepthBounds,maxDepthBounds)
    ccall((:vkCmdSetDepthBounds,libvulkan),Void,(VkCommandBuffer,Cfloat,Cfloat),commandBuffer,minDepthBounds,maxDepthBounds)
end

function vkCmdSetStencilCompareMask(commandBuffer,faceMask,compareMask)
    ccall((:vkCmdSetStencilCompareMask,libvulkan),Void,(VkCommandBuffer,VkStencilFaceFlags,UInt32),commandBuffer,faceMask,compareMask)
end

function vkCmdSetStencilWriteMask(commandBuffer,faceMask,writeMask)
    ccall((:vkCmdSetStencilWriteMask,libvulkan),Void,(VkCommandBuffer,VkStencilFaceFlags,UInt32),commandBuffer,faceMask,writeMask)
end

function vkCmdSetStencilReference(commandBuffer,faceMask,reference)
    ccall((:vkCmdSetStencilReference,libvulkan),Void,(VkCommandBuffer,VkStencilFaceFlags,UInt32),commandBuffer,faceMask,reference)
end

function vkCmdBindDescriptorSets(commandBuffer,pipelineBindPoint,layout,firstSet,descriptorSetCount,pDescriptorSets,dynamicOffsetCount,pDynamicOffsets)
    ccall((:vkCmdBindDescriptorSets,libvulkan),Void,(VkCommandBuffer,VkPipelineBindPoint,VkPipelineLayout,UInt32,UInt32,Ptr{VkDescriptorSet},UInt32,Ptr{UInt32}),commandBuffer,pipelineBindPoint,layout,firstSet,descriptorSetCount,pDescriptorSets,dynamicOffsetCount,pDynamicOffsets)
end

function vkCmdBindIndexBuffer(commandBuffer,buffer,offset,indexType)
    ccall((:vkCmdBindIndexBuffer,libvulkan),Void,(VkCommandBuffer,VkBuffer,VkDeviceSize,VkIndexType),commandBuffer,buffer,offset,indexType)
end

function vkCmdBindVertexBuffers(commandBuffer,firstBinding,bindingCount,pBuffers,pOffsets)
    ccall((:vkCmdBindVertexBuffers,libvulkan),Void,(VkCommandBuffer,UInt32,UInt32,Ptr{VkBuffer},Ptr{VkDeviceSize}),commandBuffer,firstBinding,bindingCount,pBuffers,pOffsets)
end

function vkCmdDraw(commandBuffer,vertexCount,instanceCount,firstVertex,firstInstance)
    ccall((:vkCmdDraw,libvulkan),Void,(VkCommandBuffer,UInt32,UInt32,UInt32,UInt32),commandBuffer,vertexCount,instanceCount,firstVertex,firstInstance)
end

function vkCmdDrawIndexed(commandBuffer,indexCount,instanceCount,firstIndex,vertexOffset,firstInstance)
    ccall((:vkCmdDrawIndexed,libvulkan),Void,(VkCommandBuffer,UInt32,UInt32,UInt32,Int32,UInt32),commandBuffer,indexCount,instanceCount,firstIndex,vertexOffset,firstInstance)
end

function vkCmdDrawIndirect(commandBuffer,buffer,offset,drawCount,stride)
    ccall((:vkCmdDrawIndirect,libvulkan),Void,(VkCommandBuffer,VkBuffer,VkDeviceSize,UInt32,UInt32),commandBuffer,buffer,offset,drawCount,stride)
end

function vkCmdDrawIndexedIndirect(commandBuffer,buffer,offset,drawCount,stride)
    ccall((:vkCmdDrawIndexedIndirect,libvulkan),Void,(VkCommandBuffer,VkBuffer,VkDeviceSize,UInt32,UInt32),commandBuffer,buffer,offset,drawCount,stride)
end

function vkCmdDispatch(commandBuffer,x,y,z)
    ccall((:vkCmdDispatch,libvulkan),Void,(VkCommandBuffer,UInt32,UInt32,UInt32),commandBuffer,x,y,z)
end

function vkCmdDispatchIndirect(commandBuffer,buffer,offset)
    ccall((:vkCmdDispatchIndirect,libvulkan),Void,(VkCommandBuffer,VkBuffer,VkDeviceSize),commandBuffer,buffer,offset)
end

function vkCmdCopyBuffer(commandBuffer,srcBuffer,dstBuffer,regionCount,pRegions)
    ccall((:vkCmdCopyBuffer,libvulkan),Void,(VkCommandBuffer,VkBuffer,VkBuffer,UInt32,Ptr{VkBufferCopy}),commandBuffer,srcBuffer,dstBuffer,regionCount,pRegions)
end

function vkCmdCopyImage(commandBuffer,srcImage,srcImageLayout,dstImage,dstImageLayout,regionCount,pRegions)
    ccall((:vkCmdCopyImage,libvulkan),Void,(VkCommandBuffer,VkImage,VkImageLayout,VkImage,VkImageLayout,UInt32,Ptr{VkImageCopy}),commandBuffer,srcImage,srcImageLayout,dstImage,dstImageLayout,regionCount,pRegions)
end

function vkCmdBlitImage(commandBuffer,srcImage,srcImageLayout,dstImage,dstImageLayout,regionCount,pRegions,filter)
    ccall((:vkCmdBlitImage,libvulkan),Void,(VkCommandBuffer,VkImage,VkImageLayout,VkImage,VkImageLayout,UInt32,Ptr{VkImageBlit},VkFilter),commandBuffer,srcImage,srcImageLayout,dstImage,dstImageLayout,regionCount,pRegions,filter)
end

function vkCmdCopyBufferToImage(commandBuffer,srcBuffer,dstImage,dstImageLayout,regionCount,pRegions)
    ccall((:vkCmdCopyBufferToImage,libvulkan),Void,(VkCommandBuffer,VkBuffer,VkImage,VkImageLayout,UInt32,Ptr{VkBufferImageCopy}),commandBuffer,srcBuffer,dstImage,dstImageLayout,regionCount,pRegions)
end

function vkCmdCopyImageToBuffer(commandBuffer,srcImage,srcImageLayout,dstBuffer,regionCount,pRegions)
    ccall((:vkCmdCopyImageToBuffer,libvulkan),Void,(VkCommandBuffer,VkImage,VkImageLayout,VkBuffer,UInt32,Ptr{VkBufferImageCopy}),commandBuffer,srcImage,srcImageLayout,dstBuffer,regionCount,pRegions)
end

function vkCmdUpdateBuffer(commandBuffer,dstBuffer,dstOffset,dataSize,pData)
    ccall((:vkCmdUpdateBuffer,libvulkan),Void,(VkCommandBuffer,VkBuffer,VkDeviceSize,VkDeviceSize,Ptr{UInt32}),commandBuffer,dstBuffer,dstOffset,dataSize,pData)
end

function vkCmdFillBuffer(commandBuffer,dstBuffer,dstOffset,size,data)
    ccall((:vkCmdFillBuffer,libvulkan),Void,(VkCommandBuffer,VkBuffer,VkDeviceSize,VkDeviceSize,UInt32),commandBuffer,dstBuffer,dstOffset,size,data)
end

function vkCmdClearColorImage(commandBuffer,image,imageLayout,pColor,rangeCount,pRanges)
    ccall((:vkCmdClearColorImage,libvulkan),Void,(VkCommandBuffer,VkImage,VkImageLayout,Ptr{VkClearColorValue},UInt32,Ptr{VkImageSubresourceRange}),commandBuffer,image,imageLayout,pColor,rangeCount,pRanges)
end

function vkCmdClearDepthStencilImage(commandBuffer,image,imageLayout,pDepthStencil,rangeCount,pRanges)
    ccall((:vkCmdClearDepthStencilImage,libvulkan),Void,(VkCommandBuffer,VkImage,VkImageLayout,Ptr{VkClearDepthStencilValue},UInt32,Ptr{VkImageSubresourceRange}),commandBuffer,image,imageLayout,pDepthStencil,rangeCount,pRanges)
end

function vkCmdClearAttachments(commandBuffer,attachmentCount,pAttachments,rectCount,pRects)
    ccall((:vkCmdClearAttachments,libvulkan),Void,(VkCommandBuffer,UInt32,Ptr{VkClearAttachment},UInt32,Ptr{VkClearRect}),commandBuffer,attachmentCount,pAttachments,rectCount,pRects)
end

function vkCmdResolveImage(commandBuffer,srcImage,srcImageLayout,dstImage,dstImageLayout,regionCount,pRegions)
    ccall((:vkCmdResolveImage,libvulkan),Void,(VkCommandBuffer,VkImage,VkImageLayout,VkImage,VkImageLayout,UInt32,Ptr{VkImageResolve}),commandBuffer,srcImage,srcImageLayout,dstImage,dstImageLayout,regionCount,pRegions)
end

function vkCmdSetEvent(commandBuffer,event,stageMask)
    ccall((:vkCmdSetEvent,libvulkan),Void,(VkCommandBuffer,VkEvent,VkPipelineStageFlags),commandBuffer,event,stageMask)
end

function vkCmdResetEvent(commandBuffer,event,stageMask)
    ccall((:vkCmdResetEvent,libvulkan),Void,(VkCommandBuffer,VkEvent,VkPipelineStageFlags),commandBuffer,event,stageMask)
end

function vkCmdWaitEvents(commandBuffer,eventCount,pEvents,srcStageMask,dstStageMask,memoryBarrierCount,pMemoryBarriers,bufferMemoryBarrierCount,pBufferMemoryBarriers,imageMemoryBarrierCount,pImageMemoryBarriers)
    ccall((:vkCmdWaitEvents,libvulkan),Void,(VkCommandBuffer,UInt32,Ptr{VkEvent},VkPipelineStageFlags,VkPipelineStageFlags,UInt32,Ptr{VkMemoryBarrier},UInt32,Ptr{VkBufferMemoryBarrier},UInt32,Ptr{VkImageMemoryBarrier}),commandBuffer,eventCount,pEvents,srcStageMask,dstStageMask,memoryBarrierCount,pMemoryBarriers,bufferMemoryBarrierCount,pBufferMemoryBarriers,imageMemoryBarrierCount,pImageMemoryBarriers)
end

function vkCmdPipelineBarrier(commandBuffer,srcStageMask,dstStageMask,dependencyFlags,memoryBarrierCount,pMemoryBarriers,bufferMemoryBarrierCount,pBufferMemoryBarriers,imageMemoryBarrierCount,pImageMemoryBarriers)
    ccall((:vkCmdPipelineBarrier,libvulkan),Void,(VkCommandBuffer,VkPipelineStageFlags,VkPipelineStageFlags,VkDependencyFlags,UInt32,Ptr{VkMemoryBarrier},UInt32,Ptr{VkBufferMemoryBarrier},UInt32,Ptr{VkImageMemoryBarrier}),commandBuffer,srcStageMask,dstStageMask,dependencyFlags,memoryBarrierCount,pMemoryBarriers,bufferMemoryBarrierCount,pBufferMemoryBarriers,imageMemoryBarrierCount,pImageMemoryBarriers)
end

function vkCmdBeginQuery(commandBuffer,queryPool,query,flags)
    ccall((:vkCmdBeginQuery,libvulkan),Void,(VkCommandBuffer,VkQueryPool,UInt32,VkQueryControlFlags),commandBuffer,queryPool,query,flags)
end

function vkCmdEndQuery(commandBuffer,queryPool,query)
    ccall((:vkCmdEndQuery,libvulkan),Void,(VkCommandBuffer,VkQueryPool,UInt32),commandBuffer,queryPool,query)
end

function vkCmdResetQueryPool(commandBuffer,queryPool,firstQuery,queryCount)
    ccall((:vkCmdResetQueryPool,libvulkan),Void,(VkCommandBuffer,VkQueryPool,UInt32,UInt32),commandBuffer,queryPool,firstQuery,queryCount)
end

function vkCmdWriteTimestamp(commandBuffer,pipelineStage,queryPool,query)
    ccall((:vkCmdWriteTimestamp,libvulkan),Void,(VkCommandBuffer,VkPipelineStageFlagBits,VkQueryPool,UInt32),commandBuffer,pipelineStage,queryPool,query)
end

function vkCmdCopyQueryPoolResults(commandBuffer,queryPool,firstQuery,queryCount,dstBuffer,dstOffset,stride,flags)
    ccall((:vkCmdCopyQueryPoolResults,libvulkan),Void,(VkCommandBuffer,VkQueryPool,UInt32,UInt32,VkBuffer,VkDeviceSize,VkDeviceSize,VkQueryResultFlags),commandBuffer,queryPool,firstQuery,queryCount,dstBuffer,dstOffset,stride,flags)
end

function vkCmdPushConstants(commandBuffer,layout,stageFlags,offset,size,pValues)
    ccall((:vkCmdPushConstants,libvulkan),Void,(VkCommandBuffer,VkPipelineLayout,VkShaderStageFlags,UInt32,UInt32,Ptr{Void}),commandBuffer,layout,stageFlags,offset,size,pValues)
end

function vkCmdBeginRenderPass(commandBuffer,pRenderPassBegin,contents)
    ccall((:vkCmdBeginRenderPass,libvulkan),Void,(VkCommandBuffer,Ptr{VkRenderPassBeginInfo},VkSubpassContents),commandBuffer,pRenderPassBegin,contents)
end

function vkCmdNextSubpass(commandBuffer,contents)
    ccall((:vkCmdNextSubpass,libvulkan),Void,(VkCommandBuffer,VkSubpassContents),commandBuffer,contents)
end

function vkCmdEndRenderPass(commandBuffer)
    ccall((:vkCmdEndRenderPass,libvulkan),Void,(VkCommandBuffer,),commandBuffer)
end

function vkCmdExecuteCommands(commandBuffer,commandBufferCount,pCommandBuffers)
    ccall((:vkCmdExecuteCommands,libvulkan),Void,(VkCommandBuffer,UInt32,Ptr{VkCommandBuffer}),commandBuffer,commandBufferCount,pCommandBuffers)
end

function vkDestroySurfaceKHR(instance,surface,pAllocator)
    ccall((:vkDestroySurfaceKHR,libvulkan),Void,(VkInstance,VkSurfaceKHR,Ptr{VkAllocationCallbacks}),instance,surface,pAllocator)
end

function vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice,queueFamilyIndex,surface,pSupported)
    ccall((:vkGetPhysicalDeviceSurfaceSupportKHR,libvulkan),VkResult,(VkPhysicalDevice,UInt32,VkSurfaceKHR,Ptr{VkBool32}),physicalDevice,queueFamilyIndex,surface,pSupported)
end

function vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice,surface,pSurfaceCapabilities)
    ccall((:vkGetPhysicalDeviceSurfaceCapabilitiesKHR,libvulkan),VkResult,(VkPhysicalDevice,VkSurfaceKHR,Ptr{VkSurfaceCapabilitiesKHR}),physicalDevice,surface,pSurfaceCapabilities)
end

function vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,surface,pSurfaceFormatCount,pSurfaceFormats)
    ccall((:vkGetPhysicalDeviceSurfaceFormatsKHR,libvulkan),VkResult,(VkPhysicalDevice,VkSurfaceKHR,Ptr{UInt32},Ptr{VkSurfaceFormatKHR}),physicalDevice,surface,pSurfaceFormatCount,pSurfaceFormats)
end

function vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice,surface,pPresentModeCount,pPresentModes)
    ccall((:vkGetPhysicalDeviceSurfacePresentModesKHR,libvulkan),VkResult,(VkPhysicalDevice,VkSurfaceKHR,Ptr{UInt32},Ptr{VkPresentModeKHR}),physicalDevice,surface,pPresentModeCount,pPresentModes)
end

function vkCreateSwapchainKHR(device,pCreateInfo,pAllocator,pSwapchain)
    ccall((:vkCreateSwapchainKHR,libvulkan),VkResult,(VkDevice,Ptr{VkSwapchainCreateInfoKHR},Ptr{VkAllocationCallbacks},Ptr{VkSwapchainKHR}),device,pCreateInfo,pAllocator,pSwapchain)
end

function vkDestroySwapchainKHR(device,swapchain,pAllocator)
    ccall((:vkDestroySwapchainKHR,libvulkan),Void,(VkDevice,VkSwapchainKHR,Ptr{VkAllocationCallbacks}),device,swapchain,pAllocator)
end

function vkGetSwapchainImagesKHR(device,swapchain,pSwapchainImageCount,pSwapchainImages)
    ccall((:vkGetSwapchainImagesKHR,libvulkan),VkResult,(VkDevice,VkSwapchainKHR,Ptr{UInt32},Ptr{VkImage}),device,swapchain,pSwapchainImageCount,pSwapchainImages)
end

function vkAcquireNextImageKHR(device,swapchain,timeout,semaphore,fence,pImageIndex)
    ccall((:vkAcquireNextImageKHR,libvulkan),VkResult,(VkDevice,VkSwapchainKHR,UInt64,VkSemaphore,VkFence,Ptr{UInt32}),device,swapchain,timeout,semaphore,fence,pImageIndex)
end

function vkQueuePresentKHR(queue,pPresentInfo)
    ccall((:vkQueuePresentKHR,libvulkan),VkResult,(VkQueue,Ptr{VkPresentInfoKHR}),queue,pPresentInfo)
end

function vkGetPhysicalDeviceDisplayPropertiesKHR(physicalDevice,pPropertyCount,pProperties)
    ccall((:vkGetPhysicalDeviceDisplayPropertiesKHR,libvulkan),VkResult,(VkPhysicalDevice,Ptr{UInt32},Ptr{VkDisplayPropertiesKHR}),physicalDevice,pPropertyCount,pProperties)
end

function vkGetPhysicalDeviceDisplayPlanePropertiesKHR(physicalDevice,pPropertyCount,pProperties)
    ccall((:vkGetPhysicalDeviceDisplayPlanePropertiesKHR,libvulkan),VkResult,(VkPhysicalDevice,Ptr{UInt32},Ptr{VkDisplayPlanePropertiesKHR}),physicalDevice,pPropertyCount,pProperties)
end

function vkGetDisplayPlaneSupportedDisplaysKHR(physicalDevice,planeIndex,pDisplayCount,pDisplays)
    ccall((:vkGetDisplayPlaneSupportedDisplaysKHR,libvulkan),VkResult,(VkPhysicalDevice,UInt32,Ptr{UInt32},Ptr{VkDisplayKHR}),physicalDevice,planeIndex,pDisplayCount,pDisplays)
end

function vkGetDisplayModePropertiesKHR(physicalDevice,display,pPropertyCount,pProperties)
    ccall((:vkGetDisplayModePropertiesKHR,libvulkan),VkResult,(VkPhysicalDevice,VkDisplayKHR,Ptr{UInt32},Ptr{VkDisplayModePropertiesKHR}),physicalDevice,display,pPropertyCount,pProperties)
end

function vkCreateDisplayModeKHR(physicalDevice,display,pCreateInfo,pAllocator,pMode)
    ccall((:vkCreateDisplayModeKHR,libvulkan),VkResult,(VkPhysicalDevice,VkDisplayKHR,Ptr{VkDisplayModeCreateInfoKHR},Ptr{VkAllocationCallbacks},Ptr{VkDisplayModeKHR}),physicalDevice,display,pCreateInfo,pAllocator,pMode)
end

function vkGetDisplayPlaneCapabilitiesKHR(physicalDevice,mode,planeIndex,pCapabilities)
    ccall((:vkGetDisplayPlaneCapabilitiesKHR,libvulkan),VkResult,(VkPhysicalDevice,VkDisplayModeKHR,UInt32,Ptr{VkDisplayPlaneCapabilitiesKHR}),physicalDevice,mode,planeIndex,pCapabilities)
end

function vkCreateDisplayPlaneSurfaceKHR(instance,pCreateInfo,pAllocator,pSurface)
    ccall((:vkCreateDisplayPlaneSurfaceKHR,libvulkan),VkResult,(VkInstance,Ptr{VkDisplaySurfaceCreateInfoKHR},Ptr{VkAllocationCallbacks},Ptr{VkSurfaceKHR}),instance,pCreateInfo,pAllocator,pSurface)
end

function vkCreateSharedSwapchainsKHR(device,swapchainCount,pCreateInfos,pAllocator,pSwapchains)
    ccall((:vkCreateSharedSwapchainsKHR,libvulkan),VkResult,(VkDevice,UInt32,Ptr{VkSwapchainCreateInfoKHR},Ptr{VkAllocationCallbacks},Ptr{VkSwapchainKHR}),device,swapchainCount,pCreateInfos,pAllocator,pSwapchains)
end

function vkCreateXcbSurfaceKHR(instance,pCreateInfo,pAllocator,pSurface)
    ccall((:vkCreateXcbSurfaceKHR,libvulkan),VkResult,(VkInstance,Ptr{VkXcbSurfaceCreateInfoKHR},Ptr{VkAllocationCallbacks},Ptr{VkSurfaceKHR}),instance,pCreateInfo,pAllocator,pSurface)
end

function vkGetPhysicalDeviceXcbPresentationSupportKHR(physicalDevice,queueFamilyIndex,connection,visual_id)
    ccall((:vkGetPhysicalDeviceXcbPresentationSupportKHR,libvulkan),VkBool32,(VkPhysicalDevice,UInt32,Ptr{xcb_connection_t},xcb_visualid_t),physicalDevice,queueFamilyIndex,connection,visual_id)
end

function vkCreateWaylandSurfaceKHR(instance,pCreateInfo,pAllocator,pSurface)
    ccall((:vkCreateWaylandSurfaceKHR,libvulkan),VkResult,(VkInstance,Ptr{VkWaylandSurfaceCreateInfoKHR},Ptr{VkAllocationCallbacks},Ptr{VkSurfaceKHR}),instance,pCreateInfo,pAllocator,pSurface)
end

function vkGetPhysicalDeviceWaylandPresentationSupportKHR(physicalDevice,queueFamilyIndex,display)
    ccall((:vkGetPhysicalDeviceWaylandPresentationSupportKHR,libvulkan),VkBool32,(VkPhysicalDevice,UInt32,Ptr{wl_display}),physicalDevice,queueFamilyIndex,display)
end

function vkCreateMirSurfaceKHR(instance,pCreateInfo,pAllocator,pSurface)
    ccall((:vkCreateMirSurfaceKHR,libvulkan),VkResult,(VkInstance,Ptr{VkMirSurfaceCreateInfoKHR},Ptr{VkAllocationCallbacks},Ptr{VkSurfaceKHR}),instance,pCreateInfo,pAllocator,pSurface)
end

function vkGetPhysicalDeviceMirPresentationSupportKHR(physicalDevice,queueFamilyIndex,connection)
    ccall((:vkGetPhysicalDeviceMirPresentationSupportKHR,libvulkan),VkBool32,(VkPhysicalDevice,UInt32,Ptr{Cint}),physicalDevice,queueFamilyIndex,connection)
end

function vkCreateWin32SurfaceKHR(instance,pCreateInfo,pAllocator,pSurface)
    ccall((:vkCreateWin32SurfaceKHR,libvulkan),VkResult,(VkInstance,Ptr{VkWin32SurfaceCreateInfoKHR},Ptr{VkAllocationCallbacks},Ptr{VkSurfaceKHR}),instance,pCreateInfo,pAllocator,pSurface)
end

function vkGetPhysicalDeviceWin32PresentationSupportKHR(physicalDevice,queueFamilyIndex)
    ccall((:vkGetPhysicalDeviceWin32PresentationSupportKHR,libvulkan),VkBool32,(VkPhysicalDevice,UInt32),physicalDevice,queueFamilyIndex)
end

function vkCreateDebugReportCallbackEXT(instance,pCreateInfo,pAllocator,pCallback)
    ccall((:vkCreateDebugReportCallbackEXT,libvulkan),VkResult,(VkInstance,Ptr{VkDebugReportCallbackCreateInfoEXT},Ptr{VkAllocationCallbacks},Ptr{VkDebugReportCallbackEXT}),instance,pCreateInfo,pAllocator,pCallback)
end

function vkDestroyDebugReportCallbackEXT(instance,callback,pAllocator)
    ccall((:vkDestroyDebugReportCallbackEXT,libvulkan),Void,(VkInstance,VkDebugReportCallbackEXT,Ptr{VkAllocationCallbacks}),instance,callback,pAllocator)
end

function vkDebugReportMessageEXT(instance,flags,objectType,object,location,messageCode,pLayerPrefix,pMessage)
    ccall((:vkDebugReportMessageEXT,libvulkan),Void,(VkInstance,VkDebugReportFlagsEXT,VkDebugReportObjectTypeEXT,UInt64,Csize_t,Int32,Cstring,Cstring),instance,flags,objectType,object,location,messageCode,pLayerPrefix,pMessage)
end


text:
using DrWatson
@quickactivate "PECUZAL_Julia"

using DelayEmbeddings
using DelimitedFiles
using StatsBase
using Random

include("../../../src/pecuzal_method.jl")
include("../../../src/data_analysis_functions.jl")

## We analyze the reconstruction from standard time delay embedding, the
# MDOP embedding algorithm and the Garcia & Almeida method and compare it to
# our propsed method: The pecuzal method.
# For evaluation of the different reconstructions we consider Uzal's L-statistic,
# the fraction of recurrence rates from the JRP of the reconstruction and the
# reference and only the reference. As a third criterion we look at the
# recurrence time entropy, since it is related to the Kolmogorov-entropy as a
# dynamical invariant. We also look at two other RQA-measures and, moreover, the
# generalized mutual false nearest neighbors.

# Here we look at real data of a chaotic electrochemical oscillator (Ni) from
# the Kiss group with two different resistances R₁ = 1,5kΩ, R₂ = 2,5kΩ leading to
# "more" chaoticity.

## Load the data
Random.seed!(1234)

data1 = readdlm("./scripts/Experimental data/Standard electrochemical chaos/s3ch4.txt")
data2 = readdlm("./scripts/Experimental data/Standard electrochemical chaos/s1ch3.txt")

# length of the whole time series
M1 = length(data1)
M2 = length(data2)
M = minimum(hcat(M1, M2))

# downsampling
data1 = data1[1:4:M]
data2 = data2[1:4:M]
M = length(data1)

data1 = regularize(data1 .+ .000001*randn(length(data1)))
data2 = regularize(data2 .+ .000001*randn(length(data2)))

# the possible lags
taus = 0:200

# set recurrence threshold for further analysis (and min line length)
ε = 0.08
lmin = 2

# set length of time series sample
N = 500

# number of time series samples
samplesize = 1000

# draw samples
idxs1 = sample(vec(1:M-N-1), samplesize, replace = false)
idxs2 = sample(vec(1:M-N-1), samplesize, replace = false)

#preallocation
RQA_tde1 = zeros(4,samplesize)
RQA_tde2 = zeros(4,samplesize)
RQA_GA1 = zeros(4,samplesize)
RQA_GA2 = zeros(4,samplesize)
RQA_mdop1 = zeros(4,samplesize)
RQA_mdop2 = zeros(4,samplesize)
RQA_pec1 = zeros(4,samplesize)
RQA_pec2 = zeros(4,samplesize)

dim_tde1 = zeros(Int, samplesize)
dim_tde2 = zeros(Int, samplesize)
L_tde1 = zeros(samplesize)
L_tde2 = zeros(samplesize)

dim_GA1 = zeros(Int, samplesize)
dim_GA2 = zeros(Int, samplesize)
L_GA1 = zeros(samplesize)
L_GA2 = zeros(samplesize)

dim_mdop1 = zeros(Int, samplesize)
dim_mdop2 = zeros(Int, samplesize)
L_mdop1 = zeros(samplesize)
L_mdop2 = zeros(samplesize)

dim_pec1 = zeros(Int, samplesize)
dim_pec2 = zeros(Int, samplesize)
L_pec1 = zeros(samplesize)
L_pec2 = zeros(samplesize)
include("../../../src/pecuzal_method.jl")
for i = 1:1
    display("run: $i")
    # draw the actual sample
    idx1 = idxs1[i]
    idx2 = idxs2[i]
    x1 = data1[idx1:idx1+N]
    x2 = data2[idx2:idx2+N]

    w1 = estimate_delay(x1, "mi_min")
    w2 = estimate_delay(x2, "mi_min")

    ## Perform embeddings
    #Standard TDE
    Y_tde1, τ_tde1, _ = optimal_traditional_de(x1; τs = taus)
    Y_tde2, τ_tde2, _ = optimal_traditional_de(x2; τs = taus)

    dim_tde1[i] = size(Y_tde1,2)
    dim_tde2[i] = size(Y_tde2,2)
    τ_tdes1 = [(i-1)*τ_tde1 for i = 1:(size(Y_tde1,2))]
    τ_tdes2 = [(i-1)*τ_tde2 for i = 1:(size(Y_tde2,2))]
    L_tde1[i] = compute_delta_L(x1, τ_tdes1, taus[end]; w = w1)
    L_tde2[i] = compute_delta_L(x2, τ_tdes2, taus[end]; w = w2)

    #MDOP embedding
    tw1 = mdop_maximum_delay(x1)
    tw2 = mdop_maximum_delay(x2)
    lm1 = DelayEmbeddings.findlocalminima(tw1[2])
    if lm1[1] ≤ 3
        lmm1 = try lm1[2]
        catch
            lm1[1]
        end
    else
        lmm1 = lm1[1]
    end
    lm2 = DelayEmbeddings.findlocalminima(tw2[2])
    if lm2[1] ≤ 3
        lmm2 = try lm2[2]
        catch
            lm2[1]
        end
    else
        lmm2 = lm2[1]
    end
    tau_max1 = lmm1
    tau_max2 = lmm2
    taus_mdop1 = 0:tau_max1
    taus_mdop2 = 0:tau_max2

    Y_mdop1, τ_vals_mdop1, ts_vals_mdop1, FNNs_mdop1 , βs_mdop1 = mdop_embedding(x1;
                                                        τs = taus_mdop1 , w = w1)
    dim_mdop1[i] = size(Y_mdop1,2)
    L_mdop1[i] = compute_delta_L(x1, τ_vals_mdop1, taus_mdop1[end]; w = w1)

    Y_mdop2, τ_vals_mdop2, ts_vals_mdop2, FNNs_mdop2 , βs_mdop2 = mdop_embedding(x2;
                                                        τs = taus_mdop2 , w = w2)
    dim_mdop2[i] = size(Y_mdop2,2)
    L_mdop2[i] = compute_delta_L(x2, τ_vals_mdop2, taus_mdop2[end]; w = w2)

    #Garcia & Almeida

    Y_GA1, τ_vals_GA1, ts_vals_GA1, FNNs_GA1 , ns_GA1 = garcia_almeida_embedding(x1;
                                                        τs = taus , w = w1, T = w1)
    dim_GA1[i] = size(Y_GA1,2)
    L_GA1[i] = compute_delta_L(x1, τ_vals_GA1, taus[end]; w = w1)
    Y_GA2, τ_vals_GA2, ts_vals_GA2, FNNs_GA2 , ns_GA2 = garcia_almeida_embedding(x2;
                                                        τs = taus , w = w2, T = w2)
    dim_GA2[i] = size(Y_GA2,2)
    L_GA2[i] = compute_delta_L(x2, τ_vals_GA2, taus[end]; w = w2)

    #Pecuzal
    Y_pec1, τ_vals_pec1, ts_vals_pec1, Ls_pec1 , εs_pec1 = pecuzal_embedding_update(x1;
                                                                τs = taus , w = w1)
    dim_pec1[i] = size(Y_pec1,2)
    L_pec1[i] = sum(Ls_pec1)
    Y_pec2, τ_vals_pec2, ts_vals_pec2, Ls_pec2 , εs_pec2 = pecuzal_embedding_update(x2;
                                                                τs = taus , w = w2)
    dim_pec2[i] = size(Y_pec2,2)
    L_pec2[i] = sum(Ls_pec2)

    ## Make all reconstructions equally long
    N1 = length(Y_tde1)
    N2 = length(Y_GA1)
    N3 = length(Y_mdop1)
    N4 = length(Y_pec1)
    NN1 = minimum(hcat(N1, N2, N3, N4))

    N1 = length(Y_tde2)
    N2 = length(Y_GA2)
    N3 = length(Y_mdop2)
    N4 = length(Y_pec2)
    NN2 = minimum(hcat(N1, N2, N3, N4))

    ## RQA
    R11 = RecurrenceMatrix(Y_tde1[1:NN1,:], ε; fixedrate = true)
    R21 = RecurrenceMatrix(Y_GA1[1:NN1,:], ε; fixedrate = true)
    R31 = RecurrenceMatrix(Y_mdop1[1:NN1,:], ε; fixedrate = true)
    R41 = RecurrenceMatrix(Y_pec1[1:NN1,:], ε; fixedrate = true)

    R12 = RecurrenceMatrix(Y_tde2[1:NN2,:], ε; fixedrate = true)
    R22 = RecurrenceMatrix(Y_GA2[1:NN2,:], ε; fixedrate = true)
    R32 = RecurrenceMatrix(Y_mdop2[1:NN2,:], ε; fixedrate = true)
    R42 = RecurrenceMatrix(Y_pec2[1:NN2,:], ε; fixedrate = true)

    RQA11 = rqa(R11; theiler = w1, lmin = lmin)
    RQA21 = rqa(R21; theiler = w1, lmin = lmin)
    RQA31 = rqa(R31; theiler = w1, lmin = lmin)
    RQA41 = rqa(R41; theiler = w1, lmin = lmin)

    RQA12 = rqa(R12; theiler = w2, lmin = lmin)
    RQA22 = rqa(R22; theiler = w2, lmin = lmin)
    RQA32 = rqa(R32; theiler = w2, lmin = lmin)
    RQA42 = rqa(R42; theiler = w2, lmin = lmin)

    RQA_tde1[1,i] = RQA11.ENTR
    RQA_tde1[2,i] = RQA11.LAM
    RQA_tde1[3,i] = RQA11.RTE
    RQA_tde1[4,i] = RQA11.TRANS
    RQA_tde2[1,i] = RQA12.ENTR
    RQA_tde2[2,i] = RQA12.LAM
    RQA_tde2[3,i] = RQA12.RTE
    RQA_tde2[4,i] = RQA12.TRANS

    RQA_GA1[1,i] = RQA21.ENTR
    RQA_GA1[2,i] = RQA21.LAM
    RQA_GA1[3,i] = RQA21.RTE
    RQA_GA1[4,i] = RQA21.TRANS
    RQA_GA2[1,i] = RQA22.ENTR
    RQA_GA2[2,i] = RQA22.LAM
    RQA_GA2[3,i] = RQA22.RTE
    RQA_GA2[4,i] = RQA22.TRANS

    RQA_mdop1[1,i] = RQA31.ENTR
    RQA_mdop1[2,i] = RQA31.LAM
    RQA_mdop1[3,i] = RQA31.RTE
    RQA_mdop1[4,i] = RQA31.TRANS
    RQA_mdop2[1,i] = RQA32.ENTR
    RQA_mdop2[2,i] = RQA32.LAM
    RQA_mdop2[3,i] = RQA32.RTE
    RQA_mdop2[4,i] = RQA32.TRANS

    RQA_pec1[1,i] = RQA41.ENTR
    RQA_pec1[2,i] = RQA41.LAM
    RQA_pec1[3,i] = RQA41.RTE
    RQA_pec1[4,i] = RQA41.TRANS
    RQA_pec2[1,i] = RQA42.ENTR
    RQA_pec2[2,i] = RQA42.LAM
    RQA_pec2[3,i] = RQA42.RTE
    RQA_pec2[4,i] = RQA42.TRANS
end

# save results
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/RQA_tde1.csv", RQA_tde1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/RQA_tde2.csv", RQA_tde2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/RQA_GA1.csv", RQA_GA1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/RQA_GA2.csv", RQA_GA2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/RQA_mdop1.csv", RQA_mdop1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/RQA_mdop2.csv", RQA_mdop2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/RQA_pec1.csv", RQA_pec1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/RQA_pec2.csv", RQA_pec2)

writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/dim_tde1.csv", dim_tde1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/dim_tde2.csv", dim_tde2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/L_tde1.csv", L_tde1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/L_tde2.csv", L_tde2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/dim_GA1.csv", dim_GA1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/dim_GA2.csv", dim_GA2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/L_GA1.csv", L_GA1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/L_GA2.csv", L_GA2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/dim_mdop1.csv", dim_mdop1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/dim_mdop2.csv", dim_mdop2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/L_mdop1.csv", L_mdop1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/L_mdop2.csv", L_mdop2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/dim_pec1.csv", dim_pec1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/dim_pec2.csv", dim_pec2)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/L_pec1.csv", L_pec1)
writedlm("./scripts/Experimental data/Standard electrochemical chaos/RQA results/L_pec2.csv", L_pec2)

##
# println("TDE:")
# println(mean(dim_tde1))
# println(mean(dim_tde2))
# println(mean(L_tde1))
# println(mean(L_tde2))
# println("***********")
# println("GA:")
# println(mean(dim_GA1))
# println(mean(dim_GA2))
# println(mean(L_GA1))
# println(mean(L_GA2))
# println("***********")
# println("mdop:")
# println(mean(dim_mdop1))
# println(mean(dim_mdop2))
# println(mean(L_mdop1))
# println(mean(L_mdop2))
# println("***********")
# println("pec:")
# println(mean(dim_pec1))
# println(mean(dim_pec2))
# println(mean(L_pec1))
# println(mean(L_pec2))
# println("***********")

max_stars_repo_path: scripts/Experimental data/Standard electrochemical chaos/comm_analyze_standard_ecoscillator.jl


text:
function horizon_plan(C::Int, P::Int, J::Int, Q::Int, tt::Int, delta::Int, bj::Array{Int,1}, tasks_by_position::Dict{Int, Array{LTask, 1}})
    med = median(bj)
    H=0
    for (key, value) in tasks_by_position
        h=0
        for t in value
            if t.t > h
                h=2*t.t
            end
        end
        if bj[key] < med
            H-=2*bj[key]
        elseif bj[key] > med
            H+=2*bj[key]
        end
        H+=h
    end
    if med in bj
        H-=med
    end
    H+=minimum(bj)
    return(H)
end

function horizon_plan_new(C::Int, P::Int, J::Int, Q::Int, tt::Int, delta::Int, bj::Array{Int,1}, tasks_by_position::Dict{Int, Array{LTask, 1}})
    UB=0
    #calculate max loading time
    LT=0
    for (key, value) in tasks_by_position
        h=0
        for t in value
            if t.t > h
                h=2*t.t
            end
        end
        LT+=h
    end
    #calculate max travel time
    for it = 1:Q
        bj_dict = Dict{Int, Array{Int, 1}}()
        order=Array{Tuple{Int,Int},1}()
        for q = 1:Q
            if q == it
                push!(order, ((q-1)*(delta+1)+1, J-(Q-q)*(delta+1)))
            elseif q < it
                push!(order, ((q-1)*(delta+1)+1, q*(delta+1)))
            elseif q > it
                push!(order, (J-(Q-q)*(delta+1)-1, J-(Q-q)*(delta+1)))
            end
        end
        println(order)
        for q = 1:Q
            bj_dict[q] = bj[order[q][1]:order[q][2]]
        end

        H=0
        for (key, value) in bj_dict
            TT=0
            med = median(value)
            for p = 1:P
                if p in value && p < med
                    TT-=2*p
                elseif p in value && p >med
                    TT+=2*p
                end
            end
            if med in value
                TT-=med
            end
            TT+=minimum(value)
            if TT > H
                H = TT
            end
        end

        H+=LT
        if H > UB
            UB = H
        end
    end
    return(UB)
end

function subset_pos(dummy::Array, set::Array{Int, 2}, pos_cont::Int)
    sub_set = findall(x->x!=0, set[pos_cont,:])
    return(sub_set)
end

function subset_pos_cont(set::Array, pos_cont::Int)
    sub_set = findall(x->x!=0, set[pos_cont,:])
    return(sub_set)
end

function subset_bay(CTS::Constants, q::Int)
    sub_set = collect((q-1)*(CTS.delta+1)+1:CTS.J-(CTS.Q-q)*(CTS.delta+1))
    return(sub_set)
end

function bay_to_pos(bay::Int, bj::Array{Int, 1})
    l = Array{Int, 1}()
    for p = 1:length(bj)
        if bj[p] == bay
            push!(l, p)
        end
    end
    return(l)
end

function subset_pos_crane(CTS::Constants, q::Int, bj::Array{Int, 1})
    available_bays = subset_bay(CTS, q)
    sub_set = Array{Int, 1}()
    for bay in available_bays
        append!(sub_set, bay_to_pos(bay, bj))
    end
    return(sub_set)
end

function subset_crane_pos(CTS::Constants, p::Int, bj::Array{Int, 1})
    sub_set = Array{Int, 1}()
    for q = 1:CTS.Q
        if p in subset_pos_crane(CTS, q, bj)
            push!(sub_set, q)
        end
    end
    return(sub_set)
end

max_stars_repo_licenses: Zlib MIT

max_issues_repo_licenses: Zlib MIT

max_forks_repo_licenses: Zlib MIT


text:
using SimplePartitions: find_part
import SimpleGraphs

function Base.convert(::Type{SimpleGraph}, d::SimpleDigraph)
    g = SimpleGraph{Symbol}()
    add_edges!(g, elist(d))
    g
end

# Type piracy, this should really go in SimpleGraphs
# OTOH there's not anything else this could really mean
SimpleGraphs.components(g::SimpleDigraph) = SimpleGraphs.components(convert(SimpleGraph, g))

export predictive
function predictive(m::Model, x :: Symbol)
    g = digraph(m) #Creates a new SimpleDigraph, so no need to copy before mutating

    for xparent ∈ in_neighbors(g, x)
        delete!(g, xparent, x)
    end

    # Find the strongly connected component containing x
    part = find_part(SimpleGraphs.components(g), x) |> union

    newargs = (arguments(m) ∪ [x]) ∩ part
    setdiff!(part, newargs)

    theModule = getmodule(m)
    m_init = Model(theModule, newargs, NamedTuple(), NamedTuple(), nothing)
    m = foldl(part; init=m_init) do m0,v
        merge(m0, Model(theModule, findStatement(m, v)))
    end
end

predictive(m::Model, x::Symbol, xs...) = predictive(predictive(m,x), xs...)

export predict

function predict(d::JointDistribution, post::Vector{NamedTuple{N,T}}) where {N,T}
    args = d.args
    m = d.model
    pred = predictive(m, keys(post[1])...)
    map(nt -> rand(pred(merge(args,nt))), post)
end

function predict(m::Model, post::Vector{NamedTuple{N,T}}) where {N,T}
    pred = predictive(m, keys(post[1])...)
    map(nt -> rand(pred(nt)), post)
end

# TODO: These don't yet work properly t on particles

function predict(d::JointDistribution, post::NamedTuple{N,T}) where {N,T}
    args = d.args
    m = d.model
    pred = predictive(m, keys(post)...)
    rand(pred(merge(args,post)))
end

function predict(m::Model, post::NamedTuple{N,T}) where {N,T}
    pred = predictive(m, keys(post)...)
    rand(pred(post))
end

predict(m::Model; kwargs...) = predict(m,(;kwargs...))


text:
struct LineSearchOptions
    sufficient_decrease::Float64
    curvature::Float64
    max_iter::Int
end

function LineSearchOptions(; sufficient_decrease = 1e-4, curvature = 0.1, max_iter = 100)
    LineSearchOptions(sufficient_decrease, curvature, max_iter)
end

function line_search(
    fcn,
    x0,
    step_direction,
    f0 = fcn(x0),
    search_options::LineSearchOptions = LineSearchOptions())
# suff_decrease = 1e-4, curvature = 0.1, max_iter = 100)

    # rename for ease of refactoring
    suff_decrease = search_options.sufficient_decrease
    curvature     = search_options.curvature
    max_iter      = search_options.max_iter

    # strong wolfe condition
    step_size_prev = zero(eltype(x0))
    step_size      = one(eltype(x0))
    step_size_lo   = step_size_prev
    step_size_hi   = step_size_prev
    f_prev         = NaN
    dphi0          = numder.directional_diff_fw(fcn, x0, step_direction)

    # bracket phase
    for iter = 1:max_iter

        f1 = fcn(x0 + step_direction * step_size)
        if f1 > f0 + suff_decrease * step_size * dphi0 || (iter > 1 && f1 >= f_prev)
            step_size_lo, step_size_hi = step_size_prev, step_size
            break
        end

        dphi = numder.directional_diff_fw(fcn, x0 + step_direction * step_size, step_direction)
        if abs(dphi) <= abs(dphi0) * curvature
            return step_size
        elseif dphi >= 0
            step_size_lo, step_size_hi = step_size, step_size_prev
            break
        end

        f_prev = f1
        step_size_prev, step_size = step_size, step_size * 2
    end

    # zoom phase
    f_lo = fcn(x0 + step_size_lo * step_direction)
    for iter = 1:max_iter
        step_size = 0.5 * (step_size_lo + step_size_hi)
        f1 = fcn(x0 + step_size * step_direction)
        if f1 > f0 + suff_decrease * step_size * dphi0 || f1 >= f_lo
            step_size_hi = step_size
        else
            dphi = numder.directional_diff_fw(fcn, x0 + step_direction * step_size, step_direction)
            if abs(dphi) <= abs(dphi0) * curvature
                return step_size
            elseif dphi * (step_size_hi - step_size_lo) >= 0
                step_size_hi = step_size_lo
            end
            step_size_lo = step_size
        end

    end

    return step_size
end

#=
function armijo_backtracking(fcn, x0, direction, f0 = fcn(x0), alpha_0 = 1, step_factor = 0.5, max_iteration = 20, beta = 1e-4)
    # sufficient decrease condition shall be satisfied
    phi_0 = f0
    dphi_dalpha_0 = NumDiff.directional_diff_fw(fcn, x0, direction)

    alpha = alpha_0
    for iter = 1:max_iteration
        phi_alpha = fcn( x0 + direction .* alpha)
        if phi_alpha <= phi_0 + beta * alpha * phi_alpha
            break
        end
        alpha = alpha * step_factor
    end
end
=#

max_stars_repo_name: HomoModelicus/julia

max_issues_repo_name: HomoModelicus/julia

max_forks_repo_name: HomoModelicus/julia


text:
function make_epileptor(weights)
    a = 1.0f0
    b = 3.0f0
    c = 1.0f0
    d = 5.0f0
    r = 0.00015f0
    s = 4.0f0
    Iext = 3.1f0
    slope = 0.0f0
    Iext2 = 0.45f0
    tau = 10.0f0
    aa = 6.0f0
    bb = 2.0f0
    Kvf = 0.0f0
    Kf = 0.01f0
    Ks = 0.01f0
    tt = 1.0f0
    modification = 0.0f0
    x0 = -2f0
    weights = Float32.(weights)

    function node(i,ydot,y,p,t,c_pop1,c_pop2)
        if y[1] < 0.0
            ydot[i,1] = - a * y[1] ^ 2 + b * y[1]
        else
            ydot[i,1] = slope - y[3] + 0.6 * (y[3] - 4.0) ^ 2
        end
        ydot[i,1] = tt * (y[2] - y[3] + Iext + Kvf * c_pop1 + ydot[i,1] * y[1])
        ydot[i,2] = tt * (c - d * y[1] ^ 2 - y[2])

        # energy
        if y[3] < 0.0
            ydot[i,3] = - 0.1 * y[3] ^ 7
        else
            ydot[i,3] = 0.0
        end
        if modification>0
            h =  x0 + 3/(1 + exp(-(y[1]+0.5)/0.1))
        else
            h = 4 * (y[1] - x0) + ydot[i,3]
        end
        ydot[i,3] = tt * (r * (h - y[3]  + Ks * c_pop1))

        # population 2
        ydot[i,4] = tt * (-y[5] + y[4] - y[4] ^ 3 + Iext2 + bb * y[6] - 0.3 * (y[3] - 3.5) + Kf * c_pop2)
        if y[4] < -0.25
            ydot[i,5] = 0.0
        else
            ydot[i,5] = aa * (y[4] + 0.25)
        end
        ydot[i,5] = tt * ((-y[5] + ydot[i,5]) / tau)

        # filter
        ydot[i,6] = tt * (-0.01 * (y[6] - 0.1 * y[1]))
    end

    function network(ydot,y,p,t)
        c_pop1 = dropdims(sum(weights .* (y[:,1] .- y[:,1]'); dims=2); dims=2)
        c_pop2 = dropdims(sum(weights .* (y[:,4] .- y[:,4]'); dims=2); dims=2)
        for i=1:size(weights,1)
            node(i,ydot,y[i,:],p,t,c_pop1[i],c_pop2[i])
        end
    end

    return network
end


text:
using Interpolations

f = [0 0 .1 .2  .25  .2 .25 .3 .35 .43 .45 .5 .55  .5 .4 .425 .45 .425 .4 .35 .3 .25 .225 .2 .1 0 0];
g = [0 0 .025 .1  .2  .175 .2 .25 .25 .3 .32 .35 .375  .325 .3 .275 .275 .25 .225 .225 .2 .175 .15 .15 .05 0 0].- 0.025;

x = 0.1 * (1:length(f));
xf = .01:.01:last(x)

ff = scale(interpolate(f, BSpline(Cubic(Line(OnGrid())))), x)


text:
using SIMDAlignment
using Bio.Seq
using Bio.Align
using Base.Test

function make_submat{score_t}(::Type{score_t})
    submat = Matrix{score_t}(4, 4)
    fill!(submat, -6)
    submat[diagind(submat)] = 0
    return submat
end

function test_same_seqs{score_t}(::Type{score_t})
    submat = make_submat(score_t)
    gap_open = 5
    gap_extend = 3

    seq = seq_t([0x00, 0x01, 0x02, 0x03])
    for n in 1:100
        refs = seq_t[]
        for _ in 1:n
            push!(refs, [0x00, 0x01, 0x02, 0x03])
        end
        alns = paralign_score(submat, gap_open, gap_extend, seq, refs)
        for aln in alns
            @test score(aln) == 0
        end
    end
end

function test_empty_seq{score_t}(::Type{score_t})
    seq = dna""
    refs = [
        dna"A",
        dna"AC",
        dna""
    ]
    submat = make_submat(score_t)
    model = AffineGapScoreModel(submat, gap_open_penalty=5, gap_extend_penalty=3)

    refs′ = [convert(seq_t, ref) for ref in refs]
    alns = paralign_score(submat, model.gap_open_penalty, model.gap_extend_penalty, seq, refs′)
    for i in 1:length(refs)
        ref = refs[i]
        aln = alns[i]
        aln′ = pairalign(GlobalAlignment(), seq, ref, model)
        @test score(aln) == score(aln′)
    end
end

function test_various_seqs{score_t}(::Type{score_t})
    seq = dna"ACGT"
    refs = [
        dna"ACGT",
        dna"ACGG",
        dna"AACGT",
        dna"ACGTT",
        dna"ACATG",
        dna"AACGT",
        dna"AACGTG",
        dna"AACCTG",
        dna"AACCTGA",
        dna"ACG",
        dna"ACT",
        dna"AGT",
        dna"AGG",
        dna"CGT",
        dna"CCT",
        dna"CT",
        dna"C",
        dna"",
        dna"AACCTGA"[2:5],
        dna"AACCTGA"[2:6],
    ]

    submat = make_submat(score_t)
    model = AffineGapScoreModel(submat, gap_open_penalty=5, gap_extend_penalty=3)

    refs′ = [convert(seq_t, ref) for ref in refs]
    alns = paralign_score(submat, model.gap_open_penalty, model.gap_extend_penalty, seq, refs′)

    for i in 1:length(refs)
        ref = refs[i]
        aln = alns[i]
        aln′ = pairalign(GlobalAlignment(), seq, ref, model)
        @test score(aln) == score(aln′)
    end
end

function test_reversed_seqs{score_t}(::Type{score_t})
    seq = dna"ACGTAT"
    refs = [
        dna"TATGCA",
        dna"ACGTAT",
        dna"ATTGA",
        dna"",
    ]

    submat = make_submat(score_t)
    model = AffineGapScoreModel(submat, gap_open_penalty=5, gap_extend_penalty=3)
    refs′ = [seq_t(ref, true) for ref in refs]
    alns = paralign_score(submat, model.gap_open_penalty, model.gap_extend_penalty, seq, refs′)

    for i in 1:length(refs)
        ref = reverse(refs[i])
        aln = alns[i]
        aln′ = pairalign(GlobalAlignment(), seq, ref, model)
        @test score(aln) == score(aln′)
    end
end

# run tests
for score_t in (Int8, Int16, Int32)
    test_same_seqs(score_t)
    test_empty_seq(score_t)
    test_various_seqs(score_t)
end


text:
function solve()
    m, h = [parse(Int, x) for x in split(readline())]
    h % m == 0 ? "Yes" : "No"
end

println(solve())

max_stars_repo_name: aishikawa/atcoder-julia

max_issues_repo_name: aishikawa/atcoder-julia

max_forks_repo_name: aishikawa/atcoder-julia


text:
"""
    BlindPolicySolver <: Solver
POMDP solver for solving a blind policy, which selects the same action regardless of the current belief state.
"""
mutable struct BlindPolicySolver <: Solver
    max_iterations::Int64
    tolerance::Float64
    verbose::Bool
end
function BlindPolicySolver(;max_iterations::Int64=100, tolerance::Float64=1e-3, verbose::Bool=false)
    return BlindPolicySolver(max_iterations, tolerance, verbose)
end

function POMDPs.solve(solver::BlindPolicySolver, pomdp::POMDP)
    S = ordered_states(pomdp)
    A = ordered_actions(pomdp)

    ns = length(S)
    na = length(A)

    γ = discount(pomdp)

    # best action worst state lower bound
    α_init = 1 / (1 - γ) * maximum(minimum(reward(pomdp, s, a, sp) for s in S for sp in S) for a in A)
    Γ = fill(α_init, ns, na)

    for i = 1:solver.max_iterations
        residual = 0.0
        for (ai, a) in enumerate(A)
            for (si, s) in enumerate(S)

                sp_dist = transition(pomdp, s, a)

                r = 0.0
                for (sp, p_sp) in weighted_iterator(sp_dist)
                    r += p_sp * (reward(pomdp, s, a, sp) + γ * Γ[stateindex(pomdp, sp), ai])
                end

                alpha_diff = abs(Γ[si, ai] - r)
                Γ[si, ai] = r
                residual = max(alpha_diff, residual)
            end
        end
        solver.verbose ? @printf("[Iteration %-4d] residual: %10.3G \n", i, residual) : nothing
        residual < solver.tolerance ? break : nothing
    end

    return AlphaVectorPolicy(pomdp, Γ, A)
end


text:
# This file imports, 'expands' and exports a handpicked set of units and derived dimensions.
# 'Expands' meaning that exponents -4 to 4 are also defined as symbols, where applicable.
const global mechanical_si_prefixes = (:n, :μ, :μ, :m, :c, :d, Symbol(""), :k, :M, :G, :T, :P)
const global exclude_import = (:ng, :μg, :μg, :g, :dg, :Mg, :Gg, :Tg, :Pg,
                              :cs, :ds, :ks, :Ms, :Gs, :Ts, :Ps,
                              )
"""
A list of available unit symbols. All are exported by default, which means that some may
crash with symbols defined. One way to solve such issues is importing just what you need:
```example
import MechanicalUnits: kg, m
```
"""
const global MECH_UNITS = Vector{Symbol}()
# units with standard prefixes
@import_expand ~m ~s ~g
@import_expand rad ° K Ra
@import_expand minute d atm bar
# units with a small set of prefixes
@import_expand N daN kN MN GN
@import_expand Pa kPa MPa GPa
@import_expand J kJ MJ GJ
# In order to avoid awkwardness like 'm∙N', we define the product as its own unit.
# It is used to represent a moment, rather than energy.
begin
    @unit Nmm     "Nmm"     NewtonMilliMeter  (1//1000)N*m false
    @unit Nm     "Nm"       NewtonMeter      (1//1)N*m false
    @unit daNm   "daNm"     dekaNewtonMeter  (10//1)N*m false
    @unit kNm    "kNm"      kiloNewtonMeter  (1000//1)N*m false
    @unit MNm    "MNm"      MegaNewtonMeter  (1000000//1)N*m false
    @unit GNm    "GNm"      GigaNewtonMeter  (1000000000//1)N*m false
    push!(MECH_UNITS, :Nmm)
    push!(MECH_UNITS, :Nm)
    push!(MECH_UNITS, :daNm)
    push!(MECH_UNITS, :kNm)
    push!(MECH_UNITS, :MNm)
    push!(MECH_UNITS, :GNm)
    export Nmm, Nm, daNm, kNm, MNm, GNm
    eval(exponents_superscripts(:Nmm))
    eval(exponents_superscripts(:Nm))
    eval(exponents_superscripts(:daNm))
    eval(exponents_superscripts(:kNm))
    eval(exponents_superscripts(:MNm))
    eval(exponents_superscripts(:GNm))
end

# U.S. units
@import_expand inch ft lb lbf
# affine units
@import_affine_from_Unitfu °C °F
abbr(::genericunit(°C)) = "°C"
abbr(::genericunit(°F)) = "°F"
# preferred capitalization units
begin
    @unit h      "h"       hour        (3600//1)s false
    push!(MECH_UNITS, :h)
    export h
    eval(exponents_superscripts(:h))
end
begin
    @unit yr     "yr"      JulianYear  (31557600//1)s false
    push!(MECH_UNITS, :yr)
    export yr
    eval(exponents_superscripts(:yr))
end

begin
    @unit l     "l"      liter  (1//1000)m³ false
    push!(MECH_UNITS, :l)
    export l
    eval(exponents_superscripts(:l))
end

begin
    @unit dl     "dl"      DesiLiter  (1//10000)m³ false
    push!(MECH_UNITS, :dl)
    export dl
    eval(exponents_superscripts(:dl))
end

begin
    @unit cl     "cl"      CentiLiter  (1//100000)m³ false
    push!(MECH_UNITS, :cl)
    export cl
    eval(exponents_superscripts(:cl))
end

begin
    @unit ml     "ml"      MilliLiter  (1//1000000)m³ false
    push!(MECH_UNITS, :ml)
    export ml
    eval(exponents_superscripts(:ml))
end

begin
    @unit g     "g"      "StandardGravity"  9.80665m/s² false
    push!(MECH_UNITS, :g)
    export g
    eval(exponents_superscripts(:g))
end

begin
    @unit kip     "kip"      "KiloPoundForce"  1000lbf false
    push!(MECH_UNITS, :kip)
    export kip
    eval(exponents_superscripts(:kip))
end

begin
    @unit shton     "shton"      "ShortTon"  2000lb false
    push!(MECH_UNITS, :shton)
    export shton
    eval(exponents_superscripts(:shton))
end

@show MECH_UNITS

# Define derived dimensions promotions
#= example
[100000.0N 10daN]
1×2 Array{Float64{kN},2}:
 100.0  0.1
=#

Unitfu.promote_unit(::S, ::T) where
{S<:ForceFreeUnits, T<:ForceFreeUnits} = kN

#= example
[10N/mm^2 100000000N/m^2]
1×2 Array{Rational{Int64}{MPa},2}:
(10//1)  (100//1)
=#
Unitfu.promote_unit(::S, ::T) where
{S<:PressureFreeUnits, T<:PressureFreeUnits} = MPa

#= example
[10000000N*mm 1000.0J]
1×2 Array{Float64{kNm},2}:
 10.0  1.0
=#
Unitfu.promote_unit(::S, ::T) where
{S<:EnergyFreeUnits, T<:EnergyFreeUnits} = kNm

#= example
[1.0kg/mm³ 2kg/m/m/m]

1×2 Array{Float64{cm²},2}:
 1000.0  100.0
=#
Unitfu.promote_unit(::S, ::T) where
{S<:AreaFreeUnits, T<:AreaFreeUnits} = cm²

#= example
 [1.0mg/mm³ 2kg/m/m/m]
1×2 Array{Float64{kg∙m^-3},2}:
 1000.0  2.0
=#
Unitfu.promote_unit(::S, ::T) where
{S<:DensityFreeUnits, T<:DensityFreeUnits} = kg/m³

#= example
[1/12*100mm*40mm^3/50mm 1l]
1×2 Array{Float64{cm³},2}:
 0.00666667  1000.0
=#
Unitfu.promote_unit(::S, ::T) where
{S<:VolumeFreeUnits, T<:VolumeFreeUnits} = cm³

max_stars_repo_name: hustf/MechanicalUnits

max_issues_repo_name: hustf/MechanicalUnits


text:
#    Problem :
#    *********
#    The Dixon-Maany test problem (version B)
#
#    Origonal SIF Source:
#    L.C.W. Dixon and Z. Maany,
#    "A family of test problems with sparse Hessians for unconstrained
#    optimization",
#    TR 206, Numerical Optimization Centre, Hatfield Polytechnic, 1988.
#
# 	 See also Buckley#221 (p. 49)
#
#    DIXMAANB.SIF classification OUR2-AN-V-0
#
#    M is equal to the third of the number of variables (N is divisible by 3)
#
# Daniel Henderson, 08/2021

f = (x) -> begin
	n = lastindex(x)
	m = Int(n/3)
	fx = 1.0
	α = 1.0
	Β = 0.0625
	γ = 0.0625
	δ = 0.0625
	E = [0, 0, 0, 0]
	fx += sum(α*x[i]^2*(i/n)^E[1] for i in 1:n)							# S1
	fx += sum(Β*x[i]^2*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2] for i in 1:n-1)   # S2
	fx += sum(γ*x[i]^2*x[i+m]^4*(i/n)^E[3] for i in 1:Int(2*m))   		# S3
	fx += sum(δ*x[i]*x[i+2m]*(i/n)^E[4] for i in 1:m) 					# S4
    return fx
end

g! = (g, x) -> begin
	n = lastindex(x)
	m = Int(n/3)
	α = 1.0
	Β = 0.0625
	γ = 0.0625
	δ = 0.0625
	E = [0, 0, 0, 0]

	# S1 := ∑ α*x[i]^2*(i/n)^E[1] for i in 1:n
	for i in 1:n
		g[i] += 2*α*x[i]*(i/n)^E[1]
	end

	# S2 := ∑ Β*x[i]^2*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2] for i in 1:n-1
	for i in 1:n-1
		g[i]   += 2*Β*x[i]*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2]
		g[i+1] += 2*Β*x[i]^2*(x[i+1]+x[i+1]^2)*(i/n)^E[2]*(1+2x[i+1])
	end

	# S3 := ∑ γ*x[i]^2*x[i+m]^4*(i/n)^E[3] for i in 1:Int(2*m)
	for i in 1:Int(2*m)
		g[i]   += 2*γ*x[i]*x[i+m]^4*(i/n)^E[3]
		g[i+m] += 4*γ*x[i]^2*x[i+m]^3*(i/n)^E[3]
	end

	#S4 := ∑ δ*x[i]*x[i+2m]*(i/n)^E[4] for i in 1:m
	for i in 1:m
		g[i]    += δ*x[i+2m]*(i/n)^E[4]
		g[i+2m] += δ*x[i]*(i/n)^E[4]
	end
	return g
end

fg! = (g, x) -> begin
	n = lastindex(x)
	m = Int(n/3)
	fx = 1.0
	α = 1.0
	Β = 0.0625
	γ = 0.0625
	δ = 0.0625
	E = [0, 0, 0, 0]

	# S1 := ∑ α*x[i]^2*(i/n)^E[1] for i in 1:n
	for i in 1:n
		g[i] += 2*α*x[i]*(i/n)^E[1]
		fx   += α*x[i]^2*(i/n)^E[1]
	end

	# S2 := ∑ Β*x[i]^2*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2] for i in 1:n-1
	for i in 1:n-1
		g[i]   += 2*Β*x[i]*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2]
		g[i+1] += 2*Β*x[i]^2*(x[i+1]+x[i+1]^2)*(i/n)^E[2]*(1+2x[i+1])
		fx     += Β*x[i]^2*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2]
	end

	# S3 := ∑ γ*x[i]^2*x[i+m]^4*(i/n)^E[3] for i in 1:Int(2*m)
	for i in 1:Int(2*m)
		g[i]   += 2*γ*x[i]*x[i+m]^4*(i/n)^E[3]
		g[i+m] += 4*γ*x[i]^2*x[i+m]^3*(i/n)^E[3]
		fx     += γ*x[i]^2*x[i+m]^4*(i/n)^E[3]
	end

	#S4 := ∑ δ*x[i]*x[i+2m]*(i/n)^E[4] for i in 1:m
	for i in 1:m
		g[i]    += δ*x[i+2m]*(i/n)^E[4]
		g[i+2m] += δ*x[i]*(i/n)^E[4]
		fx      += δ*x[i]*x[i+2m]*(i/n)^E[4]
	end
	return fx, g
end

@warn "TODO: Clean up DIXMAANB (and others) implementation. See comment block"

init = (n::Int=3000) -> begin
	mod(n, 3) > 0 && @warn "DIXMAANB: number of variables must be divisible by 3"
	q = max(1, div(n, 3))
	n = 3*q

	x0 = 2.0*ones(n)
    return n, x0
end

TestSet["DIXMAANB"] = UncProgram("DIXMAANB", f, g!, fg!, init)

# A cleaner implmentation might look like this: (issues rebasing S2, g[n] and g[m] need to be fixed)
# function g!(x, g)
# 	n = lastindex(x)
# 	m = Int(n/3)
# 	fx = 1.0
# 	α = 1.0
# 	Β = 0.0625
# 	γ = 0.0625
# 	δ = 0.0625
# 	E = [0, 0, 0, 0]
# 	for i in 1:m
# 		# S1 := ∑ α*x[i]^2*(i/n)^E[1] for i in 1:n
# 		g[i]    += 2*α*x[i]*(i/n)^E[1]
# 		g[i+m]  += 2*α*x[i]*(i/n)^E[1]
# 		g[i+2m] += 2*α*x[i]*(i/n)^E[1]

# 		# S2 := ∑ Β*x[i]^2*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2] for i in 1:n-1
# 		g[i]    += 2*Β*x[i]*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2]
# 		g[i+m]  += 2*Β*x[i]*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2]
# 		g[i+2m] += 2*Β*x[i]*(x[i+1]+x[i+1]^2)^2*(i/n)^E[2]
# 		g[i]    += 2*Β*x[i-1]^2*(x[i]+x[i]^2)*((i-1)/n)^E[2]*(1+2x[i])
# 		g[i+m]  += 2*Β*x[i-1]^2*(x[i]+x[i]^2)*((i-1)/n)^E[2]*(1+2x[i])
# 		g[i+2m] += 2*Β*x[i-1]^2*(x[i]+x[i]^2)*((i-1)/n)^E[2]*(1+2x[i])

# 		# S3 := ∑ γ*x[i]^2*x[i+m]^4*(i/n)^E[3] for i in 1:Int(2*m)
# 		g[i]    += 2*γ*x[i]*x[i+m]^4*(i/n)^E[3]
# 		g[i+m]  += 2*γ*x[i]*x[i+m]^4*(i/n)^E[3]
# 		g[i+m]  += 4*γ*x[i]^2*x[i+m]^3*(i/n)^E[3]
# 		g[i+2m] += 4*γ*x[i]^2*x[i+m]^3*(i/n)^E[3]

# 		#S4 := ∑ δ*x[i]*x[i+2m]*(i/n)^E[4] for i in 1:m
# 		g[i]    += δ*x[i+2m]*(i/n)^E[4]
# 		g[i+2m] += δ*x[i]*(i/n)^E[4]
# 	end
# 	g[1] = 2*α*x[1]*n^(-E[1]) + 2*Β*x[1]*(x[2]+x[2]^2)^2*n^(-E[2]) + 2*γ*x[1]*x[1+m]^4*n^(-E[3]) + δ*x[2m+1]*n^(-E[4])
# 	g[n] -= 2*Β*x[n-1]^2*(x[n]+x[n]^2)*((n-1)/n)^E[2]*(1+2x[n])
# 	return g
# end


text:
using BinaryBuilder

name = "Glibc"
version = v"2.29"

# sources to build, such as glibc, linux kernel headers, our patches, etc....
sources = [
    ArchiveSource("https://mirrors.kernel.org/gnu/glibc/glibc-$(version.major).$(version.minor).tar.xz",
                  "f3eeb8d57e25ca9fc13c2af3dae97754f9f643bc69229546828e3a240e2af04b"),
    DirectorySource("./bundled"),
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/glibc-*/

# patch for avoiding linking in musl libs for a glibc-linked binary
atomic_patch -p1 $WORKSPACE/srcdir/patches/glibc_musl_rejection.patch

# Patch to fix u_char_t definition problems
atomic_patch -p1 $WORKSPACE/srcdir/patches/glibc_sunrpc_uchar.patch

mkdir -p $WORKSPACE/srcdir/glibc_build
cd $WORKSPACE/srcdir/glibc_build
$WORKSPACE/srcdir/glibc-*/configure --prefix=/usr \
	--host=${target} \
	--disable-multilib \
	--disable-werror

make -j${nproc}

# Install to the main prefix and also to the sysroot.
make install install_root=${prefix}
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = [p for p in supported_platforms() if libc(p) == "glibc"]

# The products that we will ensure are always built
products = [
    LibraryProduct("libc", :libc; dont_dlopen=true),
    LibraryProduct("libdl", :libld; dont_dlopen=true),
    LibraryProduct("libm", :libm; dont_dlopen=true),
    LibraryProduct("libpthread", :libpthread; dont_dlopen=true),
    LibraryProduct("librt", :librt; dont_dlopen=true),
]

# Dependencies that must be installed before this package can be built
dependencies = [
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; skip_audit=true, preferred_gcc_version=v"8")

max_stars_repo_name: blenessy/Yggdrasil

max_issues_repo_name: blenessy/Yggdrasil

max_forks_repo_name: blenessy/Yggdrasil


text:
### A Pluto.jl notebook ###
# v0.12.7

using Markdown
using InteractiveUtils

# ╔═╡ de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec
using Pkg, DrWatson

# ╔═╡ e4eeb13a-1ee4-11eb-0113-91f9a9c3b659
begin
	@quickactivate "StatisticsWithJuliaPlutoNotebooks"
	using Random, DataFrames
	Random.seed!(1)
end;

# ╔═╡ ac3ceabe-1ee4-11eb-3935-313e96aafd62
md"## Listing 2.12"

# ╔═╡ ab1ec376-1f63-11eb-3eb3-d7f282f2ad65
begin
	N = 10^5
	prob1 = 0.7
	eps0, eps1 = 0.1, 0.05
end

# ╔═╡ faad978c-1f63-11eb-189c-bf9767f58cae
flipWithProb(bit,prob) = rand() < prob ? xor(bit,1) : bit

# ╔═╡ faade49e-1f63-11eb-3c17-5f937cb796ca
begin
	TxData = rand(N) .< prob1
	RxData = [x == 0 ? flipWithProb(x,eps0) : flipWithProb(x,eps1) for x in TxData]

	numTx1 = 0
	totalRx1 = 0
	for i in 1:N
	   if RxData[i] == 1
			global totalRx1 += 1
			global numTx1 += TxData[i]
		end
	end
end

# ╔═╡ faae7008-1f63-11eb-2811-914bae0ac42d
monteCarlo = numTx1/totalRx1

# ╔═╡ fabb6902-1f63-11eb-1a72-c3d127ec17c2
analytic = ((1-eps1)*0.7)/((1-eps1)*0.7+0.3*eps0)

# ╔═╡ fabbef8a-1f63-11eb-2122-3791b9449669
Text("Monte Carlo: $monteCarlo Analytic: $analytic")

# ╔═╡ ea086874-1eeb-11eb-2cb0-4186697d4294
md"## End of listing 2.12"

# ╔═╡ Cell order:
# ╟─ac3ceabe-1ee4-11eb-3935-313e96aafd62
# ╠═de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec
# ╠═e4eeb13a-1ee4-11eb-0113-91f9a9c3b659
# ╠═ab1ec376-1f63-11eb-3eb3-d7f282f2ad65
# ╠═faad978c-1f63-11eb-189c-bf9767f58cae
# ╠═faade49e-1f63-11eb-3c17-5f937cb796ca
# ╠═faae7008-1f63-11eb-2811-914bae0ac42d
# ╠═fabb6902-1f63-11eb-1a72-c3d127ec17c2
# ╠═fabbef8a-1f63-11eb-2122-3791b9449669
# ╟─ea086874-1eeb-11eb-2cb0-4186697d4294


text:
using CUDA
using MadNLPTests

function _compare_gpu_with_cpu(n, m, ind_fixed)
    madnlp_options = Dict{Symbol, Any}(
        :kkt_system=>MadNLP.DENSE_KKT_SYSTEM,
        :linear_solver=>MadNLPLapackGPU,
        :print_level=>MadNLP.ERROR,
    )

    nlp = MadNLPTests.DenseDummyQP(; n=n, m=m, fixed_variables=ind_fixed)

    h_ips = MadNLP.InteriorPointSolver(nlp; option_dict=copy(madnlp_options))
    MadNLP.optimize!(h_ips)

    # Reinit NonlinearProgram to avoid side effect
    ind_cons = MadNLP.get_index_constraints(nlp)
    ns = length(ind_cons.ind_ineq)

    # Init KKT on the GPU
    TKKTGPU = MadNLP.DenseKKTSystem{Float64, CuVector{Float64}, CuMatrix{Float64}}
    opt = MadNLP.Options(; madnlp_options...)
    # Instantiate Solver with KKT on the GPU
    d_ips = MadNLP.InteriorPointSolver{TKKTGPU}(nlp, opt; option_linear_solver=copy(madnlp_options))
    MadNLP.optimize!(d_ips)

    # Check that both results match exactly
    @test h_ips.cnt.k == d_ips.cnt.k
    @test h_ips.obj_val ≈ d_ips.obj_val atol=1e-10
    @test h_ips.x ≈ d_ips.x atol=1e-10
    @test h_ips.l ≈ d_ips.l atol=1e-10
end

@testset "MadNLP: dense versus sparse" begin
    @testset "Size: ($n, $m)" for (n, m) in [(10, 0), (10, 5), (50, 10)]
        _compare_gpu_with_cpu(n, m, Int[])
    end
    @testset "Fixed variables" begin
        n, m = 10, 5
        _compare_gpu_with_cpu(10, 5, Int[1, 2])
    end
end