text:
# Julia wrapper for header: /home/jpsamaroo/AMDGPURuntime/ext/include/hsa/hsa.h
# Automatically generated using Clang.jl wrap_c

function hsa_status_string(status, status_string)
    ccall((:hsa_status_string, "libhsa-runtime64"), hsa_status_t, (hsa_status_t, Ptr{Cstring}), status, status_string)
end

function hsa_init()
    ccall((:hsa_init, "libhsa-runtime64"), hsa_status_t, ())
end

function hsa_shut_down()
    ccall((:hsa_shut_down, "libhsa-runtime64"), hsa_status_t, ())
end

function hsa_system_get_info(attribute, value)
    ccall((:hsa_system_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_system_info_t, Ptr{Cvoid}), attribute, value)
end

function hsa_extension_get_name(extension, name)
    ccall((:hsa_extension_get_name, "libhsa-runtime64"), hsa_status_t, (UInt16, Ptr{Cstring}), extension, name)
end

function hsa_system_extension_supported(extension, version_major, version_minor, result)
    ccall((:hsa_system_extension_supported, "libhsa-runtime64"), hsa_status_t, (UInt16, UInt16, UInt16, Ptr{Bool}), extension, version_major, version_minor, result)
end

function hsa_system_major_extension_supported(extension, version_major, version_minor, result)
    ccall((:hsa_system_major_extension_supported, "libhsa-runtime64"), hsa_status_t, (UInt16, UInt16, Ptr{UInt16}, Ptr{Bool}), extension, version_major, version_minor, result)
end

function hsa_system_get_extension_table(extension, version_major, version_minor, table)
    ccall((:hsa_system_get_extension_table, "libhsa-runtime64"), hsa_status_t, (UInt16, UInt16, UInt16, Ptr{Cvoid}), extension, version_major, version_minor, table)
end

function hsa_system_get_major_extension_table(extension, version_major, table_length, table)
    ccall((:hsa_system_get_major_extension_table, "libhsa-runtime64"), hsa_status_t, (UInt16, UInt16, Csize_t, Ptr{Cvoid}), extension, version_major, table_length, table)
end

function hsa_agent_get_info(agent, attribute, value)
    ccall((:hsa_agent_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_agent_info_t, Ptr{Cvoid}), agent, attribute, value)
end

function hsa_iterate_agents(callback, data)
    ccall((:hsa_iterate_agents, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Ptr{Cvoid}), callback, data)
end

function hsa_agent_get_exception_policies(agent, profile, mask)
    ccall((:hsa_agent_get_exception_policies, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_profile_t, Ptr{UInt16}), agent, profile, mask)
end

function hsa_cache_get_info(cache, attribute, value)
    ccall((:hsa_cache_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_cache_t, hsa_cache_info_t, Ptr{Cvoid}), cache, attribute, value)
end

function hsa_agent_iterate_caches(agent, callback, data)
    ccall((:hsa_agent_iterate_caches, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{Cvoid}, Ptr{Cvoid}), agent, callback, data)
end

function hsa_agent_extension_supported(extension, agent, version_major, version_minor, result)
    ccall((:hsa_agent_extension_supported, "libhsa-runtime64"), hsa_status_t, (UInt16, hsa_agent_t, UInt16, UInt16, Ptr{Bool}), extension, agent, version_major, version_minor, result)
end

function hsa_agent_major_extension_supported(extension, agent, version_major, version_minor, result)
    ccall((:hsa_agent_major_extension_supported, "libhsa-runtime64"), hsa_status_t, (UInt16, hsa_agent_t, UInt16, Ptr{UInt16}, Ptr{Bool}), extension, agent, version_major, version_minor, result)
end

function hsa_signal_create(initial_value, num_consumers, consumers, signal)
    ccall((:hsa_signal_create, "libhsa-runtime64"), hsa_status_t, (hsa_signal_value_t, UInt32, Ptr{hsa_agent_t}, Ptr{hsa_signal_t}), initial_value, num_consumers, consumers, signal)
end

function hsa_signal_destroy(signal)
    ccall((:hsa_signal_destroy, "libhsa-runtime64"), hsa_status_t, (hsa_signal_t,), signal)
end

function hsa_signal_load_scacquire(signal)
    ccall((:hsa_signal_load_scacquire, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t,), signal)
end

function hsa_signal_load_relaxed(signal)
    ccall((:hsa_signal_load_relaxed, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t,), signal)
end

function hsa_signal_load_acquire(signal)
    ccall((:hsa_signal_load_acquire, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t,), signal)
end

function hsa_signal_store_relaxed(signal, value)
    ccall((:hsa_signal_store_relaxed, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_store_screlease(signal, value)
    ccall((:hsa_signal_store_screlease, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_store_release(signal, value)
    ccall((:hsa_signal_store_release, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_silent_store_relaxed(signal, value)
    ccall((:hsa_signal_silent_store_relaxed, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_silent_store_screlease(signal, value)
    ccall((:hsa_signal_silent_store_screlease, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_exchange_scacq_screl(signal, value)
    ccall((:hsa_signal_exchange_scacq_screl, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_exchange_acq_rel(signal, value)
    ccall((:hsa_signal_exchange_acq_rel, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_exchange_scacquire(signal, value)
    ccall((:hsa_signal_exchange_scacquire, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_exchange_acquire(signal, value)
    ccall((:hsa_signal_exchange_acquire, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_exchange_relaxed(signal, value)
    ccall((:hsa_signal_exchange_relaxed, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_exchange_screlease(signal, value)
    ccall((:hsa_signal_exchange_screlease, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_exchange_release(signal, value)
    ccall((:hsa_signal_exchange_release, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_cas_scacq_screl(signal, expected, value)
    ccall((:hsa_signal_cas_scacq_screl, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t, hsa_signal_value_t), signal, expected, value)
end

function hsa_signal_cas_acq_rel(signal, expected, value)
    ccall((:hsa_signal_cas_acq_rel, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t, hsa_signal_value_t), signal, expected, value)
end

function hsa_signal_cas_scacquire(signal, expected, value)
    ccall((:hsa_signal_cas_scacquire, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t, hsa_signal_value_t), signal, expected, value)
end

function hsa_signal_cas_acquire(signal, expected, value)
    ccall((:hsa_signal_cas_acquire, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t, hsa_signal_value_t), signal, expected, value)
end

function hsa_signal_cas_relaxed(signal, expected, value)
    ccall((:hsa_signal_cas_relaxed, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t, hsa_signal_value_t), signal, expected, value)
end

function hsa_signal_cas_screlease(signal, expected, value)
    ccall((:hsa_signal_cas_screlease, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t, hsa_signal_value_t), signal, expected, value)
end

function hsa_signal_cas_release(signal, expected, value)
    ccall((:hsa_signal_cas_release, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_value_t, hsa_signal_value_t), signal, expected, value)
end

function hsa_signal_add_scacq_screl(signal, value)
    ccall((:hsa_signal_add_scacq_screl, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_add_acq_rel(signal, value)
    ccall((:hsa_signal_add_acq_rel, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_add_scacquire(signal, value)
    ccall((:hsa_signal_add_scacquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_add_acquire(signal, value)
    ccall((:hsa_signal_add_acquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_add_relaxed(signal, value)
    ccall((:hsa_signal_add_relaxed, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_add_screlease(signal, value)
    ccall((:hsa_signal_add_screlease, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_add_release(signal, value)
    ccall((:hsa_signal_add_release, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_subtract_scacq_screl(signal, value)
    ccall((:hsa_signal_subtract_scacq_screl, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_subtract_acq_rel(signal, value)
    ccall((:hsa_signal_subtract_acq_rel, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_subtract_scacquire(signal, value)
    ccall((:hsa_signal_subtract_scacquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_subtract_acquire(signal, value)
    ccall((:hsa_signal_subtract_acquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_subtract_relaxed(signal, value)
    ccall((:hsa_signal_subtract_relaxed, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_subtract_screlease(signal, value)
    ccall((:hsa_signal_subtract_screlease, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_subtract_release(signal, value)
    ccall((:hsa_signal_subtract_release, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_and_scacq_screl(signal, value)
    ccall((:hsa_signal_and_scacq_screl, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_and_acq_rel(signal, value)
    ccall((:hsa_signal_and_acq_rel, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_and_scacquire(signal, value)
    ccall((:hsa_signal_and_scacquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_and_acquire(signal, value)
    ccall((:hsa_signal_and_acquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_and_relaxed(signal, value)
    ccall((:hsa_signal_and_relaxed, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_and_screlease(signal, value)
    ccall((:hsa_signal_and_screlease, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_and_release(signal, value)
    ccall((:hsa_signal_and_release, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_or_scacq_screl(signal, value)
    ccall((:hsa_signal_or_scacq_screl, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_or_acq_rel(signal, value)
    ccall((:hsa_signal_or_acq_rel, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_or_scacquire(signal, value)
    ccall((:hsa_signal_or_scacquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_or_acquire(signal, value)
    ccall((:hsa_signal_or_acquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_or_relaxed(signal, value)
    ccall((:hsa_signal_or_relaxed, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_or_screlease(signal, value)
    ccall((:hsa_signal_or_screlease, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_or_release(signal, value)
    ccall((:hsa_signal_or_release, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_xor_scacq_screl(signal, value)
    ccall((:hsa_signal_xor_scacq_screl, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_xor_acq_rel(signal, value)
    ccall((:hsa_signal_xor_acq_rel, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_xor_scacquire(signal, value)
    ccall((:hsa_signal_xor_scacquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_xor_acquire(signal, value)
    ccall((:hsa_signal_xor_acquire, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_xor_relaxed(signal, value)
    ccall((:hsa_signal_xor_relaxed, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_xor_screlease(signal, value)
    ccall((:hsa_signal_xor_screlease, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_xor_release(signal, value)
    ccall((:hsa_signal_xor_release, "libhsa-runtime64"), Cvoid, (hsa_signal_t, hsa_signal_value_t), signal, value)
end

function hsa_signal_wait_scacquire(signal, condition, compare_value, timeout_hint, wait_state_hint)
    ccall((:hsa_signal_wait_scacquire, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_condition_t, hsa_signal_value_t, UInt64, hsa_wait_state_t), signal, condition, compare_value, timeout_hint, wait_state_hint)
end

function hsa_signal_wait_relaxed(signal, condition, compare_value, timeout_hint, wait_state_hint)
    ccall((:hsa_signal_wait_relaxed, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_condition_t, hsa_signal_value_t, UInt64, hsa_wait_state_t), signal, condition, compare_value, timeout_hint, wait_state_hint)
end

function hsa_signal_wait_acquire(signal, condition, compare_value, timeout_hint, wait_state_hint)
    ccall((:hsa_signal_wait_acquire, "libhsa-runtime64"), hsa_signal_value_t, (hsa_signal_t, hsa_signal_condition_t, hsa_signal_value_t, UInt64, hsa_wait_state_t), signal, condition, compare_value, timeout_hint, wait_state_hint)
end

function hsa_signal_group_create(num_signals, signals, num_consumers, consumers, signal_group)
    ccall((:hsa_signal_group_create, "libhsa-runtime64"), hsa_status_t, (UInt32, Ptr{hsa_signal_t}, UInt32, Ptr{hsa_agent_t}, Ptr{hsa_signal_group_t}), num_signals, signals, num_consumers, consumers, signal_group)
end

function hsa_signal_group_destroy(signal_group)
    ccall((:hsa_signal_group_destroy, "libhsa-runtime64"), hsa_status_t, (hsa_signal_group_t,), signal_group)
end

function hsa_signal_group_wait_any_scacquire(signal_group, conditions, compare_values, wait_state_hint, signal, value)
    ccall((:hsa_signal_group_wait_any_scacquire, "libhsa-runtime64"), hsa_status_t, (hsa_signal_group_t, Ptr{hsa_signal_condition_t}, Ptr{hsa_signal_value_t}, hsa_wait_state_t, Ptr{hsa_signal_t}, Ptr{hsa_signal_value_t}), signal_group, conditions, compare_values, wait_state_hint, signal, value)
end

function hsa_signal_group_wait_any_relaxed(signal_group, conditions, compare_values, wait_state_hint, signal, value)
    ccall((:hsa_signal_group_wait_any_relaxed, "libhsa-runtime64"), hsa_status_t, (hsa_signal_group_t, Ptr{hsa_signal_condition_t}, Ptr{hsa_signal_value_t}, hsa_wait_state_t, Ptr{hsa_signal_t}, Ptr{hsa_signal_value_t}), signal_group, conditions, compare_values, wait_state_hint, signal, value)
end

function hsa_queue_create(agent, size, type, callback, data, private_segment_size, group_segment_size, queue)
    ccall((:hsa_queue_create, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, UInt32, hsa_queue_type32_t, Ptr{Cvoid}, Ptr{Cvoid}, UInt32, UInt32, Ptr{Ptr{hsa_queue_t}}), agent, size, type, callback, data, private_segment_size, group_segment_size, queue)
end

function hsa_soft_queue_create(region, size, type, features, doorbell_signal, queue)
    ccall((:hsa_soft_queue_create, "libhsa-runtime64"), hsa_status_t, (hsa_region_t, UInt32, hsa_queue_type32_t, UInt32, hsa_signal_t, Ptr{Ptr{hsa_queue_t}}), region, size, type, features, doorbell_signal, queue)
end

function hsa_queue_destroy(queue)
    ccall((:hsa_queue_destroy, "libhsa-runtime64"), hsa_status_t, (Ptr{hsa_queue_t},), queue)
end

function hsa_queue_inactivate(queue)
    ccall((:hsa_queue_inactivate, "libhsa-runtime64"), hsa_status_t, (Ptr{hsa_queue_t},), queue)
end

function hsa_queue_load_read_index_acquire(queue)
    ccall((:hsa_queue_load_read_index_acquire, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t},), queue)
end

function hsa_queue_load_read_index_scacquire(queue)
    ccall((:hsa_queue_load_read_index_scacquire, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t},), queue)
end

function hsa_queue_load_read_index_relaxed(queue)
    ccall((:hsa_queue_load_read_index_relaxed, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t},), queue)
end

function hsa_queue_load_write_index_acquire(queue)
    ccall((:hsa_queue_load_write_index_acquire, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t},), queue)
end

function hsa_queue_load_write_index_scacquire(queue)
    ccall((:hsa_queue_load_write_index_scacquire, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t},), queue)
end

function hsa_queue_load_write_index_relaxed(queue)
    ccall((:hsa_queue_load_write_index_relaxed, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t},), queue)
end

function hsa_queue_store_write_index_relaxed(queue, value)
    ccall((:hsa_queue_store_write_index_relaxed, "libhsa-runtime64"), Cvoid, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_store_write_index_release(queue, value)
    ccall((:hsa_queue_store_write_index_release, "libhsa-runtime64"), Cvoid, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_store_write_index_screlease(queue, value)
    ccall((:hsa_queue_store_write_index_screlease, "libhsa-runtime64"), Cvoid, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_cas_write_index_acq_rel(queue, expected, value)
    ccall((:hsa_queue_cas_write_index_acq_rel, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64, UInt64), queue, expected, value)
end

function hsa_queue_cas_write_index_scacq_screl(queue, expected, value)
    ccall((:hsa_queue_cas_write_index_scacq_screl, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64, UInt64), queue, expected, value)
end

function hsa_queue_cas_write_index_acquire(queue, expected, value)
    ccall((:hsa_queue_cas_write_index_acquire, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64, UInt64), queue, expected, value)
end

function hsa_queue_cas_write_index_scacquire(queue, expected, value)
    ccall((:hsa_queue_cas_write_index_scacquire, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64, UInt64), queue, expected, value)
end

function hsa_queue_cas_write_index_relaxed(queue, expected, value)
    ccall((:hsa_queue_cas_write_index_relaxed, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64, UInt64), queue, expected, value)
end

function hsa_queue_cas_write_index_release(queue, expected, value)
    ccall((:hsa_queue_cas_write_index_release, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64, UInt64), queue, expected, value)
end

function hsa_queue_cas_write_index_screlease(queue, expected, value)
    ccall((:hsa_queue_cas_write_index_screlease, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64, UInt64), queue, expected, value)
end

function hsa_queue_add_write_index_acq_rel(queue, value)
    ccall((:hsa_queue_add_write_index_acq_rel, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_add_write_index_scacq_screl(queue, value)
    ccall((:hsa_queue_add_write_index_scacq_screl, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_add_write_index_acquire(queue, value)
    ccall((:hsa_queue_add_write_index_acquire, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_add_write_index_scacquire(queue, value)
    ccall((:hsa_queue_add_write_index_scacquire, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_add_write_index_relaxed(queue, value)
    ccall((:hsa_queue_add_write_index_relaxed, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_add_write_index_release(queue, value)
    ccall((:hsa_queue_add_write_index_release, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_add_write_index_screlease(queue, value)
    ccall((:hsa_queue_add_write_index_screlease, "libhsa-runtime64"), UInt64, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_store_read_index_relaxed(queue, value)
    ccall((:hsa_queue_store_read_index_relaxed, "libhsa-runtime64"), Cvoid, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_store_read_index_release(queue, value)
    ccall((:hsa_queue_store_read_index_release, "libhsa-runtime64"), Cvoid, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_queue_store_read_index_screlease(queue, value)
    ccall((:hsa_queue_store_read_index_screlease, "libhsa-runtime64"), Cvoid, (Ptr{hsa_queue_t}, UInt64), queue, value)
end

function hsa_region_get_info(region, attribute, value)
    ccall((:hsa_region_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_region_t, hsa_region_info_t, Ptr{Cvoid}), region, attribute, value)
end

function hsa_agent_iterate_regions(agent, callback, data)
    ccall((:hsa_agent_iterate_regions, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{Cvoid}, Ptr{Cvoid}), agent, callback, data)
end

function hsa_memory_allocate(region, size, ptr)
    ccall((:hsa_memory_allocate, "libhsa-runtime64"), hsa_status_t, (hsa_region_t, Csize_t, Ptr{Ptr{Cvoid}}), region, size, ptr)
end

function hsa_memory_free(ptr)
    ccall((:hsa_memory_free, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid},), ptr)
end

function hsa_memory_copy(dst, src, size)
    ccall((:hsa_memory_copy, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), dst, src, size)
end

function hsa_memory_assign_agent(ptr, agent, access)
    ccall((:hsa_memory_assign_agent, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, hsa_agent_t, hsa_access_permission_t), ptr, agent, access)
end

function hsa_memory_register(ptr, size)
    ccall((:hsa_memory_register, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Csize_t), ptr, size)
end

function hsa_memory_deregister(ptr, size)
    ccall((:hsa_memory_deregister, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Csize_t), ptr, size)
end

function hsa_isa_from_name(name, isa)
    ccall((:hsa_isa_from_name, "libhsa-runtime64"), hsa_status_t, (Cstring, Ptr{hsa_isa_t}), name, isa)
end

function hsa_agent_iterate_isas(agent, callback, data)
    ccall((:hsa_agent_iterate_isas, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{Cvoid}, Ptr{Cvoid}), agent, callback, data)
end

function hsa_isa_get_info(isa, attribute, index, value)
    ccall((:hsa_isa_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_isa_t, hsa_isa_info_t, UInt32, Ptr{Cvoid}), isa, attribute, index, value)
end

function hsa_isa_get_info_alt(isa, attribute, value)
    ccall((:hsa_isa_get_info_alt, "libhsa-runtime64"), hsa_status_t, (hsa_isa_t, hsa_isa_info_t, Ptr{Cvoid}), isa, attribute, value)
end

function hsa_isa_get_exception_policies(isa, profile, mask)
    ccall((:hsa_isa_get_exception_policies, "libhsa-runtime64"), hsa_status_t, (hsa_isa_t, hsa_profile_t, Ptr{UInt16}), isa, profile, mask)
end

function hsa_isa_get_round_method(isa, fp_type, flush_mode, round_method)
    ccall((:hsa_isa_get_round_method, "libhsa-runtime64"), hsa_status_t, (hsa_isa_t, hsa_fp_type_t, hsa_flush_mode_t, Ptr{hsa_round_method_t}), isa, fp_type, flush_mode, round_method)
end

function hsa_wavefront_get_info(wavefront, attribute, value)
    ccall((:hsa_wavefront_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_wavefront_t, hsa_wavefront_info_t, Ptr{Cvoid}), wavefront, attribute, value)
end

function hsa_isa_iterate_wavefronts(isa, callback, data)
    ccall((:hsa_isa_iterate_wavefronts, "libhsa-runtime64"), hsa_status_t, (hsa_isa_t, Ptr{Cvoid}, Ptr{Cvoid}), isa, callback, data)
end

function hsa_isa_compatible(code_object_isa, agent_isa, result)
    ccall((:hsa_isa_compatible, "libhsa-runtime64"), hsa_status_t, (hsa_isa_t, hsa_isa_t, Ptr{Bool}), code_object_isa, agent_isa, result)
end

function hsa_code_object_reader_create_from_file(file, code_object_reader)
    ccall((:hsa_code_object_reader_create_from_file, "libhsa-runtime64"), hsa_status_t, (hsa_file_t, Ptr{hsa_code_object_reader_t}), file, code_object_reader)
end

function hsa_code_object_reader_create_from_memory(code_object, size, code_object_reader)
    ccall((:hsa_code_object_reader_create_from_memory, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Csize_t, Ptr{hsa_code_object_reader_t}), code_object, size, code_object_reader)
end

function hsa_code_object_reader_destroy(code_object_reader)
    ccall((:hsa_code_object_reader_destroy, "libhsa-runtime64"), hsa_status_t, (hsa_code_object_reader_t,), code_object_reader)
end

function hsa_executable_create(profile, executable_state, options, executable)
    ccall((:hsa_executable_create, "libhsa-runtime64"), hsa_status_t, (hsa_profile_t, hsa_executable_state_t, Cstring, Ptr{hsa_executable_t}), profile, executable_state, options, executable)
end

function hsa_executable_create_alt(profile, default_float_rounding_mode, options, executable)
    ccall((:hsa_executable_create_alt, "libhsa-runtime64"), hsa_status_t, (hsa_profile_t, hsa_default_float_rounding_mode_t, Cstring, Ptr{hsa_executable_t}), profile, default_float_rounding_mode, options, executable)
end

function hsa_executable_destroy(executable)
    ccall((:hsa_executable_destroy, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t,), executable)
end

function hsa_executable_load_program_code_object(executable, code_object_reader, options, loaded_code_object)
    ccall((:hsa_executable_load_program_code_object, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, hsa_code_object_reader_t, Cstring, Ptr{hsa_loaded_code_object_t}), executable, code_object_reader, options, loaded_code_object)
end

function hsa_executable_load_agent_code_object(executable, agent, code_object_reader, options, loaded_code_object)
    ccall((:hsa_executable_load_agent_code_object, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, hsa_agent_t, hsa_code_object_reader_t, Cstring, Ptr{hsa_loaded_code_object_t}), executable, agent, code_object_reader, options, loaded_code_object)
end

function hsa_executable_freeze(executable, options)
    ccall((:hsa_executable_freeze, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, Cstring), executable, options)
end

function hsa_executable_get_info(executable, attribute, value)
    ccall((:hsa_executable_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, hsa_executable_info_t, Ptr{Cvoid}), executable, attribute, value)
end

function hsa_executable_global_variable_define(executable, variable_name, address)
    ccall((:hsa_executable_global_variable_define, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, Cstring, Ptr{Cvoid}), executable, variable_name, address)
end

function hsa_executable_agent_global_variable_define(executable, agent, variable_name, address)
    ccall((:hsa_executable_agent_global_variable_define, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, hsa_agent_t, Cstring, Ptr{Cvoid}), executable, agent, variable_name, address)
end

function hsa_executable_readonly_variable_define(executable, agent, variable_name, address)
    ccall((:hsa_executable_readonly_variable_define, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, hsa_agent_t, Cstring, Ptr{Cvoid}), executable, agent, variable_name, address)
end

function hsa_executable_validate(executable, result)
    ccall((:hsa_executable_validate, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, Ptr{UInt32}), executable, result)
end

function hsa_executable_validate_alt(executable, options, result)
    ccall((:hsa_executable_validate_alt, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, Cstring, Ptr{UInt32}), executable, options, result)
end

function hsa_executable_get_symbol(executable, module_name, symbol_name, agent, call_convention, symbol)
    ccall((:hsa_executable_get_symbol, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, Cstring, Cstring, hsa_agent_t, Int32, Ptr{hsa_executable_symbol_t}), executable, module_name, symbol_name, agent, call_convention, symbol)
end

function hsa_executable_get_symbol_by_name(executable, symbol_name, agent, symbol)
    ccall((:hsa_executable_get_symbol_by_name, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, Cstring, Ptr{hsa_agent_t}, Ptr{hsa_executable_symbol_t}), executable, symbol_name, agent, symbol)
end

function hsa_executable_symbol_get_info(executable_symbol, attribute, value)
    ccall((:hsa_executable_symbol_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_executable_symbol_t, hsa_executable_symbol_info_t, Ptr{Cvoid}), executable_symbol, attribute, value)
end

function hsa_executable_iterate_symbols(executable, callback, data)
    ccall((:hsa_executable_iterate_symbols, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, Ptr{Cvoid}, Ptr{Cvoid}), executable, callback, data)
end

function hsa_executable_iterate_agent_symbols(executable, agent, callback, data)
    ccall((:hsa_executable_iterate_agent_symbols, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, hsa_agent_t, Ptr{Cvoid}, Ptr{Cvoid}), executable, agent, callback, data)
end

function hsa_executable_iterate_program_symbols(executable, callback, data)
    ccall((:hsa_executable_iterate_program_symbols, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, Ptr{Cvoid}, Ptr{Cvoid}), executable, callback, data)
end

function hsa_code_object_serialize(code_object, alloc_callback, callback_data, options, serialized_code_object, serialized_code_object_size)
    ccall((:hsa_code_object_serialize, "libhsa-runtime64"), hsa_status_t, (hsa_code_object_t, Ptr{Cvoid}, hsa_callback_data_t, Cstring, Ptr{Ptr{Cvoid}}, Ptr{Csize_t}), code_object, alloc_callback, callback_data, options, serialized_code_object, serialized_code_object_size)
end

function hsa_code_object_deserialize(serialized_code_object, serialized_code_object_size, options, code_object)
    ccall((:hsa_code_object_deserialize, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Csize_t, Cstring, Ptr{hsa_code_object_t}), serialized_code_object, serialized_code_object_size, options, code_object)
end

function hsa_code_object_destroy(code_object)
    ccall((:hsa_code_object_destroy, "libhsa-runtime64"), hsa_status_t, (hsa_code_object_t,), code_object)
end

function hsa_code_object_get_info(code_object, attribute, value)
    ccall((:hsa_code_object_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_code_object_t, hsa_code_object_info_t, Ptr{Cvoid}), code_object, attribute, value)
end

function hsa_executable_load_code_object(executable, agent, code_object, options)
    ccall((:hsa_executable_load_code_object, "libhsa-runtime64"), hsa_status_t, (hsa_executable_t, hsa_agent_t, hsa_code_object_t, Cstring), executable, agent, code_object, options)
end

function hsa_code_object_get_symbol(code_object, symbol_name, symbol)
    ccall((:hsa_code_object_get_symbol, "libhsa-runtime64"), hsa_status_t, (hsa_code_object_t, Cstring, Ptr{hsa_code_symbol_t}), code_object, symbol_name, symbol)
end

function hsa_code_object_get_symbol_from_name(code_object, module_name, symbol_name, symbol)
    ccall((:hsa_code_object_get_symbol_from_name, "libhsa-runtime64"), hsa_status_t, (hsa_code_object_t, Cstring, Cstring, Ptr{hsa_code_symbol_t}), code_object, module_name, symbol_name, symbol)
end

function hsa_code_symbol_get_info(code_symbol, attribute, value)
    ccall((:hsa_code_symbol_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_code_symbol_t, hsa_code_symbol_info_t, Ptr{Cvoid}), code_symbol, attribute, value)
end

function hsa_code_object_iterate_symbols(code_object, callback, data)
    ccall((:hsa_code_object_iterate_symbols, "libhsa-runtime64"), hsa_status_t, (hsa_code_object_t, Ptr{Cvoid}, Ptr{Cvoid}), code_object, callback, data)
end
# Julia wrapper for header: /home/jpsamaroo/AMDGPURuntime/ext/include/hsa/hsa_ext_amd.h
# Automatically generated using Clang.jl wrap_c

function hsa_amd_coherency_get_type(agent, type)
    ccall((:hsa_amd_coherency_get_type, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{hsa_amd_coherency_type_t}), agent, type)
end

function hsa_amd_coherency_set_type(agent, type)
    ccall((:hsa_amd_coherency_set_type, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_amd_coherency_type_t), agent, type)
end

function hsa_amd_profiling_set_profiler_enabled(queue, enable)
    ccall((:hsa_amd_profiling_set_profiler_enabled, "libhsa-runtime64"), hsa_status_t, (Ptr{hsa_queue_t}, Cint), queue, enable)
end

function hsa_amd_profiling_async_copy_enable(enable)
    ccall((:hsa_amd_profiling_async_copy_enable, "libhsa-runtime64"), hsa_status_t, (Bool,), enable)
end

function hsa_amd_profiling_get_dispatch_time(agent, signal, time)
    ccall((:hsa_amd_profiling_get_dispatch_time, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_signal_t, Ptr{hsa_amd_profiling_dispatch_time_t}), agent, signal, time)
end

function hsa_amd_profiling_get_async_copy_time(signal, time)
    ccall((:hsa_amd_profiling_get_async_copy_time, "libhsa-runtime64"), hsa_status_t, (hsa_signal_t, Ptr{hsa_amd_profiling_async_copy_time_t}), signal, time)
end

function hsa_amd_profiling_convert_tick_to_system_domain(agent, agent_tick, system_tick)
    ccall((:hsa_amd_profiling_convert_tick_to_system_domain, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, UInt64, Ptr{UInt64}), agent, agent_tick, system_tick)
end

function hsa_amd_signal_create(initial_value, num_consumers, consumers, attributes, signal)
    ccall((:hsa_amd_signal_create, "libhsa-runtime64"), hsa_status_t, (hsa_signal_value_t, UInt32, Ptr{hsa_agent_t}, UInt64, Ptr{hsa_signal_t}), initial_value, num_consumers, consumers, attributes, signal)
end

function hsa_amd_signal_async_handler(signal, cond, value, handler, arg)
    ccall((:hsa_amd_signal_async_handler, "libhsa-runtime64"), hsa_status_t, (hsa_signal_t, hsa_signal_condition_t, hsa_signal_value_t, hsa_amd_signal_handler, Ptr{Cvoid}), signal, cond, value, handler, arg)
end

function hsa_amd_async_function(callback, arg)
    ccall((:hsa_amd_async_function, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Ptr{Cvoid}), callback, arg)
end

function hsa_amd_signal_wait_any(signal_count, signals, conds, values, timeout_hint, wait_hint, satisfying_value)
    ccall((:hsa_amd_signal_wait_any, "libhsa-runtime64"), UInt32, (UInt32, Ptr{hsa_signal_t}, Ptr{hsa_signal_condition_t}, Ptr{hsa_signal_value_t}, UInt64, hsa_wait_state_t, Ptr{hsa_signal_value_t}), signal_count, signals, conds, values, timeout_hint, wait_hint, satisfying_value)
end

function hsa_amd_image_get_info_max_dim(agent, attribute, value)
    ccall((:hsa_amd_image_get_info_max_dim, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_agent_info_t, Ptr{Cvoid}), agent, attribute, value)
end

function hsa_amd_queue_cu_set_mask(queue, num_cu_mask_count, cu_mask)
    ccall((:hsa_amd_queue_cu_set_mask, "libhsa-runtime64"), hsa_status_t, (Ptr{hsa_queue_t}, UInt32, Ptr{UInt32}), queue, num_cu_mask_count, cu_mask)
end

function hsa_amd_memory_pool_get_info(memory_pool, attribute, value)
    ccall((:hsa_amd_memory_pool_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_amd_memory_pool_t, hsa_amd_memory_pool_info_t, Ptr{Cvoid}), memory_pool, attribute, value)
end

function hsa_amd_agent_iterate_memory_pools(agent, callback, data)
    ccall((:hsa_amd_agent_iterate_memory_pools, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{Cvoid}, Ptr{Cvoid}), agent, callback, data)
end

function hsa_amd_memory_pool_allocate(memory_pool, size, flags, ptr)
    ccall((:hsa_amd_memory_pool_allocate, "libhsa-runtime64"), hsa_status_t, (hsa_amd_memory_pool_t, Csize_t, UInt32, Ptr{Ptr{Cvoid}}), memory_pool, size, flags, ptr)
end

function hsa_amd_memory_pool_free(ptr)
    ccall((:hsa_amd_memory_pool_free, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid},), ptr)
end

function hsa_amd_memory_async_copy(dst, dst_agent, src, src_agent, size, num_dep_signals, dep_signals, completion_signal)
    ccall((:hsa_amd_memory_async_copy, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, hsa_agent_t, Ptr{Cvoid}, hsa_agent_t, Csize_t, UInt32, Ptr{hsa_signal_t}, hsa_signal_t), dst, dst_agent, src, src_agent, size, num_dep_signals, dep_signals, completion_signal)
end

function hsa_amd_agent_memory_pool_get_info(agent, memory_pool, attribute, value)
    ccall((:hsa_amd_agent_memory_pool_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_amd_memory_pool_t, hsa_amd_agent_memory_pool_info_t, Ptr{Cvoid}), agent, memory_pool, attribute, value)
end

function hsa_amd_agents_allow_access(num_agents, agents, flags, ptr)
    ccall((:hsa_amd_agents_allow_access, "libhsa-runtime64"), hsa_status_t, (UInt32, Ptr{hsa_agent_t}, Ptr{UInt32}, Ptr{Cvoid}), num_agents, agents, flags, ptr)
end

function hsa_amd_memory_pool_can_migrate(src_memory_pool, dst_memory_pool, result)
    ccall((:hsa_amd_memory_pool_can_migrate, "libhsa-runtime64"), hsa_status_t, (hsa_amd_memory_pool_t, hsa_amd_memory_pool_t, Ptr{Bool}), src_memory_pool, dst_memory_pool, result)
end

function hsa_amd_memory_migrate(ptr, memory_pool, flags)
    ccall((:hsa_amd_memory_migrate, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, hsa_amd_memory_pool_t, UInt32), ptr, memory_pool, flags)
end

function hsa_amd_memory_lock(host_ptr, size, agents, num_agent, agent_ptr)
    ccall((:hsa_amd_memory_lock, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Csize_t, Ptr{hsa_agent_t}, Cint, Ptr{Ptr{Cvoid}}), host_ptr, size, agents, num_agent, agent_ptr)
end

function hsa_amd_memory_unlock(host_ptr)
    ccall((:hsa_amd_memory_unlock, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid},), host_ptr)
end

function hsa_amd_memory_fill(ptr, value, count)
    ccall((:hsa_amd_memory_fill, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, UInt32, Csize_t), ptr, value, count)
end

function hsa_amd_interop_map_buffer(num_agents, agents, interop_handle, flags, size, ptr, metadata_size, metadata)
    ccall((:hsa_amd_interop_map_buffer, "libhsa-runtime64"), hsa_status_t, (UInt32, Ptr{hsa_agent_t}, Cint, UInt32, Ptr{Csize_t}, Ptr{Ptr{Cvoid}}, Ptr{Csize_t}, Ptr{Ptr{Cvoid}}), num_agents, agents, interop_handle, flags, size, ptr, metadata_size, metadata)
end

function hsa_amd_interop_unmap_buffer(ptr)
    ccall((:hsa_amd_interop_unmap_buffer, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid},), ptr)
end

function hsa_amd_image_create(agent, image_descriptor, image_layout, image_data, access_permission, image)
    ccall((:hsa_amd_image_create, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{hsa_ext_image_descriptor_t}, Ptr{hsa_amd_image_descriptor_t}, Ptr{Cvoid}, hsa_access_permission_t, Ptr{hsa_ext_image_t}), agent, image_descriptor, image_layout, image_data, access_permission, image)
end

function hsa_amd_pointer_info(ptr, info, alloc, num_agents_accessible, accessible)
    ccall((:hsa_amd_pointer_info, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Ptr{hsa_amd_pointer_info_t}, Ptr{Cvoid}, Ptr{UInt32}, Ptr{Ptr{hsa_agent_t}}), ptr, info, alloc, num_agents_accessible, accessible)
end

function hsa_amd_pointer_info_set_userdata(ptr, userdata)
    ccall((:hsa_amd_pointer_info_set_userdata, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Ptr{Cvoid}), ptr, userdata)
end

function hsa_amd_ipc_memory_create(ptr, len, handle)
    ccall((:hsa_amd_ipc_memory_create, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid}, Csize_t, Ptr{hsa_amd_ipc_memory_t}), ptr, len, handle)
end

function hsa_amd_ipc_memory_attach(handle, len, num_agents, mapping_agents, mapped_ptr)
    ccall((:hsa_amd_ipc_memory_attach, "libhsa-runtime64"), hsa_status_t, (Ptr{hsa_amd_ipc_memory_t}, Csize_t, UInt32, Ptr{hsa_agent_t}, Ptr{Ptr{Cvoid}}), handle, len, num_agents, mapping_agents, mapped_ptr)
end

function hsa_amd_ipc_memory_detach(mapped_ptr)
    ccall((:hsa_amd_ipc_memory_detach, "libhsa-runtime64"), hsa_status_t, (Ptr{Cvoid},), mapped_ptr)
end

function hsa_amd_ipc_signal_create(signal, handle)
    ccall((:hsa_amd_ipc_signal_create, "libhsa-runtime64"), hsa_status_t, (hsa_signal_t, Ptr{hsa_amd_ipc_signal_t}), signal, handle)
end

function hsa_amd_ipc_signal_attach(handle, signal)
    ccall((:hsa_amd_ipc_signal_attach, "libhsa-runtime64"), hsa_status_t, (Ptr{hsa_amd_ipc_signal_t}, Ptr{hsa_signal_t}), handle, signal)
end
# Julia wrapper for header: /home/jpsamaroo/AMDGPURuntime/ext/include/hsa/hsa_ext_finalize.h
# Automatically generated using Clang.jl wrap_c

function hsa_ext_program_create(machine_model, profile, default_float_rounding_mode, options, program)
    ccall((:hsa_ext_program_create, "libhsa-runtime64"), hsa_status_t, (hsa_machine_model_t, hsa_profile_t, hsa_default_float_rounding_mode_t, Cstring, Ptr{hsa_ext_program_t}), machine_model, profile, default_float_rounding_mode, options, program)
end

function hsa_ext_program_destroy(program)
    ccall((:hsa_ext_program_destroy, "libhsa-runtime64"), hsa_status_t, (hsa_ext_program_t,), program)
end

function hsa_ext_program_add_module(program, _module)
    ccall((:hsa_ext_program_add_module, "libhsa-runtime64"), hsa_status_t, (hsa_ext_program_t, hsa_ext_module_t), program, _module)
end

function hsa_ext_program_iterate_modules(program, callback, data)
    ccall((:hsa_ext_program_iterate_modules, "libhsa-runtime64"), hsa_status_t, (hsa_ext_program_t, Ptr{Cvoid}, Ptr{Cvoid}), program, callback, data)
end

function hsa_ext_program_get_info(program, attribute, value)
    ccall((:hsa_ext_program_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_ext_program_t, hsa_ext_program_info_t, Ptr{Cvoid}), program, attribute, value)
end

function hsa_ext_program_finalize(program, isa, call_convention, control_directives, options, code_object_type, code_object)
    ccall((:hsa_ext_program_finalize, "libhsa-runtime64"), hsa_status_t, (hsa_ext_program_t, hsa_isa_t, Int32, hsa_ext_control_directives_t, Cstring, hsa_code_object_type_t, Ptr{hsa_code_object_t}), program, isa, call_convention, control_directives, options, code_object_type, code_object)
end
# Julia wrapper for header: /home/jpsamaroo/AMDGPURuntime/ext/include/hsa/hsa_ext_image.h
# Automatically generated using Clang.jl wrap_c

function hsa_ext_image_get_capability(agent, geometry, image_format, capability_mask)
    ccall((:hsa_ext_image_get_capability, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_ext_image_geometry_t, Ptr{hsa_ext_image_format_t}, Ptr{UInt32}), agent, geometry, image_format, capability_mask)
end

function hsa_ext_image_get_capability_with_layout(agent, geometry, image_format, image_data_layout, capability_mask)
    ccall((:hsa_ext_image_get_capability_with_layout, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_ext_image_geometry_t, Ptr{hsa_ext_image_format_t}, hsa_ext_image_data_layout_t, Ptr{UInt32}), agent, geometry, image_format, image_data_layout, capability_mask)
end

function hsa_ext_image_data_get_info(agent, image_descriptor, access_permission, image_data_info)
    ccall((:hsa_ext_image_data_get_info, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{hsa_ext_image_descriptor_t}, hsa_access_permission_t, Ptr{hsa_ext_image_data_info_t}), agent, image_descriptor, access_permission, image_data_info)
end

function hsa_ext_image_data_get_info_with_layout(agent, image_descriptor, access_permission, image_data_layout, image_data_row_pitch, image_data_slice_pitch, image_data_info)
    ccall((:hsa_ext_image_data_get_info_with_layout, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{hsa_ext_image_descriptor_t}, hsa_access_permission_t, hsa_ext_image_data_layout_t, Csize_t, Csize_t, Ptr{hsa_ext_image_data_info_t}), agent, image_descriptor, access_permission, image_data_layout, image_data_row_pitch, image_data_slice_pitch, image_data_info)
end

function hsa_ext_image_create(agent, image_descriptor, image_data, access_permission, image)
    ccall((:hsa_ext_image_create, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{hsa_ext_image_descriptor_t}, Ptr{Cvoid}, hsa_access_permission_t, Ptr{hsa_ext_image_t}), agent, image_descriptor, image_data, access_permission, image)
end

function hsa_ext_image_create_with_layout(agent, image_descriptor, image_data, access_permission, image_data_layout, image_data_row_pitch, image_data_slice_pitch, image)
    ccall((:hsa_ext_image_create_with_layout, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{hsa_ext_image_descriptor_t}, Ptr{Cvoid}, hsa_access_permission_t, hsa_ext_image_data_layout_t, Csize_t, Csize_t, Ptr{hsa_ext_image_t}), agent, image_descriptor, image_data, access_permission, image_data_layout, image_data_row_pitch, image_data_slice_pitch, image)
end

function hsa_ext_image_destroy(agent, image)
    ccall((:hsa_ext_image_destroy, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_ext_image_t), agent, image)
end

function hsa_ext_image_copy(agent, src_image, src_offset, dst_image, dst_offset, range)
    ccall((:hsa_ext_image_copy, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_ext_image_t, Ptr{hsa_dim3_t}, hsa_ext_image_t, Ptr{hsa_dim3_t}, Ptr{hsa_dim3_t}), agent, src_image, src_offset, dst_image, dst_offset, range)
end

function hsa_ext_image_import(agent, src_memory, src_row_pitch, src_slice_pitch, dst_image, image_region)
    ccall((:hsa_ext_image_import, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{Cvoid}, Csize_t, Csize_t, hsa_ext_image_t, Ptr{hsa_ext_image_region_t}), agent, src_memory, src_row_pitch, src_slice_pitch, dst_image, image_region)
end

function hsa_ext_image_export(agent, src_image, dst_memory, dst_row_pitch, dst_slice_pitch, image_region)
    ccall((:hsa_ext_image_export, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_ext_image_t, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{hsa_ext_image_region_t}), agent, src_image, dst_memory, dst_row_pitch, dst_slice_pitch, image_region)
end

function hsa_ext_image_clear(agent, image, data, image_region)
    ccall((:hsa_ext_image_clear, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_ext_image_t, Ptr{Cvoid}, Ptr{hsa_ext_image_region_t}), agent, image, data, image_region)
end

function hsa_ext_sampler_create(agent, sampler_descriptor, sampler)
    ccall((:hsa_ext_sampler_create, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, Ptr{hsa_ext_sampler_descriptor_t}, Ptr{hsa_ext_sampler_t}), agent, sampler_descriptor, sampler)
end

function hsa_ext_sampler_destroy(agent, sampler)
    ccall((:hsa_ext_sampler_destroy, "libhsa-runtime64"), hsa_status_t, (hsa_agent_t, hsa_ext_sampler_t), agent, sampler)
end


text:
using CombinedParsers
using Test

@testset "CombinedParsers.jl" begin
    include("test-parser.jl")
    include("test-re.jl")
    include("pcretest-parser.jl")
end

import TextParse
import TextParse: Numeric
import Dates
@testset "TextParse" begin
    @test parser(Numeric(Int)) isa CombinedParser
    @test !(TextParse.Numeric(Int) isa CombinedParser)
    @test parse(("some " * Numeric(Int))[2], "some 100") == 100
    Dates.DateFormat.(("y-m-d","d.m.y"))
    CombinedParsers.DateParser("y-m-d","d.m.y")
    schedule = ("on " * CombinedParsers.DateParser("y-m-d","d.m.y"))[2]
    @test parse(schedule, "on 12.12.2020") == Dates.Date(2020,12,12)
    @test parse(schedule, "on 2020-12-12") == Dates.Date(2020,12,12)
end

ext: jl


text:
using SimulatedNeuralMoments, Flux, MCMCChains, StatsPlots, DelimitedFiles
using BSON:@save
using BSON:@load
using DelimitedFiles

# get the things to define the structure for the model
include("SVlib.jl")
function main()
lb, ub = PriorSupport()

# fill in the structure that defines the model
model = SNMmodel("Stochastic Volatility example", lb, ub, InSupport, Prior, PriorDraw, auxstat)

# train the net, and save it and the transformation info
#nnmodel, nninfo = MakeNeuralMoments(model)
#@save "neuralmodel.bson" nnmodel nninfo  # use this line to save the trained neural net
@load "neuralmodel.bson" nnmodel nninfo # use this to load a trained net

# draw a sample at the design parameters, or use an existing data set
#y = SVmodel(TrueParameters()) # draw a sample of 500 obsns. at design parameters
y = readdlm("svdata.txt") # load a data set
p1 = plot(y)
p2 = density(y)
plot(p1, p2, layout=(2,1))
#savefig("data.png")

# define the neural moments using the real data
m = NeuralMoments(auxstat(y), model, nnmodel, nninfo)
@show m
## draw a chain of length 10000 plus 500 burnin
chain, junk, junk = MCMC(m, 10500, model, nnmodel, nninfo, do_cue=false, verbosity=false)
chain = chain[501:end,:]
# visualize results
chn = Chains(chain, ["ϕ", "ρ", "σ"])
display(chn)
println("SNM estimation, estimated pos. median")
cnames = ["pos. median"]
prettyprint(median(chain,dims=1)[:], cnames)
plot(chn)
#savefig("chain.png")
#writedlm("chain.txt", chain)
end
main()


text:
using RecipesBase

@recipe function f(contres::ContResult; plotfold = true, putbifptlegend = true, filterbifpoints = false, vars = nothing )
	colorbif = Dict(:fold => :black, :hopf => :red, :bp => :blue, :nd => :magenta, :none => :yellow, :ns => :orange, :pd => :green)
	axisDict = Dict(:p => 1, :sol => 1, :itnewton => 3, :ds => 4, :theta => 5, :step => 6)
	# seriestype --> :path
	# Special case labels when vars = (:p,:y,:z) or (:x) or [:x,:y] ...
	if typeof(vars) <: Tuple && (typeof(vars[1]) == Symbol && typeof(vars[2]) == Symbol)
		ind1 = axisDict[vars[1]]
		ind2 = axisDict[vars[2]]
	elseif typeof(vars) <: Tuple && (typeof(vars[1]) <: Int && typeof(vars[2]) <: Int)
		ind1 = vars[1]
		ind2 = vars[2]
	else
		ind1 = 1
		ind2 = 2
	end
	@series begin
		if length(contres.stability) > 2
			linewidth --> map(x -> isodd(x) ? 2.0 : 1.0, contres.stability)
		end
		label --> ""
		contres.branch[ind1, :], contres.branch[ind2, :]
	end
	# display last point on the branch
	@series begin
		seriestype := :scatter
		markershape --> :cross
		seriescolor --> :red
		label --> ""
		[contres.branch[ind1, end]], [contres.branch[ind2, end]]
	end

	# display bifurcation points
	bifpoints = vcat(contres.bifpoint, filter(x->x.type != :none, contres.foldpoint))
	if length(bifpoints) >= 1 && ind2 == 2
		id = 1
		bifpoints[1].type == :none ? id = 2 : id = 1
		if plotfold
			bifpt = bifpoints[id:end]
		else
			bifpt = filter(x->x.type != :fold, bifpoints[id:end])
		end
		if filterbifpoints == true
			bifpt = filterBifurcations(bifpt)
		end
		@series begin
			seriestype := :scatter
			seriescolor --> map(x->colorbif[x.type], bifpt)
			markersize --> 4
			markerstrokewidth --> 0
			label --> ""
			map(x -> x.param, bifpt), map(x -> x.printsol, bifpt)
		end

		# add legend for bifurcation points
		if putbifptlegend && length(bifpoints) >= 1
			bp = unique([pt.type for pt in bifpt if pt.type != :none])
			(length(bp) == 0) && return
			for pt in bp
				@series begin
					seriestype := :scatter
					seriescolor --> colorbif[pt]
					label --> "$pt"
					markerstrokewidth --> 0
					[], []
				end
			end
		end

	end
end

@recipe function Plots(brs::AbstractVector{<:ContResult}; plotfold = true, putbifptlegend = true, filterbifpoints = false, vars = nothing, pspan=nothing )
	colorbif = Dict(:fold => :black, :hopf => :red, :bp => :blue, :nd => :magenta, :none => :yellow, :ns => :orange, :pd => :green)
	bp = Set(unique([pt.type for pt in brs[1].bifpoint]))
	for res in brs
		@series begin
			putbifptlegend --> false
			plotfold --> plotfold
			label --> false

			for pt in res.bifpoint
				push!(bp, pt.type)
			end
			res
		end
	end
	# add legend for bifurcation points
	if putbifptlegend && length(bp) > 0
		for pt in bp
			@series begin
				seriestype := :scatter
				seriescolor --> colorbif[pt]
				label --> "$pt"
				markerstrokewidth --> 0
			# scatter!([], [], color = colorbif[pt], label = "$pt", markerstrokewidth = 0)
				[], []
			end
		end
	end
end

####################################################################################################
"""
Plot the branch of solutions during the continuation
"""
function plotBranchCont(contres::ContResult, sol::BorderedArray, contparms, plotuserfunction)
	colorbif = Dict(:fold => :black, :hopf => :red, :bp => :blue, :nd => :magenta, :none => :yellow, :ns => :orange, :pd => :green)

	if contparms.computeEigenValues == false
		l =  Plots.@layout [a{0.5w} [b; c]]
	else
		l =  Plots.@layout [a{0.5w} [b; c]; e{0.2h}]
	end
	Plots.plot(layout = l)

	plot!(contres ; filterbifpoints = true, putbifptlegend = false, xlabel="p",  ylabel="||x||", label="", subplot=1)
	plot!(contres;	vars = (:step,:p), putbifptlegend = false, xlabel="it", ylabel="p", label = "", subplot=2)

	if contparms.computeEigenValues
		eigvals = contres.eig[end].eigenvals
		scatter!(real.(eigvals), imag.(eigvals), subplot=4, label="", markerstrokewidth=0, markersize = 3, color=:black)
	end

	plotuserfunction(sol.u, sol.p; subplot = 3)

	display(title!(""))
end

function filterBifurcations(bifpt)
	# this function filters Fold points and Branch points which are located at the same/previous/next point
	res = [(type = :none, idx = 1, param = 1., printsol = 1.)]
	ii = 1
	while ii <= length(bifpt) - 1
		if (abs(bifpt[ii].idx - bifpt[ii+1].idx) <= 1) && bifpt[ii].type ∈ [:fold, :bp]
			if (bifpt[ii].type == :fold && bifpt[ii].type == :bp) ||
				(bifpt[ii].type == :bp && bifpt[ii].type == :fold)
				push!(res, (type = :fold, idx = bifpt[ii].idx, param = bifpt[ii].param, printsol = bifpt[ii].printsol) )
			else
				push!(res, (type = bifpt[ii].type, idx = bifpt[ii].idx, param = bifpt[ii].param, printsol = bifpt[ii].printsol) )
				push!(res, (type = bifpt[ii+1].type, idx = bifpt[ii+1].idx, param = bifpt[ii+1].param, printsol = bifpt[ii+1].printsol) )
			end
			ii += 2
		else
			push!(res, (type = bifpt[ii].type, idx = bifpt[ii].idx, param = bifpt[ii].param, printsol = bifpt[ii].printsol) )
			ii += 1
		end
	end
	0<ii<=length(bifpt) &&	push!(res, (type = bifpt[ii].type, idx = bifpt[ii].idx, param = bifpt[ii].param, printsol = bifpt[ii].printsol) )

	# for p in (res[2:end])
	# 	println(p)
	# end
	res[2:end]
end


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

using Markdown
using InteractiveUtils

# ╔═╡ c819a820-13d1-11ec-174e-31eef4e20fc4
md"""
# Basic operators

Operators are symbols used to perform for example a basic mathematical operation. Some are very easy and straighforward, some are a little bit more complicated.

Let's start by the simple ones.

## Numeric operators

They include +, -, / and *, and are simply used as with a calculator as follows:
"""

# ╔═╡ 63b315e1-6bab-48d2-9992-6e6598bdf5fb
1 + 2

# ╔═╡ e874c232-256c-4d9f-a214-e526192be0cd
1 - 2

# ╔═╡ 4c362d08-3b79-44e3-8b48-0f9231526dca
1 * 2

# ╔═╡ f9ec2db0-d20a-4aac-ad24-66df4c7e6bde
1 / 2

# ╔═╡ 2222f963-31d7-460c-940f-4b544b3bc8a2
md"""
There is also the equal sign to assign a value to a variable:
"""

# ╔═╡ 36732368-836f-46bb-9a75-b75b10890505
a = 1

# ╔═╡ 9cb19c7e-9218-4f37-be67-c1e5d7b5a883
a

# ╔═╡ e43721b6-d642-4b6e-88ff-2bc48635effa
md"""
There's the integer division using ÷ (`\div` + tab)
"""

# ╔═╡ cc9cff27-b864-475b-b162-0503dc308432
1 ÷ 2

# ╔═╡ 98f549a9-1757-4e7c-bfac-0bf0d951b10d
md"""
To get the reminder of a division, we use the modulus, which is defined by the percent sign:
"""

# ╔═╡ 0272780b-6ace-499a-bf2b-441b9a148de4
1 % 2

# ╔═╡ 9f59bff0-bc85-4f36-b92c-d84e25cbdd9e
md"""
This is especially usefull if you want to know if the value of a variable is odd or even. To do so, you would use the remainder of the division by 2, which gives 0 for an even number, and 1 for an odd number:
"""

# ╔═╡ 7ed2ed34-f811-40c5-b6d2-17b7263f934c
a % 2

# ╔═╡ 00b8743b-8597-4fea-82d9-c191bfe73050
b = 2

# ╔═╡ 72ffc8b6-8543-42d2-b0bf-1640ccfcdea7
b % 2

# ╔═╡ 1df480ee-375f-421f-bfe6-cac883d290e3
md"""
To raise a value to the power of a number, we can use the caret:
"""

# ╔═╡ 278e7cb7-f760-4df2-8bdf-c87f1b8f5bec
2^4

# ╔═╡ 74bb4a3d-1d27-4555-8a47-98472ead2c9a
md"""
There are some short-hands if you want to update the value of a variable:
"""

# ╔═╡ ebc07294-3d9b-4973-b2b6-1afb535dc1ae
let
var = 1
var += 1
end

# ╔═╡ 73ced44d-503a-46a7-b1df-4db81e21375c
let
var = 1
var -= 1
end

# ╔═╡ 4293c2a4-cbd5-4b22-8b4a-280bbdacd1c8
let
var = 1
var *= 2
end

# ╔═╡ 1c238add-1c4f-4236-9943-6b9e7f45d8ab
let
var = 1
var /= 2
end

# ╔═╡ 6aa9bc63-bbf2-4b6e-9690-13ff4344c460
md"""
## Comparison operators

Some operators can be used to compare two values. They always return a boolean value: either `true` or `false`.

Greater than:
"""

# ╔═╡ 81ef192e-8e24-4865-8d79-06568e33390e
2 > 1

# ╔═╡ 2ee4020f-debb-4d0d-b25c-889f0f821d02
md"""
Greater or equal to:
"""

# ╔═╡ 6703e50a-18f1-4286-a5a7-2e18a28dc9ac
2 >= 1

# ╔═╡ 682bc70c-8ab9-40da-a231-df3f998d3562
md"""
The opposite:
"""

# ╔═╡ c7b5b7b7-3766-4a20-b847-f6ce2a077ace
2 < 1

# ╔═╡ 9e48d85f-61a8-4e93-9cc7-079f33359f0c
2 <= 1

# ╔═╡ daf09d9e-556d-4e2c-9e35-d78b0f61cd26
md"""
Testing equality:
"""

# ╔═╡ cce83b75-2ce6-489d-b7f6-05853fd6d056
2 == 1

# ╔═╡ 5f68213a-6d1d-4b3a-a7b3-c0abfbaa305b
md"""
!!! note
	Note that equality is done using `==`, which is not the same than `=`, used to assign a value to a variable.
"""

# ╔═╡ 9e9b02b8-f47d-494f-9332-7701903e6810
md"""
To test inequality, we use `!=`:
"""

# ╔═╡ 37d52bfb-6965-4ecd-804f-98d9f7c1b01b
2 != 1

# ╔═╡ bc6ad01a-f7ec-4538-8115-73ba67406943
md"""
## Boolean operators

There are also the logical tests using `!` ("not"), `&&` ("and") and `||` ("or") on boolean values (`true` or `false`).

### Negation

The `!` operator negates the boolean value of the statement:
"""

# ╔═╡ 83f6f3fd-ab7e-4ebb-8285-b49188a1f50b
!false

# ╔═╡ dcbbe212-23aa-4ff9-9fda-f1f0d67b3f95
!true

# ╔═╡ 8bbe84a0-93de-4bb9-8995-caed6bc920c7
md"""
So this:
"""

# ╔═╡ f0752ae9-5401-49fc-8ddc-d07302499185
2 > 1

# ╔═╡ b88e0721-cf58-4f85-b54a-4514982e2218
md"""
Is equivalent to this:
"""

# ╔═╡ 0a8e65d5-7043-4f66-8987-c2e56e09d223
!(2 <= 1)

# ╔═╡ 729ae192-df5b-47a3-a245-9d40e8014f5a
md"""

### Logical "and"

The logical "and" (`&&`) returns `true` only if the right-hand side and left-hand side values of the operator are both `true`:
"""

# ╔═╡ f032b44b-16b0-4383-8076-97d110249fb5
true && true

# ╔═╡ 4d44dd47-ff82-417a-b248-cacdac6d91d4
true && false

# ╔═╡ 0de3bcfb-f4e0-43cc-b407-ececfbb1d8bf
md"""
### Logical "or"
"""

# ╔═╡ c2b86ba3-d54e-4191-9efb-a70e0f706516
md"""
The logical "or" returns true if at least one is true:
"""

# ╔═╡ 8e7cce54-9217-4ad0-978e-67fa21cb6fd5
true || false

# ╔═╡ 4f5d628f-de89-43a0-9a50-d79d39d8fd44
false || false

# ╔═╡ f91b3d97-a611-4a5e-8cf6-3e45eb052ff1
md"""
In reality you'll use variables instead of boolean values directly. For example you could say that `c` is equal to `true` in the case both `a` and `b` are bellow 3:
"""

# ╔═╡ ff6e339d-89ba-4df9-b674-4602dd4549a9
c = a < 3 && b < 3

# ╔═╡ 2f44b8ec-3414-4903-b5a2-ea7c819b3b86
md"""
### Conditional execution
"""

# ╔═╡ a0cf3510-a2f1-4b8d-9e95-54b49f37d926
md"""
The nice thing with Julia is that it tests the conditions incrementally because we know that if the first condition is `false` in a `&&` statement, the whole statement will be false, and if the first condition is `true` in a `||` statement, the whole statement will be `true`. We can use that as a tool to conditionally execute a line of code.
"""

# ╔═╡ 98fa4586-e163-40a5-9084-c9a1cb4c350b
a == 1 && "a is equal to 1!"

# ╔═╡ 8dc5efc6-6c25-45d7-a944-6f229eef9b49
b == 1 && "b is equal to 1!"

# ╔═╡ 986244f3-b4eb-4d16-ab5f-7585a44d3784
b == 1 || "b is not equal to 1!"

# ╔═╡ 102364c0-98a9-411b-94c7-cd129c99f04a
md"""
The concept of conditional execution is very important, and we will see it in more details in a coming video.
"""

# ╔═╡ 0da85da4-18eb-431e-972a-426e73f16781
md"""
## Vectorizing operators

All operators we just saw are applied to one value at a time. But very often we want to apply an operator over a sequence of values stored in an Array for example.

To do so, we can use the vectorized version of the operators by adding a dot right before it. This is called broadcasting. We will see more details about that in another video.
"""

# ╔═╡ 5356fedc-2524-4b32-8559-a0ba5ae2f5cf
a_vec = [1, 2, 3]

# ╔═╡ 7e0b0477-e72d-4bf5-a059-63993cf0035b
md"""
For example adding a single value to a vector of values using the `+` sign will return an error:
"""

# ╔═╡ 0d905737-2738-4564-9273-139a84aa100d
a_vec + 2

# ╔═╡ 13b1edec-9ae6-4a0b-b8ed-2f63df2e6792
md"""
THe error is a `MethodError`, because there is no method implemented for the `+` function with a vector of integer and an integer.

Using the vectorized version will work perfectly:
"""

# ╔═╡ 02a4c901-8c29-42ec-8864-fe5d4c70f46b
a_vec .+ 2

# ╔═╡ 6515d475-294a-40c4-9ac7-8e3ef15e8f89
md"""
!!! note
	In practice, the vectorized version applies the `+` function sequentially over the values of the `a_vec` array, and then return the results back as an array.
"""

# ╔═╡ e087cd30-f78f-40a4-95f5-87bfcf05fbe7
md"""
There are other ways to do so, such as the for loops or array comprehension, but we will see that in another video.
"""

# ╔═╡ Cell order:
# ╟─c819a820-13d1-11ec-174e-31eef4e20fc4
# ╠═63b315e1-6bab-48d2-9992-6e6598bdf5fb
# ╠═e874c232-256c-4d9f-a214-e526192be0cd
# ╠═4c362d08-3b79-44e3-8b48-0f9231526dca
# ╠═f9ec2db0-d20a-4aac-ad24-66df4c7e6bde
# ╟─2222f963-31d7-460c-940f-4b544b3bc8a2
# ╠═36732368-836f-46bb-9a75-b75b10890505
# ╠═9cb19c7e-9218-4f37-be67-c1e5d7b5a883
# ╟─e43721b6-d642-4b6e-88ff-2bc48635effa
# ╠═cc9cff27-b864-475b-b162-0503dc308432
# ╟─98f549a9-1757-4e7c-bfac-0bf0d951b10d
# ╠═0272780b-6ace-499a-bf2b-441b9a148de4
# ╟─9f59bff0-bc85-4f36-b92c-d84e25cbdd9e
# ╠═7ed2ed34-f811-40c5-b6d2-17b7263f934c
# ╠═00b8743b-8597-4fea-82d9-c191bfe73050
# ╠═72ffc8b6-8543-42d2-b0bf-1640ccfcdea7
# ╟─1df480ee-375f-421f-bfe6-cac883d290e3
# ╠═278e7cb7-f760-4df2-8bdf-c87f1b8f5bec
# ╟─74bb4a3d-1d27-4555-8a47-98472ead2c9a
# ╠═ebc07294-3d9b-4973-b2b6-1afb535dc1ae
# ╠═73ced44d-503a-46a7-b1df-4db81e21375c
# ╠═4293c2a4-cbd5-4b22-8b4a-280bbdacd1c8
# ╠═1c238add-1c4f-4236-9943-6b9e7f45d8ab
# ╟─6aa9bc63-bbf2-4b6e-9690-13ff4344c460
# ╠═81ef192e-8e24-4865-8d79-06568e33390e
# ╟─2ee4020f-debb-4d0d-b25c-889f0f821d02
# ╠═6703e50a-18f1-4286-a5a7-2e18a28dc9ac
# ╟─682bc70c-8ab9-40da-a231-df3f998d3562
# ╠═c7b5b7b7-3766-4a20-b847-f6ce2a077ace
# ╠═9e48d85f-61a8-4e93-9cc7-079f33359f0c
# ╟─daf09d9e-556d-4e2c-9e35-d78b0f61cd26
# ╠═cce83b75-2ce6-489d-b7f6-05853fd6d056
# ╟─5f68213a-6d1d-4b3a-a7b3-c0abfbaa305b
# ╟─9e9b02b8-f47d-494f-9332-7701903e6810
# ╠═37d52bfb-6965-4ecd-804f-98d9f7c1b01b
# ╟─bc6ad01a-f7ec-4538-8115-73ba67406943
# ╠═83f6f3fd-ab7e-4ebb-8285-b49188a1f50b
# ╠═dcbbe212-23aa-4ff9-9fda-f1f0d67b3f95
# ╟─8bbe84a0-93de-4bb9-8995-caed6bc920c7
# ╠═f0752ae9-5401-49fc-8ddc-d07302499185
# ╟─b88e0721-cf58-4f85-b54a-4514982e2218
# ╠═0a8e65d5-7043-4f66-8987-c2e56e09d223
# ╟─729ae192-df5b-47a3-a245-9d40e8014f5a
# ╠═f032b44b-16b0-4383-8076-97d110249fb5
# ╠═4d44dd47-ff82-417a-b248-cacdac6d91d4
# ╟─0de3bcfb-f4e0-43cc-b407-ececfbb1d8bf
# ╟─c2b86ba3-d54e-4191-9efb-a70e0f706516
# ╠═8e7cce54-9217-4ad0-978e-67fa21cb6fd5
# ╠═4f5d628f-de89-43a0-9a50-d79d39d8fd44
# ╟─f91b3d97-a611-4a5e-8cf6-3e45eb052ff1
# ╠═ff6e339d-89ba-4df9-b674-4602dd4549a9
# ╟─2f44b8ec-3414-4903-b5a2-ea7c819b3b86
# ╟─a0cf3510-a2f1-4b8d-9e95-54b49f37d926
# ╠═98fa4586-e163-40a5-9084-c9a1cb4c350b
# ╠═8dc5efc6-6c25-45d7-a944-6f229eef9b49
# ╠═986244f3-b4eb-4d16-ab5f-7585a44d3784
# ╟─102364c0-98a9-411b-94c7-cd129c99f04a
# ╟─0da85da4-18eb-431e-972a-426e73f16781
# ╠═5356fedc-2524-4b32-8559-a0ba5ae2f5cf
# ╟─7e0b0477-e72d-4bf5-a059-63993cf0035b
# ╠═0d905737-2738-4564-9273-139a84aa100d
# ╟─13b1edec-9ae6-4a0b-b8ed-2f63df2e6792
# ╠═02a4c901-8c29-42ec-8864-fe5d4c70f46b
# ╟─6515d475-294a-40c4-9ac7-8e3ef15e8f89
# ╟─e087cd30-f78f-40a4-95f5-87bfcf05fbe7


text:
# """
# For this experiment we see how well our greedy peeling approximation algorithm
# does compared to the optimal solution on smaller datasets.
#
# We first solve the objective optimally using repeated submodular minimization.
# See MATLAB code.
#
# Here we use the greedy algorithm and compare its output against the optimal.
# """
using Plots
using MAT

include("../src/pdensity_algorithms.jl")

datasets = ["KarateA","dolphinsA","polbooksA","adjnounA","lesmisA","footballA","jazzA","Netscience"]

for j = 1:length(datasets)
tol = 0.1
if j > 6
    tol = 0.25
end
graph = datasets[j]
G = matread("../data/$(graph).mat")
A = G["A"]
n = size(A,1)
@show graph, n
end

## other
Ps = collect(1:0.5:5.0)
Opts = zeros(length(Ps))
for i = 1:length(Ps)
    p = Ps[i]
    if p == floor(p)
        p = round(Int64,p)
    end
    M = matread("Exact_Solutions/$(graph)_$(p)_$tol.mat")
    Svecs = M["Svecs"]
    check = M["check"]
    # S = round.(Int64,M["S"])          # bug in how this was saved
    S = findall(x->x>0,Svecs[:,end])
    # @show S, p
    pm = pdensityobj(A,S,p)
    timer = M["timer"]
    pmdensitybound = (M["pmdensity"]+tol)^(1/p) # upper bound we can guarantee
    Densities = (M["Densities"]).^(1/p)
    # @show pm,pmdensity, maximum(Densities)
    # @show Densities
    Opts[i] = pmdensitybound
    p = Float64(p)
    nS = length(S)
    # println("$graph \t $p \t $check \t $timer \t $pmdensity \t $nS")
end

## Run Approximation Algorithm

Ssets = zeros(n,length(Ps))
Times = zeros(length(Ps))
Ranks = zeros(n,length(Ps))
Objectives = zeros(n,length(Ps))
Pdens = zeros(length(Ps))
Approx = zeros(length(Ps))
for i = 1:length(Ps)
    p = Ps[i]
    if p == floor(p)
        p = round(Int64,p)
    end

    # compute approximate
    tic = time()
    S, objS, Objs, ranking = GenPeel(A,p)
    timers = time()-tic
    Times[i] = timers
    Ssets[S,i] .= 1
    Objectives[:,i] = Objs
    Ranks[:,i] = ranking
    nS = length(S)
    obj = maximum(Objs)
    Pdens[i] = obj
    println("$p \t $nS \t $obj ")

end
matwrite("Approx_Solutions/$(graph)_output.mat",
        Dict("Ssets"=>Ssets,"Ps"=>Ps,"Pdens"=>Pdens,
        "Ranks"=>Ranks,"Times"=>Times,"Objectives"=>Objectives))

## Plot the results

# For each algorithm (which is parameterized by p), we see how well
# it does in solving different version of the objective (also parameterized by p).

M = matread("Approx_Solutions/$(graph)_output.mat")
Ssets = M["Ssets"]
Scores = zeros(length(Ps),length(Ps))
for j = 1:length(Ps)
    pa = Ps[j]
    if pa == floor(pa)
        pa = round(Int64,pa)
    end

    # uncomment this if you want to see how the optimal sets do
    Ms = matread("Exact_Solutions/$(graph)_$(pa)_$tol.mat")
    Svecs = Ms["Svecs"]
    S = findall(x->x>0,Svecs[:,end])
    # pmdensity = (Ms["pmdensity"])^(1/pa)
    # S = findall(x->x>0,Ssets[:,j])      # There resulting set
    for k = 1:length(Ps)
        p = Ps[k]
        # @show pdensityobj(A,S,p)
        Scores[j,k] = pdensityobj(A,S,p)/Opts[k]  # The approx ratio
    end
end

## Plot
P = plot(grid = false)
ms = 3.5

C = [1 0 0;
0 .75 0;
0 0 1;
0 .5 .5;
.5 0 .5;
1 .5 0;
0 0 0;
.75 .75 0;
0.1 0.5 0.6;
0 .75 .75;
.4 .5 .3]
for j = 1:2:length(Ps)
    pa = Ps[j]                       # The p for which the algorithm was run
    if pa == floor(pa)
        pa = round(Int64,pa)
    end
    col = color = RGBA(C[j,1],C[j,2],C[j,3],1)
    plot!(P,Ps,Scores[j,:],label = "GenPeel-$pa",markershape = :circle,
        markerstrokewidth = 0,markersize = ms,color = col, markerstrokecolor = col)
end

s1 = 300
s2 = 250
plot!(P,[1;5],[1;1], size = (s1,s2),color = :gray, legend = :bottomright,label = "", yaxis = "Approximation Guarantee", xaxis = "p")

savefig("Figures/$(graph)_plot_opt_sets.pdf")

end

max_stars_repo_name: nveldt/GenMeanDSG

max_issues_repo_name: nveldt/GenMeanDSG

max_forks_repo_name: nveldt/GenMeanDSG


text:
export estimate_treewidth

#=
This file contains an implementation of an anytime, branch-and-bound depth-first
search for computing the treewidth of a graph. If the search doesn't complete within
the allocated time, an upper bound is resturned representing the best solution the
algorithm was able to find.

The basic algorithm is outlined by Gogate in the 2004 paper "A complete anytime
algorithm for treewidth".

One of the heuristics mentioned in Yaun's 2011 paper "A Fast Parallel Branch and
Bound Algorithm for Treewidth" is also used.

A discussion of relevant heuristics can be found in Bodlaender's "Treewidth
Computations 1 & 2" papers but not yet used.
=#

###
### Interface for the branch-and-bound depth-first search.
###

"""
    estimate_treewidth(G::AbstractGraph, duration::Float63; seed::Int=42)

Uses a branch-and-bound depth-first search to compute a vertex elimination order
for the graph `g` with minimal treewidth. If the search does not complete within
the allocated time, the best treewidth and elimination order is returned.

# Positional arguments
- `G::SimpleGraph`: A LightGraphs SimpleGraph representing the graph to estimate
                    the treewidth for.
- `run_time::AbstractFloat`: The amount of time to run the algorithm for.

# Keyword arguments
- `seed::Integer=-1`: The seed used by flow cutter. Most be a non negative integer,
                      otherwise the seed is set by flow cutter.
"""
function estimate_treewidth(
                        G::lg.SimpleGraph,
                        run_time::AbstractFloat;
                        seed::Integer=42
                        )
    start_time = time()
    finish_time = start_time + run_time

    # Compute an initial upper bound on the treewidth.
    initial_ub = initialise_upper_bound(G, seed)
    heurisitc_finish_time = time()

    # Create a depth-first search state for each thread and run the algorithm.
    states = initialise_dfsstates(G, initial_ub, finish_time, seed, nthreads())
    _estimate_treewidth!(states)
    actual_finish_time = time()

    # Return the best result and a report containing metadata.
    report = DFSReport(states, run_time, start_time, heurisitc_finish_time, actual_finish_time)
    report.tw, report.order, report
end

"""Run the algorithm with the given vector states."""
function _estimate_treewidth!(states::Vector{DFSState})::Nothing
    # Randomly distribute the vertices of G amongst the threads.
    state = states[1]
    verts = shuffle(state.rng, copy(state.graph.vertices))
    verts = [UInt16[verts[i] for i = j:nthreads():state.graph.num_vertices] for j = 1:nthreads()]

    # Start each thread running a bb-dfs.
    @threads for t = 1:nthreads()
        _bb!(states[t], 0x0000, verts[t])
    end
    nothing
end

"""
Call the branch and bound step on each vertex in the given array.
(Only used by the interface function)
"""
function _bb!(state::DFSState, curr_tw::UInt16, verts::Vector{UInt16})
    for v in verts
        bb!(state, curr_tw, v)
    end
    nothing
end

###
### Implementation of a branch-and-bound depth-first search of elimination orders.
###

"""Performs the branch and bound step."""
function bb!(state::DFSState, curr_tw::UInt16, v::UInt16)
    # Add the next vertex to the current order and update the treewidth.
    state.curr_order[state.depth] = v
    next_tw = max(curr_tw, degree(state.graph, v))

    # Prune unless the current treewidth is less than the current upper bound.
    if next_tw < state.ub.tw

        # Eliminate the vertex from the current graph.
        eliminate!(state, v)
        state.nodes_visited += 1

        if check_lower_bounds!(state, next_tw)
            dfs!(state, next_tw)
        end

        # Restore the graph to its original state before returning.
        restore_last_eliminated!(state)
    else
        if curr_tw >= state.ub.tw
            state.ub_prune_at_depth[state.depth] += 1
        end
    end
end

"""Performs the recursive depth first search step."""
function dfs!(state::DFSState, curr_tw::T) where T <: UInt16
    state.depth += 1

    # Recursive base case: an n-vertex graph can't have a treewidth
    # larger than n-1.
    if state.graph.num_vertices - 0x0001 <= curr_tw
        if curr_tw < state.ub.tw
            lock(state.ub.lock)
            if curr_tw < state.ub.tw
                @info "Thread $(threadid()): The treewidth is now $curr_tw"
                state.curr_order[state.depth:end] .= vertices(state.graph)[:]
                copy!(state.ub.order, state.curr_order)
                state.ub.tw = curr_tw
            end
            unlock(state.ub.lock)
        end

    else
        # Copy the vertices which may be eliminated next.
        # (This is needed as vertices(graph) may mutate after
        # subsequent eliminations.)
        N = num_vertices(state.graph)
        verts = state.branches[state.depth]
        copy!(verts, vertices(state.graph))

        # Explore eliminating each of the next candidates.
        for i = 0x0001:N
            timed_out(state, N, i) && break
            v = verts[i]
            bb!(state, curr_tw, v)
        end
    end

    state.depth -= 1
    nothing
end

###
### functions to aid the branch-and-bound depth-first search
###

"""Checks if pruning can be performed due to lower bounds"""
function check_lower_bounds!(state::DFSState, curr_tw::UInt16)
    # Compute a lower bound on the remaining graph and prune if
    # it is equal or larger than the current upper bound.
    if state.lb_ub >= state.ub.tw
        state.lb_ub = mmd(state)
        if state.lb_ub >= state.ub.tw
            state.mmd_prune_at_depth[state.depth] += 1
            return false
        end
    end

    # Below the pruning rule used by Yaun's tabel of lower bounds
    # is used.
    state_key = state.intermediate_graph_key
    tabel = state.lbs.tabel
    slock = state.lbs.lock
    state_lb = get(tabel, state_key, nothing)

    if state_lb === nothing
        lock(slock)
        if !haskey(tabel, state_key) || tabel[state_key] > curr_tw
            tabel[state_key] = curr_tw
        end
        unlock(slock)
        return true

    else
        if curr_tw < state_lb
            lock(slock)
            tabel[state_key] = curr_tw
            unlock(slock)
            return true
        else
            state.lbs_prune_at_depth[state.depth] += 1
            return false
        end
    end
end

"""Check if the algorithm has ran out of time"""
function timed_out(state::DFSState, N::UInt16, i::Integer)
    if time() >= state.finish_time
        if state.timed_out
            state.space_covered *= 1/N
            state.space_covered += (i-1)/N
        else
            state.timed_out = true
        end
        return true
    end
    false
end


text:
using HorizonSideRobots
include("../basics.jl")

md"""
        # Подсчитать число и вертикальных и горизонтальных прямолинейных перегородок (прямоугольных - нет)
"""

"""
Считает кол-во горизонтальных перегородок со стороны {border_side} в строке/столбце, двигаясь в направлении {side}
"""
function count_borders_inline_at!(r, side, border_side)
    counter = 0
    is_under_border = false
    cond = true
    while cond
        if !is_under_border && isborder(r, border_side)
            counter+=1
            is_under_border = true
        elseif !isborder(r, border_side)
            is_under_border = false
        end
        cond = try_move!(r, side)
    end
    return counter
end

"""
Считает количество линейных перегородок в стороне {border_side}
"""
function count_linear_borders_at!(r, border_side)
    counter = 0
    while !isborder(r, border_side)
        counter += count_borders_inline_at!(r, next_side(border_side), border_side)
        carefull_move!(r, border_side)
        if !isborder(r, border_side)
            counter += count_borders_inline_at!(r, previous_side(border_side), border_side)
            carefull_move!(r, border_side)
        end
    end
    return counter
end

"""Решение задачи 21"""
function solve_21!(r)
    path = move_to_corner!(r, West, Sud)

    horizontal_counter = count_linear_borders_at!(r, Nord)
    move_to_corner!(r, West, Nord)
    vertical_counter = count_linear_borders_at!(r, Ost)

    move_to_corner!(r, West, Sud)
    move_back_from_corner!(r, West, Sud, reverse(path))

    return horizontal_counter + vertical_counter
end


text:
# Define and register smooth functions
_cos_wave(t, f, A, st, ϕ) = A*cos(2*π*f*(t - st) + ϕ)
_sin_wave(t, f, A, st, ϕ) = A*sin(2*π*f*(t - st) + ϕ)
_damped_sine_wave(t, f, A, st, ϕ, d) = exp((st-t)*d)*A*sin(2*π*f*(t-st) + ϕ)
_ramp(t, δ, st, et, h) = h/(et-st)*(_xH(t, δ, st) - _xH(t, δ, et))
_square_wave(t, δ, f, A, st) = A*2atan(sin(2π*(t-st)*f)/δ)/π
_step(t, δ, h, a) = h*(atan((t-a)/δ)/π + 0.5)
_triangular_wave(t, δ, f, A, st) = A*(1-2acos((1 - δ)sin(2π*(t-st)*f))/π)
_xH(t, δ, tₒ) = (t-tₒ)*(1+((t-tₒ)/sqrt((t-tₒ)^2+δ^2)))/2

@register_symbolic _cos_wave(t, f, A, st, ϕ)
@register_symbolic _sin_wave(t, f, A, st, ϕ)
@register_symbolic _damped_sine_wave(t, f, A, st, ϕ, damping)
@register_symbolic _ramp(t, δ, st, et, h)
@register_symbolic _square_wave(t, δ, f, A, st)
@register_symbolic _step(t, δ, h, a)
@register_symbolic _triangular_wave(t, δ, f, A, st)

"""
    ConstantVoltage(;name, V = 1.0)

Source for constant voltage,

# Parameters:
- `V`: [V] Voltage
"""
function ConstantVoltage(;name, V = 1.0)
    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters V=V
    eqs = [
        v ~ V
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    CosineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)

Generate cosine voltage.

# Parameters:
- `frequency`: [Hz] Frequency of sine wave
- `amplitude`: [V] Amplitude of sine wave
- `phase`: [rad] Phase of sine wave
- `offset`: [V] Offset of output voltage
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function CosineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)
    δ = 0.00001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        frequency=frequency
        start_time=start_time
        phase=phase
    end
    eqs = [
        v ~ _cos_wave(t, frequency, amplitude, start_time, phase) * _step(t, δ, 1.0, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
Generate damped sine voltage.

# Parameters:
- `frequency`: [Hz] Frequency of sine wave
- `amplitude`: [V] Amplitude of sine wave
- `damping`: [1/s] Damping coefficient of sine wave
- `phase`: [rad] Phase of sine wave
- `offset`: [V] Offset of output voltage
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function ExpSineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0, damping=0.0)
    δ = 0.00001
    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        frequency=frequency
        start_time=start_time
        phase=phase
        damping=damping
    end
    eqs = [
        v ~ _damped_sine_wave(t, frequency, amplitude, start_time, phase, damping) * _step(t, δ, 1.0, start_time)
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    RampVoltage(;name, offset=0.0, start_time=0.0, duration=1.0, height=1.0)

Generate ramp voltage.

# Parameters:
- `height`: [V] Height of ramp
- `duration`: [s] Duration of ramp (= 0.0 gives a Step)
- `offset`: [V] Offset of output voltage
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function RampVoltage(;name, offset=0.0, start_time=0.0, duration=1.0, height=1.0)
    δ = 0.00001
    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        height=height
        start_time=start_time
        duration=duration
    end
    eqs = [
        v ~ _ramp(t, δ, start_time, start_time + duration, height) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    SineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)

Generate sine voltage.

# Parameters:
- `frequency`: [Hz] Frequency of sine wave
- `amplitude`: [V] Amplitude of sine wave
- `phase`: [rad] Phase of sine wave
- `offset`: [V] Offset of output voltage
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function SineVoltage(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)
    δ = 0.00001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        frequency=frequency
        start_time=start_time
        phase=phase
    end
    eqs = [
        v ~ _sin_wave(t, frequency, amplitude, start_time, phase) * _step(t, δ, 1.0, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    SquareVoltage(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)

Generate square voltage.
"""
function SquareVoltage(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)
    δ = 0.0001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        start_time=start_time
    end
    eqs = [
        v ~ _square_wave(t, δ, frequency, amplitude, start_time) * _step(t, δ, 1.0, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    StepVoltage(;name, offset=0.0, start_time=0.0, height=1.0)

Generate step voltage.

# Parameters:
- `height`: [V] Height of step
- `offset`: [V] Offset of output voltage
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function StepVoltage(;name, offset=0.0, start_time=0.0, height=1.0)
    δ = 0.0001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        height=height
        start_time=start_time
    end
    eqs = [
        v ~ _step(t, δ, height, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

function TriangularVoltage(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)
    δ = 0.00001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        frequency=frequency
        start_time=start_time
    end
    eqs = [
        v ~ _triangular_wave(t, δ, frequency, amplitude, start_time) * _step(t, δ, 1.0, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

# Current Sources ######################################################################################################
"""
    ConstantCurrent(;name, I = 1.0)

Source for constant current.

# Parameters:
- `I`: [A] Current
"""
function ConstantCurrent(;name, I = 1.0)
    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters I=I
    eqs = [
        i ~ I
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    CosineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)

Generate cosine current.

# Parameters:
- `frequency`: [Hz] Frequency of sine wave
- `amplitude`: [A] Amplitude of sine wave
- `phase`: [rad] Phase of sine wave
- `offset`: [A] Offset of output current
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function CosineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)
    δ = 0.00001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        frequency=frequency
        start_time=start_time
        phase=phase
    end
    eqs = [
        i ~ _cos_wave(t, frequency, amplitude, start_time, phase) * _step(t, δ, 1.0, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    ExpSineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0, damping=0.0)

Generate damped sine current.

# Parameters:
- `frequency`: [Hz] Frequency of sine wave
- `amplitude`: [A] Amplitude of sine wave
- `damping`: [1/s] Damping coefficient of sine wave
- `phase`: [rad] Phase of sine wave
- `offset`: [A] Offset of output current
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function ExpSineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0, damping=0.0)
    δ = 0.00001
    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        frequency=frequency
        start_time=start_time
        phase=phase
        damping=damping
    end
    eqs = [
        i ~ _damped_sine_wave(t, frequency, amplitude, start_time, phase, damping) * _step(t, δ, 1.0, start_time)
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    RampCurrent(;name, offset=0.0, start_time=0.0, duration=1.0, height=1.0)

Generate ramp current.

# Parameters:
- `height`: [A] Height of ramp
- `duration`: [s] Duration of ramp (= 0.0 gives a Step)
- `offset`: [A] Offset of output current
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function RampCurrent(;name, offset=0.0, start_time=0.0, duration=1.0, height=1.0)
    δ = 0.00001
    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        height=height
        start_time=start_time
        duration=duration
    end
    eqs = [
        i ~ _ramp(t, δ, start_time, start_time + duration, height) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    SineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)

Generate sine current.

# Parameters:
- `frequency`: [Hz] Frequency of sine wave
- `amplitude`: [A] Amplitude of sine wave
- `phase`: [rad] Phase of sine wave
- `offset`: [A] Offset of output current
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function SineCurrent(;name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0, phase=0.0)
    δ = 0.00001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        frequency=frequency
        start_time=start_time
        phase=phase
    end
    eqs = [
        i ~ _sin_wave(t, frequency, amplitude, start_time, phase) * _step(t, δ, 1.0, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

function SquareCurrent(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)
    δ = 0.0001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        start_time=start_time
    end
    eqs = [
        i ~ _square_wave(t, δ, frequency, amplitude, start_time) * _step(t, δ, 1.0, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

"""
    StepCurrent(;name, offset=0.0, start_time=0.0, height=1.0)

Generate step current.

# Parameters:
- `height`: [A] Height of step
- `offset`: [A] Offset of output current
- `start_time`: [s] Output `y = offset` for `t < start_time`
"""
function StepCurrent(;name, offset=0.0, start_time=0.0, height=1.0)
    δ = 0.0001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        height=height
        start_time=start_time
    end
    eqs = [
        i ~ _step(t, δ, height, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end

function TriangularCurrent(; name, offset=0.0, amplitude=1.0, frequency=1.0, start_time=0.0)
    δ = 0.00001

    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        offset=offset
        amplitude=amplitude
        frequency=frequency
        start_time=start_time
    end
    eqs = [
        i ~ _triangular_wave(t, δ, frequency, amplitude, start_time) * _step(t, δ, 1.0, start_time) + offset
    ]

    extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end


text:
module GeometryWrappers #@fverdugo rename as RefCells ??

# Dependencies of this module

using Gridap
using Gridap.Helpers
using Gridap.CellValuesGallery
using UnstructuredGrids.Core: VERTEX
using UnstructuredGrids.Kernels: UNSET
using UnstructuredGrids.Kernels: generate_data_and_ptrs

# Functionality provided by this module

export RefCell
import UnstructuredGrids.Core: RefCell
import UnstructuredGrids.Core: Connections
import UnstructuredGrids: generate_dual_connections
import UnstructuredGrids: find_cell_to_faces
import Gridap: Grid

"""
Construct a RefCell from a Polytope
"""
RefCell(polytope::Polytope) = _ref_cell_from_polytope(polytope)

"""
Construct a Grid from a polytope
"""
function Grid(polytope::Polytope{D},dim::Int) where D
  if dim < D
    _grid_d(polytope,dim)
  elseif dim==D
    _grid_D(polytope)
  else
    @unreachable
  end
end

function generate_dual_connections(face_to_nodes::CellVector)
 face_to_nodes_data, face_to_nodes_ptrs = compress(face_to_nodes)
 node_to_faces_data, node_to_faces_ptrs =
   generate_dual_connections(face_to_nodes_data, face_to_nodes_ptrs)
 CellVectorFromDataAndPtrs(node_to_faces_data, node_to_faces_ptrs)
end

function find_cell_to_faces(fgrid::Grid, vertex_to_jfaces::IndexCellArray, j)
  _fgrid = UGrid(fgrid)
  data, ptrs = compress(vertex_to_jfaces)
  _vertex_to_jfaces = Connections(data,ptrs)
  face_to_jfaces = find_cell_to_faces(_fgrid, _vertex_to_jfaces, j)
  CellVectorFromDataAndPtrs(face_to_jfaces.list,face_to_jfaces.ptrs)
end

# Helpers

function _grid_D(polytope::Polytope{D}) where D

  order = 1
  reffe = LagrangianRefFE(Float64,polytope,order)
  points = reffe.dofbasis.nodes

  cell_to_nodes = [ [i for i in 1:length(points)], ]

  cells_data,cells_ptrs = generate_data_and_ptrs(cell_to_nodes)
  extrusion = polytope.extrusion.array.data

  l = 1
  co = ConstantCellValue(order,l)
  ct = ConstantCellValue(extrusion,l)

  UnstructuredGrid(points,cells_data,cells_ptrs,ct,co)

end

function _grid_d(polytope::Polytope{D},dim::Int) where D
  @assert dim < D

  order = 1
  reffe = LagrangianRefFE(Float64,polytope,order)
  points = reffe.dofbasis.nodes

  dim_to_jface_to_vertices, dim_to_jface_to_code = _faces(polytope)
  jface_to_vertices = dim_to_jface_to_vertices[dim+1]
  jface_to_code = dim_to_jface_to_code[dim+1]

  njfaces = length(jface_to_code)
  @assert njfaces > 0
  code1 = jface_to_code[1]
  # TODO for the moment, we assume all faces of the polytope have the same
  # extrusion code
  @notimplementedif any([ code1 != code for code in jface_to_code ])

  cells_data, cells_ptrs = generate_data_and_ptrs(jface_to_vertices)
  code = (code1...,)
  ctypes = ConstantCellValue(code,njfaces)
  order = 1
  orders = ConstantCellValue(order,njfaces)

  UnstructuredGrid(points,cells_data,cells_ptrs,ctypes,orders)

end

function _ref_cell_from_polytope(polytope::Polytope{D}) where D

  dim_to_jface_to_vertices, dim_to_jface_to_code = _faces(polytope)

  vertex_to_coords = _coordinates(polytope)

  dim_to_jface_to_ftype, dim_to_ftype_to_code = _ftypes(dim_to_jface_to_code)

  dim_to_ftype_to_refface = _reffaces(dim_to_ftype_to_code)

  _vtkid, _vtknodes = _vtkinfo(polytope)

  RefCell(
    ndims = D,
    faces = dim_to_jface_to_vertices,
    facetypes = dim_to_jface_to_ftype,
    reffaces = dim_to_ftype_to_refface,
    coordinates = vertex_to_coords,
    vtkid = _vtkid,
    vtknodes = _vtknodes)

end

function _faces(polytope)

  nface_to_dim, nface_to_vertices, nface_to_code = (
    _extract_nface_to_info(polytope) )

 dim_to_jface_to_vertices, dim_to_jface_to_code = (
    _sort_nfaces_to_vertices_per_dim(
      nface_to_dim, nface_to_vertices, nface_to_code) )

 (dim_to_jface_to_vertices, dim_to_jface_to_code)
end

function _reffaces(dim_to_ftype_to_code)

  [ [ _code_to_refface(code) for code in ftype_to_code ]
   for ftype_to_code in dim_to_ftype_to_code ]

end

function _code_to_refface(code)
  if length(code) == 0
    return VERTEX
  else
    t = tuple(code...)
    p = Polytope(t)
    return RefCell(p)
  end
end

function _ftypes(dim_to_jface_to_code)
  dim_to_jface_to_ftype = Vector{Int}[]
  dim_to_ftype_to_code = Vector{Vector{Int}}[]
  for d in 1:length(dim_to_jface_to_code)
    jface_to_code = dim_to_jface_to_code[d]
    jface_to_ftype, ftype_to_code = _find_unique_codes(jface_to_code)
    push!(dim_to_jface_to_ftype,jface_to_ftype)
    push!(dim_to_ftype_to_code,ftype_to_code)
  end
  (dim_to_jface_to_ftype, dim_to_ftype_to_code)
end

function _coordinates(polytope)
  num_nfaces = length(polytope.nf_dim)
  nvertices = 0
  for nface in 1:num_nfaces
    d = length(polytope.nf_dim[nface])-1
    if d == 0
      nvertices += 1
    end
  end
  dim = length(polytope.extrusion)
  coords = Array{Float64,2}(undef,(dim,nvertices))
  x = Vector{Float64}(undef,dim)
  for nface in 1:num_nfaces
    d = length(polytope.nf_dim[nface])-1
    if d == 0
      x .= polytope.nfaces[nface].anchor.array
      coords[:,nface] .= x
    end
  end
  coords
end

# TODO use this once NodesArray works for general polytopes
#function _coordinates(polytope::Polytope{D}) where D
#  orders = fill(1,D)
#  na = NodesArray(polytope,orders)
#  x = na.coordinates
#  nnodes = length(x)
#  coords = Array{Float64,2}(undef,(D,nnodes))
#  for i in 1:nnodes
#    for d in 1:D
#      coords[d,i] = x[i][d]
#    end
#  end
#  coords
#end

function _vtknodes(code)
  h = HEX_AXIS
  t = TET_AXIS
  if code == [] ; [1,]
  elseif code[2:end] == [] ; [1,2]
  elseif code[2:end] == [t] ; [1,2,3]
  elseif code[2:end] == [h] ; [1,2,4,3]
  elseif code[2:end] == [t,t] ; [1,2,3,4]
  elseif code[2:end] == [h,h] ; [1,2,4,3,5,6,8,7]
  else; Int[]
  end
end

function _vtkid(code)
  h = HEX_AXIS
  t = TET_AXIS
  if code == []; 1
  elseif code[2:end] == []; 3
  elseif code[2:end] == [t]; 5
  elseif code[2:end] == [h]; 9
  elseif code[2:end] == [t,t]; 10
  elseif code[2:end] == [h,h]; 12
  else; UNSET
  end
end

function _vtkinfo(polytope)
  code = [i for i in polytope.extrusion.array]
  (_vtkid(code), _vtknodes(code))
end

function _extract_nface_to_info(polytope)
  num_nfaces = length(polytope.nf_dim)
  nface_to_dim = zeros(Int,num_nfaces)
  nface_to_vertices = Vector{Vector{Int}}(undef,num_nfaces)
  nface_to_code = Vector{Vector{Int}}(undef,num_nfaces)
  vdim = 0
  for nface in 1:num_nfaces
    nface_to_dim[nface] = length(polytope.nf_dim[nface])-1
    v = polytope.nf_dim[nface][vdim+1]
    nface_to_vertices[nface] = polytope.nf_nfs[nface][v]
    nface_to_code[nface] = _nface_code(polytope.nfaces[nface])
  end
  (nface_to_dim, nface_to_vertices, nface_to_code)
end

function _nface_code(nface)
  [ i for i in nface.extrusion if i != 0 ]
end

function _sort_nfaces_to_vertices_per_dim(
  nface_to_dim, nface_to_vertices, nface_to_code)
  num_nfaces = length(nface_to_dim)
  ndims = maximum(nface_to_dim)
  dim_to_jface_to_vertices = Vector{Vector{Vector{Int}}}(undef,ndims)
  dim_to_jface_to_code = Vector{Vector{Vector{Int}}}(undef,ndims)
  vdim = 0
  for d in 0:ndims-1
    jface_to_vertices = Vector{Vector{Int}}(undef,0)
    jface_to_code = Vector{Vector{Int}}(undef,0)
    for nface in 1:num_nfaces
      if nface_to_dim[nface] == d
        push!(jface_to_vertices,nface_to_vertices[nface])
        push!(jface_to_code, nface_to_code[nface])
      end
    end
    dim_to_jface_to_vertices[d+1] = jface_to_vertices
    dim_to_jface_to_code[d+1] = jface_to_code
  end
  dim_to_jface_to_vertices, dim_to_jface_to_code
end

function _find_unique_codes(jface_to_code)
  ftype_to_code = unique(jface_to_code)
  _jface_to_ftype = indexin(jface_to_code,ftype_to_code)
  jface_to_ftype = _remove_nothing(_jface_to_ftype)
  (jface_to_ftype, ftype_to_code)
end

function _remove_nothing(a)
  b = Vector{Int}(undef,size(a))
  b .= a
end

end # module


text:
import Base.in
import Base.==
import Base.length
import Base.start
import Base.done
import Base.next
import Base.string
import Base.show
import Base.enumerate
import Base.isequal
import Base.print
import Base.println
import Base.display

immutable TSet
    dict::Dict{Tuple{Any,DataType},Any}

    TSet() = new(Dict{Tuple{Any,DataType},Any}())
    TSet(itr) = new([(x, typeof(x)) => x for x in itr])
end

in(x, s::TSet) = haskey(s.dict, (x, typeof(x)))
==(s::TSet, t::TSet) = ==(s.dict, t.dict)
length(s::TSet) = length(s.dict)
start(s::TSet) = start(s.dict)
function next(s::TSet, x::Any)
    nextdict = next(s.dict, x)
    return (nextdict[1][2], nextdict[2])
end

done(s::TSet, state::Any) = done(s.dict, state)
enumerate(s::TSet) = enumerate(values(s.dict))
string(s::TSet) = "TSet($(join(map(string, [a for a in s]), ",")))"
show(s::TSet) = println(string(s))
display(s::TSet) = println(string(s))
print(io::IO, s::TSet) = print(io, string(s))

const hashtset_seed = UInt === UInt64 ? 0x852ada37cfe8e0ce : 0xcfe8e0ce
function hash(s::TSet, h::UInt)
    h = hash(hashtset_seed, h)
    for x in s
        h $= hash(x)
    end
    return h
end


text:
using BenchmarkTools

"""
    look_and_say_sequence(startsequence, n)

Construct the look and say sequence of order n and starting sequence startsequence.
"""
#function look_and_say_sequence(startsequence::String, n::Integer)
function look_and_say_sequence(startsequence, n)
    currentsequence = startsequence

    i = 2

    while i <= n
        count = 1
        tempseries = ""
        for j in 2:length(currentsequence)
            if currentsequence[j] == currentsequence[j-1]
                count += 1
            else
                tempseries = string(tempseries, count, currentsequence[j-1])
                count = 1
            end
        end
        tempseries = string(tempseries, count, currentsequence[length(currentsequence)])
        currentsequence = tempseries
        i += 1
    end
    return currentsequence
end

N = parse(Int, ARGS[1])

println("--------------------------")
println(@sprintf "Look and say sequence: %d" N)
println("--------------------------")

@btime begin
    r = look_and_say_sequence("1223334444", N)
end
#   println(r)