text:
@enum Id::Int begin
    IdResultType      = 1
    IdResult          = 2
    IdMemorySemantics = 3
    IdScope           = 4
    IdRef             = 5
end

@enum Literal::Int begin
    LiteralInteger                = 1
    LiteralString                 = 2
    LiteralContextDependentNumber = 3
    LiteralExtInstInteger         = 4
    LiteralSpecConstantOpInteger  = 5
end

@enum Composite::Int begin
    PairLiteralIntegerIdRef = 1
    PairIdRefLiteralInteger = 2
    PairIdRefIdRef = 3
end

@cenum ImageOperands::UInt32 begin
    ImageOperandsNone                  = 0x00000000
    ImageOperandsBias                  = 0x00000001
    ImageOperandsLod                   = 0x00000002
    ImageOperandsGrad                  = 0x00000004
    ImageOperandsConstOffset           = 0x00000008
    ImageOperandsOffset                = 0x00000010
    ImageOperandsConstOffsets          = 0x00000020
    ImageOperandsSample                = 0x00000040
    ImageOperandsMinLod                = 0x00000080
    ImageOperandsMakeTexelAvailable    = 0x00000100
    ImageOperandsMakeTexelAvailableKHR = 0x00000100
    ImageOperandsMakeTexelVisible      = 0x00000200
    ImageOperandsMakeTexelVisibleKHR   = 0x00000200
    ImageOperandsNonPrivateTexel       = 0x00000400
    ImageOperandsNonPrivateTexelKHR    = 0x00000400
    ImageOperandsVolatileTexel         = 0x00000800
    ImageOperandsVolatileTexelKHR      = 0x00000800
    ImageOperandsSignExtend            = 0x00001000
    ImageOperandsZeroExtend            = 0x00002000
end

@cenum FPFastMathMode::UInt32 begin
    FPFastMathModeNone       = 0x00000000
    FPFastMathModeNotNaN     = 0x00000001
    FPFastMathModeNotInf     = 0x00000002
    FPFastMathModeNSZ        = 0x00000004
    FPFastMathModeAllowRecip = 0x00000008
    FPFastMathModeFast       = 0x00000010
end

@cenum SelectionControl::UInt32 begin
    SelectionControlNone        = 0x00000000
    SelectionControlFlatten     = 0x00000001
    SelectionControlDontFlatten = 0x00000002
end

@cenum LoopControl::UInt32 begin
    LoopControlNone                      = 0x00000000
    LoopControlUnroll                    = 0x00000001
    LoopControlDontUnroll                = 0x00000002
    LoopControlDependencyInfinite        = 0x00000004
    LoopControlDependencyLength          = 0x00000008
    LoopControlMinIterations             = 0x00000010
    LoopControlMaxIterations             = 0x00000020
    LoopControlIterationMultiple         = 0x00000040
    LoopControlPeelCount                 = 0x00000080
    LoopControlPartialCount              = 0x00000100
    LoopControlInitiationIntervalINTEL   = 0x00010000
    LoopControlMaxConcurrencyINTEL       = 0x00020000
    LoopControlDependencyArrayINTEL      = 0x00040000
    LoopControlPipelineEnableINTEL       = 0x00080000
    LoopControlLoopCoalesceINTEL         = 0x00100000
    LoopControlMaxInterleavingINTEL      = 0x00200000
    LoopControlSpeculatedIterationsINTEL = 0x00400000
end

@cenum FunctionControl::UInt32 begin
    FunctionControlNone       = 0x00000000
    FunctionControlInline     = 0x00000001
    FunctionControlDontInline = 0x00000002
    FunctionControlPure       = 0x00000004
    FunctionControlConst      = 0x00000008
end

@cenum MemorySemantics::UInt32 begin
    MemorySemanticsRelaxed                = 0x00000000
    MemorySemanticsNone                   = 0x00000000
    MemorySemanticsAcquire                = 0x00000002
    MemorySemanticsRelease                = 0x00000004
    MemorySemanticsAcquireRelease         = 0x00000008
    MemorySemanticsSequentiallyConsistent = 0x00000010
    MemorySemanticsUniformMemory          = 0x00000040
    MemorySemanticsSubgroupMemory         = 0x00000080
    MemorySemanticsWorkgroupMemory        = 0x00000100
    MemorySemanticsCrossWorkgroupMemory   = 0x00000200
    MemorySemanticsAtomicCounterMemory    = 0x00000400
    MemorySemanticsImageMemory            = 0x00000800
    MemorySemanticsOutputMemory           = 0x00001000
    MemorySemanticsOutputMemoryKHR        = 0x00001000
    MemorySemanticsMakeAvailable          = 0x00002000
    MemorySemanticsMakeAvailableKHR       = 0x00002000
    MemorySemanticsMakeVisible            = 0x00004000
    MemorySemanticsMakeVisibleKHR         = 0x00004000
    MemorySemanticsVolatile               = 0x00008000
end

@cenum MemoryAccess::UInt32 begin
    MemoryAccessNone                    = 0x00000000
    MemoryAccessVolatile                = 0x00000001
    MemoryAccessAligned                 = 0x00000002
    MemoryAccessNontemporal             = 0x00000004
    MemoryAccessMakePointerAvailable    = 0x00000008
    MemoryAccessMakePointerAvailableKHR = 0x00000008
    MemoryAccessMakePointerVisible      = 0x00000010
    MemoryAccessMakePointerVisibleKHR   = 0x00000010
    MemoryAccessNonPrivatePointer       = 0x00000020
    MemoryAccessNonPrivatePointerKHR    = 0x00000020
end

@cenum KernelProfilingInfo::UInt32 begin
    KernelProfilingInfoNone        = 0x00000000
    KernelProfilingInfoCmdExecTime = 0x00000001
end

@cenum RayFlags::UInt32 begin
    RayFlagsNoneKHR                     = 0x00000000
    RayFlagsOpaqueKHR                   = 0x00000001
    RayFlagsNoOpaqueKHR                 = 0x00000002
    RayFlagsTerminateOnFirstHitKHR      = 0x00000004
    RayFlagsSkipClosestHitShaderKHR     = 0x00000008
    RayFlagsCullBackFacingTrianglesKHR  = 0x00000010
    RayFlagsCullFrontFacingTrianglesKHR = 0x00000020
    RayFlagsCullOpaqueKHR               = 0x00000040
    RayFlagsCullNoOpaqueKHR             = 0x00000080
    RayFlagsSkipTrianglesKHR            = 0x00000100
    RayFlagsSkipAABBsKHR                = 0x00000200
end

@cenum FragmentShadingRate::UInt32 begin
    FragmentShadingRateVertical2Pixels   = 0x00000001
    FragmentShadingRateVertical4Pixels   = 0x00000002
    FragmentShadingRateHorizontal2Pixels = 0x00000004
    FragmentShadingRateHorizontal4Pixels = 0x00000008
end

@cenum SourceLanguage::UInt32 begin
    SourceLanguageUnknown    = 0
    SourceLanguageESSL       = 1
    SourceLanguageGLSL       = 2
    SourceLanguageOpenCL_C   = 3
    SourceLanguageOpenCL_CPP = 4
    SourceLanguageHLSL       = 5
end

@cenum ExecutionModel::UInt32 begin
    ExecutionModelVertex                 = 0
    ExecutionModelTessellationControl    = 1
    ExecutionModelTessellationEvaluation = 2
    ExecutionModelGeometry               = 3
    ExecutionModelFragment               = 4
    ExecutionModelGLCompute              = 5
    ExecutionModelKernel                 = 6
    ExecutionModelTaskNV                 = 5267
    ExecutionModelMeshNV                 = 5268
    ExecutionModelRayGenerationNV        = 5313
    ExecutionModelRayGenerationKHR       = 5313
    ExecutionModelIntersectionNV         = 5314
    ExecutionModelIntersectionKHR        = 5314
    ExecutionModelAnyHitNV               = 5315
    ExecutionModelAnyHitKHR              = 5315
    ExecutionModelClosestHitNV           = 5316
    ExecutionModelClosestHitKHR          = 5316
    ExecutionModelMissNV                 = 5317
    ExecutionModelMissKHR                = 5317
    ExecutionModelCallableNV             = 5318
    ExecutionModelCallableKHR            = 5318
end

@cenum AddressingModel::UInt32 begin
    AddressingModelLogical                    = 0
    AddressingModelPhysical32                 = 1
    AddressingModelPhysical64                 = 2
    AddressingModelPhysicalStorageBuffer64    = 5348
    AddressingModelPhysicalStorageBuffer64EXT = 5348
end

@cenum MemoryModel::UInt32 begin
    MemoryModelSimple    = 0
    MemoryModelGLSL450   = 1
    MemoryModelOpenCL    = 2
    MemoryModelVulkan    = 3
    MemoryModelVulkanKHR = 3
end

@cenum ExecutionMode::UInt32 begin
    ExecutionModeInvocations                      = 0
    ExecutionModeSpacingEqual                     = 1
    ExecutionModeSpacingFractionalEven            = 2
    ExecutionModeSpacingFractionalOdd             = 3
    ExecutionModeVertexOrderCw                    = 4
    ExecutionModeVertexOrderCcw                   = 5
    ExecutionModePixelCenterInteger               = 6
    ExecutionModeOriginUpperLeft                  = 7
    ExecutionModeOriginLowerLeft                  = 8
    ExecutionModeEarlyFragmentTests               = 9
    ExecutionModePointMode                        = 10
    ExecutionModeXfb                              = 11
    ExecutionModeDepthReplacing                   = 12
    ExecutionModeDepthGreater                     = 14
    ExecutionModeDepthLess                        = 15
    ExecutionModeDepthUnchanged                   = 16
    ExecutionModeLocalSize                        = 17
    ExecutionModeLocalSizeHint                    = 18
    ExecutionModeInputPoints                      = 19
    ExecutionModeInputLines                       = 20
    ExecutionModeInputLinesAdjacency              = 21
    ExecutionModeTriangles                        = 22
    ExecutionModeInputTrianglesAdjacency          = 23
    ExecutionModeQuads                            = 24
    ExecutionModeIsolines                         = 25
    ExecutionModeOutputVertices                   = 26
    ExecutionModeOutputPoints                     = 27
    ExecutionModeOutputLineStrip                  = 28
    ExecutionModeOutputTriangleStrip              = 29
    ExecutionModeVecTypeHint                      = 30
    ExecutionModeContractionOff                   = 31
    ExecutionModeInitializer                      = 33
    ExecutionModeFinalizer                        = 34
    ExecutionModeSubgroupSize                     = 35
    ExecutionModeSubgroupsPerWorkgroup            = 36
    ExecutionModeSubgroupsPerWorkgroupId          = 37
    ExecutionModeLocalSizeId                      = 38
    ExecutionModeLocalSizeHintId                  = 39
    ExecutionModePostDepthCoverage                = 4446
    ExecutionModeDenormPreserve                   = 4459
    ExecutionModeDenormFlushToZero                = 4460
    ExecutionModeSignedZeroInfNanPreserve         = 4461
    ExecutionModeRoundingModeRTE                  = 4462
    ExecutionModeRoundingModeRTZ                  = 4463
    ExecutionModeStencilRefReplacingEXT           = 5027
    ExecutionModeOutputLinesNV                    = 5269
    ExecutionModeOutputPrimitivesNV               = 5270
    ExecutionModeDerivativeGroupQuadsNV           = 5289
    ExecutionModeDerivativeGroupLinearNV          = 5290
    ExecutionModeOutputTrianglesNV                = 5298
    ExecutionModePixelInterlockOrderedEXT         = 5366
    ExecutionModePixelInterlockUnorderedEXT       = 5367
    ExecutionModeSampleInterlockOrderedEXT        = 5368
    ExecutionModeSampleInterlockUnorderedEXT      = 5369
    ExecutionModeShadingRateInterlockOrderedEXT   = 5370
    ExecutionModeShadingRateInterlockUnorderedEXT = 5371
    ExecutionModeMaxWorkgroupSizeINTEL            = 5893
    ExecutionModeMaxWorkDimINTEL                  = 5894
    ExecutionModeNoGlobalOffsetINTEL              = 5895
    ExecutionModeNumSIMDWorkitemsINTEL            = 5896
end

@cenum StorageClass::UInt32 begin
    StorageClassUniformConstant          = 0
    StorageClassInput                    = 1
    StorageClassUniform                  = 2
    StorageClassOutput                   = 3
    StorageClassWorkgroup                = 4
    StorageClassCrossWorkgroup           = 5
    StorageClassPrivate                  = 6
    StorageClassFunction                 = 7
    StorageClassGeneric                  = 8
    StorageClassPushConstant             = 9
    StorageClassAtomicCounter            = 10
    StorageClassImage                    = 11
    StorageClassStorageBuffer            = 12
    StorageClassCallableDataNV           = 5328
    StorageClassCallableDataKHR          = 5328
    StorageClassIncomingCallableDataNV   = 5329
    StorageClassIncomingCallableDataKHR  = 5329
    StorageClassRayPayloadNV             = 5338
    StorageClassRayPayloadKHR            = 5338
    StorageClassHitAttributeNV           = 5339
    StorageClassHitAttributeKHR          = 5339
    StorageClassIncomingRayPayloadNV     = 5342
    StorageClassIncomingRayPayloadKHR    = 5342
    StorageClassShaderRecordBufferNV     = 5343
    StorageClassShaderRecordBufferKHR    = 5343
    StorageClassPhysicalStorageBuffer    = 5349
    StorageClassPhysicalStorageBufferEXT = 5349
    StorageClassCodeSectionINTEL         = 5605
end

@cenum Dim::UInt32 begin
    Dim1D          = 0
    Dim2D          = 1
    Dim3D          = 2
    DimCube        = 3
    DimRect        = 4
    DimBuffer      = 5
    DimSubpassData = 6
end

@cenum SamplerAddressingMode::UInt32 begin
    SamplerAddressingModeNone           = 0
    SamplerAddressingModeClampToEdge    = 1
    SamplerAddressingModeClamp          = 2
    SamplerAddressingModeRepeat         = 3
    SamplerAddressingModeRepeatMirrored = 4
end

@cenum SamplerFilterMode::UInt32 begin
    SamplerFilterModeNearest = 0
    SamplerFilterModeLinear  = 1
end

@cenum ImageFormat::UInt32 begin
    ImageFormatUnknown      = 0
    ImageFormatRgba32f      = 1
    ImageFormatRgba16f      = 2
    ImageFormatR32f         = 3
    ImageFormatRgba8        = 4
    ImageFormatRgba8Snorm   = 5
    ImageFormatRg32f        = 6
    ImageFormatRg16f        = 7
    ImageFormatR11fG11fB10f = 8
    ImageFormatR16f         = 9
    ImageFormatRgba16       = 10
    ImageFormatRgb10A2      = 11
    ImageFormatRg16         = 12
    ImageFormatRg8          = 13
    ImageFormatR16          = 14
    ImageFormatR8           = 15
    ImageFormatRgba16Snorm  = 16
    ImageFormatRg16Snorm    = 17
    ImageFormatRg8Snorm     = 18
    ImageFormatR16Snorm     = 19
    ImageFormatR8Snorm      = 20
    ImageFormatRgba32i      = 21
    ImageFormatRgba16i      = 22
    ImageFormatRgba8i       = 23
    ImageFormatR32i         = 24
    ImageFormatRg32i        = 25
    ImageFormatRg16i        = 26
    ImageFormatRg8i         = 27
    ImageFormatR16i         = 28
    ImageFormatR8i          = 29
    ImageFormatRgba32ui     = 30
    ImageFormatRgba16ui     = 31
    ImageFormatRgba8ui      = 32
    ImageFormatR32ui        = 33
    ImageFormatRgb10a2ui    = 34
    ImageFormatRg32ui       = 35
    ImageFormatRg16ui       = 36
    ImageFormatRg8ui        = 37
    ImageFormatR16ui        = 38
    ImageFormatR8ui         = 39
    ImageFormatR64ui        = 40
    ImageFormatR64i         = 41
end

@cenum ImageChannelOrder::UInt32 begin
    ImageChannelOrderR            = 0
    ImageChannelOrderA            = 1
    ImageChannelOrderRG           = 2
    ImageChannelOrderRA           = 3
    ImageChannelOrderRGB          = 4
    ImageChannelOrderRGBA         = 5
    ImageChannelOrderBGRA         = 6
    ImageChannelOrderARGB         = 7
    ImageChannelOrderIntensity    = 8
    ImageChannelOrderLuminance    = 9
    ImageChannelOrderRx           = 10
    ImageChannelOrderRGx          = 11
    ImageChannelOrderRGBx         = 12
    ImageChannelOrderDepth        = 13
    ImageChannelOrderDepthStencil = 14
    ImageChannelOrdersRGB         = 15
    ImageChannelOrdersRGBx        = 16
    ImageChannelOrdersRGBA        = 17
    ImageChannelOrdersBGRA        = 18
    ImageChannelOrderABGR         = 19
end

@cenum ImageChannelDataType::UInt32 begin
    ImageChannelDataTypeSnormInt8        = 0
    ImageChannelDataTypeSnormInt16       = 1
    ImageChannelDataTypeUnormInt8        = 2
    ImageChannelDataTypeUnormInt16       = 3
    ImageChannelDataTypeUnormShort565    = 4
    ImageChannelDataTypeUnormShort555    = 5
    ImageChannelDataTypeUnormInt101010   = 6
    ImageChannelDataTypeSignedInt8       = 7
    ImageChannelDataTypeSignedInt16      = 8
    ImageChannelDataTypeSignedInt32      = 9
    ImageChannelDataTypeUnsignedInt8     = 10
    ImageChannelDataTypeUnsignedInt16    = 11
    ImageChannelDataTypeUnsignedInt32    = 12
    ImageChannelDataTypeHalfFloat        = 13
    ImageChannelDataTypeFloat            = 14
    ImageChannelDataTypeUnormInt24       = 15
    ImageChannelDataTypeUnormInt101010_2 = 16
end

@cenum FPRoundingMode::UInt32 begin
    FPRoundingModeRTE = 0
    FPRoundingModeRTZ = 1
    FPRoundingModeRTP = 2
    FPRoundingModeRTN = 3
end

@cenum LinkageType::UInt32 begin
    LinkageTypeExport = 0
    LinkageTypeImport = 1
end

@cenum AccessQualifier::UInt32 begin
    AccessQualifierReadOnly  = 0
    AccessQualifierWriteOnly = 1
    AccessQualifierReadWrite = 2
end

@cenum FunctionParameterAttribute::UInt32 begin
    FunctionParameterAttributeZext        = 0
    FunctionParameterAttributeSext        = 1
    FunctionParameterAttributeByVal       = 2
    FunctionParameterAttributeSret        = 3
    FunctionParameterAttributeNoAlias     = 4
    FunctionParameterAttributeNoCapture   = 5
    FunctionParameterAttributeNoWrite     = 6
    FunctionParameterAttributeNoReadWrite = 7
end

@cenum Decoration::UInt32 begin
    DecorationRelaxedPrecision            = 0
    DecorationSpecId                      = 1
    DecorationBlock                       = 2
    DecorationBufferBlock                 = 3
    DecorationRowMajor                    = 4
    DecorationColMajor                    = 5
    DecorationArrayStride                 = 6
    DecorationMatrixStride                = 7
    DecorationGLSLShared                  = 8
    DecorationGLSLPacked                  = 9
    DecorationCPacked                     = 10
    DecorationBuiltIn                     = 11
    DecorationNoPerspective               = 13
    DecorationFlat                        = 14
    DecorationPatch                       = 15
    DecorationCentroid                    = 16
    DecorationSample                      = 17
    DecorationInvariant                   = 18
    DecorationRestrict                    = 19
    DecorationAliased                     = 20
    DecorationVolatile                    = 21
    DecorationConstant                    = 22
    DecorationCoherent                    = 23
    DecorationNonWritable                 = 24
    DecorationNonReadable                 = 25
    DecorationUniform                     = 26
    DecorationUniformId                   = 27
    DecorationSaturatedConversion         = 28
    DecorationStream                      = 29
    DecorationLocation                    = 30
    DecorationComponent                   = 31
    DecorationIndex                       = 32
    DecorationBinding                     = 33
    DecorationDescriptorSet               = 34
    DecorationOffset                      = 35
    DecorationXfbBuffer                   = 36
    DecorationXfbStride                   = 37
    DecorationFuncParamAttr               = 38
    DecorationFPRoundingMode              = 39
    DecorationFPFastMathMode              = 40
    DecorationLinkageAttributes           = 41
    DecorationNoContraction               = 42
    DecorationInputAttachmentIndex        = 43
    DecorationAlignment                   = 44
    DecorationMaxByteOffset               = 45
    DecorationAlignmentId                 = 46
    DecorationMaxByteOffsetId             = 47
    DecorationNoSignedWrap                = 4469
    DecorationNoUnsignedWrap              = 4470
    DecorationExplicitInterpAMD           = 4999
    DecorationOverrideCoverageNV          = 5248
    DecorationPassthroughNV               = 5250
    DecorationViewportRelativeNV          = 5252
    DecorationSecondaryViewportRelativeNV = 5256
    DecorationPerPrimitiveNV              = 5271
    DecorationPerViewNV                   = 5272
    DecorationPerTaskNV                   = 5273
    DecorationPerVertexNV                 = 5285
    DecorationNonUniform                  = 5300
    DecorationNonUniformEXT               = 5300
    DecorationRestrictPointer             = 5355
    DecorationRestrictPointerEXT          = 5355
    DecorationAliasedPointer              = 5356
    DecorationAliasedPointerEXT           = 5356
    DecorationReferencedIndirectlyINTEL   = 5602
    DecorationCounterBuffer               = 5634
    DecorationHlslCounterBufferGOOGLE     = 5634
    DecorationUserSemantic                = 5635
    DecorationHlslSemanticGOOGLE          = 5635
    DecorationUserTypeGOOGLE              = 5636
    DecorationRegisterINTEL               = 5825
    DecorationMemoryINTEL                 = 5826
    DecorationNumbanksINTEL               = 5827
    DecorationBankwidthINTEL              = 5828
    DecorationMaxPrivateCopiesINTEL       = 5829
    DecorationSinglepumpINTEL             = 5830
    DecorationDoublepumpINTEL             = 5831
    DecorationMaxReplicatesINTEL          = 5832
    DecorationSimpleDualPortINTEL         = 5833
    DecorationMergeINTEL                  = 5834
    DecorationBankBitsINTEL               = 5835
    DecorationForcePow2DepthINTEL         = 5836
end

@cenum BuiltIn::UInt32 begin
    BuiltInPosition                    = 0
    BuiltInPointSize                   = 1
    BuiltInClipDistance                = 3
    BuiltInCullDistance                = 4
    BuiltInVertexId                    = 5
    BuiltInInstanceId                  = 6
    BuiltInPrimitiveId                 = 7
    BuiltInInvocationId                = 8
    BuiltInLayer                       = 9
    BuiltInViewportIndex               = 10
    BuiltInTessLevelOuter              = 11
    BuiltInTessLevelInner              = 12
    BuiltInTessCoord                   = 13
    BuiltInPatchVertices               = 14
    BuiltInFragCoord                   = 15
    BuiltInPointCoord                  = 16
    BuiltInFrontFacing                 = 17
    BuiltInSampleId                    = 18
    BuiltInSamplePosition              = 19
    BuiltInSampleMask                  = 20
    BuiltInFragDepth                   = 22
    BuiltInHelperInvocation            = 23
    BuiltInNumWorkgroups               = 24
    BuiltInWorkgroupSize               = 25
    BuiltInWorkgroupId                 = 26
    BuiltInLocalInvocationId           = 27
    BuiltInGlobalInvocationId          = 28
    BuiltInLocalInvocationIndex        = 29
    BuiltInWorkDim                     = 30
    BuiltInGlobalSize                  = 31
    BuiltInEnqueuedWorkgroupSize       = 32
    BuiltInGlobalOffset                = 33
    BuiltInGlobalLinearId              = 34
    BuiltInSubgroupSize                = 36
    BuiltInSubgroupMaxSize             = 37
    BuiltInNumSubgroups                = 38
    BuiltInNumEnqueuedSubgroups        = 39
    BuiltInSubgroupId                  = 40
    BuiltInSubgroupLocalInvocationId   = 41
    BuiltInVertexIndex                 = 42
    BuiltInInstanceIndex               = 43
    BuiltInSubgroupEqMask              = 4416
    BuiltInSubgroupGeMask              = 4417
    BuiltInSubgroupGtMask              = 4418
    BuiltInSubgroupLeMask              = 4419
    BuiltInSubgroupLtMask              = 4420
    BuiltInSubgroupEqMaskKHR           = 4416
    BuiltInSubgroupGeMaskKHR           = 4417
    BuiltInSubgroupGtMaskKHR           = 4418
    BuiltInSubgroupLeMaskKHR           = 4419
    BuiltInSubgroupLtMaskKHR           = 4420
    BuiltInBaseVertex                  = 4424
    BuiltInBaseInstance                = 4425
    BuiltInDrawIndex                   = 4426
    BuiltInPrimitiveShadingRateKHR     = 4432
    BuiltInDeviceIndex                 = 4438
    BuiltInViewIndex                   = 4440
    BuiltInShadingRateKHR              = 4444
    BuiltInBaryCoordNoPerspAMD         = 4992
    BuiltInBaryCoordNoPerspCentroidAMD = 4993
    BuiltInBaryCoordNoPerspSampleAMD   = 4994
    BuiltInBaryCoordSmoothAMD          = 4995
    BuiltInBaryCoordSmoothCentroidAMD  = 4996
    BuiltInBaryCoordSmoothSampleAMD    = 4997
    BuiltInBaryCoordPullModelAMD       = 4998
    BuiltInFragStencilRefEXT           = 5014
    BuiltInViewportMaskNV              = 5253
    BuiltInSecondaryPositionNV         = 5257
    BuiltInSecondaryViewportMaskNV     = 5258
    BuiltInPositionPerViewNV           = 5261
    BuiltInViewportMaskPerViewNV       = 5262
    BuiltInFullyCoveredEXT             = 5264
    BuiltInTaskCountNV                 = 5274
    BuiltInPrimitiveCountNV            = 5275
    BuiltInPrimitiveIndicesNV          = 5276
    BuiltInClipDistancePerViewNV       = 5277
    BuiltInCullDistancePerViewNV       = 5278
    BuiltInLayerPerViewNV              = 5279
    BuiltInMeshViewCountNV             = 5280
    BuiltInMeshViewIndicesNV           = 5281
    BuiltInBaryCoordNV                 = 5286
    BuiltInBaryCoordNoPerspNV          = 5287
    BuiltInFragSizeEXT                 = 5292
    BuiltInFragmentSizeNV              = 5292
    BuiltInFragInvocationCountEXT      = 5293
    BuiltInInvocationsPerPixelNV       = 5293
    BuiltInLaunchIdNV                  = 5319
    BuiltInLaunchIdKHR                 = 5319
    BuiltInLaunchSizeNV                = 5320
    BuiltInLaunchSizeKHR               = 5320
    BuiltInWorldRayOriginNV            = 5321
    BuiltInWorldRayOriginKHR           = 5321
    BuiltInWorldRayDirectionNV         = 5322
    BuiltInWorldRayDirectionKHR        = 5322
    BuiltInObjectRayOriginNV           = 5323
    BuiltInObjectRayOriginKHR          = 5323
    BuiltInObjectRayDirectionNV        = 5324
    BuiltInObjectRayDirectionKHR       = 5324
    BuiltInRayTminNV                   = 5325
    BuiltInRayTminKHR                  = 5325
    BuiltInRayTmaxNV                   = 5326
    BuiltInRayTmaxKHR                  = 5326
    BuiltInInstanceCustomIndexNV       = 5327
    BuiltInInstanceCustomIndexKHR      = 5327
    BuiltInObjectToWorldNV             = 5330
    BuiltInObjectToWorldKHR            = 5330
    BuiltInWorldToObjectNV             = 5331
    BuiltInWorldToObjectKHR            = 5331
    BuiltInHitTNV                      = 5332
    BuiltInHitKindNV                   = 5333
    BuiltInHitKindKHR                  = 5333
    BuiltInIncomingRayFlagsNV          = 5351
    BuiltInIncomingRayFlagsKHR         = 5351
    BuiltInRayGeometryIndexKHR         = 5352
    BuiltInWarpsPerSMNV                = 5374
    BuiltInSMCountNV                   = 5375
    BuiltInWarpIDNV                    = 5376
    BuiltInSMIDNV                      = 5377
end

@cenum Scope::UInt32 begin
    ScopeCrossDevice    = 0
    ScopeDevice         = 1
    ScopeWorkgroup      = 2
    ScopeSubgroup       = 3
    ScopeInvocation     = 4
    ScopeQueueFamily    = 5
    ScopeQueueFamilyKHR = 5
    ScopeShaderCallKHR  = 6
end

@cenum GroupOperation::UInt32 begin
    GroupOperationReduce                     = 0
    GroupOperationInclusiveScan              = 1
    GroupOperationExclusiveScan              = 2
    GroupOperationClusteredReduce            = 3
    GroupOperationPartitionedReduceNV        = 6
    GroupOperationPartitionedInclusiveScanNV = 7
    GroupOperationPartitionedExclusiveScanNV = 8
end

@cenum KernelEnqueueFlags::UInt32 begin
    KernelEnqueueFlagsNoWait        = 0
    KernelEnqueueFlagsWaitKernel    = 1
    KernelEnqueueFlagsWaitWorkGroup = 2
end

@cenum Capability::UInt32 begin
    CapabilityMatrix                                       = 0
    CapabilityShader                                       = 1
    CapabilityGeometry                                     = 2
    CapabilityTessellation                                 = 3
    CapabilityAddresses                                    = 4
    CapabilityLinkage                                      = 5
    CapabilityKernel                                       = 6
    CapabilityVector16                                     = 7
    CapabilityFloat16Buffer                                = 8
    CapabilityFloat16                                      = 9
    CapabilityFloat64                                      = 10
    CapabilityInt64                                        = 11
    CapabilityInt64Atomics                                 = 12
    CapabilityImageBasic                                   = 13
    CapabilityImageReadWrite                               = 14
    CapabilityImageMipmap                                  = 15
    CapabilityPipes                                        = 17
    CapabilityGroups                                       = 18
    CapabilityDeviceEnqueue                                = 19
    CapabilityLiteralSampler                               = 20
    CapabilityAtomicStorage                                = 21
    CapabilityInt16                                        = 22
    CapabilityTessellationPointSize                        = 23
    CapabilityGeometryPointSize                            = 24
    CapabilityImageGatherExtended                          = 25
    CapabilityStorageImageMultisample                      = 27
    CapabilityUniformBufferArrayDynamicIndexing            = 28
    CapabilitySampledImageArrayDynamicIndexing             = 29
    CapabilityStorageBufferArrayDynamicIndexing            = 30
    CapabilityStorageImageArrayDynamicIndexing             = 31
    CapabilityClipDistance                                 = 32
    CapabilityCullDistance                                 = 33
    CapabilityImageCubeArray                               = 34
    CapabilitySampleRateShading                            = 35
    CapabilityImageRect                                    = 36
    CapabilitySampledRect                                  = 37
    CapabilityGenericPointer                               = 38
    CapabilityInt8                                         = 39
    CapabilityInputAttachment                              = 40
    CapabilitySparseResidency                              = 41
    CapabilityMinLod                                       = 42
    CapabilitySampled1D                                    = 43
    CapabilityImage1D                                      = 44
    CapabilitySampledCubeArray                             = 45
    CapabilitySampledBuffer                                = 46
    CapabilityImageBuffer                                  = 47
    CapabilityImageMSArray                                 = 48
    CapabilityStorageImageExtendedFormats                  = 49
    CapabilityImageQuery                                   = 50
    CapabilityDerivativeControl                            = 51
    CapabilityInterpolationFunction                        = 52
    CapabilityTransformFeedback                            = 53
    CapabilityGeometryStreams                              = 54
    CapabilityStorageImageReadWithoutFormat                = 55
    CapabilityStorageImageWriteWithoutFormat               = 56
    CapabilityMultiViewport                                = 57
    CapabilitySubgroupDispatch                             = 58
    CapabilityNamedBarrier                                 = 59
    CapabilityPipeStorage                                  = 60
    CapabilityGroupNonUniform                              = 61
    CapabilityGroupNonUniformVote                          = 62
    CapabilityGroupNonUniformArithmetic                    = 63
    CapabilityGroupNonUniformBallot                        = 64
    CapabilityGroupNonUniformShuffle                       = 65
    CapabilityGroupNonUniformShuffleRelative               = 66
    CapabilityGroupNonUniformClustered                     = 67
    CapabilityGroupNonUniformQuad                          = 68
    CapabilityShaderLayer                                  = 69
    CapabilityShaderViewportIndex                          = 70
    CapabilityFragmentShadingRateKHR                       = 4422
    CapabilitySubgroupBallotKHR                            = 4423
    CapabilityDrawParameters                               = 4427
    CapabilitySubgroupVoteKHR                              = 4431
    CapabilityStorageBuffer16BitAccess                     = 4433
    CapabilityStorageUniformBufferBlock16                  = 4433
    CapabilityUniformAndStorageBuffer16BitAccess           = 4434
    CapabilityStorageUniform16                             = 4434
    CapabilityStoragePushConstant16                        = 4435
    CapabilityStorageInputOutput16                         = 4436
    CapabilityDeviceGroup                                  = 4437
    CapabilityMultiView                                    = 4439
    CapabilityVariablePointersStorageBuffer                = 4441
    CapabilityVariablePointers                             = 4442
    CapabilityAtomicStorageOps                             = 4445
    CapabilitySampleMaskPostDepthCoverage                  = 4447
    CapabilityStorageBuffer8BitAccess                      = 4448
    CapabilityUniformAndStorageBuffer8BitAccess            = 4449
    CapabilityStoragePushConstant8                         = 4450
    CapabilityDenormPreserve                               = 4464
    CapabilityDenormFlushToZero                            = 4465
    CapabilitySignedZeroInfNanPreserve                     = 4466
    CapabilityRoundingModeRTE                              = 4467
    CapabilityRoundingModeRTZ                              = 4468
    CapabilityRayQueryProvisionalKHR                       = 4471
    CapabilityRayQueryKHR                                  = 4472
    CapabilityRayTraversalPrimitiveCullingKHR              = 4478
    CapabilityRayTracingKHR                                = 4479
    CapabilityFloat16ImageAMD                              = 5008
    CapabilityImageGatherBiasLodAMD                        = 5009
    CapabilityFragmentMaskAMD                              = 5010
    CapabilityStencilExportEXT                             = 5013
    CapabilityImageReadWriteLodAMD                         = 5015
    CapabilityInt64ImageEXT                                = 5016
    CapabilityShaderClockKHR                               = 5055
    CapabilitySampleMaskOverrideCoverageNV                 = 5249
    CapabilityGeometryShaderPassthroughNV                  = 5251
    CapabilityShaderViewportIndexLayerEXT                  = 5254
    CapabilityShaderViewportIndexLayerNV                   = 5254
    CapabilityShaderViewportMaskNV                         = 5255
    CapabilityShaderStereoViewNV                           = 5259
    CapabilityPerViewAttributesNV                          = 5260
    CapabilityFragmentFullyCoveredEXT                      = 5265
    CapabilityMeshShadingNV                                = 5266
    CapabilityImageFootprintNV                             = 5282
    CapabilityFragmentBarycentricNV                        = 5284
    CapabilityComputeDerivativeGroupQuadsNV                = 5288
    CapabilityFragmentDensityEXT                           = 5291
    CapabilityShadingRateNV                                = 5291
    CapabilityGroupNonUniformPartitionedNV                 = 5297
    CapabilityShaderNonUniform                             = 5301
    CapabilityShaderNonUniformEXT                          = 5301
    CapabilityRuntimeDescriptorArray                       = 5302
    CapabilityRuntimeDescriptorArrayEXT                    = 5302
    CapabilityInputAttachmentArrayDynamicIndexing          = 5303
    CapabilityInputAttachmentArrayDynamicIndexingEXT       = 5303
    CapabilityUniformTexelBufferArrayDynamicIndexing       = 5304
    CapabilityUniformTexelBufferArrayDynamicIndexingEXT    = 5304
    CapabilityStorageTexelBufferArrayDynamicIndexing       = 5305
    CapabilityStorageTexelBufferArrayDynamicIndexingEXT    = 5305
    CapabilityUniformBufferArrayNonUniformIndexing         = 5306
    CapabilityUniformBufferArrayNonUniformIndexingEXT      = 5306
    CapabilitySampledImageArrayNonUniformIndexing          = 5307
    CapabilitySampledImageArrayNonUniformIndexingEXT       = 5307
    CapabilityStorageBufferArrayNonUniformIndexing         = 5308
    CapabilityStorageBufferArrayNonUniformIndexingEXT      = 5308
    CapabilityStorageImageArrayNonUniformIndexing          = 5309
    CapabilityStorageImageArrayNonUniformIndexingEXT       = 5309
    CapabilityInputAttachmentArrayNonUniformIndexing       = 5310
    CapabilityInputAttachmentArrayNonUniformIndexingEXT    = 5310
    CapabilityUniformTexelBufferArrayNonUniformIndexing    = 5311
    CapabilityUniformTexelBufferArrayNonUniformIndexingEXT = 5311
    CapabilityStorageTexelBufferArrayNonUniformIndexing    = 5312
    CapabilityStorageTexelBufferArrayNonUniformIndexingEXT = 5312
    CapabilityRayTracingNV                                 = 5340
    CapabilityVulkanMemoryModel                            = 5345
    CapabilityVulkanMemoryModelKHR                         = 5345
    CapabilityVulkanMemoryModelDeviceScope                 = 5346
    CapabilityVulkanMemoryModelDeviceScopeKHR              = 5346
    CapabilityPhysicalStorageBufferAddresses               = 5347
    CapabilityPhysicalStorageBufferAddressesEXT            = 5347
    CapabilityComputeDerivativeGroupLinearNV               = 5350
    CapabilityRayTracingProvisionalKHR                     = 5353
    CapabilityCooperativeMatrixNV                          = 5357
    CapabilityFragmentShaderSampleInterlockEXT             = 5363
    CapabilityFragmentShaderShadingRateInterlockEXT        = 5372
    CapabilityShaderSMBuiltinsNV                           = 5373
    CapabilityFragmentShaderPixelInterlockEXT              = 5378
    CapabilityDemoteToHelperInvocationEXT                  = 5379
    CapabilitySubgroupShuffleINTEL                         = 5568
    CapabilitySubgroupBufferBlockIOINTEL                   = 5569
    CapabilitySubgroupImageBlockIOINTEL                    = 5570
    CapabilitySubgroupImageMediaBlockIOINTEL               = 5579
    CapabilityIntegerFunctions2INTEL                       = 5584
    CapabilityFunctionPointersINTEL                        = 5603
    CapabilityIndirectReferencesINTEL                      = 5604
    CapabilitySubgroupAvcMotionEstimationINTEL             = 5696
    CapabilitySubgroupAvcMotionEstimationIntraINTEL        = 5697
    CapabilitySubgroupAvcMotionEstimationChromaINTEL       = 5698
    CapabilityFPGAMemoryAttributesINTEL                    = 5824
    CapabilityUnstructuredLoopControlsINTEL                = 5886
    CapabilityFPGALoopControlsINTEL                        = 5888
    CapabilityKernelAttributesINTEL                        = 5892
    CapabilityFPGAKernelAttributesINTEL                    = 5897
    CapabilityBlockingPipesINTEL                           = 5945
    CapabilityFPGARegINTEL                                 = 5948
    CapabilityAtomicFloat32AddEXT                          = 6033
    CapabilityAtomicFloat64AddEXT                          = 6034
end

@cenum RayQueryIntersection::UInt32 begin
    RayQueryIntersectionRayQueryCandidateIntersectionKHR = 0
    RayQueryIntersectionRayQueryCommittedIntersectionKHR = 1
end

@cenum RayQueryCommittedIntersectionType::UInt32 begin
    RayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionNoneKHR      = 0
    RayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionTriangleKHR  = 1
    RayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionGeneratedKHR = 2
end

@cenum RayQueryCandidateIntersectionType::UInt32 begin
    RayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionTriangleKHR = 0
    RayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionAABBKHR     = 1
end

const extra_operands = Dict(
    ImageOperands => Dict(
        ImageOperandsBias => [(kind = IdRef,)],
        ImageOperandsLod => [(kind = IdRef,)],
        ImageOperandsGrad => [(kind = IdRef,), (kind = IdRef,)],
        ImageOperandsConstOffset => [(kind = IdRef,)],
        ImageOperandsOffset => [(kind = IdRef,)],
        ImageOperandsConstOffsets => [(kind = IdRef,)],
        ImageOperandsSample => [(kind = IdRef,)],
        ImageOperandsMinLod => [(kind = IdRef,)],
        ImageOperandsMakeTexelAvailable => [(kind = IdScope,)],
        ImageOperandsMakeTexelAvailableKHR => [(kind = IdScope,)],
        ImageOperandsMakeTexelVisible => [(kind = IdScope,)],
        ImageOperandsMakeTexelVisibleKHR => [(kind = IdScope,)],
    ),
    LoopControl => Dict(
        LoopControlDependencyLength => [(kind = LiteralInteger,)],
        LoopControlMinIterations => [(kind = LiteralInteger,)],
        LoopControlMaxIterations => [(kind = LiteralInteger,)],
        LoopControlIterationMultiple => [(kind = LiteralInteger,)],
        LoopControlPeelCount => [(kind = LiteralInteger,)],
        LoopControlPartialCount => [(kind = LiteralInteger,)],
        LoopControlInitiationIntervalINTEL => [(kind = LiteralInteger,)],
        LoopControlMaxConcurrencyINTEL => [(kind = LiteralInteger,)],
        LoopControlDependencyArrayINTEL => [(kind = LiteralInteger,)],
        LoopControlPipelineEnableINTEL => [(kind = LiteralInteger,)],
        LoopControlLoopCoalesceINTEL => [(kind = LiteralInteger,)],
        LoopControlMaxInterleavingINTEL => [(kind = LiteralInteger,)],
        LoopControlSpeculatedIterationsINTEL => [(kind = LiteralInteger,)],
    ),
    MemoryAccess => Dict(
        MemoryAccessAligned => [(kind = LiteralInteger,)],
        MemoryAccessMakePointerAvailable => [(kind = IdScope,)],
        MemoryAccessMakePointerAvailableKHR => [(kind = IdScope,)],
        MemoryAccessMakePointerVisible => [(kind = IdScope,)],
        MemoryAccessMakePointerVisibleKHR => [(kind = IdScope,)],
    ),
    ExecutionMode => Dict(
        ExecutionModeInvocations => [(
            kind = LiteralInteger,
            name = "Number of <<Invocation,invocations>>",
        )],
        ExecutionModeLocalSize => [
            (kind = LiteralInteger, name = "x size"),
            (kind = LiteralInteger, name = "y size"),
            (kind = LiteralInteger, name = "z size"),
        ],
        ExecutionModeLocalSizeHint => [
            (kind = LiteralInteger, name = "x size"),
            (kind = LiteralInteger, name = "y size"),
            (kind = LiteralInteger, name = "z size"),
        ],
        ExecutionModeOutputVertices => [(kind = LiteralInteger, name = "Vertex count")],
        ExecutionModeVecTypeHint => [(kind = LiteralInteger, name = "Vector type")],
        ExecutionModeSubgroupSize => [(kind = LiteralInteger, name = "Subgroup Size")],
        ExecutionModeSubgroupsPerWorkgroup =>
            [(kind = LiteralInteger, name = "Subgroups Per Workgroup")],
        ExecutionModeSubgroupsPerWorkgroupId =>
            [(kind = IdRef, name = "Subgroups Per Workgroup")],
        ExecutionModeLocalSizeId => [
            (kind = IdRef, name = "x size"),
            (kind = IdRef, name = "y size"),
            (kind = IdRef, name = "z size"),
        ],
        ExecutionModeLocalSizeHintId => [(kind = IdRef, name = "Local Size Hint")],
        ExecutionModeDenormPreserve => [(kind = LiteralInteger, name = "Target Width")],
        ExecutionModeDenormFlushToZero =>
            [(kind = LiteralInteger, name = "Target Width")],
        ExecutionModeSignedZeroInfNanPreserve =>
            [(kind = LiteralInteger, name = "Target Width")],
        ExecutionModeRoundingModeRTE =>
            [(kind = LiteralInteger, name = "Target Width")],
        ExecutionModeRoundingModeRTZ =>
            [(kind = LiteralInteger, name = "Target Width")],
        ExecutionModeOutputPrimitivesNV =>
            [(kind = LiteralInteger, name = "Primitive count")],
        ExecutionModeMaxWorkgroupSizeINTEL => [
            (kind = LiteralInteger, name = "max_x_size"),
            (kind = LiteralInteger, name = "max_y_size"),
            (kind = LiteralInteger, name = "max_z_size"),
        ],
        ExecutionModeMaxWorkDimINTEL =>
            [(kind = LiteralInteger, name = "max_dimensions")],
        ExecutionModeNumSIMDWorkitemsINTEL =>
            [(kind = LiteralInteger, name = "vector_width")],
    ),
    Decoration => Dict(
        DecorationSpecId =>
            [(kind = LiteralInteger, name = "Specialization Constant ID")],
        DecorationArrayStride => [(kind = LiteralInteger, name = "Array Stride")],
        DecorationMatrixStride => [(kind = LiteralInteger, name = "Matrix Stride")],
        DecorationBuiltIn => [(kind = BuiltIn,)],
        DecorationUniformId => [(kind = IdScope, name = "Execution")],
        DecorationStream => [(kind = LiteralInteger, name = "Stream Number")],
        DecorationLocation => [(kind = LiteralInteger, name = "Location")],
        DecorationComponent => [(kind = LiteralInteger, name = "Component")],
        DecorationIndex => [(kind = LiteralInteger, name = "Index")],
        DecorationBinding => [(kind = LiteralInteger, name = "Binding Point")],
        DecorationDescriptorSet => [(kind = LiteralInteger, name = "Descriptor Set")],
        DecorationOffset => [(kind = LiteralInteger, name = "Byte Offset")],
        DecorationXfbBuffer => [(kind = LiteralInteger, name = "XFB Buffer Number")],
        DecorationXfbStride => [(kind = LiteralInteger, name = "XFB Stride")],
        DecorationFuncParamAttr => [(
            kind = FunctionParameterAttribute,
            name = "Function Parameter Attribute",
        )],
        DecorationFPRoundingMode =>
            [(kind = FPRoundingMode, name = "Floating-Point Rounding Mode")],
        DecorationFPFastMathMode => [(kind = FPFastMathMode, name = "Fast-Math Mode")],
        DecorationLinkageAttributes => [
            (kind = LiteralString, name = "Name"),
            (kind = LinkageType, name = "Linkage Type"),
        ],
        DecorationInputAttachmentIndex =>
            [(kind = LiteralInteger, name = "Attachment Index")],
        DecorationAlignment => [(kind = LiteralInteger, name = "Alignment")],
        DecorationMaxByteOffset => [(kind = LiteralInteger, name = "Max Byte Offset")],
        DecorationAlignmentId => [(kind = IdRef, name = "Alignment")],
        DecorationMaxByteOffsetId => [(kind = IdRef, name = "Max Byte Offset")],
        DecorationSecondaryViewportRelativeNV =>
            [(kind = LiteralInteger, name = "Offset")],
        DecorationCounterBuffer => [(kind = IdRef, name = "Counter Buffer")],
        DecorationHlslCounterBufferGOOGLE => [(kind = IdRef, name = "Counter Buffer")],
        DecorationUserSemantic => [(kind = LiteralString, name = "Semantic")],
        DecorationHlslSemanticGOOGLE => [(kind = LiteralString, name = "Semantic")],
        DecorationUserTypeGOOGLE => [(kind = LiteralString, name = "User Type")],
        DecorationMemoryINTEL => [(kind = LiteralString, name = "Memory Type")],
        DecorationNumbanksINTEL => [(kind = LiteralInteger, name = "Banks")],
        DecorationBankwidthINTEL => [(kind = LiteralInteger, name = "Bank Width")],
        DecorationMaxPrivateCopiesINTEL =>
            [(kind = LiteralInteger, name = "Maximum Copies")],
        DecorationMaxReplicatesINTEL =>
            [(kind = LiteralInteger, name = "Maximum Replicates")],
        DecorationMergeINTEL => [
            (kind = LiteralString, name = "Merge Key"),
            (kind = LiteralString, name = "Merge Type"),
        ],
        DecorationBankBitsINTEL =>
            [(kind = LiteralInteger, quantifier = "*", name = "Bank Bits")],
        DecorationForcePow2DepthINTEL => [(kind = LiteralInteger, name = "Force Key")],
    ),
)


text:
# ---
# title: 1286. Iterator for Combination
# id: problem1286
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Backtracking, Design
# link: <https://leetcode.com/problems/iterator-for-combination/description/>
# hidden: true
# ---
#
# Design the `CombinationIterator` class:
#
#   * `CombinationIterator(string characters, int combinationLength)` Initializes the object with a string `characters` of **sorted distinct** lowercase English letters and a number `combinationLength` as arguments.
#   * `next()` Returns the next combination of length `combinationLength` in **lexicographical order**.
#   * `hasNext()` Returns `true` if and only if there exists a next combination.
#
#
#
# **Example 1:**
#
#
#
#     **Input**
#     ["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
#     [["abc", 2], [], [], [], [], [], []]
#     **Output**
#     [null, "ab", true, "ac", true, "bc", false]
#
#     **Explanation**
#     CombinationIterator itr = new CombinationIterator("abc", 2);
#     itr.next();    // return "ab"
#     itr.hasNext(); // return True
#     itr.next();    // return "ac"
#     itr.hasNext(); // return True
#     itr.next();    // return "bc"
#     itr.hasNext(); // return False
#
#
#
#
# **Constraints:**
#
#   * `1 <= combinationLength <= characters.length <= 15`
#   * All the characters of `characters` are **unique**.
#   * At most `104` calls will be made to `next` and `hasNext`.
#   * It's guaranteed that all calls of the function `next` are valid.
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end

ext: jl


text:
module ArcadeLearningEnvironment

include("aleinterface.jl")
include("game.jl")

end


text:
import Base.Test: @test
using RNG.Random123

stdout_ = STDOUT
pwd_ = pwd()
cd(joinpath(Pkg.dir("RNG"), "test/Random123"))
mkpath("./actual")

for (rng_name, stype, seed, args) in (
    (:Threefry2x, UInt32, (123, 321), (32,)),
    (:Threefry2x, UInt64, (123, 321), (32,)),
    (:Threefry4x, UInt32, (123, 321, 456, 654), (72,)),
    (:Threefry4x, UInt64, (123, 321, 456, 654), (72,)),
    (:Philox2x, UInt32, 123, (16,)),
    (:Philox2x, UInt64, 123, (16,)),
    (:Philox4x, UInt32, (123, 321), (16,)),
    (:Philox4x, UInt64, (123, 321), (16,))
)
    outfile = open(string(
        "./actual/check-$(string(lowercase("$rng_name"), sizeof(stype)<<3)).out"
    ), "w")
    redirect_stdout(outfile)

    @eval $rng_name($stype)
    x = @eval $rng_name($stype, $seed, $(args...))

    x.p = 1
    rand(x, UInt64)
    x.p = 1
    rand(x, UInt128)
    @eval rand(x, NTuple{$(string(rng_name)[end-1]-'0'), $stype})

    set_counter!(x, 0)
    for i in 1:100
        @printf "%.9f\n" rand(x)
    end

    close(outfile)
end
redirect_stdout(stdout_)

@test success(`diff -ru expected actual`)
cd(pwd_)

include("aesni.jl")
include("ars.jl")


text:
function OrphanFrame(arg0::JString)
    return OrphanFrame((JString,), arg0)
end

function add_child(obj::OrphanFrame, arg0::OrphanFrame, arg1::Transform, arg2::jboolean)
    return jcall(obj, "addChild", void, (OrphanFrame, Transform, jboolean), arg0, arg1, arg2)
end

function add_child(obj::OrphanFrame, arg0::OrphanFrame, arg1::TransformProvider, arg2::jboolean)
    return jcall(obj, "addChild", void, (OrphanFrame, TransformProvider, jboolean), arg0, arg1, arg2)
end

function attach_to(obj::OrphanFrame, arg0::Frame, arg1::Transform, arg2::jboolean)
    return jcall(obj, "attachTo", void, (Frame, Transform, jboolean), arg0, arg1, arg2)
end

function attach_to(obj::OrphanFrame, arg0::Frame, arg1::TransformProvider, arg2::jboolean)
    return jcall(obj, "attachTo", void, (Frame, TransformProvider, jboolean), arg0, arg1, arg2)
end

function get_children(obj::OrphanFrame)
    return jcall(obj, "getChildren", List, ())
end

function get_frame(obj::OrphanFrame)
    return jcall(obj, "getFrame", Frame, ())
end

function to_string(obj::OrphanFrame)
    return jcall(obj, "toString", JString, ())
end


text:
using IterTools, ProgressBars
using JLD
using LaTeXStrings, PyPlot

include("synthetic.jl")
qrng_names = vcat(collect(keys(qrngs)), ["RR", "SO"])

RUNS    = 1
EPOCHS  = 1000
T       = n * EPOCHS

SEED    = 42
Random.seed!(SEED)

function gen_syn_data_all()
    # generate the training set consisting of n examples
    # sampled iid uniformly from the underlying distribution,
    # and the same training set will be used for all runs,
    gaussian_samples = gen_syn_data(n, "IID Uniform", d+1, SEED)
    return gaussian_samples
end

println("generating data...")
samples_offline = gen_syn_data_all()

# compute wopt, which is different from wgen since the objective is a finite sum
# so wopt should be the solution to the lstsq problem

X = hcat([pair[1] for pair in samples_offline]...)'
y = [pair[2] for pair in samples_offline]

wopt = (X'X)\(X'y)

println("begin training...")
result = Dict()

for qrng_name in qrng_names
    subopt_list = zeros(RUNS, T)

    for run in 1:RUNS
        # for offline mode we first need to determine sample ordering of the training set
        if qrng_name in collect(keys(qrngs))
            distrib = qrngs[qrng_name]
            # generate QMC indices
            sample_indices = [Int(ceil(i)) for i in QuasiMonteCarlo.sample(T, 0, n, distrib)]
        else
            if qrng_name == "SO"
                Random.seed!(SEED + run)
                perm = randperm!(collect(1:n))
                sample_indices = repeat(perm, EPOCHS)

            elseif qrng_name == "RR"
                sample_indices = zeros(Int64, T)
                for epoch in 1:EPOCHS
                    Random.seed!(SEED + run + epoch)
                    perm = randperm!(collect(1:n))
                    sample_indices[(epoch-1)*n+1 : epoch*n] = perm
                end
            else
                ArgumentError("SGD variant does not exist.")
            end
        end

        # run sgd for offline mode
        subopt_list[run, :] = sgd(T, w0, wopt, samples_offline, sample_indices)
    end
    result[qrng_name] = subopt_list
end

println("training completed")
println("plotting...")

# final plotting
figure(figsize = (6,6))
colors = ["#1f77bf", "#ff7f0e", "#17becf", "#7f7f7f"]
for (q, qrng_name) in enumerate(["IID Uniform", "Sobol", "RR", "SO"])
    subopt_list = result[qrng_name]
    subopt_mean = mean(subopt_list, dims=1)

    # use moving average to smooth out the curves as RR and SO are highly oscillatory
    # towards the end
    using RollingFunctions
    ws = 2000
    subopt_mean = runmean(reshape(subopt_mean, T), ws)

    loglog(collect(100:100:T), subopt_mean[100:100:T], label=qrng_name, color=colors[q])
end

legend(loc="lower left", fontsize=18)

xlabel(string("iterations ", L"t"), fontsize=20)
ylabel(L"\Vert w_t-w^*_n\Vert^2", fontsize=20)
title("Offline", fontsize=24)
xticks(fontsize=20)
yticks(fontsize=20)

ax = gca()
locmin = matplotlib.ticker.LogLocator(base=10.0, subs=(0.25,0.5,0.75), numticks=50)
ax.yaxis.set_minor_locator(locmin)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

tight_layout()
plot_fn = joinpath(pwd(),"figs", "qmc-offline.pdf")
savefig(plot_fn)
println("plot saved at $plot_fn")

max_stars_repo_name: EugeneLYC/qmc-ordering

max_issues_repo_name: EugeneLYC/qmc-ordering

max_forks_repo_name: EugeneLYC/qmc-ordering


text:
module DLSMethod

using LinearAlgebra

export dls_fit!, dls_fit

function fit!(
        X::Matrix{Float64}, y::Vector{Float64}, n::Int64, a::Vector{Float64})
    a[:] = view(X, 1:n, :) \ view(y, 1:n)
    return nothing
end

function arrange_layer!(
        X::Matrix{Float64}, y::Vector{Float64}, a::Vector{Float64},
        n_current::Int64, width::Float64, removal_parameter::Float64)::Int64
    remove_distance = removal_parameter * width
    while true
        n_init = n_current
        i = 1
        while i <= n_current
            y_pred = dot(view(X, i, :), a)
            if abs(y[i] - y_pred) >= remove_distance
                y_pred = dot(view(X, n_current, :), a)
                if abs(y[n_current] - y_pred) < remove_distance
                    # swap
                    X[i, :], X[n_current, :] = X[n_current, :], X[i, :]
                    y[i], y[n_current] = y[n_current], y[i]
                end
                n_current -= 1
            else
                i += 1
            end
        end
        if (n_current == n_init) || (n_current <= length(a) + 3)
            break
        end
        fit!(X, y, n_current, a)
    end
    return n_current
end

function dls_fit!(
        X::Matrix{Float64}, y::Vector{Float64},
        k::Int64, removal_parameter::Float64)::Tuple{Int64, Vector{Float64}}
    n, m = size(X)
    subset_n, subset_dls = Int64[], Float64[]
    a = Vector{Float64}(undef, m)
    fit!(X, y, n, a)

    while n > m + 3
        d = abs.(view(y, 1:n) - view(X, 1:n, :) * a)
        width = maximum(d)
        dls = sum(d .^ 2) / width .^ k

        push!(subset_n, n)
        push!(subset_dls, dls)

        n = arrange_layer!(X, y, a, n, width, removal_parameter)
    end

    n_best = subset_n[argmax(subset_dls)]
    fit!(X, y, n_best, a)
    return n_best, a
end

function dls_fit(
        X::Matrix{Float64}, y::Vector{Float64},
        k::Int64, removal_parameter::Float64)::Tuple{Int64, Vector{Float64}}
    dls_fit!(copy(X), copy(y), k, removal_parameter)
end

end # module


text:
#########################
@info "starting 3D3V model"
TD = 15000 # eV
TT = 15000 # eV
Te = 13000 # eV

e = species.e
T = species.T
D = species.D

De = Distribution(Maxwellian(Te, e.m), e)
DT = Distribution(Maxwellian(TT, T.m), T)
DD = Distribution(Maxwellian(TD, D.m), D)
G = Geometry()

plasma = CollisionlessPlasma([De,DT,DD], G)

sol = Plasma.solve(plasma, GPU=false)

@save "3d3v.bson" sol

Plasma.plot(sol)

#########################
@info "starting 3D3V electrostatic model"
TD = 70000 # eV

D = species.D

DD = Distribution(HotCarrier(TD), D)
G = Geometry()

plasma = ElectrostaticPlasma([DD], G)

sol = Plasma.solve(plasma; GPU=false, time_ub=10.0)

@save "3d3v_electrostatic.bson" sol

Plasma.plot(sol)


text:
"""
Qu, H., Zhao, J., Zhao, J. and Jiang, D., 2019, June.
Towards support vector data description based on heuristic sample condensed rule.
In 2019 Chinese Control And Decision Conference (CCDC) (pp. 4647-4653). IEEE.

Heuristic Sample Condensed (HSC)
Parameter:
k for kNN search: no recommendation
n_grid: number of parameters to test for each threshold during grid search

We use a PWC to split the data set into inlier/outlier to
allow tuning the disT and denT parameters from the paper.
"""
mutable struct HSC <: Sampler
    k::Int
    n_grid::Int
    threshold_strat::ThresholdStrategy
    threshold::Union{Real, Nothing}
    kde_cache::Union{KDECache, Nothing}
    gamma::Union{Symbol, Real}
    init_strategy::SVDD.InitializationStrategy
    solver::OptimizerFactory
    function HSC(k::Int, n_grid::Int,
                 threshold_strat::ThresholdStrategy, kde_cache::Union{KDECache, Nothing}, gamma::Union{Symbol, Real},
                 init_strategy::SVDD.InitializationStrategy, solver::OptimizerFactory)
        k > 0 || throw(ArgumentError("Non-positive number of nearest neighbors to consider $(k)."))
        n_grid > 0 || throw(ArgumentError("Non-positive number of grid parameter to test per threshold $(n_grid)."))
        return new(k, n_grid, threshold_strat, nothing, kde_cache, gamma, init_strategy, solver)
    end
end

function HSC(k::Int, n_grid::Int,
             threshold_strat::ThresholdStrategy, kde_cache::KDECache,
             init_strategy::SVDD.InitializationStrategy, solver::OptimizerFactory)
    return HSC(k, n_grid, threshold_strat, kde_cache, :precomputed, init_strategy, solver)
end

function HSC(k::Int, n_grid::Int,
             threshold_strat::ThresholdStrategy, gamma::Union{Symbol, Real},
             init_strategy::SVDD.InitializationStrategy, solver::OptimizerFactory)
    return HSC(k, n_grid, threshold_strat, nothing, gamma, init_strategy, solver)
end

function calculate_hsc_values(sampler, data)
    n = size(data, 2)
    sampler.k = min(n - 1, sampler.k)
    tree = KDTree(data)
    p_i = zeros(n)
    indices, distances = knn(tree, data, sampler.k + 1, true)
    p_i = [exp(-mean(distances[i][2:end])) for i in 1:n]
    d_ij = Distances.pairwise(Distances.Euclidean(), data, dims=2)
    δ_i = zeros(n)
    for i in 1:n
        dist_to_high_dens = [d_ij[i, j] for j in 1:n if p_i[j] > p_i[i]]
        δ_i[i] = isempty(dist_to_high_dens) ? maximum(d_ij[i, :]) : minimum(dist_to_high_dens)
    end
    return δ_i, p_i
end

function hsc_mask(δ_i, p_i, disT, denT)
    mask = falses(length(p_i))
    mask[(δ_i .<= disT) .& (p_i .<= denT)] .= true
    return mask
end

function sample(sampler::HSC, data::DataSet, labels::Vector{Symbol})::BitArray{1}
    δ_i, p_i = calculate_hsc_values(sampler, data)

    # Split data set to allow disT and denT tuning
    if sampler.kde_cache === nothing || sampler.kde_cache.data != data
        sampler.kde_cache = KDECache(data, sampler.gamma)
    end
    pwc = PWC(sampler.kde_cache, sampler.threshold_strat)
    calculate_threshold!(pwc, labels)
    pwc_ground_truth = predict(pwc, data)

    # Tune disT and denT
    best_s = -Inf
    best_mask = falses(size(data, 2))
    for disT in range(extrema(δ_i)..., length=sampler.n_grid)
        for denT in range(extrema(p_i)..., length=sampler.n_grid)
            sample_mask = hsc_mask(δ_i, p_i, disT, denT)
            if !any(sample_mask)
                continue
            end
            model = SVDD.VanillaSVDD(data)
            SVDD.initialize!(model, sampler.init_strategy)
            SVDD.set_adjust_K!(model, true)
            SVDD.set_data!(model, data[:, sample_mask])
            try
                SVDD.fit!(model, sampler.solver)
            catch e
                debug(LOGGER, "[HSC] Failed fitting model on data set of size $(size(model.data)) due to $e.")
                continue
            end
            pred = SVDD.predict(model, data)
            s = mcc(pred, pwc_ground_truth)
            if s > best_s
                best_s = s
                best_mask = copy(sample_mask)
            end
        end
    end
    if best_s == -Inf
        throw(SamplingException("[HSC] Failed fitting any model."))
    end
    return best_mask
end


text:
# Test basic API

const rankstr = @sprintf "%06d" comm_rank

if comm_rank == comm_root
    const dirname = Filesystem.mktempdir(; cleanup=true)
end
if use_mpi
    if comm_rank == comm_root
        MPI.bcast(dirname, comm_root, comm)
    else
        const dirname = MPI.bcast(nothing, comm_root, comm)
    end
end
const filename = "$dirname/test.bp"

@testset "File write tests" begin
    # Set up ADIOS
    if use_mpi
        adios = adios_init_mpi(comm)
    else
        adios = adios_init_serial()
    end
    @test adios isa Adios
    @test match(r"Adios\(.+\)", string(adios)) ≢ nothing
    @test match(r"Adios\(0x[0-9a-f]+\)", showmime(adios)) ≢ nothing

    io = declare_io(adios, "IO")
    @test io isa AIO
    @test match(r"AIO\(.+\)", string(io)) ≢ nothing
    @test match(r"AIO\(0x[0-9a-f]+\)", showmime(io)) ≢ nothing

    # Define some variables
    variables = Dict()
    for T in
        Type[String, Float32, Float64, Complex{Float32}, Complex{Float64}, Int8,
             Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64]
        val = T ≡ String ? "42" : T(42)
        val::T

        # Global value
        nm = "gvalue.p$rankstr.$T"
        gval = define_variable(io, nm, T)
        @test gval isa Variable
        @test match(r"Variable\(name=.+,type=.+,shapeid=.+,shape=.+\)",
                    string(gval)) ≢ nothing
        @test match(r"Variable\(.+\)", showmime(gval)) ≢ nothing
        variables[(shapeid_global_value, -1, -1, T)] = (nm, gval)

        # Local value
        nm = "lvalue.p$rankstr.$T"
        lval = define_variable(io, nm, val)
        @test lval isa Variable
        @test match(r"Variable\(name=.+,type=.+,shapeid=.+,shape=.+\)",
                    string(lval)) ≢ nothing
        @test match(r"Variable\(.+\)", showmime(lval)) ≢ nothing
        variables[(shapeid_local_value, -1, -1, T)] = (nm, lval)

        # String arrays are not supported
        if T ≢ String
            for D in 1:3, len in 0:2
                # size
                sz = ntuple(d -> len == 0 ? 0 : len == 1 ? 1 : d, D)
                arr = fill(val, sz)

                # shape, start, count of global array
                cs = ntuple(d -> d < D ? 1 : comm_size, D)
                cr = ntuple(d -> d < D ? 0 : comm_rank, D)
                sh = cs .* sz
                st = cr .* sz
                co = sz

                # Global array
                nm = "garray.$T.$D.$len"
                garr = define_variable(io, nm, T, sh, st, co)
                @test garr isa Variable
                @test match(r"Variable\(name=.+,type=.+,shapeid=.+,shape=.+\)",
                            string(garr)) ≢ nothing
                @test match(r"Variable\(.+\)", showmime(garr)) ≢ nothing
                variables[(shapeid_global_array, D, len, T)] = (nm, garr)

                # Local array
                nm = "larray.p$rankstr.$T.$D.$len"
                larr = define_variable(io, nm, arr)
                @test larr isa Variable
                @test match(r"Variable\(name=.+,type=.+,shapeid=.+,shape=.+\)",
                            string(larr)) ≢ nothing
                @test match(r"Variable\(.+\)", showmime(larr)) ≢ nothing
                variables[(shapeid_local_array, D, len, T)] = (nm, larr)
            end
        end
    end

    # Check variables
    allvars = inquire_all_variables(io)
    @test Set(allvars) == Set([var for (name, var) in values(variables)])

    var0 = inquire_variable(io, "not a variable")
    @test var0 isa Nothing

    for ((si, D, len, T), (nm, var)) in variables
        var1 = inquire_variable(io, nm)
        @test var1 isa Variable
        @test nm == name(var1)
        @test type(var1) == T
        @test shapeid(var1) == si
        if si == shapeid_global_value
            @test ndims(var1) == 0
            @test shape(var1) == ()
            @test start(var1) == ()
            @test count(var1) == ()
        elseif si == shapeid_local_value
            @test ndims(var1) == 0
            @test shape(var1) ≡ nothing
            @test start(var1) ≡ nothing
            @test count(var1) ≡ ()
        elseif si == shapeid_global_array
            sz = ntuple(d -> len == 0 ? 0 : len == 1 ? 1 : d, D)
            cs = ntuple(d -> d < D ? 1 : comm_size, D)
            cr = ntuple(d -> d < D ? 0 : comm_rank, D)
            sh = cs .* sz
            st = cr .* sz
            co = sz
            @test ndims(var1) == D
            @test shape(var1) == sh
            @test start(var1) == st
            @test count(var1) == co
        elseif si == shapeid_local_array
            sz = ntuple(d -> len == 0 ? 0 : len == 1 ? 1 : d, D)
            @test ndims(var1) == D
            @test shape(var1) ≡ nothing
            @test start(var1) ≡ nothing
            @test count(var1) == sz
        else
            error("internal error")
        end
    end

    # Define some attributes
    attributes = Dict()
    for T in Type[String, Float32, Float64,
             # Currently broken, see
             # <https://github.com/ornladios/ADIOS2/issues/2734>
             # Complex{Float32}, Complex{Float64},
             Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64]
        val = T ≡ String ? "42" : T(42)
        val::T

        # Attribute
        nm = "value.p$rankstr.$T"
        attr = define_attribute(io, nm, val)
        @test attr isa Attribute
        @test match(r"Attribute\(name=.+,type=.+,is_value=(false|true),size=.+,data=.+\)",
                    string(attr)) ≢ nothing
        @test match(r"Attribute\(.+\)", showmime(attr)) ≢ nothing
        attributes[(-1, -1, "", T)] = (nm, attr)

        # Variable attribute
        nm = "value.p$rankstr.$T"
        varname = variables[(shapeid_global_value, -1, -1, T)][1]
        attr = define_variable_attribute(io, nm, val, varname)
        @test attr isa Attribute
        @test match(r"Attribute\(name=.+,type=.+,is_value=(false|true),size=.+,data=.+\)",
                    string(attr)) ≢ nothing
        @test match(r"Attribute\(.+\)", showmime(attr)) ≢ nothing
        attributes[(-1, -1, varname, T)] = ("$varname/$nm", attr)

        # Attribute arrays need to have at least one element (why?)
        for len in 1:2:3
            vals = (T ≡ String ? String["42", "", "44"] : T[42, 0, 44])[1:len]

            # Attribute array
            nm = "array.p$rankstr.$T.$len"
            arr = define_attribute_array(io, nm, vals)
            @test arr isa Attribute
            @test match(r"Attribute\(name=.+,type=.+,is_value=(false|true),size=.+,data=.+\)",
                        string(arr)) ≢ nothing
            @test match(r"Attribute\(.+\)", showmime(arr)) ≢ nothing
            attributes[(1, len, "", T)] = (nm, arr)

            # Variable attribute array
            nm = "array.p$rankstr.$T.$len"
            varname = variables[(shapeid_global_value, -1, -1, T)][1]
            arr = define_variable_attribute_array(io, nm, vals, varname)
            @test match(r"Attribute\(name=.+,type=.+,is_value=(false|true),size=.+,data=.+\)",
                        string(arr)) ≢ nothing
            @test match(r"Attribute\(.+\)", showmime(arr)) ≢ nothing
            @test arr isa Attribute
            attributes[(1, len, varname, T)] = ("$varname/$nm", arr)
        end
    end

    # Check attributes
    allattrs = inquire_all_attributes(io)
    @test Set(allattrs) == Set([attr for (name, attr) in values(attributes)])

    attr0 = inquire_attribute(io, "not an attribute")
    @test attr0 isa Nothing
    attr0 = inquire_variable_attribute(io, "not an attribute", "not a variable")
    @test attr0 isa Nothing

    for ((D, len, varname, T), (nm, attr)) in attributes
        attr1 = inquire_attribute(io, nm)
        @test attr1 isa Attribute
        @test nm == name(attr1)
        @test type(attr1) == T
        if D == -1
            @test is_value(attr)
            @test size(attr) == 1
            val = T ≡ String ? "42" : T(42)
            @test data(attr) == val
        else
            @test !is_value(attr)
            @test size(attr) == len
            vals = (T ≡ String ? String["42", "", "44"] : T[42, 0, 44])[1:len]
            @test data(attr) == vals
        end
    end

    etype = engine_type(io)
    @test etype == "File"

    # Write the file
    engine = open(io, filename, mode_write)

    # Schedule variables for writing
    for ((si, D, len, T), (nm, var)) in variables
        val = T ≡ String ? "42" : T(42)
        if si ∈ (shapeid_global_value, shapeid_local_value)
            err = put!(engine, var, val)
            @test err ≡ error_none
        elseif si ∈ (shapeid_global_array, shapeid_local_array)
            sz = ntuple(d -> len == 0 ? 0 : len == 1 ? 1 : d, D)
            # Construct a single number from a tuple
            ten(i, s) = i == () ? s : ten(i[2:end], 10s + i[1])
            # Convert to type `T`
            function mkT(T, s)
                return (T ≡ String ? "$s" :
                        T <: Union{AbstractFloat,Complex} ? T(s) : s % T)::T
            end
            arr = T[mkT(T, ten(Tuple(i), 0)) for i in CartesianIndices(sz)]
            err = put!(engine, var, arr)
            @test err ≡ error_none
        else
            error("internal error")
        end
    end

    # Write the variables
    err = perform_puts!(engine)
    @test err ≡ error_none

    # Minima and maxima are only available when reading a file
    # for ((si, D, T), (nm, var)) in variables
    #     val = T ≡ String ? "42" : T(42)
    #     @test minimum(var) == val
    #     @test maximum(var) == val
    # end

    err = close(engine)
    @test err ≡ error_none

    finalize(adios)
end

# Call gc to test finalizing the Adios object
GC.gc(true)

# run(`/Users/eschnett/src/CarpetX/Cactus/view/bin/bpls -aD $filename`)

@testset "File read tests" begin
    # Set up ADIOS
    if use_mpi
        adios = adios_init_mpi(comm)
    else
        adios = adios_init_serial()
    end
    @test adios isa Adios

    io = declare_io(adios, "IO")
    @test io isa AIO

    # Open the file
    engine = open(io, filename, mode_read)

    # Inquire about all variables
    variables = Dict()
    for T in
        Type[String, Float32, Float64, Complex{Float32}, Complex{Float64}, Int8,
             Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64]
        # Global value
        nm = "gvalue.p$rankstr.$T"
        gval = inquire_variable(io, nm)
        @test gval isa Variable
        variables[(shapeid_global_value, -1, -1, T)] = (nm, gval)

        # Local value
        nm = "lvalue.p$rankstr.$T"
        lval = inquire_variable(io, nm)
        @test lval isa Variable
        variables[(shapeid_local_value, -1, -1, T)] = (nm, lval)

        # String arrays are not supported
        if T ≢ String
            for D in 1:3, len in 0:2
                # Global array
                nm = "garray.$T.$D.$len"
                garr = inquire_variable(io, nm)
                @test garr isa Variable
                variables[(shapeid_global_array, D, len, T)] = (nm, garr)

                # Local array
                nm = "larray.p$rankstr.$T.$D.$len"
                larr = inquire_variable(io, nm)
                @test larr isa Variable
                variables[(shapeid_local_array, D, len, T)] = (nm, larr)
            end
        end
    end

    # Check variables
    allvars = inquire_all_variables(io)
    if comm_size == 1
        @test Set(allvars) == Set([var for (name, var) in values(variables)])
    else
        @test Set(allvars) ⊇ Set([var for (name, var) in values(variables)])
    end

    var0 = inquire_variable(io, "not a variable")
    @test var0 isa Nothing

    for ((si, D, len, T), (nm, var)) in variables
        var1 = inquire_variable(io, nm)
        @test var1 isa Variable
        @test nm == name(var1)
        @test type(var1) == T
        if si == shapeid_global_value
            # Global values are re-interpreted as global arrays
            @test shapeid(var1) == si
            @test ndims(var1) == 0
            @test shape(var1) == ()
            @test start(var1) == ()
            @test count(var1) == ()
        elseif si == shapeid_local_value
            # Local values are re-interpreted as global arrays
            @test shapeid(var1) == shapeid_global_array
            @test ndims(var1) == 1
            @test shape(var1) == (1,)
            @test start(var1) == (0,)
            @test count(var1) == (1,)
        elseif si == shapeid_global_array
            sz = ntuple(d -> len == 0 ? 0 : len == 1 ? 1 : d, D)
            cs = ntuple(d -> d < D ? 1 : comm_size, D)
            cr = ntuple(d -> d < D ? 0 : comm_rank, D)
            sh = cs .* sz
            st = cr .* sz
            co = sz
            # Empty global arrays are mis-interpreted as global values
            if len == 0
                @test shapeid(var1) == shapeid_global_value
                @test ndims(var1) == 0
                @test shape(var1) == ()
                @test start(var1) == ()
                @test count(var1) == ()
            else
                @test shapeid(var1) == si
                @test ndims(var1) == D
                @test shape(var1) == sh
                if comm_size == 1
                    # With multiple processes, there are multiple
                    # blocks, and they each have a different starting
                    # offset
                    @test start(var1) == st
                    @test count(var1) == co
                else
                    @test_broken false
                end
                #TODO "need to select block to access variable"
            end
        elseif si == shapeid_local_array
            sz = ntuple(d -> len == 0 ? 0 : len == 1 ? 1 : d, D)
            # Empty local arrays are mis-interpreted as global values
            if len == 0
                @test shapeid(var1) == shapeid_global_value
                @test ndims(var1) == 0
                @test shape(var1) == ()
                @test start(var1) == ()
                @test count(var1) == ()
            else
                @test shapeid(var1) == si
                @test ndims(var1) == D
                @test shape(var1) ≡ nothing
                @test start(var1) ≡ nothing
                @test count(var1) == sz
            end
        else
            error("internal error")
        end
    end

    # Read attributes
    attributes = Dict()
    for T in
        Type[String, Float32, Float64, Complex{Float32}, Complex{Float64}, Int8,
             Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64]
        # Complex attributes cannot be read via the C API (see
        # <https://github.com/ornladios/ADIOS2/issues/2734>)
        T <: Complex && continue

        # Attribute
        nm = "value.p$rankstr.$T"
        attr = inquire_attribute(io, nm)
        @test attr isa Attribute
        attributes[(-1, -1, "", T)] = (nm, attr)

        # Variable attribute
        nm = "value.p$rankstr.$T"
        varname = variables[(shapeid_global_value, -1, -1, T)][1]
        attr = inquire_variable_attribute(io, nm, varname)
        @test attr isa Attribute
        attributes[(-1, -1, varname, T)] = (nm, attr)

        # Attribute arrays need to have at least one element (why?)
        for len in 1:2:3
            # Attribute array
            nm = "array.p$rankstr.$T.$len"
            arr = inquire_attribute(io, nm)
            @test arr isa Attribute
            attributes[(1, len, "", T)] = (nm, arr)

            # Variable attribute array
            nm = "array.p$rankstr.$T.$len"
            varname = variables[(shapeid_global_value, -1, -1, T)][1]
            arr = inquire_variable_attribute(io, nm, varname)
            @test arr isa Attribute
            attributes[(1, len, varname, T)] = (nm, arr)
        end
    end

    # Check attributes
    allattrs = inquire_all_attributes(io)
    if comm_size == 1
        @test Set(allattrs) ==
              Set([attr for (name, attr) in values(attributes)])
    else
        @test Set(allattrs) ⊇ Set([attr for (name, attr) in values(attributes)])
    end

    attr0 = inquire_attribute(io, "not an attribute")
    @test attr0 isa Nothing
    attr0 = inquire_variable_attribute(io, "not an attribute", "not a variable")
    @test attr0 isa Nothing

    for ((D, len, varname, T), (nm, attr)) in attributes
        val = T ≡ String ? "42" : T(42)
        val::T

        attr1 = inquire_attribute(io, nm)
        @test attr1 isa Attribute
        @test nm == name(attr1)
        @test type(attr1) == T
        if D == -1
            @test is_value(attr)
            @test size(attr) == 1
            @test data(attr) == val
        else
            # Length-1 non-string attribute arrays are mis-interpreted as values
            if T ≢ String && len == 1
                @test is_value(attr)
                @test size(attr) == len
                vals = (T ≡ String ? String["42", "", "44"] : T[42, 0, 44])[1:len]
                @test [data(attr)] == vals
            else
                @test !is_value(attr)
                @test size(attr) == len
                vals = (T ≡ String ? String["42", "", "44"] : T[42, 0, 44])[1:len]
                @test data(attr) == vals
            end
        end
    end

    # Schedule variables for reading
    buffers = Dict()
    for ((si, D, len, T), (nm, var)) in variables
        if si ∈ (shapeid_global_value, shapeid_local_value)
            ref = T ≡ String ? Ref{Vector{Cchar}}() : Ref{T}()
            err = get(engine, var, ref)
            @test err ≡ error_none
            buffers[(si, D, len, T)] = ref
        elseif si ∈ (shapeid_global_array, shapeid_local_array)
            co = count(var)
            arr = Array{T}(undef, Tuple(co))
            err = get(engine, var, arr)
            @test err ≡ error_none
            buffers[(si, D, len, T)] = arr
        else
            error("internal error")
        end
    end

    # Read variables
    err = perform_gets(engine)
    @test err ≡ error_none

    # Check variables
    for ((si, D, len, T), (nm, var)) in variables
        # String variables cannot be read (compare
        # <https://github.com/ornladios/ADIOS2/issues/2735>)
        T ≡ String && continue
        if si ∈ (shapeid_global_value, shapeid_local_value)
            val = T ≡ String ? "42" : T(42)
            if T ≡ String
                str = unsafe_string(pointer(buffers[(si, D, len, T)][]))
                @test str == val
            else
                @test buffers[(si, D, len, T)][] == val
            end
        elseif si ∈ (shapeid_global_array, shapeid_local_array)
            sz = ntuple(d -> len == 0 ? 0 : len == 1 ? 1 : d, D)
            # Construct a single number from a tuple
            ten(i, s) = i == () ? s : ten(i[2:end], 10s + i[1])
            # Convert to type `T`
            function mkT(T, s)
                return (T ≡ String ? "$s" :
                        T <: Union{AbstractFloat,Complex} ? T(s) : s % T)::T
            end
            arr = T[mkT(T, ten(Tuple(i), 0)) for i in CartesianIndices(sz)]
            # Empty global arrays are mis-interpreted as global values
            if len == 0
                # There is a spurious value `0`
                @test buffers[(si, D, len, T)] == fill(T(0))
            else
                if comm_size == 1
                    @test buffers[(si, D, len, T)] == arr
                else
                    @test_broken false
                end
            end
        else
            error("internal error")
        end
    end

    err = close(engine)
    @test err ≡ error_none

    err = adios_finalize(adios)
    @test err ≡ error_none
end
# Call gc to test finalizing the Adios object
GC.gc(true)


text:
################################################################################
#  Copyright 2020, Tom Van Acker                                               #
################################################################################
# MultiStateSystems.jl                                                         #
# A Julia package to solve multi-state system models.                          #
# See http://github.com/timmyfaraday/MultiStateSystems.jl                      #
################################################################################

## Universal Generating Function
# structs
"""
    UGF

An ugf is a struct containing: a measure `msr`, corresponding values `val` and
associated probabilities `prb`, with default constructor:

    UGF(msr::Symbol, val::Vector, prb::Vector; red::Bool=true)

A UGF constructor for a specific measure `msr` based on a given value vector
`val` and associated probability vector `prb`.

This function automatically reduces the state-space to where only unique values
and associated probabilites remain. This behavior is circumvented by passing the
optional argument `rdc=false`.

# Example
```julia-repl
julia> ugfᵍᵉⁿ = UGF(:power, [0.0u"MW",0.0u"MW",2.0u"MW"], [0.1,0.2,0.7])
julia> isequal(ugfᵍᵉⁿ.val, [0.0u"MW",2.0u"MW"])
true
julia> ugfᵍᵉⁿ = UGF(:power, [0.0u"MW",0.0u"MW",2.0u"MW"], [0.1,0.2,0.7], rdc=false)
julia> isequal(ugfᵍᵉⁿ.val, [0.0u"MW",0.0u"MW",2.0u"MW"])
true
```
"""
struct UGF <: AbstractUGF
    msr::Symbol
    val::Vector
    prb::Vector

    # default constructor
    UGF(msr::Symbol, val::Vector, prb::Vector; rdc::Bool=true) =
        rdc ? new(msr,reduce(val,prb)...) : new(msr,val,prb)
end

# constructors
function UGF(msr::Symbol)
    prb = [1.0]
    val = [get_max(msr)]

    return UGF(msr, val, prb)
end

"""
    UGF(msr::Symbol, std::MultiStateSystems.AbstractSTD)

A UGF constructor for a specific measure `msr` based on a given state-transition
diagram `std`.

This function automatically reduces the state-space to where only unique values
and associated probabilites remain.

# Example
```julia-repl
julia> stdᵍᵉⁿ = solvedSTD(prob  = [0.1,0.2,0.7],
                          power = [0.0u"MW",0.0u"MW",2.0u"MW"])
julia> ugfᵍᵉⁿ = UGF(:power, stdᵍᵉⁿ)
julia> isequal(ugfᵍᵉⁿ.val,[0.0u"MW",2.0u"MW"])
true
```
"""
UGF(msr::Symbol, std::AbstractSTD) =
    UGF(msr,get_sprop(std,msr),get_sprop(std,:prob))
################################################################################
# WARNING:  The empty constructor needs to be last in order to overwrite the   #
#           empty constructor created by other contructors, see: discourse -   #
#           keyword argument contructor breaks incomplete constructor.         #                                               #
################################################################################
function UGF()
    msr = :msr
    prb = Vector()
    val = Vector()

    return UGF(msr,val,prb)
end

# functions
function cmp_ugf(msr::Symbol,cmp::PropDict)
    if haskey(cmp,:std) return UGF(msr,cmp[:std]) end
    if haskey(cmp,:ntw) ntw, id = cmp[:ntw]; return ntw.usr[id][:ugf] end
    return UGF(msr)
end
function src_ugf(msr::Symbol,src::PropDict)
    if haskey(src,:dep) return UGF(msr,[(1.0)get_unit(msr)],[1.0]) end
    if haskey(src,:std) return UGF(msr,src[:std]) end
    if haskey(src,:ntw) ntw, id = src[:ntw]; return ntw.usr[id][:ugf] end
    return UGF(msr)
end
function set_ugf!(ntw::AbstractNetwork)
    msr = ntw.props[:msr]
    for cmp in cmp(ntw) if !haskey(cmp,:ugf) cmp[:ugf] = cmp_ugf(msr,cmp) end end
    for src in src(ntw) if !haskey(src,:ugf) src[:ugf] = src_ugf(msr,src) end end
end


text:
export set_or_add!, calc_boundary_indices

# Usage:
# - set_or_add(t, i, j, k, s, Val(:(+=)))
# - set_or_add(t, i, j, k, s, Val(:(=)))
@generated function set_or_add!(t::AbsArrNumber, ind::Tuple{Vararg{Integer}}, s::Number, ::Val{OP}) where {OP}
    return Expr(OP, :(t[ind...]), :s)
end

function calc_boundary_indices(N::Tuple{Vararg{Int}})  # range of index: 1 through N
    Nₜ = nthreads()

    Nₑ = N[end]
    L = prod(N) ÷ Nₑ

    ∆n₀ = Nₑ ÷ Nₜ  # default value of entries of ∆n
    min_L∆n₀ = 50 * 50 * 3  # want ∆n₀ to satisfy L * ∆n₀ ≥ 50 * 50 * 3
    if L*∆n₀ < min_L∆n₀
        Nₜ = Int(cld(Nₑ, min_L∆n₀/L))  # cld to make Nₜ ≥ 1; min_L∆n₀/L is target number of entries in each chuck in last dimension
        ∆n₀ = Nₑ ÷ Nₜ
    end

    ∆n = SVec(ntuple(i->(i≤Nₑ%Nₜ ? ∆n₀+1 : ∆n₀), Nₜ))  # first N%Nₜ entries are ∆n₀+1; remaining entries are ∆n₀
    @assert sum(∆n)==Nₑ

    # nₛ = @MVector ones(Int, Nₜ)
    # for j = 2:Nₜ, i = 1:j-1
    #     nₛ[j] += ∆n[i]  # nₛ[1] = 1, nₛ[2] = 1 + ∆n[1], nₛ[3] = 1 + ∆n[1] + ∆n[2], ...
    # end
    nₛ = SVec(ntuple(i->1+sum(@view(∆n[1:i-1])), Nₜ))  # nₛ[1] = 1, nₛ[2] = 1 + ∆n[1], nₛ[3] = 1 + ∆n[1] + ∆n[2], ...

    # nₑ = @MVector zeros(Int, Nₜ)
    # for j = 1:Nₜ, i = 1:j
    #     nₑ[j] += ∆n[i]  # nₑ[1] = ∆n[1], nₑ[2] = ∆n[1] + ∆n[2], nₑ[3] = ∆n[1] + ∆n[2] + ∆n[3], ...
    # end
    nₑ = SVec(ntuple(i->sum(@view(∆n[1:i])), Nₜ))  # nₑ[1] = ∆n[1], nₑ[2] = ∆n[1] + ∆n[2], nₑ[3] = ∆n[1] + ∆n[2] + ∆n[3], ...

    return (nₛ, nₑ)
end

include("differential/differential.jl")
include("mean.jl")


text:
using SpatialDependence
using GeoInterface
using RecipesBase
using SpatialDatasets
using StableRNGs
using Test

@testset "SpatialDependence.jl" begin

    include("sweights.jl")
    include("guerry.jl")
    include("bostonhsg.jl")
    include("maps.jl")
    include("random.jl")

end


text:
using Test
using OpenQuantumSystems
using Random, SparseArrays, LinearAlgebra, StableRNGs

@testset "evolution" begin

    Random.seed!(StableRNG(0), 1)

    D(op1::Array, op2::Array) = abs(norm(op1 - op2))
    D(x1::StateVector, x2::StateVector) = norm(x2 - x1)
    D(op1::AbstractOperator, op2::AbstractOperator) =
        abs(tracedistance_nh(dense(op1), dense(op2)))
    D(op1::AbstractSuperOperator, op2::AbstractSuperOperator) =
        abs(tracedistance_nh(dense(op1), dense(op2)))

    tspan = get_tspan(0., 1., 10)
    ref = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
    @test tspan == ref

    mode1 = Mode(0.2, 1.0)
    mode2 = Mode(0.3, 2.0)
    Energy = [0.0, 200.0]
    mol1 = Molecule([mode1], 3, [2.0, 200.0])
    mol2 = Molecule([mode2], 3, [3.0, 300.0])
    aggCore = AggregateCore([mol1, mol2])
    aggCore.coupling[2, 3] = 50
    aggCore.coupling[3, 2] = 50
    agg = setupAggregate(aggCore)

    Ham = agg.operators.Ham
    H_lambda, H_S = eigen(Ham.data)
    H_Sinv = inv(H_S)
    H_lambda = diagm(H_lambda)

    t = 0.0
    U_op_ref = exp(-1im * Ham * t)
    U_op = evolutionOperator(Ham, t)
    @test 1e-12 > D(U_op, U_op_ref)
    U_op = evolutionOperatorA(H_lambda, H_S, H_Sinv, t)
    @test 1e-12 > D(U_op, U_op_ref.data)

    U_sop = evolutionSuperOperator(Ham, t)
    U_sop_ref = spre(U_op_ref) * spost(U_op_ref')
    @test 1e-12 > D(U_sop, U_sop_ref)

    t = 1.0
    U_op_ref = exp(-1im * Ham * t)
    U_op = evolutionOperator(Ham, t)
    @test 1e-12 > D(U_op, U_op_ref)
    U_op = evolutionOperatorA(H_lambda, H_S, H_Sinv, t)
    @test 1e-12 > D(U_op, U_op_ref.data)

    U_sop = evolutionSuperOperator(Ham, t)
    U_sop_ref = spre(U_op_ref) * spost(U_op_ref')
    @test 1e-12 > D(U_sop, U_sop_ref)

    tspan = [0.0:0.5:1.0;]
    U_op_array = evolutionOperatorArray(Ham, tspan)
    U_op1 = evolutionOperator(Ham, 0.0)
    U_op2 = evolutionOperator(Ham, 0.5)
    U_op3 = evolutionOperator(Ham, 1.0)
    @test 1e-12 > D(U_op_array[1], U_op1)
    @test 1e-12 > D(U_op_array[2], U_op2)
    @test 1e-11 > D(U_op_array[3], U_op3)

    U_sop_array = evolutionSuperOperatorArray(Ham, tspan)
    U_sop1 = evolutionSuperOperator(Ham, 0.0)
    U_sop2 = evolutionSuperOperator(Ham, 0.5)
    U_sop3 = evolutionSuperOperator(Ham, 1.0)
    @test 1e-11 > D(U_sop_array[1], U_sop1)
    @test 1e-10 > D(U_sop_array[2], U_sop2)
    @test 1e-10 > D(U_sop_array[3], U_sop3)

    t = 0.0
    foreach(evolutionOperatorIterator(Ham, tspan; diagonalize = true, approximate = false)
    ) do U_op
        U_op_ref = evolutionOperator(Ham, t)
        @test 1e-11 > D(U_op, U_op_ref)
        t += 0.5
    end

    t = 0.0
    foreach(
        evolutionOperatorIterator(Ham, tspan; diagonalize = false, approximate = false),
    ) do U_op
        U_op_ref = evolutionOperator(Ham, t)
        @test 1e-12 > D(U_op, U_op_ref)
        t += 0.5
    end

    t = 0.0
    foreach(
        evolutionOperatorIterator(Ham, tspan; diagonalize = false, approximate = true),
    ) do U_op
        U_op_ref = evolutionOperator(Ham, t)
        @test 1e-12 > D(U_op, U_op_ref)
        t += 0.5
    end

    t = 0.0
    foreach(
        evolutionSuperOperatorIterator(Ham, tspan; diagonalize = false, approximate = true)
    ) do U_sop
        U_sop_ref = evolutionSuperOperator(Ham, t)
        @test 1e-10 > D(U_sop, U_sop_ref)
        t += 0.5
    end

    t = 0.0
    foreach(
        evolutionSuperOperatorIterator(Ham, tspan; diagonalize = false, approximate = false),
    ) do U_op
        U_op_ref = evolutionSuperOperator(Ham, t)
        @test 1e-12 > D(U_op, U_op_ref)
        t += 0.5
    end

    t = 0.0
    foreach(
        evolutionSuperOperatorIterator(Ham, tspan; diagonalize = false, approximate = true),
    ) do U_op
        U_op_ref = evolutionSuperOperator(Ham, t)
        @test 1e-12 > D(U_op, U_op_ref)
        t += 0.5
    end

    ket = randstate(agg.tools.basis)
    ket1 = U_op1 * ket
    ket2 = U_op2 * ket
    ket3 = U_op3 * ket
    ket_array = evolutionExact(ket, tspan, Ham)
    @test 1e-12 > D(ket1, ket_array[1])
    @test 1e-12 > D(ket2, ket_array[2])
    @test 1e-12 > D(ket3, ket_array[3])

    ket_array = Array{Array{ComplexF32,1},1}(undef, 0)
    evolutionExact!(ket_array, ket, tspan, Ham)
    @test 1e-7 > D(ket1.data, ket_array[1])
    @test 1e-7 > D(ket2.data, ket_array[2])
    @test 1e-7 > D(ket3.data, ket_array[3])

    ket_array = evolutionApproximate(ket, tspan, Ham)
    @test 1e-12 > D(ket1, ket_array[1])
    @test 1e-12 > D(ket2, ket_array[2])
    @test 1e-12 > D(ket3, ket_array[3])

    ket_array = Array{Array{ComplexF32,1},1}(undef, 0)
    evolutionApproximate!(ket_array, ket, tspan, Ham)
    @test 1e-7 > D(ket1.data, ket_array[1])
    @test 1e-7 > D(ket2.data, ket_array[2])
    @test 1e-7 > D(ket3.data, ket_array[3])

    op = dm(ket)
    op1 = U_sop1 * op
    op2 = U_sop2 * op
    op3 = U_sop3 * op
    op_array = evolutionExact(op, tspan, Ham)
    @test 1e-12 > D(op1, op_array[1])
    @test 1e-12 > D(op2, op_array[2])
    @test 1e-12 > D(op3, op_array[3])

    op_array = Array{Array{ComplexF32,2},1}(undef, 0)
    evolutionExact!(op_array, op, tspan, Ham)
    @test 1e-7 > D(op1.data, op_array[1])
    @test 1e-7 > D(op2.data, op_array[2])
    @test 1e-7 > D(op3.data, op_array[3])

    op_array = evolutionApproximate(op, tspan, Ham)
    @test 1e-12 > D(op1, op_array[1])
    @test 1e-12 > D(op2, op_array[2])
    @test 1e-12 > D(op3, op_array[3])

    op_array = Array{Array{ComplexF32,2},1}(undef, 0)
    evolutionApproximate!(op_array, op, tspan, Ham)
    @test 1e-7 > D(op1.data, op_array[1])
    @test 1e-7 > D(op2.data, op_array[2])
    @test 1e-7 > D(op3.data, op_array[3])

    data = Matrix(Hermitian(rand(ComplexF64, agg.tools.bSize, agg.tools.bSize)))
    rho0 = DenseOperator(agg.tools.basis, agg.tools.basis, data)
    normalize!(rho0)

    tspan = [0.0:0.1:1.0;]
    rho_t_ref = evolutionExact(rho0, tspan, Ham)

    T, rho_t = evolution_exact(rho0, tspan, Ham; diagonalize = false)
    U_op_array = evolutionOperatorArray(Ham, tspan)
    for t_i = 1:length(tspan)
        U_op = U_op_array[t_i]
        rho_ref = U_op * rho0 * U_op'
        @test 1e-12 > D(rho_t_ref[t_i], rho_t[t_i])
    end

    T, rho_t = evolution_exact(rho0, tspan, Ham; diagonalize = true)
    for t_i = 1:length(tspan)
        U_op = U_op_array[t_i]
        rho_ref = U_op * rho0 * U_op'
        @test 1e-12 > D(rho_t_ref[t_i], rho_t[t_i])
    end

    T, rho_t = evolution_approximate(rho0, tspan, Ham; diagonalize = false)
    for t_i = 1:length(tspan)
        U_op = U_op_array[t_i]
        rho_ref = U_op * rho0 * U_op'
        @test 1e-12 > D(rho_t_ref[t_i], rho_t[t_i])
    end

    T, rho_t = evolution_approximate(rho0, tspan, Ham; diagonalize = true)
    for t_i = 1:length(tspan)
        U_op = U_op_array[t_i]
        rho_ref = U_op * rho0 * U_op'
        @test 1e-12 > D(rho_t_ref[t_i], rho_t[t_i])
    end

    t = 1.
    indicesMap = agg.tools.indicesMap
    U_part = evolution_el_part(Ham, t, 2, 2, indicesMap)
    data = take_el_part(Ham.data, 2, 2, indicesMap)
    b = GenericBasis([size(data, 1)])
    data = evolutionOperator(data, t)
    ref = DenseOperator(b, b, data)
    @test 1e-12 > D(ref, U_part)

    mode1 = Mode(0.2, 1.0)
    mode2 = Mode(0.3, 2.0)
    Energy = [0.0, 200.0]
    mol1 = Molecule([mode1], 2, [2.0, 200.0])
    mol2 = Molecule([mode2], 2, [3.0, 300.0])
    aggCore = AggregateCore([mol1, mol2])
    aggCore.coupling[2, 3] = 50
    aggCore.coupling[3, 2] = 50
    agg = setupAggregate(aggCore)
    aggTools = agg.tools
    aggOperators = agg.operators

    Ham_I = agg.operators.Ham_I
    Ham_0 = agg.operators.Ham_0
    Ham = agg.operators.Ham

    basis = agg.tools.basis
    indicesLen = agg.tools.bSize
    indices = agg.tools.indices
    indicesMap = agg.tools.indicesMap
    FCFact = agg.tools.FCfactors
    FCProd = agg.tools.FCproduct

    W0 = [0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.25000143755694526 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.2499997124870238 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.2500002875090083 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.24999856244702248]
    W0 = DenseOperator(basis, basis, complex(W0))

    t = 1.
    tspan = get_tspan(0., t, 1)
    _, W_int_t_ = Evolution_SI_exact(W0, tspan, agg)
    U_op = evolutionOperator(Ham, t)
    W = U_op * W0 * U_op'
    U_0_op = evolutionOperator(Ham_0, t)
    W = U_0_op' * W * U_0_op
    W_int_t_ref = W.data
    @test 1e-12 > D(W_int_t_ref, W_int_t_[2, :, :])

    _, rho_int_t_ = Evolution_sI_exact(W0, tspan, agg)
    rho_int_t_ref = trace_bath(W_int_t_ref, agg.core, agg.tools)
    @test 1e-12 > D(rho_int_t_ref, rho_int_t_[2, :, :])

    _, W_t_ = Evolution_SS_exact(W0, tspan, agg)
    U_op = evolutionOperator(Ham, t)
    W = U_op * W0 * U_op'
    W_t_ref = W.data
    @test 1e-12 > D(W_t_ref, W_t_[2, :, :])

    _, rho_t_ = Evolution_sS_exact(W0, tspan, agg)
    rho_t_ref = trace_bath(W_t_ref, agg.core, agg.tools)
    @test 1e-12 > D(rho_t_ref, rho_t_[2, :, :])
end

max_stars_repo_name: detrin/OpenQuantumSystems

max_issues_repo_name: detrin/OpenQuantumSystems

max_forks_repo_name: detrin/OpenQuantumSystems


text:
using Distributed, Serialization
using JLD2, FileIO
import Random

addprocs(3, exeflags="--project=.")

@everywhere using JLD2, FileIO, Serialization

@everywhere function calculate(x)
    return x^2
end

@everywhere function save_results!(fn::String, idx::String, results::Tuple)::Nothing
    jldopen(fn, "a+") do file
        # g = JLD2.Group(file, idx)  # create group
        file["$(idx)/results"] = results[2]  # zone_results
    end

    return nothing
end

function run_calc(x)
    n_ele = length(x)
    results = @sync @distributed (hcat) for i in 1:n_ele
        b = IOBuffer()
        res = calculate(x[i])
        serialize(b, res)
        b.data
    end

    @sync for i in 1:size(results, 2)
        res = deserialize(IOBuffer(@view results[:, i]))
        @async save_results!("dist_res.jld2", string(i), (i, res))
    end
end

arr = randn((100, 1))

run_calc(arr)

imported_res = load("dist_res.jld2")

@info imported_res

max_stars_repo_name: ConnectedSystems/agtor-jl

max_issues_repo_name: ConnectedSystems/agtor-jl

max_forks_repo_name: ConnectedSystems/agtor-jl


text:
using Distributed
@everywhere using MCPhylo

@everywhere extensions = quote
  using Distributions
  import Distributions: location, scale, skewness, kurtosis, minimum, maximum,
         quantile

  struct GK <: ContinuousUnivariateDistribution
    A::Float64
    B::Float64
    g::Float64
    k::Float64
    c::Float64

    function GK(A::Real, B::Real, g::Real, k::Real, c::Real)
      ## check args
      0.0 <= c < 1.0 || throw(ArgumentError("c must be in [0, 1)"))

      ## create distribution
      new(A, B, g, k, c)
    end

    GK(A::Real, B::Real, g::Real, k::Real) = GK(A, B, g, k, 0.8)
  end

  ## Parameters
  location(d::GK) = d.A
  scale(d::GK) = d.B
  skewness(d::GK) = d.g
  kurtosis(d::GK) = d.k
  asymmetry(d::GK) = d.c

  minimum(d::GK) = -Inf
  maximum(d::GK) = Inf

  function quantile(d::GK, p::Float64)
    z = quantile(Normal(), p)
    z2gk(d, z)
  end

  function z2gk(d::GK, z::Float64)
    term1 = exp(-skewness(d) * z)
    term2 = (1.0 + asymmetry(d) * (1.0 - term1) / (1.0 + term1))
    term3 = (1.0 + z^2)^kurtosis(d)
    location(d) + scale(d) * z * term2 * term3
  end
end

@everywhere eval(extensions)

d = GK(3, 1, 2, 0.5)
x = rand(d, 1000)

allingham = Dict{Symbol, Any}(
  :x => x
)

model = Model(
  x = Stochastic(1, (A, B, g, k) -> GK(A, B, g, k), false),
  A = Stochastic(() -> Uniform(0, 10)),
  B = Stochastic(() -> Uniform(0, 10)),
  g = Stochastic(() -> Uniform(0, 10)),
  k = Stochastic(() -> Uniform(0, 10))
)

inits = [
  Dict{Symbol, Any}(:x => x, :A => 3.5, :B => 0.5,
                    :g => 2.0, :k => 0.5),
  Dict{Symbol, Any}(:x => x, :A => median(x),
                    :B => sqrt(var(x)),
                    :g => 1.0, :k => 1.0),
  Dict{Symbol, Any}(:x => x, :A => median(x),
                    :B => diff(quantile(x, [0.25, 0.75]))[1],
                    :g => mean((x .- mean(x)).^3) / (var(x)^(3 / 2)),
                    :k => rand())
]

sigma1 = 0.05
sigma2 = 0.5
stats = x -> quantile(x, [0.1, 0.25, 0.5, 0.75, 0.9])
epsilon = 0.1

scheme = [ABC([:A, :B, :k],
              sigma1, stats, epsilon, maxdraw=50, decay=0.75, randeps=true),
          ABC(:g, sigma2, stats, epsilon, maxdraw=50, decay=0.75)]
setsamplers!(model, scheme)

sim = mcmc(model, allingham, inits, 10000, burnin=2500, chains=3)
describe(sim)
p = plot(sim)
draw(p, filename="gk")