text:
# Julia wrapper for header: niFgen.h
# Automatically generated using Clang.jl

function niFgen_init(resourceName, IDQuery, resetDevice, vi)
    ccall((:niFgen_init, libnifgen), ViStatus, (ViRsrc, ViBoolean, ViBoolean, Ptr{ViSession}), resourceName, IDQuery, resetDevice, vi)
end

function niFgen_InitWithOptions(resourceName, IDQuery, resetDevice, optionString, newVi)
    ccall((:niFgen_InitWithOptions, libnifgen), ViStatus, (ViRsrc, ViBoolean, ViBoolean, ViConstString, Ptr{ViSession}), resourceName, IDQuery, resetDevice, optionString, newVi)
end

function niFgen_InitializeWithChannels(resourceName, channelName, resetDevice, optionString, newVi)
    ccall((:niFgen_InitializeWithChannels, libnifgen), ViStatus, (ViRsrc, ViConstString, ViBoolean, ViConstString, Ptr{ViSession}), resourceName, channelName, resetDevice, optionString, newVi)
end

function niFgen_close(vi)
    ccall((:niFgen_close, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_reset(vi)
    ccall((:niFgen_reset, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_self_test(vi, testResult, testMessage)
    ccall((:niFgen_self_test, libnifgen), ViStatus, (ViSession, Ptr{ViInt16}, Ptr{ViChar}), vi, testResult, testMessage)
end

function niFgen_error_query(vi, errorCode, selfTestMessage)
    ccall((:niFgen_error_query, libnifgen), ViStatus, (ViSession, Ptr{ViInt32}, Ptr{ViChar}), vi, errorCode, selfTestMessage)
end

function niFgen_error_message(vi, statusCode, message)
    ccall((:niFgen_error_message, libnifgen), ViStatus, (ViSession, ViStatus, Ptr{ViChar}), vi, statusCode, message)
end

function niFgen_revision_query(vi, driverRev, instrRev)
    ccall((:niFgen_revision_query, libnifgen), ViStatus, (ViSession, Ptr{ViChar}, Ptr{ViChar}), vi, driverRev, instrRev)
end

function niFgen_GetError(vi, errorCode, errorDescriptionBufferSize, errorDescription)
    ccall((:niFgen_GetError, libnifgen), ViStatus, (ViSession, Ptr{ViStatus}, ViInt32, Ptr{ViChar}), vi, errorCode, errorDescriptionBufferSize, errorDescription)
end

function niFgen_ClearError(vi)
    ccall((:niFgen_ClearError, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_ErrorHandler(vi, statusCode, errorMessage)
    ccall((:niFgen_ErrorHandler, libnifgen), ViStatus, (ViSession, ViStatus, Ptr{ViChar}), vi, statusCode, errorMessage)
end

function niFgen_LockSession(vi, callerHasLock)
    ccall((:niFgen_LockSession, libnifgen), ViStatus, (ViSession, Ptr{ViBoolean}), vi, callerHasLock)
end

function niFgen_UnlockSession(vi, callerHasLock)
    ccall((:niFgen_UnlockSession, libnifgen), ViStatus, (ViSession, Ptr{ViBoolean}), vi, callerHasLock)
end

function niFgen_GetChannelName(vi, index, bufferSize, name)
    ccall((:niFgen_GetChannelName, libnifgen), ViStatus, (ViSession, ViInt32, ViInt32, Ptr{ViChar}), vi, index, bufferSize, name)
end

function niFgen_GetNextInterchangeWarning(vi, bufferSize, warnString)
    ccall((:niFgen_GetNextInterchangeWarning, libnifgen), ViStatus, (ViSession, ViInt32, Ptr{ViChar}), vi, bufferSize, warnString)
end

function niFgen_ResetInterchangeCheck(vi)
    ccall((:niFgen_ResetInterchangeCheck, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_ClearInterchangeWarnings(vi)
    ccall((:niFgen_ClearInterchangeWarnings, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_GetNextCoercionRecord(vi, bufferSize, record)
    ccall((:niFgen_GetNextCoercionRecord, libnifgen), ViStatus, (ViSession, ViInt32, Ptr{ViChar}), vi, bufferSize, record)
end

function niFgen_InvalidateAllAttributes(vi)
    ccall((:niFgen_InvalidateAllAttributes, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_ResetWithDefaults(vi)
    ccall((:niFgen_ResetWithDefaults, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_Disable(vi)
    ccall((:niFgen_Disable, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_Commit(vi)
    ccall((:niFgen_Commit, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_GetHardwareState(vi, state)
    ccall((:niFgen_GetHardwareState, libnifgen), ViStatus, (ViSession, Ptr{ViInt32}), vi, state)
end

function niFgen_WaitUntilDone(vi, maxTime)
    ccall((:niFgen_WaitUntilDone, libnifgen), ViStatus, (ViSession, ViInt32), vi, maxTime)
end

function niFgen_IsDone(vi, done)
    ccall((:niFgen_IsDone, libnifgen), ViStatus, (ViSession, Ptr{ViBoolean}), vi, done)
end

function niFgen_ResetDevice(vi)
    ccall((:niFgen_ResetDevice, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_ConfigureOperationMode(vi, channelName, mode)
    ccall((:niFgen_ConfigureOperationMode, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32), vi, channelName, mode)
end

function niFgen_ConfigureOutputMode(vi, outputMode)
    ccall((:niFgen_ConfigureOutputMode, libnifgen), ViStatus, (ViSession, ViInt32), vi, outputMode)
end

function niFgen_ConfigureReferenceClock(vi, referenceClockSource, referenceClockFrequency)
    ccall((:niFgen_ConfigureReferenceClock, libnifgen), ViStatus, (ViSession, ViConstString, ViReal64), vi, referenceClockSource, referenceClockFrequency)
end

function niFgen_ConfigureOutputImpedance(vi, channelName, outputImpedance)
    ccall((:niFgen_ConfigureOutputImpedance, libnifgen), ViStatus, (ViSession, ViConstString, ViReal64), vi, channelName, outputImpedance)
end

function niFgen_ConfigureOutputEnabled(vi, channelName, enabled)
    ccall((:niFgen_ConfigureOutputEnabled, libnifgen), ViStatus, (ViSession, ViConstString, ViBoolean), vi, channelName, enabled)
end

function niFgen_ConfigureChannels(vi, channelName)
    ccall((:niFgen_ConfigureChannels, libnifgen), ViStatus, (ViSession, ViConstString), vi, channelName)
end

function niFgen_InitiateGeneration(vi)
    ccall((:niFgen_InitiateGeneration, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_AbortGeneration(vi)
    ccall((:niFgen_AbortGeneration, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_ConfigureStandardWaveform(vi, channelName, waveform, amplitude, dcOffset, frequency, startPhase)
    ccall((:niFgen_ConfigureStandardWaveform, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViReal64, ViReal64, ViReal64, ViReal64), vi, channelName, waveform, amplitude, dcOffset, frequency, startPhase)
end

function niFgen_DefineUserStandardWaveform(vi, channelName, numberOfSamples, data)
    ccall((:niFgen_DefineUserStandardWaveform, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViReal64}), vi, channelName, numberOfSamples, data)
end

function niFgen_ClearUserStandardWaveform(vi, channelName)
    ccall((:niFgen_ClearUserStandardWaveform, libnifgen), ViStatus, (ViSession, ViConstString), vi, channelName)
end

function niFgen_ConfigureFrequency(vi, channelName, Frequency)
    ccall((:niFgen_ConfigureFrequency, libnifgen), ViStatus, (ViSession, ViConstString, ViReal64), vi, channelName, Frequency)
end

function niFgen_ConfigureAmplitude(vi, channelName, Amplitude)
    ccall((:niFgen_ConfigureAmplitude, libnifgen), ViStatus, (ViSession, ViConstString, ViReal64), vi, channelName, Amplitude)
end

function niFgen_QueryArbWfmCapabilities(vi, maxNumWfms, wfmQuantum, minNumberOfSamples, maxNumberOfSamples)
    ccall((:niFgen_QueryArbWfmCapabilities, libnifgen), ViStatus, (ViSession, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}), vi, maxNumWfms, wfmQuantum, minNumberOfSamples, maxNumberOfSamples)
end

function niFgen_CreateWaveformF64(vi, channelName, numberOfSamples, wfmData, wfmHandle)
    ccall((:niFgen_CreateWaveformF64, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViReal64}, Ptr{ViInt32}), vi, channelName, numberOfSamples, wfmData, wfmHandle)
end

function niFgen_CreateWaveformI16(vi, channelName, numberOfSamples, wfmData, wfmHandle)
    ccall((:niFgen_CreateWaveformI16, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViInt16}, Ptr{ViInt32}), vi, channelName, numberOfSamples, wfmData, wfmHandle)
end

function niFgen_CreateWaveformComplexF64(vi, channelName, numberOfSamples, wfmData, wfmHandle)
    ccall((:niFgen_CreateWaveformComplexF64, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{NIComplexNumber}, Ptr{ViInt32}), vi, channelName, numberOfSamples, wfmData, wfmHandle)
end

function niFgen_CreateWaveformFromFileI16(vi, channelName, fileName, byteOrder, wfmHandle)
    ccall((:niFgen_CreateWaveformFromFileI16, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32, Ptr{ViInt32}), vi, channelName, fileName, byteOrder, wfmHandle)
end

function niFgen_CreateWaveformFromFileF64(vi, channelName, fileName, byteOrder, wfmHandle)
    ccall((:niFgen_CreateWaveformFromFileF64, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32, Ptr{ViInt32}), vi, channelName, fileName, byteOrder, wfmHandle)
end

function niFgen_CreateWaveformFromFileHWS(vi, channelName, fileName, useRateFromWaveform, useGainAndOffsetFromWaveform, wfmHandle)
    ccall((:niFgen_CreateWaveformFromFileHWS, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViBoolean, ViBoolean, Ptr{ViInt32}), vi, channelName, fileName, useRateFromWaveform, useGainAndOffsetFromWaveform, wfmHandle)
end

function niFgen_ConfigureSampleRate(vi, sampleRate)
    ccall((:niFgen_ConfigureSampleRate, libnifgen), ViStatus, (ViSession, ViReal64), vi, sampleRate)
end

function niFgen_ConfigureArbWaveform(vi, channelName, wfmHandle, arbGain, arbOffset)
    ccall((:niFgen_ConfigureArbWaveform, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViReal64, ViReal64), vi, channelName, wfmHandle, arbGain, arbOffset)
end

function niFgen_ClearArbWaveform(vi, wfmHandle)
    ccall((:niFgen_ClearArbWaveform, libnifgen), ViStatus, (ViSession, ViInt32), vi, wfmHandle)
end

function niFgen_AllocateNamedWaveform(vi, channelName, wfmName, numberOfSamples)
    ccall((:niFgen_AllocateNamedWaveform, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32), vi, channelName, wfmName, numberOfSamples)
end

function niFgen_SetNamedWaveformNextWritePosition(vi, channelName, wfmName, relativeTo, offset)
    ccall((:niFgen_SetNamedWaveformNextWritePosition, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32, ViInt32), vi, channelName, wfmName, relativeTo, offset)
end

function niFgen_WriteNamedWaveformF64(vi, channelName, wfmName, numberOfSamples, wfmData)
    ccall((:niFgen_WriteNamedWaveformF64, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32, Ptr{ViReal64}), vi, channelName, wfmName, numberOfSamples, wfmData)
end

function niFgen_WriteNamedWaveformI16(vi, channelName, wfmName, numberOfSamples, wfmData)
    ccall((:niFgen_WriteNamedWaveformI16, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32, Ptr{ViInt16}), vi, channelName, wfmName, numberOfSamples, wfmData)
end

function niFgen_WriteNamedWaveformComplexF64(vi, channelName, wfmName, numberOfSamples, wfmData)
    ccall((:niFgen_WriteNamedWaveformComplexF64, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32, Ptr{NIComplexNumber}), vi, channelName, wfmName, numberOfSamples, wfmData)
end

function niFgen_WriteNamedWaveformComplexI16(vi, channelName, wfmName, numberOfSamples, wfmData)
    ccall((:niFgen_WriteNamedWaveformComplexI16, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32, Ptr{NIComplexI16}), vi, channelName, wfmName, numberOfSamples, wfmData)
end

function niFgen_DeleteNamedWaveform(vi, channelName, wfmName)
    ccall((:niFgen_DeleteNamedWaveform, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString), vi, channelName, wfmName)
end

function niFgen_QueryArbSeqCapabilities(vi, maxNumSeqs, minSeqLength, maxSeqLength, maxLoopCount)
    ccall((:niFgen_QueryArbSeqCapabilities, libnifgen), ViStatus, (ViSession, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}), vi, maxNumSeqs, minSeqLength, maxSeqLength, maxLoopCount)
end

function niFgen_CreateArbSequence(vi, seqLength, wfmHandle, wfmLoopCount, seqHandle)
    ccall((:niFgen_CreateArbSequence, libnifgen), ViStatus, (ViSession, ViInt32, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}), vi, seqLength, wfmHandle, wfmLoopCount, seqHandle)
end

function niFgen_CreateAdvancedArbSequence(vi, seqLength, wfmHandles, loopCounts, sampleCounts, markers, coercedMarkers, seqHandle)
    ccall((:niFgen_CreateAdvancedArbSequence, libnifgen), ViStatus, (ViSession, ViInt32, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}), vi, seqLength, wfmHandles, loopCounts, sampleCounts, markers, coercedMarkers, seqHandle)
end

function niFgen_ConfigureArbSequence(vi, channelName, seqHandle, arbGain, arbOffset)
    ccall((:niFgen_ConfigureArbSequence, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViReal64, ViReal64), vi, channelName, seqHandle, arbGain, arbOffset)
end

function niFgen_ClearArbSequence(vi, seqHandle)
    ccall((:niFgen_ClearArbSequence, libnifgen), ViStatus, (ViSession, ViInt32), vi, seqHandle)
end

function niFgen_ClearArbMemory(vi)
    ccall((:niFgen_ClearArbMemory, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_QueryFreqListCapabilities(vi, maximumNumberOfFreqLists, minimumFrequencyListLength, maximumFrequencyListLength, minimumFrequencyListDuration, maximumFrequencyListDuration, frequencyListDurationQuantum)
    ccall((:niFgen_QueryFreqListCapabilities, libnifgen), ViStatus, (ViSession, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViReal64}, Ptr{ViReal64}, Ptr{ViReal64}), vi, maximumNumberOfFreqLists, minimumFrequencyListLength, maximumFrequencyListLength, minimumFrequencyListDuration, maximumFrequencyListDuration, frequencyListDurationQuantum)
end

function niFgen_CreateFreqList(vi, waveform, frequencyListLength, frequencyArray, durationArray, frequencyListHandle)
    ccall((:niFgen_CreateFreqList, libnifgen), ViStatus, (ViSession, ViInt32, ViInt32, Ptr{ViReal64}, Ptr{ViReal64}, Ptr{ViInt32}), vi, waveform, frequencyListLength, frequencyArray, durationArray, frequencyListHandle)
end

function niFgen_ConfigureFreqList(vi, channelName, frequencyListHandle, amplitude, dcOffset, startPhase)
    ccall((:niFgen_ConfigureFreqList, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViReal64, ViReal64, ViReal64), vi, channelName, frequencyListHandle, amplitude, dcOffset, startPhase)
end

function niFgen_ClearFreqList(vi, frequencyListHandle)
    ccall((:niFgen_ClearFreqList, libnifgen), ViStatus, (ViSession, ViInt32), vi, frequencyListHandle)
end

function niFgen_WriteScript(vi, channelName, script)
    ccall((:niFgen_WriteScript, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString), vi, channelName, script)
end

function niFgen_DeleteScript(vi, channelName, scriptName)
    ccall((:niFgen_DeleteScript, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString), vi, channelName, scriptName)
end

function niFgen_ExportSignal(vi, signal, signalIdentifier, outputTerminal)
    ccall((:niFgen_ExportSignal, libnifgen), ViStatus, (ViSession, ViInt32, ViConstString, ViConstString), vi, signal, signalIdentifier, outputTerminal)
end

function niFgen_RouteSignalOut(vi, channelName, from, to)
    ccall((:niFgen_RouteSignalOut, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViInt32), vi, channelName, from, to)
end

function niFgen_SendSoftwareEdgeTrigger(vi, triggerName, triggerIdentifier)
    ccall((:niFgen_SendSoftwareEdgeTrigger, libnifgen), ViStatus, (ViSession, ViInt32, ViConstString), vi, triggerName, triggerIdentifier)
end

function niFgen_ConfigureDigitalEdgeStartTrigger(vi, source, edge)
    ccall((:niFgen_ConfigureDigitalEdgeStartTrigger, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32), vi, source, edge)
end

function niFgen_ConfigureSoftwareEdgeStartTrigger(vi)
    ccall((:niFgen_ConfigureSoftwareEdgeStartTrigger, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_DisableStartTrigger(vi)
    ccall((:niFgen_DisableStartTrigger, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_ConfigureP2PEndpointFullnessStartTrigger(vi, p2pEndpointFullnessLevel)
    ccall((:niFgen_ConfigureP2PEndpointFullnessStartTrigger, libnifgen), ViStatus, (ViSession, ViInt32), vi, p2pEndpointFullnessLevel)
end

function niFgen_ConfigureDigitalEdgeScriptTrigger(vi, triggerID, source, edge)
    ccall((:niFgen_ConfigureDigitalEdgeScriptTrigger, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32), vi, triggerID, source, edge)
end

function niFgen_ConfigureDigitalLevelScriptTrigger(vi, triggerID, source, level)
    ccall((:niFgen_ConfigureDigitalLevelScriptTrigger, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString, ViInt32), vi, triggerID, source, level)
end

function niFgen_ConfigureSoftwareEdgeScriptTrigger(vi, triggerID)
    ccall((:niFgen_ConfigureSoftwareEdgeScriptTrigger, libnifgen), ViStatus, (ViSession, ViConstString), vi, triggerID)
end

function niFgen_DisableScriptTrigger(vi, triggerID)
    ccall((:niFgen_DisableScriptTrigger, libnifgen), ViStatus, (ViSession, ViConstString), vi, triggerID)
end

function niFgen_ConfigureClockMode(vi, clockMode)
    ccall((:niFgen_ConfigureClockMode, libnifgen), ViStatus, (ViSession, ViInt32), vi, clockMode)
end

function niFgen_AdjustSampleClockRelativeDelay(vi, tm)
    ccall((:niFgen_AdjustSampleClockRelativeDelay, libnifgen), ViStatus, (ViSession, ViReal64), vi, tm)
end

function niFgen_AllocateWaveform(vi, channelName, numberOfSamples, waveformHandle)
    ccall((:niFgen_AllocateWaveform, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViInt32}), vi, channelName, numberOfSamples, waveformHandle)
end

function niFgen_SetWaveformNextWritePosition(vi, channelName, waveformHandle, relativeTo, offset)
    ccall((:niFgen_SetWaveformNextWritePosition, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViInt32, ViInt32), vi, channelName, waveformHandle, relativeTo, offset)
end

function niFgen_WriteWaveform(vi, channelName, waveformHandle, numberOfSamples, wfmData)
    ccall((:niFgen_WriteWaveform, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViInt32, Ptr{ViReal64}), vi, channelName, waveformHandle, numberOfSamples, wfmData)
end

function niFgen_WriteBinary16Waveform(vi, channelName, waveformHandle, numberOfSamples, wfmData)
    ccall((:niFgen_WriteBinary16Waveform, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViInt32, Ptr{ViInt16}), vi, channelName, waveformHandle, numberOfSamples, wfmData)
end

function niFgen_WriteWaveformComplexF64(vi, channelName, numberOfSamples, wfmData, wfmHandle)
    ccall((:niFgen_WriteWaveformComplexF64, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{NIComplexNumber}, ViInt32), vi, channelName, numberOfSamples, wfmData, wfmHandle)
end

function niFgen_WriteComplexBinary16Waveform(vi, channelName, waveformHandle, numberOfSamples, wfmData)
    ccall((:niFgen_WriteComplexBinary16Waveform, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViInt32, Ptr{NIComplexI16}), vi, channelName, waveformHandle, numberOfSamples, wfmData)
end

function niFgen_InitExtCal(resourceName, password, vi)
    ccall((:niFgen_InitExtCal, libnifgen), ViStatus, (ViRsrc, ViConstString, Ptr{ViSession}), resourceName, password, vi)
end

function niFgen_InitializeOscillatorFrequencyCalibration(vi)
    ccall((:niFgen_InitializeOscillatorFrequencyCalibration, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_InitializeAnalogOutputCalibration(vi)
    ccall((:niFgen_InitializeAnalogOutputCalibration, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_InitializeCalADCCalibration(vi)
    ccall((:niFgen_InitializeCalADCCalibration, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_InitializeFlatnessCalibration(vi)
    ccall((:niFgen_InitializeFlatnessCalibration, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_CloseExtCal(vi, action)
    ccall((:niFgen_CloseExtCal, libnifgen), ViStatus, (ViSession, ViInt32), vi, action)
end

function niFgen_SelfCal(vi)
    ccall((:niFgen_SelfCal, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_RestoreLastExtCalConstants(vi)
    ccall((:niFgen_RestoreLastExtCalConstants, libnifgen), ViStatus, (ViSession,), vi)
end

function niFgen_GetSelfCalSupported(vi, selfCalSupported)
    ccall((:niFgen_GetSelfCalSupported, libnifgen), ViStatus, (ViSession, Ptr{ViBoolean}), vi, selfCalSupported)
end

function niFgen_GetSelfCalLastDateAndTime(vi, year, month, day, hour, minute)
    ccall((:niFgen_GetSelfCalLastDateAndTime, libnifgen), ViStatus, (ViSession, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}), vi, year, month, day, hour, minute)
end

function niFgen_GetExtCalLastDateAndTime(vi, year, month, day, hour, minute)
    ccall((:niFgen_GetExtCalLastDateAndTime, libnifgen), ViStatus, (ViSession, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}), vi, year, month, day, hour, minute)
end

function niFgen_GetSelfCalLastTemp(vi, temp)
    ccall((:niFgen_GetSelfCalLastTemp, libnifgen), ViStatus, (ViSession, Ptr{ViReal64}), vi, temp)
end

function niFgen_GetExtCalLastTemp(vi, temp)
    ccall((:niFgen_GetExtCalLastTemp, libnifgen), ViStatus, (ViSession, Ptr{ViReal64}), vi, temp)
end

function niFgen_GetExtCalRecommendedInterval(vi, months)
    ccall((:niFgen_GetExtCalRecommendedInterval, libnifgen), ViStatus, (ViSession, Ptr{ViInt32}), vi, months)
end

function niFgen_ChangeExtCalPassword(vi, oldPassword, newPassword)
    ccall((:niFgen_ChangeExtCalPassword, libnifgen), ViStatus, (ViSession, ViConstString, ViConstString), vi, oldPassword, newPassword)
end

function niFgen_SetCalUserDefinedInfo(vi, info)
    ccall((:niFgen_SetCalUserDefinedInfo, libnifgen), ViStatus, (ViSession, ViConstString), vi, info)
end

function niFgen_GetCalUserDefinedInfo(vi, info)
    ccall((:niFgen_GetCalUserDefinedInfo, libnifgen), ViStatus, (ViSession, ViString), vi, info)
end

function niFgen_GetCalUserDefinedInfoMaxSize(vi, infoSize)
    ccall((:niFgen_GetCalUserDefinedInfoMaxSize, libnifgen), ViStatus, (ViSession, Ptr{ViInt32}), vi, infoSize)
end

function niFgen_ReadCurrentTemperature(vi, temperature)
    ccall((:niFgen_ReadCurrentTemperature, libnifgen), ViStatus, (ViSession, Ptr{ViReal64}), vi, temperature)
end

function niFgen_ReadCalADC(vi, numberOfReadsToAverage, returnCalibratedValue, calADCValue)
    ccall((:niFgen_ReadCalADC, libnifgen), ViStatus, (ViSession, ViInt32, ViBoolean, Ptr{ViReal64}), vi, numberOfReadsToAverage, returnCalibratedValue, calADCValue)
end

function niFgen_WriteBinary16AnalogStaticValue(vi, channelName, value)
    ccall((:niFgen_WriteBinary16AnalogStaticValue, libnifgen), ViStatus, (ViSession, ViConstString, ViInt16), vi, channelName, value)
end

function niFgen_CalAdjustMainPathPreAmpOffset(vi, channelName, configuration, gainDACValues, offsetDACValues, measuredOutputs)
    ccall((:niFgen_CalAdjustMainPathPreAmpOffset, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViReal64}), vi, channelName, configuration, gainDACValues, offsetDACValues, measuredOutputs)
end

function niFgen_CalAdjustMainPathPreAmpGain(vi, channelName, configuration, mainDACValues, gainDACValues, offsetDACValues, measuredOutputs)
    ccall((:niFgen_CalAdjustMainPathPreAmpGain, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViReal64}), vi, channelName, configuration, mainDACValues, gainDACValues, offsetDACValues, measuredOutputs)
end

function niFgen_CalAdjustMainPathPostAmpGainAndOffset(vi, channelName, configuration, mainDACValues, gainDACValues, offsetDACValues, measuredOutputs)
    ccall((:niFgen_CalAdjustMainPathPostAmpGainAndOffset, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViReal64}), vi, channelName, configuration, mainDACValues, gainDACValues, offsetDACValues, measuredOutputs)
end

function niFgen_CalAdjustDirectPathGain(vi, channelName, mainDACValues, gainDACValues, measuredOutputs)
    ccall((:niFgen_CalAdjustDirectPathGain, libnifgen), ViStatus, (ViSession, ViConstString, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViReal64}), vi, channelName, mainDACValues, gainDACValues, measuredOutputs)
end

function niFgen_CalAdjustMainPathOutputImpedance(vi, channelName, configuration, loadImpedance, measuredSourceVoltage, measuredVoltageAcrossLoad)
    ccall((:niFgen_CalAdjustMainPathOutputImpedance, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViReal64, ViReal64, ViReal64), vi, channelName, configuration, loadImpedance, measuredSourceVoltage, measuredVoltageAcrossLoad)
end

function niFgen_CalAdjustDirectPathOutputImpedance(vi, channelName, configuration, loadImpedance, measuredSourceVoltage, measuredVoltageAcrossLoad)
    ccall((:niFgen_CalAdjustDirectPathOutputImpedance, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViReal64, ViReal64, ViReal64), vi, channelName, configuration, loadImpedance, measuredSourceVoltage, measuredVoltageAcrossLoad)
end

function niFgen_CalAdjustOscillatorFrequency(vi, desiredFrequencyInHz, measuredFrequencyInHz)
    ccall((:niFgen_CalAdjustOscillatorFrequency, libnifgen), ViStatus, (ViSession, ViReal64, ViReal64), vi, desiredFrequencyInHz, measuredFrequencyInHz)
end

function niFgen_CalAdjustADC(vi, channelName, configuration, voltagesMeasuredExternally, voltagesMeasuredWithCalADC)
    ccall((:niFgen_CalAdjustADC, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViReal64}, Ptr{ViReal64}), vi, channelName, configuration, voltagesMeasuredExternally, voltagesMeasuredWithCalADC)
end

function niFgen_CalAdjustFlatness(vi, channelName, configuration, requestedAmplitude, frequencies, measuredAmplitudes, numberOfMeasurements)
    ccall((:niFgen_CalAdjustFlatness, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, ViReal64, Ptr{ViReal64}, Ptr{ViReal64}, ViInt32), vi, channelName, configuration, requestedAmplitude, frequencies, measuredAmplitudes, numberOfMeasurements)
end

function niFgen_ConfigureCustomFIRFilterCoefficients(vi, channelName, numberOfCoefficients, coefficients)
    ccall((:niFgen_ConfigureCustomFIRFilterCoefficients, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViReal64}), vi, channelName, numberOfCoefficients, coefficients)
end

function niFgen_GetFIRFilterCoefficients(vi, channelName, arraySize, coefficients, numberOfCoefficientsRead)
    ccall((:niFgen_GetFIRFilterCoefficients, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViReal64}, Ptr{ViInt32}), vi, channelName, arraySize, coefficients, numberOfCoefficientsRead)
end

function niFgen_GetStreamEndpointHandle(vi, streamEndpoint, readerHandle)
    ccall((:niFgen_GetStreamEndpointHandle, libnifgen), ViStatus, (ViSession, ViConstString, Ptr{ViUInt32}), vi, streamEndpoint, readerHandle)
end

function niFgen_ManualEnableP2PStream(vi, streamEndpoint)
    ccall((:niFgen_ManualEnableP2PStream, libnifgen), ViStatus, (ViSession, ViConstString), vi, streamEndpoint)
end

function niFgen_WriteP2PEndpointI16(vi, fifoEndpointName, numberOfSamples, endpointData)
    ccall((:niFgen_WriteP2PEndpointI16, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViInt16}), vi, fifoEndpointName, numberOfSamples, endpointData)
end

function niFgen_ConfigureSynchronization(vi, channelName, Synchronization)
    ccall((:niFgen_ConfigureSynchronization, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32), vi, channelName, Synchronization)
end

function niFgen_EnableDigitalPatterning(vi, channelName)
    ccall((:niFgen_EnableDigitalPatterning, libnifgen), ViStatus, (ViSession, ViConstString), vi, channelName)
end

function niFgen_DisableDigitalPatterning(vi, channelName)
    ccall((:niFgen_DisableDigitalPatterning, libnifgen), ViStatus, (ViSession, ViConstString), vi, channelName)
end

function niFgen_EnableDigitalFilter(vi, channelName)
    ccall((:niFgen_EnableDigitalFilter, libnifgen), ViStatus, (ViSession, ViConstString), vi, channelName)
end

function niFgen_DisableDigitalFilter(vi, channelName)
    ccall((:niFgen_DisableDigitalFilter, libnifgen), ViStatus, (ViSession, ViConstString), vi, channelName)
end

function niFgen_EnableAnalogFilter(vi, channelName, filterCorrectionFreq)
    ccall((:niFgen_EnableAnalogFilter, libnifgen), ViStatus, (ViSession, ViConstString, ViReal64), vi, channelName, filterCorrectionFreq)
end

function niFgen_DisableAnalogFilter(vi, channelName)
    ccall((:niFgen_DisableAnalogFilter, libnifgen), ViStatus, (ViSession, ViConstString), vi, channelName)
end

function niFgen_ConfigureSampleClockSource(vi, sampleClockSource)
    ccall((:niFgen_ConfigureSampleClockSource, libnifgen), ViStatus, (ViSession, ViConstString), vi, sampleClockSource)
end

function niFgen_ConfigureTriggerMode(vi, channelName, mode)
    ccall((:niFgen_ConfigureTriggerMode, libnifgen), ViStatus, (ViSession, ViConstString, ViInt32), vi, channelName, mode)
end

function niFgen_ImportAttributeConfigurationFile(vi, filePath)
    ccall((:niFgen_ImportAttributeConfigurationFile, libnifgen), ViStatus, (ViSession, ViConstString), vi, filePath)
end

function niFgen_ExportAttributeConfigurationFile(vi, filePath)
    ccall((:niFgen_ExportAttributeConfigurationFile, libnifgen), ViStatus, (ViSession, ViConstString), vi, filePath)
end

function niFgen_ImportAttributeConfigurationBuffer(vi, sz, configuration)
    ccall((:niFgen_ImportAttributeConfigurationBuffer, libnifgen), ViStatus, (ViSession, ViInt32, ViAddr), vi, sz, configuration)
end

function niFgen_ExportAttributeConfigurationBuffer(vi, sz, configuration)
    ccall((:niFgen_ExportAttributeConfigurationBuffer, libnifgen), ViStatus, (ViSession, ViInt32, ViAddr), vi, sz, configuration)
end

function niFgen_SetAttributeViInt64(vi, channelName, attributeId, value)
    ccall((:niFgen_SetAttributeViInt64, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViInt64), vi, channelName, attributeId, value)
end

function niFgen_CheckAttributeViInt64(vi, channelName, attributeId, value)
    ccall((:niFgen_CheckAttributeViInt64, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViInt64), vi, channelName, attributeId, value)
end

function niFgen_GetAttributeViInt64(vi, channelName, attributeId, value)
    ccall((:niFgen_GetAttributeViInt64, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, Ptr{ViInt64}), vi, channelName, attributeId, value)
end

function niFgen_SetAttributeViInt32(vi, channelName, attributeId, value)
    ccall((:niFgen_SetAttributeViInt32, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViInt32), vi, channelName, attributeId, value)
end

function niFgen_SetAttributeViReal64(vi, channelName, attributeId, value)
    ccall((:niFgen_SetAttributeViReal64, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViReal64), vi, channelName, attributeId, value)
end

function niFgen_SetAttributeViString(vi, channelName, attributeId, value)
    ccall((:niFgen_SetAttributeViString, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViConstString), vi, channelName, attributeId, value)
end

function niFgen_SetAttributeViBoolean(vi, channelName, attributeId, value)
    ccall((:niFgen_SetAttributeViBoolean, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViBoolean), vi, channelName, attributeId, value)
end

function niFgen_SetAttributeViSession(vi, channelName, attributeId, value)
    ccall((:niFgen_SetAttributeViSession, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViSession), vi, channelName, attributeId, value)
end

function niFgen_CheckAttributeViInt32(vi, channelName, attributeId, value)
    ccall((:niFgen_CheckAttributeViInt32, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViInt32), vi, channelName, attributeId, value)
end

function niFgen_CheckAttributeViReal64(vi, channelName, attributeId, value)
    ccall((:niFgen_CheckAttributeViReal64, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViReal64), vi, channelName, attributeId, value)
end

function niFgen_CheckAttributeViString(vi, channelName, attributeId, value)
    ccall((:niFgen_CheckAttributeViString, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViConstString), vi, channelName, attributeId, value)
end

function niFgen_CheckAttributeViBoolean(vi, channelName, attributeId, value)
    ccall((:niFgen_CheckAttributeViBoolean, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViBoolean), vi, channelName, attributeId, value)
end

function niFgen_CheckAttributeViSession(vi, channelName, attributeId, value)
    ccall((:niFgen_CheckAttributeViSession, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViSession), vi, channelName, attributeId, value)
end

function niFgen_GetAttributeViInt32(vi, channelName, attributeId, value)
    ccall((:niFgen_GetAttributeViInt32, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, Ptr{ViInt32}), vi, channelName, attributeId, value)
end

function niFgen_GetAttributeViReal64(vi, channelName, attributeId, value)
    ccall((:niFgen_GetAttributeViReal64, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, Ptr{ViReal64}), vi, channelName, attributeId, value)
end

function niFgen_GetAttributeViString(vi, channelName, attributeId, bufSize, value)
    ccall((:niFgen_GetAttributeViString, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, ViInt32, Ptr{ViChar}), vi, channelName, attributeId, bufSize, value)
end

function niFgen_GetAttributeViBoolean(vi, channelName, attributeId, value)
    ccall((:niFgen_GetAttributeViBoolean, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, Ptr{ViBoolean}), vi, channelName, attributeId, value)
end

function niFgen_GetAttributeViSession(vi, channelName, attributeId, value)
    ccall((:niFgen_GetAttributeViSession, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr, Ptr{ViSession}), vi, channelName, attributeId, value)
end

function niFgen_ResetAttribute(vi, channelName, attributeId)
    ccall((:niFgen_ResetAttribute, libnifgen), ViStatus, (ViSession, ViConstString, ViAttr), vi, channelName, attributeId)
end


text:
# To run this script, `cd` to the `./test/fixtures` directory and then, from the Julia terminal, `include("./runner.jl")`.

import JSON

# Medium negative values:
x = linspace( -709.78, -1.0, 1000 )

y = expm1( x )
println( y )

data = Dict([
	("x", x),
	("expected", y)
])

outfile = open( "./medium_negative.json", "w" )
JSON.json( data )

write( outfile, JSON.json(data) )
close( outfile )

# Medium positive values:
x = linspace( 1.0, 709.78, 1000 )

y = expm1( x )
println( y )

data = Dict([
	("x", x),
	("expected", y)
])

outfile = open( "./medium_positive.json", "w" )
JSON.json( data )

write( outfile, JSON.json(data) )
close( outfile )

# Small negative values:
x = linspace( -1.0, -2.0^-54, 1000 )

y = expm1( x )
println( y )

data = Dict([
	("x", x),
	("expected", y)
])

outfile = open( "./small_negative.json", "w" )
JSON.json( data )

write( outfile, JSON.json(data) )
close( outfile )

# Small positive values:
x = linspace( 2.0^-54, 1.0, 1000 )

y = expm1( x )
println( y )

data = Dict([
	("x", x),
	("expected", y)
])

outfile = open( "./small_positive.json", "w" )
JSON.json( data )

write( outfile, JSON.json(data) )
close( outfile )

# Tiny values:
x = linspace( -2.0^-54, 2.0^-54, 1000 )

y = expm1( x )
println( y )

data = Dict([
	("x", x),
	("expected", y)
])

outfile = open( "./tiny.json", "w" )
JSON.json( data )

write( outfile, JSON.json(data) )
close( outfile )

ext: jl


text:
# Autogenerated wrapper script for libspatialite_jll for i686-w64-mingw32-cxx03
export libspatialite, mod_spatialite

using SQLite_jll
using GEOS_jll
using PROJ_jll
using Libiconv_jll
using Zlib_jll
using XML2_jll
JLLWrappers.@generate_wrapper_header("libspatialite")
JLLWrappers.@declare_library_product(libspatialite, "libspatialite-4.dll")
JLLWrappers.@declare_library_product(mod_spatialite, "mod_spatialite.dll")
function __init__()
    JLLWrappers.@generate_init_header(SQLite_jll, GEOS_jll, PROJ_jll, Libiconv_jll, Zlib_jll, XML2_jll)
    JLLWrappers.@init_library_product(
        libspatialite,
        "bin\\libspatialite-4.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        mod_spatialite,
        "bin\\mod_spatialite.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
#
# univariate orderstatistic methods
#
orderstatistic(Xs::MultivariateDistribution,k::Int64) = ScalarOrderStatistic(Xs,k)
function orderstatistic{T<:ContinuousUnivariateDistribution}(X::T,n::Integer,k::Integer)
  return orderstatistic(IIDRandomSequence(X,n),k)
end

orderstatistics(Xs::MultivariateDistribution) = [orderstatistic(Xs,k) for k = 1:length(Xs)]
orderstatistics{T<:ContinuousUnivariateDistribution}(X::T,n::Int64) = orderstatistics(IIDRandomSequence(X,n))

#
# joint order statistic methods
#
sort(X::MultivariateDistribution) = jointorderstatistic(X)

jointorderstatistic(X::MultivariateDistribution,orders::Vector{Int64}) = JointOrderStatistic(X,orders)
jointorderstatistic(X::MultivariateDistribution) = jointorderstatistic(X,collect(1:length(X)))
function jointorderstatistic(X::JointOrderStatistic)
  fullorders = collect(1:length(X))
  if orders(X) == fullorders
    return X
  else
    error("not yet implemented (coming soon though)")
  end
end

function jointorderstatistics(X::MultivariateDistribution,n::Integer)
  return imap(orders->jointorderstatistic(X,orders),combinations(1:length(X),n))
end
function jointorderstatistics(X::MultivariateDistribution)
  N = length(X)
  ordercombos = chain([combinations(1:N,k) for k=2:N]...)
  return imap(orders->jointorderstatistic(X,orders),ordercombos)
end

#
# max/min methods
#
min(Xs::MultivariateDistribution) = orderstatistic(Xs,1)
min{T<:ContinuousUnivariateDistribution}(X::T,n::Int64) = min(IIDRandomSequence(X,n))

max(Xs::MultivariateDistribution) = orderstatistic(Xs,length(Xs))
max{T<:ContinuousUnivariateDistribution}(X::T,n::Int64) = max(IIDRandomSequence(X,n))

#
# range methods
#
function range(Y::MultivariateDistribution)
  error("No generic implementation available at this time")
end

#
# spacing methods
#
function spacing(Y::MultivariateDistribution,space::Integer)
  error("No generic implementation available at this time")
end

spacings(Y::MultivariateDistribution) = [spacing(Y,space) for space = 1:length(Y)+1]

function jointspacing(Y::MultivariateDistribution,spaces::Vector{Integer})
  error("No generic implementation available at this time")
end

function jointspacings(X::MultivariateDistribution)
  N = length(X)+1
  spacecombos = chain([combinations(1:N,k) for k=2:N]...)
  return imap(orders->jointspacing(X,spaces),spacecombos)
end


text:
"""Find all neighbors of vertex `u`` within `G` that precede it in the given ordering"""
function lowernbrs(G::AbstractComplex, uidx::IX, E) where {IX <: Integer}
    upos = position(G, uidx, 0)
    nbrs = Set{IX}()
    # get all edges of u: select {v} s.t. u > v for all edges {u,v}
    for v in cells(G,0)
        vidx = hash(v)
        vpos = position(G, vidx, 0)
        upos > vpos && E[vpos, upos] && push!(nbrs, vidx)
    end
    return nbrs
end

"""Inductive construction of VR complex from neighborhood graph"""
function inductive!(cplx, k, E)
    C0 = cells(cplx, 0)
    for i in 1:k-1
        cls = cells(cplx, i)
        cls === nothing && continue
        for τ in cls
            # N = ∩ᵤₜlowernbrs(G,u)
            V = vertecies(τ)
            N = lowernbrs(cplx, V[1], E)
            for i in 2:length(V)
                intersect!(N, lowernbrs(cplx, V[i], E))
            end
            #K ⟵ K ∪ {τ ∪ {v}}
            for vidx in N
                vpos = position(cplx, vidx, 0)
                σ = τ ∪ C0[vpos]
                push!(cplx, σ)
            end
        end
    end
end

"""Add all simplices of the `k`-skeleton whose maximal vertex is `τ`"""
function addcofaces!(cplx, k, τ, N, E)
    # V ← V ∪ {τ}
    τ ∉ cplx && addsimplex!(cplx, τ)
    # stop recursion
    dim(τ) >= k && return
    for vidx in N
        # σ ← τ ∪ {v}
        vpos = position(cplx, vidx, 0)
        σ = τ ∪ cells(cplx, 0)[vpos]
        # M ← N ∩ lowernbrs(G, v)
        M = intersect(N, lowernbrs(cplx, vidx, E))
        addcofaces!(cplx, k, σ, M, E)
    end
end

"""Incremental construction of VR complex from neighborhood graph"""
function incremental!(cplx, k, E)
    # construct VR complex
    for u in cells(cplx, 0)
        N = lowernbrs(cplx, hash(u), E)
        addcofaces!(cplx, k, u, N, E)
    end
end

"""Weight function for VR complex"""
function weight(σ, w, cplx)
    k = dim(σ)
    k == 0 && return 0.
    k == 1 && return w[1][cplx[σ]]
    return maximum([w[k-1][position(cplx, τ)] for τ in faces(σ)])
end

function expand(method, cplx, w, kmax, E)
    # perform nerve expansion
    if method == :incremental
        incremental!(cplx, kmax, E)
    elseif method == :inductive
        inductive!(cplx, kmax, E)
    else
        throw(ArgumentError("Invalid method name $(method)"))
    end

    if w !== nothing
        for k in 2:dim(cplx)
            w[k] = zeros(size(cplx,k))
            for σ in cells(cplx,k)
                w[k][position(cplx, σ)] = weight(σ, w, cplx)
            end
        end
    end
    return
end

"""
    vietorisrips(X, ɛ[, weights])

Construction of a Vietoris–Rips complex

# Arguments
- `X::AbstractMatrix{T}`: the dataset where each column defines a data point.
- `ɛ::Real`: the maximal scale value.
- `weights::Bool`: this flag indicates if the filteration weight should be calculated. Default value is `true`.

This is an inefficient implementation (based on distance matrix) of the VRC algorithm from:

    Afra Zomorodian, Fast construction of the Vietoris-Rips complex, 2010
"""
function vietorisrips(X::AbstractMatrix{T}, ɛ::Real, weights = true;
                      expansion = :incremental,
                      distance  = Distances.Euclidean(),
                      maxoutdim = size(X,2)-1) where T <: Real
    d, n = size(X)

    # add zero-dimensional simplices to complex
    splxs = map(Simplex, 1:n)
    cplx = SimplicialComplex(splxs...)

    # calculate cross distances for each point in dataset
    D = Distances.pairwise(distance, X)

    # build 1-skeleton (neighborhood graph)
    E = spzeros(Bool, n, n) # adjacency matrix
    for i in 1:n
        E[i,i] = true
        for j in findall(d-> 0 < d <= ɛ, view(D, :, i))
            s = Simplex(i,j)
            # check if simplex is already added
            s in cplx && continue
            # add simplex to complex
            push!(cplx, s)
            # fill adjacency matrix
            E[i,j] = true
            E[j,i] = true
        end
    end

    # determine maximal dimension
    kmax = min(maxoutdim, maximum(mapslices(c->count(d-> 0.0 < d ≤ ɛ, c), D, dims=1)))

    # calculate weights of nerve
    w = nothing
    if weights
        w = Dict{Int, Vector{T}}()
        w[0] = zeros(size(cplx,0))
        if size(cplx, 1) > 0
            w[1] = zeros(size(cplx,1))
            for e in cells(cplx,1)
                w[1][position(cplx, e)] = D[map(v->position(cplx, v), faces(e))...]
            end
        end
    end

    # perform expansion
    expand(expansion, cplx, w, kmax, E)

    return cplx, w
end

"""
Landmark selection for witness complex
"""
function landmarks(X::AbstractMatrix, l::Int; method = :minmax,
                   distance = Distances.Euclidean(), firstpoint = 0)
    d, n = size(X)
    if method == :random
        return Random.randperm(n)[1:l]
    elseif method == :minmax
        idxs = firstpoint > 0 ? [firstpoint] : rand(1:n, 1)
        Z = view(X, :, idxs)
        for i in 2:l
            maxv = -Inf
            maxvidx = 0
            for j in 1:n
                if j ∉ idxs
                    v, _ = findmin(Distances.colwise(distance, X[:,j], Z))
					if v > maxv
					    maxv = v
                        maxvidx = j
                    end
                end
            end
            push!(idxs, maxvidx)
        end
        return idxs
    else
        throw(ArgumentError("Invalid method name $(method)"))
    end
end

"""
    witness(X, l, ɛ[, weights])

Construction of a witness complex.

# Arguments
- `X::AbstractMatrix{T}`: the dataset where each column defines a data point.
- `l::Int`: the number of landmarks.
- `ɛ::Real`: the maximal scale value.
- `weights::Bool`: this flag indicates if the filteration weight should be calculated. Default value is `true`.

# Keyword arguments
For parameter ν = 0, 1, 2 determines size of landmark radius.
- If ν = 0, then for i = 1, 2, . . . , N define m_i = 0.
- If ν > 0, then for i = 1, 2, . . . , N define m_i to be the ν-th smallest entry of the i-th column of D.
"""
function witness(X::AbstractMatrix{T}, l::Int, ɛ::Real, weights = true;
                 landmark = :minmax, distance = Distances.Euclidean(),
                 expansion = :incremental, ν::Int = 2, maxoutdim = size(X,1)-1,
                 firstpoint = 0) where T <: Real

    # get landmarks
    L = landmarks(X, l, method = landmark, distance = distance, firstpoint=firstpoint)

    # get distances to landmarks
    D = Distances.pairwise(distance, X[:,L], X)

    # simplexes contain indexes to landamarks
    cplx, w = witness(D, ɛ, weights, expansion=expansion, ν=ν, maxoutdim=maxoutdim, firstpoint=firstpoint)

    return cplx, w
end

"""
    witness(D, ɛ[, weights])

Construction of a witness complex from the distance matrix `D` with a maximum scale value `ɛ`.
"""
function witness(D::AbstractMatrix, ɛ::Real, weights = true;
                 expansion = :incremental,
                 ν::Int = 2,
                 maxoutdim = size(D,1)-1,
                 firstpoint = 0) where T <: Real

    @assert ν < 3 "ν only can take values of 0, 1 or 2"
    @assert maxoutdim > 0 "Maximum dimension should be more then 0"

    l, n = size(D)

    # get landmark radius extension m_i
    m = zeros(eltype(D), n)
    if ν > 0
        idxs = zeros(Int, l)
        for i in 1:n
            sortperm!(idxs, D[:,i])
            m[i] = D[idxs[ν], i]
        end
    end

    # construct 1-seleton edges
    splxs = map(Simplex, 1:l)
    cplx = SimplicialComplex(splxs...)
    w = nothing
    if weights
        w = Dict{Int, Vector{Float64}}()
        w[0] = zeros(size(cplx,0))
        w[1] = zeros(0)
    end

    # the edge σ = [ab] belongs to W(D; ɛ, ν) iff there exists a witness i ∈ {1, 2, ..., N} such that:
    # max(D(a, i), D(b, i)) ≤ ɛ + m_i
    E = spzeros(Bool, l, l) # adjacency matrix
    for i in 1:l
        for j in i+1:l
            e = Inf
            @inbounds for k in 1:n
                d = max(D[i, k], D[j, k])
                d = d < m[k] ? 0.0 : d - m[k]
                if d < e
                    e = d
                end
            end

            if e ≤ ɛ
                push!(cplx, Simplex(i, j))
                weights && push!(w[1], e)
                E[i, j] = true
            end
        end
    end

    # determine maximal dimension
    Rmax = ɛ+maximum(m)
    kmax = min(maxoutdim, maximum(mapslices(c->count(d->0.0<d≤Rmax, c), D, dims=1)))

    # perform expansion
    expand(expansion, cplx, w, kmax, E)

    return cplx, w
end

"""
    welzl(P, R)

Computes the smallest enclosing circle of the union of `P` and `R`.
"""
function welzl(P, R)
    p = length(P)
    r = length(R)
    if p == 0 || r >= 3
        if r == 1
            return R[1], 0.0
        elseif r == 2
            p1 = R[1]
            p2 = R[2]
            m = (p1.+p2) ./ 2.
            d = sqrt(sum(abs2, (x .- y)))
            return m, d / 2.
        elseif true
            @warn "the points of R are cocircular"
            return [], 0.0
        else
            @error "Undefined"
            return [], -1.0
       end
    end
    i = rand(1:p)
    x = P[i]
    c, r = welzl(deleteat!(P, i), R)
    norm(x - c) <= r && return (c, r)
    return welzl(P, push!(R, x))
end

"""
    čech(X, ɛ[, weights])
    cech(X, ɛ[, weights])

Construction of a Čeck complex.

# Arguments
- `X::AbstractMatrix{T}`: the dataset where each column defines a data point.
- `ɛ::Real`: the maximal scale value.
- `weights::Bool`: this flag indicates if the filteration weight should be calculated. Default value is `true`.

"""
function čech(X::AbstractMatrix{T}, ɛ::Real, weights = true;
              distance  = Distances.Euclidean(),
              maxoutdim = size(X,2)-1) where T <: Real

    d, n = size(X)

    splxs = map(Simplex, 1:n) # construct 0-simplices
    cplx = SimplicialComplex(splxs...) # and 0-complex

    w = nothing
    if weights
        w = Dict{Int, Vector{Float64}}()
        w[0] = zeros(size(cplx,0))
    end

    for h in 1:maxoutdim
        idx = collect(h+1:-1:1)
        weights && setindex!(w, zeros(T, 0), h)

        while idx[end] <= n-h
            # find radius of bounding sphere
            c, r = BoundingSphere.boundingsphere([X[:, i] for i in idx])

            # add simplex in radius less then maximal filtration value
            if r <= ε
                s = Simplex(reverse(idx))
                addsimplex!(cplx, s)
                weights && push!(w[h], r)
            end

            # iterate through all combinations of point indecies
            for i in 1:h+1
                idx[i] += 1
                if idx[i] <= n-i+1
                    for j in i-1:-1:1
                        idx[j] = idx[j+1] + 1
                    end
                    break
                end
            end
        end
    end

    return cplx, w
end
const cech = čech


text:
module SparsityOperators

import Base: length, iterate, \
using LinearAlgebra
import LinearAlgebra.BLAS: gemv, gemv!
import LinearAlgebra: BlasFloat, normalize!, norm, rmul!, lmul!
using SparseArrays
using Random
using CUDA

using Reexport
@reexport using Reexport
@reexport using LinearOperators
@reexport using FFTW
@reexport using Wavelets

const Trafo = Union{AbstractMatrix, AbstractLinearOperator, Nothing}
const FuncOrNothing = Union{Function, Nothing}

include("FFTOp.jl")
include("DCTOp.jl")
include("DSTOp.jl")
include("WaveletOp.jl")
include("GradientOp.jl")
include("SamplingOp.jl")
include("WeightingOp.jl")
include("NormalOp.jl")

export linearOperator, linearOperatorList

linearOperator(op::Nothing,shape,T::Type=ComplexF32) = nothing

"""
  returns a list of currently implemented `LinearOperator`s
"""
function linearOperatorList()
  return ["DCT-II", "DCT-IV", "FFT", "DST", "Wavelet", "Gradient"]
end

"""
    linearOperator(op::AbstractString, shape)

returns the `LinearOperator` with name `op`.

# valid names
* `"FFT"`
* `"DCT-II"`
* `"DCT-IV"`
* `"DST"`
* `"Wavelet"`
* `"Gradient"`
"""
function linearOperator(op::AbstractString, shape, T::Type=ComplexF32)
  shape_ = tuple(shape...)
  if op == "FFT"
    trafo = FFTOp(T, shape_, false) #FFTOperator(shape)
  elseif op == "DCT-II"
    shape_ = tuple(shape[shape .!= 1]...)
    trafo = DCTOp(T, shape_, 2)
  elseif op == "DCT-IV"
    shape_ = tuple(shape[shape .!= 1]...)
    trafo = DCTOp(T, shape_, 4)
  elseif op == "DST"
    trafo = DSTOp(T, shape_)
  elseif op == "Wavelet"
    trafo = WaveletOp(T,shape_)
  elseif op=="Gradient"
    trafo = GradientOp(T,shape_)
  else
    error("Unknown transformation")
  end
  trafo
end

end # module


text:
using Pkg.TOML

const WEBIO_VERSION = let
    project_file = normpath(joinpath(@__DIR__, "..", "Project.toml"))
    project = TOML.parsefile(project_file)
    VersionNumber(project["version"])
end

# Make sure that we're running tests for this repository, we don't want to do
# extra steps when testing other packages.  For the time being we run tests only
# on Travis, so isci() checks Travis-specific environment variables.
function isci()
    return get(ENV, "TRAVIS", "false") == "true" &&
        split(get(ENV, "TRAVIS_REPO_SLUG", "Foo/Bar.jl"), '/')[2] == "WebIO.jl"
end
isdev() = isci() || basename(dirname(dirname(@__DIR__))) == "dev"

const PACKAGES_PATH = normpath(joinpath(@__DIR__, "..", "packages"))
const BUNDLES_PATH = normpath(joinpath(@__DIR__, "bundles"))

function bundleurl(pkg::String, filename::String)
    return "https://unpkg.com/@webio/$(pkg)@$(WEBIO_VERSION)/dist/$(filename)"
end

const CORE_BUNDLE_PATH = joinpath(BUNDLES_PATH, "webio.bundle.js")
const CORE_BUNDLE_URL = bundleurl("webio", "webio.bundle.js")
const GENERIC_HTTP_BUNDLE_PATH = joinpath(BUNDLES_PATH, "generic-http.bundle.js")
const GENERIC_HTTP_BUNDLE_URL = bundleurl("generic-http-provider", "generic-http.bundle.js")
const MUX_BUNDLE_PATH = joinpath(BUNDLES_PATH, "mux.bundle.js")
const MUX_BUNDLE_URL = bundleurl("mux-provider", "mux.bundle.js")

const JUPYTER_NBEXTENSION_NAME = "webio-jupyter-notebook"
const JUPYTER_NBEXTENSION_PATH = joinpath(BUNDLES_PATH, "$(JUPYTER_NBEXTENSION_NAME).js")
const JUPYTER_NBEXTENSION_URL = bundleurl("jupyter-notebook-provider", "jupyter-notebook.bundle.js")

# Deprecated! Remove for WebIO version 1.0.0
const BLINK_BUNDLE_PATH = joinpath(BUNDLES_PATH, "blink.bundle.js")
const BLINK_BUNDLE_URL = bundleurl("blink-provider", "blink.bundle.js")

function download_bundle(name::String, path::String, url::String)
    if !isfile(path)
        @info "Downloading WebIO $(name) bundle from unpkg..."
        download(url, path)
    end
end

function download_js_bundles()
    if isci()
        # In CI, we always build the bundles from scratch.
        @info "Not downloading WebIO bundles in CI; building instead..."
        include("./_bundlejs.jl")
        return
    end

    mkpath(BUNDLES_PATH)
    download_bundle("core", CORE_BUNDLE_PATH, CORE_BUNDLE_URL)
    download_bundle("generic-http", GENERIC_HTTP_BUNDLE_PATH, GENERIC_HTTP_BUNDLE_URL)
    download_bundle("mux", MUX_BUNDLE_PATH, MUX_BUNDLE_URL)
    download_bundle("jupyter-notebook", JUPYTER_NBEXTENSION_PATH, JUPYTER_NBEXTENSION_URL)
    download_bundle("blink", BLINK_BUNDLE_PATH, BLINK_BUNDLE_URL)

    # NOTE: we don't download JupyterLab files because that should just begin
    # installed directly from npm (à la the
    # `jupyter labextension install @webio/jupyter-lab-provider` command).
end


text:
module BioBridgeR

include("ape/ape.jl")

end # module BioBridgeR


text:
using Test

include("pull_julia_code.jl")

println("="^20)
println("Importing support code!")
include("support_code.jl")

println("="^20)
println("Running tests!")
include("all_test_blocks.jl")

println("ALL TESTS PASSED")

max_stars_repo_name: jleugeri/phd

max_issues_repo_name: jleugeri/phd

max_forks_repo_name: jleugeri/phd


text:
using DelimitedFiles

masses = readdlm(stdin, Int)

function fuel(mass::Int)::Int
    mass ÷ 3 - 2
end

function fuel_r(mass::Int)
    f = fuel(mass)
    f <= 0 ? 0 : f + fuel_r(f)
end

function part1()
    println(sum(fuel, masses))
end

function part2()
    println(sum(fuel_r, masses))
end

part1()
part2()


text:
mutable struct TunnelData
    wp::Vector{Any}
    lw_wp::Vector{Any}
    rw_wp::Vector{Any}
    distances::Vector{Float64}
    c_distances::Vector{Float64}
    num_turns::Int
    num_segments::Int
    wall_distance::Float64
end

dist(x1, x2) = sqrt((x2[2]-x1[2])^2 + (x2[1]-x1[1])^2)

mutable struct Placement
    num_sensors::Int
    distances::Vector{Any}
    l_positions::Vector{Any}
    r_positions::Vector{Any}
    segment_id::Dict{Int,Int}
    num_sensors_in_segment::Vector{Int}
    los_points::Vector{Any}
end


text:
# MadNLP.jl
# Created by Sungho Shin (sungho.shin@wisc.edu)

abstract type AbstractSparseMatrixCOO{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti} end

mutable struct SparseMatrixCOO{Tv,Ti<:Integer} <: AbstractSparseMatrixCOO{Tv,Ti}
    m::Int
    n::Int
    I::StrideOneVector{Ti}
    J::StrideOneVector{Ti}
    V::StrideOneVector{Tv}
end
size(A::SparseMatrixCOO) = (A.m,A.n)
getindex(A::SparseMatrixCOO{Float64,Ti},i::Int,j::Int) where Ti <: Integer = sum(A.V[(A.I.==i) .* (A.J.==j)])
nnz(A::SparseMatrixCOO) = length(A.I)

function findIJ(S::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti}
    numnz = nnz(S)
    I = Vector{Ti}(undef,numnz)
    J = Vector{Ti}(undef,numnz)

    cnt = 1
    @inbounds for col = 1 : size(S, 2), k = getcolptr(S)[col] : (getcolptr(S)[col+1]-1)
        I[cnt] = rowvals(S)[k]
        J[cnt] = col
        cnt += 1
    end

    return I,J
end

get_mapping(dest::Matrix{Tv}, src::SparseMatrixCOO{Tv,Ti}) where {Tv,Ti} = nothing

function diag!(dest::AbstractVector{T}, src::AbstractMatrix{T}) where T
    @assert length(dest) == size(src, 1)
    @inbounds for i in eachindex(dest)
        dest[i] = src[i, i]
    end
end

function get_tril_to_full(csc::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti<:Integer}
    cscind = SparseMatrixCSC{Int,Ti}(Symmetric(
        SparseMatrixCSC{Int,Ti}(csc.m,csc.n,csc.colptr,csc.rowval,collect(1:nnz(csc))),:L))
    return SparseMatrixCSC{Tv,Ti}(
        csc.m,csc.n,cscind.colptr,cscind.rowval,Vector{Tv}(undef,nnz(cscind))),view(csc.nzval,cscind.nzval)
end
function tril_to_full!(dense::Matrix{T}) where T
    for i=1:size(dense,1)
        Threads.@threads for j=i:size(dense,2)
            @inbounds dense[i,j]=dense[j,i]
        end
    end
end

function SparseMatrixCSC{Tv, Ti}(coo::SparseMatrixCOO{Tv,Ti}) where {Tv,Ti <: Integer}
    cscind = sparse(coo.I,coo.J,ones(Ti,nnz(coo)),coo.m,coo.n)
    nzval = Vector{Tv}(undef,nnz(cscind))
    fill!(nzval, zero(Tv))
    return SparseMatrixCSC{Tv, Ti}(
        coo.m,coo.n,cscind.colptr,cscind.rowval,nzval,
    )
end

function _get_coo_to_csc(I,J,cscind,map)
    for i=1:length(I)
        @inbounds map[i] = cscind[I[i],J[i]]
    end
end
function _transfer!(vec1, vec2, map)
    fill!(vec1, 0.0)
    for i=1:length(map)
        @inbounds vec1[map[i]] += vec2[i]
    end
end

function transfer!(dest::SparseMatrixCSC, src::SparseMatrixCOO, map::Vector{Int})
    _transfer!(dest.nzval, src.V, map)
end

function get_mapping(dest::SparseMatrixCSC{Tv1,Ti1}, src::SparseMatrixCOO{Tv2,Ti2}) where {Tv1,Tv2,Ti1,Ti2}
    map = Vector{Int}(undef,nnz(src))
    dest.nzval .= 1:nnz(dest)
    _get_coo_to_csc(src.I, src.J, dest, map)
    return map
end

function Matrix{Tv}(coo::SparseMatrixCOO{Tv,Ti}) where {Tv,Ti<:Integer}
    return Matrix{Tv}(undef,coo.m,coo.n)
end

Base.copyto!(dense::Matrix{Tv},coo::SparseMatrixCOO{Tv,Ti}) where {Tv,Ti<:Integer} = _copyto!(dense,coo.I,coo.J,coo.V)
function _copyto!(dense::Matrix{Tv},I,J,V) where Tv
    fill!(dense, zero(Tv))
    for i=1:length(I)
        @inbounds dense[I[i], J[i]] += V[i]
    end
    return dense
end

function get_cscsy_view(csc::SparseMatrixCSC{Tv,Ti},Ix;inds=collect(1:nnz(csc))) where {Tv,Ti<:Integer}
    cscind = SparseMatrixCSC{Int,Ti}(csc.m,csc.n,csc.colptr,csc.rowval,inds)
    cscindsub = cscind[Ix,Ix]
    return SparseMatrixCSC{Tv,Ti}(
        cscindsub.m,cscindsub.n,cscindsub.colptr,
        cscindsub.rowval,Vector{Tv}(undef,nnz(cscindsub))), view(csc.nzval,cscindsub.nzval)

end

function get_csc_view(csc::SparseMatrixCSC{Tv,Ti},Ix,Jx;inds=collect(1:nnz(csc))) where {Tv,Ti<:Integer}
    cscind = Symmetric(SparseMatrixCSC{Int,Ti}(csc.m,csc.n,csc.colptr,csc.rowval,inds),:L)
    cscindsub = cscind[Ix,Jx]
    resize!(cscindsub.rowval,cscindsub.colptr[end]-1)
    resize!(cscindsub.nzval,cscindsub.colptr[end]-1)
    return SparseMatrixCSC{Tv,Ti}(
        cscindsub.m,cscindsub.n,cscindsub.colptr,
        cscindsub.rowval,Vector{Tv}(undef,nnz(cscindsub))), view(csc.nzval,cscindsub.nzval)
end


text:
using Revise
includet(joinpath("..", "init.jl"))

# Load the ordering variable
chronMatrix = Array(CSV.read(joinpath(dataPath, "ordering_32_days.csv")))
u = Array(CSV.read(joinpath(dataPath, "decision_32_days.csv"))[:,:periods][:])
chron = [
    first(u[findall(x -> x == 1, chronMatrix[i,:])])
    for i = 1:size(chronMatrix, 1)
]

# Create the mapping as an OrderedDict(t_start,t_end => [t_start,t_end])
model_start = DateTime(2017)
jsonDict = OrderedDict(
    "type" => "map",
    "index_type" => "date_time",
    "data" => []
)
for d = 1:365
    for h = 1:24
        push!(
            jsonDict["data"],
            [string(model_start + Day(d-1) + Hour(h-1)), OrderedDict(
                "type" => "map",
                "index_type" => "date_time",
                "data" => [
                    [string(model_start + Day(d-1) + Hour(h)), OrderedDict(
                        "type" => "map",
                        "index_type" => "str",
                        "data" => hcat(
                            [
                                "start",
                                string(model_start + Hour(h-1) + Day(chron[d]-1))
                            ],
                            [
                                "end",
                                string(model_start + Hour(h) + Day(chron[d]-1))
                            ]
                        )
                    )]
                ]
            )]
        )
    end
end
open(joinpath(@__DIR__, "..", "data", "timeslice_map.json"),"w") do f
    JSON.print(f, jsonDict)
end

# NOTE: I haven't automated writing the JSON string to the database yet


text:
"""
    IsStochasticInteger{T=Int}() <: StochasticStyle{T}

FCIQMC algorithm with integer walkers as in
[Booth *et al.* (2009)](https://doi.org/10.1063/1.3193710). During the vector matrix product
each individual diagonal and spawning step is rounded stochastically to a nearby integer
value.

See also [`StochasticStyle`](@ref).
"""
struct IsStochasticInteger{T<:Integer} <: StochasticStyle{T} end
IsStochasticInteger() =  IsStochasticInteger{Int}()

function step_stats(::IsStochasticInteger{T}) where {T}
    z = zero(T)
    return (
        (:spawn_attempts, :spawns, :deaths, :clones, :zombies, :annihilations),
        MultiScalar(0, z, z, z, z, z),
    )
end
function fciqmc_col!(
    ::IsStochasticInteger, w, ham, add, num::Real, shift, dτ
)
    clones, deaths, zombies, ann_diag = diagonal_step!(w, ham, add, num, dτ, shift, 0, true)
    attempts, spawns, ann_offdiag = spawn!(WithReplacement(), w, ham, add, num, dτ)
    return (attempts, spawns, deaths, clones, zombies, ann_diag + ann_offdiag)
end

"""
    IsStochastic2Pop{T=Complex{Int}}() <: StochasticStyle{T}

Stochastic propagation with complex walker numbers representing two populations of integer
walkers.

When using this style, make sure to set a complex target number walkers in the
[`ShiftStrategy`](@ref)!

This style is experimental.

See also [`StochasticStyle`](@ref).
"""
struct IsStochastic2Pop{T<:Complex{<:Integer}} <: StochasticStyle{T} end
IsStochastic2Pop() = IsStochastic2Pop{Complex{Int}}()

function step_stats(::IsStochastic2Pop{T}) where {T}
    z = zero(T)
    return (
        (:spawns, :deaths, :clones, :zombies, :annihilations),
        MultiScalar(z, z, z, z, z)
    )
end
function fciqmc_col!(::IsStochastic2Pop, w, ham, add, val, shift, dτ)
    offdiags = offdiagonals(ham, add)
    spawns = deaths = clones = zombies = ann_o = ann_d = 0 + 0im
    # off-diagonal real.
    s, a = spawn!(WithReplacement(), w, offdiags, add, real(val), dτ)
    spawns += s; ann_o += a
    # off-diagonal complex: complex dτ ensures spawning to the correct population.
    s, a = spawn!(WithReplacement(), w, offdiags, add, imag(val), dτ * im)
    spawns += s; ann_o += a

    clones, deaths, zombies, ann_d = diagonal_step!(w, ham, add, val, dτ, shift, 0, true)

    return (spawns, deaths, clones, zombies, ann_o + ann_d)
end

"""
    IsDeterministic{T=Float64}(compression=NoCompression()) <: StochasticStyle{T}

Propagate with deterministic vector matrix multiplications. Stochastic compression of the
resultant vector (after annihilations) can be triggered by setting the optional
`compression` argument to a relevant [`CompressionStrategy`](@ref).

See also [`StochasticStyle`](@ref).
"""
struct IsDeterministic{T<:AbstractFloat,C<:CompressionStrategy} <: StochasticStyle{T}
    compression::C
end
function IsDeterministic{T}(compression::C=NoCompression()) where {T,C}
    return IsDeterministic{T,C}(compression)
end
IsDeterministic(args...) = IsDeterministic{Float64}(args...)

CompressionStrategy(s::IsDeterministic) = s.compression

function Base.show(io::IO, s::IsDeterministic{T}) where {T}
    if s.compression isa NoCompression
        print(io, "IsDeterministic{$T}()")
    else
        print(io, "IsDeterministic{$T}($(s.compression))")
    end
end

function step_stats(::IsDeterministic)
    return (:exact_steps,), MultiScalar(0,)
end
function fciqmc_col!(::IsDeterministic, w, ham::AbstractMatrix, add, num, shift, dτ)
    for i in axes(ham, 1) # iterate through off-diagonal rows of `ham`
        i == add && continue
        deposit!(w, i, -dτ * ham[i, add] * num, add => num)
    end
    deposit!(w, add, (1 + dτ * (shift - ham[add, add])) * num, add => num) # diagonal
    return (1,)
end
function fciqmc_col!(::IsDeterministic, w, ham, add, val, shift, dτ)
    diagonal_step!(w, ham, add, val, dτ, shift)
    spawn!(Exact(), w, ham, add, val, dτ)
    return (1,)
end

"""
    IsStochasticWithThreshold{T=Float64}(threshold=1.0) <: StochasticStyle{T}

Stochastic propagation with floating point walker numbers. During the vector matrix product
each individual diagonal and spawning result is rounded stochastically if smaller than
`threshold` (before annihilations).

See also [`StochasticStyle`](@ref).
"""
struct IsStochasticWithThreshold{T<:AbstractFloat} <: StochasticStyle{T}
    threshold::T
end
IsStochasticWithThreshold(args...) = IsStochasticWithThreshold{Float64}(args...)
IsStochasticWithThreshold{T}(t=1.0) where {T} = IsStochasticWithThreshold{T}(T(t))

function step_stats(::IsStochasticWithThreshold{T}) where {T}
    z = zero(T)
    return (
        (:spawn_attempts, :spawns),
        MultiScalar(0, z)
    )
end
function fciqmc_col!(s::IsStochasticWithThreshold, w, ham, add, val, shift, dτ)
    diagonal_step!(w, ham, add, val, dτ, shift)
    attempts, spawns, _ = spawn!(WithReplacement(s.threshold), w, ham, add, val, dτ)
    return (attempts, spawns)
end

"""
    IsDynamicSemistochastic{T=Float64}(; kwargs...) <: StochasticStyle{T}

QMC propagation with floating-point walker numbers and reduced noise. All possible spawns
(offdiagonal elements in vector-matrix multiplication)
are performed deterministically when number of walkers in a configuration is high, as
controlled by the `rel_threshold` and `abs_threshold` keywords. Stochastic selection of
spawns is controlled  by the `spawning` keyword.

By default, a stochastic vector compression is applied after annihilations are completed.
This behaviour can be changed to on-the-fly projection (as in [`IsStochasticInteger`](@ref)
or [`IsStochasticWithThreshold`](@ref)) by setting a threshold to `spawning` and
setting `compression` to [`NoCompression`](@ref).

## Parameters:

* `rel_threshold = 1.0`: If the walker number on a configuration times this threshold
  is greater than the number of offdiagonals, spawning is done deterministically. Should be
  set to 1 or more for best performance.

* `abs_threshold = Inf`: If the walker number on a configuration is greater than this value,
  spawning is done deterministically. Can be set to e.g.
  `abs_threshold = 0.1 * target_walkers`.

* `proj_threshold = 1.0`: Values below this number are stochastically projected to this
  value or zero. See also [`ThresholdCompression`](@ref).

* `spawning = WithReplacement()`: [`SpawningStrategy`](@ref) to use for the non-exact
  spawns. See [`WithReplacement`](@ref) for behaviour and possible arguments.

* `compression = ThresholdCompression(proj_threshold)`: [`CompressionStartegy`](@ref) used
  to compress the vector after a step. Overrides `proj_threshold`.

See also [`StochasticStyle`](@ref).
"""
struct IsDynamicSemistochastic{
    T<:AbstractFloat,C<:CompressionStrategy,S<:DynamicSemistochastic
} <: StochasticStyle{T}
    compression::C
    spawning::S
end
function IsDynamicSemistochastic{T}(
    ;
    proj_threshold=1.0, strength=1.0, rel_threshold=1.0, abs_threshold=Inf,
    compression=ThresholdCompression(proj_threshold),
    spawning=WithReplacement(),
) where {T}
    s = DynamicSemistochastic(spawning, rel_threshold, abs_threshold)
    return IsDynamicSemistochastic{T,typeof(compression),typeof(s)}(compression, s)
end
IsDynamicSemistochastic(; kwargs...) = IsDynamicSemistochastic{Float64}(; kwargs...)

function Base.show(io::IO, s::IsDynamicSemistochastic{T,C,S}) where {T,C,S}
    print(io, "IsDynamicSemistochastic{$T,", nameof(C), ",", nameof(S), "}()")
end

CompressionStrategy(s::IsDynamicSemistochastic) = s.compression

function step_stats(::IsDynamicSemistochastic{T}) where {T}
    z = zero(T)
    return (
        (:exact_steps, :inexact_steps, :spawn_attempts, :spawns),
        MultiScalar(0, 0, 0, z),
    )
end
function fciqmc_col!(s::IsDynamicSemistochastic, w, ham, add, val, shift, dτ)
    diagonal_step!(w, ham, add, val, dτ, shift)
    exact, inexact, attempts, spawns, _ = spawn!(s.spawning, w, ham, add, val, dτ)
    return (exact, inexact, attempts, spawns)
end

"""
    IsExplosive{T=Float64}(;
        splatter_factor,
        explosion_threshold,
        compression
    ) <: StochasticStyle{T}

QMC propagation with explosive walkers. Walkers with small walker numbers do not perform the
standard death/spawning steps. Instead, a walker will either die completely and spawn with a
greater magnitude (refered to as explosion below), or stay unchanged and not spawn. The
probabilty of exploding is controlled by the shift and `dτ`.

Walkers with high walker numbers spawn as if [`IsDynamicSemistochastic`](@ref) was used.

Like [`IsDynamicSemistochastic`](@ref), the vector is compressed after all spawning is
performed.

This style is experimental.

## Parameters

* `splatter_factor = 1.0`: The spawning strength to use with exploded walkers.

* `explosion_threshold = 1.0`: Entries smaller or equal than this value will attempt to
  explode.

* `proj_threshold = 1.0`: Threshold to use in vector compression. See
  [`ThresholdCompression`](@ref).

* `compression = ThresholdCompression(proj_threshold)`: [`CompressionStrategy`](@ref) to use
  to compress the vector. Overrides `proj_threshold`.

See also [`StochasticStyle`](@ref).
"""
struct IsExplosive{T<:AbstractFloat,C<:CompressionStrategy} <: StochasticStyle{T}
    splatter_factor::T
    explosion_threshold::T
    compression::C
end
function IsExplosive{T}(
    ;
    splatter_factor=one(T),
    explosion_threshold=one(T),
    proj_threshold=one(T),
    compression=ThresholdCompression(proj_threshold),
) where {T}
    return IsExplosive(T(splatter_factor), T(explosion_threshold), compression)
end
IsExplosive(; kwargs...) = IsExplosive{Float64}(; kwargs...)

CompressionStrategy(s::IsExplosive) = s.compression

function step_stats(::IsExplosive{T}) where {T}
    z = zero(T)
    return (
        (:explosions, :ticks, :normal_steps, :spawn_attempts,
         :explosive_spawns, :normal_spawns,
         ),
        MultiScalar(0, 0, 0, 0, z, z),
    )
end
function fciqmc_col!(s::IsExplosive{T}, w, ham, add, val, shift, dτ) where {T}
    explosions = normal_steps = ticks = 0
    explosive_spawns = normal_spawns = zero(T)
    clones = deaths = zombies = zero(T)
    attempts = 0

    pd = dτ * (diagonal_element(ham, add) - shift)
    if abs(val) ≤ s.explosion_threshold && 0 ≤ pd < 1
        if cRand() < pd
            _, _, attempts, explosive_spawns, _ = spawn!(
                DynamicSemistochastic(strat=WithReplacement(zero(T), s.splatter_factor)),
                w, ham, add, val / pd, dτ,
            )
            explosions = 1
        else
            deposit!(w, add, val, add => val)
            ticks = 1
        end
    else
        _ = diagonal_step!(w, ham, add, val, dτ, shift)
        _, _, attempts, normal_spawns, _ = spawn!(
            DynamicSemistochastic(strat=WithReplacement()), w, ham, add, val, dτ,
        )
        normal_steps = 1
    end

    return (
        explosions, ticks, normal_steps, attempts, explosive_spawns, normal_spawns,
    )
end

default_style(::Type{T}) where {T<:Integer} = IsStochasticInteger{T}()
default_style(::Type{T}) where {T<:AbstractFloat} = IsDeterministic{T}()
default_style(::Type{T}) where {T<:Complex{<:Integer}} = IsStochastic2Pop{T}()


text:
#misc.jl has misceranious functions

macro nyi(name)
 return:(println("Not yet implemented ", $name))
end

max_stars_repo_name: sazare/cheapViews

max_issues_repo_name: sazare/cheapViews

max_forks_repo_name: sazare/cheapViews


text:
module TestDoctest

import RecordArrays
using Documenter: doctest
using Test

@testset "doctest" begin
    doctest(RecordArrays; manual = false)
end

end  # module


text:
module MKtest

	using Parameters, SparseArrays, Distributed, CSV, JLD2, DataFrames, ProgressMeter, Quadmath, GZip, StatsBase, Unzip, ThreadsX, ParallelUtilities, Suppressor, Pkg, CondaPkg

	# Analytical solutions
	import Roots: find_zero
	import NLsolve: nlsolve
	import SpecialFunctions: polygamma, zeta
	import PoissonRandom: pois_rand
	import Distributions: Binomial, pdf

	# Parse data
	import GZip: open
	import Parsers: parse
	import OrderedCollections: OrderedDict
	import FastaIO: readfasta
	import Random: randstring

	# MK-approaches
	import LsqFit: curve_fit, confidence_interval
	import HypothesisTests: pvalue,FisherExactTest

	include("parameters.jl")
	include("fixations.jl")
	include("polymorphism.jl")
	include("summary_statistics.jl")
	include("rates.jl")
	include("infer_tools.jl")
	include("read_fasta.jl")
	include("methods.jl")

end


text:
using NeuralVerification
using LazySets
using DataStructures
using LinearAlgebra

include("ai2zPQ.jl")
include("tree_utils.jl")

network = read_nnet("../../models/full_mlp_supervised.nnet")

const TOL = Ref(sqrt(eps()))

""" Discretized Ai2z"""

function discretized_ai2z_bounds(network, lbs, ubs, coeffs; n_per_latent = 10, n_per_state = 1)
    # Ai2z overapproximation through discretization
    ai2z = Ai2z()
    overestimate = -Inf
    underestimate = Inf

    lbs_disc, ubs_disc = get_bounds(lbs, ubs, n_per_latent, n_per_state)

    for (curr_lbs, curr_ubs) in zip(lbs_disc, ubs_disc)
        # Construct the input set, then propagate forwards to a
        # zonotope over-approximation of the output set
        input_set = Hyperrectangle(low=curr_lbs, high=curr_ubs)
        reach = forward_network(ai2z, network, input_set)

        # The support function ρ maximizes coeffs^T x for x in reach
        curr_overestimate = ρ(coeffs, reach)
        curr_overestimate ≥ overestimate ? overestimate = curr_overestimate : nothing
        # Maximize the negative and take negative to get minimum
        curr_underestimate = -ρ(-coeffs, reach)
        curr_underestimate ≤ underestimate ? underestimate = curr_underestimate : nothing
    end

    return underestimate, overestimate
end

function get_bounds(lbs, ubs, n_per_latent, n_per_state)
    lbs_disc = []
    ubs_disc = []

    for i = 1:n_per_latent
        for j = 1:n_per_latent
            for k = 1:n_per_state
                for l = 1:n_per_state
                    # Find the upper and lower bounds of your region
                    lb1 = lbs[1] + (i-1)/n_per_latent * (ubs[1] - lbs[1])
                    lb2 = lbs[2] + (j-1)/n_per_latent * (ubs[2] - lbs[2])
                    lb3 = lbs[3] + (k-1)/n_per_state * (ubs[3] - lbs[3])
                    lb4 = lbs[4] + (l-1)/n_per_state * (ubs[4] - lbs[4])
                    ub1 = lbs[1] + (i)/n_per_latent * (ubs[1] - lbs[1])
                    ub2 = lbs[2] + (j)/n_per_latent * (ubs[2] - lbs[2])
                    ub3 = lbs[3] + (k)/n_per_state * (ubs[3] - lbs[3])
                    ub4 = lbs[4] + (l)/n_per_state * (ubs[4] - lbs[4])
                    cur_lbs = [lb1, lb2, lb3, lb4]
                    cur_ubs = [ub1, ub2, ub3, ub4]

                    push!(lbs_disc, cur_lbs)
                    push!(ubs_disc, cur_ubs)
                end
            end
        end
    end

    return lbs_disc, ubs_disc
end

""" ai2zPQ functions """

function ai2zPQ_bounds(network, lbs, ubs, coeffs)
    # Define functions
    evaluate_objective_max(network, x) = dot(coeffs, NeuralVerification.compute_output(network, x))
    evaluate_objective_min(network, x) = dot(-coeffs, NeuralVerification.compute_output(network, x))
    optimize_reach_max(reach) = ρ(coeffs, reach)
    optimize_reach_min(reach) = ρ(-coeffs, reach)

    # Get maximum control
    x, under, value = priority_optimization(network, lbs, ubs, optimize_reach_max, evaluate_objective_max)
    max_control = value
    println(value - under)
    println(x)
    # Get the minimum control
    _, _, value = priority_optimization(network, lbs, ubs, optimize_reach_min, evaluate_objective_min)
    min_control = -value

    return min_control, max_control
end

""" Perform verification on entire tree """

function verify_tree!(tree, network; get_control_bounds = ai2zPQ_bounds, coeffs = [-0.74, -0.44],
            n_per_latent = 30, n_per_state = 2, latent_bound = 1.0)
    # Stacks to go through tree
    lb_s = Stack{Vector{Float64}}()
    ub_s = Stack{Vector{Float64}}()
    s = Stack{Union{LEAFNODE, KDNODE}}()

    push!(lb_s, tree.lbs)
    push!(ub_s, tree.ubs)
    push!(s, tree.root_node)

    while !(isempty(s))
        println(length(s))
        curr = pop!(s)
        curr_lbs = pop!(lb_s)
        curr_ubs = pop!(ub_s)

        if typeof(curr) == LEAFNODE
            verify_lbs = [-latent_bound; -latent_bound; curr_lbs ./ [6.366468343804353, 17.248858791583547]]
            verify_ubs = [latent_bound; latent_bound; curr_ubs ./ [6.366468343804353, 17.248858791583547]]

            min_control, max_control = get_control_bounds(network, verify_lbs, verify_ubs, coeffs)

            curr.min_control = min_control
            curr.max_control = max_control
        else
            # Traverse tree and keep track of bounds
            dim = curr.dim
            split = curr.split
            # Go left, upper bounds will change
            left_ubs = copy(curr_ubs)
            left_ubs[dim] = split

            push!(lb_s, curr_lbs)
            push!(ub_s, left_ubs)
            push!(s, curr.left)

            # Go right, lower bounds will change
            right_lbs = copy(curr_lbs)
            right_lbs[dim] = split

            push!(lb_s, right_lbs)
            push!(ub_s, curr_ubs)
            push!(s, curr.right)
        end
    end
end

max_stars_repo_name: sisl/VerifyGAN

max_issues_repo_name: sisl/VerifyGAN

max_forks_repo_name: sisl/VerifyGAN


text:
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
#  Niccolò Antonello <nantonel@idiap.ch>

module HMMGradients

using LinearAlgebra, SparseArrays
using ChainRulesCore

include("forward.jl")
include("logforward.jl")
include("backward.jl")
include("logbackward.jl")
include("posteriors.jl")
include("losses.jl")
include("grad.jl")
include("loggrad.jl")
include("chain_rules.jl")
include("utils.jl")

end


text:
import Pkg; Pkg.activate(".")
include("../required.jl")

coords = (left = -145.0, right = -50.0, bottom = 20.0, top = 75.0)

# Test loading variables
# lc_vars = landcover(1:10, resolution = 5.0)
# lc_vars = landcover(1:10, resolution = 10.0)
# lc_vars = map(x -> landcover(x, resolution = 10.0)[coords], 1:10)

# # Test loading variables
# lc_vars = SimpleSDMPredictor(Copernicus, LandCover, 1:10; resolution = 5.0)
# lc_vars = SimpleSDMPredictor(Copernicus, LandCover, 1:10)
# lc_vars = map(x -> SimpleSDMPredictor(Copernicus, LandCover, x)[coords], 1:10)

# # Check compatibility
# lc1 = SimpleSDMPredictor(Copernicus, LandCover, 1)
# wc1 = SimpleSDMPredictor(WorldClim, BioClim, 1)
# SimpleSDMLayers._layers_are_compatible(lc1, wc1) # compatible

# # lc1 = SimpleSDMPredictor(Copernicus, LandCover, 1; coords...)
# lc1 = SimpleSDMPredictor(Copernicus, LandCover, 1)[coords]
# lc1 = lc1[top = coords.top - stride(lc1, 2)]
# wc1 = SimpleSDMPredictor(WorldClim, BioClim, 1; coords...)
# SimpleSDMLayers._layers_are_compatible(lc1, wc1) # not compatible

## Export values to compare
lc_path = joinpath("assets", "landcover")
function nothingtomissing!(df::DataFrame)
    allowmissing!(df)
    for col in eachcol(df)
        replace!(col, nothing => missing)
    end
end
function valuesdf(layers::Vector{T}) where {T <: SimpleSDMLayer}
    df = DataFrame(layers)
    select!(df, Not([:longitude, :latitude]))
    rename!(df, Symbol.("lc", 1:10))
    nothingtomissing!(df)
    return df
end

# lc_vars = map(x -> SimpleSDMPredictor(Copernicus, LandCover, x)[coords], 1:10)
# lc_vars = [l[top = coords.top - stride(l, 2)] for l in lc_vars]
lc_vars = SimpleSDMPredictor(Copernicus, LandCover, 1:10)
lc_vars = SimpleSDMPredictor(Copernicus, LandCover, 1:10; coords...)
lc1 = copy(lc_vars)[1]
wc1 = SimpleSDMPredictor(WorldClim, BioClim, 1; coords...)

# Step 1: SimpleSDMPredictor, as before
df1 = valuesdf(lc_vars)
# CSV.write(joinpath(lc_path, "landcover_values_df1.csv"), df1)
df1 = CSV.read(joinpath(lc_path, "landcover_values_df1.csv"), DataFrame)

# Step 2: SimpleSDMPredictor, with integer as default and range as overload
SimpleSDMPredictor(Copernicus, LandCover)
SimpleSDMPredictor(Copernicus, LandCover, 1)
SimpleSDMPredictor(Copernicus, LandCover, 1:10)
df2 = valuesdf(lc_vars)
# CSV.write(joinpath(lc_path, "landcover_values_df2.csv"), df2)
df2 = CSV.read(joinpath(lc_path, "landcover_values_df2.csv"), DataFrame)
isequal(df1, df2) # true
# confirmed by comparison

# Step 3. load with geotiff instead of custom ArchGDAL call
layer = 1
resolution = 10.0
path = joinpath("assets", "landcover")

# List files in path
lc_files = readdir(path)
# Filter for selected resolution
filter!(x -> occursin.("$(Int(resolution))m.tif", x), lc_files)
# Create path for selected layer only
p = joinpath.(path, lc_files)[layer]
# Use geotiff instead
geotiff(SimpleSDMPredictor, p)
ArchGDAL.getgeotransform(d)
wctransform = ArchGDAL.getgeotransform(ArchGDAL.read(joinpath(ENV["SDMLAYERS_PATH"], "WorldClim", "BioClim", "10", "wc2.1_10m_bio_1.tif")))

gdalwarp -te -180.0 -60.0 180.0 80.0 assets/landcover/lc_bare_10m.tif assets/landcover/lc_bare_10m2.tif

p2 = replace(p, ".tif" => "2.tif")
d2 = ArchGDAL.read(p2)
ArchGDAL.getgeotransform(d2)
landcover_layers2 = geotiff(SimpleSDMPredictor, p2)

l3 = geotiff(SimpleSDMPredictor, p2; coords...)
SimpleSDMLayers._layers_are_compatible(l3, l1) # not compatible
SimpleSDMLayers._layers_are_compatible(l3, wc1) # true, compatible with WorldClim!!
isequal(l3.grid, l1.grid) # grids are equal!!

# Export values
lc_files = readdir(path)
filter!(x -> occursin.("$(Int(resolution))m.tif", x), lc_files)
ps = joinpath.(path, lc_files)
lc_vars = geotiff.(SimpleSDMPredictor, ps)
lc_vars = geotiff.(SimpleSDMPredictor, ps; coords...)
lc_vars = convert.(Float32, lc_vars)
df3 = valuesdf(lc_vars)
# CSV.write(joinpath(lc_path, "landcover_values_df1.csv"), df3)
# CSV.write(joinpath(lc_path, "landcover_values_df3.csv"), df3)
df3 = CSV.read(joinpath(lc_path, "landcover_values_df3.csv"), DataFrame)
isequal(df1, df3) # true
# confirmed by comparison

# Step 4: Update function
SimpleSDMLayers._layers_are_compatible(lc1, wc1)
df4 = valuesdf(lc_vars)
# CSV.write(joinpath(lc_path, "landcover_values_df1.csv"), df4)
# CSV.write(joinpath(lc_path, "landcover_values_df4.csv"), df4)
df4 = CSV.read(joinpath(lc_path, "landcover_values_df4.csv"), DataFrame)
isequal(df1, df4) # true
# confirmed by comparison

# Step 5: stack
stack_path = joinpath("assets", "landcover", "landcover.tif")
geotiff(stack_path, lc_vars)
lc_vars2 = [geotiff(SimpleSDMPredictor, stack_path, i) for i in 1:10]
lc_vars2 = replace.(lc_vars2, NaN => nothing)
isequal(lc_vars, lc_vars2)
isequal(lc_vars[1], lc_vars2[1])
isequal(lc_vars[1].grid, lc_vars2[1].grid)
isequal(size(lc_vars[1]), size(lc_vars2[1].grid)) # not same size...
# so dimensions problem with geotiff writing and/or reading call too...

geotiff("test.tif", lc_vars[1])
test1 = geotiff(SimpleSDMPredictor, "test.tif")
isequal(size(lc_vars[1]), test1) # not equal
dtest1 = ArchGDAL.read("test.tif") # dimensions are good in tif file
ArchGDAL.getgeotransform(dtest1) # possibly are problem with left coordinate?

max_stars_repo_name: gabrieldansereau/betadiversity-hotspots

max_issues_repo_name: gabrieldansereau/betadiversity-hotspots

max_forks_repo_name: gabrieldansereau/betadiversity-hotspots


text:
function to_rna(dna)
    replacements = Dict(
        'G' => 'C',
        'C' => 'G',
        'T' => 'A',
        'A' => 'U'
    )

    try
        map(ch -> replacements[ch], dna)
    catch KeyError
        error("invalid strand")
    end
end

max_stars_repo_name: twolodzko/Learning

max_issues_repo_name: twolodzko/Learning

max_forks_repo_name: twolodzko/Learning


text:
function *(s::Shell{Nothing}, obj::AbstractPrimitive{N,T}) where {N,T}
    Shell(obj, s.distance)
end

function translate(vect::AbstractVector)
    Translation(vect...)
end

function *(transform::AbstractAffineMap, obj::PT) where {PT<:AbstractPrimitive}
    MapContainer(transform, inv(transform), obj)
end

function *(t::AbstractAffineMap, obj::MapContainer)
    c = compose(obj.map, t)
    MapContainer(c, inv(c), obj.primitive)
end

function *(a::AbstractAffineMap, b::AbstractAffineMap)
    compose(a,b)
end

function transform(t::AbstractAffineMap, h::HyperRectangle{3,T}) where {T}
    p_1 = t(h.origin)
    p_2 = t(h.widths)
    p_3 = t(SVector(h.origin[1]+h.widths[1],h.origin[2],h.origin[3]))
    p_4 = t(SVector(h.origin[1],h.origin[2]+h.widths[2],h.origin[3]))
    p_5 = t(SVector(h.origin[1],h.origin[2],h.origin[3]+h.widths[3]))
    p_6 = t(SVector(h.origin[1]+h.widths[1],h.origin[2],h.origin[3]+h.widths[3]))
    p_7 = t(SVector(h.origin[1],h.origin[2]+h.widths[2],h.origin[3]+h.widths[3]))
    p_8 = t(SVector(h.origin[1]+h.widths[1],h.origin[2]+h.widths[2],h.origin[3]))
    x_o = min(p_1[1],p_2[1],p_3[1],p_4[1],p_5[1],p_6[1],p_7[1],p_8[1])
    y_o = min(p_1[2],p_2[2],p_3[2],p_4[2],p_5[2],p_6[2],p_7[2],p_8[2])
    z_o = min(p_1[3],p_2[3],p_3[3],p_4[3],p_5[3],p_6[3],p_7[3],p_8[3])
    x_w = max(p_1[1],p_2[1],p_3[1],p_4[1],p_5[1],p_6[1],p_7[1],p_8[1])
    y_w = max(p_1[2],p_2[2],p_3[2],p_4[2],p_5[2],p_6[2],p_7[2],p_8[2])
    z_w = max(p_1[3],p_2[3],p_3[3],p_4[3],p_5[3],p_6[3],p_7[3],p_8[3])
    HyperRectangle(x_o, y_o, z_o, x_w-x_o, y_w-y_o, z_w-z_o)
end

function rotate(ang, axis::Vector)
    if !iszero(axis[1])
        return LinearMap(RotX(ang))
    elseif !iszero(axis[2])
        return LinearMap(RotY(ang))
    elseif !iszero(axis[3])
        return LinearMap(RotZ(ang))
    else
        return LinearMap(RotX(ang)) # default to X? TODO: What does OpenSCAD use?
    end
end

function transform(t::AbstractAffineMap, h::HyperRectangle{2,T}) where {T}
    p_1 = t(h.origin)
    p_2 = t(h.widths)
    p_3 = t(SVector(h.origin[1]+h.widths[1],h.origin[2]))
    p_4 = t(SVector(h.origin[1],h.origin[2]+h.widths[2]))
    x_o = min(p_1[1],p_2[1],p_3[1],p_4[1])
    y_o = min(p_1[2],p_2[2],p_3[2],p_4[2])
    x_w = max(p_1[1],p_2[1],p_3[1],p_4[1])
    y_w = max(p_1[2],p_2[2],p_3[2],p_4[2])
    HyperRectangle(x_o, y_o, x_w-x_o, y_w-y_o)
end

#function clarkcatmull!(n::Integer, pipe::Pipe{Float64})
#    length(pipe.points) < 3 && return
#    num_pts = length(pipe.points)
#    num_new_pts = num_pts + num_pts*(2^n-1)
#
#    for _ = 1:n
#        i = 1
#        while i < length(p.points)
#            e1 = pipe.points[i]
#            e2 = pipe.points[i+1]
#            e3 = pipe.points[i+2]
#            fp1 = e1 + (e2-e1)/2
#            fp2 = e2 + (e3-e2)/2
#        end
#    end
#end


text:
using JuMP
using Clp
using Cbc
using GLPK

include("../OptMaps.jl")
using .OptMaps

function solve_model(solver, model_log, solver_options=Dict())
    model = Model(solver)

    for (k, v) in solver_options
        set_optimizer_attribute(model, k, v)
    end

    #sets
    foods = [:carrots, :potatoes, :bread, :cheese]
    resources = [:calories, :fat, :protein, :carbohydrate]

    #parameters
    cost_per_food = [0.14 0.4 0.3 0.75]
    rsc_per_food = [23.0  171.0  65.0  112.0;
                     0.1    0.2   0.0    9.3;
                     0.6    3.7   2.2    7.0;
                     6.0   30.0  13.0    5.0]

    demand_per_rsc = [2000 30 200 250]

    n_foods = length(foods)
    n_resources =length(resources)

    n_variables = n_foods
    n_constraints = n_resources

    ###############################################################
    #decision variables
    @variable(model, amt_per_food[1:n_foods] >= 0)

    starting_point = zeros(Float64, n_foods)
    solution_point = zeros(Float64, n_foods)

    for i in 1:n_foods
        v = start_value(amt_per_food[i])
        starting_point[i] = v === nothing ? 0.0 : v
    end

    ###############################################################
    #objective

    #regular function
    total_cost_f(amt_per_food) = sum([cost_per_food[f] * amt_per_food[f] for f in 1:n_foods])

    #jump expression
    total_cost = @expression(model, total_cost, sum(cost_per_food[f] * amt_per_food[f] for f in 1:n_foods))
    @objective(model, Min, total_cost)

    ###############################################################
    #constraints: fulfill min nutrition demand (demand_per_rsc)

    #regular functions
    constraints_f = []

    for r in 1:n_resources
        push!(constraints_f, (amt_per_food) -> sum([amt_per_food[f]*rsc_per_food[r,f]  for f in 1:n_foods]) >= demand_per_rsc[r])
    end

    #jump expressions
    @constraint(model, dmd[r = 1:n_resources], sum((amt_per_food[f]*rsc_per_food[r,f]  for f in 1:n_foods)) >= demand_per_rsc[r])

    ###############################################################
    #save model textual description
    open(model_log, "w") do f
        print(f, model)

        ###############################################################
        #solve model
        elapsed_time = @elapsed optimize!(model)

        println(f, "-----------------------------------------------")
        println(f, "Elapsed time: $elapsed_time")
        println(f, "-----------------------------------------------")
        println(f, "Status:    $(termination_status(model))")
        println(f, "Objective: $(objective_value(model))")
        println(f, "-----------------------------------------------")
        println(f, "Variables:")

        for fd in 1:n_foods
            println(f, "$(foods[fd]): $(value(amt_per_food[fd]))")
            solution_point[fd] = value(amt_per_food[fd])
        end
        # println(f, "-----------------------------------------------")
        # println(f, "Shadow prices:")
        # for r in 1:n_resources
        #     println(f, "$r - $(resources[r]):  $(shadow_price(dmd[r]))")
        # end
    end

    variable_names = ["amt_per_food[$(String(f))]" for f in foods]
    constraint_names = ["dmd[$(String(r))]" for r in resources]

    obj_val = objective_value(model)

    return total_cost_f, constraints_f, variable_names, constraint_names, starting_point, solution_point, obj_val
end

#The datatype used in the tuples is used to determine if the variable is "real" or integer
variable_domains = [(0.0,30.0), (0.0,30.0), (0.0,30.0), (0.0,30.0)]

optimizers = [Clp.Optimizer, GLPK.Optimizer, Cbc.Optimizer]
opt_names = ["clp", "glpk", "cbc"]

problems = Dict()

for (opt, opt_name) in zip(optimizers, opt_names)
    objective_f, constraints_f, variable_names, constraint_names, starting_point, solution_point, obj_val = solve_model(opt, "diet_$(opt_name).log")
    problems[opt_name] = (objective_f, constraints_f, variable_names, constraint_names, starting_point, solution_point, obj_val)
end

#All functions are equal, get first to initialize OptMap
objective_f, constraints_f, variable_names, constraint_names, _, _, obj_val = problems[opt_names[1]]
O = OptMap(variable_names, variable_domains, objective_f; constraint_names=constraint_names, constraints_f=constraints_f, verbose=true)
create_map!(O)

for opt_name in opt_names
    _, _, _, _, starting_point, solution_point, _ = problems[opt_name]

    path_to_solution = zeros(Float64, length(variable_domains), 2)
    path_to_solution[:,1] = starting_point
    path_to_solution[:,2] = solution_point

    draw_solution!(O, path_to_solution)
    save_all(O, "diet_$(opt_name)", ".")
end

max_stars_repo_name: nmaterise/optmap

max_issues_repo_name: nmaterise/optmap

max_forks_repo_name: nmaterise/optmap


text:
"""
    Empty(T)

Create a proxy of an empty container of type `T`.

This is a simple API for solving problems such as:

* There is no consistent way to create an empty container given its type.
* There is no consistent way to know that nothing was appended into the
  container in type-domain.

Internally, this function simply works by creating a singleton container
(a container with one element) using [`singletonof`](@ref) when the first
element is [`push!!`](@ref)'ed.

# Examples
```jldoctest
julia> using BangBang

julia> push!!(Empty(Vector), 1)
1-element Array{Int64,1}:
 1

julia> append!!(Empty(Dict), (:a=>1, :b=>2))
Dict{Symbol,Int64} with 2 entries:
  :a => 1
  :b => 2

julia> using DataFrames: DataFrame

julia> @assert push!!(Empty(DataFrame), (a=1, b=2)) == DataFrame(a=[1], b=[2])

julia> using StructArrays: StructVector

julia> @assert push!!(Empty(StructVector), (a=1, b=2)) == StructVector(a=[1], b=[2])

julia> using TypedTables: Table

julia> @assert push!!(Empty(Table), (a=1, b=2)) == Table(a=[1], b=[2])

julia> using StaticArrays: SVector

julia> @assert push!!(Empty(SVector), 1) === SVector(1)
```

`Empty(T)` object is an iterable with length 0 and element type `Union{}`:

```jldoctest; setup=:(using BangBang)
julia> collect(Empty(Vector))
0-element Array{Union{},1}

julia> length(Empty(Vector))
0

julia> eltype(typeof(Empty(Vector)))
Union{}

julia> Base.IteratorSize(Empty)
Base.HasLength()

julia> Base.IteratorEltype(Empty)
Base.HasEltype()
```
"""
struct Empty{T} end
Empty(T::Type) = Empty{T}()

push(::Empty{T}, x) where T = singletonof(T, x)
append(::Empty{T}, x) where T = T(x)
# In `append`, it is assumed that `T(x::Vector)` works (as done in the
# implementation of `singletonof`).

append(e::Empty, ::Empty) = e

_empty(x::Empty) = x
resize(::Empty{T}, n::Integer) where {T <: AbstractVector} = similar(T, (n,))

_union(::Empty{T}, x) where {T} = unique!!(T(x))
_union(e::Empty, ::Empty) = e

_setdiff(x::Empty, _) = x

_setindex(::Empty{T}, v, k) where {T <: AbstractDict} = T(SingletonDict(k, v))
Base.get(::Empty, _, default) = default

Base.IteratorSize(::Type{<:Empty}) = Base.HasLength()
Base.IteratorEltype(::Type{<:Empty}) = Base.HasEltype()
Base.eltype(::Type{<:Empty}) = Union{}
Base.eltype(::Type{<:Empty{<:AbstractVector{T}}}) where {T} = T
Base.length(::Empty) = 0
Base.iterate(::Empty) = nothing
Base.haskey(::Empty, ::Any) = false

Base.firstindex(::Empty{<:Vector}) = 1
Base.lastindex(::Empty{<:Vector}) = 0
Base.similar(e::Empty) = similar(e, eltype(e), (0,))
Base.similar(e::Empty, dims::Int...) = similar(e, eltype(e), dims)
Base.similar(e::Empty, dims::Tuple{Vararg{Int}}) = similar(e, eltype(e), dims)
Base.similar(e::Empty, T::Type) = similar(e, T, (0,))
Base.similar(e::Empty, T::Type, dims::Int...) = similar(e, T, dims)
Base.similar(::Empty{<:Vector}, T::Type, dims::Tuple{Vararg{Int}}) =
    similar(Vector{T}, dims)
Base.similar(::Empty{Vector{T}}, dims::Tuple{Vararg{Int}}) where {T} =
    similar(Vector{T}, dims)


text:
using StatsBase

function algSDA(problem::Problem, opts::Opts, oo::OutputOpts, writeFunction::Function)

	srand(1)

	opts.outputLevel>0 && println("Function to minimize: $(problem.name) with loss function $(problem.lossFunctionString), L2reg = $(problem.L2reg)")
	opts.outputLevel>0 && println("Step: SDA with stepSizePower = $(opts.stepSizePower)")
	opts.outputLevel>0 && println("Opts: $(opts.optsString)")
	opts.outputLevel>0 && println("OutputOpts: $(oo.ooString)")

	maxG = min(opts.maxG, oo.expIndices[end]);

	results_k = Int64[]
	results_gnum = Int64[]
	results_fromOutputsFunction = zeros(0,oo.outputter.numOutputsFromOutputsFunction)

	kOutputs=1
	k=0
	gnum=0
	x=opts.init

	xSum=copy(x)
	xToTest = zeros(size(x))

	opts.outputLevel>1 && println("        k     gnum"*oo.outputter.outputStringHeader)

	betahat=1

	while true

		if gnum >= oo.expIndices[kOutputs]
			xToTest = xSum/(k+1)
			fromOutputsFunction::ResultFromOO = oo.outputter.outputsFunction(xToTest)
			if opts.outputLevel>1
				@printf("%2.i %8.i %8.i ", kOutputs, k, gnum)
				println(fromOutputsFunction.resultString)
			end
			writeFunction(problem, sd, opts, k, gnum, oo.expIndices[kOutputs], fromOutputsFunction)
			if isnan(fromOutputsFunction.resultLine[end])
				return ("NaN found", results_k, results_gnum,results_fromOutputsFunction,xToTest)
			end
			push!(results_k,k)
			push!(results_gnum,gnum)
			results_fromOutputsFunction = [results_fromOutputsFunction ; fromOutputsFunction.resultLine']
			kOutputs += 1
		end

		gnum >= maxG && break

		func = consume(problem.getNextSampleFunction)
		(f, g) = func(x)

	    sumg += g
	    beta = (2.0^opts.stepSizePower) * betahat
	    x = -sumg/beta
	    if k>1
	    	betahat = betahat + 1/betahat
		end
		xSum += x;

		k+=1

	end

	exit()

	opts.outputLevel>0 && println("Finished alg: SDA")

	## Write answer!
	("Finished nicely", results_k, results_gnum, results_fromOutputsFunction, xToTest)
end


text:
# build domain and true image
domain = [0.0 1.0 0.0 1.0]
n      = [16,16]
Minv   = getRegularMesh(domain,n)
xc     = getCellCenteredGrid(Minv)
xtrue  = sin.(2*pi*xc[:,1]).*sin.(pi*xc[:,2])
A      = sparse(1.0I,Minv.nc,Minv.nc)
ids    = sort(rand(1:Minv.nc,round(Int64,Minv.nc*.8)))
A      = A[ids,:]
btrue  = A*xtrue

#Generate two forward problems
i1     = (1:round(Int64,size(A,1)/2))
i2     = (round(Int64,size(A,1)/2)+1:size(A,1))
pFor1  = LSparam(A[i1,:],[])
pFor2  = LSparam(A[i2,:],[])
sigmaBack    = zeros(length(xtrue))
Iact         = sparse(1.0I,Minv.nc,Minv.nc)
gl1          = getGlobalToLocal(1.0,sigmaBack)
gl2          = getGlobalToLocal(Iact,sigmaBack)

#Test with locally stored forward problems
localPfors = [pFor1;pFor2]
D1, = getData(xtrue,localPfors)
@test norm([fetch(D1[1]);fetch(D1[2])]-btrue)/norm(btrue) < 1e-10

#Test with forward problems on remote workers
pForRefs    = Array{RemoteChannel}(undef,2)
workerList  = workers()
nw          = nworkers()
pForRefs[1] = initRemoteChannel(LSparam,workerList[1%nw+1],A[i1,:],[])
pForRefs[2] = initRemoteChannel(LSparam,workerList[2%nw+1],A[i2,:],[])
D2,pForRefs = getData(xtrue,pForRefs,ones(length(pForRefs)),true)
@test norm([fetch(D2[1]);fetch(D2[2])]-btrue)/norm(btrue) < 1e-10

#Test doClear flag.
@test fetch(pForRefs[1]).A    == sparse(I,0,0)
@test fetch(pForRefs[1]).Ainv == []
@test fetch(pForRefs[2]).A    == sparse(I,0,0)
@test fetch(pForRefs[2]).Ainv == []
@test_throws Exception D3, = getData(xtrue,pForRefs)