{"text": "using JuliaPBF.StructPBF\n\nfunction GenParticles(inAnsDataStruct::AnalysisDataStruct)\n npart = inAnsDataStruct.nMaxParticles\n ar_ParticleData = Vector{ParticleData}(undef,npart)\n for ii in 1:npart\n ar_ParticleData[ii] = ParticleData(\n inAnsDataStruct.nMaxParticles+1, # gridID :: Int64\n Vec2(), # vel :: Vec2\n Vec2(), # pos :: Vec2\n Vec2(), # temppos:: Vec2\n 0.0, # Lambda :: Float64\n 0.0, # mass :: Float64\n 0.0) # phase :: Int64\n end\n FillInitialBox(inAnsDataStruct, ar_ParticleData)\n return ar_ParticleData\nend\n\nfunction GenGrids(inAnsDataStruct::AnalysisDataStruct)\n start_point = inAnsDataStruct.analysisBox.staPoint\n end_point = inAnsDataStruct.analysisBox.endPoint\n grid_size = 2.0 * inAnsDataStruct.kernelRadius\n n_Grid_x = Int(ceil((end_point.x - start_point.x)/grid_size))\n n_Grid_y = Int(ceil((end_point.y - start_point.y)/grid_size))\n \n ini_nNearGrid = Vector{Int64}(undef,n_Grid_x*n_Grid_y)\n ini_nGridParticles = Vector{Int64}(undef,n_Grid_x*n_Grid_y)\n ini_NearGridIndex = Vector{Int64}(undef,9*(n_Grid_x-2)*(n_Grid_y-2) + 6*(2*(n_Grid_x-2)+2*(n_Grid_y-2)) + 4*4)\n nong = 0\n for iy in 1:n_Grid_y\n for ix in 1:n_Grid_x\n # 아랫줄\n if iy > 1\n if ix > 1\n nong+=1\n ini_NearGridIndex[nong] = ix-1 + (iy-2)*n_Grid_x\n end\n nong+=1\n ini_NearGridIndex[nong] = ix + (iy-2)*n_Grid_x\n if ix < n_Grid_x\n nong+=1\n ini_NearGridIndex[nong] = ix+1 + (iy-2)*n_Grid_x\n end\n end\n # 자기줄\n if ix > 1\n nong+=1\n ini_NearGridIndex[nong] = ix-1 + (iy-1)*n_Grid_x\n end\n nong+=1\n ini_NearGridIndex[nong] = ix + (iy-1)*n_Grid_x\n if ix < n_Grid_x\n nong+=1\n ini_NearGridIndex[nong] = ix+1 + (iy-1)*n_Grid_x\n end\n # 윗줄\n if iy < n_Grid_y\n if ix > 1\n nong+=1\n ini_NearGridIndex[nong] = ix-1 + iy*n_Grid_x\n end\n nong+=1\n ini_NearGridIndex[nong] = ix + iy*n_Grid_x\n if ix < n_Grid_x\n nong+=1\n ini_NearGridIndex[nong] = ix+1 + iy*n_Grid_x\n end\n end\n ii = ix + (iy-1)*n_Grid_x\n ini_nNearGrid[ii] = nong\n ini_nGridParticles[ii] = 0\n end\n end\n\n return GridData(ini_nNearGrid,ini_NearGridIndex,ini_nGridParticles)\nend\n\nfunction GenPhases(inAnsDataStruct::AnalysisDataStruct)\n ## CREATE BOUNDARY LINES ##\n # Boundary line is a object which shape never\n # change, but only 회전/병진. at this time, it\n # won't be added since defining the method how \n # treat the boundary condition. \n # line collision? dummy particles? \n return []\nend\n\nfunction GenBoundaries(inAnsDataStruct::AnalysisDataStruct)\n ## CREATE BOUNDARY LINES ##\n # Boundary line is a object which shape never\n # change, but only 회전/병진. at this time, it\n # won't be added since defining the method how \n # treat the boundary condition. \n # line collision? dummy particles? \n return []\nend\n\n# private\n\nfunction FillInitialBox(inAnsDataStruct::AnalysisDataStruct, arParticleData::Vector{ParticleData})\n ID = 1\n for initBox_i in 1:length(inAnsDataStruct.a_initialBox)\n initBox_phaseID = inAnsDataStruct.a_initialBox[initBox_i].phaseID\n initBox_box = inAnsDataStruct.a_initialBox[initBox_i].box\n initBox_vel = inAnsDataStruct.a_initialBox[initBox_i].vel\n initBox_type = inAnsDataStruct.a_phases[initBox_phaseID].type\n if initBox_type == \"Fluid\"\n initBox_name = inAnsDataStruct.a_phases[initBox_phaseID].Fluid.name\n initBox_size = inAnsDataStruct.a_phases[initBox_phaseID].Fluid.size\n initBox_density = inAnsDataStruct.a_phases[initBox_phaseID].Fluid.density\n initBox_viscosity = inAnsDataStruct.a_phases[initBox_phaseID].Fluid.viscosity\n # initBox_mass = initBox_density * (π*(initBox_size*0.5)^2.0) # Circle\n # initBox_mass = initBox_density * (initBox_size^2.0) # Box \n initBox_mass = initBox_density * ((initBox_size^2.0)*0.85 + (π*(initBox_size*0.5)^2.0)*0.15)\n end\n boxDX = initBox_box.endPoint.x - initBox_box.staPoint.x\n boxDY = initBox_box.endPoint.y - initBox_box.staPoint.y\n for ix in 1:div(boxDX+initBox_size*0.5,initBox_size)\n for iy in 1:div(boxDY+initBox_size*0.5,initBox_size)\n xx = initBox_box.staPoint.x + (ix-0.5)*initBox_size\n yy = initBox_box.staPoint.y + (iy-0.5)*initBox_size\n arParticleData[ID] = ParticleData(\n 0, # gridID :: Int64\n initBox_vel, # vel :: Vec2\n Vec2(xx,yy), # pos :: Vec2\n Vec2(xx,yy), # temppos:: Vec2\n 0.0, # lambda :: Float64\n initBox_mass, # mass :: Float64\n initBox_phaseID)# phase :: Int64\n ID += 1\n end\n end\n end\nend", "meta": {"hexsha": "da538a258ef2b69265c1ad1bbaf7c9898ff94aad", "size": 5861, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Solver/InitializingFunctions.jl", "max_stars_repo_name": "Hipgineer/JuliaPBF", "max_stars_repo_head_hexsha": "b6322a2d0e70af15fb4b7d5d75a68483deda503a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Solver/InitializingFunctions.jl", "max_issues_repo_name": "Hipgineer/JuliaPBF", "max_issues_repo_head_hexsha": "b6322a2d0e70af15fb4b7d5d75a68483deda503a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Solver/InitializingFunctions.jl", "max_forks_repo_name": "Hipgineer/JuliaPBF", "max_forks_repo_head_hexsha": "b6322a2d0e70af15fb4b7d5d75a68483deda503a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4148148148, "max_line_length": 115, "alphanum_fraction": 0.530626173, "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2499389747764833}} {"text": "#----------------------------------------------------------------------------------------------#\n# Amount Type Interface #\n#----------------------------------------------------------------------------------------------#\n\n\"\"\"\n`function deco end`\\n\nInterface to return a unique decorative `Symbol` from a method's argument type.\n\"\"\"\nfunction deco end\n\n\"\"\"\n`function ppu end`\\n\nInterface to pretty-print units.\n\"\"\"\nfunction ppu end\n\n# A 191113-212130 benchmark showed amt(x) is faster than x.amt:\n#\n# ```julia-repl\n# julia> u1 = u(1.0f0 ± 0.1f0, MO)\n# ū₃₂: (1 ± 0.1) kJ/kmol\n#\n# julia> typeof(u1)\n# uAmt{Float32,MM,MO}\n#\n# julia> @benchmark u1.amt\n# ✂ ✂ ✂ median time: 26.918 ns (0.00% GC) ✂ ✂ ✂\n#\n# julia> @benchmark amt(u1)\n# ✂ ✂ ✂ median time: 16.710 ns (0.00% GC) ✂ ✂ ✂\n#\n# ```\n\n\"\"\"\n`function amt end`\\n\nInterface to get an `AMOUNTS`' `:amt` field in a type-stable manner.\n\"\"\"\nfunction amt end\n\nexport deco, ppu, amt\n\n\n#----------------------------------------------------------------------------------------------#\n# Generic Amount Type #\n#----------------------------------------------------------------------------------------------#\n\nimport Base: cp, convert\nimport Unicode: normalize\nimport Base: +, -, *, /\n\n\"\"\"\nGeneric Amount type factory.\n\"\"\"\nfunction mkGenAmt(TYPE::Symbol, # Type name: :_Amt\n SUPT::Symbol, # Supertype: :GenerAmt\n SYMB::AbstractString, # Printing symbol: \"?\"\n WHAT::AbstractString, # Description: \"generic amounts\"\n DELT::Bool=false, # Whether a Δ quantity\n )\n # Constants\n i, f = DELT ? (3, 4) : (1, 2)\n 𝑠SY = normalize((DELT ? \"Δ\" : \"\") * string(SYMB))\n # Documentation\n hiStr = tyArchy(eval(SUPT))\n dcStr = \"\"\"\n`struct $TYPE{𝗽<:PREC,𝘅<:EXAC} <: $SUPT{𝗽,𝘅}`\\n\nPrecision-, and Exactness- parametric $WHAT amounts based in arbitrary units.\\n\n`$TYPE{𝗽,𝘅}` parameters are:\\n\n- Precision `𝗽<:Union{Float16,Float32,Float64,BigFloat}`;\\n\n- Exactness `𝘅<:Union{EX,MM}`, i.e., either a single, precise value or an uncertainty-bearing\n measurement, respectively;\\n\nA `$TYPE` can be natively constructed from the following argument types:\\n\n- A plain, unitless float;\\n\n- A plain, unitless `Measurement`; hence, any `AbstractFloat`;\\n\n- A `Quantity{AbstractFloat}` with any units.\\n\n## Hierarchy\\n\n`$(TYPE) <: $(hiStr)`\n \"\"\"\n # @eval block\n @eval begin\n # Concrete type definition\n struct $TYPE{𝗽,𝘅} <: $SUPT{𝗽,𝘅}\n amt::UATY{𝗽} where 𝗽<:PREC\n # Inner, non-converting, parameter-determining constructors\n $TYPE(x::$TYPE{𝗽,𝘅}) where {𝗽<:PREC,𝘅<:EXAC} = new{𝗽,𝘅}(amt(x))\n $TYPE(x::Union{𝗽,UETY{𝗽}}) where 𝗽<:PREC = new{𝗽,EX}(_qty(x))\n $TYPE(x::Union{PMTY{𝗽},UMTY{𝗽}}) where 𝗽<:PREC = new{𝗽,MM}(_qty(x))\n # Inner, non-converting, fully-specified constructors\n (::Type{$TYPE{𝗽,EX}})(x::𝗽) where 𝗽<:PREC = new{𝗽,EX}(_qty(x))\n (::Type{$TYPE{𝗽,EX}})(x::PMTY{𝗽}) where 𝗽<:PREC = new{𝗽,EX}(_qty(x.val))\n (::Type{$TYPE{𝗽,MM}})(x::𝗽) where 𝗽<:PREC = new{𝗽,MM}(_qty(measurement(x)))\n (::Type{$TYPE{𝗽,MM}})(x::PMTY{𝗽}) where 𝗽<:PREC = new{𝗽,MM}(_qty(x))\n end\n # Type documentation\n @doc $dcStr $TYPE\n # Precision-changing external constructors\n (::Type{$TYPE{𝘀}})(x::$TYPE{𝗽,EX}) where {𝘀<:PREC,𝗽<:PREC} = begin\n $TYPE(𝘀(amt(x).val) * unit(amt(x)))\n end\n (::Type{$TYPE{𝘀}})(x::$TYPE{𝗽,MM}) where {𝘀<:PREC,𝗽<:PREC} = begin\n $TYPE(Measurement{𝘀}(amt(x).val) * unit(amt(x)))\n end\n # Precision+Exactness-changing external constructors\n (::Type{$TYPE{𝘀,EX}})(x::$TYPE{𝗽,EX}) where {𝘀<:PREC,𝗽<:PREC} = begin\n $TYPE(𝘀(amt(x).val) * unit(amt(x)))\n end\n (::Type{$TYPE{𝘀,EX}})(x::$TYPE{𝗽,MM}) where {𝘀<:PREC,𝗽<:PREC} = begin\n $TYPE(𝘀(amt(x).val.val) * unit(amt(x)))\n end\n (::Type{$TYPE{𝘀,MM}})(x::$TYPE{𝗽,EX},\n e::𝘀=𝘀(max(eps(𝘀), eps(amt(x).val)))) where {𝘀<:PREC,\n 𝗽<:PREC} = begin\n $TYPE(measurement(𝘀(amt(x).val), e) * unit(amt(x)))\n end\n (::Type{$TYPE{𝘀,MM}})(x::$TYPE{𝗽,MM}) where {𝘀<:PREC,𝗽<:PREC} = begin\n $TYPE(Measurement{𝘀}(amt(x).val) * unit(amt(x)))\n end\n # Type export\n export $TYPE\n # Type-stabler wrapped amount obtaining function\n amt(x::$TYPE{𝗽,EX}) where 𝗽<:PREC = x.amt::Quantity{𝗽}\n amt(x::$TYPE{𝗽,MM}) where 𝗽<:PREC = x.amt::Quantity{Measurement{𝗽}}\n # Type-specific functions\n deco(x::$TYPE{𝗽,𝘅} where {𝗽,𝘅}) = Symbol($𝑠SY)\n ppu(x::$TYPE{𝗽,𝘅} where {𝗽,𝘅}) = string(unit(amt(x)))\n # Conversions\n convert(::Type{$TYPE{𝘀,𝘅}},\n y::$TYPE{𝗽,𝘅}) where {𝘀<:PREC,𝗽<:PREC,𝘅<:EXAC} = begin\n $TYPE{promote_type(𝘀,𝗽),𝘅}(y)\n end\n convert(::Type{$TYPE{𝘀,𝘆}},\n y::$TYPE{𝗽,𝘅}) where {𝘀<:PREC,𝗽<:PREC,𝘆<:EXAC,𝘅<:EXAC} = begin\n $TYPE{promote_type(𝘀,𝗽),promote_type(𝘆,𝘅)}(y)\n end\n # Promotion rules\n promote_rule(::Type{$TYPE{𝘀,𝘆}},\n ::Type{$TYPE{𝗽,𝘅}}) where {𝘀<:PREC,𝗽<:PREC,𝘆<:EXAC,𝘅<:EXAC} = begin\n $TYPE{promote_type(𝘀,𝗽),promote_type(𝘆,𝘅)}\n end\n # same-type sum,sub with Unitful promotion\n +(x::$TYPE{𝘀,𝘆}, y::$TYPE{𝗽,𝘅}) where {𝘀<:PREC,𝗽<:PREC,𝘆<:EXAC,𝘅<:EXAC} = begin\n $TYPE(+(amt(x), amt(y)))\n end\n -(x::$TYPE{𝘀,𝘆}, y::$TYPE{𝗽,𝘅}) where {𝘀<:PREC,𝗽<:PREC,𝘆<:EXAC,𝘅<:EXAC} = begin\n $TYPE(-(amt(x), amt(y)))\n end\n # scalar mul,div with Unitful promotion\n *(y::plnF{𝘀}, x::$TYPE{𝗽}) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(*(amt(x), y))\n *(x::$TYPE{𝗽}, y::plnF{𝘀}) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(*(amt(x), y))\n /(x::$TYPE{𝗽}, y::plnF{𝘀}) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(/(amt(x), y))\n # Type-preserving scalar mul,div\n *(y::REAL, x::$TYPE{𝗽}) where 𝗽<:PREC = $TYPE(*(amt(x), 𝗽(y)))\n *(x::$TYPE{𝗽}, y::REAL) where 𝗽<:PREC = $TYPE(*(amt(x), 𝗽(y)))\n /(x::$TYPE{𝗽}, y::REAL) where 𝗽<:PREC = $TYPE(/(amt(x), 𝗽(y)))\n end\nend\n\n#----------------------------------------------------------------------------------------------#\n# Generic Amount Declarations #\n#----------------------------------------------------------------------------------------------#\n\n# The fallback generic amount\nmkGenAmt(:_Amt , :GenerAmt , \"?\" , \"generic amounts\" , false )\n\n\n#----------------------------------------------------------------------------------------------#\n# Whole Amount Type Factory #\n#----------------------------------------------------------------------------------------------#\n\n\"\"\"\nWhole Amount type factory.\n\"\"\"\nfunction mkWhlAmt(TYPE::Symbol, # Type name: :sysT\n SUPT::Symbol, # Supertype: :WProperty\n FNAM::Symbol, # Function Name: :T\n SYMB::AbstractString, # Printing symbol: \"T\"\n UNIT::Unitful.Units, # SY quantity units: u\"K\"\n USTR::AbstractString, # PrettyPrinting units: \"K\"\n WHAT::AbstractString, # Description: \"temperature\"\n DELT::Bool=false, # Whether a Δ quantity\n )\n # Constants\n uSY = UNIT\n 𝑢SY = typeof(uSY)\n 𝑑SY = dimension(uSY)\n i, f = DELT ? (3, 4) : (1, 2)\n 𝑠SY = normalize((DELT ? \"Δ\" : \"\") * string(SYMB))\n # Documentation\n hiStr = tyArchy(eval(SUPT))\n dcStr = \"\"\"\n`struct $TYPE{𝗽<:PREC,𝘅<:EXAC} <: $SUPT{𝗽,𝘅}`\\n\nPrecision-, and Exactness- parametric $WHAT amounts based in $USTR.\\n\n`$TYPE{𝗽,𝘅}` parameters are:\\n\n- Precision `𝗽<:Union{Float16,Float32,Float64,BigFloat}`;\\n\n- Exactness `𝘅<:Union{EX,MM}`, i.e., either a single, precise value or an uncertainty-bearing\n measurement, respectively;\\n\nA `$TYPE` can be natively constructed from the following argument types:\\n\n- A plain, unitless float;\\n\n- A plain, unitless `Measurement`; hence, any `AbstractFloat`;\\n\n- A `Quantity{AbstractFloat}` with compatible units.\\n\nConstructors determine all parameters from their arguments.\\n\n## Hierarchy\\n\n`$(TYPE) <: $(hiStr)`\n \"\"\"\n # @eval block\n @eval begin\n # Concrete type definition\n struct $TYPE{𝗽,𝘅} <: $SUPT{𝗽,𝘅}\n amt::UATY{𝗽,$𝑑SY,$𝑢SY} where 𝗽<:PREC\n # Inner, non-converting, parameter-determining constructors\n # ---------------------------------------------------------\n # Copy constructor\n $TYPE(x::$TYPE{𝗽,𝘅}) where {𝗽<:PREC,𝘅<:EXAC} = new{𝗽,𝘅}(amt(x))\n # Plain constructors enforce default units & avoid unit conversion\n $TYPE(x::𝗽) where 𝗽<:PREC = new{𝗽,EX}(_qty(x * $uSY))\n $TYPE(x::PMTY{𝗽}) where 𝗽<:PREC = new{𝗽,MM}(_qty(x * $uSY))\n # Quantity constructors have to perform unit conversion despite matching dimensions\n $TYPE(x::UETY{𝗽,$𝑑SY}) where 𝗽<:PREC = new{𝗽,EX}(_qty(uconvert($uSY, x)))\n $TYPE(x::UMTY{𝗽,$𝑑SY}) where 𝗽<:PREC = new{𝗽,MM}(_qty(uconvert($uSY, x)))\n # Inner, non-converting, fully-specified constructors\n # ---------------------------------------------------\n (::Type{$TYPE{𝗽,EX}})(x::𝗽) where 𝗽<:PREC = new{𝗽,EX}(_qty(x * $uSY))\n (::Type{$TYPE{𝗽,EX}})(x::PMTY{𝗽}) where 𝗽<:PREC = new{𝗽,EX}(_qty(x.val * $uSY))\n (::Type{$TYPE{𝗽,MM}})(x::𝗽) where 𝗽<:PREC = new{𝗽,MM}(_qty(measurement(x) * $uSY))\n (::Type{$TYPE{𝗽,MM}})(x::PMTY{𝗽}) where 𝗽<:PREC = new{𝗽,MM}(_qty(x * $uSY))\n end\n # Type documentation\n @doc $dcStr $TYPE\n # Precision-changing external constructors\n (::Type{$TYPE{𝘀}})(x::$TYPE{𝗽,EX}\n ) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(𝘀(amt(x).val))\n (::Type{$TYPE{𝘀}})(x::$TYPE{𝗽,MM}\n ) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(Measurement{𝘀}(amt(x).val))\n # Precision+Exactness-changing external constructors\n (::Type{$TYPE{𝘀,EX}})(x::$TYPE{𝗽,EX}\n ) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(𝘀(amt(x).val))\n (::Type{$TYPE{𝘀,EX}})(x::$TYPE{𝗽,MM}\n ) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(𝘀(amt(x).val.val))\n (::Type{$TYPE{𝘀,MM}})(x::$TYPE{𝗽,EX},\n e::𝘀=𝘀(max(eps(𝘀),eps(amt(x).val)))\n ) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(measurement(𝘀(amt(x).val), e))\n (::Type{$TYPE{𝘀,MM}})(x::$TYPE{𝗽,MM}\n ) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(Measurement{𝘀}(amt(x).val))\n # Type export\n export $TYPE\n # Type-stable wrapped amount obtaining function\n amt(x::$TYPE{𝗽,EX}) where 𝗽<:PREC = x.amt::Quantity{𝗽,$𝑑SY,$𝑢SY}\n amt(x::$TYPE{𝗽,MM}) where 𝗽<:PREC = x.amt::Quantity{Measurement{𝗽},$𝑑SY,$𝑢SY}\n # Type-specific functions\n deco(x::$TYPE{𝗽,𝘅} where {𝗽,𝘅}) = Symbol($𝑠SY)\n ppu(x::$TYPE{𝗽,𝘅} where {𝗽,𝘅}) = $USTR\n # Indirect construction from plain\n $FNAM(x::plnF) = $TYPE(x)\n $FNAM(x::REAL) = $TYPE(float(x))\n # Indirect construction from quantity\n $FNAM(x::UATY{𝗽,$𝑑SY}) where 𝗽<:PREC = $TYPE(x)\n $FNAM(x::uniR{𝗽,$𝑑SY}) where 𝗽<:REAL = $TYPE(float(x.val) * unit(x))\n export $FNAM\n # Conversions\n convert(::Type{$TYPE{𝘀,𝘅}},\n y::$TYPE{𝗽,𝘅}) where {𝘀<:PREC,𝗽<:PREC,𝘅<:EXAC} = begin\n $TYPE{promote_type(𝘀,𝗽),𝘅}(y)\n end\n convert(::Type{$TYPE{𝘀,𝘆}},\n y::$TYPE{𝗽,𝘅}) where {𝘀<:PREC,𝗽<:PREC,𝘆<:EXAC,𝘅<:EXAC} = begin\n $TYPE{promote_type(𝘀,𝗽),promote_type(𝘆,𝘅)}(y)\n end\n # Promotion rules\n promote_rule(::Type{$TYPE{𝘀,𝘆}},\n ::Type{$TYPE{𝗽,𝘅}}) where {𝘀<:PREC,𝗽<:PREC,𝘆<:EXAC,𝘅<:EXAC} = begin\n $TYPE{promote_type(𝘀,𝗽),promote_type(𝘆,𝘅)}\n end\n # same-type sum,sub with Unitful promotion\n +(x::$TYPE{𝘀,𝘆}, y::$TYPE{𝗽,𝘅}) where {𝘀<:PREC,𝗽<:PREC,𝘆<:EXAC,𝘅<:EXAC} = begin\n $TYPE(+(amt(x), amt(y)))\n end\n -(x::$TYPE{𝘀,𝘆}, y::$TYPE{𝗽,𝘅}) where {𝘀<:PREC,𝗽<:PREC,𝘆<:EXAC,𝘅<:EXAC} = begin\n $TYPE(-(amt(x), amt(y)))\n end\n # scalar mul,div with Unitful promotion\n *(y::plnF{𝘀}, x::$TYPE{𝗽}) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(*(amt(x), y))\n *(x::$TYPE{𝗽}, y::plnF{𝘀}) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(*(amt(x), y))\n /(x::$TYPE{𝗽}, y::plnF{𝘀}) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(/(amt(x), y))\n # Type-preserving scalar mul,div\n *(y::REAL, x::$TYPE{𝗽}) where 𝗽<:PREC = $TYPE(*(amt(x), 𝗽(y)))\n *(x::$TYPE{𝗽}, y::REAL) where 𝗽<:PREC = $TYPE(*(amt(x), 𝗽(y)))\n /(x::$TYPE{𝗽}, y::REAL) where 𝗽<:PREC = $TYPE(/(amt(x), 𝗽(y)))\n end\nend\n\n\n#----------------------------------------------------------------------------------------------#\n# Thermodynamic Whole Amount Declarations #\n#----------------------------------------------------------------------------------------------#\n\n# Regular properties -- \\bb# velocity/speed function names\nmkWhlAmt(:sysT , :WProperty, :T , \"T\" , u\"K\" , \"K\" , \"temperature\" , false )\nmkWhlAmt(:sysP , :WProperty, :P , \"P\" , u\"kPa\" , \"kPa\" , \"pressure\" , false )\nmkWhlAmt(:VELO , :WProperty, :velo , \"𝕍\" , u\"√(kJ/kg)\" , \"√kJ/kg\" , \"velocity\" , false )\nmkWhlAmt(:SPEE , :WProperty, :spee , \"𝕧\" , u\"m/s\" , \"m/s\" , \"speed\" , false )\n\n# Regular unranked -- \\sans# function names\nmkWhlAmt(:TIME , :WUnranked, :TIME , \"𝗍\" , u\"s\" , \"s\" , \"time\" , false )\nmkWhlAmt(:grav , :WUnranked, :grav , \"𝗀\" , u\"m/s^2\" , \"m/s²\" , \"gravity\" , false )\nmkWhlAmt(:alti , :WUnranked, :alti , \"𝗓\" , u\"m\" , \"m\" , \"altitude\" , false )\n\n\n#----------------------------------------------------------------------------------------------#\n# Based Amount Type Factory #\n#----------------------------------------------------------------------------------------------#\n\n\"\"\"\nBased Amount type factory.\n\"\"\"\nfunction mkBasAmt(TYPE::Symbol, # Type Name: :uAmt\n SUPT::Symbol, # Supertype: :BProperty\n FNAM::Symbol, # Function Name: :u\n SYMB::AbstractString, # Printing symbol: \"U\"\n UNIT::Unitful.Units, # SY quantity units: u\"kJ\"\n USTR::AbstractString, # PrettyPrinting units: \"K\"\n WHAT::AbstractString, # Description: \"internal energy\"\n DELT::Bool=false; # Whether a Δ quantity\n bsym::NTuple{4,Symbol}=(:none,:none,:none,:none)\n )\n # Constants\n uSY = UNIT\n uDT = UNIT / u\"s\"\n uMA = UNIT / u\"kg\"\n uMO = UNIT / u\"kmol\"\n 𝑢SY = typeof(uSY)\n 𝑢DT = typeof(uDT)\n 𝑢MA = typeof(uMA)\n 𝑢MO = typeof(uMO)\n 𝑑SY = dimension(uSY)\n 𝑑DT = dimension(uDT)\n 𝑑MA = dimension(uMA)\n 𝑑MO = dimension(uMO)\n i, f = DELT ? (3, 4) : (1, 2)\n 𝑠SY = bsym[1] == :none ?\n normalize((DELT ? \"Δ\" : \"\") * uppercase(string(SYMB))) :\n string(bsym[1])\n 𝑠DT = bsym[2] == :none ?\n normalize(string(𝑠SY[1:i], \"\\u0307\", 𝑠SY[f:end])) :\n string(bsym[2])\n 𝑠MA = bsym[3] == :none ?\n normalize((DELT ? \"Δ\" : \"\") * lowercase(string(SYMB))) :\n string(bsym[3])\n 𝑠MO = bsym[4] == :none ?\n normalize(string(𝑠MA[1:i], \"\\u0304\", 𝑠MA[f:end])) :\n string(bsym[4])\n # Documentation\n hiStr = tyArchy(eval(SUPT))\n dcStr = \"\"\"\n`struct $TYPE{𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE} <: $SUPT{𝗽,𝘅,𝗯}`\\n\nPrecision-, Exactness-, and Base- parametric $WHAT amounts based in $USTR.\\n\n`$TYPE{𝗽,𝘅,𝗯}` parameters are:\\n\n- Precision `𝗽<:Union{Float16,Float32,Float64,BigFloat}`;\\n\n- Exactness `𝘅<:Union{EX,MM}`, i.e., either a single, precise value or an uncertainty-bearing\n measurement, respectively;\\n\n- Thermodynamic base `𝗯<:Union{SY,DT,MA,MO}` respectively for system, rate, mass, or molar\n quantities, respectively in units of $(uSY), $(uDT), $(uMA), or $(uMO).\\n\nA `$TYPE` can be natively constructed from the following argument types:\\n\n- A plain, unitless float;\\n\n- A plain, unitless `Measurement`; hence, any `AbstractFloat`;\\n\n- A `Quantity{AbstractFloat}` with compatible units.\\n\nConstructors determine parameters from their arguments. `Quantity` constructors do not need a\nbase argument. Plain, `AbstractFloat` ones require the base argument.\\n\n## Hierarchy\\n\n`$(TYPE) <: $(hiStr)`\n \"\"\"\n # @eval block\n @eval begin\n # Concrete type definition\n struct $TYPE{𝗽,𝘅,𝗯} <: $SUPT{𝗽,𝘅,𝗯}\n amt::Union{UATY{𝗽,$𝑑SY,$𝑢SY},UATY{𝗽,$𝑑DT,$𝑢DT},\n UATY{𝗽,$𝑑MA,$𝑢MA},UATY{𝗽,$𝑑MO,$𝑢MO}} where 𝗽<:PREC\n # Inner, non-converting, parameter-determining constructors\n # ---------------------------------------------------------\n # Copy constructor\n $TYPE(x::$TYPE{𝗽,𝘅,𝗯}) where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE} = new{𝗽,𝘅,𝗯}(amt(x))\n # Plain constructors enforce default units & avoid unit conversion\n # Plain Exact (𝗽<:PREC) float constructors\n $TYPE(x::𝗽, ::Type{SY}) where 𝗽<:PREC = new{𝗽,EX,SY}(_qty(x * $uSY))\n $TYPE(x::𝗽, ::Type{DT}) where 𝗽<:PREC = new{𝗽,EX,DT}(_qty(x * $uDT))\n $TYPE(x::𝗽, ::Type{MA}) where 𝗽<:PREC = new{𝗽,EX,MA}(_qty(x * $uMA))\n $TYPE(x::𝗽, ::Type{MO}) where 𝗽<:PREC = new{𝗽,EX,MO}(_qty(x * $uMO))\n # Plain Measurement (PMTY) constructors\n $TYPE(x::PMTY{𝗽}, ::Type{SY}) where 𝗽<:PREC = new{𝗽,MM,SY}(_qty(x * $uSY))\n $TYPE(x::PMTY{𝗽}, ::Type{DT}) where 𝗽<:PREC = new{𝗽,MM,DT}(_qty(x * $uDT))\n $TYPE(x::PMTY{𝗽}, ::Type{MA}) where 𝗽<:PREC = new{𝗽,MM,MA}(_qty(x * $uMA))\n $TYPE(x::PMTY{𝗽}, ::Type{MO}) where 𝗽<:PREC = new{𝗽,MM,MO}(_qty(x * $uMO))\n # Quantity constructors have to perform unit conversion despite matching dimensions\n # United Exact (UETY) constructors\n $TYPE(x::UETY{𝗽,$𝑑SY}) where 𝗽<:PREC = new{𝗽,EX,SY}(_qty(uconvert($uSY, x)))\n $TYPE(x::UETY{𝗽,$𝑑DT}) where 𝗽<:PREC = new{𝗽,EX,DT}(_qty(uconvert($uDT, x)))\n $TYPE(x::UETY{𝗽,$𝑑MA}) where 𝗽<:PREC = new{𝗽,EX,MA}(_qty(uconvert($uMA, x)))\n $TYPE(x::UETY{𝗽,$𝑑MO}) where 𝗽<:PREC = new{𝗽,EX,MO}(_qty(uconvert($uMO, x)))\n # United Measurement (UMTY) constructors\n $TYPE(x::UMTY{𝗽,$𝑑SY}) where 𝗽<:PREC = new{𝗽,MM,SY}(_qty(uconvert($uSY, x)))\n $TYPE(x::UMTY{𝗽,$𝑑DT}) where 𝗽<:PREC = new{𝗽,MM,DT}(_qty(uconvert($uDT, x)))\n $TYPE(x::UMTY{𝗽,$𝑑MA}) where 𝗽<:PREC = new{𝗽,MM,MA}(_qty(uconvert($uMA, x)))\n $TYPE(x::UMTY{𝗽,$𝑑MO}) where 𝗽<:PREC = new{𝗽,MM,MO}(_qty(uconvert($uMO, x)))\n # Inner, non-converting, fully-specified constructors\n # ---------------------------------------------------\n # SY-based constructors\n (::Type{$TYPE{𝗽,EX,SY}})(x::𝗽) where 𝗽<:PREC = begin\n new{𝗽,EX,SY}(_qty( x * $uSY))\n end\n (::Type{$TYPE{𝗽,EX,SY}})(x::PMTY{𝗽}) where 𝗽<:PREC = begin\n new{𝗽,EX,SY}(_qty( x.val * $uSY))\n end\n (::Type{$TYPE{𝗽,MM,SY}})(x::𝗽) where 𝗽<:PREC = begin\n new{𝗽,MM,SY}(_qty(measurement(x) * $uSY))\n end\n (::Type{$TYPE{𝗽,MM,SY}})(x::PMTY{𝗽}) where 𝗽<:PREC = begin\n new{𝗽,MM,SY}(_qty( x * $uSY))\n end\n # DT-based constructors\n (::Type{$TYPE{𝗽,EX,DT}})(x::𝗽) where 𝗽<:PREC = begin\n new{𝗽,EX,DT}(_qty( x * $uDT))\n end\n (::Type{$TYPE{𝗽,EX,DT}})(x::PMTY{𝗽}) where 𝗽<:PREC = begin\n new{𝗽,EX,DT}(_qty( x.val * $uDT))\n end\n (::Type{$TYPE{𝗽,MM,DT}})(x::𝗽) where 𝗽<:PREC = begin\n new{𝗽,MM,DT}(_qty(measurement(x) * $uDT))\n end\n (::Type{$TYPE{𝗽,MM,DT}})(x::PMTY{𝗽}) where 𝗽<:PREC = begin\n new{𝗽,MM,DT}(_qty( x * $uDT))\n end\n # MA-based constructors\n (::Type{$TYPE{𝗽,EX,MA}})(x::𝗽) where 𝗽<:PREC = begin\n new{𝗽,EX,MA}(_qty( x * $uMA))\n end\n (::Type{$TYPE{𝗽,EX,MA}})(x::PMTY{𝗽}) where 𝗽<:PREC = begin\n new{𝗽,EX,MA}(_qty( x.val * $uMA))\n end\n (::Type{$TYPE{𝗽,MM,MA}})(x::𝗽) where 𝗽<:PREC = begin\n new{𝗽,MM,MA}(_qty(measurement(x) * $uMA))\n end\n (::Type{$TYPE{𝗽,MM,MA}})(x::PMTY{𝗽}) where 𝗽<:PREC = begin\n new{𝗽,MM,MA}(_qty( x * $uMA))\n end\n # MO-based constructors\n (::Type{$TYPE{𝗽,EX,MO}})(x::𝗽) where 𝗽<:PREC = begin\n new{𝗽,EX,MO}(_qty( x * $uMO))\n end\n (::Type{$TYPE{𝗽,EX,MO}})(x::PMTY{𝗽}) where 𝗽<:PREC = begin\n new{𝗽,EX,MO}(_qty( x.val * $uMO))\n end\n (::Type{$TYPE{𝗽,MM,MO}})(x::𝗽) where 𝗽<:PREC = begin\n new{𝗽,MM,MO}(_qty(measurement(x) * $uMO))\n end\n (::Type{$TYPE{𝗽,MM,MO}})(x::PMTY{𝗽}) where 𝗽<:PREC = begin\n new{𝗽,MM,MO}(_qty( x * $uMO))\n end\n end\n # Type documentation\n @doc $dcStr $TYPE\n # Precision-changing external constructors\n (::Type{$TYPE{𝘀}})(x::$TYPE{𝗽,EX,𝗯}) where {𝘀<:PREC,𝗽<:PREC,𝗯<:BASE} = begin\n $TYPE(𝘀(amt(x).val), 𝗯)\n end\n (::Type{$TYPE{𝘀}})(x::$TYPE{𝗽,MM,𝗯}) where {𝘀<:PREC,𝗽<:PREC,𝗯<:BASE} = begin\n $TYPE(Measurement{𝘀}(amt(x).val), 𝗯)\n end\n # Precision+Exactness-changing external constructors\n (::Type{$TYPE{𝘀,EX}})(x::$TYPE{𝗽,EX,𝗯}) where {𝘀<:PREC,𝗽<:PREC,𝗯<:BASE} = begin\n $TYPE(𝘀(amt(x).val), 𝗯)\n end\n (::Type{$TYPE{𝘀,EX}})(x::$TYPE{𝗽,MM,𝗯}) where {𝘀<:PREC,𝗽<:PREC,𝗯<:BASE} = begin\n $TYPE(𝘀(amt(x).val.val), 𝗯)\n end\n (::Type{$TYPE{𝘀,MM}})(x::$TYPE{𝗽,EX,𝗯},\n e::𝘀=𝘀(max(eps(𝘀),eps(amt(x).val)))\n ) where {𝘀<:PREC,𝗽<:PREC,𝗯<:BASE} = begin\n $TYPE(measurement(𝘀(amt(x).val), e), 𝗯)\n end\n (::Type{$TYPE{𝘀,MM}})(x::$TYPE{𝗽,MM,𝗯}) where {𝘀<:PREC,𝗽<:PREC,𝗯<:BASE} = begin\n $TYPE(Measurement{𝘀}(amt(x).val), 𝗯)\n end\n # Type export\n export $TYPE\n # Type-stable wrapped amount obtaining function\n amt(x::$TYPE{𝗽,EX,SY}) where 𝗽<:PREC = x.amt::Quantity{𝗽,$𝑑SY,$𝑢SY}\n amt(x::$TYPE{𝗽,EX,DT}) where 𝗽<:PREC = x.amt::Quantity{𝗽,$𝑑DT,$𝑢DT}\n amt(x::$TYPE{𝗽,EX,MA}) where 𝗽<:PREC = x.amt::Quantity{𝗽,$𝑑MA,$𝑢MA}\n amt(x::$TYPE{𝗽,EX,MO}) where 𝗽<:PREC = x.amt::Quantity{𝗽,$𝑑MO,$𝑢MO}\n amt(x::$TYPE{𝗽,MM,SY}) where 𝗽<:PREC = x.amt::Quantity{Measurement{𝗽},$𝑑SY,$𝑢SY}\n amt(x::$TYPE{𝗽,MM,DT}) where 𝗽<:PREC = x.amt::Quantity{Measurement{𝗽},$𝑑DT,$𝑢DT}\n amt(x::$TYPE{𝗽,MM,MA}) where 𝗽<:PREC = x.amt::Quantity{Measurement{𝗽},$𝑑MA,$𝑢MA}\n amt(x::$TYPE{𝗽,MM,MO}) where 𝗽<:PREC = x.amt::Quantity{Measurement{𝗽},$𝑑MO,$𝑢MO}\n # Type-specific functions\n deco(x::$TYPE{𝗽,𝘅,SY} where {𝗽,𝘅}) = Symbol($𝑠SY)\n deco(x::$TYPE{𝗽,𝘅,DT} where {𝗽,𝘅}) = Symbol($𝑠DT)\n deco(x::$TYPE{𝗽,𝘅,MA} where {𝗽,𝘅}) = Symbol($𝑠MA)\n deco(x::$TYPE{𝗽,𝘅,MO} where {𝗽,𝘅}) = Symbol($𝑠MO)\n ppu(x::$TYPE{𝗽,𝘅,SY} where {𝗽,𝘅}) = $USTR\n ppu(x::$TYPE{𝗽,𝘅,DT} where {𝗽,𝘅}) = $USTR * \"/s\"\n ppu(x::$TYPE{𝗽,𝘅,MA} where {𝗽,𝘅}) = $USTR * \"/kg\"\n ppu(x::$TYPE{𝗽,𝘅,MO} where {𝗽,𝘅}) = $USTR * \"/kmol\"\n # Indirect construction from plain\n $FNAM(x::plnF, b::Type{𝗯}=DEF[:IB]) where 𝗯<:BASE = $TYPE(x, b)\n $FNAM(x::REAL, b::Type{𝗯}=DEF[:IB]) where 𝗯<:BASE = $TYPE(float(x), b)\n # Indirect construction from quantity\n $FNAM(x::Union{UATY{𝗽,$𝑑SY},UATY{𝗽,$𝑑DT},\n UATY{𝗽,$𝑑MA},UATY{𝗽,$𝑑MO}}) where 𝗽<:PREC = begin\n $TYPE(x)\n end\n $FNAM(x::Union{uniR{𝗽,$𝑑SY},uniR{𝗽,$𝑑DT},\n uniR{𝗽,$𝑑MA},uniR{𝗽,$𝑑MO}}) where 𝗽<:REAL = begin\n $TYPE(float(x.val) * unit(x))\n end\n export $FNAM\n # Conversions - Change of base is _not_ a conversion\n # Same {EXAC,BASE}, {PREC}- conversion\n convert(::Type{$TYPE{𝘀,𝘅,𝗯}},\n y::$TYPE{𝗽,𝘅,𝗯}) where {𝘀<:PREC,𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE} = begin\n $TYPE{promote_type(𝘀,𝗽),𝘅}(y)\n end\n # Same {BASE}, {PREC,EXAC}- conversion\n convert(::Type{$TYPE{𝘀,𝘆,𝗯}},\n y::$TYPE{𝗽,𝘅,𝗯}) where {𝘀<:PREC,𝗽<:PREC,𝘆<:EXAC,𝘅<:EXAC,𝗯<:BASE} = begin\n $TYPE{promote_type(𝘀,𝗽),promote_type(𝘆,𝘅)}(y)\n end\n # Promotion rules\n promote_rule(::Type{$TYPE{𝘀,𝘆,𝗯}},\n ::Type{$TYPE{𝗽,𝘅,𝗯}}) where {𝘀<:PREC,𝗽<:PREC,\n 𝘆<:EXAC,𝘅<:EXAC,𝗯<:BASE} = begin\n $TYPE{promote_type(𝘀,𝗽),promote_type(𝘆,𝘅),𝗯}\n end\n # same-type sum,sub with Unitful promotion\n +(x::$TYPE{𝘀,𝘆,𝗯}, y::$TYPE{𝗽,𝘅,𝗯}) where {𝘀<:PREC,𝗽<:PREC,\n 𝘆<:EXAC,𝘅<:EXAC,\n 𝗯<:BASE} = begin\n $TYPE(+(amt(x), amt(y)))\n end\n -(x::$TYPE{𝘀,𝘆,𝗯}, y::$TYPE{𝗽,𝘅,𝗯}) where {𝘀<:PREC,𝗽<:PREC,\n 𝘆<:EXAC,𝘅<:EXAC,\n 𝗯<:BASE} = begin\n $TYPE(-(amt(x), amt(y)))\n end\n # scalar mul,div with Unitful promotion\n *(y::plnF{𝘀}, x::$TYPE{𝗽}) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(*(amt(x), y))\n *(x::$TYPE{𝗽}, y::plnF{𝘀}) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(*(amt(x), y))\n /(x::$TYPE{𝗽}, y::plnF{𝘀}) where {𝘀<:PREC,𝗽<:PREC} = $TYPE(/(amt(x), y))\n # Type-preserving scalar mul,div\n *(y::REAL, x::$TYPE{𝗽}) where 𝗽<:PREC = $TYPE(*(amt(x), 𝗽(y)))\n *(x::$TYPE{𝗽}, y::REAL) where 𝗽<:PREC = $TYPE(*(amt(x), 𝗽(y)))\n /(x::$TYPE{𝗽}, y::REAL) where 𝗽<:PREC = $TYPE(/(amt(x), 𝗽(y)))\n end\nend\n\n\n#----------------------------------------------------------------------------------------------#\n# Thermodynamic Amount Group Declarations #\n#----------------------------------------------------------------------------------------------#\n\n# Mass / Mass fraction anomalous\nmkBasAmt(:mAmt , :BProperty, :m , \"m\" , u\"kg\" , \"kg\" , \"mass\" , false , bsym=(:m , :ṁ , :mf, :M))\n# Chemical amount / Molar fraction anomalous\nmkBasAmt(:nAmt , :BProperty, :N , \"N\" , u\"kmol\" , \"kmol\" , \"chemical amount\" , false , bsym=(:N , :Ṅ , :n , :y))\n# Gas constant / System constant anomalous\nmkBasAmt(:RAmt , :BProperty, :R , \"mR\" , u\"kJ/K\" , \"kJ/K\" , \"gas constant\" , false , bsym=(:mR, :ṁR, :R , :R̄))\n# Plank function anomalous\nmkBasAmt(:rAmt , :BProperty, :r , \"mr\" , u\"kJ/K\" , \"kJ/K\" , \"Planck function\" , false , bsym=(:mr, :ṁr, :r , :r̄))\n\n# Regular properties\nmkBasAmt(:vAmt , :BProperty, :v , \"V\" , u\"m^3\" , \"m³\" , \"volume\" , false )\nmkBasAmt(:uAmt , :BProperty, :u , \"U\" , u\"kJ\" , \"kJ\" , \"internal energy\" , false )\nmkBasAmt(:hAmt , :BProperty, :h , \"H\" , u\"kJ\" , \"kJ\" , \"enthalpy\" , false )\nmkBasAmt(:gAmt , :BProperty, :g , \"G\" , u\"kJ\" , \"kJ\" , \"Gibbs energy\" , false )\nmkBasAmt(:aAmt , :BProperty, :a , \"A\" , u\"kJ\" , \"kJ\" , \"Helmholtz energy\" , false )\nmkBasAmt(:eAmt , :BProperty, :e , \"E\" , u\"kJ\" , \"kJ\" , \"total energy\" , false )\nmkBasAmt(:ekAmt , :BProperty, :ek , \"Ek\" , u\"kJ\" , \"kJ\" , \"kinetic energy\" , false )\nmkBasAmt(:epAmt , :BProperty, :ep , \"Ep\" , u\"kJ\" , \"kJ\" , \"potential energy\" , false )\nmkBasAmt(:sAmt , :BProperty, :s , \"S\" , u\"kJ/K\" , \"kJ/K\" , \"entropy\" , false )\nmkBasAmt(:cpAmt , :BProperty, :cp , \"Cp\" , u\"kJ/K\" , \"kJ/K\" , \"iso-P specific heat\" , false )\nmkBasAmt(:cvAmt , :BProperty, :cv , \"Cv\" , u\"kJ/K\" , \"kJ/K\" , \"iso-v specific heat\" , false )\nmkBasAmt(:jAmt , :BProperty, :j , \"J\" , u\"kJ/K\" , \"kJ/K\" , \"Massieu function\" , false )\n\n# Regular interactions\nmkBasAmt(:qAmt , :BInteract, :q , \"Q\" , u\"kJ\" , \"kJ\" , \"heat\" , false )\nmkBasAmt(:wAmt , :BInteract, :w , \"W\" , u\"kJ\" , \"kJ\" , \"work\" , false )\nmkBasAmt(:ΔeAmt , :BInteract, :Δe , \"E\" , u\"kJ\" , \"kJ\" , \"energy variation\" , true )\nmkBasAmt(:ΔsAmt , :BInteract, :Δs , \"S\" , u\"kJ/K\" , \"kJ/K\" , \"entropy variation\" , true )\n\n\n#----------------------------------------------------------------------------------------------#\n# AMOUNT Type Unions #\n#----------------------------------------------------------------------------------------------#\n\n# Unions of amounts of like units and thermodynamic classification, for same-unit operations\n\n# --- energy\n\"\"\"\n`ENERGYP{𝗽,𝘅,𝗯} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}`\\n\nEnergy property type union.\n\"\"\"\nENERGYP{𝗽,𝘅,𝗯} = Union{uAmt{𝗽,𝘅,𝗯},hAmt{𝗽,𝘅,𝗯},\n gAmt{𝗽,𝘅,𝗯},aAmt{𝗽,𝘅,𝗯},\n eAmt{𝗽,𝘅,𝗯},ekAmt{𝗽,𝘅,𝗯},\n epAmt{𝗽,𝘅,𝗯}} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}\n\n\"\"\"\n`ENERGYI{𝗽,𝘅,𝗯} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}`\\n\nEnergy interaction type union.\n\"\"\"\nENERGYI{𝗽,𝘅,𝗯} = Union{qAmt{𝗽,𝘅,𝗯},wAmt{𝗽,𝘅,𝗯},\n ΔeAmt{𝗽,𝘅,𝗯}} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}\n\n\"\"\"\n`ENERGYA{𝗽,𝘅,𝗯} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}`\\n\nEnergy amount type union.\n\"\"\"\nENERGYA{𝗽,𝘅,𝗯} = Union{ENERGYP{𝗽,𝘅,𝗯},ENERGYI{𝗽,𝘅,𝗯}} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}\n\n\n# --- entropy\n\"\"\"\n`NTROPYP{𝗽,𝘅,𝗯} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}`\\n\nEntropy property type union.\n\"\"\"\nNTROPYP{𝗽,𝘅,𝗯} = Union{RAmt{𝗽,𝘅,𝗯},rAmt{𝗽,𝘅,𝗯},\n sAmt{𝗽,𝘅,𝗯},jAmt{𝗽,𝘅,𝗯},\n cpAmt{𝗽,𝘅,𝗯},cvAmt{𝗽,𝘅,𝗯}} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}\n\n\"\"\"\n`NTROPYI{𝗽,𝘅,𝗯} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}`\\n\nEntropy interaction type union.\n\"\"\"\nNTROPYI{𝗽,𝘅,𝗯} = Union{ΔsAmt{𝗽,𝘅,𝗯}} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}\n\n\"\"\"\n`NTROPYA{𝗽,𝘅,𝗯} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}`\\n\nEntropy amount type union.\n\"\"\"\nNTROPYA{𝗽,𝘅,𝗯} = Union{NTROPYP{𝗽,𝘅,𝗯},NTROPYI{𝗽,𝘅,𝗯}} where {𝗽<:PREC,𝘅<:EXAC,𝗯<:BASE}\n\n\n# --- velocity\n\"\"\"\n`VELOCYP{𝗽,𝘅} where {𝗽<:PREC,𝘅<:EXAC}`\\n\nVelocity property type union.\n\"\"\"\nVELOCYP{𝗽,𝘅,𝗯} = Union{VELO{𝗽,𝘅},SPEE{𝗽,𝘅}} where {𝗽<:PREC,𝘅<:EXAC}\n\n\n#----------------------------------------------------------------------------------------------#\n# Pretty Printing #\n#----------------------------------------------------------------------------------------------#\n\nimport Base: show\nimport Formatting: sprintf1\n\n# Auxiliar method\nfunction subscript(x::Int)\n asSub(c::Char) = Char(Int(c) - Int('0') + Int('₀'))\n map(asSub, \"$(x)\")\nend\n\n# Precision decoration\npDeco(::Type{Float16}) = DEF[:showPrec] ? subscript(16) : \"\"\npDeco(::Type{Float32}) = DEF[:showPrec] ? subscript(32) : \"\"\npDeco(::Type{Float64}) = DEF[:showPrec] ? subscript(64) : \"\"\npDeco(::Type{BigFloat}) = DEF[:showPrec] ? subscript(precision(BigFloat)) : \"\"\n\n# Custom printing\nBase.show(io::IO, x::AMOUNTS{𝗽,EX}) where 𝗽<:PREC = begin\n if DEF[:pprint]\n print(io,\n \"$(string(deco(x)))$(pDeco(𝗽)): \",\n sprintf1(\"%.$(DEF[:showSigD])g\", amt(x).val),\n \" \", ppu(x))\n else\n Base.show_default(io, x)\n end\nend\n\nBase.show(io::IO, x::AMOUNTS{𝗽,MM}) where 𝗽<:PREC = begin\n if DEF[:pprint]\n print(io,\n \"$(string(deco(x)))$(pDeco(𝗽)): (\",\n sprintf1(\"%.$(DEF[:showSigD])g\", amt(x).val.val),\n \" ± \",\n sprintf1(\"%.2g\", amt(x).val.err),\n \") \", ppu(x))\n else\n Base.show_default(io, x)\n end\nend\n\n\n", "meta": {"hexsha": "7d8153c668e66c752f9fb76c7174225128e0619b", "size": 32902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/amounts.jl", "max_stars_repo_name": "jengtherm/EngThermBase.jl", "max_stars_repo_head_hexsha": "e2174cf074f63f335c72d776ab60a17f1d4cdc1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/amounts.jl", "max_issues_repo_name": "jengtherm/EngThermBase.jl", "max_issues_repo_head_hexsha": "e2174cf074f63f335c72d776ab60a17f1d4cdc1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amounts.jl", "max_forks_repo_name": "jengtherm/EngThermBase.jl", "max_forks_repo_head_hexsha": "e2174cf074f63f335c72d776ab60a17f1d4cdc1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-12T17:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T17:50:32.000Z", "avg_line_length": 47.409221902, "max_line_length": 133, "alphanum_fraction": 0.4673576074, "num_tokens": 12541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24993408376257828}} {"text": "\nfunction create_cache_analysis(analyzer, mesh::TreeMesh{3},\n equations, dg::DG, cache,\n RealT, uEltype)\n\n # pre-allocate buffers\n # We use `StrideArray`s here since these buffers are used in performance-critical\n # places and the additional information passed to the compiler makes them faster\n # than native `Array`s.\n u_local = StrideArray(undef, uEltype,\n StaticInt(nvariables(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)))\n u_tmp1 = StrideArray(undef, uEltype,\n StaticInt(nvariables(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)), StaticInt(nnodes(dg)))\n u_tmp2 = StrideArray(undef, uEltype,\n StaticInt(nvariables(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)))\n x_local = StrideArray(undef, RealT,\n StaticInt(ndims(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)))\n x_tmp1 = StrideArray(undef, RealT,\n StaticInt(ndims(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)), StaticInt(nnodes(dg)))\n x_tmp2 = StrideArray(undef, RealT,\n StaticInt(ndims(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)))\n\n return (; u_local, u_tmp1, u_tmp2, x_local, x_tmp1, x_tmp2)\nend\n\n\nfunction create_cache_analysis(analyzer, mesh::CurvedMesh{3},\n equations, dg::DG, cache,\n RealT, uEltype)\n\n # pre-allocate buffers\n # We use `StrideArray`s here since these buffers are used in performance-critical\n # places and the additional information passed to the compiler makes them faster\n # than native `Array`s.\n u_local = StrideArray(undef, uEltype,\n StaticInt(nvariables(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)))\n u_tmp1 = StrideArray(undef, uEltype,\n StaticInt(nvariables(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)), StaticInt(nnodes(dg)))\n u_tmp2 = StrideArray(undef, uEltype,\n StaticInt(nvariables(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)))\n x_local = StrideArray(undef, RealT,\n StaticInt(ndims(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)))\n x_tmp1 = StrideArray(undef, RealT,\n StaticInt(ndims(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)), StaticInt(nnodes(dg)))\n x_tmp2 = StrideArray(undef, RealT,\n StaticInt(ndims(equations)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)))\n jacobian_local = StrideArray(undef, RealT,\n StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)))\n jacobian_tmp1 = StrideArray(undef, RealT,\n StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)), StaticInt(nnodes(dg)))\n jacobian_tmp2 = StrideArray(undef, RealT,\n StaticInt(nnodes(analyzer)), StaticInt(nnodes(analyzer)), StaticInt(nnodes(dg)))\n\n return (; u_local, u_tmp1, u_tmp2, x_local, x_tmp1, x_tmp2, jacobian_local, jacobian_tmp1, jacobian_tmp2)\nend\n\n\nfunction calc_error_norms(func, u, t, analyzer,\n mesh::TreeMesh{3}, equations, initial_condition,\n dg::DGSEM, cache, cache_analysis)\n @unpack vandermonde, weights = analyzer\n @unpack node_coordinates = cache.elements\n @unpack u_local, u_tmp1, u_tmp2, x_local, x_tmp1, x_tmp2 = cache_analysis\n\n # Set up data structures\n l2_error = zero(func(get_node_vars(u, equations, dg, 1, 1, 1, 1), equations))\n linf_error = copy(l2_error)\n\n # Iterate over all elements for error calculations\n for element in eachelement(dg, cache)\n # Interpolate solution and node locations to analysis nodes\n multiply_dimensionwise!(u_local, vandermonde, view(u, :, :, :, :, element), u_tmp1, u_tmp2)\n multiply_dimensionwise!(x_local, vandermonde, view(node_coordinates, :, :, :, :, element), x_tmp1, x_tmp2)\n\n # Calculate errors at each analysis node\n volume_jacobian_ = volume_jacobian(element, mesh, cache)\n\n for k in eachnode(analyzer), j in eachnode(analyzer), i in eachnode(analyzer)\n u_exact = initial_condition(get_node_coords(x_local, equations, dg, i, j, k), t, equations)\n diff = func(u_exact, equations) - func(get_node_vars(u_local, equations, dg, i, j, k), equations)\n l2_error += diff.^2 * (weights[i] * weights[j] * weights[k] * volume_jacobian_)\n linf_error = @. max(linf_error, abs(diff))\n end\n end\n\n # For L2 error, divide by total volume\n total_volume_ = total_volume(mesh)\n l2_error = @. sqrt(l2_error / total_volume_)\n\n return l2_error, linf_error\nend\n\n\nfunction calc_error_norms(func, u, t, analyzer,\n mesh::CurvedMesh{3}, equations, initial_condition,\n dg::DGSEM, cache, cache_analysis)\n @unpack vandermonde, weights = analyzer\n @unpack node_coordinates, inverse_jacobian = cache.elements\n @unpack u_local, u_tmp1, u_tmp2, x_local, x_tmp1, x_tmp2, jacobian_local, jacobian_tmp1, jacobian_tmp2 = cache_analysis\n\n # Set up data structures\n l2_error = zero(func(get_node_vars(u, equations, dg, 1, 1, 1, 1), equations))\n linf_error = copy(l2_error)\n total_volume = zero(real(mesh))\n\n # Iterate over all elements for error calculations\n for element in eachelement(dg, cache)\n # Interpolate solution and node locations to analysis nodes\n multiply_dimensionwise!(u_local, vandermonde, view(u, :, :, :, :, element), u_tmp1, u_tmp2)\n multiply_dimensionwise!(x_local, vandermonde, view(node_coordinates, :, :, :, :, element), x_tmp1, x_tmp2)\n multiply_scalar_dimensionwise!(jacobian_local, vandermonde, inv.(view(inverse_jacobian, :, :, :, element)), jacobian_tmp1, jacobian_tmp2)\n\n # Calculate errors at each analysis node\n @. jacobian_local = abs(jacobian_local)\n\n for k in eachnode(analyzer), j in eachnode(analyzer), i in eachnode(analyzer)\n u_exact = initial_condition(get_node_coords(x_local, equations, dg, i, j, k), t, equations)\n diff = func(u_exact, equations) - func(get_node_vars(u_local, equations, dg, i, j, k), equations)\n l2_error += diff.^2 * (weights[i] * weights[j] * weights[k] * jacobian_local[i, j, k])\n linf_error = @. max(linf_error, abs(diff))\n total_volume += weights[i] * weights[j] * weights[k] * jacobian_local[i, j, k]\n end\n end\n\n # For L2 error, divide by total volume\n l2_error = @. sqrt(l2_error / total_volume)\n\n return l2_error, linf_error\nend\n\n\nfunction integrate_via_indices(func::Func, u,\n mesh::TreeMesh{3}, equations, dg::DGSEM, cache,\n args...; normalize=true) where {Func}\n @unpack weights = dg.basis\n\n # Initialize integral with zeros of the right shape\n integral = zero(func(u, 1, 1, 1, 1, equations, dg, args...))\n\n # Use quadrature to numerically integrate over entire domain\n for element in eachelement(dg, cache)\n volume_jacobian_ = volume_jacobian(element, mesh, cache)\n for k in eachnode(dg), j in eachnode(dg), i in eachnode(dg)\n integral += volume_jacobian_ * weights[i] * weights[j] * weights[k] * func(u, i, j, k, element, equations, dg, args...)\n end\n end\n\n # Normalize with total volume\n if normalize\n integral = integral / total_volume(mesh)\n end\n\n return integral\nend\n\n\nfunction integrate_via_indices(func::Func, u,\n mesh::CurvedMesh{3}, equations, dg::DGSEM, cache,\n args...; normalize=true) where {Func}\n @unpack weights = dg.basis\n\n # Initialize integral with zeros of the right shape\n integral = zero(func(u, 1, 1, 1, 1, equations, dg, args...))\n total_volume = zero(real(mesh))\n\n # Use quadrature to numerically integrate over entire domain\n for element in eachelement(dg, cache)\n for k in eachnode(dg), j in eachnode(dg), i in eachnode(dg)\n volume_jacobian = abs(inv(cache.elements.inverse_jacobian[i, j, k, element]))\n integral += volume_jacobian * weights[i] * weights[j] * weights[k] * func(u, i, j, k, element, equations, dg, args...)\n total_volume += volume_jacobian * weights[i] * weights[j] * weights[k]\n end\n end\n\n # Normalize with total volume\n if normalize\n integral = integral / total_volume\n end\n\n return integral\nend\n\n\nfunction integrate(func::Func, u,\n mesh::Union{TreeMesh{3},CurvedMesh{3}},\n equations, dg::DGSEM, cache; normalize=true) where {Func}\n integrate_via_indices(u, mesh, equations, dg, cache; normalize=normalize) do u, i, j, k, element, equations, dg\n u_local = get_node_vars(u, equations, dg, i, j, k, element)\n return func(u_local, equations)\n end\nend\n\n\nfunction analyze(::typeof(entropy_timederivative), du, u, t,\n mesh::Union{TreeMesh{3},CurvedMesh{3}}, equations, dg::DG, cache)\n # Calculate ∫(∂S/∂u ⋅ ∂u/∂t)dΩ\n integrate_via_indices(u, mesh, equations, dg, cache, du) do u, i, j, k, element, equations, dg, du\n u_node = get_node_vars(u, equations, dg, i, j, k, element)\n du_node = get_node_vars(du, equations, dg, i, j, k, element)\n dot(cons2entropy(u_node, equations), du_node)\n end\nend\n\n\n\nfunction analyze(::Val{:l2_divb}, du, u, t,\n mesh::TreeMesh{3}, equations::IdealGlmMhdEquations3D,\n dg::DG, cache)\n integrate_via_indices(u, mesh, equations, dg, cache, cache, dg.basis.derivative_matrix) do u, i, j, k, element, equations, dg, cache, derivative_matrix\n divb = zero(eltype(u))\n for l in eachnode(dg)\n divb += ( derivative_matrix[i, l] * u[6, l, j, k, element] +\n derivative_matrix[j, l] * u[7, i, l, k, element] +\n derivative_matrix[k, l] * u[7, i, j, l, element] )\n end\n divb *= cache.elements.inverse_jacobian[element]\n divb^2\n end |> sqrt\nend\n\nfunction analyze(::Val{:linf_divb}, du, u, t,\n mesh::TreeMesh{3}, equations::IdealGlmMhdEquations3D,\n dg::DG, cache)\n @unpack derivative_matrix, weights = dg.basis\n\n # integrate over all elements to get the divergence-free condition errors\n linf_divb = zero(eltype(u))\n for element in eachelement(dg, cache)\n for k in eachnode(dg), j in eachnode(dg), i in eachnode(dg)\n divb = zero(eltype(u))\n for l in eachnode(dg)\n divb += ( derivative_matrix[i, l] * u[6, l, j, k, element] +\n derivative_matrix[j, l] * u[7, i, l, k, element] +\n derivative_matrix[k, l] * u[7, i, j, l, element] )\n end\n divb *= cache.elements.inverse_jacobian[element]\n linf_divb = max(linf_divb, abs(divb))\n end\n end\n\n return linf_divb\nend\n", "meta": {"hexsha": "7fcd970667cc54f33229bb7c5adb0c6a203ee998", "size": 11077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/callbacks_step/analysis_dg3d.jl", "max_stars_repo_name": "JuliaOd/Trixi.jl", "max_stars_repo_head_hexsha": "2b93858cef54772c99cc7818ceefd624b4a4e0a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-13T11:10:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T11:10:53.000Z", "max_issues_repo_path": "src/callbacks_step/analysis_dg3d.jl", "max_issues_repo_name": "JuliaOd/Trixi.jl", "max_issues_repo_head_hexsha": "2b93858cef54772c99cc7818ceefd624b4a4e0a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/callbacks_step/analysis_dg3d.jl", "max_forks_repo_name": "JuliaOd/Trixi.jl", "max_forks_repo_head_hexsha": "2b93858cef54772c99cc7818ceefd624b4a4e0a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-23T09:45:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T09:46:17.000Z", "avg_line_length": 45.5843621399, "max_line_length": 153, "alphanum_fraction": 0.6571273811, "num_tokens": 3002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24993407701023118}} {"text": "# Data tables from the specificatioms\n\n\"\"\"\nAllowed characters for `Alphanumeric()` mode and their number.\n\"\"\"\nconst alphanumeric = Dict{AbstractChar, Int64}(\n zip(vcat('0':'9', 'A':'Z', collect(\" %*+-./:\\$\")), 0:44))\n\n\"\"\"\nNumber of characters allowed for a given mode, error correction level and\nversion.\n\"\"\"\nconst characterscapacity = Dict{Tuple{ErrCorrLevel, Mode}, Array{Int64, 1}}(\n (Low(), Numeric()) =>\n [41, 77, 127, 187, 255, 322, 370, 461, 552, 652, 772, 883, 1022, 1101,\n 1250, 1408, 1548, 1725, 1903, 2061, 2232, 2409, 2620, 2812, 3057, 3283,\n 3517, 3669, 3909, 4158, 4417, 4686, 4965, 5253, 5529, 5836, 6153, 6479,\n 6743, 7089]\n , (Low(), Alphanumeric()) =>\n [25, 47, 77, 114, 154, 195, 224, 279, 335, 395, 468, 535, 619, 667, 758,\n 854, 938, 1046, 1153, 1249, 1352, 1460, 1588, 1704, 1853, 1990, 2132,\n 2223, 2369, 2520, 2677, 2840, 3009, 3183, 3351, 3537, 3729, 3927, 4087,\n 4296]\n , (Low(), Byte()) =>\n [17, 32, 53, 78, 106, 134, 154, 192, 230, 271, 321, 367, 425, 458, 520,\n 586, 644, 718, 792, 858, 929, 1003, 1091, 1171, 1273, 1367, 1465, 1528,\n 1628, 1732, 1840, 1952, 2068, 2188, 2303, 2431, 2563, 2699, 2809, 2953]\n , (Medium(), Numeric()) =>\n [34, 63, 101, 149, 202, 255, 293, 365, 432, 513, 604, 691, 796, 871,\n 991, 1082, 1212, 1346, 1500, 1600, 1708, 1872, 2059, 2188, 2395, 2544,\n 2701, 2857, 3035, 3289, 3486, 3693, 3909, 4134, 4343, 4588, 4775, 5039,\n 5313, 5596]\n , (Medium(), Alphanumeric()) =>\n [20, 38, 61, 90, 122, 154, 178, 221, 262, 311, 366, 419, 483, 528, 600,\n 656, 734, 816, 909, 970, 1035, 1134, 1248, 1326, 1451, 1542, 1637,\n 1732, 1839, 1994, 2113, 2238, 2369, 2506, 2632, 2780, 2894, 3054, 3220,\n 3391]\n , (Medium(), Byte()) =>\n [14, 26, 42, 62, 84, 106, 122, 152, 180, 213, 251, 287, 331, 362, 412,\n 450, 504, 560, 624, 666, 711, 779, 857, 911, 997, 1059, 1125, 1190,\n 1264, 1370, 1452, 1538, 1628, 1722, 1809, 1911, 1989, 2099, 2213, 2331]\n , (Quartile(), Numeric()) =>\n [27, 48, 77, 111, 144, 178, 207, 259, 312, 364, 427, 489, 580, 621, 703,\n 775, 876, 948, 1063, 1159, 1224, 1358, 1468, 1588, 1718, 1804, 1933,\n 2085, 2181, 2358, 2473, 2670, 2805, 2949, 3081, 3244, 3417, 3599, 3791,\n 3993]\n , (Quartile(), Alphanumeric()) =>\n [16, 29, 47, 67, 87, 108, 125, 157, 189, 221, 259, 296, 352, 376, 426,\n 470, 531, 574, 644, 702, 742, 823, 890, 963, 1041, 1094, 1172, 1263,\n 1322, 1429, 1499, 1618, 1700, 1787, 1867, 1966, 2071, 2181, 2298, 2420]\n , (Quartile(), Byte()) =>\n [11, 20, 32, 46, 60, 74, 86, 108, 130, 151, 177, 203, 241, 258, 292,\n 322, 364, 394, 442, 482, 509, 565, 611, 661, 715, 751, 805, 868, 908,\n 982, 1030, 1112, 1168, 1228, 1283, 1351, 1423, 1499, 1579, 1663]\n , (High(), Numeric()) =>\n [17, 34, 58, 82, 106, 139, 154, 202, 235, 288, 331, 374, 427, 468, 530,\n 602, 674, 746, 813, 919, 969, 1056, 1108, 1228, 1286, 1425, 1501, 1581,\n 1677, 1782, 1897, 2022, 2157, 2301, 2361, 2524, 2625, 2735, 2927, 3057]\n , (High(), Alphanumeric()) =>\n [10, 20, 35, 50, 64, 84, 93, 122, 143, 174, 200, 227, 259, 283, 321,\n 365, 408, 452, 493, 557, 587, 640, 672, 744, 779, 864, 910, 958, 1016,\n 1080, 1150, 1226, 1307, 1394, 1431, 1530, 1591, 1658, 1774, 1852]\n , (High(), Byte()) =>\n [7, 14, 24, 34, 44, 58, 64, 84, 98, 119, 137, 155, 177, 194, 220, 250,\n 280, 310, 338, 382, 403, 439, 461, 511, 535, 593, 625, 658, 698, 742,\n 790, 842, 898, 958, 983, 1051, 1093, 1139, 1219, 1273]\n )\n\n\"\"\"\nMode indicators.\n\"\"\"\nconst modeindicators = Dict{Mode, BitArray{1}}(\n Numeric() => BitArray([0, 0, 0, 1])\n , Alphanumeric() => BitArray([0, 0, 1, 0])\n , Byte() => BitArray([0, 1, 0, 0])\n )\n\n\"\"\"\nCharacter count length for different mode and version groups.\n\"\"\"\nconst charactercountlength = Dict{Mode, Array{Int64, 1}}(\n Numeric() => [10, 12, 14]\n , Alphanumeric() => [9, 11, 13]\n , Byte() => [8, 16, 16]\n )\n\n\"\"\"\nInformation about the error correction codeblocks per level and version.\n\"\"\"\nconst ecblockinfo = Dict{ErrCorrLevel,Array{Int64,2}}(\n Low() =>\n [7 1 19 0 0; 10 1 34 0 0; 15 1 55 0 0; 20 1 80 0 0; 26 1 108 0 0;\n 18 2 68 0 0; 20 2 78 0 0; 24 2 97 0 0; 30 2 116 0 0; 18 2 68 2 69;\n 20 4 81 0 0; 24 2 92 2 93; 26 4 107 0 0; 30 3 115 1 116; 22 5 87 1 88;\n 24 5 98 1 99; 28 1 107 5 108; 30 5 120 1 121; 28 3 113 4 114;\n 28 3 107 5 108; 28 4 116 4 117; 28 2 111 7 112; 30 4 121 5 122;\n 30 6 117 4 118; 26 8 106 4 107; 28 10 114 2 115; 30 8 122 4 123;\n 30 3 117 10 118; 30 7 116 7 117; 30 5 115 10 116; 30 13 115 3 116;\n 30 17 115 0 0; 30 17 115 1 116; 30 13 115 6 116; 30 12 121 7 122;\n 30 6 121 14 122; 30 17 122 4 123; 30 4 122 18 123; 30 20 117 4 118;\n 30 19 118 6 119]\n , Medium() =>\n [10 1 16 0 0; 16 1 28 0 0; 26 1 44 0 0; 18 2 32 0 0; 24 2 43 0 0;\n 16 4 27 0 0; 18 4 31 0 0; 22 2 38 2 39; 22 3 36 2 37; 26 4 43 1 44;\n 30 1 50 4 51; 22 6 36 2 37; 22 8 37 1 38; 24 4 40 5 41; 24 5 41 5 42;\n 28 7 45 3 46; 28 10 46 1 47; 26 9 43 4 44; 26 3 44 11 45; 26 3 41 13 42;\n 26 17 42 0 0; 28 17 46 0 0; 28 4 47 14 48; 28 6 45 14 46; 28 8 47 13 48;\n 28 19 46 4 47; 28 22 45 3 46; 28 3 45 23 46; 28 21 45 7 46; 28 19 47 10 48;\n 28 2 46 29 47; 28 10 46 23 47; 28 14 46 21 47; 28 14 46 23 47;\n 28 12 47 26 48; 28 6 47 34 48; 28 29 46 14 47; 28 13 46 32 47;\n 28 40 47 7 48; 28 18 47 31 48]\n , Quartile() =>\n [13 1 13 0 0; 22 1 22 0 0; 18 2 17 0 0; 26 2 24 0 0; 18 2 15 2 16;\n 24 4 19 0 0; 18 2 14 4 15; 22 4 18 2 19; 20 4 16 4 17; 24 6 19 2 20;\n 28 4 22 4 23; 26 4 20 6 21; 24 8 20 4 21; 20 11 16 5 17; 30 5 24 7 25;\n 24 15 19 2 20; 28 1 22 15 23; 28 17 22 1 23; 26 17 21 4 22;\n 30 15 24 5 25; 28 17 22 6 23; 30 7 24 16 25; 30 11 24 14 25;\n 30 11 24 16 25; 30 7 24 22 25; 28 28 22 6 23; 30 8 23 26 24;\n 30 4 24 31 25; 30 1 23 37 24; 30 15 24 25 25; 30 42 24 1 25;\n 30 10 24 35 25; 30 29 24 19 25; 30 44 24 7 25; 30 39 24 14 25;\n 30 46 24 10 25; 30 49 24 10 25; 30 48 24 14 25; 30 43 24 22 25;\n 30 34 24 34 25]\n , High() =>\n [17 1 9 0 0; 28 1 16 0 0; 22 2 13 0 0; 16 4 9 0 0; 22 2 11 2 12;\n 28 4 15 0 0; 26 4 13 1 14; 26 4 14 2 15; 24 4 12 4 13; 28 6 15 2 16;\n 24 3 12 8 13; 28 7 14 4 15; 22 12 11 4 12; 24 11 12 5 13; 24 11 12 7 13;\n 30 3 15 13 16; 28 2 14 17 15; 28 2 14 19 15; 26 9 13 16 14;\n 28 15 15 10 16; 30 19 16 6 17; 24 34 13 0 0; 30 16 15 14 16;\n 30 30 16 2 17; 30 22 15 13 16; 30 33 16 4 17; 30 12 15 28 16;\n 30 11 15 31 16; 30 19 15 26 16; 30 23 15 25 16; 30 23 15 28 16;\n 30 19 15 35 16; 30 11 15 46 16; 30 59 16 1 17; 30 22 15 41 16;\n 30 2 15 64 16; 30 24 15 46 16; 30 42 15 32 16; 30 10 15 67 16;\n 30 20 15 61 16]\n )\n\n\"\"\"\nRemainder bits per version.\n\"\"\"\nconst remainderbits = Array{Int64, 1}(\n [0, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3,\n 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0])\n\n\"\"\"\nLocation of the alignment patterns per version.\n\"\"\"\nconst alignmentlocation = Array{Array{Int64, 1}, 1}(\n [ []\n , [6, 18]\n , [6, 22]\n , [6, 26]\n , [6, 30]\n , [6, 34]\n , [6, 22, 38]\n , [6, 24, 42]\n , [6, 26, 46]\n , [6, 28, 50]\n , [6, 30, 54]\n , [6, 32, 58]\n , [6, 34, 62]\n , [6, 26, 46, 66]\n , [6, 26, 48, 70]\n , [6, 26, 50, 74]\n , [6, 30, 54, 78]\n , [6, 30, 56, 82]\n , [6, 30, 58, 86]\n , [6, 34, 62, 90]\n , [6, 28, 50, 72, 94]\n , [6, 26, 50, 74, 98]\n , [6, 30, 54, 78, 102]\n , [6, 28, 54, 80, 106]\n , [6, 32, 58, 84, 110]\n , [6, 30, 58, 86, 114]\n , [6, 34, 62, 90, 118]\n , [6, 26, 50, 74, 98, 122]\n , [6, 30, 54, 78, 102, 126]\n , [6, 26, 52, 78, 104, 130]\n , [6, 30, 56, 82, 108, 134]\n , [6, 34, 60, 86, 112, 138]\n , [6, 30, 58, 86, 114, 142]\n , [6, 34, 62, 90, 118, 146]\n , [6, 30, 54, 78, 102, 126, 150]\n , [6, 24, 50, 76, 102, 128, 154]\n , [6, 28, 54, 80, 106, 132, 158]\n , [6, 32, 58, 84, 110, 136, 162]\n , [6, 26, 54, 82, 110, 138, 166]\n , [6, 30, 58, 86, 114, 142, 170]\n ]\n )\n\n\"\"\"\nFormat information per mode and mask number.\n\"\"\"\nconst formatinfo = Dict{Tuple{ErrCorrLevel, Int64}, BitArray{1}}(\n [ (Low(), 0) => [1,1,1,0,1,1,1,1,1,0,0,0,1,0,0]\n , (Low(), 1) => [1,1,1,0,0,1,0,1,1,1,1,0,0,1,1]\n , (Low(), 2) => [1,1,1,1,1,0,1,1,0,1,0,1,0,1,0]\n , (Low(), 3) => [1,1,1,1,0,0,0,1,0,0,1,1,1,0,1]\n , (Low(), 4) => [1,1,0,0,1,1,0,0,0,1,0,1,1,1,1]\n , (Low(), 5) => [1,1,0,0,0,1,1,0,0,0,1,1,0,0,0]\n , (Low(), 6) => [1,1,0,1,1,0,0,0,1,0,0,0,0,0,1]\n , (Low(), 7) => [1,1,0,1,0,0,1,0,1,1,1,0,1,1,0]\n , (Medium(), 0) => [1,0,1,0,1,0,0,0,0,0,1,0,0,1,0]\n , (Medium(), 1) => [1,0,1,0,0,0,1,0,0,1,0,0,1,0,1]\n , (Medium(), 2) => [1,0,1,1,1,1,0,0,1,1,1,1,1,0,0]\n , (Medium(), 3) => [1,0,1,1,0,1,1,0,1,0,0,1,0,1,1]\n , (Medium(), 4) => [1,0,0,0,1,0,1,1,1,1,1,1,0,0,1]\n , (Medium(), 5) => [1,0,0,0,0,0,0,1,1,0,0,1,1,1,0]\n , (Medium(), 6) => [1,0,0,1,1,1,1,1,0,0,1,0,1,1,1]\n , (Medium(), 7) => [1,0,0,1,0,1,0,1,0,1,0,0,0,0,0]\n , (Quartile(), 0) => [0,1,1,0,1,0,1,0,1,0,1,1,1,1,1]\n , (Quartile(), 1) => [0,1,1,0,0,0,0,0,1,1,0,1,0,0,0]\n , (Quartile(), 2) => [0,1,1,1,1,1,1,0,0,1,1,0,0,0,1]\n , (Quartile(), 3) => [0,1,1,1,0,1,0,0,0,0,0,0,1,1,0]\n , (Quartile(), 4) => [0,1,0,0,1,0,0,1,0,1,1,0,1,0,0]\n , (Quartile(), 5) => [0,1,0,0,0,0,1,1,0,0,0,0,0,1,1]\n , (Quartile(), 6) => [0,1,0,1,1,1,0,1,1,0,1,1,0,1,0]\n , (Quartile(), 7) => [0,1,0,1,0,1,1,1,1,1,0,1,1,0,1]\n , (High(), 0) => [0,0,1,0,1,1,0,1,0,0,0,1,0,0,1]\n , (High(), 1) => [0,0,1,0,0,1,1,1,0,1,1,1,1,1,0]\n , (High(), 2) => [0,0,1,1,1,0,0,1,1,1,0,0,1,1,1]\n , (High(), 3) => [0,0,1,1,0,0,1,1,1,0,1,0,0,0,0]\n , (High(), 4) => [0,0,0,0,1,1,1,0,1,1,0,0,0,1,0]\n , (High(), 5) => [0,0,0,0,0,1,0,0,1,0,1,0,1,0,1]\n , (High(), 6) => [0,0,0,1,1,0,1,0,0,0,0,1,1,0,0]\n , (High(), 7) => [0,0,0,1,0,0,0,0,0,1,1,1,0,1,1]\n ]\n )\n\n\"\"\"\nVersion information.\n\"\"\"\nconst versioninfo = Array{Array{Bool, 1}, 1}(\n [ []\n , []\n , []\n , []\n , []\n , []\n , [0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0]\n , [0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0]\n , [1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0]\n , [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0]\n , [0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0]\n , [0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0]\n , [1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0]\n , [1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0]\n , [0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0]\n , [0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0]\n , [1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0]\n , [1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0]\n , [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0]\n , [0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0]\n , [1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0]\n , [1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0]\n , [0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0]\n , [0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0]\n , [1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0]\n , [1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0]\n , [0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0]\n , [0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0]\n , [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0]\n , [1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0]\n , [0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]\n , [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1]\n , [0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1]\n , [0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1]\n , [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1]\n , [1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1]\n , [0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1]\n , [0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1]\n , [1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1]\n , [1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1]\n ]\n )\n", "meta": {"hexsha": "252ea263629a8314872493d6a5bd47c218098182", "size": 12350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tables.jl", "max_stars_repo_name": "UnofficialJuliaMirror/QRCode.jl-6cfbe66a-a49d-11e9-1842-750d329cfcbb", "max_stars_repo_head_hexsha": "38cf4fa47e82fe1c304d34e68398dddff4c47247", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-07-24T15:26:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T05:39:38.000Z", "max_issues_repo_path": "src/tables.jl", "max_issues_repo_name": "UnofficialJuliaMirror/QRCode.jl-6cfbe66a-a49d-11e9-1842-750d329cfcbb", "max_issues_repo_head_hexsha": "38cf4fa47e82fe1c304d34e68398dddff4c47247", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-29T13:52:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-07T16:04:46.000Z", "max_forks_repo_path": "src/tables.jl", "max_forks_repo_name": "UnofficialJuliaMirror/QRCode.jl-6cfbe66a-a49d-11e9-1842-750d329cfcbb", "max_forks_repo_head_hexsha": "38cf4fa47e82fe1c304d34e68398dddff4c47247", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:06:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T15:08:54.000Z", "avg_line_length": 44.9090909091, "max_line_length": 80, "alphanum_fraction": 0.4667206478, "num_tokens": 7990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.24990280524119862}} {"text": "# This file is a part of JuliaFEM.\n# License is MIT: see https://github.com/JuliaFEM/JuliaFEM.jl/blob/master/LICENSE.md\n\n\"\"\"\nProblem u(X) = u₀ in Γ(d)\n\"\"\"\nmutable struct Dirichlet <: BoundaryProblem\n formulation :: Symbol\n variational :: Bool\n dual_basis :: Bool\n order :: Int\nend\n\nfunction Dirichlet()\n Dirichlet(:incremental, false, false, 1)\nend\n\n\"\"\" Return dual basis transformation matrix Ae. \"\"\"\nfunction get_dualbasis(element::Element, time::Float64, order=1)\n nnodes = length(element)\n De = zeros(nnodes, nnodes)\n Me = zeros(nnodes, nnodes)\n for ip in get_integration_points(element, order)\n detJ = element(ip, time, Val{:detJ})\n w = ip.weight*detJ\n N = element(ip, time)\n De += w*Matrix(Diagonal(vec(N)))\n Me += w*N'*N\n end\n return De, Me, De*inv(Me)\nend\n\nfunction get_formulation_type(problem::Problem{Dirichlet})\n return problem.properties.formulation\nend\n\nfunction assemble!(problem::Problem{Dirichlet}, time::Float64=0.0;\n auto_initialize=true)\n # FIXME: boilerplate\n if !isempty(problem.assembly)\n @warn(\"Assemble problem $(problem.name): problem.assembly is not empty and assembling, are you sure you know what are you doing?\")\n end\n if isempty(problem.elements)\n @warn(\"Assemble problem $(problem.name): problem.elements is empty, no elements in problem?\")\n else\n first_element = first(problem.elements)\n unknown_field_name = get_unknown_field_name(problem)\n if !haskey(first_element, unknown_field_name)\n @warn(\"Assemble problem $(problem.name): seems that problem is uninitialized.\")\n if auto_initialize\n @info(\"Initializing problem $(problem.name) at time $time automatically.\")\n initialize!(problem, time)\n end\n end\n end\n\n if hasmethod(assemble_prehook!, Tuple{typeof(problem), Float64})\n assemble_prehook!(problem, time)\n end\n\n if problem.properties.variational\n for element in get_elements(problem)\n assemble!(problem.assembly, problem, element, time)\n end\n else # nodal collocation\n field_vals = Dict{Int64, Float64}()\n field_name = get_parent_field_name(problem)\n field_dim = get_unknown_field_dimension(problem)\n for element in get_elements(problem)\n gdofs = get_gdofs(problem, element)\n for i=1:field_dim\n haskey(element, field_name*\" $i\") || continue\n ldofs = gdofs[i:field_dim:end]\n xis = get_reference_coordinates(element)\n vals = Float64[]\n for xi in xis\n g = element(field_name*\" $i\", xi, time)\n # u = u_prev + Δu ⇒ Δu = u - u_prev\n if haskey(element, field_name)\n g_prev = element(field_name, xi, time)\n g -= g_prev[i]\n end\n push!(vals, g)\n end\n for (dof, g) in zip(ldofs, vals)\n field_vals[dof] = g\n end\n end\n end\n for (k, v) in field_vals\n FEMBase.add!(problem.assembly.C1, k, k, 1.0)\n FEMBase.add!(problem.assembly.C2, k, k, 1.0)\n FEMBase.add!(problem.assembly.g, k, 1, v)\n end\n end\n\n if hasmethod(assemble_posthook!, Tuple{typeof(problem), Float64})\n assemble_posthook!(problem, time)\n end\nend\n\nfunction assemble!(assembly::Assembly, problem::Problem{Dirichlet},\n element::Element, time::Float64)\n\n # get dimension and name of PARENT field\n nnodes = length(element)\n field_dim = get_unknown_field_dimension(problem)\n field_name = get_parent_field_name(problem)\n gdofs = get_gdofs(problem, element)\n props = problem.properties\n\n if problem.properties.dual_basis\n De, Me, Ae = get_dualbasis(element, time)\n else\n Ae = I\n De = zeros(nnodes, nnodes)\n for ip in get_integration_points(element, props.order)\n N = element(ip, time)\n detJ = element(ip, time, Val{:detJ})\n De += ip.weight*N'*N*detJ\n end\n end\n\n # left hand side\n for i=1:field_dim\n ldofs = gdofs[i:field_dim:end]\n if haskey(element, field_name*\" $i\")\n add!(assembly.C1, ldofs, ldofs, De)\n add!(assembly.C2, ldofs, ldofs, De)\n end\n end\n\n # right hand side\n for ip in get_integration_points(element, props.order)\n detJ = element(ip, time, Val{:detJ})\n w = ip.weight*detJ\n N = element(ip, time)\n\n for i=1:field_dim\n ldofs = gdofs[i:field_dim:end]\n if haskey(element, field_name*\" $i\")\n g = element(field_name*\" $i\", ip, time)\n # u = u_prev + Δu ⇒ Δu = u - u_prev\n if haskey(element, field_name)\n g_prev = element(field_name, ip, time)\n g -= g_prev[i]\n end\n add!(assembly.g, ldofs, w*g*Ae*N')\n end\n end\n\n end\n\nend\n\nfunction postprocess!(problem::Problem{Dirichlet}, time::Float64, ::Type{Val{Symbol(\"reaction force\")}})\n la = problem(\"lambda\", time)\n rf = Dict(nid => -lai for (nid, lai) in la)\n update!(problem, \"reaction force\", time => rf)\nend\n", "meta": {"hexsha": "183a924de8a2cf4f2bbf34fff81d6737666c5381", "size": 5367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems_dirichlet.jl", "max_stars_repo_name": "JuliaTagBot/JuliaFEM.jl", "max_stars_repo_head_hexsha": "ff807d0ead1ee28648a6826051dcc301a333b3b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 226, "max_stars_repo_stars_event_min_datetime": "2015-07-26T04:20:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T23:11:04.000Z", "max_issues_repo_path": "src/problems_dirichlet.jl", "max_issues_repo_name": "JuliaTagBot/JuliaFEM.jl", "max_issues_repo_head_hexsha": "ff807d0ead1ee28648a6826051dcc301a333b3b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 234, "max_issues_repo_issues_event_min_datetime": "2015-06-23T19:08:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T06:45:55.000Z", "max_forks_repo_path": "src/problems_dirichlet.jl", "max_forks_repo_name": "JuliaTagBot/JuliaFEM.jl", "max_forks_repo_head_hexsha": "ff807d0ead1ee28648a6826051dcc301a333b3b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 79, "max_forks_repo_forks_event_min_datetime": "2015-06-24T04:51:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T08:07:56.000Z", "avg_line_length": 33.3354037267, "max_line_length": 138, "alphanum_fraction": 0.5856158003, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24981693395037463}} {"text": "# License for this file: MIT (expat)\n# Copyright 2017-2018, DLR Institute of System Dynamics and Control\n#\n# This file is part of module\n# ModiaMath.NonlinearEquations (ModiaMath/NonlinearEquations/_module.jl)\n#\n\n\"\"\"\n module KINSOL - Solve nonlinear equation system with Sundials KINSOL\n\nThe goal is to solve the same system several times with KINSOL.\n\"\"\"\nmodule KINSOL\n\nimport Sundials\nimport ModiaMath\nusing LinearAlgebra\n\n@noinline function old_cfunction(f, r, a)\n ccall(:jl_function_ptr, Ptr{Cvoid}, (Any, Any, Any), f, r, a)\nend\n\n\nmutable struct NonlinearEquationsInfo\n extraInfo # Model-specific extra information\n name::String # Name of equation system\n ny::Int # Number of equations (length of y-vector)\n getResidues!::Function # Function of the nonlinear equation system\n y0::Vector{Float64} # The initial y vector (to print in error messages)\n lastNorm_r::Float64\n lastrScaledNorm_r::Float64\n kin_mem::Ptr{Cvoid} # KINSOL pointer (to access all KINgetXXX functions)\n\n function NonlinearEquationsInfo(name::String, ny::Int, getResidues!::Function; extraInfo=nothing)\n @assert(ny >= 0)\n new(extraInfo, name, ny, getResidues!, zeros(ny), 1.0, 1.0)\n end\nend\n\nfunction kinsol_f(y::Sundials.N_Vector, r::Sundials.N_Vector, eqInfo::NonlinearEquationsInfo)\n eqInfo.getResidues!(eqInfo, Sundials.asarray(y), Sundials.asarray(r))\n return Cint(0) # indicates normal return\nend\n\n@static if VERSION < v\"0.7.0-DEV.2005\"\n const kinsol_fc = cfunction(kinsol_f, Cint, (Sundials.N_Vector, Sundials.N_Vector, Ref{NonlinearEquationsInfo}))\nend\n\nfunction kinsol_ErrHandlerFn(error_code::Cint, KINmodule::Cstring, KINfunction::Cstring,\n message::Cstring, eqInfo::NonlinearEquationsInfo)\n if error_code > 0\n # Print information text\n println(\"\\n\\n!!! Warning from ModiaMath.NonlinearEquations.KINSOL: \", unsafe_string(KINfunction),\n \"(...) returned with a [\", unsafe_string(KINmodule), \"] error_code = \",\n error_code, \":\\n\", unsafe_string(message), \"\\n\")\n else\n simulationModel = eqInfo.extraInfo\n tables = ModiaMath.getVariableAndResidueValues(simulationModel)\n\n if tables != nothing\n println(\"\\n\\nLast used values in model:\\n\\n\",\n tables[1], \"\\n\\n\",\n tables[2], \"\\n\\n\")\n end\n\n if error_code == -11\n str1 = \"\\nIt might be that the Jacobian is singular (= there are redundant equations).\\n\"\n else\n str1 = \"\\n\"\n end\n\n if typeof(simulationModel) <: ModiaMath.AbstractSimulationModel\n simState = simulationModel.simulationState\n x_names = String[simState.getVariableName(simState.model, ModiaMath.DAE.Category_X, i) for i = 1:simState.nx]\n\n error(\"\\n\\n!!! Error from ModiaMath.NonlinearEquations.KINSOL: \", unsafe_string(KINfunction),\n \"(...) returned with a [\", unsafe_string(KINmodule), \"] error:\\n \",\n unsafe_string(message), \"\\nModiaMath info:\\nlastNorm(r) = \", eqInfo.lastNorm_r,\n \", lastNorm(rScaled*r) = \", eqInfo.lastrScaledNorm_r, \".\", str1,\n string(simState.name), \": time = \" , string(simState.time) ,\n \", stepsize of implicit Euler step = \" , string(simState.hev) ,\n \", scaleConstraintsAtEvents = \" , string(simState.scaleConstraintsAtEvents) ,\n \"\\nx_names = \" , string(x_names) ,\n \"\\nx_start = \" , string(eqInfo.y0) ,\n \"\\nx_fixed = \" , string(simState.x_fixed) ,\n \"\\nx_nominal = \" , string(simState.x_nominal) ,\n \"\\nx_yScale = \" , string(simState.yScale) ,\n \"\\nx_rScale = \" , string(simState.rScale) ,\n \"\\nx = \" , string(simState.xev) ,\n \"\\nderx = \" , string(simState.derxev) ,\n \"\\nresidues = \" , string(simState.residues) ,\n \"\\nnx = \" , string(simState.nx) ,\n \"\\nnd = \" , string(simState.nd) ,\n \"\\nnc = \" , string(simState.nc) ,\n \"\\nnw = \" , string(simState.nw) ,\n \"\\nnz = \" , string(simState.nz) ,\n \"\\ntolerance = \" , string(simState.tolerance) ,\n \"\\nFTOL = \" , string(simState.FTOL))\n\n else\n error(\"\\n\\n!!! Error from ModiaMath.NonlinearEquations.KINSOL: \", unsafe_string(KINfunction),\n \"(...) returned with a [\", unsafe_string(KINmodule), \"] error:\\n \",\n unsafe_string(message), \"\\nModiaMath info:\\nlastNorm(r) = \", eqInfo.lastNorm_r,\n \", lastNorm(rScaled*r) = \", eqInfo.lastrScaledNorm_r, \".\", str1)\n end\n end\n return nothing\nend\n\n@static if VERSION < v\"0.7.0-DEV.2005\"\n const kinsol_ErrHandlerFnc = cfunction(kinsol_ErrHandlerFn, Void, (Cint, Cstring, Cstring, Cstring, Ref{NonlinearEquationsInfo}))\nend\n\n\nfunction solveNonlinearEquations!(eqInfo::NonlinearEquationsInfo, y::Vector{Float64};\n FTOL::Float64=eps(Float64)^(1 / 3),\n yScale::Vector{Float64}=ones(length(y)),\n rScale::Vector{Float64}=ones(length(y)))\n # Create KINSOL and info structure\n @assert(length(y) == eqInfo.ny)\n kmem = Sundials.KINCreate()\n if kmem == C_NULL\n error(\"ModiaMath.NonlinearEquations.KINSOL.solveNonlinearEquations!: Failed to allocate KINSOL solver object\")\n end\n eqInfo.kin_mem = kmem\n eqInfo.y0 .= y\n\n # Run KINSOL\n try\n # Set error handler function\n @static if VERSION >= v\"0.7.0-DEV.2005\"\n Sundials.KINSetErrHandlerFn(kmem, old_cfunction(kinsol_ErrHandlerFn, Nothing, Tuple{Cint,Cstring,Cstring,Cstring,Ref{typeof(NonlinearEquationsInfo)}}), pointer_from_objref(eqInfo))\n else\n Sundials.KINSetErrHandlerFn(kmem, kinsol_ErrHandlerFnc, pointer_from_objref(eqInfo))\n end\n\n # Initialize KINSOL\n @static if VERSION >= v\"0.7.0-DEV.2005\"\n Sundials.KINInit(kmem, old_cfunction(kinsol_f, Cint, Tuple{Sundials.N_Vector,Sundials.N_Vector,Ref{typeof(NonlinearEquationsInfo)}}), Sundials.NVector(y))\n else\n Sundials.KINInit(kmem, kinsol_fc, y)\n end\n Sundials.KINSetUserData(kmem, eqInfo)\n Sundials.KINSetFuncNormTol(kmem, FTOL)\n Sundials.KINSetScaledStepTol(kmem, FTOL * FTOL)\n\n # Set maximum allowable scaled length mxnewtstep of the Newton step\n # KINSOL defines a default of mxnewtstep = 1000*norm(y.*yScale).\n # This fails if y is a zero vector. Therefore, mxnewtstep is changed to\n # take only yScale into account.\n Sundials.KINSetMaxNewtonStep(kmem, 1000.0 * norm(yScale, Inf))\n\n # Set linear solver\n # nnz_jac = nnz(sim.jac)\n # IDAKLU(mem, ny, nnz_jac)\n # IDAKLUSetOrdering(mem, KLUorderingChoice)\n # IDASlsSetSparseJacFn(mem);\n #else\n A = Sundials.SUNDenseMatrix(length(y), length(y))\n LS = Sundials.SUNDenseLinearSolver(Sundials.NVector(y), A)\n Sundials.KINDlsSetLinearSolver(kmem, LS, A)\n #end\n strategy = Sundials.KIN_LINESEARCH\n\n @static if VERSION >= v\"0.7.0-DEV.2005\"\n Sundials.KINSol(kmem, Sundials.NVector(y), strategy, Sundials.NVector(yScale), Sundials.NVector(rScale))\n else\n Sundials.KINSol(kmem, y, strategy, yScale, rScale)\n end\n\n finally\n # Free allocated memory\n Sundials.KINFree([kmem])\n end\n\n return nothing\nend\n\nend", "meta": {"hexsha": "a27b42c9922a751b11c6e5f039639b9bac317409", "size": 7758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NonlinearEquations/sundials_kinsol.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ModiaMath.jl-67ccffd1-116d-535b-ad39-76a8fd0cbf71", "max_stars_repo_head_hexsha": "c7377c5570de24305bbfe20d25847ccae1e4d60d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2018-08-02T18:33:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-02T02:54:44.000Z", "max_issues_repo_path": "src/NonlinearEquations/sundials_kinsol.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ModiaMath.jl-67ccffd1-116d-535b-ad39-76a8fd0cbf71", "max_issues_repo_head_hexsha": "c7377c5570de24305bbfe20d25847ccae1e4d60d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2018-08-05T10:36:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T16:19:06.000Z", "max_forks_repo_path": "src/NonlinearEquations/sundials_kinsol.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/ModiaMath.jl-67ccffd1-116d-535b-ad39-76a8fd0cbf71", "max_forks_repo_head_hexsha": "c7377c5570de24305bbfe20d25847ccae1e4d60d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-08-04T11:56:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T12:47:55.000Z", "avg_line_length": 43.3407821229, "max_line_length": 192, "alphanum_fraction": 0.6107244135, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24981693395037458}} {"text": "function gather_bodies_initial_coordinates(simulation::NBodySimulation)\n system = simulation.system\n bodies = system.bodies;\n len = n = length(bodies)\n if simulation.thermostat isa NoseHooverThermostat\n len += 1\n end\n u0 = zeros(3, len)\n v0 = zeros(3, len)\n for i = 1:n\n u0[:, i] = bodies[i].r\n v0[:, i] = bodies[i].v\n end\n (u0, v0, n)\nend\n\nfunction gather_bodies_initial_coordinates(simulation::NBodySimulation{<:WaterSPCFw})\n system = simulation.system\n molecules = system.bodies\n n = length(molecules)\n len = 3*n\n if simulation.thermostat isa NoseHooverThermostat\n len = 3*n+1\n end\n (u0,v0) = gather_atom_coordinates(simulation.system, len)\n (u0, v0, n)\nend\n\nfunction gather_atom_coordinates(system::WaterSPCFw{<:MassBody}, len)\n molecules = system.bodies\n n = length(molecules)\n T = eltype(first(molecules).r)\n u0 = zeros(T,3,len)\n v0 = zeros(T,3,len)\n for i = 1:n\n p = system.scpfw_parameters\n indO, indH1, indH2 = 3*(i-1)+1, 3*(i-1)+2, 3*(i-1)+3\n u0[:, indO] = molecules[i].r\n u0[:, indH1] = molecules[i].r .+ [p.rOH, 0.0, 0.0]\n u0[:, indH2] = molecules[i].r .+ [cos(p.aHOH) * p.rOH, 0.0, sin(p.aHOH) * p.rOH]\n v0[:, indO] = molecules[i].v\n v0[:, indH1] = molecules[i].v\n v0[:, indH2] = molecules[i].v\n end\n (u0, v0)\nend\n\nfunction gather_atom_coordinates(system::WaterSPCFw{<:WaterMolecule}, len)\n molecules = system.bodies\n n = length(molecules)\n T = eltype(first(molecules).r)\n u0 = zeros(T,3,len)\n v0 = zeros(T,3,len)\n for i = 1:n\n p = system.scpfw_parameters\n indO, indH1, indH2 = 3*(i-1)+1, 3*(i-1)+2, 3*(i-1)+3\n u0[:, indO] = molecules[i].O.r\n u0[:, indH1] = molecules[i].H1.r\n u0[:, indH2] = molecules[i].H2.r\n v0[:, indO] = molecules[i].O.v\n v0[:, indH1] = molecules[i].H1.v\n v0[:, indH2] = molecules[i].H2.v\n end\n (u0, v0)\nend\n\nfunction gather_accelerations_for_potentials(simulation::NBodySimulation{CustomAccelerationSystem})\n acceleration_functions = []\n push!(acceleration_functions, simulation.system.acceleration)\n acceleration_functions\nend\n\nfunction gather_accelerations_for_potentials(simulation::NBodySimulation{<:PotentialNBodySystem})\n acceleration_functions = []\n for (potential, parameters) in simulation.system.potentials\n push!(acceleration_functions, get_accelerating_function(parameters, simulation))\n end\n acceleration_functions\nend\n\nfunction gather_group_accelerations(simulation::NBodySimulation{<:WaterSPCFw})\n accelerations = []\n push!(accelerations, get_group_accelerating_function(simulation.system.scpfw_parameters, simulation))\n accelerations\nend\n\nfunction get_accelerating_function(parameters::LennardJonesParameters, simulation::NBodySimulation)\n (ms, indxs) = obtain_data_for_lennard_jones_interaction(simulation.system)\n (dv, u, v, t, i) -> pairwise_lennard_jones_acceleration!(dv, u, i, indxs, ms, parameters, simulation.boundary_conditions)\nend\n\nfunction get_accelerating_function(parameters::ElectrostaticParameters, simulation::NBodySimulation)\n (qs, ms, indxs, exclude) = obtain_data_for_electrostatic_interaction(simulation.system)\n (dv, u, v, t, i) -> pairwise_electrostatic_acceleration!(dv, u, i, length(indxs), qs, ms, exclude, parameters, simulation.boundary_conditions)\nend\n\nfunction get_accelerating_function(parameters::SPCFwParameters, simulation::NBodySimulation)\n (ms, neighbouhood) = obtain_data_for_harmonic_bond_interaction(simulation.system, parameters)\n (dv, u, v, t, i) -> harmonic_bond_potential_acceleration!(dv, u, i, ms, neighbouhood, parameters)\nend\n\nfunction get_accelerating_function(parameters::GravitationalParameters, simulation::NBodySimulation)\n (dv, u, v, t, i) -> gravitational_acceleration!(dv, u, i, length(simulation.system.bodies), simulation.system.bodies, parameters)\nend\n\nfunction get_accelerating_function(parameters::MagnetostaticParameters, simulation::NBodySimulation)\n (dv, u, v, t, i) -> magnetostatic_dipdip_acceleration!(dv, u, i, length(simulation.system.bodies), simulation.system.bodies, parameters)\nend\n\nfunction get_group_accelerating_function(parameters::PotentialParameters, simulation::NBodySimulation{<:WaterSPCFw})\n (ms, indxs) = obtain_data_for_lennard_jones_interaction(simulation.system)\n (dv, u, v, t, i) -> valence_angle_potential_acceleration!(dv, u, 3*(i-1)+2, 3*(i-1)+1, 3*(i-1)+3, ms, parameters)\nend\n\nfunction obtain_data_for_harmonic_bond_interaction(system::WaterSPCFw, p::SPCFwParameters)\n neighbouhoods = Dict{Int, Vector{Tuple{Int,Float64}}}()\n n = length(system.bodies)\n ms = zeros(3 * n)\n for i in 1:n\n indO, indH1, indH2 = 3 * (i - 1) + 1, 3 * (i - 1) + 2, 3 * (i - 1) + 3\n ms[indO] = system.mO\n ms[indH1] = system.mH\n ms[indH2] = system.mH\n neighbours_o = Vector{Tuple{Int,Float64}}()\n push!(neighbours_o, (indH1, p.kb))\n push!(neighbours_o, (indH2, p.kb))\n neighbours_h1 = Vector{Tuple{Int,Float64}}()\n push!(neighbours_h1, (indO, p.kb))\n neighbours_h2 = Vector{Tuple{Int,Float64}}()\n push!(neighbours_h2, (indO, p.kb))\n neighbouhoods[indO] = neighbours_o\n neighbouhoods[indH1] = neighbours_h1\n neighbouhoods[indH2] = neighbours_h2\n end\n (ms, neighbouhoods)\nend\n\nfunction obtain_data_for_lennard_jones_interaction(system::PotentialNBodySystem)\n bodies = system.bodies\n n = length(bodies)\n ms = zeros(typeof(first(bodies).m), n)\n indxs = zeros(Int, n)\n for i = 1:n\n ms[i] = bodies[i].m\n indxs[i] = i\n end\n return (ms, indxs)\nend\n\nfunction obtain_data_for_lennard_jones_interaction(system::WaterSPCFw)\n bodies = system.bodies\n n = length(bodies)\n ms = zeros(3 * n)\n indxs = zeros(Int, n)\n for i = 1:n\n indxs[i] = 3 * (i - 1) + 1\n ms[3 * (i - 1) + 1] = system.mO\n ms[3 * (i - 1) + 2] = system.mH\n ms[3 * (i - 1) + 3] = system.mH\n end\n return (ms, indxs)\nend\n\nfunction obtain_data_for_electrostatic_interaction(system::PotentialNBodySystem)\n bodies = system.bodies\n n = length(bodies)\n qs = zeros(typeof(first(bodies).q), n)\n ms = zeros(typeof(first(bodies).m), n)\n indxs = collect(1:n)\n exclude = Dict{Int, Vector{Int}}()\n for i = 1:n\n qs[i] = bodies[i].q\n ms[i] = bodies[i].m\n exclude[i] = [i]\n end\n return (qs, ms, indxs, exclude)\nend\n\nfunction obtain_data_for_electrostatic_interaction(system::WaterSPCFw)\n bodies = system.bodies\n n = length(bodies)\n qs = zeros(3 * n)\n ms = zeros(3 * n)\n indxs = collect(1:3*n)\n exclude = Dict{Int, Vector{Int}}()\n for i = 1:n\n Oind = 3 * (i - 1) + 1\n qs[Oind] = system.qO\n qs[Oind + 1] = system.qH\n qs[Oind + 2] = system.qH\n ms[Oind] = system.mO\n ms[Oind + 1] = system.mH\n ms[Oind + 2] = system.mH\n exclude[Oind] = [Oind, Oind+1, Oind+2,3*n+1]\n exclude[Oind+1] = [Oind, Oind+1, Oind+2,3*n+1]\n exclude[Oind+2] = [Oind, Oind+1, Oind+2,3*n+1]\n end\n return (qs, ms, indxs, exclude)\nend\n\nfunction obtain_data_for_electrostatic_interaction(system::NBodySystem)\n bodies = system.bodies\n n = length(bodies)\n qs = zeros(typeof(first(bodies).m), n)\n ms = zeros(typeof(first(bodies).m), n)\n return (qs, ms)\nend\n\nfunction obtain_data_for_valence_angle_harmonic_interaction(system::WaterSPCFw)\n p = system.scpfw_parameters\n bonds = Vector{Tuple{Int, Int, Int, Float64, Float64}}()\n n = length(system.bodies)\n ms = zeros(3 * n)\n for i = 1:n\n indO, indH1, indH2 = 3 * (i - 1) + 1, 3 * (i - 1) + 2, 3 * (i - 1) + 3\n ms[indO] = system.mO\n ms[indH1] = system.mH\n ms[indH2] = system.mH\n push!(bonds, (indH1, indO, indH2, p.aHOH, p.ka))\n end\n return (ms, bonds)\nend\n\nfunction gather_simultaneous_acceleration(s::NBodySimulation)\n acelerations = []\n if s.thermostat isa BerendsenThermostat\n push!(acelerations, get_berendsen_thermostating_acceleration(s))\n elseif s.thermostat isa NoseHooverThermostat\n push!(acelerations, get_nosehoover_thermostating_acceleration(s))\n end\n acelerations\nend\n\nfunction get_berendsen_thermostating_acceleration(simulation::NBodySimulation)\n (ms, kb, n, nc, p) = obtain_data_for_berendsen_thermostating(simulation)\n (dv, u, v, t) -> berendsen_acceleration!(dv, v, ms, kb, n, nc, p)\nend\n\nfunction obtain_data_for_berendsen_thermostating(simulation::NBodySimulation)\n ms = get_masses(simulation.system)\n kb = simulation.kb\n n = length(simulation.system.bodies)\n nc = 0\n p = simulation.thermostat\n (ms, kb, n, nc, p)\nend\n\nfunction obtain_data_for_berendsen_thermostating(simulation::NBodySimulation{<:WaterSPCFw})\n ms = get_masses(simulation.system)\n kb = simulation.kb\n n = 3*length(simulation.system.bodies)\n nc = 2*length(simulation.system.bodies)\n p = simulation.thermostat\n (ms, kb, n, nc, p)\nend\n\nfunction get_nosehoover_thermostating_acceleration(simulation::NBodySimulation)\n (ms, kb, n, nc, γind, p) = obtain_data_for_nosehoover_thermostating(simulation)\n (dv, u, v, t) -> nosehoover_acceleration!(dv, u, v, ms, kb, n, nc, γind, p)\nend\n\nfunction obtain_data_for_nosehoover_thermostating(simulation::NBodySimulation)\n ms = get_masses(simulation.system)\n kb = simulation.kb\n n = length(simulation.system.bodies)\n γind = 3*n+1\n nc = 0\n p = simulation.thermostat\n (ms, kb, n, nc, γind, p)\nend\n\nfunction obtain_data_for_nosehoover_thermostating(simulation::NBodySimulation{<:WaterSPCFw})\n ms = get_masses(simulation.system)\n kb = simulation.kb\n n = 3*length(simulation.system.bodies)\n γind = 3*n+1\n nc = 2*length(simulation.system.bodies)\n p = simulation.thermostat\n (ms, kb, n, nc, γind, p)\nend\n\nfunction DiffEqBase.ODEProblem(simulation::NBodySimulation{<:PotentialNBodySystem})\n (u0, v0, n) = gather_bodies_initial_coordinates(simulation)\n\n acceleration_functions = gather_accelerations_for_potentials(simulation)\n\n function ode_system!(du, u, p, t)\n du[:, 1:n] = @view u[:, n + 1:2n];\n\n @inbounds for i = 1:n\n a = MVector(0.0, 0.0, 0.0)\n for acceleration! in acceleration_functions\n acceleration!(a, u[:, 1:n], u[:, n + 1:end], t, i);\n end\n du[:, n + i] .= a\n end\n end\n\n return ODEProblem(ode_system!, hcat(u0, v0), simulation.tspan)\nend\n\nfunction DiffEqBase.SecondOrderODEProblem(simulation::NBodySimulation{<:PotentialNBodySystem})\n (u0, v0, n) = gather_bodies_initial_coordinates(simulation)\n acceleration_functions = gather_accelerations_for_potentials(simulation)\n simultaneous_acceleration = gather_simultaneous_acceleration(simulation)\n\n function soode_system!(dv, v, u, p, t)\n @inbounds for i = 1:n\n a = MVector(0.0, 0.0, 0.0)\n for acceleration! in acceleration_functions\n acceleration!(a, u, v, t, i);\n end\n dv[:, i] .= a\n end\n for acceleration! in simultaneous_acceleration\n acceleration!(dv, u, v, t);\n end\n end\n\n SecondOrderODEProblem(soode_system!, v0, u0, simulation.tspan)\nend\n\nfunction DiffEqBase.SecondOrderODEProblem(simulation::NBodySimulation{<:WaterSPCFw})\n (u0, v0, n) = gather_bodies_initial_coordinates(simulation)\n (o_acelerations, h_acelerations) = gather_accelerations_for_potentials(simulation)\n group_accelerations = gather_group_accelerations(simulation)\n simultaneous_acceleration = gather_simultaneous_acceleration(simulation)\n #(ms_lj, indxs_lj) = obtain_data_for_lennard_jones_interaction(simulation.system)\n #(qs, ms_em, indxs_em, exclude) = obtain_data_for_electrostatic_interaction(simulation.system)\n #lj_parameters = simulation.system.lj_parameters\n #e_parameters = simulation.system.e_parameters\n #pbc = simulation.boundary_conditions\n\n function soode_system!(dv, v, u, p, t)\n T = eltype(v)\n #=\n @inbounds for i=1:n\n aO = MVector{3,T}(zero(T), zero(T), zero(T))\n aH1 = MVector{3,T}(zero(T), zero(T), zero(T))\n aH2 = MVector{3,T}(zero(T), zero(T), zero(T))\n pairwise_lennard_jones_acceleration!(aO, u, 3*i-2, indxs_lj, ms_lj, lj_parameters, pbc)\n pairwise_electrostatic_acceleration!(aO, u, 3*i-2, length(indxs_em), qs, ms_em, exclude, e_parameters, pbc)\n pairwise_electrostatic_acceleration!(aH1, u, 3*i-1, length(indxs_em), qs, ms_em, exclude, e_parameters, pbc)\n pairwise_electrostatic_acceleration!(aH2, u, 3*i-0, length(indxs_em), qs, ms_em, exclude, e_parameters, pbc)\n dv[:, 3*i-2] .= aO\n dv[:, 3*i-1] .= aH1\n dv[:, 3*i-0] .= aH2\n end\n =#\n @inbounds for i = 1:n\n a = MVector{3,T}(zero(T), zero(T), zero(T))\n for acceleration! in o_acelerations\n acceleration!(a, u, v, t, 3*i-2);\n end\n dv[:, 3*i-2] .= a\n end\n @inbounds for i ∈ 1:n, j ∈ (1,2)\n a = MVector{3,T}(zero(T), zero(T), zero(T))\n for acceleration! in h_acelerations\n acceleration!(a, u, v, t, 3*i-2+j);\n end\n dv[:, 3*i-2+j] .= a\n end\n @inbounds for i = 1:n\n for acceleration! in group_accelerations\n acceleration!(dv, u, v, t, i)\n end\n end\n for acceleration! in simultaneous_acceleration\n acceleration!(dv, u, v, t)\n end\n end\n SecondOrderODEProblem(soode_system!, v0, u0, simulation.tspan)\nend\n\nfunction gather_accelerations_for_potentials(simulation::NBodySimulation{<:WaterSPCFw})\n o_acelerations = []\n h_acelerations = []\n push!(o_acelerations, get_accelerating_function(simulation.system.e_parameters, simulation))\n push!(o_acelerations, get_accelerating_function(simulation.system.scpfw_parameters, simulation))\n push!(o_acelerations, get_accelerating_function(simulation.system.lj_parameters, simulation))\n push!(h_acelerations, get_accelerating_function(simulation.system.e_parameters, simulation))\n push!(h_acelerations, get_accelerating_function(simulation.system.scpfw_parameters, simulation))\n (o_acelerations, h_acelerations)\nend\n\nfunction DiffEqBase.SDEProblem(simulation::NBodySimulation{<:PotentialNBodySystem})\n (u0, v0, n) = gather_bodies_initial_coordinates(simulation)\n acceleration_functions = gather_accelerations_for_potentials(simulation)\n therm = simulation.thermostat\n\n function deterministic_acceleration!(du, u, p, t)\n du[:, 1:n] = @view u[:, n + 1:2n]\n @inbounds for i = 1:n\n a = MVector(0.0, 0.0, 0.0)\n for acceleration! in acceleration_functions\n acceleration!(a, (@view u[:, 1:n]), (@view u[:, n + 1:end]), t, i);\n end\n du[:, n + i] .= a\n end\n @. du[:, n + 1:end] -= therm.γ*u[:, n + 1:end]\n end\n\n σ = sqrt(2*therm.γ*simulation.kb*therm.T/simulation.system.bodies[1].m)\n\n function noise!(du, u, p, t)\n @. du[:, n + 1:end] += σ\n end\n\n return SDEProblem(deterministic_acceleration!, noise!, hcat(u0, v0), simulation.tspan)\nend\n\nfunction DiffEqBase.SDEProblem(simulation::NBodySimulation{<:WaterSPCFw})\n (u0, v0, n) = gather_bodies_initial_coordinates(simulation)\n (o_acelerations, h_acelerations) = gather_accelerations_for_potentials(simulation)\n group_accelerations = gather_group_accelerations(simulation)\n simultaneous_acceleration = gather_simultaneous_acceleration(simulation)\n therm = simulation.thermostat\n mH = simulation.system.mH\n mO = simulation.system.mO\n\n function deterministic_acceleration!(du, u, p, t)\n du[:, 1:3*n] = @view u[:, 3*n+1 : 2*3*n]\n @inbounds for i = 1:n\n a = MVector(0.0, 0.0, 0.0)\n for acceleration! in o_acelerations\n acceleration!(a, (@view u[:, 1:3*n]), (@view u[:, 3*n+1 : 2*3*n]), t, 3 * (i - 1) + 1);\n end\n du[:, 3*n+3 * (i - 1) + 1] .= a\n @. du[:, 3*n+3 * (i - 1) + 1] -= therm.γ*u[:, 3*n+3 * (i - 1) + 1]/mO\n @. du[:, 3*n+3 * (i - 1) + 2] -= therm.γ*u[:, 3*n+3 * (i - 1) + 2]/mH\n @. du[:, 3*n+3 * (i - 1) + 3] -= therm.γ*u[:, 3*n+3 * (i - 1) + 3]/mH\n end\n @inbounds for i in 1:n, j in (2, 3)\n a = MVector(0.0, 0.0, 0.0)\n for acceleration! in h_acelerations\n acceleration!(a, (@view u[:, 1:3*n]), (@view u[:, 3*n+1 : 2*3*n]), t, 3 * (i - 1) + j);\n end\n du[:, 3*n+3 * (i - 1) + j] .= a\n end\n @inbounds for i = 1:n\n for acceleration! in group_accelerations\n acceleration!((@view du[ :, 3*n+1 : 2*3*n]), (@view u[:, 1:3*n]), (@view u[:, 3*n+1 : 2*3*n]), t, i);\n end\n end\n for acceleration! in simultaneous_acceleration\n acceleration!((@view du[:, 3*n+1 : 2*3*n]), (@view u[:, 1:3*n]), (@view u[:, 3*n+1 : 2*3*n]), t);\n end\n @. du[:, 3*n+1 : 2*3*n] -= therm.γ*u[:, 3*n+1 : 2*3*n]\n end\n σO = sqrt(2*therm.γ*simulation.kb*therm.T)/mO\n σH = sqrt(2*therm.γ*simulation.kb*therm.T)/mH\n\n function noise!(du, u, p, t)\n @inbounds for i = 1:n\n @. du[:, 3*n+3 * (i - 1) + 1] += σO\n @. du[:, 3*n+3 * (i - 1) + 2] += σH\n @. du[:, 3*n+3 * (i - 1) + 3] += σH\n end\n end\n\n return SDEProblem(deterministic_acceleration!, noise!, hcat(u0, v0), simulation.tspan)\nend\n", "meta": {"hexsha": "d283a60e2335cf65fa43090c74fe11057639dbf3", "size": 17665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nbody_to_ode.jl", "max_stars_repo_name": "dextorious/NBodySimulator.jl", "max_stars_repo_head_hexsha": "a76b3fa0a567a4a1c2a2b45f262b9a523f282166", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nbody_to_ode.jl", "max_issues_repo_name": "dextorious/NBodySimulator.jl", "max_issues_repo_head_hexsha": "a76b3fa0a567a4a1c2a2b45f262b9a523f282166", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nbody_to_ode.jl", "max_forks_repo_name": "dextorious/NBodySimulator.jl", "max_forks_repo_head_hexsha": "a76b3fa0a567a4a1c2a2b45f262b9a523f282166", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0711206897, "max_line_length": 146, "alphanum_fraction": 0.6352108689, "num_tokens": 5628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24972471497828694}} {"text": "# *********************************************************************************\n# REopt, Copyright (c) 2019-2020, Alliance for Sustainable Energy, LLC.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# Redistributions of source code must retain the above copyright notice, this list\n# of conditions and the following disclaimer.\n#\n# Redistributions in binary form must reproduce the above copyright notice, this\n# list of conditions and the following disclaimer in the documentation and/or other\n# materials provided with the distribution.\n#\n# Neither the name of the copyright holder nor the names of its contributors may be\n# used to endorse or promote products derived from this software without specific\n# prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n# OF THE POSSIBILITY OF SUCH DAMAGE.\n# *********************************************************************************\n\"\"\"\n struct ElectricTariff\n\n- data for electric tariff in reopt model\n- can be defined using custom rates or URDB rate\n- very similar to the URDB struct but includes export rates and bins\n\"\"\"\nstruct ElectricTariff\n energy_rates::AbstractArray{Float64, 2} # gets a second dim with tiers\n energy_tier_limits::AbstractArray{Float64,1}\n n_energy_tiers::Int\n\n monthly_demand_rates::AbstractArray{Float64, 2} # gets a second dim with tiers\n time_steps_monthly::AbstractArray{AbstractArray{Int64,1},1} # length = 0 or 12\n monthly_demand_tier_limits::AbstractArray{Float64,1}\n n_monthly_demand_tiers::Int\n\n tou_demand_rates::AbstractArray{Float64, 2} # gets a second dim with tiers\n tou_demand_ratchet_time_steps::AbstractArray{AbstractArray{Int64,1},1} # length = n_tou_demand_ratchets\n tou_demand_tier_limits::AbstractArray{Float64,1}\n n_tou_demand_tiers::Int\n\n demand_lookback_months::AbstractArray{Int,1}\n demand_lookback_percent::Float64\n demand_lookback_range::Int\n\n fixed_monthly_charge::Float64\n annual_min_charge::Float64\n min_monthly_charge::Float64\n\n export_rates::Dict{Symbol, AbstractArray}\n export_bins::AbstractArray{Symbol,1}\n\n coincident_peak_load_active_time_steps::AbstractVector{AbstractVector{Int64}}\n coincident_peak_load_charge_per_kw::AbstractVector{Float64}\n coincpeak_periods::AbstractVector{Int64}\nend\n\n\n\"\"\"\n ElectricTariff\n\nElectricTariff constructor\n```julia\nfunction ElectricTariff(;\n urdb_label::String=\"\",\n urdb_response::Dict=Dict(),\n urdb_utility_name::String=\"\",\n urdb_rate_name::String=\"\",\n year::Int=2020,\n time_steps_per_hour::Int=1,\n NEM::Bool=false,\n wholesale_rate::T1=nothing,\n export_rate_beyond_net_metering_limit::T2=nothing,\n monthly_energy_rates::Array=[],\n monthly_demand_rates::Array=[],\n blended_annual_energy_rate::S=nothing,\n blended_annual_demand_rate::R=nothing,\n add_monthly_rates_to_urdb_rate::Bool=false,\n tou_energy_rates_per_kwh::Array=[],\n add_tou_energy_rates_to_urdb_rate::Bool=false,\n remove_tiers::Bool=false,\n demand_lookback_months::AbstractArray{Int64, 1}=Int64[],\n demand_lookback_percent::Float64=0.0,\n demand_lookback_range::Int=0,\n coincident_peak_load_active_time_steps::Vector{Vector{Int64}}=[Int64[]],\n coincident_peak_load_charge_per_kw::AbstractVector{<:Real}=Real[]\n ) where {\n T1 <: Union{Nothing, Int, Float64, Array}, \n T2 <: Union{Nothing, Int, Float64, Array}, \n S <: Union{Nothing, Int, Float64}, \n R <: Union{Nothing, Int, Float64}\n }\n```\n\n!!! note\n The `NEM` boolean is determined by the ElectricUtility.net_metering_limit_kw. There is no need to pass in a `NEM`\n value.\n \n\"\"\"\nfunction ElectricTariff(;\n urdb_label::String=\"\",\n urdb_response::Dict=Dict(),\n urdb_utility_name::String=\"\",\n urdb_rate_name::String=\"\",\n year::Int=2020,\n time_steps_per_hour::Int=1,\n NEM::Bool=false,\n wholesale_rate::T1=nothing,\n export_rate_beyond_net_metering_limit::T2=nothing,\n monthly_energy_rates::Array=[],\n monthly_demand_rates::Array=[],\n blended_annual_energy_rate::S=nothing,\n blended_annual_demand_rate::R=nothing,\n add_monthly_rates_to_urdb_rate::Bool=false,\n tou_energy_rates_per_kwh::Array=[],\n add_tou_energy_rates_to_urdb_rate::Bool=false,\n remove_tiers::Bool=false,\n demand_lookback_months::AbstractArray{Int64, 1}=Int64[],\n demand_lookback_percent::Float64=0.0,\n demand_lookback_range::Int=0,\n coincident_peak_load_active_time_steps::Vector{Vector{Int64}}=[Int64[]],\n coincident_peak_load_charge_per_kw::AbstractVector{<:Real}=Real[]\n ) where {\n T1 <: Union{Nothing, Int, Float64, Array}, \n T2 <: Union{Nothing, Int, Float64, Array}, \n S <: Union{Nothing, Int, Float64}, \n R <: Union{Nothing, Int, Float64}\n }\n # TODO remove_tiers for multinode models\n nem_rate = Float64[]\n\n energy_tier_limits = Float64[]\n n_energy_tiers = 1\n monthly_demand_tier_limits = Float64[]\n n_monthly_demand_tiers = 1\n tou_demand_tier_limits = Float64[]\n n_tou_demand_tiers = 1\n time_steps_monthly = get_monthly_time_steps(year, time_steps_per_hour=time_steps_per_hour)\n\n u = nothing\n if !isempty(urdb_response)\n\n u = URDBrate(urdb_response, year, time_steps_per_hour=time_steps_per_hour)\n\n elseif !isempty(urdb_label)\n\n u = URDBrate(urdb_label, year, time_steps_per_hour=time_steps_per_hour)\n\n elseif !isempty(urdb_utility_name) && !isempty(urdb_rate_name)\n\n u = URDBrate(urdb_utility_name, urdb_rate_name, year, time_steps_per_hour=time_steps_per_hour)\n\n elseif !isempty(tou_energy_rates_per_kwh) && length(tou_energy_rates_per_kwh) == 8760*time_steps_per_hour\n\n tou_demand_rates = Float64[]\n tou_demand_ratchet_time_steps = []\n energy_rates = tou_energy_rates_per_kwh\n monthly_demand_rates = convert(Array{Float64}, monthly_demand_rates)\n\n fixed_monthly_charge = 0.0\n annual_min_charge = 0.0\n min_monthly_charge = 0.0\n\n if NEM\n nem_rate = [-0.999 * x for x in energy_rates]\n end\n\n elseif !isempty(monthly_energy_rates)\n\n invalid_args = String[]\n if !(length(monthly_energy_rates) == 12)\n push!(invalid_args, \"length(monthly_energy_rates) must equal 12, got length $(length(monthly_energy_rates))\")\n end\n if !isempty(monthly_demand_rates) && !(length(monthly_demand_rates) == 12)\n push!(invalid_args, \"length(monthly_demand_rates) must equal 12, got length $(length(monthly_demand_rates))\")\n end\n if length(invalid_args) > 0\n error(\"Invalid argument values: $(invalid_args)\")\n end\n\n if isempty(monthly_demand_rates)\n monthly_demand_rates = repeat([0.0], 12)\n end\n\n tou_demand_rates = Float64[]\n tou_demand_ratchet_time_steps = []\n energy_rates = Real[]\n for m in 1:12\n append!(energy_rates, [monthly_energy_rates[m] for ts in time_steps_monthly[m]])\n end\n\n fixed_monthly_charge = 0.0\n annual_min_charge = 0.0\n min_monthly_charge = 0.0\n\n if NEM\n nem_rate = [-0.999 * x for x in energy_rates]\n end\n\n elseif !isnothing(blended_annual_energy_rate)\n\n tou_demand_rates = Float64[]\n tou_demand_ratchet_time_steps = []\n energy_rates = repeat(Real[blended_annual_energy_rate], 8760 * time_steps_per_hour)\n if !isnothing(blended_annual_demand_rate)\n monthly_demand_rates = repeat(Real[blended_annual_demand_rate], 12)\n end\n if isempty(monthly_demand_rates)\n monthly_demand_rates = repeat([0.0], 12)\n end\n\n fixed_monthly_charge = 0.0\n annual_min_charge = 0.0\n min_monthly_charge = 0.0\n\n if NEM\n nem_rate = [-0.999 * x for x in energy_rates]\n end\n\n else\n error(\"Creating ElectricTariff requires at least urdb_label, urdb_response, monthly rates, annual rates, or tou_energy_rates_per_kwh.\")\n end\n\n if !isnothing(u) # use URDBrate\n\n if NEM\n t = get_tier_with_lowest_energy_rate(u)\n nem_rate = [-0.999 * x for x in u.energy_rates[t,:]]\n end\n\n energy_rates = u.energy_rates\n energy_tier_limits = u.energy_tier_limits\n n_energy_tiers = u.n_energy_tiers\n users_monthly_demand_rates = copy(monthly_demand_rates)\n monthly_demand_rates = u.monthly_demand_rates\n monthly_demand_tier_limits = u.monthly_demand_tier_limits\n n_monthly_demand_tiers = u.n_monthly_demand_tiers\n tou_demand_rates = u.tou_demand_rates\n tou_demand_tier_limits = u.tou_demand_tier_limits\n n_tou_demand_tiers = u.n_tou_demand_tiers\n\n if remove_tiers\n energy_rates, monthly_demand_rates, tou_demand_rates = remove_tiers_from_urdb_rate(u)\n energy_tier_limits, monthly_demand_tier_limits, tou_demand_tier_limits = \n Float64[], Float64[], Float64[]\n n_energy_tiers, n_monthly_demand_tiers, n_tou_demand_tiers = 1, 1, 1\n end\n\n tou_demand_ratchet_time_steps = u.tou_demand_ratchet_time_steps\n demand_lookback_months = u.demand_lookback_months\n demand_lookback_percent = u.demand_lookback_percent\n demand_lookback_range = u.demand_lookback_range\n fixed_monthly_charge = u.fixed_monthly_charge\n annual_min_charge = u.annual_min_charge\n min_monthly_charge = u.min_monthly_charge\n\n if add_monthly_rates_to_urdb_rate \n if length(monthly_energy_rates) == 12\n for tier in 1:size(energy_rates, 2), mth in 1:12, ts in time_steps_monthly[mth]\n energy_rates[ts, tier] += monthly_energy_rates[mth]\n end\n end\n if length(users_monthly_demand_rates) == 12\n for tier in 1:size(monthly_demand_rates, 2), mth in 1:12\n monthly_demand_rates[mth, tier] += users_monthly_demand_rates[mth]\n end\n end\n end\n\n if add_tou_energy_rates_to_urdb_rate && length(tou_energy_rates_per_kwh) == size(energy_rates, 1)\n for tier in 1:size(energy_rates, 2)\n energy_rates[1:end, tier] += tou_energy_rates_per_kwh\n end\n end\n else\n # need to reshape cost vectors to arrays (2nd dim is for tiers)\n energy_rates = reshape(energy_rates, :, 1)\n monthly_demand_rates = reshape(monthly_demand_rates, :, 1)\n tou_demand_rates = reshape(tou_demand_rates, :, 1)\n end\n\n #= export_rates\n There are three Export tiers and their associated export rates (negative values):\n 1. NEM (Net Energy Metering)\n 2. WHL (Wholesale)\n 3. EXC (Excess, beyond NEM)\n\n Only one of NEM and Wholesale can be exported into due to the binary constraints.\n Excess can be exported into in the same time step as NEM.\n\n Excess is meant to be combined with NEM: NEM export is limited to the total grid purchased energy in a year and some\n utilities offer a compensation mechanism for export beyond the site load.\n The Excess tier is not available with the Wholesale tier.\n\n - if NEM then set ExportRate[:Nem, :] to energy_rate[tier_with_lowest_energy_rate, :]\n - user can provide either scalar wholesale rate or vector of time_steps, \n =#\n whl_rate = create_export_rate(wholesale_rate, length(energy_rates), time_steps_per_hour)\n if !isnothing(u) && sum(u.sell_rates) < 0\n whl_rate += u.sell_rates\n end\n exc_rate = create_export_rate(export_rate_beyond_net_metering_limit, length(energy_rates), time_steps_per_hour)\n \n if !NEM & (sum(whl_rate) >= 0)\n export_rates = Dict{Symbol, AbstractArray}()\n export_bins = Symbol[]\n elseif !NEM\n export_bins = [:WHL]\n export_rates = Dict(:WHL => whl_rate)\n elseif (sum(whl_rate) >= 0)\n export_bins = [:NEM]\n export_rates = Dict(:NEM => nem_rate)\n if sum(exc_rate) < 0\n push!(export_bins, :EXC)\n export_rates[:EXC] = exc_rate\n end\n else\n export_bins = [:NEM, :WHL]\n export_rates = Dict(:NEM => nem_rate, :WHL => whl_rate)\n if sum(exc_rate) < 0\n push!(export_bins, :EXC)\n export_rates[:EXC] = exc_rate\n end\n end\n\n coincpeak_periods = Int64[]\n if !isempty(coincident_peak_load_charge_per_kw)\n coincpeak_periods = collect(1:length(coincident_peak_load_charge_per_kw))\n end\n\n ElectricTariff(\n energy_rates,\n energy_tier_limits,\n n_energy_tiers,\n monthly_demand_rates,\n time_steps_monthly,\n monthly_demand_tier_limits,\n n_monthly_demand_tiers,\n tou_demand_rates,\n tou_demand_ratchet_time_steps,\n tou_demand_tier_limits,\n n_tou_demand_tiers,\n demand_lookback_months,\n demand_lookback_percent,\n demand_lookback_range,\n fixed_monthly_charge,\n annual_min_charge,\n min_monthly_charge,\n export_rates,\n export_bins,\n coincident_peak_load_active_time_steps,\n coincident_peak_load_charge_per_kw,\n coincpeak_periods\n )\nend\n\n\nfunction get_tier_with_lowest_energy_rate(u::URDBrate)\n \"\"\"\n ExportRate should be lowest energy cost for tiered rates. \n Otherwise, ExportRate can be > FuelRate, which leads REopt to export all PV energy produced.\n \"\"\"\n tier_with_lowest_energy_cost = 1\n if length(u.energy_tier_limits) > 1\n annual_energy_charge_sums = Float64[]\n for etier in u.energy_rates\n push!(annual_energy_charge_sums, sum(etier))\n end\n tier_with_lowest_energy_cost = \n findall(annual_energy_charge_sums .== minimum(annual_energy_charge_sums))[1]\n end\n return tier_with_lowest_energy_cost\nend\n\n\n\"\"\"\n function create_export_rate(e::Nothing, N::Int, ts_per_hour::Int=1)\nNo export rate provided by user: set to 0 dollars/kWh for all time\n\"\"\"\nfunction create_export_rate(e::Nothing, N::Int, ts_per_hour::Int=1)\n [0 for _ in range(1, stop=N) for ts in 1:ts_per_hour]\nend\n\n\n\"\"\"\n function create_export_rate(e::T, N::Int, ts_per_hour::Int=1) where T<:Real\nCase for scaler export rate provided -> convert to array of time_steps\n\"\"\"\nfunction create_export_rate(e::T, N::Int, ts_per_hour::Int=1) where T<:Real\n repeat(float(-1*e), N * ts_per_hour)\nend\n\n\n\"\"\"\n function create_export_rate(e::AbstractArray{<:Real, 1}, N::Int, ts_per_hour::Int=1)\n\nCheck length of e and upsample if length(e) != N\n\"\"\"\nfunction create_export_rate(e::AbstractArray{<:Real, 1}, N::Int, ts_per_hour::Int=1)\n Ne = length(e)\n if Ne != Int(N/ts_per_hour) || Ne != N\n @error \"Export rates do not have correct number of entries. Must be $(N) or $(Int(N/ts_per_hour)).\"\n end\n if Ne != N # upsample\n export_rates = [-1*x for x in e for ts in 1:ts_per_hour]\n else\n export_rates = -1*e\n end\n return export_rates\nend\n\n\n\"\"\"\n get_monthly_time_steps(year::Int; time_steps_per_hour=1)\n\nreturn Array{Array{Int64,1},1}, size = (12,)\n\"\"\"\nfunction get_monthly_time_steps(year::Int; time_steps_per_hour=1)\n a = Array[]\n i = 1\n for m in range(1, stop=12)\n n_days = daysinmonth(Date(string(year) * \"-\" * string(m)))\n stop = n_days * 24 * time_steps_per_hour + i - 1\n if m == 2 && isleapyear(year)\n stop -= 24 * time_steps_per_hour # TODO support extra day in leap years?\n end\n steps = [step for step in range(i, stop=stop)]\n append!(a, [steps])\n i = stop + 1\n end\n return a\nend\n\n# TODO use this function only for URDBrate\nfunction remove_tiers_from_urdb_rate(u::URDBrate)\n # tariff args: have to validate that there are no tiers\n if length(u.energy_tier_limits) > 1\n @warn \"Energy rate contains tiers. Using the first tier!\"\n end\n elec_rates = vec(u.energy_rates[1,:])\n\n if u.n_monthly_demand_tiers > 1\n @warn \"Monthly demand rate contains tiers. Using the last tier!\"\n end\n if u.n_monthly_demand_tiers > 0\n demand_rates_monthly = vec(u.monthly_demand_rates[:,u.n_monthly_demand_tiers])\n else\n demand_rates_monthly = vec(u.monthly_demand_rates) # 0×0 Array{Float64,2}\n end\n\n if u.n_tou_demand_tiers > 1\n @warn \"TOU demand rate contains tiers. Using the last tier!\"\n end\n if u.n_tou_demand_tiers > 0\n demand_rates = vec(u.tou_demand_rates[:,u.n_tou_demand_tiers])\n else\n demand_rates = vec(u.tou_demand_rates)\n end\n\n return elec_rates, demand_rates_monthly, demand_rates\nend\n", "meta": {"hexsha": "56ffb0ac5befc216d835358215b2d34466199663", "size": 17390, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core/electric_tariff.jl", "max_stars_repo_name": "NREL/REopt", "max_stars_repo_head_hexsha": "cece86212568ca6171e01469eab0bac9af6eb561", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-08T02:00:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:03:51.000Z", "max_issues_repo_path": "src/core/electric_tariff.jl", "max_issues_repo_name": "NREL/REopt", "max_issues_repo_head_hexsha": "cece86212568ca6171e01469eab0bac9af6eb561", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2022-02-08T15:51:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T02:50:48.000Z", "max_forks_repo_path": "src/core/electric_tariff.jl", "max_forks_repo_name": "NREL/REopt", "max_forks_repo_head_hexsha": "cece86212568ca6171e01469eab0bac9af6eb561", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-16T17:07:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T17:07:24.000Z", "avg_line_length": 36.843220339, "max_line_length": 143, "alphanum_fraction": 0.6861414606, "num_tokens": 4458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.24971927279901593}} {"text": "\"\"\"\n Controls(mitigate, remove, geoeng, adapt)\n\nCreate data structure for climate controls.\n\n# Examples\n```jldoctest\na = zeros(4);\nC = Controls(a, a, a, a);\nC.geoeng\n\n# output\n4-element Array{Float64,1}:\n 0.0\n 0.0\n 0.0\n 0.0\n```\n\nSee also: [`ClimateModel`](@ref)\n\"\"\"\nmutable struct Controls\n mitigate::Array{Float64,1}\n remove::Array{Float64,1}\n geoeng::Array{Float64,1}\n adapt::Array{Float64,1}\nend", "meta": {"hexsha": "c1f3bc1ecce74e1b1af08453632a3eda47f1b58a", "size": 413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Models/controls.jl", "max_stars_repo_name": "pitmonticone/ClimateMARGO.jl", "max_stars_repo_head_hexsha": "0d89578cc22c0034aedf2a747fe1840603c3cec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-11-03T17:10:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:53:29.000Z", "max_issues_repo_path": "src/Models/controls.jl", "max_issues_repo_name": "pitmonticone/ClimateMARGO.jl", "max_issues_repo_head_hexsha": "0d89578cc22c0034aedf2a747fe1840603c3cec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-10-25T23:12:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T13:18:09.000Z", "max_forks_repo_path": "src/Models/controls.jl", "max_forks_repo_name": "pitmonticone/ClimateMARGO.jl", "max_forks_repo_head_hexsha": "0d89578cc22c0034aedf2a747fe1840603c3cec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-11-24T11:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T13:11:35.000Z", "avg_line_length": 15.2962962963, "max_line_length": 45, "alphanum_fraction": 0.6585956416, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.24961891798924277}} {"text": "#####\n##### 'Tupled closure' implementation: 1-tuple, 2-tuple, and then n-tuple by induction\n#####\n\n#####\n##### Stress divergences\n#####\n\nfor stress_div in (:∂ⱼ_τ₁ⱼ, :∂ⱼ_τ₂ⱼ, :∂ⱼ_τ₃ⱼ)\n @eval begin\n @inline $stress_div(i, j, k, grid::AbstractGrid, closures::Tuple{<:Any}, clock, U, Ks, args...) =\n $stress_div(i, j, k, grid, closures[1], clock, U, Ks[1], args...)\n\n @inline $stress_div(i, j, k, grid::AbstractGrid, closures::Tuple{<:Any, <:Any}, clock, U, Ks, args...) = (\n $stress_div(i, j, k, grid, closures[1], clock, U, Ks[1], args...)\n + $stress_div(i, j, k, grid, closures[2], clock, U, Ks[2], args...))\n\n @inline $stress_div(i, j, k, grid::AbstractGrid, closures::Tuple{<:Any, <:Any, <:Any}, clock, U, Ks, args...) = (\n $stress_div(i, j, k, grid, closures[1], clock, U, Ks[1], args...)\n + $stress_div(i, j, k, grid, closures[2], clock, U, Ks[2], args...) \n + $stress_div(i, j, k, grid, closures[3], clock, U, Ks[3], args...))\n\n @inline $stress_div(i, j, k, grid::AbstractGrid, closures::Tuple, clock, U, Ks, args...) = (\n $stress_div(i, j, k, grid, closures[1:2], clock, U, Ks[1:2], args...)\n + $stress_div(i, j, k, grid, closures[3:end], clock, U, Ks[3:end], args...))\n end\nend\n\n#####\n##### Tracer flux divergences\n#####\n\n@inline ∇_dot_qᶜ(i, j, k, grid::AbstractGrid, closures::Tuple{<:Any}, c, iᶜ, clock, Ks, args...) =\n ∇_dot_qᶜ(i, j, k, grid, closures[1], c, iᶜ, clock, Ks[1], args...)\n\n@inline ∇_dot_qᶜ(i, j, k, grid::AbstractGrid, closures::Tuple{<:Any, <:Any}, c, iᶜ, clock, Ks, args...) = (\n ∇_dot_qᶜ(i, j, k, grid, closures[1], c, iᶜ, clock, Ks[1], args...)\n + ∇_dot_qᶜ(i, j, k, grid, closures[2], c, iᶜ, clock, Ks[2], args...))\n\n@inline ∇_dot_qᶜ(i, j, k, grid::AbstractGrid, closures::Tuple{<:Any, <:Any, <:Any}, c, iᶜ, clock, Ks, args...) = (\n ∇_dot_qᶜ(i, j, k, grid, closures[1], c, iᶜ, clock, Ks[1], args...)\n + ∇_dot_qᶜ(i, j, k, grid, closures[2], c, iᶜ, clock, Ks[2], args...) \n + ∇_dot_qᶜ(i, j, k, grid, closures[3], c, iᶜ, clock, Ks[3], args...))\n\n@inline ∇_dot_qᶜ(i, j, k, grid::AbstractGrid, closures::Tuple, c, iᶜ, clock, Ks, args...) = (\n ∇_dot_qᶜ(i, j, k, grid, closures[1:2], c, iᶜ, clock, Ks[1:2], args...)\n + ∇_dot_qᶜ(i, j, k, grid, closures[3:end], c, iᶜ, clock, Ks[3:end], args...))\n\n#####\n##### Utilities\n#####\n\nwith_tracers(tracers, closure_tuple::Tuple) =\n Tuple(with_tracers(tracers, closure) for closure in closure_tuple)\n\nfunction calculate_diffusivities!(diffusivity_fields_tuple, closure_tuple::Tuple, args...)\n for (α, closure) in enumerate(closure_tuple)\n @inbounds diffusivity_fields = diffusivity_fields_tuple[α]\n calculate_diffusivities!(diffusivity_fields, closure, args...)\n end\n return nothing\nend\n\n#####\n##### Support for VerticallyImplicitTimeDiscretization\n#####\n\nconst EC = AbstractTurbulenceClosure{<:ExplicitTimeDiscretization}\nconst VIC = AbstractTurbulenceClosure{<:VerticallyImplicitTimeDiscretization}\n\n# Filter explicitly-discretized closures.\n@inline z_diffusivity(clo::Tuple{<:EC}, iᶜ, Ks, args...) = tuple(0)\n@inline z_diffusivity(clo::Tuple{<:VIC}, iᶜ, Ks, args...) = tuple(z_diffusivity(clo[1], iᶜ, Ks[1], args...))\n@inline z_diffusivity(clo::Tuple{<:VIC, <:EC}, iᶜ, Ks, args...) = tuple(z_diffusivity(clo[1], iᶜ, Ks[1], args...))\n@inline z_diffusivity(clo::Tuple{<:EC, <:VIC}, iᶜ, Ks, args...) = tuple(z_diffusivity(clo[2], iᶜ, Ks[2], args...))\n\n@inline z_diffusivity(clo::Tuple{<:VIC, <:VIC}, iᶜ, Ks, args...) = tuple(z_diffusivity(clo[1], iᶜ, Ks[1], args...),\n z_diffusivity(clo[2], iᶜ, Ks[2], args...))\n\n@inline z_diffusivity(clo::Tuple, iᶜ, Ks, args...) = tuple(z_diffusivity(clo[1:2], iᶜ, Ks[1:2], args...)...,\n z_diffusivity(clo[3:end], iᶜ, Ks[3:end], args...)...)\n\n@inline z_viscosity(clo::Tuple{<:EC}, Ks, args...) = tuple(0)\n@inline z_viscosity(clo::Tuple{<:VIC}, Ks, args...) = tuple(z_viscosity(clo[1], Ks[1], args...))\n@inline z_viscosity(clo::Tuple{<:VIC, <:EC}, Ks, args...) = tuple(z_viscosity(clo[1], Ks[1], args...))\n@inline z_viscosity(clo::Tuple{<:EC, <:VIC}, Ks, args...) = tuple(z_viscosity(clo[2], Ks[2], args...))\n\n@inline z_viscosity(clo::Tuple{<:VIC, <:VIC}, Ks, args...) = tuple(z_viscosity(clo[1], Ks[1], args...),\n z_viscosity(clo[2], Ks[2], args...))\n\n@inline z_viscosity(clo::Tuple, Ks, args...) = tuple(z_viscosity(clo[1:2], Ks[1:2], args...)...,\n z_viscosity(clo[3:end], Ks[3:end], args...)...)\n\nfor coeff in (:νᶜᶜᶜ, :νᶠᶠᶜ, :νᶠᶜᶠ, :νᶜᶠᶠ, :κᶜᶜᶠ, :κᶜᶠᶜ, :κᶠᶜᶜ)\n @eval begin\n @inline $coeff(i, j, k, grid, clock, ν::Tuple{C1}) where C1 = $coeff(i, j, k, grid, clock, ν[1])\n @inline $coeff(i, j, k, grid, clock, ν::Tuple{C1, C2}) where {C1, C2} = $coeff(i, j, k, grid, clock, ν[1]) + $coeff(i, j, k, grid, clock, ν[2])\n @inline $coeff(i, j, k, grid, clock, ν::Tuple) = $coeff(i, j, k, grid, clock, ν[1:2]) + $coeff(i, j, k, grid, clock, ν[3:end])\n end\nend\n\nconst ImplicitClosure = AbstractTurbulenceClosure{TD} where TD <: VerticallyImplicitTimeDiscretization\nconst ExplicitOrNothing = Union{ExplicitTimeDiscretization, Nothing}\n\n@inline combine_time_discretizations(disc) = disc\n\n@inline combine_time_discretizations(::ExplicitTimeDiscretization, ::VerticallyImplicitTimeDiscretization) = VerticallyImplicitTimeDiscretization()\n@inline combine_time_discretizations(::VerticallyImplicitTimeDiscretization, ::ExplicitTimeDiscretization) = VerticallyImplicitTimeDiscretization()\n@inline combine_time_discretizations(::VerticallyImplicitTimeDiscretization, ::VerticallyImplicitTimeDiscretization) = VerticallyImplicitTimeDiscretization()\n@inline combine_time_discretizations(::ExplicitTimeDiscretization, ::ExplicitTimeDiscretization) = ExplicitTimeDiscretization()\n\n@inline combine_time_discretizations(disc1, disc2, other_discs...) =\n combine_time_discretizations(combine_time_discretizations(disc1, disc2), other_discs...)\n\n@inline time_discretization(closures::Tuple) = combine_time_discretizations(time_discretization.(closures)...)\n", "meta": {"hexsha": "96e53071c81042b042e5a9b1cedd6753a589634e", "size": 6470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TurbulenceClosures/closure_tuples.jl", "max_stars_repo_name": "chemicalfiend/Oceananigans.jl", "max_stars_repo_head_hexsha": "04ca8e2f143afd53fd60bdaeb885a4dc1ed5825c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TurbulenceClosures/closure_tuples.jl", "max_issues_repo_name": "chemicalfiend/Oceananigans.jl", "max_issues_repo_head_hexsha": "04ca8e2f143afd53fd60bdaeb885a4dc1ed5825c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TurbulenceClosures/closure_tuples.jl", "max_forks_repo_name": "chemicalfiend/Oceananigans.jl", "max_forks_repo_head_hexsha": "04ca8e2f143afd53fd60bdaeb885a4dc1ed5825c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-10T17:23:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-16T16:35:12.000Z", "avg_line_length": 55.775862069, "max_line_length": 157, "alphanum_fraction": 0.6, "num_tokens": 2265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24956931203338625}} {"text": "\"\"\"\nspin15.jl - T1 optimized pulses\n\"\"\"\n\nWDIR = get(ENV, \"ROBUST_QOC_PATH\", \"../../\")\ninclude(joinpath(WDIR, \"src\", \"spin\", \"spin.jl\"))\n\nusing Altro\nusing HDF5\nusing LinearAlgebra\nusing RobotDynamics\nusing StaticArrays\nusing TrajectoryOptimization\nconst RD = RobotDynamics\nconst TO = TrajectoryOptimization\n\n# paths\nconst EXPERIMENT_META = \"spin\"\nconst EXPERIMENT_NAME = \"spin15\"\nconst SAVE_PATH = abspath(joinpath(WDIR, \"out\", EXPERIMENT_META, EXPERIMENT_NAME))\n\n# problem\nconst CONTROL_COUNT = 1\nconst STATE_COUNT = 2\nconst ASTATE_SIZE_BASE = STATE_COUNT * HDIM_ISO + 3 * CONTROL_COUNT\n# state indices\nconst STATE1_IDX = 1:HDIM_ISO\nconst STATE2_IDX = STATE1_IDX[end] + 1:STATE1_IDX[end] + HDIM_ISO\nconst INTCONTROLS_IDX = STATE2_IDX[end] + 1:STATE2_IDX[end] + CONTROL_COUNT\nconst CONTROLS_IDX = INTCONTROLS_IDX[end] + 1:INTCONTROLS_IDX[end] + CONTROL_COUNT\nconst DCONTROLS_IDX = CONTROLS_IDX[end] + 1:CONTROLS_IDX[end] + CONTROL_COUNT\nconst INTGAMMA_IDX = DCONTROLS_IDX[end] + 1:DCONTROLS_IDX[end] + 1\n# control indices\nconst D2CONTROLS_IDX = 1:CONTROL_COUNT\nconst DT_IDX = D2CONTROLS_IDX[end] + 1:D2CONTROLS_IDX[end] + 1\n\n\n# model\n# DA = decay aware, TO = time optimal\nstruct Model{DA, TO} <: AbstractModel\n Model(DA::Bool=true, TO::Bool=true) = new{DA, TO}()\nend\n@inline RD.state_dim(::Model{false, TO}) where TO = ASTATE_SIZE_BASE\n@inline RD.state_dim(::Model{true, TO}) where TO = ASTATE_SIZE_BASE + 1\n@inline RD.control_dim(::Model{DA, false}) where DA = CONTROL_COUNT\n@inline RD.control_dim(::Model{DA, true}) where DA = CONTROL_COUNT + 1\n\n\n# dynamics\nfunction RD.discrete_dynamics(::Type{RK3}, model::Model{DA, TO}, astate::StaticVector,\n acontrols::StaticVector, time::Real, dt::Real) where {DA, TO}\n if TO\n dt = acontrols[DT_IDX[1]]^2\n end\n \n h_prop = exp(dt * (FQ_NEGI_H0_ISO + astate[CONTROLS_IDX[1]] * NEGI_H1_ISO))\n state1 = h_prop * astate[STATE1_IDX]\n state2 = h_prop * astate[STATE2_IDX]\n intcontrols = astate[INTCONTROLS_IDX[1]] + dt * astate[CONTROLS_IDX[1]]\n controls = astate[CONTROLS_IDX[1]] + dt * astate[DCONTROLS_IDX[1]]\n dcontrols = astate[DCONTROLS_IDX[1]] + dt * acontrols[D2CONTROLS_IDX[1]]\n astate_ = [\n state1; state2; intcontrols; controls; dcontrols;\n ]\n \n if DA\n intgamma = (astate[INTGAMMA_IDX[1]] +\n dt * amp_t1_reduced_spline(astate[CONTROLS_IDX[1]])^(-1))\n push!(astate_, intgamma)\n end\n \n return astate_\nend\n\n\n# main\nfunction run_traj(;evolution_time=21.61, gate_type=zpiby2, time_optimal=false,\n decay_aware=false, solver_type=altro, sqrtbp=false,\n integrator_type=rk3, qs=[1e0, 1e0, 1e0, 1e-1, 1e2, 1e-1, 5e2],\n smoke_test=false,\n al_tol=1e-4, constraint_tol=1e-8, max_penalty=1e11,\n pn_steps=2, save=true, verbose=true, dt_inv=Int64(1e1),\n max_cost_value=1e8, max_iterations=Int64(2e5),\n benchmark=false,)\n # model configuration\n dt = dt_inv^(-1)\n dt_max = (dt_inv / 2)^(-1)\n dt_min = (dt_inv * 2)^(-1)\n model = Model(decay_aware, time_optimal)\n n = state_dim(model)\n m = control_dim(model)\n t0 = 0.\n\n # initial state\n x0 = zeros(n)\n x0[STATE1_IDX] = IS1_ISO_\n x0[STATE2_IDX] = IS2_ISO_\n x0 = SVector{n}(x0)\n \n # final state\n if gate_type == xpiby2\n target_state1 = Array(XPIBY2_ISO_1)\n target_state2 = Array(XPIBY2_ISO_2)\n elseif gate_type == ypiby2\n target_state1 = Array(YPIBY2_ISO_1)\n target_state2 = Array(YPIBY2_ISO_2)\n elseif gate_type == zpiby2\n target_state1 = Array(ZPIBY2_ISO_1)\n target_state2 = Array(ZPIBY2_ISO_2)\n end\n xf = zeros(n)\n xf[STATE1_IDX] = target_state1\n xf[STATE2_IDX] = target_state2\n xf = SVector{n}(xf)\n \n # control amplitude constraint\n x_max = fill(Inf, n)\n x_max[CONTROLS_IDX] .= MAX_CONTROL_NORM_0\n x_max = SVector{n}(x_max)\n x_min = fill(-Inf, n)\n x_min[CONTROLS_IDX] .= -MAX_CONTROL_NORM_0\n x_min = SVector{n}(x_min)\n \n # control amplitude constraint at boundary\n x_max_boundary = fill(Inf, n)\n x_max_boundary[CONTROLS_IDX] .= 0\n x_max_boundary = SVector{n}(x_max_boundary)\n x_min_boundary = fill(-Inf, n)\n x_min_boundary[CONTROLS_IDX] .= 0\n x_min_boundary = SVector{n}(x_min_boundary)\n\n # dt bound\n u_max = SVector{m}([\n fill(Inf, CONTROL_COUNT);\n fill(sqrt(dt_max), eval(:($time_optimal ? 1 : 0))); #dt\n ])\n u_min = SVector{m}([\n fill(-Inf, CONTROL_COUNT);\n fill(sqrt(dt_min), eval(:($time_optimal ? 1 : 0))); #dt\n ])\n\n # initial trajectory\n N = Int(floor(evolution_time * dt_inv)) + 1\n U0 = [SVector{m}([\n fill(1e-4, CONTROL_COUNT);\n fill(sqrt(dt), eval(:($time_optimal ? 1 : 0)));\n ]) for k = 1:N - 1]\n X0 = [SVector{n}(\n fill(NaN, n)\n ) for k = 1:N]\n dt_ = time_optimal ? 1 : dt\n Z = Traj(X0, U0, dt_ * ones(N))\n\n # cost function\n Q = Diagonal(SVector{n}([\n fill(qs[1], STATE_COUNT * HDIM_ISO); # ψ1, ψ2\n fill(qs[2], CONTROL_COUNT); # ∫a\n fill(qs[3], CONTROL_COUNT); # a\n fill(qs[4], CONTROL_COUNT); # ∂a\n fill(qs[5], eval(:($decay_aware ? 1 : 0))); # ∫γ1\n ]))\n Qf = Q * N\n R = Diagonal(SVector{m}([\n fill(qs[6], CONTROL_COUNT); # ∂2a\n fill(qs[7], eval(:($time_optimal ? 1 : 0))); # Δt\n ]))\n objective = LQRObjective(Q, R, Qf, xf, N)\n\n # constraints\n # must satisfy control amplitude bound\n control_bnd = BoundConstraint(n, m, x_max=x_max, x_min=x_min)\n # must statisfy conrols start and end at 0\n control_bnd_boundary = BoundConstraint(n, m, x_max=x_max_boundary, x_min=x_min_boundary)\n # must satisfy dt bound\n dt_bnd = BoundConstraint(n, m, u_max=u_max, u_min=u_min)\n # must reach target state, must have zero net flux\n target_astate_constraint = GoalConstraint(xf, [STATE1_IDX; STATE2_IDX; INTCONTROLS_IDX])\n # must obey unit norm\n norm_constraints = [NormConstraint(n, m, 1, TO.Equality(), idx)\n for idx in [STATE1_IDX, STATE2_IDX]]\n \n constraints = ConstraintList(n, m, N)\n add_constraint!(constraints, control_bnd, 2:N-2)\n add_constraint!(constraints, control_bnd_boundary, N-1:N-1)\n add_constraint!(constraints, target_astate_constraint, N:N)\n for norm_constraint in norm_constraints\n add_constraint!(constraints, norm_constraint, 2:N-1)\n end\n if time_optimal\n add_constraint!(constraints, dt_bnd, 1:N-1)\n end\n\n # solve problem\n prob = Problem{IT_RDI[integrator_type]}(model, objective, constraints,\n x0, xf, Z, N, t0, evolution_time)\n solver = ALTROSolver(prob)\n verbose_pn = verbose ? true : false\n verbose_ = verbose ? 2 : 0\n projected_newton = solver_type == altro ? true : false\n constraint_tolerance = solver_type == altro ? constraint_tol : al_tol\n iterations_inner = smoke_test ? 1 : 300\n iterations_outer = smoke_test ? 1 : 30\n n_steps = smoke_test ? 1 : pn_steps\n set_options!(solver, square_root=sqrtbp, constraint_tolerance=constraint_tolerance,\n projected_newton_tolerance=al_tol, n_steps=n_steps,\n penalty_max=max_penalty, verbose_pn=verbose_pn, verbose=verbose_,\n projected_newton=projected_newton, iterations_inner=iterations_inner,\n iterations_outer=iterations_outer, iterations=max_iterations,\n max_cost_value=max_cost_value)\n if benchmark\n benchmark_result = Altro.benchmark_solve!(solver)\n else\n benchmark_result = nothing\n Altro.solve!(solver)\n end\n\n # Post-process.\n acontrols_raw = TO.controls(solver)\n acontrols_arr = permutedims(reduce(hcat, map(Array, acontrols_raw)), [2, 1])\n astates_raw = TO.states(solver)\n astates_arr = permutedims(reduce(hcat, map(Array, astates_raw)), [2, 1])\n Q_raw = Array(Q)\n Q_arr = [Q_raw[i, i] for i in 1:size(Q_raw)[1]]\n Qf_raw = Array(Qf)\n Qf_arr = [Qf_raw[i, i] for i in 1:size(Qf_raw)[1]]\n R_raw = Array(R)\n R_arr = [R_raw[i, i] for i in 1:size(R_raw)[1]]\n cidx_arr = Array(CONTROLS_IDX)\n d2cidx_arr = Array(D2CONTROLS_IDX)\n dtidx_arr = Array(DT_IDX)\n # Square the dts.\n if time_optimal\n acontrols_arr[:, DT_IDX] = acontrols_arr[:, DT_IDX] .^2\n # acontrols_arr[:, DT_IDX] = map(abs, acontrols_arr[:, DT_IDX])\n end\n cmax = TO.max_violation(solver)\n cmax_info = TO.findmax_violation(TO.get_constraints(solver))\n iterations_ = iterations(solver)\n\n result = Dict(\n \"acontrols\" => acontrols_arr,\n \"controls_idx\" => cidx_arr,\n \"d2controls_dt2_idx\" => d2cidx_arr,\n \"dt_idx\" => dtidx_arr,\n \"evolution_time\" => evolution_time,\n \"astates\" => astates_arr,\n \"Q\" => Q_arr,\n \"Qf\" => Qf_arr,\n \"R\" => R_arr,\n \"cmax\" => cmax,\n \"cmax_info\" => cmax_info,\n \"dt\" => dt,\n \"solver_type\" => Integer(solver_type),\n \"sqrtbp\" => Integer(sqrtbp),\n \"max_penalty\" => max_penalty,\n \"constraint_tol\" => constraint_tol,\n \"al_tol\" => al_tol,\n \"integrator_type\" => Integer(integrator_type),\n \"gate_type\" => Integer(gate_type),\n \"save_type\" => Integer(jl),\n \"iterations\" => iterations_,\n \"pn_steps\" => pn_steps,\n \"max_iterations\" => max_iterations,\n \"max_cost_value\" => max_cost_value,\n )\n\n if time_optimal\n # sample the important metrics\n (controls_sample, d2controls_dt2_sample, evolution_time_sample\n ) = sample_controls(save_file_path)\n result[\"controls_sample\"] = controls_sample\n result[\"d2controls_dt2_sample\"] = d2controls_dt2_sample\n result[\"evolution_time_sample\"] = evolution_time_sample\n result[\"save_type\"] = Integer(samplejl)\n end\n \n # save\n if save\n save_file_path = generate_file_path(\"h5\", EXPERIMENT_NAME, SAVE_PATH)\n println(\"Saving this optimization to $(save_file_path)\")\n h5open(save_file_path, \"cw\") do save_file\n for key in keys(result)\n write(save_file, key, result[key])\n end\n end\n result[\"save_file_path\"] = save_file_path\n end\n\n result = benchmark ? benchmark_result : result\n\n return result\nend\n", "meta": {"hexsha": "3bf284aba971e97e1f32a3d9c9854a8ccbb46762", "size": 10475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spin/spin15.jl", "max_stars_repo_name": "SchusterLab/rbqoc", "max_stars_repo_head_hexsha": "70bac2d8a9cd3c96928fc52821c59534305c20ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-03-30T01:13:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T21:28:40.000Z", "max_issues_repo_path": "src/spin/spin15.jl", "max_issues_repo_name": "SchusterLab/rbqoc", "max_issues_repo_head_hexsha": "70bac2d8a9cd3c96928fc52821c59534305c20ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-09T04:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-09T04:51:57.000Z", "max_forks_repo_path": "src/spin/spin15.jl", "max_forks_repo_name": "SchusterLab/rbqoc", "max_forks_repo_head_hexsha": "70bac2d8a9cd3c96928fc52821c59534305c20ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-30T11:28:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T11:28:38.000Z", "avg_line_length": 35.7508532423, "max_line_length": 92, "alphanum_fraction": 0.6344630072, "num_tokens": 3088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2495693120333862}} {"text": "module OneDTMazeUtils\n\nusing SparseArrays\nusing Distributions\n\nimport ..TMazeCumulantSchedules\nimport ..OneDTmazeConst\nimport ..OneDTMaze\nimport ..Learner\nimport ..check_goal\nimport ..range_check\nimport ..get_action_probs\nimport ..GVFHordes\nimport ..update\nimport ..Curiosity\nimport ..GVFSRHordes\nimport ..SRCreationUtils\nimport ..FeatureCreator\nusing ...StatsBase\n\n\nconst TMCS = TMazeCumulantSchedules\nconst ODTMC = OneDTmazeConst\nconst SRCU = Curiosity.SRCreationUtils\n\n\n#####\n# GVF Parameter Functions\n####\n\nstruct GoalTermination <: GVFHordes.GVFParamFuncs.AbstractDiscount\n γ::Float64\nend\n\nfunction Base.get(gt::GoalTermination; state_tp1, kwargs...)\n any([check_goal(OneDTMaze, i, state_tp1) for i in 1:4]) ? 0.0 : gt.γ\nend\n\nstruct GoalPolicy <: GVFHordes.GVFParamFuncs.AbstractPolicy\n goal::Int\nend\n(π::GoalPolicy)(s) = sample(Weights([get(π, state_t=s, action_t=a) for a ∈ 1:4]))\n\nfunction Base.get(π::GoalPolicy; state_t, action_t, kwargs...)\n cur_x = state_t[1]\n cur_y = state_t[2]\n if π.goal == 1\n if cur_x == 0.5\n if range_check(cur_y, 0.8 - ODTMC.EPSILON, 0.8 + ODTMC.EPSILON)\n ODTMC.LEFT == action_t\n else\n ODTMC.UP == action_t\n end\n elseif cur_x == 1.0\n if range_check(cur_y, 0.8 - ODTMC.EPSILON, 0.8 + ODTMC.EPSILON)\n ODTMC.LEFT == action_t\n elseif cur_y <= 0.8 - ODTMC.EPSILON\n ODTMC.UP == action_t\n elseif cur_y >= 0.8 + ODTMC.EPSILON\n ODTMC.DOWN == action_t\n end\n elseif range_check(cur_x, 0.0 - ODTMC.EPSILON, 0.0 + ODTMC.EPSILON)\n ODTMC.UP == action_t\n else\n ODTMC.LEFT == action_t\n end\n elseif π.goal == 2\n if cur_x == 0.5\n if range_check(cur_y, 0.8 - ODTMC.EPSILON, 0.8 + ODTMC.EPSILON)\n ODTMC.LEFT == action_t\n else\n ODTMC.UP == action_t\n end\n elseif cur_x == 1.0\n if range_check(cur_y, 0.8 - ODTMC.EPSILON, 0.8 + ODTMC.EPSILON)\n ODTMC.LEFT == action_t\n elseif cur_y <= 0.8 - ODTMC.EPSILON\n ODTMC.UP == action_t\n elseif cur_y >= 0.8 + ODTMC.EPSILON\n ODTMC.DOWN == action_t\n end\n elseif range_check(cur_x, 0.0 - ODTMC.EPSILON, 0.0 + ODTMC.EPSILON)\n ODTMC.DOWN == action_t\n else\n ODTMC.LEFT == action_t\n end\n elseif π.goal == 3\n if cur_x == 0.5\n if range_check(cur_y, 0.8 - ODTMC.EPSILON, 0.8 + ODTMC.EPSILON)\n ODTMC.RIGHT == action_t\n else\n ODTMC.UP == action_t\n end\n elseif cur_x == 0.0\n if range_check(cur_y, 0.8 - ODTMC.EPSILON, 0.8 + ODTMC.EPSILON)\n ODTMC.RIGHT == action_t\n elseif cur_y <= 0.8 - ODTMC.EPSILON\n ODTMC.UP == action_t\n elseif cur_y >= 0.8 + ODTMC.EPSILON\n ODTMC.DOWN == action_t\n end\n elseif range_check(cur_x, 1.0 - ODTMC.EPSILON, 1.0 + ODTMC.EPSILON)\n ODTMC.UP == action_t\n else\n ODTMC.RIGHT == action_t\n end\n elseif π.goal == 4\n if cur_x == 0.5\n if range_check(cur_y, 0.8 - ODTMC.EPSILON, 0.8 + ODTMC.EPSILON)\n ODTMC.RIGHT == action_t\n else\n ODTMC.UP == action_t\n end\n elseif cur_x == 0.0\n if range_check(cur_y, 0.8 - ODTMC.EPSILON, 0.8 + ODTMC.EPSILON)\n ODTMC.RIGHT == action_t\n elseif cur_y <= 0.8 - ODTMC.EPSILON\n ODTMC.UP == action_t\n elseif cur_y >= 0.8 + ODTMC.EPSILON\n ODTMC.DOWN == action_t\n end\n elseif range_check(cur_x, 1.0 - ODTMC.EPSILON, 1.0 + ODTMC.EPSILON)\n ODTMC.DOWN == action_t\n else\n ODTMC.RIGHT == action_t\n end\n end\nend\n\n\n####\n# Demon Creation\n####\n\nfunction create_demons(parsed, demon_projected_fc = nothing)\n action_space = 4\n demons = if parsed[\"demon_learner\"] != \"SR\"\n GVFHordes.Horde(\n [GVFHordes.GVF(GVFHordes.GVFParamFuncs.FeatureCumulant(i+2),\n GoalTermination(0.9),\n GoalPolicy(i)) for i in 1:4])\n elseif parsed[\"demon_learner\"] == \"SR\"\n @assert demon_projected_fc != nothing\n pred_horde = GVFHordes.Horde(\n [GVFHordes.GVF(GVFHordes.GVFParamFuncs.FeatureCumulant(i+2),\n GVFHordes.GVFParamFuncs.ConstantDiscount(0.0),\n GoalPolicy(i)) for i in 1:4])\n\n SF_policies = [GoalPolicy(i) for i in 1:4]\n SF_discounts = [GoalTermination(0.9) for i in 1:4]\n num_SFs = length(SF_policies)\n # SF_horde = if parsed[\"demon_reward_feature_type\"] == \"state\"\n # SRCU.create_state_SF_horde(SF_policies, SF_discounts, demon_projected_fc,1:action_space)\n # else\n # SF_horde = SRCU.create_SF_horde(SF_policies, SF_discounts, demon_projected_fc,1:action_space)\n SF_horde = SRCU.create_SF_horde(SF_policies, SF_discounts, demon_projected_fc,1:action_space)\n\n # end\n GVFSRHordes.SRHorde(pred_horde, SF_horde, num_SFs, demon_projected_fc)\n else\n throw(ArgumentError(\"Cannot create demons\"))\n end\n return demons\nend\n\nfunction make_behaviour_gvf(learner, γ, state_constructor, expl_strat) #discount, state_constructor_func, learner, exploration_strategy)\n function b_π(state_constructor, learner, exploration_strategy; kwargs...)\n s = state_constructor(kwargs[:state_t])\n preds = learner(s)\n return exploration_strategy(preds)[kwargs[:action_t]]\n end\n GVF_policy = GVFHordes.GVFParamFuncs.FunctionalPolicy((;kwargs...) -> b_π(state_constructor, learner, expl_strat; kwargs...))\n BehaviourGVF = GVFHordes.GVF(GVFHordes.GVFParamFuncs.RewardCumulant(),\n GoalTermination(γ),\n GVF_policy)\nend\n\n\n# ####\nstruct IdealStateActionDemonFeatures <: FeatureCreator\n num_actions::Int\nend\nfunction project_features(fc::IdealStateActionDemonFeatures, s_t, a_t, s_tp1)\n # new_state = sparsevec(convert(Array{Int,1}, [check_goal(OneDTMaze, i, s_tp1) for i in 1:4]))\n goal_ind = findfirst([check_goal(OneDTMaze, i, s_tp1) for i in 1:4])\n reward_feature = zeros(Int(fc.num_actions*4))\n if !(goal_ind isa Nothing)\n reward_feature[Int((goal_ind-1)*fc.num_actions + a_t)] = 1\n end\n return sparsevec(reward_feature)\nend\n(FP::IdealStateActionDemonFeatures)(s_t,a_t,s_tp1) = project_features(FP, s_t,a_t,s_tp1)\n\nBase.size(FP::IdealStateActionDemonFeatures) = 16\n####\n# Ideal Feature Creator\n####\nstruct IdealDemonFeatures <: FeatureCreator\nend\n\nfunction project_features(fc::IdealDemonFeatures, state,action,state_tp1)\n new_state = sparsevec(convert(Array{Int,1}, [check_goal(OneDTMaze, i, state_tp1) for i in 1:4]))\n return new_state\nend\n\n(FP::IdealDemonFeatures)(state, action, next_state) = project_features(FP, state, action, next_state)\nBase.size(FP::IdealDemonFeatures) = 4\n\nstruct MarthaIdealDemonFeatures <: FeatureCreator\n num_actions::Int\nend\n\nfunction project_features(fc::MarthaIdealDemonFeatures, state)\n new_state = sparsevec(convert(Array{Int,1}, [check_goal(OneDTMaze, i, state, ODTMC.ACTION_STEP + ODTMC.EPSILON + 0.00001) for i in 1:4]))\n # alt_state = sparsevec(convert(Array{Int,1}, [check_goal(OneDTMaze, i, state_tp1) for i in 1:4]))\n return new_state\nend\n\n(FP::MarthaIdealDemonFeatures)(state) = project_features(FP, state)\nBase.size(FP::MarthaIdealDemonFeatures) = 4\n\n####\n# GPI Feature Creation\n####\nstruct TMazeEncoding <: FeatureCreator\n num_segments::Int\n num_partitions::Int\n num_actions::Int\n function TMazeEncoding()\n new(7,3,4)\n end\nend\nBase.size(FP::TMazeEncoding) = FP.num_segments * FP.num_partitions * FP.num_actions\nfunction project_features(fc::FeatureCreator, obs, a_t, obs_tp1)\n segment = Inf\n partition = Inf\n x,y = obs\n\n #Segment 1: Top Right\n if (x == 0.0 && y >= 0.8)\n segment_length = (1.0 + ODTMC.ACTION_STEP) - (0.8)\n segment = 1\n partition = (y - 0.8) / segment_length\n #Segment 2: Bottom Right\n elseif (x == 0.0 && y < 0.8)\n segment_length = (0.8) - (0.6 - ODTMC.ACTION_STEP)\n segment = 2\n partition = (y - 0.8) / segment_length\n #Segment 3: Middle Left Branch\n elseif (y == 0.8 && range_check(x,0.0,0.5))\n segment_length = (0.5 - 0.0)\n segment = 3\n partition = (x) / segment_length\n # Segment 4: Middle Right Branch\n elseif (y == 0.8 && range_check(x,0.5,1.0))\n segment_length = (1.0-0.5)\n segment = 4\n partition = (x - 0.5)/segment_length\n #Segment 5: Bottom Branch\n elseif (x == 0.5)\n segment_length = (0.8 - 0.0)\n segment = 5\n partition = (y - 0.0)/segment_length\n # #Segment 6: Top Left Branch\n elseif (x == 1.0 && y >= 0.8)\n segment_length = (1.0 + ODTMC.ACTION_STEP) - (0.8)\n segment = 6\n partition = (y - 0.8) / segment_length\n #Segment 7: Bottom Left Branch\n elseif (x == 1.0 && y < 0.8)\n segment_length = (0.8) - (0.6 - ODTMC.ACTION_STEP)\n segment = 7\n partition = (y - 0.8) / segment_length\n else\n @warn \"Not A Valid State (x,y)\"\n end\n\n state_action = zeros(fc.num_segments * fc.num_partitions * fc.num_actions)\n # Need maximum since if agent is right on boundary, ceil (0.0) is 0.\n partition_offset = maximum([Int(ceil(partition * fc.num_partitions)),1])\n if partition_offset == 0\n @show x,y,segment\n end\n state_ind = (segment-1)*fc.num_partitions + partition_offset\n state_action_ind = state_ind * fc.num_actions + a_t\n\n state_action[state_action_ind] = 1\n return sparsevec(state_action)\nend\n(FP::TMazeEncoding)(state, action, state_tp1) = project_features(FP, state, action, state_tp1)\n\n\n####\n# Behaviour policies\n####\n\nBase.@kwdef struct RoundRobinPolicy <: Learner\n update = Nothing\nend\n\nCuriosity.update!(learner::RoundRobinPolicy, args...) = nothing\n\nBase.get(π::RoundRobinPolicy; state_t, action_t, kwargs...) =\n get_action_probs(π, state_t, nothing)[action_t]\n\n\n\nfunction Curiosity.get_action_probs(π::RoundRobinPolicy, features, state)\n cur_x = state[1]\n cur_y = state[2]\n ret = zeros(4)\n\n if cur_x == 0.5\n if range_check(cur_y, 0.8 - ODTMC.EPSILON, 0.8 + ODTMC.EPSILON) # Middle Junction\n ret[ODTMC.LEFT] = 0.5\n ret[ODTMC.RIGHT] = 0.5\n else # Middle Hallway\n ret[ODTMC.UP] = 1.0\n end\n elseif cur_y == 0.8 && range_check(cur_x, 0.0 - ODTMC.EPSILON, 0.0 + ODTMC.EPSILON) # Left Junction\n ret[ODTMC.UP] = 0.5\n ret[ODTMC.DOWN] = 0.5\n elseif cur_y == 0.8 && range_check(cur_x, 1.0 - ODTMC.EPSILON, 1.0 + ODTMC.EPSILON)\n ret[ODTMC.UP] = 0.5\n ret[ODTMC.DOWN] = 0.5\n elseif cur_x == 0.0\n if cur_y > 0.8\n ret[ODTMC.UP] = 1.0\n else\n ret[ODTMC.DOWN] = 1.0\n end\n elseif cur_x == 1.0\n if cur_y > 0.8\n ret[ODTMC.UP] = 1.0\n else\n ret[ODTMC.DOWN] = 1.0\n end\n elseif cur_x < 0.5\n ret[ODTMC.LEFT] = 1.0\n else\n ret[ODTMC.RIGHT] = 1.0\n end\n ret\nend\n\n\n\n####\n# Cumulant Schedules\n####\nDrifterDistractor(parsed) = begin\n c_dist = Uniform(parsed[\"constant_target\"][1],parsed[\"constant_target\"][2])\n c1,c2 = rand(c_dist,2)\n if \"drifter\" ∈ keys(parsed)\n TMCS.DrifterDistractor(\n c1,\n c2,\n parsed[\"drifter\"][1],\n parsed[\"drifter\"][2],\n parsed[\"distractor\"][1],\n parsed[\"distractor\"][2])\n else\n TMCS.DrifterDistractor(\n c1,\n c2,\n parsed[\"drifter_init\"],\n parsed[\"drifter_std\"],\n parsed[\"distractor_mean\"],\n parsed[\"distractor_std\"])\n end\nend\n\nfunction get_cumulant_schedule(parsed)\n sched = parsed[\"cumulant_schedule\"]\n if parsed[\"cumulant_schedule\"] == \"DrifterDistractor\"\n DrifterDistractor(parsed)\n elseif parsed[\"cumulant_schedule\"] == \"Constant\"\n if parsed[\"cumulant\"] isa Number\n TMCS.Constant(parsed[\"cumulant\"])\n else\n TMCS.Constant(parsed[\"cumulant\"]...)\n end\n\n else\n throw(\"$(sched) Not Implemented\")\n end\nend\n\nfunction get_true_values(env::Curiosity.OneDTMaze, eval_set)\n copy_eval_est = deepcopy(eval_set)\n num_gvfs = 4\n goal_cumulants = TMCS.get_cumulant_eval_values(env.cumulant_schedule)\n for i in 1:num_gvfs\n copy_eval_est[i, :] .*= goal_cumulants[i]\n end\n return copy_eval_est\nend\nfunction get_true_values(env::Curiosity.OneDTMaze, eval_set, gvf_idx)\n copy_eval_est = deepcopy(eval_set)\n goal_cumulants = TMCS.get_cumulant_eval_values(env.cumulant_schedule)\n copy_eval_est .*= goal_cumulants[gvf_idx]\n return copy_eval_est\nend\n\nend\n", "meta": {"hexsha": "dd6262e13d119f50a5688df2c18cff1a46f76150", "size": 13008, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/1d-tmaze.jl", "max_stars_repo_name": "MatthewMcLeod/curiosity", "max_stars_repo_head_hexsha": "7b452cb296c36a2e7b2f01763177c097bae8011c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-06T22:40:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T22:40:25.000Z", "max_issues_repo_path": "src/utils/1d-tmaze.jl", "max_issues_repo_name": "MatthewMcLeod/curiosity", "max_issues_repo_head_hexsha": "7b452cb296c36a2e7b2f01763177c097bae8011c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/1d-tmaze.jl", "max_forks_repo_name": "MatthewMcLeod/curiosity", "max_forks_repo_head_hexsha": "7b452cb296c36a2e7b2f01763177c097bae8011c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.039408867, "max_line_length": 141, "alphanum_fraction": 0.6143142681, "num_tokens": 3954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.24945148725570085}} {"text": "\"\"\"\n```\nstruct VarName{sym}\n indexing :: String\nend\n```\n\nA variable identifier. Every variable has a symbol `sym` and `indices `indexing`. \nThe Julia variable in the model corresponding to `sym` can refer to a single value or \nto a hierarchical array structure of univariate, multivariate or matrix variables. `indexing` stores the indices that can access the random variable from the Julia \nvariable.\n\nExamples:\n\n- `x[1] ~ Normal()` will generate a `VarName` with `sym == :x` and `indexing == \"[1]\"`.\n- `x[:,1] ~ MvNormal(zeros(2))` will generate a `VarName` with `sym == :x` and\n `indexing == \"[Colon(),1]\"`.\n- `x[:,1][2] ~ Normal()` will generate a `VarName` with `sym == :x` and\n `indexing == \"[Colon(),1][2]\"`.\n\"\"\"\nstruct VarName{sym}\n indexing::String\nend\n\n\n\n\"\"\"\n @varname(var)\n\nA macro that returns an instance of `VarName` given the symbol or expression of a Julia variable, e.g. `@varname x[1,2][1+5][45][3]` returns `VarName{:x}(\"[1,2][6][45][3]\")`.\n\"\"\"\nmacro varname(expr::Union{Expr, Symbol})\n expr |> varname |> esc\nend\nfunction varname(expr)\n ex = deepcopy(expr)\n (ex isa Symbol) && return quote\n DynamicPPL.VarName{$(QuoteNode(ex))}(\"\")\n end\n (ex.head == :ref) || throw(\"VarName: Mis-formed variable name $(expr)!\")\n inds = :(())\n while ex.head == :ref\n if length(ex.args) >= 2\n strs = map(x -> :($x === (:) ? \"Colon()\" : string($x)), ex.args[2:end])\n pushfirst!(inds.args, :(\"[\" * join($(Expr(:vect, strs...)), \",\") * \"]\"))\n end\n ex = ex.args[1]\n isa(ex, Symbol) && return quote\n DynamicPPL.VarName{$(QuoteNode(ex))}(foldl(*, $inds, init = \"\"))\n end\n end\n throw(\"VarName: Mis-formed variable name $(expr)!\")\nend\n\nmacro vsym(expr::Union{Expr, Symbol})\n expr |> vsym\nend\n\n\"\"\"\n vsym(expr::Union{Expr, Symbol})\n\nReturns the variable symbol given the input variable expression `expr`. For example, if the input `expr = :(x[1])`, the output is `:x`.\n\"\"\"\nfunction vsym(expr::Union{Expr, Symbol})\n ex = deepcopy(expr)\n (ex isa Symbol) && return QuoteNode(ex)\n (ex.head == :ref) || throw(\"VarName: Mis-formed variable name $(expr)!\")\n while ex.head == :ref\n ex = ex.args[1]\n isa(ex, Symbol) && return QuoteNode(ex)\n end\n throw(\"VarName: Mis-formed variable name $(expr)!\")\nend\n\n\"\"\"\n @vinds(expr)\n\nReturns a tuple of tuples of the indices in `expr`. For example, `@vinds x[1,:][2]` returns \n`((1, Colon()), (2,))`.\n\"\"\"\nmacro vinds(expr::Union{Expr, Symbol})\n expr |> vinds |> esc\nend\nfunction vinds(expr::Union{Expr, Symbol})\n ex = deepcopy(expr)\n inds = Expr(:tuple)\n (ex isa Symbol) && return inds\n (ex.head == :ref) || throw(\"VarName: Mis-formed variable name $(expr)!\")\n while ex.head == :ref\n pushfirst!(inds.args, Expr(:tuple, ex.args[2:end]...))\n ex = ex.args[1]\n isa(ex, Symbol) && return inds\n end\n throw(\"VarName: Mis-formed variable name $(expr)!\")\nend\n\n\"\"\"\n split_var_str(var_str, inds_as = Vector)\n\nThis function splits a variable string, e.g. `\"x[1:3,1:2][3,2]\"` to the variable's symbol `\"x\"` and the indexing `\"[1:3,1:2][3,2]\"`. If `inds_as = String`, the indices are returned as a string, e.g. `\"[1:3,1:2][3,2]\"`. If `inds_as = Vector`, the indices are returned as a vector of vectors of strings, e.g. `[[\"1:3\", \"1:2\"], [\"3\", \"2\"]]`.\n\"\"\"\nfunction split_var_str(var_str, inds_as = Vector)\n ind = findfirst(c -> c == '[', var_str)\n if inds_as === String\n if ind === nothing\n return var_str, \"\"\n else\n return var_str[1:ind-1], var_str[ind:end]\n end\n end\n @assert inds_as === Vector\n inds = Vector{String}[]\n if ind === nothing\n return var_str, inds\n end\n sym = var_str[1:ind-1]\n ind = length(sym)\n while ind < length(var_str)\n ind += 1\n @assert var_str[ind] == '['\n push!(inds, String[])\n while var_str[ind] != ']'\n ind += 1\n if var_str[ind] == '['\n ind2 = findnext(c -> c == ']', var_str, ind)\n push!(inds[end], strip(var_str[ind:ind2]))\n ind = ind2+1\n else\n ind2 = findnext(c -> c == ',' || c == ']', var_str, ind)\n push!(inds[end], strip(var_str[ind:ind2-1]))\n ind = ind2\n end\n end\n end\n return sym, inds\nend\n\n\n@generated function inargnames(::VarName{s}, ::Model{_F, argnames}) where {s, argnames, _F}\n return s in argnames\nend\n\n@generated function inmissings(::VarName{s}, ::Model{_F, _a, _T, missings}) where {s, missings, _F, _a, _T}\n return s in missings\nend\n", "meta": {"hexsha": "85db0b7c4bedb00501d46e05f2378786556b8f1e", "size": 4652, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/varname.jl", "max_stars_repo_name": "torfjelde/DynamicPPL.jl", "max_stars_repo_head_hexsha": "61e8adc5458c31f69dbd9903f91bc334c40b927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/varname.jl", "max_issues_repo_name": "torfjelde/DynamicPPL.jl", "max_issues_repo_head_hexsha": "61e8adc5458c31f69dbd9903f91bc334c40b927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/varname.jl", "max_forks_repo_name": "torfjelde/DynamicPPL.jl", "max_forks_repo_head_hexsha": "61e8adc5458c31f69dbd9903f91bc334c40b927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8630136986, "max_line_length": 338, "alphanum_fraction": 0.5758813414, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.24945148725570085}} {"text": "\"\"\"\n SMCModel(M!::F1, lG::F2, maxn::Int64, particle::Type, pScratch::Type) where\n {F1<:Function,F2<:Function}\n- ```M!``` Mutation function\n- ```lG``` Log potential function\n- ```maxn``` Maximum n for which the model is well-defined\n- ```particle``` Type of a particle\n- ```pScratch``` Type of particle scratch space\n\"\"\"\nstruct SMCModel{F1<:Function,F2<:Function}\n M!::F1\n lG::F2\n maxn::Int64\n particle::Type\n pScratch::Type\nend\n\nconst SubVectorF64 = SubArray{Float64, 1, Array{Float64, 1},\n Tuple{UnitRange{Int64}}, true}\nconst SubVectorI64 = SubArray{Int64, 1, Array{Int64, 1},\n Tuple{UnitRange{Int64}}, true}\nconst SubVector{Particle} = SubArray{Particle,1,Array{Particle,1},Tuple{UnitRange{Int64}},true}\n\n# the fields of this struct are used by the parallel SMC algorithm\n# they are not intended for use by users of the package\nmutable struct _SMCInternalParallel{Particle, ParticleScratch}\n Nperthread::Int64\n maxlws::Vector{Float64}\n partialSums::Vector{Float64}\n partialSumSqs::Vector{Float64}\n Ns::Vector{Int64}\n NsPartial::Vector{Int64}\n particleScratches::Vector{ParticleScratch}\n\n localAs::Vector{SubVectorI64}\n localEves::Vector{SubVectorI64}\n localOldEves::Vector{SubVectorI64}\n localZetas::Vector{SubVector{Particle}}\n localZetaAncs::Vector{SubVector{Particle}}\n localWs::Vector{SubVectorF64}\n localLogWs::Vector{SubVectorF64}\n localScratch1s::Vector{SubVectorF64}\n\n ## below are only populated if fullOutput = true\n localAllAs::Vector{Vector{SubVectorI64}}\n localAllZetas::Vector{Vector{SubVector{Particle}}}\n localAllEves::Vector{Vector{SubVectorI64}}\n localAllWs::Vector{Vector{SubVectorF64}}\nend\n\nfunction _SMCInternalParallel{Particle, ParticleScratch}(N::Int64, n::Int64,\n nthreads::Int64, fullOutput::Bool) where {Particle, ParticleScratch}\n @assert mod(N, nthreads) == 0 \"N must be a multiple of nthreads\"\n Nperthread = div(N, nthreads)\n\n if nthreads > 1\n maxlws::Vector{Float64} = Vector{Float64}(undef, nthreads)\n partialSums::Vector{Float64} = Vector{Float64}(undef, nthreads)\n partialSumSqs::Vector{Float64} = Vector{Float64}(undef, nthreads)\n Ns::Vector{Int64} = Vector{Int64}(undef, nthreads)\n NsPartial::Vector{Int64} = Vector{Int64}(undef, nthreads)\n\n particleScratches::Vector{ParticleScratch} =\n Vector{ParticleScratch}(undef, nthreads)\n # avoid false sharing\n Threads.@threads for i = 1:nthreads\n @inbounds particleScratches[i] = ParticleScratch()\n end\n\n localAs::Vector{SubVectorI64} =\n Vector{SubVectorI64}(undef, nthreads)\n localEves::Vector{SubVectorI64} =\n Vector{SubVectorI64}(undef, nthreads)\n localOldEves::Vector{SubVectorI64} =\n Vector{SubVectorI64}(undef, nthreads)\n localZetas::Vector{SubVector{Particle}} =\n Vector{SubVector{Particle}}(undef, nthreads)\n localZetaAncs::Vector{SubVector{Particle}} =\n Vector{SubVector{Particle}}(undef, nthreads)\n localWs::Vector{SubVectorF64} =\n Vector{SubVectorF64}(undef, nthreads)\n localLogWs::Vector{SubVectorF64} =\n Vector{SubVectorF64}(undef, nthreads)\n localScratch1s::Vector{SubVectorF64} =\n Vector{SubVectorF64}(undef, nthreads)\n else\n maxlws = Vector{Float64}(undef, 0)\n partialSums = Vector{Float64}(undef, 0)\n partialSumSqs = Vector{Float64}(undef, 0)\n Ns = Vector{Int64}(undef, 0)\n NsPartial = Vector{Int64}(undef, 0)\n particleScratches = Vector{ParticleScratch}(undef, 0)\n\n localAs = Vector{SubVectorI64}(undef, 0)\n localEves = Vector{SubVectorI64}(undef, 0)\n localOldEves = Vector{SubVectorI64}(undef, 0)\n localZetas = Vector{SubVector{Particle}}(undef, 0)\n localZetaAncs = Vector{SubVector{Particle}}(undef, 0)\n localWs = Vector{SubVectorF64}(undef, 0)\n localLogWs = Vector{SubVectorF64}(undef, 0)\n localScratch1s = Vector{SubVectorF64}(undef, 0)\n end\n\n if fullOutput && nthreads > 1\n localAllZetas::Vector{Vector{SubVector{Particle}}} =\n Vector{Vector{SubVector{Particle}}}(undef, n)\n localAllAs::Vector{Vector{SubVectorI64}} =\n Vector{Vector{SubVectorI64}}(undef, n-1)\n localAllEves::Vector{Vector{SubVectorI64}} =\n Vector{Vector{SubVectorI64}}(undef, n)\n localAllWs::Vector{Vector{SubVectorF64}} =\n Vector{Vector{SubVectorF64}}(undef, n)\n for p = 1:n\n localAllZetas[p] = Vector{SubVector{Particle}}(undef, nthreads)\n localAllEves[p] = Vector{SubVectorI64}(undef, nthreads)\n localAllWs[p] = Vector{SubVectorF64}(undef, nthreads)\n p < n && (localAllAs[p] = Vector{SubVectorI64}(undef, nthreads))\n end\n else\n localAllAs = Vector{Vector{SubVectorI64}}(undef, 0)\n localAllZetas = Vector{Vector{SubVector{Particle}}}(undef, 0)\n localAllEves = Vector{Vector{SubVectorI64}}(undef, 0)\n localAllWs = Vector{Vector{SubVectorF64}}(undef, 0)\n end\n\n return _SMCInternalParallel(Nperthread, maxlws, partialSums, partialSumSqs,\n Ns, NsPartial, particleScratches, localAs, localEves, localOldEves,\n localZetas, localZetaAncs, localWs, localLogWs, localScratch1s, localAllAs,\n localAllZetas, localAllEves, localAllWs)\nend\n\n# the fields of this struct are used by the SMC algorithm\n# they are not intended for use by users of the package\nmutable struct _SMCInternal{Particle, ParticleScratch}\n zetaAncs::Vector{Particle}\n oldEves::Vector{Int64}\n as::Vector{Int64}\n lws::Vector{Float64}\n scratch1::Vector{Float64}\n scratch2::Vector{Float64}\n vecOnes::Vector{Float64}\n nresamples::Int64\n\n sws::Float64\n mws::Float64\n maxlw::Float64\n particleScratch::ParticleScratch\n\n parallel::_SMCInternalParallel{Particle, ParticleScratch}\nend\n\n## constructor for _SMCInternal\nfunction _SMCInternal{Particle, ParticleScratch}(N::Int64, n::Int64,\n nthreads::Int64, fullOutput::Bool) where {Particle, ParticleScratch}\n\n lws = Vector{Float64}(undef, N)\n as = Vector{Int64}(undef, N)\n fill!(as, 1)\n scratch1 = Vector{Float64}(undef, N)\n scratch2 = Vector{Float64}(undef, N)\n vecOnes = ones(N)\n nresamples::Int64 = 0\n zetaAncs = Vector{Particle}(undef, N)\n for i in 1:N\n zetaAncs[i] = Particle()\n end\n oldEves = Vector{Int64}(undef, N)\n\n ## assign user-defined particle scratch space\n @assert ParticleScratch == Nothing || !isbitstype(ParticleScratch)\n particleScratch = ParticleScratch()\n\n parallel::_SMCInternalParallel{Particle, ParticleScratch} =\n _SMCInternalParallel{Particle, ParticleScratch}(N, n, nthreads, fullOutput)\n\n return _SMCInternal(zetaAncs, oldEves, as, lws, scratch1, scratch2, vecOnes,\n nresamples, 0.0, 0.0, 0.0, particleScratch, parallel)\nend\n\nfunction _assignThreadViews(internal::_SMCInternal{Particle},\n zetas::Vector{Particle}, eves::Vector{Int64}, ws::Vector{Float64},\n allZetas::Vector{Vector{Particle}}, allWs::Vector{Vector{Float64}},\n allAs::Vector{Vector{Int64}}, allEves::Vector{Vector{Int64}}) where Particle\n\n zetaAncs::Vector{Particle} = internal.zetaAncs\n as::Vector{Int64} = internal.as\n oldEves::Vector{Int64} = internal.oldEves\n lws::Vector{Float64} = internal.lws\n scratch1::Vector{Float64} = internal.scratch1\n\n ip::_SMCInternalParallel = internal.parallel\n nthreads::Int64 = length(ip.localWs)\n Nperthread::Int64 = ip.Nperthread\n for i = 1:nthreads\n start = Nperthread * (i - 1) + 1\n finish = start + Nperthread - 1\n ip.localAs[i] = view(as, start:finish)\n ip.localEves[i] = view(eves, start:finish)\n ip.localOldEves[i] = view(oldEves, start:finish)\n ip.localZetas[i] = view(zetas, start:finish)\n ip.localZetaAncs[i] = view(zetaAncs, start:finish)\n ip.localWs[i] = view(ws, start:finish)\n ip.localLogWs[i] = view(lws, start:finish)\n ip.localScratch1s[i] = view(scratch1, start:finish)\n end\n\n fullOutput::Bool = length(ip.localAllWs) > 0\n if fullOutput && nthreads > 1\n n::Int64 = length(allWs)\n for p = 1:n\n for i = 1:nthreads\n start = Nperthread * (i - 1) + 1\n finish = start + Nperthread - 1\n ip.localAllZetas[p][i] = view(allZetas[p], start:finish)\n ip.localAllEves[p][i] = view(allEves[p], start:finish)\n ip.localAllWs[p][i] = view(allWs[p], start:finish)\n p < n && (ip.localAllAs[p][i] = view(allAs[p], start:finish))\n end\n end\n end\nend\n\n## SMC input / output struct. Also contains internal state for the SMC\n## implementation\n\"\"\"\n SMCIO{Particle, ParticleScratch}\nStructs of this type should be constructed using the provided constructor.\nImportant fields:\n- ```N::Int64``` Number of particles ``N``\n- ```n::Int64``` Number of steps ``n``\n- ```nthreads::Int64``` Number of threads\n- ```fullOutput::Bool``` Whether particle system history should be recorded\n- ```essThreshold::Float64``` Relative ESS Threshold ``\\\\tau``\n- ```zetas::Vector{Particle}``` Time n particles ``\\\\zeta_n^1, \\\\ldots, \\\\zeta_n^N``\n- ```eves::Vector{Int64}``` Time n Eve indices ``E_n^1, \\\\ldots, E_n^N``\n- ```ws::Vector{Float64}``` Time n weights ``W_n^1, \\\\ldots, W_n^N``\n- ```logZhats::Vector{Float64}``` ``\\\\log(\\\\hat{Z}^N_1), \\\\ldots, \\\\log(\\\\hat{Z}^N_n)``\n- ```Vhat1s::Vector{Float64}``` ``\\\\hat{V}_1^N(1), \\\\ldots, \\\\hat{V}_n^N(1)``\n- ```esses::Vector{Float64}``` Relative ESS values ``\\\\mathcal{E}_1^N, \\\\ldots, \\\\mathcal{E}_n^N``\n- ```resample::Vector{Bool}``` Resampling indicators ``R_1, \\\\ldots, R_{n-1}``\nPopulated only if ```fullOutput == true```\n- ```allZetas::Vector{Vector{Particle}}``` All the particles\n- ```allWs::Vector{Vector{Float64}}``` All the weights\n- ```allAs::Vector{Vector{Int64}}``` All the ancestor indices\n- ```allEves::Vector{Vector{Int64}}``` All the Eve indices\n\"\"\"\nstruct SMCIO{Particle, ParticleScratch}\n N::Int64\n n::Int64\n nthreads::Int64\n zetas::Vector{Particle}\n eves::Vector{Int64}\n ws::Vector{Float64}\n logZhats::Vector{Float64}\n Vhat1s::Vector{Float64}\n esses::Vector{Float64}\n resample::Vector{Bool}\n fullOutput::Bool\n essThreshold::Float64\n\n internal::_SMCInternal{Particle, ParticleScratch} # for internal use only\n\n # these are only populated if fullOutput = true\n allZetas::Vector{Vector{Particle}}\n allWs::Vector{Vector{Float64}}\n allAs::Vector{Vector{Int64}}\n allEves::Vector{Vector{Int64}}\nend\n\n\"\"\"\n SMCIO{Particle, ParticleScratch}(N::Int64, n::Int64, nthreads::Int64,\n fullOutput::Bool, essThreshold::Float64 = 2.0) where\n {Particle, ParticleScratch}\nConstructor for ```SMCIO``` structs.\n\"\"\"\nfunction SMCIO{Particle, ParticleScratch}(N::Int64, n::Int64, nthreads::Int64,\n fullOutput::Bool, essThreshold::Float64 = 2.0) where {Particle,\n ParticleScratch}\n @assert hasmethod(Particle, ()) \"Particle() must exist\"\n @assert hasmethod(ParticleScratch, ()) \"ParticleScratch() must exist\"\n\n zetas = Vector{Particle}(undef, N)\n for i=1:N\n zetas[i] = Particle()\n end\n\n eves = Vector{Int64}(undef, N)\n ws = Vector{Float64}(undef, N)\n logZhats = Vector{Float64}(undef, n)\n Vhat1s = Vector{Float64}(undef, n)\n esses = Vector{Float64}(undef, n)\n resample = Vector{Bool}(undef, n-1)\n\n if fullOutput\n allZetas = Vector{Vector{Particle}}(undef, n)\n for i=1:n\n allZetas[i] = Vector{Particle}(undef, N)\n for j=1:N\n allZetas[i][j] = Particle()\n end\n end\n allWs = Vector{Vector{Float64}}(undef, n)\n for i=1:n\n allWs[i] = Vector{Float64}(undef, N)\n end\n allAs = Vector{Vector{Int64}}(undef, n-1)\n for i=1:n-1\n allAs[i] = Vector{Int64}(undef, N)\n end\n allEves = Vector{Vector{Int64}}(undef, n)\n for i=1:n\n allEves[i] = Vector{Int64}(undef, N)\n end\n else\n allZetas = Vector{Vector{Particle}}(undef, 0)\n allWs = Vector{Vector{Float64}}(undef, 0)\n allAs = Vector{Vector{Int64}}(undef, 0)\n allEves = Vector{Vector{Int64}}(undef, 0)\n end\n\n internal::_SMCInternal = _SMCInternal{Particle, ParticleScratch}(N, n,\n nthreads, fullOutput)\n\n _assignThreadViews(internal, zetas, eves, ws, allZetas, allWs, allAs, allEves)\n\n return SMCIO(N, n, nthreads, zetas, eves, ws, logZhats, Vhat1s, esses,\n resample, fullOutput, essThreshold, internal, allZetas, allWs, allAs,\n allEves)\nend\n", "meta": {"hexsha": "43dd6c9d96529bdf4ebb03b1439556d548f3c59f", "size": 11944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/structures.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SequentialMonteCarlo.jl-8c675823-c5d5-50f8-acb2-29aff48dfc1d", "max_stars_repo_head_hexsha": "d64cc56102e7c3b8a13a8eb4ff9b2dba3d6988e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:56:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T10:23:05.000Z", "max_issues_repo_path": "src/structures.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SequentialMonteCarlo.jl-8c675823-c5d5-50f8-acb2-29aff48dfc1d", "max_issues_repo_head_hexsha": "d64cc56102e7c3b8a13a8eb4ff9b2dba3d6988e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-10-17T07:19:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T23:56:37.000Z", "max_forks_repo_path": "src/structures.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SequentialMonteCarlo.jl-8c675823-c5d5-50f8-acb2-29aff48dfc1d", "max_forks_repo_head_hexsha": "d64cc56102e7c3b8a13a8eb4ff9b2dba3d6988e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:26:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-12T17:11:58.000Z", "avg_line_length": 36.1939393939, "max_line_length": 98, "alphanum_fraction": 0.6980073677, "num_tokens": 3937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24945148725570082}} {"text": "function Base.get{S<:VehicleState,D,I,R}(::Feature_PosFt, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0)\n FeatureValue(rec[pastframe][vehicle_index].state.posF.t)\nend\nfunction Base.get{S<:VehicleState,D,I,R}(::Feature_PosFyaw, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0)\n FeatureValue(rec[pastframe][vehicle_index].state.posF.ϕ)\nend\nfunction Base.get{S<:VehicleState,D,I,R}(::Feature_Speed, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0)\n FeatureValue(rec[pastframe][vehicle_index].state.v)\nend\nfunction Base.get{S<:VehicleState,D,I,R}(::Feature_VelFs, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0)\n veh = rec[pastframe][vehicle_index]\n FeatureValue(veh.state.v*cos(veh.state.posF.ϕ))\nend\nfunction Base.get{S<:VehicleState,D,I,R}(::Feature_VelFt, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0)\n veh = rec[pastframe][vehicle_index]\n FeatureValue(veh.state.v*sin(veh.state.posF.ϕ))\nend\n\ngenerate_feature_functions(\"TurnRateG\", :turnrateG, Float64, \"rad/s\")\nfunction Base.get{S<:VehicleState,D,I,R}(::Feature_TurnRateG, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0; frames_back::Int=1)\n\n id = rec[pastframe][vehicle_index].id\n\n retval = FeatureValue(0.0, FeatureState.INSUF_HIST)\n pastframe2 = pastframe - frames_back\n if pastframe_inbounds(rec, pastframe2)\n\n veh_index_curr = vehicle_index\n veh_index_prev = findfirst(rec[pastframe2], id)\n\n if veh_index_prev != 0\n curr = rec[pastframe][veh_index_curr].state.posG.θ\n past = rec[pastframe2][veh_index_prev].state.posG.θ\n Δt = get_elapsed_time(rec, pastframe2, pastframe)\n retval = FeatureValue(deltaangle(past, curr) / Δt)\n end\n end\n\n retval\nend\ngenerate_feature_functions(\"TurnRateF\", :turnrateF, Float64, \"rad/s\")\nfunction Base.get{S<:VehicleState,D,I,R}(::Feature_TurnRateF, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0)\n _get_feature_derivative_backwards(POSFYAW, rec, roadway, vehicle_index, pastframe)\nend\ngenerate_feature_functions(\"AngularRateG\", :angrateG, Float64, \"rad/s²\")\nfunction Base.get{S<:VehicleState,D,I,R}(::Feature_AngularRateG, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0)\n _get_feature_derivative_backwards(TURNRATEG, rec, roadway, vehicle_index, pastframe)\nend\ngenerate_feature_functions(\"AngularRateF\", :angrateF, Float64, \"rad/s²\")\nfunction Base.get{S<:VehicleState,D,I,R}(::Feature_AngularRateF, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0)\n _get_feature_derivative_backwards(TURNRATEF, rec, roadway, vehicle_index, pastframe)\nend\ngenerate_feature_functions(\"DesiredAngle\", :desang, Float64, \"rad\")\nfunction Base.get{S<:VehicleState,D,I,R}(::Feature_DesiredAngle, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0;\n kp_desired_angle::Float64 = 1.0,\n )\n\n retval = FeatureValue(0.0, FeatureState.INSUF_HIST)\n if pastframe_inbounds(rec, pastframe) && pastframe_inbounds(rec, pastframe-1)\n\n id = rec[pastframe][vehicle_index].id\n\n pastϕ = get_state(rec, id, pastframe-1).posF.ϕ\n currϕ = get_state(rec, id, pastframe).posF.ϕ\n\n Δt = rec.timestep\n expconst = exp(-kp_desired_angle*Δt)\n retval = FeatureValue((currϕ - pastϕ*expconst) / (1.0 - expconst))\n end\n retval\nend\n\ngenerate_feature_functions(\"MarkerDist_Left\", :d_ml, Float64, \"m\")\nBase.get(::Feature_MarkerDist_Left, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0) =\n FeatureValue(get_markerdist_left(rec[pastframe][vehicle_index], roadway))\n\ngenerate_feature_functions(\"MarkerDist_Right\", :d_mr, Float64, \"m\")\nBase.get(::Feature_MarkerDist_Right, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0) =\n FeatureValue(get_markerdist_right(rec[pastframe][vehicle_index], roadway))\n\ngenerate_feature_functions(\"MarkerDist_Left_Left\", :d_mll, Float64, \"m\", can_be_missing=true)\nfunction Base.get(::Feature_MarkerDist_Left_Left, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n #=\n Distance to the left lane marker one lane to the left\n =#\n\n veh = rec[pastframe][vehicle_index]\n lane = roadway[veh.state.posF.roadind.tag]\n if n_lanes_left(lane, roadway) > 0\n offset = veh.state.posF.t\n lane_left = roadway[LaneTag(lane.tag.segment, lane.tag.lane + 1)]\n FeatureValue(lane.width/2 - offset + lane_left.width)\n else\n FeatureValue(NaN, FeatureState.MISSING) # there is no left lane\n end\nend\ngenerate_feature_functions(\"MarkerDist_Right_Right\", :d_mrr, Float64, \"m\", can_be_missing=true)\nfunction Base.get(::Feature_MarkerDist_Right_Right, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n #=\n Distance to the right lane marker one lane to the right\n =#\n\n veh = rec[pastframe][vehicle_index]\n lane = roadway[veh.state.posF.roadind.tag]\n if n_lanes_right(lane, roadway) > 0\n offset = veh.state.posF.t\n lane_right = roadway[LaneTag(lane.tag.segment, lane.tag.lane - 1)]\n FeatureValue(lane.width/2 + offset + lane_right.width)\n else\n FeatureValue(NaN, FeatureState.MISSING) # there is no right lane\n end\nend\ngenerate_feature_functions(\"RoadEdgeDist_Left\", :d_edgel, Float64, \"m\")\nfunction Base.get(::Feature_RoadEdgeDist_Left, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n veh = rec[pastframe][vehicle_index]\n offset = veh.state.posF.t\n footpoint = get_footpoint(veh)\n seg = roadway[veh.state.posF.roadind.tag.segment]\n lane = seg.lanes[end]\n roadproj = proj(footpoint, lane, roadway)\n curvept = roadway[RoadIndex(roadproj)]\n lane = roadway[roadproj.tag]\n FeatureValue(lane.width/2 + abs(curvept.pos - footpoint) - offset)\nend\ngenerate_feature_functions(\"RoadEdgeDist_Right\", :d_edger, Float64, \"m\")\nfunction Base.get(::Feature_RoadEdgeDist_Right, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n veh = rec[pastframe][vehicle_index]\n offset = veh.state.posF.t\n footpoint = get_footpoint(veh)\n seg = roadway[veh.state.posF.roadind.tag.segment]\n lane = seg.lanes[1]\n roadproj = proj(footpoint, lane, roadway)\n curvept = roadway[RoadIndex(roadproj)]\n lane = roadway[roadproj.tag]\n FeatureValue(lane.width/2 + abs(curvept.pos - footpoint) + offset)\nend\ngenerate_feature_functions(\"LaneOffsetLeft\", :posFtL, Float64, \"m\", can_be_missing=true)\nfunction Base.get(::Feature_LaneOffsetLeft, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n veh_ego = rec[pastframe][vehicle_index]\n t = veh_ego.state.posF.t\n lane = roadway[veh_ego.state.posF.roadind.tag]\n if n_lanes_left(lane, roadway) > 0\n lane_left = roadway[LaneTag(lane.tag.segment, lane.tag.lane + 1)]\n lane_offset = t - lane.width/2 - lane_left.width/2\n FeatureValue(lane_offset)\n else\n FeatureValue(NaN, FeatureState.MISSING)\n end\nend\ngenerate_feature_functions(\"LaneOffsetRight\", :posFtR, Float64, \"m\", can_be_missing=true)\nfunction Base.get(::Feature_LaneOffsetRight, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n veh_ego = rec[pastframe][vehicle_index]\n t = veh_ego.state.posF.t\n lane = roadway[veh_ego.state.posF.roadind.tag]\n if n_lanes_right(lane, roadway) > 0\n lane_right = roadway[LaneTag(lane.tag.segment, lane.tag.lane - 1)]\n lane_offset = t + lane.width/2 + lane_right.width/2\n FeatureValue(lane_offset)\n else\n FeatureValue(NaN, FeatureState.MISSING)\n end\nend\ngenerate_feature_functions(\"N_Lane_Right\", :n_lane_right, Int, \"-\", lowerbound=0.0)\nfunction Base.get(::Feature_N_Lane_Right, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n nlr = rec[pastframe][vehicle_index].state.posF.roadind.tag.lane - 1\n FeatureValue(convert(Float64, nlr))\nend\ngenerate_feature_functions(\"N_Lane_Left\", :n_lane_left, Int, \"-\", lowerbound=0.0)\nfunction Base.get(::Feature_N_Lane_Left, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n veh = rec[pastframe][vehicle_index]\n seg = roadway[veh.state.posF.roadind.tag.segment]\n nll = length(seg.lanes) - veh.state.posF.roadind.tag.lane\n FeatureValue(convert(Float64, nll))\nend\ngenerate_feature_functions(\"Has_Lane_Right\", :has_lane_right, Bool, \"-\", lowerbound=0.0, upperbound=1.0)\nfunction Base.get(::Feature_Has_Lane_Right, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n val = get(N_LANE_RIGHT, rec, roadway, vehicle_index, pastframe).v > 0.0\n FeatureValue(convert(Float64, val))\nend\ngenerate_feature_functions(\"Has_Lane_Left\", :has_lane_left, Bool, \"-\", lowerbound=0.0, upperbound=1.0)\nfunction Base.get(::Feature_Has_Lane_Left, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n val = get(N_LANE_LEFT, rec, roadway, vehicle_index, pastframe).v > 0.0\n FeatureValue(convert(Float64, val))\nend\ngenerate_feature_functions(\"LaneCurvature\", :curvature, Float64, \"1/m\", can_be_missing=true)\nfunction Base.get(::Feature_LaneCurvature, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n veh = rec[pastframe][vehicle_index]\n curvept = roadway[veh.state.posF.roadind]\n val = curvept.k\n if isnan(val)\n FeatureValue(0.0, FeatureState.MISSING)\n else\n FeatureValue(val)\n end\nend\n\n# Dist_Merge\n# Dist_Split\n\ngenerate_feature_functions(\"TimeToCrossing_Right\", :ttcr_mr, Float64, \"s\", lowerbound=0.0, censor_hi=10.0)\nfunction Base.get(::Feature_TimeToCrossing_Right, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n d_mr = get(MARKERDIST_RIGHT, rec, roadway, vehicle_index, pastframe).v\n velFt = get(VELFT, rec, roadway, vehicle_index, pastframe).v\n\n if d_mr > 0.0 && velFt < 0.0\n FeatureValue(-d_mr / velFt)\n else\n FeatureValue(Inf)\n end\nend\ngenerate_feature_functions(\"TimeToCrossing_Left\", :ttcr_ml, Float64, \"s\", lowerbound=0.0, censor_hi=10.0)\nfunction Base.get(::Feature_TimeToCrossing_Left, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n d_ml = get(MARKERDIST_RIGHT, rec, roadway, vehicle_index, pastframe).v\n velFt = get(VELFT, rec, roadway, vehicle_index, pastframe).v\n\n if d_ml > 0.0 && velFt < 0.0\n FeatureValue(-d_ml / velFs)\n else\n FeatureValue(Inf)\n end\nend\ngenerate_feature_functions(\"EstimatedTimeToLaneCrossing\", :est_ttcr, Float64, \"s\", lowerbound=0.0, censor_hi=10.0)\nfunction Base.get(::Feature_EstimatedTimeToLaneCrossing, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n ttcr_left = get(TIMETOCROSSING_LEFT, rec, roadway, vehicle_index, pastframe).v\n ttcr_right = get(TIMETOCROSSING_RIGHT, rec, roadway, vehicle_index, pastframe).v\n FeatureValue(min(ttcr_left, ttcr_right))\nend\ngenerate_feature_functions(\"A_REQ_StayInLane\", :a_req_stayinlane, Float64, \"m/s²\", can_be_missing=true)\nfunction Base.get(::Feature_A_REQ_StayInLane, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n velFt = get(VELFT, rec, roadway, vehicle_index, pastframe).v\n\n if velFt > 0.0\n d_mr = get(MARKERDIST_RIGHT, rec, roadway, vehicle_index, pastframe).v\n if d_mr > 0.0\n return FeatureValue(0.5velFt*velFt / d_mr)\n else\n return FeatureValue(NaN, FeatureState.MISSING)\n end\n else\n d_ml = get(MARKERDIST_LEFT, rec, roadway, vehicle_index, pastframe)\n if d_ml < 0.0\n return FeatureValue(-0.5velFt*velFt / d_ml)\n else\n return FeatureValue(NaN, FeatureState.MISSING)\n end\n end\nend\n\ngenerate_feature_functions(\"Time_Consecutive_Brake\", :time_consec_brake, Float64, \"s\", lowerbound=0.0)\nfunction Base.get(::Feature_Time_Consecutive_Brake, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n\n prev_accel = convert(Float64, get(ACC, rec, roadway, vehicle_index, pastframe))\n if prev_accel ≥ 0.0\n FeatureValue(0.0)\n else\n pastframe_orig = pastframe\n id = rec[pastframe][vehicle_index].id\n while pastframe_inbounds(rec, pastframe-1) &&\n get(ACC, rec, roadway, findfirst(rec[pastframe-1], id)) < 0.0\n\n pastframe -= 1\n end\n\n FeatureValue(get_elapsed_time(rec, pastframe, pastframe_orig))\n end\nend\ngenerate_feature_functions(\"Time_Consecutive_Accel\", :time_consec_accel, Float64, \"s\", lowerbound=0.0)\nfunction Base.get(::Feature_Time_Consecutive_Accel, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n\n prev_accel = convert(Float64, get(ACC, rec, roadway, vehicle_index, pastframe))\n if prev_accel ≤ 0.0\n FeatureValue(0.0)\n else\n\n pastframe_orig = pastframe\n id = rec[pastframe][vehicle_index].id\n while pastframe_inbounds(rec, pastframe-1) &&\n get(ACC, rec, roadway, findfirst(rec[pastframe-1], id)) > 0.0\n\n pastframe -= 1\n end\n\n FeatureValue(get_elapsed_time(rec, pastframe, pastframe_orig))\n end\nend\ngenerate_feature_functions(\"Time_Consecutive_Throttle\", :time_consec_throttle, Float64, \"s\", lowerbound=0.0)\nfunction Base.get(::Feature_Time_Consecutive_Throttle, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0)\n tc_accel = get(TIME_CONSECUTIVE_ACCEL, rec, roadway, vehicle_index, pastframe).v\n tc_brake = get(TIME_CONSECUTIVE_BRAKE, rec, roadway, vehicle_index, pastframe).v\n FeatureValue(tc_accel ≥ tc_brake ? tc_accel : -tc_brake)\nend\n\n#############################################\n#\n# FRONT\n#\n#############################################\n\ngenerate_feature_functions(\"Dist_Front\", :d_front, Float64, \"m\", lowerbound=0.0, can_be_missing=true)\nfunction Base.get(::Feature_Dist_Front, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;\n neighborfore::NeighborLongitudinalResult = get_neighbor_fore_along_lane(rec[pastframe], vehicle_index, roadway),\n censor_hi::Float64=100.0,\n )\n\n if neighborfore.ind == 0\n FeatureValue(100.0, FeatureState.CENSORED_HI)\n else\n scene = rec[pastframe]\n len_ego = scene[vehicle_index].def.length\n len_oth = scene[neighborfore.ind].def.length\n FeatureValue(neighborfore.Δs - len_ego/2 - len_oth/2)\n end\nend\ngenerate_feature_functions(\"Speed_Front\", :v_front, Float64, \"m/s\", can_be_missing=true)\nfunction Base.get(::Feature_Speed_Front, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;\n neighborfore::NeighborLongitudinalResult = get_neighbor_fore_along_lane(rec[pastframe], vehicle_index, roadway),\n )\n\n if neighborfore.ind == 0\n FeatureValue(0.0, FeatureState.MISSING)\n else\n FeatureValue(rec[pastframe][neighborfore.ind].state.v)\n end\nend\ngenerate_feature_functions(\"Timegap\", :timegap, Float64, \"s\", can_be_missing=true)\nfunction Base.get(::Feature_Timegap, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;\n neighborfore::NeighborLongitudinalResult = get_neighbor_fore_along_lane(rec[pastframe], vehicle_index, roadway),\n censor_hi::Float64 = 10.0,\n )\n\n v = rec[pastframe][vehicle_index].state.v\n\n if v ≤ 0.0 || neighborfore.ind == 0\n FeatureValue(censor_hi, FeatureState.CENSORED_HI)\n else\n scene = rec[pastframe]\n len_ego = scene[vehicle_index].def.length\n len_oth = scene[neighborfore.ind].def.length\n Δs = neighborfore.Δs - len_ego/2 - len_oth/2\n\n if Δs > 0.0\n FeatureValue(Δs / v)\n else\n FeatureValue(0.0) # collision!\n end\n end\nend\n\ngenerate_feature_functions(\"Inv_TTC\", :inv_ttc, Float64, \"1/s\", can_be_missing=true)\nfunction Base.get(::Feature_Inv_TTC, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;\n neighborfore::NeighborLongitudinalResult = get_neighbor_fore_along_lane(rec[pastframe], vehicle_index, roadway),\n censor_hi::Float64 = 10.0,\n )\n\n\n if neighborfore.ind == 0\n FeatureValue(0.0, FeatureState.MISSING)\n else\n scene = rec[pastframe]\n veh_fore = scene[neighborfore.ind]\n veh_rear = scene[vehicle_index]\n\n len_ego = veh_fore.def.length\n len_oth = veh_rear.def.length\n Δs = neighborfore.Δs - len_ego/2 - len_oth/2\n\n\n Δv = veh_fore.state.v - veh_rear.state.v\n\n if Δs < 0.0 # collision!\n FeatureValue(censor_hi, FeatureState.CENSORED_HI)\n elseif Δv > 0.0 # front car is pulling away\n FeatureValue(0.0)\n else\n f = -Δv/Δs\n if f > censor_hi\n FeatureValue(f, FeatureState.CENSORED_HI)\n else\n FeatureValue(f)\n end\n end\n end\nend\ngenerate_feature_functions(\"TTC\", :ttc, Float64, \"s\", can_be_missing=true)\nfunction Base.get(::Feature_TTC, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;\n neighborfore::NeighborLongitudinalResult = get_neighbor_fore_along_lane(rec[pastframe], vehicle_index, roadway),\n censor_hi::Float64 = 10.0,\n inv_ttc::FeatureValue = get(INV_TTC, rec, roadway, vehicle_index, pastframe, neighborfore=neighborfore, censor_hi=censor_hi),\n )\n\n if inv_ttc.i == FeatureState.MISSING\n # if the value is missing then front car not found and set TTC to censor_hi\n return FeatureValue(censor_hi, FeatureState.MISSING)\n else\n @assert is_feature_valid(inv_ttc) || inv_ttc.i == FeatureState.CENSORED_HI\n return FeatureValue(min(1.0 / inv_ttc.v, censor_hi))\n end\nend\n\n#############################################\n#\n# FRONT LEFT\n#\n#############################################\ngenerate_feature_functions(\"Dist_Front_Left\", :d_front_left, Float64, \"m\", lowerbound=0.0, can_be_missing=true)\nfunction Base.get(::Feature_Dist_Front_Left, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;\n neighborfore::NeighborLongitudinalResult = get_neighbor_fore_along_left_lane(rec[pastframe], vehicle_index, roadway),\n )\n\n get(DIST_FRONT, rec, roadway, vehicle_index, pastframe, neighborfore=neighborfore)\nend\n\n#############################################\n#\n# FRONT RIGHT\n#\n#############################################\n\ngenerate_feature_functions(\"Dist_Front_Right\", :d_front_right, Float64, \"m\", lowerbound=0.0, can_be_missing=true)\nfunction Base.get(::Feature_Dist_Front_Right, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;\n neighborfore::NeighborLongitudinalResult = get_neighbor_fore_along_right_lane(rec[pastframe], vehicle_index, roadway),\n )\n\n get(DIST_FRONT, rec, roadway, vehicle_index, pastframe, neighborfore=neighborfore)\nend\n\n#############################################\n#\n# REAR\n#\n#############################################\n\ngenerate_feature_functions(\"Dist_Rear\", :d_rear, Float64, \"m\", lowerbound=0.0, can_be_missing=true)\nfunction Base.get(::Feature_Dist_Rear, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;\n neighborrear::NeighborLongitudinalResult = get_neighbor_rear_along_lane(rec[pastframe], vehicle_index, roadway),\n censor_hi::Float64=100.0,\n )\n\n if neighborrear.ind == 0\n FeatureValue(100.0, FeatureState.CENSORED_HI)\n else\n scene = rec[pastframe]\n len_ego = scene[vehicle_index].def.length\n len_oth = scene[neighborrear.ind].def.length\n FeatureValue(neighborrear.Δs - len_ego/2 - len_oth/2)\n end\nend\ngenerate_feature_functions(\"Speed_Rear\", :v_rear, Float64, \"m/s\", can_be_missing=true)\nfunction Base.get(::Feature_Speed_Rear, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;\n neighborrear::NeighborLongitudinalResult = get_neighbor_rear_along_lane(rec[pastframe], vehicle_index, roadway),\n )\n\n if neighborrear.ind == 0\n FeatureValue(0.0, FeatureState.MISSING)\n else\n FeatureValue(rec[pastframe][neighborrear.ind].state.v)\n end\nend\n\n#############################################\n#\n# SCENE WISE\n#\n#############################################\n\ngenerate_feature_functions(\"Is_Colliding\", :is_colliding, Bool, \"-\", lowerbound=0.0, upperbound=1.0)\nfunction Base.get{S,D,I,R}(::Feature_Is_Colliding, rec::EntityQueueRecord{S,D,I}, roadway::R, vehicle_index::Int, pastframe::Int=0;\n mem::CPAMemory=CPAMemory(),\n )\n\n scene = rec[pastframe]\n is_colliding = convert(Float64, get_first_collision(scene, vehicle_index, mem).is_colliding)\n FeatureValue(is_colliding)\nend\n", "meta": {"hexsha": "2f0fffda58a768d8ddef7e4fb1bd53d0d87902d8", "size": 20767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/2d/features/features.jl", "max_stars_repo_name": "wxuejing/AutomotiveDrivingModels.jl", "max_stars_repo_head_hexsha": "27178dd5f1aeb2b5c0b4368dea7c8f24af6eb634", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/2d/features/features.jl", "max_issues_repo_name": "wxuejing/AutomotiveDrivingModels.jl", "max_issues_repo_head_hexsha": "27178dd5f1aeb2b5c0b4368dea7c8f24af6eb634", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/2d/features/features.jl", "max_forks_repo_name": "wxuejing/AutomotiveDrivingModels.jl", "max_forks_repo_head_hexsha": "27178dd5f1aeb2b5c0b4368dea7c8f24af6eb634", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.72, "max_line_length": 162, "alphanum_fraction": 0.7042423075, "num_tokens": 5889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2494412558612962}} {"text": "\n\"\"\"\nA `struct` for individuals that keeps individual-specific variables.\n\"\"\"\nmutable struct Ind{B<:AbstractFloat, C<:AbstractArray, D<:AbstractArray, E<:AbstractArray} <: AbstractAgent\n id::Int # the individual ID\n pos::Tuple{Int, Int} # the individuals position\n species::Int # the species ID the individual belongs to\n biotic_phenotype::Vector{B}\n abiotic_phenotype::Vector{B}\n epistasisMat::C # epistasis matrix\n pleiotropyMat::D # pleiotropy matrix\n q::E # expression array\n age::Int\n sex::Bool\n interaction_history::MArray{S, Int} where S # records the last interaction with all species\n energy::B # determines whether need to feed (energy=0) or not.\n W::B # survival probability\n isalive::Bool\nend\n\nstruct Params{F<:AbstractFloat, I<:Int, N<:AbstractString}\n ngenes::Vector{I}\n nphenotypes::Vector{I}\n growthrates::Vector{F}\n selectionCoeffs::Vector{F}\n ploidy::Vector{I}\n optvals::Vector{Vector{Vector{Matrix{F}}}}\n optinds::Vector{Vector{I}}\n mutProbs::Vector{Vector{DiscreteNonParametric{Bool, Float64, Vector{Bool}, Vector{Float64}}}}\n mutMagnitudes::Vector{Vector{UnivariateDistribution{S} where S<:ValueSupport}}\n N::Vector{Vector{I}}\n E::Vector{Normal{F}}\n generations::I\n nspecies::I\n new_N::Vector{Vector{I}}\n migration_traits::Vector{I}\n vision_radius::Vector{I}\n check_fraction::Vector{F}\n migration_thresholds::Vector{F}\n step::MVector{1, Int64}\n nodes::Matrix{Tuple{I, I}}\n biotic_phenotypes::Vector{Vector{I}}\n abiotic_phenotypes::Vector{Vector{I}}\n max_ages::Vector{I}\n names::Dict{I, N}\n food_sources::Matrix{F}\n interactions::Matrix{F}\n resources::Matrix{I}\n resources_org::Matrix{I}\n recombination::Vector{Poisson{F}}\n initial_energy::Vector{F}\n bottlenecks::Vector{BitMatrix}\n repro_start::Vector{Int}\n repro_end::Vector{Int}\n seed::Int\nend\n\nconst variance = 1.0\n\n\"\"\"\n model_initiation(dd)\n\nInnitializes the model.\n\"\"\"\nfunction model_initiation(dd)\n \n if !isnothing(dd[:model][\"seed\"])\n Random.seed!(dd[:model][\"seed\"])\n else\n rnd = Int(rand(1:1e6))\n dd[:model][\"seed\"] = rnd\n Random.seed!(rnd)\n end\n \n properties, species_arrays = create_properties(dd)\n epistasisMat, pleiotropyMat, expressionArrays = species_arrays\n\n space = dd[:model][\"space\"]\n\n if isnothing(space)\n fspace = GridSpace((1, 1))\n elseif typeof(space) <: Tuple\n fspace = GridSpace(space, periodic=dd[:model][\"periodic\"], metric=dd[:model][\"metric\"])\n end\n\n indtype = EvoDynamics.Ind{typeof(0.1), eltype(epistasisMat), eltype(pleiotropyMat), eltype(expressionArrays)}\n\n model = ABM(indtype, fspace, properties=properties, scheduler=Schedulers.randomly)\n \n # create and add agents\n for sp in 1:model.nspecies\n for (pos, n) in enumerate(model.N[sp])\n for ind in 1:n\n abiotic_ph = get_abiotic_phenotype(sp, epistasisMat[sp], pleiotropyMat[sp], expressionArrays[sp], model)\n biotic_ph = get_biotic_phenotype(sp, epistasisMat[sp], pleiotropyMat[sp], expressionArrays[sp], model)\n W = abiotic_fitness(abiotic_ph, sp, pos, model)\n W = adjust_fitness(W, sp, model)\n sex = false\n if model.ploidy[sp] == 2\n sex = rand((true, false))\n end\n interaction_history = MVector{model.nspecies, Int}(fill(0, model.nspecies))\n initial_energy = model.initial_energy[sp]\n add_agent!(model.nodes[pos], model, sp, biotic_ph, abiotic_ph, epistasisMat[sp], pleiotropyMat[sp], expressionArrays[sp], 0, sex, interaction_history, initial_energy, W, true)\n end \n end\n end\n\n return model\nend\n\nnnodes(x::GridSpace) = prod(size(x))\nnnodes(x::ABM) = nnodes(x.space)\n\nfunction create_properties(dd)\n nspecies = length(dd[:species])\n\n Ed = [Normal(0.0, dd[:species][i][\"environmental noise\"]) for i in 1:nspecies]\n Mdists = [[DiscreteNonParametric([true, false], [i, 1-i]) for i in dd[:species][arr][\"mutation probabilities\"]] for arr in 1:nspecies] # μ (probability of change)\n Ddists = [[Normal(0, dd[:species][ar][\"mutation magnitudes\"][1]), DiscreteNonParametric([true, false], [dd[:species][ar][\"mutation magnitudes\"][2], 1-dd[:species][ar][\"mutation magnitudes\"][2]]), Normal(0, dd[:species][ar][\"mutation magnitudes\"][3])] for ar in 1:nspecies] # amount of change in case of mutation\n \n # make single-element arrays 2D so that linAlg functions will work\n newA = Array{Array{Float64}}(undef, nspecies)\n newQ = Array{Array{Float64}}(undef, nspecies)\n for i in 1:nspecies\n if length(dd[:species][i][\"epistasis matrix\"]) == 1\n newA[i] = reshape(dd[:species][i][\"epistasis matrix\"], 1, 1)\n newQ[i] = reshape(dd[:species][i][\"expression array\"], 1, 1)\n else\n newA[i] = dd[:species][i][\"epistasis matrix\"]\n newQ[i] = dd[:species][i][\"expression array\"]\n end\n end\n\n epistasisMatS = [MArray{Tuple{size(newA[i])...}}(newA[i]) for i in eachindex(newA)]\n pleiotropyMatS = [MArray{Tuple{size(dd[:species][i][\"pleiotropy matrix\"])...}}(dd[:species][i][\"pleiotropy matrix\"]) for i in 1:nspecies]\n expressionArraysS = [MArray{Tuple{size(newQ[i])...}}(newQ[i]) for i in eachindex(newQ)]\n\n ngenes = [dd[:species][i][\"number of genes\"] for i in 1:nspecies]\n nphenotypes = [dd[:species][i][\"number of phenotypes\"] for i in 1:nspecies]\n growthrates = [dd[:species][i][\"growth rate\"] for i in 1:nspecies]\n selectionCoeffs = [dd[:species][i][\"selection coefficient\"] for i in 1:nspecies]\n ploidy = [dd[:species][i][\"ploidy\"] for i in 1:nspecies]\n optvals = [dd[:species][i][\"optimal phenotype values\"] for i in 1:nspecies]\n optinds = [dd[:species][i][\"optimal phenotypes\"] for i in 1:nspecies]\n Ns = [dd[:species][i][\"N\"] for i in 1:nspecies]\n migration_traits = [dd[:species][i][\"migration phenotype\"] for i in 1:nspecies]\n vision_radius = [dd[:species][i][\"vision radius\"] for i in 1:nspecies]\n check_fraction = [dd[:species][i][\"check fraction\"] for i in 1:nspecies]\n migration_thresholds = [dd[:species][i][\"migration threshold\"] for i in 1:nspecies]\n generations = dd[:model][\"generations\"]\n step = MVector{1, Int}(undef)\n step[1] = 0\n nnodes = Matrix{Tuple{Int, Int}}(undef, dd[:model][\"space\"]...)\n for col in 1:size(nnodes, 2)\n for row in 1:size(nnodes, 1)\n nnodes[row, col] = (row, col)\n end\n end\n biotic_phenotyps = [dd[:species][i][\"biotic phenotypes\"] for i in 1:nspecies]\n abiotic_phenotyps = [dd[:species][i][\"abiotic phenotypes\"] for i in 1:nspecies]\n max_ages = [dd[:species][i][\"age\"] for i in 1:nspecies]\n names = Dict(i => dd[:species][i][\"name\"] for i in 1:nspecies)\n recombination = [Poisson(dd[:species][i][\"recombination\"]) for i in 1:nspecies]\n initial_energy = [AbstractFloat(dd[:species][i][\"initial energy\"]) for i in 1:nspecies]\n bottlenecks = [dd[:species][i][\"bottleneck times\"] for i in 1:nspecies]\n repro_start = [dd[:species][i][\"reproduction start age\"] for i in 1:nspecies]\n repro_end = [dd[:species][i][\"reproduction end age\"] for i in 1:nspecies]\n\n properties = Params(ngenes, nphenotypes, growthrates, selectionCoeffs, ploidy, optvals, optinds, Mdists, Ddists, Ns, Ed, generations, nspecies, Ns, migration_traits, vision_radius, check_fraction, migration_thresholds, step, nnodes, biotic_phenotyps, abiotic_phenotyps, max_ages, names, dd[:model][\"food sources\"], dd[:model][\"interactions\"], dd[:model][\"resources\"], deepcopy(dd[:model][\"resources\"]), recombination, initial_energy, bottlenecks, repro_start, repro_end, dd[:model][\"seed\"])\n \n return properties, (epistasisMatS, pleiotropyMatS, expressionArraysS)\nend\n\nfunction return_opt_phenotype(species::Int, generation::Int, site::Int, model::ABM)\n nabiotic = length(model.abiotic_phenotypes[species])\n output = Array{typeof(0.1)}(undef, nabiotic)\n for trait in 1:nabiotic\n output[trait] = model.optvals[species][model.optinds[species][generation+1]][trait][site]\n end\n return output\nend\n\nfunction return_opt_phenotype(species::Int, generation::Int, site::Tuple{Int, Int}, model::ABM)\n nabiotic = length(model.abiotic_phenotypes[species])\n output = Array{typeof(0.1)}(undef, nabiotic)\n for trait in 1:nabiotic\n output[trait] = model.optvals[species][model.optinds[species][generation+1]][trait][site[1],site[2]]\n end\n return output\nend\n\nfunction model_step!(model::ABM)\n model.step[1] += 1\n model.resources .= model.resources_org\nend\n\nfunction agent_step!(agent::Ind, model::ABM)\n # update age\n agent.age += 1\n # abiotic survive\n abiotic_survive!(agent, model) # the agent first survives then feeds, reproduces, and interacts.\n if !agent.isalive\n return\n end\n # use food\n burn_energy!(agent)\n # consume basic energy if agent can\n consume_food!(agent, model)\n # interact with other species\n interact!(agent, model)\n # Kill the agent if it doesn't have energy\n if agent.isalive && agent.energy < 0\n remove_agent!(agent, model)\n return\n end\n # survive\n survive!(agent, model)\n # migrate\n migrate!(agent, model)\n # reproduction for the haploid\n reproduce!(agent, model)\n # bottleneck\n if agent.isalive && model.bottlenecks[agent.species][coord2vertex(agent.pos, model), model.step[1]]\n if EvoDynamics.bottleneck(agent, model)\n remove_agent!(agent, model)\n end\n end\nend\n\nfunction bottleneck(agent, model)\n # @info \"Package bottleneck function\"\n return false\nend\n\nfunction remove_agent!(agent, model)\n agent.isalive = false\n kill_agent!(agent, model)\nend\n\n\"\"\"\n survive!(agent::Ind, model::ABM)\n\nKills the agent if it has no energy, or is too old.\n\"\"\"\nfunction survive!(agent::Ind, model::ABM)\n if !agent.isalive\n return\n elseif agent.energy < 0\n remove_agent!(agent, model)\n elseif agent.age ≥ model.max_ages[agent.species]\n remove_agent!(agent, model)\n # elseif rand() > agent.W \n # remove_agent!(agent, model)\n end\nend\n\n\"\"\"\nKills the agent by chance given its fitness `W`\n\"\"\"\nfunction abiotic_survive!(agent::Ind, model::ABM)\n if agent.isalive && rand() > agent.W\n remove_agent!(agent, model)\n end\nend\n\nfunction adjust_fitness!(agent::Ind, model::ABM)\n W = agent.W < 0 ? 0.0 : agent.W\n newW = 1.0 - ( (1.0 - W) * model.selectionCoeffs[agent.species])\n agent.W = newW\nend\n\nfunction adjust_fitness(W, species, model::ABM)\n W2 = W < 0 ? 0.0 : W\n newW = 1.0 - ( (1.0 - W2) * model.selectionCoeffs[species])\n return newW\nend\n\nfunction burn_energy!(agent)\n agent.energy -= 1\nend\n\nfunction consume_food!(agent::Ind, model::ABM)\n environmental_consumption = model.food_sources[agent.species, agent.species]\n if environmental_consumption > 0 && model.resources[agent.pos...] >= environmental_consumption\n model.resources[agent.pos...] -= environmental_consumption\n agent.energy += environmental_consumption\n end\nend\n\n\"Mutate an agent.\"\nfunction mutate!(agent::Ind, model::ABM)\n mutated = false\n # mutate gene expression\n if rand(model.mutProbs[agent.species][1])\n agent.q .+= rand(model.mutMagnitudes[agent.species][1], model.ngenes[agent.species] * model.ploidy[agent.species])\n mutated = true\n end\n # mutate pleiotropy matrix\n if rand(model.mutProbs[agent.species][2])\n randnumbers = rand(model.mutMagnitudes[agent.species][2], size(agent.pleiotropyMat))\n agent.pleiotropyMat[randnumbers] .= .!agent.pleiotropyMat[randnumbers]\n mutated = true\n end\n # mutate epistasis matrix\n if rand(model.mutProbs[agent.species][3])\n agent.epistasisMat .+= rand(model.mutMagnitudes[agent.species][3], size(agent.epistasisMat))\n mutated = true\n end\n # update biotic and abiotic phenotypes and W\n if mutated\n update_fitness!(agent, model)\n end\nend\n\ncoord2vertex(c, model) = c[1] + (size(model.space)[1] * (c[2]-1))\n\nfunction update_fitness!(agent::Ind, model::ABM)\n abiotic_phenotype = get_abiotic_phenotype(agent, model) \n biotic_phenotype = get_biotic_phenotype(agent, model)\n W = abiotic_fitness(abiotic_phenotype, agent.species, agent.pos, model)\n W = adjust_fitness(W, agent.species, model)\n agent.biotic_phenotype .= biotic_phenotype\n agent.abiotic_phenotype .= abiotic_phenotype\n agent.W = W\nend", "meta": {"hexsha": "38b24e31c1d8bba27e3d4f7642680bebed7adbcc", "size": 11937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simulation.jl", "max_stars_repo_name": "kavir1698/EvoDynamics", "max_stars_repo_head_hexsha": "98b215efc46c3fa25a4895a816f4fad25a18125a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation.jl", "max_issues_repo_name": "kavir1698/EvoDynamics", "max_issues_repo_head_hexsha": "98b215efc46c3fa25a4895a816f4fad25a18125a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation.jl", "max_forks_repo_name": "kavir1698/EvoDynamics", "max_forks_repo_head_hexsha": "98b215efc46c3fa25a4895a816f4fad25a18125a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.504587156, "max_line_length": 492, "alphanum_fraction": 0.7012649744, "num_tokens": 3642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24943367392062052}} {"text": "import .Tracker\nusing .Tracker: Tracker,\n TrackedReal,\n TrackedVector,\n TrackedMatrix,\n TrackedArray,\n TrackedVecOrMat,\n @grad,\n track,\n data,\n param\nusing LinearAlgebra\n\n# Different from Tracker.istracked\n_istracked(x::AbstractArray{<:TrackedReal}) = true\n_istracked(::TrackedArray) = false\n\nTracker.dual(x::Bool, p) = x\nBase.prevfloat(r::TrackedReal) = track(prevfloat, r)\n@grad function prevfloat(r::Real)\n prevfloat(data(r)), Δ -> Δ\nend\nBase.nextfloat(r::TrackedReal) = track(nextfloat, r)\n@grad function nextfloat(r::Real)\n nextfloat(data(r)), Δ -> Δ\nend\nfor i = 0:2, c = Tracker.combinations([:AbstractArray, :TrackedArray, :TrackedReal, :Number], i), f = [:hcat, :vcat]\n if :TrackedReal in c\n cnames = map(_ -> gensym(), c)\n @eval Base.$f($([:($x::$c) for (x, c) in zip(cnames, c)]...), x::Union{TrackedArray,TrackedReal}, xs::Union{AbstractArray,Number}...) =\n track($f, $(cnames...), x, xs...)\n end\nend\n@grad function vcat(x::Real)\n vcat(data(x)), (Δ) -> (Δ[1],)\nend\n@grad function vcat(x1::Real, x2::Real)\n vcat(data(x1), data(x2)), (Δ) -> (Δ[1], Δ[2])\nend\n@grad function vcat(x1::AbstractVector, x2::Real)\n vcat(data(x1), data(x2)), (Δ) -> (Δ[1:length(x1)], Δ[length(x1)+1])\nend\n\nfunction Base.copy(\n A::TrackedArray{T, 2, <:Adjoint{T, <:AbstractTriangular{T, <:AbstractMatrix{T}}}},\n) where {T <: Real}\n return track(copy, A)\nend\n@grad function Base.copy(\n A::TrackedArray{T, 2, <:Adjoint{T, <:AbstractTriangular{T, <:AbstractMatrix{T}}}},\n) where {T <: Real}\n return copy(data(A)), ∇ -> (copy(∇),)\nend\n\nBase.:*(A::TrackedMatrix, B::AbstractTriangular) = track(*, A, B)\nBase.:*(A::AbstractTriangular{T}, B::TrackedVector) where {T} = track(*, A, B)\nBase.:*(A::AbstractTriangular{T}, B::TrackedMatrix) where {T} = track(*, A, B)\nBase.:*(A::Adjoint{T, <:AbstractTriangular{T}}, B::TrackedMatrix) where {T} = track(*, A, B)\nBase.:*(A::Adjoint{T, <:AbstractTriangular{T}}, B::TrackedVector) where {T} = track(*, A, B)\n\n_eps(::Type{<:TrackedReal{T}}) where {T} = _eps(T)\n\n# AD implementations\nfunction jacobian(\n b::Union{<:ADBijector{<:TrackerAD}, Inverse{<:ADBijector{<:TrackerAD}}},\n x::Real\n)\n return data(Tracker.gradient(b, x)[1])\nend\nfunction jacobian(\n b::Union{<:ADBijector{<:TrackerAD}, Inverse{<:ADBijector{<:TrackerAD}}},\n x::AbstractVector{<:Real}\n)\n # We extract `data` so that we don't return a `Tracked` type\n return data(Tracker.jacobian(b, x))\nend\n\n# implementations for Shift bijector\nfunction _logabsdetjac_shift(a::TrackedReal, x::Real, ::Val{0})\n return param(_logabsdetjac_shift(data(a), data(x), Val(0)))\nend\nfunction _logabsdetjac_shift(a::TrackedReal, x::AbstractVector{<:Real}, ::Val{0})\n return param(_logabsdetjac_shift(data(a), data(x), Val(0)))\nend\nfunction _logabsdetjac_shift(\n a::Union{TrackedReal, TrackedVector{<:Real}},\n x::AbstractVector{<:Real},\n ::Val{1}\n)\n return param(_logabsdetjac_shift(data(a), data(x), Val(1)))\nend\nfunction _logabsdetjac_shift(\n a::Union{TrackedReal, TrackedVector{<:Real}},\n x::AbstractMatrix{<:Real},\n ::Val{1}\n)\n return param(_logabsdetjac_shift(data(a), data(x), Val(1)))\nend\n\n# Log bijector\n\n@grad function logabsdetjac(b::Log{1}, x::AbstractVector)\n return -sum(log, data(x)), Δ -> (nothing, -Δ ./ data(x))\nend\n@grad function logabsdetjac(b::Log{1}, x::AbstractMatrix)\n return -vec(sum(log, data(x); dims = 1)), Δ -> (nothing, .- Δ' ./ data(x))\nend\n\n# implementations for Scale bijector\n# Adjoints for 0-dim and 1-dim `Scale` using `Real`\nfunction _logabsdetjac_scale(a::TrackedReal, x::Real, ::Val{0})\n return track(_logabsdetjac_scale, a, data(x), Val(0))\nend\n@grad function _logabsdetjac_scale(a::Real, x::Real, ::Val{0})\n return _logabsdetjac_scale(data(a), data(x), Val(0)), Δ -> (inv(data(a)) .* Δ, nothing, nothing)\nend\n# Need to treat `AbstractVector` and `AbstractMatrix` separately due to ambiguity errors\nfunction _logabsdetjac_scale(a::TrackedReal, x::AbstractVector, ::Val{0})\n return track(_logabsdetjac_scale, a, data(x), Val(0))\nend\n@grad function _logabsdetjac_scale(a::Real, x::AbstractVector, ::Val{0})\n da = data(a)\n J = fill(inv.(da), length(x))\n return _logabsdetjac_scale(da, data(x), Val(0)), Δ -> (transpose(J) * Δ, nothing, nothing)\nend\nfunction _logabsdetjac_scale(a::TrackedReal, x::AbstractMatrix, ::Val{0})\n return track(_logabsdetjac_scale, a, data(x), Val(0))\nend\n@grad function _logabsdetjac_scale(a::Real, x::AbstractMatrix, ::Val{0})\n da = data(a)\n J = fill(size(x, 1) / da, size(x, 2))\n return _logabsdetjac_scale(da, data(x), Val(0)), Δ -> (transpose(J) * Δ, nothing, nothing)\nend\n# adjoints for 1-dim and 2-dim `Scale` using `AbstractVector`\nfunction _logabsdetjac_scale(a::TrackedVector, x::AbstractVector, ::Val{1})\n return track(_logabsdetjac_scale, a, data(x), Val(1))\nend\n@grad function _logabsdetjac_scale(a::TrackedVector, x::AbstractVector, ::Val{1})\n # ∂ᵢ (∑ⱼ log|aⱼ|) = ∑ⱼ δᵢⱼ ∂ᵢ log|aⱼ|\n # = ∂ᵢ log |aᵢ|\n # = (1 / aᵢ) ∂ᵢ aᵢ\n # = (1 / aᵢ)\n da = data(a)\n J = inv.(da)\n return _logabsdetjac_scale(da, data(x), Val(1)), Δ -> (J .* Δ, nothing, nothing)\nend\nfunction _logabsdetjac_scale(a::TrackedVector, x::AbstractMatrix, ::Val{1})\n return track(_logabsdetjac_scale, a, data(x), Val(1))\nend\n@grad function _logabsdetjac_scale(a::TrackedVector, x::AbstractMatrix, ::Val{1})\n da = data(a)\n Jᵀ = repeat(inv.(da), 1, size(x, 2))\n return _logabsdetjac_scale(da, data(x), Val(1)), Δ -> (Jᵀ * Δ, nothing, nothing)\nend\n# TODO: implement analytical gradient for scaling a vector using a matrix\n# function _logabsdetjac_scale(a::TrackedMatrix, x::AbstractVector, ::Val{1})\n# track(_logabsdetjac_scale, a, data(x), Val{1})\n# end\n# @grad function _logabsdetjac_scale(a::TrackedMatrix, x::AbstractVector, ::Val{1})\n# throw\n# end\n\n# implementations for Stacked bijector\nfunction logabsdetjac(b::Stacked, x::TrackedMatrix{<:Real})\n return mapvcat(eachcol(x)) do c\n logabsdetjac(b, c)\n end\nend\n# TODO: implement custom adjoint since we can exploit block-diagonal nature of `Stacked`\nfunction (sb::Stacked)(x::TrackedMatrix{<:Real})\n return eachcolmaphcat(sb, x)\nend\n\n# Simplex adjoints\n\nfunction _simplex_bijector(X::TrackedVecOrMat, b::SimplexBijector)\n return track(_simplex_bijector, X, b)\nend\nfunction _simplex_inv_bijector(Y::TrackedVecOrMat, b::SimplexBijector)\n return track(_simplex_inv_bijector, Y, b)\nend\n\n@grad function _simplex_bijector(X::AbstractVector, b::SimplexBijector)\n Xd = data(X)\n return _simplex_bijector(Xd, b), Δ -> (simplex_link_jacobian(Xd)' * Δ, nothing)\nend\n@grad function _simplex_inv_bijector(Y::AbstractVector, b::SimplexBijector)\n Yd = data(Y)\n return _simplex_inv_bijector(Yd, b), Δ -> (simplex_invlink_jacobian(Yd)' * Δ, nothing)\nend\n\n@grad function _simplex_bijector(X::AbstractMatrix, b::SimplexBijector)\n Xd = data(X)\n return _simplex_bijector(Xd, b), Δ -> begin\n maphcat(eachcol(Xd), eachcol(Δ)) do c1, c2\n simplex_link_jacobian(c1)' * c2\n end, nothing\n end\nend\n@grad function _simplex_inv_bijector(Y::AbstractMatrix, b::SimplexBijector)\n Yd = data(Y)\n return _simplex_inv_bijector(Yd, b), Δ -> begin\n maphcat(eachcol(Yd), eachcol(Δ)) do c1, c2\n simplex_invlink_jacobian(c1)' * c2\n end, nothing\n end\nend\n\nreplace_diag(::typeof(log), X::TrackedMatrix) = track(replace_diag, log, X)\n@grad function replace_diag(::typeof(log), X)\n Xd = data(X)\n f(i, j) = i == j ? log(Xd[i, j]) : Xd[i, j]\n out = f.(1:size(Xd, 1), (1:size(Xd, 2))')\n out, ∇ -> begin\n g(i, j) = i == j ? ∇[i, j]/Xd[i, j] : ∇[i, j]\n return (nothing, g.(1:size(Xd, 1), (1:size(Xd, 2))'))\n end\nend\n\nreplace_diag(::typeof(exp), X::TrackedMatrix) = track(replace_diag, exp, X)\n@grad function replace_diag(::typeof(exp), X)\n Xd = data(X)\n f(i, j) = ifelse(i == j, exp(Xd[i, j]), Xd[i, j])\n out = f.(1:size(Xd, 1), (1:size(Xd, 2))')\n out, ∇ -> begin\n g(i, j) = ifelse(i == j, ∇[i, j]*exp(Xd[i, j]), ∇[i, j])\n return (nothing, g.(1:size(Xd, 1), (1:size(Xd, 2))'))\n end\nend\n\nlogabsdetjac(b::SimplexBijector, x::TrackedVecOrMat) = track(logabsdetjac, b, x)\n@grad function logabsdetjac(b::SimplexBijector, x::AbstractVector)\n xd = data(x)\n return logabsdetjac(b, xd), Δ -> begin\n (nothing, simplex_logabsdetjac_gradient(xd) * Δ)\n end\nend\n@grad function logabsdetjac(b::SimplexBijector, x::AbstractMatrix)\n xd = data(x)\n return logabsdetjac(b, xd), Δ -> begin\n (nothing, maphcat(eachcol(xd), Δ) do c, g\n simplex_logabsdetjac_gradient(c) * g\n end)\n end\nend\n\nfor header in [\n (:(u::TrackedArray), :w),\n (:u, :(w::TrackedArray)),\n (:(u::TrackedArray), :(w::TrackedArray)),\n]\n @eval begin\n function get_u_hat($(header...))\n if u isa TrackedArray\n T = typeof(u)\n else\n T = typeof(w)\n end\n x = w' * u\n return (u .+ (planar_flow_m(x) - x) .* w ./ sum(abs2, w))::T\n end\n end\nend\n\nfor header in [\n (:(z::TrackedArray), :w, :b),\n (:z, :(w::TrackedArray), :b),\n (:z, :w, :(b::TrackedReal)),\n (:(z::TrackedArray), :(w::TrackedArray), :b),\n (:(z::TrackedArray), :w, :(b::TrackedReal)),\n (:z, :(w::TrackedArray), :(b::TrackedReal)),\n (:(z::TrackedArray), :(w::TrackedArray), :(b::TrackedReal)),\n]\n @eval begin\n function ψ($(header...))\n if z isa AbstractMatrix\n if z isa TrackedMatrix\n T = typeof(z)\n elseif w isa TrackedVector\n T = matrixof(typeof(w))\n else\n T = matrixof(typeof(b))\n end\n else\n if z isa TrackedVector\n T = typeof(z)\n elseif w isa TrackedVector\n T = typeof(w)\n else\n T = vectorof(typeof(b))\n end\n end\n return ((1 .- tanh.(w' * z .+ b).^2) .* w)::T # for planar flow from eq(11)\n end\n end\nend\n\nfor header in [\n (:(u::TrackedArray), :w, :b, :(z::AbstractVecOrMat)),\n (:u, :(w::TrackedArray), :b, :(z::AbstractVecOrMat)),\n (:u, :w, :(b::TrackedReal), :(z::AbstractVecOrMat)),\n (:u, :w, :b, :(z::TrackedVecOrMat)),\n (:(u::TrackedArray), :(w::TrackedArray), :b, :(z::AbstractVecOrMat)),\n (:(u::TrackedArray), :w, :(b::TrackedReal), :(z::AbstractVecOrMat)),\n (:(u::TrackedArray), :w, :b, :(z::TrackedVecOrMat)),\n (:u, :(w::TrackedArray), :(b::TrackedReal), :(z::AbstractVecOrMat)),\n (:u, :(w::TrackedArray), :b, :(z::TrackedVecOrMat)),\n (:u, :w, :(b::TrackedArray), :(z::TrackedVecOrMat)),\n (:(u::TrackedArray), :(w::TrackedArray), :(b::TrackedReal), :(z::AbstractVecOrMat)),\n (:(u::TrackedArray), :(w::TrackedArray), :b, :(z::TrackedVecOrMat)),\n (:(u::TrackedArray), :w, :(b::TrackedReal), :(z::TrackedVecOrMat)),\n (:u, :(w::TrackedArray), :(b::TrackedReal), :(z::TrackedVecOrMat)),\n (:(u::TrackedArray), :(w::TrackedArray), :(b::TrackedReal), :(z::TrackedVecOrMat)),\n]\n @eval begin\n function _planar_transform($(header...))\n u_hat = get_u_hat(u, w)\n if z isa AbstractVector\n temp = w' * z + b + zero(eltype(u_hat))\n if z isa TrackedVector\n T = typeof(z)\n elseif u_hat isa TrackedVector\n T = typeof(u_hat)\n else\n T = vectorof(typeof(temp))\n end\n else\n temp = w' * z .+ (b + zero(eltype(u_hat)))\n if z isa TrackedMatrix\n T = typeof(z)\n elseif u_hat isa TrackedVector\n T = matrixof(typeof(u_hat))\n else\n T = matrixof(typeof(temp'))\n end\n end\n transformed::T = z .+ u_hat .* tanh.(temp) # from eq(10)\n return (transformed = transformed, u_hat = u_hat)\n end\n end\nend\n\nfor header in [\n (:(α_::TrackedReal), :β, :z_0, :(z::AbstractVector)),\n (:α_, :(β::TrackedReal), :z_0, :(z::AbstractVector)),\n (:α_, :β, :(z_0::TrackedVector), :(z::AbstractVector)),\n (:α_, :β, :z_0, :(z::TrackedVector)),\n (:(α_::TrackedReal), :(β::TrackedReal), :z_0, :(z::AbstractVector)),\n (:(α_::TrackedReal), :β, :(z_0::TrackedVector), :(z::AbstractVector)),\n (:(α_::TrackedReal), :β, :z_0, :(z::TrackedVecOrMat)),\n (:(α_::TrackedReal), :(β::TrackedReal), :(z_0::TrackedVector), :(z::AbstractVector)),\n (:(α_::TrackedReal), :(β::TrackedReal), :z_0, :(z::TrackedVector)),\n (:(α_::TrackedReal), :β, :(z_0::TrackedVector), :(z::TrackedVector)),\n (:α_, :(β::TrackedReal), :(z_0::TrackedVector), :(z::TrackedVector)),\n (:(α_::TrackedReal), :(β::TrackedReal), :(z_0::TrackedVector), :(z::TrackedVector)),\n]\n @eval begin\n function _radial_transform($(header...))\n α = softplus(α_) # from A.2\n β_hat = -α + softplus(β) # from A.2\n if β_hat isa TrackedReal\n TV = vectorof(typeof(β_hat))\n T = vectorof(typeof(β_hat))\n elseif z_0 isa TrackedVector\n TV = typeof(z_0)\n T = typeof(z_0)\n else\n T = TV = typeof(z)\n end\n Tr = promote_type(eltype(z), eltype(z_0))\n r::Tr = norm((z .- z_0)::TV)\n transformed::T = z .+ β_hat ./ (α .+ r') .* (z .- z_0) # from eq(14)\n return (transformed = transformed, α = α, β_hat = β_hat, r = r)\n end\n end\nend\n\nfor header in [\n (:(α_::TrackedReal), :β, :z_0, :(z::AbstractMatrix)),\n (:α_, :(β::TrackedReal), :z_0, :(z::AbstractMatrix)),\n (:α_, :β, :(z_0::TrackedVector), :(z::AbstractMatrix)),\n (:α_, :β, :z_0, :(z::TrackedMatrix)),\n (:(α_::TrackedReal), :(β::TrackedReal), :z_0, :(z::AbstractMatrix)),\n (:(α_::TrackedReal), :β, :(z_0::TrackedVector), :(z::AbstractMatrix)),\n (:(α_::TrackedReal), :β, :z_0, :(z::TrackedMatrix)),\n (:(α_::TrackedReal), :(β::TrackedReal), :(z_0::TrackedVector), :(z::AbstractMatrix)),\n (:(α_::TrackedReal), :(β::TrackedReal), :z_0, :(z::TrackedMatrix)),\n (:(α_::TrackedReal), :β, :(z_0::TrackedVector), :(z::TrackedMatrix)),\n (:α_, :(β::TrackedReal), :(z_0::TrackedVector), :(z::TrackedMatrix)),\n (:(α_::TrackedReal), :(β::TrackedReal), :(z_0::TrackedVector), :(z::TrackedMatrix)),\n]\n @eval begin\n function _radial_transform($(header...))\n α = softplus(α_) # from A.2\n β_hat = -α + softplus(β) # from A.2\n if β_hat isa TrackedReal\n TV = vectorof(typeof(β_hat))\n T = matrixof(TV)\n elseif z_0 isa TrackedVector\n TV = typeof(z_0)\n T = matrixof(TV)\n else\n T = typeof(z)\n TV = vectorof(T)\n end\n r::TV = mapvcat(norm, eachcol(z .- z_0))\n transformed::T = z .+ β_hat ./ (α .+ r') .* (z .- z_0) # from eq(14)\n return (transformed = transformed, α = α, β_hat = β_hat, r = r)\n end\n end\nend\n\nfunction matrixof(::Type{TrackedArray{T, 1, Vector{T}}}) where {T <: Real}\n return TrackedArray{T, 2, Matrix{T}}\nend\nfunction matrixof(::Type{TrackedReal{T}}) where {T <: Real}\n return TrackedArray{T, 2, Matrix{T}}\nend\nfunction vectorof(::Type{TrackedArray{T, 2, Matrix{T}}}) where {T <: Real}\n return TrackedArray{T, 1, Vector{T}}\nend\nfunction vectorof(::Type{TrackedReal{T}}) where {T <: Real}\n return TrackedArray{T, 1, Vector{T}}\nend\n\n(b::Exp)(x::TrackedVector) = exp.(x)::vectorof(float(eltype(x)))\n(b::Log)(x::TrackedVector) = log.(x)::vectorof(float(eltype(x)))\nlogabsdetjac(b::Log{0}, x::TrackedVector) = .-log.(x)::vectorof(float(eltype(x)))\nlogabsdetjac(b::Log{1}, x::TrackedMatrix) = - vec(sum(log.(x); dims = 1))\n\n_logabsdetjac_shift(a::Real, x::TrackedVector{T}, ::Val{0}) where {T<:Real} = zeros(T, length(x))\n_logabsdetjac_shift(a::T1, x::TrackedVector{T2}, ::Val{1}) where {T1<:Union{Real, TrackedVector}, T2<:Real} = zero(T2)\n_logabsdetjac_shift(a::T1, x::TrackedMatrix{T2}, ::Val{1}) where {T1<:Union{Real, TrackedVector}, T2<:Real} = zeros(T2, size(x, 2))\n", "meta": {"hexsha": "c9e6941013414600c688d83d876d6fdeef93db31", "size": 16507, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/compat/tracker.jl", "max_stars_repo_name": "AStupidBear/Bijectors.jl", "max_stars_repo_head_hexsha": "1204ba719476435bc888e3ee15bd696c83bb52d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/compat/tracker.jl", "max_issues_repo_name": "AStupidBear/Bijectors.jl", "max_issues_repo_head_hexsha": "1204ba719476435bc888e3ee15bd696c83bb52d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-07-23T09:20:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T12:24:03.000Z", "max_forks_repo_path": "src/compat/tracker.jl", "max_forks_repo_name": "AStupidBear/Bijectors.jl", "max_forks_repo_head_hexsha": "1204ba719476435bc888e3ee15bd696c83bb52d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-19T19:56:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-19T19:56:56.000Z", "avg_line_length": 38.034562212, "max_line_length": 143, "alphanum_fraction": 0.5853274368, "num_tokens": 5437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24925380755045354}} {"text": "\"\"\"\nspin18.jl - sampling robustness\n\"\"\"\n\nWDIR = joinpath(@__DIR__, \"../../\")\ninclude(joinpath(WDIR, \"src\", \"spin\", \"spin.jl\"))\n\nusing Altro\nusing HDF5\nusing LinearAlgebra\nusing RobotDynamics\nusing StaticArrays\nusing TrajectoryOptimization\nconst RD = RobotDynamics\nconst TO = TrajectoryOptimization\n\n# paths\nconst EXPERIMENT_META = \"spin\"\nconst EXPERIMENT_NAME = \"spin18\"\nconst SAVE_PATH = joinpath(WDIR, \"out\", EXPERIMENT_META, EXPERIMENT_NAME)\n\n# problem\nconst CONTROL_COUNT = 1\nconst STATE_COUNT = 2\nconst SAMPLE_COUNT = 8\nconst ASTATE_SIZE_BASE = STATE_COUNT * HDIM_ISO + 3 * CONTROL_COUNT\nconst ASTATE_SIZE = ASTATE_SIZE_BASE + SAMPLE_COUNT * HDIM_ISO\nconst ACONTROL_SIZE = CONTROL_COUNT\nconst INITIAL_STATE1 = [1., 0, 0, 0]\nconst INITIAL_STATE2 = [0., 1, 0, 0]\nconst INITIAL_STATE3 = [1., 0, 0, 1] ./ sqrt(2)\nconst INITIAL_STATE4 = [1., -1, 0, 0] ./ sqrt(2)\n# state indices\nconst STATE1_IDX = 1:HDIM_ISO\nconst STATE2_IDX = STATE1_IDX[end] + 1:STATE1_IDX[end] + HDIM_ISO\nconst INTCONTROLS_IDX = STATE2_IDX[end] + 1:STATE2_IDX[end] + CONTROL_COUNT\nconst CONTROLS_IDX = INTCONTROLS_IDX[end] + 1:INTCONTROLS_IDX[end] + CONTROL_COUNT\nconst DCONTROLS_IDX = CONTROLS_IDX[end] + 1:CONTROLS_IDX[end] + CONTROL_COUNT\nconst S1_IDX = DCONTROLS_IDX[end] + 1:DCONTROLS_IDX[end] + HDIM_ISO\nconst S2_IDX = S1_IDX[end] + 1:S1_IDX[end] + HDIM_ISO\nconst S3_IDX = S2_IDX[end] + 1:S2_IDX[end] + HDIM_ISO\nconst S4_IDX = S3_IDX[end] + 1:S3_IDX[end] + HDIM_ISO\nconst S5_IDX = S4_IDX[end] + 1:S4_IDX[end] + HDIM_ISO\nconst S6_IDX = S5_IDX[end] + 1:S5_IDX[end] + HDIM_ISO\nconst S7_IDX = S6_IDX[end] + 1:S6_IDX[end] + HDIM_ISO\nconst S8_IDX = S7_IDX[end] + 1:S7_IDX[end] + HDIM_ISO\n# control indices\nconst D2CONTROLS_IDX = 1:CONTROL_COUNT\n\n# model\nstruct Model <: AbstractModel\n namp::Float64\nend\n@inline RD.state_dim(::Model) = ASTATE_SIZE\n@inline RD.control_dim(::Model) = ACONTROL_SIZE\n\n\n# This cost puts a gate error cost on\n# the sample states and a LQR cost on the other terms.\n# The hessian w.r.t the state and controls is constant.\nstruct Cost{N,M,T} <: TO.CostFunction\n Q::Diagonal{T, SVector{N,T}}\n R::Diagonal{T, SVector{M,T}}\n q::SVector{N, T}\n c::T\n hess_astate::Symmetric{T, SMatrix{N,N,T}}\n target_states::Array{SVector{HDIM_ISO, T}, 1}\n q_ss1::T\n q_ss2::T\n q_ss3::T\n q_ss4::T\nend\n\nfunction Cost(Q::Diagonal{T,SVector{N,T}}, R::Diagonal{T,SVector{M,T}},\n xf::SVector{N,T}, target_states::Array{SVector{HDIM_ISO}, 1},\n q_ss1::T, q_ss2::T, q_ss3::T, q_ss4::T) where {N,M,T}\n q = -Q * xf\n c = 0.5 * xf' * Q * xf\n hess_astate = zeros(N, N)\n # For reasons unknown to the author, throwing a -1 in front\n # of the gate error Hessian makes the cost function work.\n # This is strange, because the gate error Hessian has been\n # checked against autodiff.\n hess_state1 = -1 * q_ss1 * hessian_gate_error_iso2(target_states[1])\n hess_state2 = -1 * q_ss2 * hessian_gate_error_iso2(target_states[2])\n hess_state3 = -1 * q_ss3 * hessian_gate_error_iso2(target_states[3])\n hess_state4 = -1 * q_ss4 * hessian_gate_error_iso2(target_states[4])\n hess_astate[S1_IDX, S1_IDX] = hess_state1\n hess_astate[S2_IDX, S2_IDX] = hess_state2\n hess_astate[S3_IDX, S3_IDX] = hess_state3\n hess_astate[S4_IDX, S4_IDX] = hess_state4\n hess_astate[S5_IDX, S5_IDX] = hess_state1\n hess_astate[S6_IDX, S6_IDX] = hess_state2\n hess_astate[S7_IDX, S7_IDX] = hess_state3\n hess_astate[S8_IDX, S8_IDX] = hess_state4\n hess_astate += Q\n hess_astate = Symmetric(SMatrix{N, N}(hess_astate))\n return Cost{N,M,T}(Q, R, q, c, hess_astate, target_states, q_ss1, q_ss2, q_ss3, q_ss4)\nend\n\n@inline TO.state_dim(cost::Cost{N,M,T}) where {N,M,T} = N\n@inline TO.control_dim(cost::Cost{N,M,T}) where {N,M,T} = M\n@inline Base.copy(cost::Cost{N,M,T}) where {N,M,T} = Cost{N,M,T}(\n cost.Q, cost.R, cost.q, cost.c, cost.hess_astate,\n cost.target_states, cost.q_ss1, cost.q_ss2, cost.q_ss3, cost.q_ss4\n)\n\n@inline TO.stage_cost(cost::Cost{N,M,T}, astate::SVector{N}) where {N,M,T} = (\n 0.5 * astate' * cost.Q * astate + cost.q'astate + cost.c\n + cost.q_ss1 * gate_error_iso2(astate, cost.target_states[1], S1_IDX[1] - 1)\n + cost.q_ss2 * gate_error_iso2(astate, cost.target_states[2], S2_IDX[1] - 1)\n + cost.q_ss3 * gate_error_iso2(astate, cost.target_states[3], S3_IDX[1] - 1)\n + cost.q_ss4 * gate_error_iso2(astate, cost.target_states[4], S4_IDX[1] - 1)\n + cost.q_ss1 * gate_error_iso2(astate, cost.target_states[1], S5_IDX[1] - 1)\n + cost.q_ss2 * gate_error_iso2(astate, cost.target_states[2], S6_IDX[1] - 1)\n + cost.q_ss3 * gate_error_iso2(astate, cost.target_states[3], S7_IDX[1] - 1)\n + cost.q_ss4 * gate_error_iso2(astate, cost.target_states[4], S8_IDX[1] - 1)\n)\n\n@inline TO.stage_cost(cost::Cost{N,M,T}, astate::SVector{N}, acontrol::SVector{M}) where {N,M,T} = (\n TO.stage_cost(cost, astate) + 0.5 * acontrol' * cost.R * acontrol\n)\n\nfunction TO.gradient!(E::TO.QuadraticCostFunction, cost::Cost{N,M,T}, astate::SVector{N,T}) where {N,M,T}\n E.q = (cost.Q * astate + cost.q + [\n @SVector zeros(ASTATE_SIZE_BASE);\n cost.q_ss1 * jacobian_gate_error_iso2(astate, cost.target_states[1], S1_IDX[1] - 1);\n cost.q_ss2 * jacobian_gate_error_iso2(astate, cost.target_states[2], S2_IDX[1] - 1);\n cost.q_ss3 * jacobian_gate_error_iso2(astate, cost.target_states[3], S3_IDX[1] - 1);\n cost.q_ss4 * jacobian_gate_error_iso2(astate, cost.target_states[4], S4_IDX[1] - 1);\n cost.q_ss1 * jacobian_gate_error_iso2(astate, cost.target_states[1], S5_IDX[1] - 1);\n cost.q_ss2 * jacobian_gate_error_iso2(astate, cost.target_states[2], S6_IDX[1] - 1);\n cost.q_ss3 * jacobian_gate_error_iso2(astate, cost.target_states[3], S7_IDX[1] - 1);\n cost.q_ss4 * jacobian_gate_error_iso2(astate, cost.target_states[4], S8_IDX[1] - 1);\n ])\n return false\nend\n\nfunction TO.gradient!(E::TO.QuadraticCostFunction, cost::Cost{N,M,T}, astate::SVector{N,T},\n acontrol::SVector{M,T}) where {N,M,T}\n TO.gradient!(E, cost, astate)\n E.r = cost.R * acontrol\n E.c = 0\n return false\nend\n\nfunction TO.hessian!(E::TO.QuadraticCostFunction, cost::Cost{N,M,T}, astate::SVector{N,T}) where {N,M,T}\n E.Q = cost.hess_astate\n return true\nend\n\nfunction TO.hessian!(E::TO.QuadraticCostFunction, cost::Cost{N,M,T}, astate::SVector{N,T},\n acontrol::SVector{M,T}) where {N,M,T}\n TO.hessian!(E, cost, astate)\n E.R = cost.R\n E.H .= 0\n return true\nend\n\n\n# dynamics\nfunction RD.discrete_dynamics(::Type{RD.RK3}, model::Model, astate::StaticVector,\n acontrols::StaticVector, time::Real, dt::Real) where {SC}\n camp = astate[CONTROLS_IDX[1]]\n negi_hc = camp * NEGI_H1_ISO\n h_prop = exp((FQ_NEGI_H0_ISO + negi_hc) * dt)\n state1 = h_prop * astate[STATE1_IDX]\n state2 = h_prop * astate[STATE2_IDX]\n intcontrols = astate[INTCONTROLS_IDX[1]] + dt * astate[CONTROLS_IDX[1]]\n controls = astate[CONTROLS_IDX[1]] + dt * astate[DCONTROLS_IDX[1]]\n dcontrols = astate[DCONTROLS_IDX[1]] + dt * acontrols[D2CONTROLS_IDX[1]]\n\n hp_prop = exp((FQ_NEGI_H0_ISO + (camp + model.namp) * NEGI_H1_ISO) * dt)\n hn_prop = exp((FQ_NEGI_H0_ISO + (camp - model.namp) * NEGI_H1_ISO) * dt)\n s1 = hp_prop * astate[S1_IDX]\n s2 = hp_prop * astate[S2_IDX]\n s3 = hp_prop * astate[S3_IDX]\n s4 = hp_prop * astate[S4_IDX]\n s5 = hn_prop * astate[S5_IDX]\n s6 = hn_prop * astate[S6_IDX]\n s7 = hn_prop * astate[S7_IDX]\n s8 = hn_prop * astate[S8_IDX]\n\n astate_ = [\n state1; state2; intcontrols; controls; dcontrols;\n s1; s2; s3; s4; s5; s6; s7; s8;\n ]\n\n return astate_\nend\n\n\n# main\nfunction run_traj(;gate_type=xpiby2, evolution_time=56.8, solver_type=altro,\n sqrtbp=false, integrator_type=rk3, qs=[1e0, 1e0, 1e0, 1e-1, 1e0, 1e0, 1e0, 1e0, 1e-1],\n dt_inv=Int64(1e1), smoke_test=false, constraint_tol=1e-8, al_tol=1e-4,\n pn_steps=2, max_penalty=1e11, verbose=true, save=true, max_iterations=Int64(2e5),\n namp=NAMP_PREFACTOR)\n # model configuration\n model = Model(namp)\n n = state_dim(model)\n m = control_dim(model)\n t0 = 0.\n tf = evolution_time\n \n # initial state\n x0 = SVector{n}([\n INITIAL_STATE1;\n INITIAL_STATE2;\n zeros(3 * CONTROL_COUNT);\n repeat([INITIAL_STATE1; INITIAL_STATE2; INITIAL_STATE3; INITIAL_STATE4], 2);\n ])\n # target state\n gate_unitary = GT_GATE[gate_type]\n target_states = Array{SVector{HDIM_ISO}, 1}(undef, 4)\n target_states[1] = gate_unitary * INITIAL_STATE1\n target_states[2] = gate_unitary * INITIAL_STATE2\n target_states[3] = gate_unitary * INITIAL_STATE3\n target_states[4] = gate_unitary * INITIAL_STATE4\n xf = SVector{n}([\n target_states[1];\n target_states[2];\n zeros(3 * CONTROL_COUNT);\n repeat([target_states[1]; target_states[2];\n target_states[3]; target_states[4]], 2);\n ])\n \n # control amplitude constraint\n x_max = SVector{n}([\n fill(Inf, STATE_COUNT * HDIM_ISO);\n fill(Inf, CONTROL_COUNT);\n fill(MAX_CONTROL_NORM_0, 1); # control\n fill(Inf, CONTROL_COUNT);\n fill(Inf, SAMPLE_COUNT * HDIM_ISO);\n ])\n x_min = SVector{n}([\n fill(-Inf, STATE_COUNT * HDIM_ISO);\n fill(-Inf, CONTROL_COUNT);\n fill(-MAX_CONTROL_NORM_0, 1); # control\n fill(-Inf, CONTROL_COUNT);\n fill(-Inf, SAMPLE_COUNT * HDIM_ISO);\n ])\n # control amplitude constraint at boundary\n x_max_boundary = SVector{n}([\n fill(Inf, STATE_COUNT * HDIM_ISO);\n fill(Inf, CONTROL_COUNT);\n fill(0, 1); # control\n fill(Inf, CONTROL_COUNT);\n fill(Inf, SAMPLE_COUNT * HDIM_ISO);\n ])\n x_min_boundary = SVector{n}([\n fill(-Inf, STATE_COUNT * HDIM_ISO);\n fill(-Inf, CONTROL_COUNT);\n fill(0, 1); # control\n fill(-Inf, CONTROL_COUNT);\n fill(-Inf, SAMPLE_COUNT * HDIM_ISO);\n ])\n\n # initial trajectory\n dt = dt_inv^(-1)\n N = Int(floor(evolution_time * dt_inv)) + 1\n U0 = [SVector{m}([\n fill(1e-4, CONTROL_COUNT);\n ]) for k = 1:N-1]\n X0 = [SVector{n}([\n fill(NaN, n);\n ]) for k = 1:N]\n Z = Traj(X0, U0, dt * ones(N))\n\n # cost function\n Q = Diagonal(SVector{n}([\n fill(qs[1], STATE_COUNT * HDIM_ISO); # ψ1, ψ2\n fill(qs[2], 1); # ∫a\n fill(qs[3], 1); # a\n fill(qs[4], 1); # ∂a\n fill(0, SAMPLE_COUNT * HDIM_ISO); \n ]))\n Qf = Q * N\n R = Diagonal(SVector{m}([\n fill(qs[9], CONTROL_COUNT);\n ]))\n cost_k = Cost(Q, R, xf, target_states, qs[5], qs[6], qs[7], qs[8])\n cost_f = Cost(Qf, R, xf, target_states, N * qs[5], N * qs[6], N * qs[7], N * qs[8])\n objective = TO.Objective(cost_k, cost_f, N)\n \n # must satisfy control amplitude bound\n control_bnd = BoundConstraint(n, m, x_max=x_max, x_min=x_min)\n # must statisfy conrols start and end at 0\n control_bnd_boundary = BoundConstraint(n, m, x_max=x_max_boundary, x_min=x_min_boundary)\n # must reach target state, must have zero net flux\n target_astate_constraint = GoalConstraint(xf, [STATE1_IDX; STATE2_IDX; INTCONTROLS_IDX])\n # must obey unit norm\n norm_constraints = [NormConstraint(n, m, 1, TO.Equality(), idxs) for idxs in (\n STATE1_IDX, STATE2_IDX, S1_IDX, S2_IDX, S3_IDX, S4_IDX, S5_IDX, S6_IDX, S7_IDX, S8_IDX,\n )]\n constraints = ConstraintList(n, m, N)\n add_constraint!(constraints, control_bnd, 2:N-2)\n add_constraint!(constraints, control_bnd_boundary, N-1:N-1)\n add_constraint!(constraints, target_astate_constraint, N:N);\n for norm_constraint in norm_constraints\n add_constraint!(constraints, norm_constraint, 2:N-1)\n end\n\n # solve problem\n prob = Problem{IT_RDI[integrator_type]}(model, objective, constraints, x0, xf, Z, N, t0, evolution_time)\n solver = ALTROSolver(prob)\n verbose_pn = verbose ? true : false\n verbose_ = verbose ? 2 : 0\n projected_newton = solver_type == altro ? true : false\n constraint_tolerance = solver_type == altro ? constraint_tol : al_tol\n iterations_inner = smoke_test ? 1 : 300\n iterations_outer = smoke_test ? 1 : 30\n n_steps = smoke_test ? 1 : pn_steps\n set_options!(solver, square_root=sqrtbp, constraint_tolerance=constraint_tolerance,\n projected_newton_tolerance=al_tol, n_steps=n_steps,\n penalty_max=max_penalty, verbose_pn=verbose_pn, verbose=verbose_,\n projected_newton=projected_newton, iterations_inner=iterations_inner,\n iterations_outer=iterations_outer, iterations=max_iterations)\n Altro.solve!(solver)\n\n # post-process\n acontrols_raw = TO.controls(solver)\n acontrols_arr = permutedims(reduce(hcat, map(Array, acontrols_raw)), [2, 1])\n astates_raw = TO.states(solver)\n astates_arr = permutedims(reduce(hcat, map(Array, astates_raw)), [2, 1])\n Q_raw = Array(Q)\n Q_arr = [Q_raw[i, i] for i in 1:size(Q_raw)[1]]\n Qf_raw = Array(Qf)\n Qf_arr = [Qf_raw[i, i] for i in 1:size(Qf_raw)[1]]\n R_raw = Array(R)\n R_arr = [R_raw[i, i] for i in 1:size(R_raw)[1]]\n cidx_arr = Array(CONTROLS_IDX)\n d2cidx_arr = Array(D2CONTROLS_IDX)\n cmax = TO.max_violation(solver)\n cmax_info = TO.findmax_violation(TO.get_constraints(solver))\n iterations_ = Altro.iterations(solver)\n\n result = Dict(\n \"acontrols\" => acontrols_arr,\n \"controls_idx\" => cidx_arr,\n \"d2controls_dt2_idx\" => d2cidx_arr,\n \"evolution_time\" => evolution_time,\n \"astates\" => astates_arr,\n \"Q\" => Q_arr,\n \"Qf\" => Qf_arr,\n \"R\" => R_arr,\n \"cmax\" => cmax,\n \"cmax_info\" => cmax_info,\n \"dt\" => dt,\n \"sample_count\" => SAMPLE_COUNT,\n \"solver_type\" => Integer(solver_type),\n \"sqrtbp\" => Integer(sqrtbp),\n \"max_penalty\" => max_penalty,\n \"constraint_tol\" => constraint_tol,\n \"al_tol\" => al_tol,\n \"gate_type\" => Integer(gate_type),\n \"save_type\" => Integer(jl),\n \"integrator_type\" => Integer(integrator_type),\n \"iterations\" => iterations_,\n \"max_iterations\" => max_iterations,\n )\n \n # save\n if save\n save_file_path = generate_file_path(\"h5\", EXPERIMENT_NAME, SAVE_PATH)\n println(\"Saving this optimization to $(save_file_path)\")\n h5open(save_file_path, \"cw\") do save_file\n for key in keys(result)\n write(save_file, key, result[key])\n end\n end\n result[\"save_file_path\"] = save_file_path\n end\n\n return result\nend\n", "meta": {"hexsha": "dfac439657ae3372fc1c7c55a142d246462dcfd1", "size": 14662, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spin/spin18.jl", "max_stars_repo_name": "SchusterLab/rbqoc", "max_stars_repo_head_hexsha": "70bac2d8a9cd3c96928fc52821c59534305c20ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-03-30T01:13:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T21:28:40.000Z", "max_issues_repo_path": "src/spin/spin18.jl", "max_issues_repo_name": "SchusterLab/rbqoc", "max_issues_repo_head_hexsha": "70bac2d8a9cd3c96928fc52821c59534305c20ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-09T04:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-09T04:51:57.000Z", "max_forks_repo_path": "src/spin/spin18.jl", "max_forks_repo_name": "SchusterLab/rbqoc", "max_forks_repo_head_hexsha": "70bac2d8a9cd3c96928fc52821c59534305c20ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-30T11:28:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T11:28:38.000Z", "avg_line_length": 38.8912466844, "max_line_length": 108, "alphanum_fraction": 0.6516846269, "num_tokens": 4733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24917494959846406}} {"text": "struct GeneralUnstructuredMesh_2D <: UnstructuredMesh_2D\n name::String\n points::Vector{Point_2D}\n edges::Vector{<:SVector{L, UInt32} where {L}}\n materialized_edges::Vector{<:Edge_2D}\n faces::Vector{<:SArray{S, UInt32, 1, L} where {S<:Tuple, L}}\n materialized_faces::Vector{<:Face_2D}\n edge_face_connectivity::Vector{SVector{2, UInt32}}\n face_edge_connectivity::Vector{<:SArray{S, UInt32, 1, L} where {S<:Tuple, L}}\n boundary_edges::Vector{Vector{UInt32}}\n face_sets::Dict{String, Set{UInt32}}\nend\n\nfunction GeneralUnstructuredMesh_2D(;\n name::String = \"DefaultMeshName\",\n points::Vector{Point_2D} = Point_2D[],\n edges::Vector{<:SVector{L, UInt32} where {L}} = SVector{2, UInt32}[],\n materialized_edges::Vector{<:Edge_2D} = LineSegment_2D[],\n faces::Vector{<:SArray{S, UInt32, 1, L} where {S<:Tuple, L}} = SVector{4, UInt32}[],\n materialized_faces::Vector{<:Face_2D} = Triangle_2D[],\n edge_face_connectivity::Vector{SVector{2, UInt32}} = SVector{2, UInt32}[],\n face_edge_connectivity ::Vector{<:SArray{S, UInt32, 1, L} where {S<:Tuple, L}} = SVector{3, UInt32}[],\n boundary_edges::Vector{Vector{UInt32}} = Vector{UInt32}[],\n face_sets::Dict{String, Set{UInt32}} = Dict{String, Set{UInt32}}()\n ) where {F <: AbstractFloat, U <: Unsigned}\n return GeneralUnstructuredMesh_2D(name,\n points,\n edges,\n materialized_edges,\n faces,\n materialized_faces,\n edge_face_connectivity,\n face_edge_connectivity,\n boundary_edges,\n face_sets,\n )\nend\n\nBase.broadcastable(mesh::GeneralUnstructuredMesh_2D) = Ref(mesh)\n\n# Return a mesh with boundary edges\nfunction add_boundary_edges(mesh::M; boundary_shape=\"Unknown\"\n ) where {M <: UnstructuredMesh_2D}\n if 0 === length(mesh.edge_face_connectivity)\n mesh = add_connectivity(mesh)\n end\n return M(name = mesh.name,\n points = mesh.points,\n edges = mesh.edges,\n materialized_edges = mesh.materialized_edges,\n faces = mesh.faces,\n materialized_faces = mesh.materialized_faces,\n edge_face_connectivity = mesh.edge_face_connectivity,\n face_edge_connectivity = mesh.face_edge_connectivity,\n boundary_edges = boundary_edges(mesh, boundary_shape),\n face_sets = mesh.face_sets\n )\nend\n\n# Return a mesh with face/edge connectivity and edge/face connectivity\nfunction add_connectivity(mesh::UnstructuredMesh_2D)\n return add_edge_face_connectivity(mesh)\nend\n\n# Return a mesh with its edges\nfunction add_edges(mesh::M) where {M <: UnstructuredMesh_2D}\n return M(name = mesh.name,\n points = mesh.points,\n edges = edges(mesh),\n materialized_edges = mesh.materialized_edges,\n faces = mesh.faces,\n materialized_faces = mesh.materialized_faces,\n edge_face_connectivity = mesh.edge_face_connectivity,\n face_edge_connectivity = mesh.face_edge_connectivity,\n boundary_edges = mesh.boundary_edges,\n face_sets = mesh.face_sets\n )\nend\n\n# Return a mesh with edge/face connectivity\nfunction add_edge_face_connectivity(mesh::M) where {M <: UnstructuredMesh_2D}\n if 0 === length(mesh.face_edge_connectivity)\n mesh = add_face_edge_connectivity(mesh)\n end\n return M(name = mesh.name,\n points = mesh.points,\n edges = mesh.edges,\n materialized_edges = mesh.materialized_edges,\n faces = mesh.faces,\n materialized_faces = mesh.materialized_faces,\n edge_face_connectivity = edge_face_connectivity(mesh),\n face_edge_connectivity = mesh.face_edge_connectivity,\n boundary_edges = mesh.boundary_edges,\n face_sets = mesh.face_sets\n )\nend\n\n# Return a mesh with every field created\nfunction add_everything(mesh::UnstructuredMesh_2D)\n return add_materialized_faces(\n add_materialized_edges(\n add_boundary_edges(mesh, boundary_shape = \"Rectangle\")))\nend\n\n# Return a mesh with face/edge connectivity\nfunction add_face_edge_connectivity(mesh::M) where {M <: UnstructuredMesh_2D}\n if 0 === length(mesh.edges)\n mesh = add_edges(mesh)\n end\n return M(name = mesh.name,\n points = mesh.points,\n edges = mesh.edges,\n materialized_edges = mesh.materialized_edges,\n faces = mesh.faces,\n materialized_faces = mesh.materialized_faces,\n edge_face_connectivity = mesh.edge_face_connectivity,\n face_edge_connectivity = face_edge_connectivity(mesh),\n boundary_edges = mesh.boundary_edges,\n face_sets = mesh.face_sets\n )\nend\n\n# Return a mesh with materialized edges\nfunction add_materialized_edges(mesh::M) where {M <: UnstructuredMesh_2D}\n if 0 === length(mesh.edges)\n mesh = add_edges(mesh)\n end\n return M(name = mesh.name,\n points = mesh.points,\n edges = mesh.edges,\n materialized_edges = materialize_edges(mesh),\n faces = mesh.faces,\n materialized_faces = mesh.materialized_faces,\n edge_face_connectivity = mesh.edge_face_connectivity,\n face_edge_connectivity = mesh.face_edge_connectivity,\n boundary_edges = mesh.boundary_edges,\n face_sets = mesh.face_sets\n )\nend\n\n# Return a mesh with materialized faces\nfunction add_materialized_faces(mesh::M) where {M <: UnstructuredMesh_2D}\n return M(name = mesh.name,\n points = mesh.points,\n edges = mesh.edges,\n materialized_edges = mesh.materialized_edges,\n faces = mesh.faces,\n materialized_faces = materialize_faces(mesh),\n edge_face_connectivity = mesh.edge_face_connectivity,\n face_edge_connectivity = mesh.face_edge_connectivity,\n boundary_edges = mesh.boundary_edges,\n face_sets = mesh.face_sets\n )\nend\n\n# Return a vector of the faces adjacent to the face of ID face\nfunction adjacent_faces(face::UInt32, mesh::UnstructuredMesh_2D)\n edges = mesh.face_edge_connectivity[face]\n the_adjacent_faces = UInt32[]\n for edge in edges\n faces = mesh.edge_face_connectivity[edge]\n for face_id in faces\n if face_id != face && face_id != 0\n push!(the_adjacent_faces, face_id)\n end\n end\n end\n return the_adjacent_faces\nend\n\n# Area of face\nfunction area(face::SVector{N, UInt32}, points::Vector{Point_2D}) where {N}\n return area(materialize_face(face, points))\nend\n\n# Return the area of a face set\nfunction area(mesh::UnstructuredMesh_2D, face_set::Set{UInt32})\n if 0 < length(mesh.materialized_faces)\n return mapreduce(x->area(mesh.materialized_faces[x]), +, face_set)\n else\n return mapreduce(x->area(mesh.faces[x], mesh.points), +, face_set)\n end \nend\n\n# Return the area of a face set by name\nfunction area(mesh::UnstructuredMesh_2D, set_name::String)\n return area(mesh, mesh.face_sets[set_name])\nend\n\n# Bounding box of a vector of points\nfunction boundingbox(points::Vector{Point_2D})\n x = getindex.(points, 1)\n y = getindex.(points, 2)\n return Rectangle_2D(minimum(x), minimum(y), maximum(x), maximum(y))\nend\n\n# Bounding box of a vector of points\nfunction boundingbox(points::SVector{L, Point_2D}) where {L}\n x = getindex.(points, 1)\n y = getindex.(points, 2)\n return Rectangle_2D(minimum(x), minimum(y), maximum(x), maximum(y))\nend\n\n# Return a vector containing vectors of the edges in each side of the mesh's bounding shape, e.g.\n# For a rectangular bounding shape the sides are North, East, South, West. Then the output would\n# be [ [e1, e2, e3, ...], [e17, e18, e18, ...], ..., [e100, e101, ...]]\nfunction boundary_edges(mesh::UnstructuredMesh_2D, boundary_shape::String)\n # edges which have face 0 in their edge_face connectivity are boundary edges\n the_boundary_edges = UInt32.(findall(x->x[1] === 0x00000000, mesh.edge_face_connectivity))\n if boundary_shape == \"Rectangle\"\n # Sort edges into NESW\n bb = boundingbox(mesh.points)\n y_north = bb.ymax\n x_east = bb.xmax\n y_south = bb.ymin\n x_west = bb.xmin\n p_NW = Point_2D(x_west, y_north)\n p_NE = bb.tr\n p_SE = Point_2D(x_east, y_south)\n p_SW = bb.bl\n edges_north = UInt32[] \n edges_east = UInt32[] \n edges_south = UInt32[] \n edges_west = UInt32[] \n # Insert edges so that indices move from NW -> NE -> SE -> SW -> NW\n for edge ∈ the_boundary_edges\n epoints = edgepoints(mesh.edges[edge], mesh.points)\n if all(x->abs(x[2] - y_north) < 1e-4, epoints)\n insert_boundary_edge!(edge, p_NW, edges_north, mesh)\n elseif all(x->abs(x[1] - x_east) < 1e-4, epoints)\n insert_boundary_edge!(edge, p_NE, edges_east, mesh)\n elseif all(x->abs(x[2] - y_south) < 1e-4, epoints)\n insert_boundary_edge!(edge, p_SE, edges_south, mesh)\n elseif all(x->abs(x[1] - x_west) < 1e-4, epoints)\n insert_boundary_edge!(edge, p_SW, edges_west, mesh)\n else\n @error \"Edge $edge could not be classified as NSEW\"\n end\n end\n return [ edges_north, edges_east, edges_south, edges_west ]\n else\n return [ convert(Vector{UInt32}, the_boundary_edges) ]\n end \nend \n\n# SVector of MVectors of point IDs representing the 3 edges of a triangle\nfunction edges(face::SVector{3, UInt32})\n edges = SVector( MVector{2, UInt32}(face[1], face[2]),\n MVector{2, UInt32}(face[2], face[3]),\n MVector{2, UInt32}(face[3], face[1]) )\n # Order the linear edge vertices by ID\n for edge in edges\n if edge[2] < edge[1]\n e1 = edge[1]\n edge[1] = edge[2]\n edge[2] = e1\n end\n end\n return edges\nend\n\n# SVector of MVectors of point IDs representing the 4 edges of a quadrilateral\nfunction edges(face::SVector{4, UInt32})\n edges = SVector( MVector{2, UInt32}(face[1], face[2]),\n MVector{2, UInt32}(face[2], face[3]),\n MVector{2, UInt32}(face[3], face[4]),\n MVector{2, UInt32}(face[4], face[1]) )\n # Order the linear edge vertices by ID\n for edge in edges\n if edge[2] < edge[1]\n e1 = edge[1]\n edge[1] = edge[2]\n edge[2] = e1\n end\n end\n return edges\nend\n\n# SVector of MVectors of point IDs representing the 3 edges of a quadratic triangle\nfunction edges(face::SVector{6, UInt32})\n edges = SVector( MVector{3, UInt32}(face[1], face[2], face[4]),\n MVector{3, UInt32}(face[2], face[3], face[5]),\n MVector{3, UInt32}(face[3], face[1], face[6]) )\n # Order the linear edge vertices by ID\n for edge in edges\n if edge[2] < edge[1]\n e1 = edge[1]\n edge[1] = edge[2]\n edge[2] = e1\n end\n end\n return edges\nend\n\n# SVector of MVectors of point IDs representing the 4 edges of a quadratic quadrilateral\nfunction edges(face::SVector{8, UInt32})\n edges = SVector( MVector{3, UInt32}(face[1], face[2], face[5]),\n MVector{3, UInt32}(face[2], face[3], face[6]),\n MVector{3, UInt32}(face[3], face[4], face[7]),\n MVector{3, UInt32}(face[4], face[1], face[8]) )\n # Order th linear edge vertices by ID\n for edge in edges\n if edge[2] < edge[1]\n e1 = edge[1]\n edge[1] = edge[2]\n edge[2] = e1\n end\n end\n return edges\nend\n\n# The unique edges from a vector of triangles or quadrilaterals represented by point IDs\nfunction edges(mesh::UnstructuredMesh_2D)\n edges_filtered = sort(unique(reduce(vcat, edges.(mesh.faces))))\n return [ SVector(e.data) for e in edges_filtered ]\nend\n\n# A vector of length 2 SVectors, denoting the face ID each edge is connected to. If the edge\n# is a boundary edge, face ID 0 is returned\nfunction edge_face_connectivity(mesh::UnstructuredMesh_2D)\n # Each edge should only border 2 faces if it is an interior edge, and 1 face if it is\n # a boundary edge.\n # Loop through each face in the face_edge_connectivity vector and mark each edge with\n # the faces that it borders.\n if length(mesh.edges) === 0\n @error \"Does not have edges!\"\n end\n if length(mesh.face_edge_connectivity) === 0\n @error \"Does not have face/edge connectivity!\"\n end\n edge_face = [MVector{2, UInt32}(0, 0) for _ in eachindex(mesh.edges)]\n for (iface, edges) in enumerate(mesh.face_edge_connectivity)\n for iedge in edges\n # Add the face id in the first non-zero position of the edge_face conn. vec.\n if edge_face[iedge][1] == 0\n edge_face[iedge][1] = iface\n elseif edge_face[iedge][2] == 0\n edge_face[iedge][2] = iface\n else\n @error \"Edge $iedge seems to have 3 faces associated with it!\"\n end\n end\n end\n return [SVector(sort(two_faces).data) for two_faces in edge_face]\nend\n\n# Return an SVector of the points in the edge (Linear)\nfunction edgepoints(edge::SVector{2, UInt32}, points::Vector{Point_2D})\n return SVector(points[edge[1]], points[edge[2]])\nend\n\n# Return an SVector of the points in the edge (Quadratic)\nfunction edgepoints(edge::SVector{3, UInt32}, points::Vector{Point_2D})\n return SVector(points[edge[1]], points[edge[2]], points[edge[3]])\nend\n\n# Return an SVector of the points in the edge\nfunction edgepoints(edge_id::UInt32, mesh::UnstructuredMesh_2D) \n return edgepoints(mesh.edges[edge_id], mesh.points)\nend\n\n# Return an SVector of the points in the face (Triangle)\nfunction facepoints(face::SVector{3, UInt32}, points::Vector{Point_2D})\n return SVector(points[face[1]], points[face[2]], points[face[3]])\nend\n\n# Return an SVector of the points in the face (Quadrilateral)\nfunction facepoints(face::SVector{4, UInt32}, points::Vector{Point_2D})\n return SVector(points[face[1]], points[face[2]], points[face[3]], points[face[4]])\nend\n\n# Return an SVector of the points in the face (Triangle6)\nfunction facepoints(face::SVector{6, UInt32}, points::Vector{Point_2D})\n return SVector(points[face[1]], points[face[2]], points[face[3]],\n points[face[4]], points[face[5]], points[face[6]])\nend\n\n# Return an SVector of the points in the face (Quadrilateral8)\nfunction facepoints(face::SVector{8, UInt32}, points::Vector{Point_2D})\n return SVector(points[face[1]], points[face[2]], points[face[3]], points[face[4]],\n points[face[5]], points[face[6]], points[face[7]], points[face[8]])\nend\n\n# Return an SVector of the points in the face\nfunction facepoints(edge_id::UInt32, mesh::UnstructuredMesh_2D)\n return facepoints(mesh.faces[edge_id], mesh.points)\nend\n\n# Find the faces which share the vertex of ID v.\nfunction faces_sharing_vertex(v::Integer, mesh::UnstructuredMesh_2D)\n shared_faces = UInt32[]\n for i ∈ 1:length(mesh.faces)\n if v ∈ mesh.faces[i]\n push!(shared_faces, UInt32(i))\n end\n end\n return shared_faces\nend\n\n# Return the face containing point p.\nfunction findface(p::Point_2D, mesh::UnstructuredMesh_2D)\n if 0 < length(mesh.materialized_faces)\n return UInt32(findface_explicit(p, mesh.materialized_faces))\n else\n return UInt32(findface_implicit(p, mesh.faces, mesh.points))\n end\nend\n\n# Find the face containing the point p, with explicitly represented faces\nfunction findface_explicit(p::Point_2D, faces::Vector{<:Face_2D})\n for i ∈ 1:length(faces)\n if p ∈ faces[i]\n return i\n end\n end\n return 0\nend\n\n# Return the face containing the point p, with implicitly represented faces\nfunction findface_implicit(p::Point_2D,\n faces::Vector{<:SArray{S, UInt32, 1, L} where {S<:Tuple, L}},\n points::Vector{Point_2D})\n for i ∈ 1:length(faces)\n bool = p ∈ materialize_face(faces[i], points)\n if bool\n return i\n end\n end\n return 0\nend\n\n# Return the intersection algorithm that will be used for l ∩ mesh\nfunction get_intersection_algorithm(mesh::UnstructuredMesh_2D)\n if length(mesh.materialized_edges) !== 0\n return \"Edges - Explicit\"\n elseif length(mesh.edges) !== 0\n return \"Edges - Implicit\"\n elseif length(mesh.materialized_faces) !== 0\n return \"Faces - Explicit\"\n else\n return \"Faces - Implicit\"\n end\nend\n\n# Insert the boundary edge into the correct place in the vector of edge indices, based on\n# the distance from some reference point\nfunction insert_boundary_edge!(edge_index::UInt32, p_ref::Point_2D, edge_indices::Vector{UInt32},\n mesh::UnstructuredMesh_2D)\n # Compute the minimum distance from the edge to be inserted to the reference point\n insertion_distance = minimum(distance.(Ref(p_ref), \n edgepoints(mesh.edges[edge_index], mesh.points)))\n # Loop through the edge indices until an edge with greater distance from the reference point\n # is found, then insert\n nindices = length(edge_indices)\n for i ∈ 1:nindices\n epoints = edgepoints(mesh.edges[edge_indices[i]], mesh.points)\n edge_distance = minimum(distance.(Ref(p_ref), epoints))\n if insertion_distance < edge_distance\n insert!(edge_indices, i, edge_index)\n return nothing\n end\n end\n insert!(edge_indices, nindices+1, edge_index)\n return nothing\nend\n\n# Intersect a line with the mesh. Returns a vector of intersection points, sorted based\n# upon distance from the line's start point\nfunction intersect(l::LineSegment_2D, mesh::UnstructuredMesh_2D)\n # Edges are faster, so they are the default\n if length(mesh.edges) !== 0\n if 0 < length(mesh.materialized_edges)\n return intersect_edges_explicit(l, mesh.materialized_edges)\n else\n return intersect_edges_implicit(l, mesh.edges, mesh.points)\n end\n else\n if 0 < length(mesh.materialized_faces)\n return intersect_faces_explicit(l, mesh.materialized_faces)\n else\n return intersect_faces_implicit(l, mesh.faces, mesh.points)\n end\n end\nend\n\n# Intersect a line with an implicitly defined edge\nfunction intersect_edge_implicit(l::LineSegment_2D,\n edge::SVector{L, UInt32} where {L},\n points::Vector{Point_2D})\n return l ∩ materialize_edge(edge, points)\nend\n\n# Intersect a line with materialized edges\nfunction intersect_edges_explicit(l::LineSegment_2D, edges::Vector{LineSegment_2D})\n # A vector to hold all of the intersection points\n intersection_points = Point_2D[]\n for edge in edges\n npoints, point = l ∩ edge\n # If the intersections yields 1 or more points, push those points to the array of points\n if 0 < npoints\n push!(intersection_points, point)\n end\n end\n sort_intersection_points!(l[1], intersection_points)\n return intersection_points\nend\n\n# Intersect a line with implicitly defined edges\nfunction intersect_edges_explicit(l::LineSegment_2D, edges::Vector{QuadraticSegment_2D})\n # A vector to hold all of the intersection points\n intersection_points = Point_2D[]\n for edge in edges\n npoints, points = l ∩ edge\n # If the intersections yields 1 or more points, push those points to the array of points\n if 0 < npoints\n append!(intersection_points, points[1:npoints])\n end\n end\n sort_intersection_points!(l[1], intersection_points)\n return intersection_points\nend\n\n\n# Intersect a line with a vector of implicitly defined linear edges\nfunction intersect_edges_implicit(l::LineSegment_2D,\n edges::Vector{SVector{2, UInt32}},\n points::Vector{Point_2D})\n # A vector to hold all of the intersection points\n intersection_points = Point_2D[]\n # Intersect the line with each of the faces\n for edge in edges\n npoints, point = intersect_edge_implicit(l, edge, points)\n if 0 < npoints\n push!(intersection_points, point)\n end\n end\n sort_intersection_points!(l[1], intersection_points)\n return intersection_points\nend\n\n# Intersect a line with a vector of implicitly defined quadratic edges\nfunction intersect_edges_implicit(l::LineSegment_2D,\n edges::Vector{SVector{3, UInt32}},\n points::Vector{Point_2D})\n # An array to hold all of the intersection points\n intersection_points = Point_2D[]\n # Intersect the line with each of the faces\n for edge in edges\n npoints, ipoints = intersect_edge_implicit(l, edge, points)\n if 0 < npoints\n append!(intersection_points, ipoints[1:npoints])\n end\n end\n sort_intersection_points!(l[1], intersection_points)\n return intersection_points\nend\n\n# Intersect a line with an implicitly defined face\nfunction intersect_face_implicit(l::LineSegment_2D,\n face::SVector{L, UInt32} where {L},\n points::Vector{Point_2D})\n return l ∩ materialize_face(face, points)\nend\n\n# Intersect a line with explicitly defined linear faces\nfunction intersect_faces_explicit(l::LineSegment_2D, faces::Vector{<:Face_2D} )\n # An array to hold all of the intersection points\n intersection_points = Point_2D[]\n for face in faces\n npoints, points = l ∩ face\n # If the intersections yields 1 or more points, push those points to the array of points\n if 0 < npoints\n append!(intersection_points, points[1:npoints])\n end\n end\n sort_intersection_points!(l[1], intersection_points)\n return intersection_points\nend\n\n# Intersect a line with implicitly defined faces\nfunction intersect_faces_implicit(l::LineSegment_2D,\n faces::Vector{<:SArray{S, UInt32, 1, L} where {S<:Tuple, L}},\n points::Vector{Point_2D})\n # An array to hold all of the intersection points\n intersection_points = Point_2D[]\n # Intersect the line with each of the faces\n for face in faces\n npoints, ipoints = intersect_face_implicit(l, face, points)\n # If the intersections yields 1 or more points, push those points to the array of points\n if 0 < npoints\n append!(intersection_points, ipoints[1:npoints])\n end\n end\n sort_intersection_points!(l[1], intersection_points)\n return intersection_points\nend\n\n# If a point is a vertex\nfunction isvertex(p::Point_2D, mesh::UnstructuredMesh_2D)\n for point in mesh.points\n if p ≈ point\n return true\n end\n end\n return false\nend\n\n# Return a LineSegment_2D from the point IDs in an edge\nfunction materialize_edge(edge::SVector{2, UInt32}, points::Vector{Point_2D})\n return LineSegment_2D(edgepoints(edge, points))\nend\n\n# Return a QuadraticSegment_2D from the point IDs in an edge\nfunction materialize_edge(edge::SVector{3, UInt32}, points::Vector{Point_2D})\n return QuadraticSegment_2D(edgepoints(edge, points))\nend\n\n# Return a LineSegment_2D or QuadraticSegment_2D\nfunction materialize_edge(edge_id::UInt32, mesh::UnstructuredMesh_2D)\n return materialize_edge(mesh.edges[edge_id], mesh.points)\nend\n\n# Return a materialized edge for each edge in the mesh\nfunction materialize_edges(mesh::UnstructuredMesh_2D)\n return materialize_edge.(mesh.edges, Ref(mesh.points))\nend\n\n# Return a Triangle_2D from the point IDs in a face\nfunction materialize_face(face::SVector{3, UInt32}, points::Vector{Point_2D})\n return Triangle_2D(facepoints(face, points))\nend\n\n# Return a Quadrilateral_2D from the point IDs in a face\nfunction materialize_face(face::SVector{4, UInt32}, points::Vector{Point_2D})\n return Quadrilateral_2D(facepoints(face, points))\nend\n\n# Return a Triangle6_2D from the point IDs in a face\nfunction materialize_face(face::SVector{6, UInt32}, points::Vector{Point_2D})\n return Triangle6_2D(facepoints(face, points))\nend\n\n# Return a Quadrilateral8_2D from the point IDs in a face\nfunction materialize_face(face::SVector{8, UInt32}, points::Vector{Point_2D})\n return Quadrilateral8_2D(facepoints(face, points))\nend\n\n# Return an SVector of the points in the edge\nfunction materialize_face(face_id::UInt32, mesh::UnstructuredMesh_2D)\n return materialize_face(mesh.faces[face_id], mesh.points)\nend\n\n# Return a materialized face for each face in the mesh\nfunction materialize_faces(mesh::UnstructuredMesh_2D)\n return materialize_face.(mesh.faces, Ref(mesh.points))\nend\n\n# Return the number of edges in a face\nfunction num_edges(face::SVector{L, UInt32}) where {L}\n if L % 3 === 0 \n return 0x00000003\n elseif L % 4 === 0\n return 0x00000004\n else\n # Error\n return 0x00000000\n end\nend\n\nfunction remap_points_to_hilbert(points::Vector{Point_2D})\n bb = boundingbox(points)\n npoints = length(points)\n # Generate a Hilbert curve\n hilbert_points = hilbert_curve(bb, npoints)\n nhilbert_points = length(hilbert_points)\n # For each point, get the index of the hilbert points that is closest\n point_indices = Vector{Int64}(undef, npoints)\n for i ∈ 1:npoints\n min_distance = 1.0e10\n for j ∈ 1:nhilbert_points\n pdistance = distance²(points[i], hilbert_points[j])\n if pdistance < min_distance\n min_distance = pdistance\n point_indices[i] = j\n end\n end\n end\n return sortperm(point_indices)\nend\n\nfunction reorder_points_to_hilbert!(mesh::UnstructuredMesh_2D)\n # Points\n # point_map maps new_points[i] == mesh.points[point_map[i]]\n # point_map_inv maps mesh.points[i] == new_points[point_map_inv[i]]\n point_map = remap_points_to_hilbert(mesh.points)\n point_map_inv = UInt32.(sortperm(point_map))\n # reordered to resemble a hilbert curve\n permute!(mesh.points, point_map)\n\n # Adjust face indices\n # Point IDs have changed, so we need to change the point IDs referenced by the faces\n new_faces_vec = [ point_map_inv[face] for face in mesh.faces]\n for i in 1:length(mesh.faces)\n mesh.faces[i] = SVector(point_map_inv[mesh.faces[i]])\n end\n return nothing \nend\n\nfunction reorder_faces_to_hilbert!(mesh::UnstructuredMesh_2D)\n face_map = UInt32.(remap_points_to_hilbert(centroid.(materialize_faces(mesh))))\n permute!(mesh.faces, face_map)\n return nothing \nend\n\nfunction reorder_to_hilbert!(mesh::UnstructuredMesh_2D)\n reorder_points_to_hilbert!(mesh)\n reorder_faces_to_hilbert!(mesh)\n return nothing\nend\n\n# Return the ID of the edge shared by two adjacent faces\nfunction shared_edge(face1::UInt32, face2::UInt32, mesh::UnstructuredMesh_2D)\n for edge1 in mesh.face_edge_connectivity[face1]\n for edge2 in mesh.face_edge_connectivity[face2]\n if edge1 == edge2\n return edge1\n end\n end\n end\n return 0x00000000 \nend\n\n# How to display a mesh in REPL\nfunction Base.show(io::IO, mesh::UnstructuredMesh_2D)\n mesh_type = typeof(mesh)\n println(io, mesh_type)\n println(io, \" ├─ Name : $(mesh.name)\")\n size_MB = Base.summarysize(mesh)/1E6\n if size_MB < 1\n size_KB = size_MB*1000\n println(io, \" ├─ Size (KB) : $size_KB\")\n else\n println(io, \" ├─ Size (MB) : $size_MB\")\n end\n println(io, \" ├─ Points : $(length(mesh.points))\")\n nedges = length(mesh.edges)\n println(io, \" ├─ Edges : $nedges\")\n println(io, \" │ ├─ Linear : $(count(x->x isa SVector{2, UInt32}, mesh.edges))\")\n println(io, \" │ ├─ Quadratic : $(count(x->x isa SVector{3, UInt32}, mesh.edges))\")\n println(io, \" │ └─ Materialized? : $(length(mesh.materialized_edges) !== 0)\")\n println(io, \" ├─ Faces : $(length(mesh.faces))\")\n println(io, \" │ ├─ Triangle : $(count(x->x isa SVector{3, UInt32}, mesh.faces))\")\n println(io, \" │ ├─ Quadrilateral : $(count(x->x isa SVector{4, UInt32}, mesh.faces))\")\n println(io, \" │ ├─ Triangle6 : $(count(x->x isa SVector{6, UInt32}, mesh.faces))\")\n println(io, \" │ ├─ Quadrilateral8 : $(count(x->x isa SVector{8, UInt32}, mesh.faces))\")\n println(io, \" │ └─ Materialized? : $(length(mesh.materialized_faces) !== 0)\")\n println(io, \" ├─ Connectivity\")\n println(io, \" │ ├─ Edge/Face : $(0 < length(mesh.edge_face_connectivity))\")\n println(io, \" │ └─ Face/Edge : $(0 < length(mesh.face_edge_connectivity))\")\n println(io, \" ├─ Boundary edges\")\n nsides = length(mesh.boundary_edges)\n if nsides !== 0\n println(io, \" │ ├─ Edges : $(mapreduce(x->length(x), +, mesh.boundary_edges))\")\n else\n println(io, \" │ ├─ Edges : 0\") \n end\n println(io, \" │ └─ Sides : $nsides\")\n println(io, \" └─ Face sets : $(length(keys(mesh.face_sets)))\")\nend\n\n# Sort intersection points, deleting points that are less than minimum_segment_length apart\nfunction sort_intersection_points!(p::Point_2D, points::Vector{Point_2D})\n if 2 <= length(points)\n sortpoints!(p, points)\n # Eliminate any points for which the distance between consecutive points \n # is less than the minimum segment length\n delete_ids = Int64[]\n id_start = 1\n for id_stop ∈ 2:length(points)\n if distance²(points[id_start], points[id_stop]) < minimum_segment_length^2\n push!(delete_ids, id_stop)\n else\n id_start = id_stop\n end\n end\n deleteat!(points, delete_ids)\n else\n return points\n end\nend\n\n# Return a mesh with name name, composed of the faces in the set face_ids\nfunction submesh(name::String, mesh::M) where {M <: UnstructuredMesh_2D}\n # Setup faces and get all vertex ids\n face_ids = mesh.face_sets[name]\n submesh_faces = Vector{Vector{UInt32}}(undef, length(face_ids))\n vertex_ids = Set{UInt32}()\n for (i, face_id) in enumerate(face_ids)\n face_vec = collect(mesh.faces[face_id].data)\n submesh_faces[i] = face_vec\n union!(vertex_ids, Set(face_vec))\n end\n # Need to remap vertex ids in faces to new ids\n vertex_ids_sorted = sort(collect(vertex_ids))\n vertex_map = Dict{UInt32, UInt32}()\n for (i,v) in enumerate(vertex_ids_sorted)\n vertex_map[v] = i\n end\n submesh_points = Vector{Point_2D}(undef, length(vertex_ids_sorted))\n for (i, v) in enumerate(vertex_ids_sorted)\n submesh_points[i] = mesh.points[v]\n end\n # remap vertex ids in faces\n for face in submesh_faces\n for (i, v) in enumerate(face)\n face[i] = vertex_map[v]\n end\n end\n # At this point we have points, faces, & name.\n # Just need to get the face sets\n submesh_face_sets = Dict{String, Set{UInt32}}()\n for face_set_name in keys(mesh.face_sets)\n set_intersection = mesh.face_sets[face_set_name] ∩ face_ids\n if length(set_intersection) !== 0\n submesh_face_sets[face_set_name] = set_intersection\n end\n end\n # Need to remap face ids in face sets\n face_map = Dict{UInt32, UInt32}()\n for (i,f) in enumerate(face_ids)\n face_map[f] = i\n end\n for face_set_name in keys(submesh_face_sets)\n new_set = Set{UInt32}()\n for fid in submesh_face_sets[face_set_name]\n union!(new_set, face_map[fid])\n end\n submesh_face_sets[face_set_name] = new_set\n end\n return M(name = name,\n points = submesh_points,\n faces = [SVector{length(f), UInt32}(f) for f in submesh_faces],\n face_sets = submesh_face_sets\n )\nend\n\n# Plot\n# -------------------------------------------------------------------------------------------------\nif enable_visualization\n function convert_arguments(LS::Type{<:LineSegments}, mesh::UnstructuredMesh_2D)\n if 0 < length(mesh.materialized_edges)\n return convert_arguments(LS, mesh.materialized_edges)\n elseif 0 < length(mesh.edges)\n return convert_arguments(LS, materialize_edges(mesh))\n else\n return convert_arguments(LS, materialize_faces(mesh))\n end\n end\n\n function convert_arguments(P::Type{<:Mesh}, mesh::UnstructuredMesh_2D)\n if 0 < length(mesh.materialized_faces)\n return convert_arguments(P, mesh.materialized_faces)\n else\n return convert_arguments(P, materialize_faces(mesh))\n end\n end\nend\n", "meta": {"hexsha": "8e9c90194fbe3cd0a2d5b5934b0b83908ca4e30b", "size": 33275, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mesh/UnstructuredMesh_2D.jl", "max_stars_repo_name": "KyleVaughn/MOCNeutronTransport", "max_stars_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-10T19:36:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T15:34:40.000Z", "max_issues_repo_path": "src/mesh/UnstructuredMesh_2D.jl", "max_issues_repo_name": "KyleVaughn/MOCNeutronTransport", "max_issues_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2022-01-20T03:03:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T18:29:33.000Z", "max_forks_repo_path": "src/mesh/UnstructuredMesh_2D.jl", "max_forks_repo_name": "KyleVaughn/MOCNeutronTransport", "max_forks_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3352534562, "max_line_length": 110, "alphanum_fraction": 0.644567994, "num_tokens": 8524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2491749429814667}} {"text": "\"\"\"\n struct CSF\n\nRepresents a single _configuration state function_ (CSF) adapted to angular momentum\nsymmetries. Depending on the type parameters, it can represent both non-relativistic CSFs in\n[``LS``-coupling](@ref) and relativistic CSFs in [``jj``-coupling](@ref).\n\nA CSF is defined by the following information:\n\n* The configuration, i.e. an ordered list of subshells together with their occupations.\n* A list of intermediate coupling terms (including the seniority quantum number to label\n states in degenerate subspaces) for each subshell in the configuration.\n* A list of coupling terms for the coupling tree. The coupling is assumed to be done by,\n first, coupling two orbitals together, then coupling that to the next orbital, and so on.\n\nAn instance of a [`CSF`](@ref) object does not specify the ``J_z`` or ``L_z``/``S_z``\nquantum number(s).\n\n# Constructors\n\n CSF(configuration::Configuration, subshell_terms::Vector, terms::Vector)\n\nConstructs an instance of a [`CSF`](@ref) from the information provided. The arguments have\ndifferent requirements depending on whether it is `configuration` is based on relativistic\nor non-relativistic orbitals.\n\n* If the configuration is based on [`Orbital`](@ref)s, `subshell_terms` must be a list of\n [`IntermediateTerm`](@ref)s and `terms` a list of [`Term`](@ref)s.\n* If it is a configuration of [`RelativisticOrbital`](@ref)s, both `subshell_terms` and\n `terms` should both be a list of half-integer values.\n\"\"\"\nstruct CSF{O<:AbstractOrbital, T<:Union{Term,HalfInteger}, S}\n config::Configuration{<:O}\n subshell_terms::Vector{IntermediateTerm{T,S}}\n terms::Vector{T}\n\n function CSF(config::Configuration{O},\n subshell_terms::Vector{IntermediateTerm{T,S}},\n terms::Vector{T}) where {O<:Union{<:Orbital,<:RelativisticOrbital},\n T<:Union{Term,HalfInt}, S}\n length(subshell_terms) == length(peel(config)) ||\n throw(ArgumentError(\"Need to provide $(length(peel(config))) subshell terms for $(config)\"))\n length(terms) == length(peel(config)) ||\n throw(ArgumentError(\"Need to provide $(length(peel(config))) terms for $(config)\"))\n\n for (i,(orb,occ,_)) in enumerate(peel(config))\n st = subshell_terms[i]\n assert_unique_classification(orb, occ, st) ||\n throw(ArgumentError(\"$(st) is not a unique classification of $(orb)$(to_superscript(occ))\"))\n end\n\n new{O,T,S}(config, subshell_terms, terms)\n end\n\n CSF(config, subshell_terms::Vector{<:IntermediateTerm}, terms::Vector{<:Real}) =\n CSF(config, subshell_terms, convert.(HalfInt, terms))\nend\n\n\"\"\"\n const NonRelativisticCSF = CSF{<:Orbital,Term}\n\"\"\"\nconst NonRelativisticCSF = CSF{<:Orbital,Term}\n\n\"\"\"\n const RelativisticCSF = CSF{<:RelativisticOrbital,HalfInt}\n\"\"\"\nconst RelativisticCSF = CSF{<:RelativisticOrbital,HalfInt}\n\nBase.:(==)(a::CSF{O,T}, b::CSF{O,T}) where {O,T} =\n (a.config == b.config) && (a.subshell_terms == b.subshell_terms) && (a.terms == b.terms)\n\n# We possibly want to sort on configuration as well\nBase.isless(a::CSF, b::CSF) = last(a.terms) < last(b.terms)\n\nnum_electrons(csf::CSF) = num_electrons(csf.config)\n\n\"\"\"\n orbitals(csf::CSF{O}) -> Vector\n\nAccess the underlying list of orbitals\n\n```jldoctest\njulia> csf = first(csfs(rc\"1s2 2p-2\"))\n1s² 2p-²\n 0 0\n 0 0+\n\njulia> orbitals(csf)\n2-element Vector{RelativisticOrbital{Int64}}:\n 1s\n 2p-\n```\n\"\"\"\norbitals(csf::CSF) = orbitals(csf.config)\n\n\"\"\"\n csfs(::Configuration) -> Vector{CSF}\n csfs(::Vector{Configuration}) -> Vector{CSF}\n\nGenerate all [`CSF`](@ref)s corresponding to a particular configuration or a set of\nconfigurations.\n\"\"\"\nfunction csfs end\n\nfunction csfs(config::Configuration)\n map(allchoices(intermediate_terms(peel(config)))) do subshell_terms\n map(intermediate_couplings(subshell_terms)) do coupled_terms\n CSF(config, subshell_terms, coupled_terms[2:end])\n end\n end |> c -> vcat(c...) |> sort\nend\n\ncsfs(configs::Vector{Configuration{O}}) where O = vcat(map(csfs, configs)...)\n\nBase.length(csf::CSF) = length(peel(csf.config))\nBase.getindex(csf::CSF, i::Integer) =\n (peel(csf.config)[i],csf.subshell_terms[i],csf.terms[i])\n\nBase.iterate(csf::CSF, (el, i)=(length(csf)>0 ? csf[1] : nothing,1)) =\n i > length(csf) ? nothing : (el, (csf[i==length(csf) ? i : i+1],i+1))\n\nfunction Base.show(io::IO, csf::CSF)\n c = core(csf.config)\n p = peel(csf.config)\n nc = length(c)\n if nc > 0\n show(io, c)\n write(io, \" \")\n end\n\n for (i,((orb,occ,state),st,t)) in enumerate(csf)\n show(io, orb)\n occ > 1 && write(io, to_superscript(occ))\n write(io, \"($(st)|$(t))\")\n i != lastindex(p) && write(io, \" \")\n end\n print(io, iseven(parity(csf.config)) ? \"+\" : \"-\")\nend\n\nfunction Base.show(io::IO, ::MIME\"text/plain\", csf::RelativisticCSF)\n c = core(csf.config)\n nc = length(c)\n cw = length(string(c))\n\n w = 0\n p = peel(csf.config)\n for (orb,occ,state) in p\n w = max(w, length(string(orb))+length(digits(occ)))\n end\n\n w += 1\n\n cfmt = FormatExpr(\"{1:$(cw)s} \")\n ofmt = FormatExpr(\"{1:<$(w+1)s}\")\n ifmt = FormatExpr(\"{1:>$(w+1)d}\")\n rfmt = FormatExpr(\"{1:>$(w-1)d}/2\")\n\n nc > 0 && printfmt(io, cfmt, c)\n for (orb,occ,state) in p\n printfmt(io, ofmt, join([string(orb), occ > 1 ? to_superscript(occ) : \"\"], \"\"))\n end\n println(io)\n\n nc > 0 && printfmt(io, cfmt, \"\")\n for it in csf.subshell_terms\n j = it.term\n if denominator(j) == 1\n printfmt(io, ifmt, numerator(j))\n else\n printfmt(io, rfmt, numerator(j))\n end\n end\n println(io)\n\n nc > 0 && printfmt(io, cfmt, \"\")\n print(io, \" \")\n for j in csf.terms\n if denominator(j) == 1\n printfmt(io, ifmt, numerator(j))\n else\n printfmt(io, rfmt, numerator(j))\n end\n end\n print(io, iseven(parity(csf.config)) ? \"+\" : \"-\")\nend\n\nexport CSF, NonRelativisticCSF, RelativisticCSF, csfs\n", "meta": {"hexsha": "af5e03a5f7e8621650d5293f479646accb024731", "size": 6091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/csfs.jl", "max_stars_repo_name": "jagot/AtomicLevels.jl", "max_stars_repo_head_hexsha": "0bb57c1d4d1083e0f12be8fe62aabe117bcd9eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/csfs.jl", "max_issues_repo_name": "jagot/AtomicLevels.jl", "max_issues_repo_head_hexsha": "0bb57c1d4d1083e0f12be8fe62aabe117bcd9eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2016-03-16T09:19:10.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-17T15:44:04.000Z", "max_forks_repo_path": "src/csfs.jl", "max_forks_repo_name": "jagot/AtomicLevels.jl", "max_forks_repo_head_hexsha": "0bb57c1d4d1083e0f12be8fe62aabe117bcd9eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3989361702, "max_line_length": 108, "alphanum_fraction": 0.6343785914, "num_tokens": 1810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24902597501361742}} {"text": "const EXPONENTS = [\n 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,\n 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,\n 1e20, 1e21, 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28, 1e29,\n 1e30, 1e31, 1e32, 1e33, 1e34, 1e35, 1e36, 1e37, 1e38, 1e39,\n 1e40, 1e41, 1e42, 1e43, 1e44, 1e45, 1e46, 1e47, 1e48, 1e49,\n 1e50, 1e51, 1e52, 1e53, 1e54, 1e55, 1e56, 1e57, 1e58, 1e59,\n 1e60, 1e61, 1e62, 1e63, 1e64, 1e65, 1e66, 1e67, 1e68, 1e69,\n 1e70, 1e71, 1e72, 1e73, 1e74, 1e75, 1e76, 1e77, 1e78, 1e79,\n 1e80, 1e81, 1e82, 1e83, 1e84, 1e85, 1e86, 1e87, 1e88, 1e89,\n 1e90, 1e91, 1e92, 1e93, 1e94, 1e95, 1e96, 1e97, 1e98, 1e99,\n 1e100, 1e101, 1e102, 1e103, 1e104, 1e105, 1e106, 1e107, 1e108, 1e109,\n 1e110, 1e111, 1e112, 1e113, 1e114, 1e115, 1e116, 1e117, 1e118, 1e119,\n 1e120, 1e121, 1e122, 1e123, 1e124, 1e125, 1e126, 1e127, 1e128, 1e129,\n 1e130, 1e131, 1e132, 1e133, 1e134, 1e135, 1e136, 1e137, 1e138, 1e139,\n 1e140, 1e141, 1e142, 1e143, 1e144, 1e145, 1e146, 1e147, 1e148, 1e149,\n 1e150, 1e151, 1e152, 1e153, 1e154, 1e155, 1e156, 1e157, 1e158, 1e159,\n 1e160, 1e161, 1e162, 1e163, 1e164, 1e165, 1e166, 1e167, 1e168, 1e169,\n 1e170, 1e171, 1e172, 1e173, 1e174, 1e175, 1e176, 1e177, 1e178, 1e179,\n 1e180, 1e181, 1e182, 1e183, 1e184, 1e185, 1e186, 1e187, 1e188, 1e189,\n 1e190, 1e191, 1e192, 1e193, 1e194, 1e195, 1e196, 1e197, 1e198, 1e199,\n 1e200, 1e201, 1e202, 1e203, 1e204, 1e205, 1e206, 1e207, 1e208, 1e209,\n 1e210, 1e211, 1e212, 1e213, 1e214, 1e215, 1e216, 1e217, 1e218, 1e219,\n 1e220, 1e221, 1e222, 1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229,\n 1e230, 1e231, 1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239,\n 1e240, 1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249,\n 1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258, 1e259,\n 1e260, 1e261, 1e262, 1e263, 1e264, 1e265, 1e266, 1e267, 1e268, 1e269,\n 1e270, 1e271, 1e272, 1e273, 1e274, 1e275, 1e276, 1e277, 1e278, 1e279,\n 1e280, 1e281, 1e282, 1e283, 1e284, 1e285, 1e286, 1e287, 1e288, 1e289,\n 1e290, 1e291, 1e292, 1e293, 1e294, 1e295, 1e296, 1e297, 1e298, 1e299,\n 1e300, 1e301, 1e302, 1e303, 1e304, 1e305, 1e306, 1e307, 1e308,\n]\n\npow10(exp) = (@inbounds v = EXPONENTS[exp+1]; return v)\n\nmaxexponent(::Type{Int16}) = 4\nmaxexponent(::Type{Int32}) = 38\nmaxexponent(::Type{Int64}) = 308\n\nminexponent(::Type{Int16}) = -5\nminexponent(::Type{Int32}) = -38\nminexponent(::Type{Int64}) = -308\n\ninttype(::Type{Float16}) = Int16\ninttype(::Type{Float32}) = Int32\ninttype(::Type{Float64}) = Int64\n\nconst BIGN = UInt8('N')\nconst LITTLEN = UInt8('n')\nconst BIGA = UInt8('A')\nconst LITTLEA = UInt8('a')\nconst BIGI = UInt8('I')\nconst LITTLEI = UInt8('i')\nconst BIGF = UInt8('F')\nconst LITTLEF = UInt8('f')\nconst BIGT = UInt8('T')\nconst LITTLET = UInt8('t')\nconst BIGY = UInt8('Y')\nconst LITTLEY = UInt8('y')\nconst BIGE = UInt8('E')\nconst LITTLEE = UInt8('e')\n\nParsingException(::Type{<:AbstractFloat}, exp::Signed, row, col) = ParsingException(\"error parsing a `$T` value on column $col, row $row; exponent out of range: $exp\")\n\nfunction scale(exp, v::T, frac, row, col) where T\n if exp >= 0\n max_exp = maxexponent(T)\n exp > max_exp && throw(ParsingException(T, exp, row, col))\n if exp > 15\n return Float64(Base.TwicePrecision{Float64}(v) * Base.TwicePrecision{Float64}(pow10(exp)))\n else\n return v * pow10(exp)\n end\n else\n min_exp = minexponent(T)\n if exp < min_exp\n -exp + min_exp > -min_exp && throw(ParsingException(T, exp, row, col))\n return Float64(Base.TwicePrecision{Float64}(v) / Base.TwicePrecision{Float64}(pow10(-exp + min_exp)))\n else\n if exp > 15\n return Float64(Base.TwicePrecision{Float64}(v) / Base.TwicePrecision{Float64}(pow10(-exp)))\n else\n return v / pow10(-exp)\n end\n end\n end\nend\n\nfunction parsefield(io::IO, ::Type{T}, opt::CSV.Options, row, col, state, ifmissing::Function) where {T <: Union{Float16, Float32, Float64}}\n mark(io)\n @checkmissingstart()\n minussign = plussign = false\n if b == MINUS # check for leading '-' or '+'\n minussign = true\n c = peekbyte(io)\n if (NEG_ONE < c < TEN) || c == opt.decimal\n b = readbyte(io)\n end\n elseif b == PLUS\n plussign = true\n c = peekbyte(io)\n if (NEG_ONE < c < TEN) || c == opt.decimal\n b = readbyte(io)\n end\n end\n # float digit parsing\n iT = inttype(T)\n v = zero(iT)\n parseddigits = false\n while NEG_ONE < b < TEN\n parseddigits = true\n # process digits\n v *= iT(10)\n v += iT(b - ZERO)\n eof(io) && (state[] = EOF; result = T(v); @goto done)\n b = readbyte(io)\n end\n # if we didn't get any digits and character isn't leading dot, check for NaN/Inf\n if !parseddigits && b != opt.decimal\n if minussign || plussign # skip sign character, if any\n eof(io) && @goto checkmissingend\n b = readbyte(io)\n end\n if b == LITTLEN || b == BIGN\n eof(io) && @goto checkmissingend\n b = readbyte(io)\n (!(b == LITTLEA || b == BIGA) || eof(io)) && (reset(io); b = readbyte(io); @goto checkmissingend)\n b = readbyte(io)\n !(b == LITTLEN || b == BIGN) && (reset(io); b = readbyte(io); @goto checkmissingend)\n result = T(NaN)\n eof(io) && (state[] = EOF; @goto done)\n b = readbyte(io)\n @goto checkdone\n elseif b == LITTLEI || b == BIGI\n eof(io) && @goto checkmissingend\n b = readbyte(io)\n (!(b == LITTLEN || b == BIGN) || eof(io)) && (reset(io); b = readbyte(io); @goto checkmissingend)\n b = readbyte(io)\n !(b == LITTLEF || b == BIGF) && (reset(io); b = readbyte(io); @goto checkmissingend)\n result = T(Inf)\n eof(io) && (state[] = EOF; @goto done)\n b = readbyte(io)\n if b == LITTLEI || b == BIGI\n # read the rest of INFINITY\n eof(io) && (state[] = EOF; @goto done)\n b = readbyte(io)\n b == LITTLEN || b == BIGN || @goto checkdone\n eof(io) && (state[] = EOF; @goto done)\n b = readbyte(io)\n b == LITTLEI || b == BIGI || @goto checkdone\n eof(io) && (state[] = EOF; @goto done)\n b = readbyte(io)\n b == LITTLET || b == BIGT || @goto checkdone\n eof(io) && (state[] = EOF; @goto done)\n b = readbyte(io)\n b == LITTLEY || b == BIGY || @goto checkdone\n eof(io) && (state[] = EOF; @goto done)\n b = readbyte(io)\n end\n @goto checkdone\n else\n @goto checkmissingend\n end\n end\n # parse fractional part\n frac = 0\n result = T(v)\n if b == opt.decimal\n eof(io) && (state[] = EOF; parseddigits ? @goto(done) : @goto(error))\n b = readbyte(io)\n elseif b == LITTLEE || b == BIGE\n @goto parseexp\n else\n @goto checkdone\n end\n\n while NEG_ONE < b < TEN\n frac += 1\n # process digits\n v *= iT(10)\n v += iT(b - ZERO)\n eof(io) && (state[] = EOF; result = scale(-frac, v, 0, row, col); @goto done)\n b = readbyte(io)\n end\n # parse potential exp\n if b == LITTLEE || b == BIGE\n @label parseexp\n eof(io) && (state[] = EOF; result = scale(-frac, v, 0, row, col); @goto done)\n b = readbyte(io)\n exp = zero(iT)\n negativeexp = false\n if b == MINUS\n negativeexp = true\n b = readbyte(io)\n elseif b == PLUS\n b = readbyte(io)\n end\n parseddigits = false\n while NEG_ONE < b < TEN\n parseddigits = true\n # process digits\n exp *= iT(10)\n exp += iT(b - ZERO)\n eof(io) && (state[] = EOF; result = scale(ifelse(negativeexp, -exp, exp) - frac, v, frac, row, col); @goto done)\n b = readbyte(io)\n end\n result = parseddigits ? scale(ifelse(negativeexp, -exp, exp) - frac, v, frac, row, col) : scale(-frac, v, 0, row, col)\n else\n result = scale(-frac, v, 0, row, col)\n end\n\n @label checkdone\n @checkdone(done)\n @goto checkmissingend\n\n @label checkmissingend\n @checkmissingend()\n @goto error\n\n @label done\n return T(ifelse(minussign, -result, result))\n\n @label missing\n return ifmissing(row, col)\n\n @label error\n throw(ParsingException(T, b, row, col))\nend\n\n\n# (-73.99378204345703, -73.99378204345702)\n# (-73.95227813720703, -73.95227813720702)\n# (-73.98616027832031, -73.98616027832033)\n# (-74.00163269042969, -74.00163269042967)\n# (-73.96940612792969, -73.9694061279297)\n# (-73.96797943115234, -73.96797943115236)\n# (-73.95426940917969, -73.95426940917967)\n# (-73.97286224365234, -73.97286224365236)\n# (-73.99149322509766, -73.99149322509767)\n# (-73.97639465332031, -73.97639465332033)\n# (-73.97297668457031, -73.97297668457033)\n# (-73.98991394042969, -73.98991394042967)\n# (-73.98424530029297, -73.98424530029298)\n# (-73.97872161865234, -73.97872161865236)\n# (-73.99348449707031, -73.99348449707033)\n# (-73.96598815917969, -73.96598815917967)\n# (-73.98743438720703, -73.98743438720702)\n", "meta": {"hexsha": "397631f32f7541346fbfbb6fdecc5ee6b4558509", "size": 9535, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/float.jl", "max_stars_repo_name": "MLackner/CSV.jl", "max_stars_repo_head_hexsha": "6a606b17c026031ed04fc75c1f990f7c8291c3d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/float.jl", "max_issues_repo_name": "MLackner/CSV.jl", "max_issues_repo_head_hexsha": "6a606b17c026031ed04fc75c1f990f7c8291c3d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/float.jl", "max_forks_repo_name": "MLackner/CSV.jl", "max_forks_repo_head_hexsha": "6a606b17c026031ed04fc75c1f990f7c8291c3d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2931726908, "max_line_length": 167, "alphanum_fraction": 0.564027268, "num_tokens": 3907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2489799450074387}} {"text": "# Default implmenentation for CuArrays\nusing CUDA: @workspace, @argout\n\nmemsize(a::CuArray) = sizeof(a)\n\nscalar(C::CuArray) = ndims(C)==0 ? collect(C)[] : throw(DimensionMismatch())\n\nfunction add!(α, A::CuArray{<:Any, N}, CA::Symbol,\n β, C::CuArray{<:Any, N}, indCinA) where {N}\n\n T = eltype(C)\n N == length(indCinA) || throw(IndexError(\"Invalid permutation of length $N: $indCinA\"))\n CA == :N || CA == :C ||\n throw(ArgumentError(\"Value of conjA should be :N or :C instead of $CA\"))\n opA = (T <: Real || CA == :N) ? CUTENSOR_OP_IDENTITY : CUTENSOR_OP_CONJ\n opAC = CUTENSOR_OP_ADD\n\n descA = CuTensorDescriptor(A; op = opA)\n descC = CuTensorDescriptor(C; op = CUTENSOR_OP_IDENTITY)\n descD = descC\n typeCompute = convert(cudaDataType, T)\n modeA = collect(Cint, 1:N)\n modeC = collect(Cint, indCinA)\n stream = CuDefaultStream()\n if β == zero(β)\n cutensorPermutation(handle(), T[α], A, descA, modeA, C, descC, modeC,\n typeCompute, stream)\n else\n cutensorElementwiseBinary(handle(), T[α], A, descA, modeA, T[β], C, descC,\n modeC, C, descC, modeC, opAC, typeCompute, stream)\n end\n\n return C\nend\n\n# TODO: the following seems broken due to bug in CUTENSOR?#\n# function add!(α, A::CuArray{T, N}, CA::Symbol,\n# β, C::CuArray{Complex{T}, N}, indCinA) where {T<:CublasReal,N}\n#\n# N == length(indCinA) || throw(IndexError(\"Invalid permutation of length $N: $indCinA\"))\n# CA == :N || CA == :C ||\n# throw(ArgumentError(\"Value of conjA should be :N or :C instead of $CA\"))\n# opid = CUTENSOR_OP_IDENTITY\n# opAC = CUTENSOR_OP_ADD\n#\n# if β == zero(β)\n# fill!(C, zero(Complex{T}))\n# elseif β != one(β)\n# rmul!(C, β)\n# end\n# sizeC = size(C)\n# stridesC = 2 .* strides(C)\n# Cr = reinterpret(T, C, (2*length(C),))\n#\n# @show stridesC, sizeC\n#\n# descA = CuTensorDescriptor(A; op = opid)\n# descCr = CuTensorDescriptor(Cr; size = sizeC, strides = stridesC, op = opid)\n# typeCompute = cudaDataType(T)\n# modeA = collect(Cint, 1:N)\n# modeC = collect(Cint, indCinA)\n# stream = CuDefaultStream()\n# cutensorElementwiseBinary(handle(), T[real(α)], A, descA, modeA, T[1], Cr, descCr,\n# modeC, Cr, descCr, modeC, opAC, typeCompute, stream)\n# if imag(α) != 0\n# Ci = view(Cr, 2:length(Cr))\n# descCi = CuTensorDescriptor(Ci; size = sizeC, strides = stridesC, op = opid)\n# cutensorElementwiseBinary(handle(), T[imag(α)], A, descA, modeA, T[1], Ci, descCi,\n# modeC, Ci, descCi, modeC, opAC, typeCompute, stream)\n# end\n# return C\n# end\n\nfunction trace!(α, A::CuArray, CA::Symbol, β, C::CuArray,\n indCinA, cindA1, cindA2)\n\n T = eltype(C)\n NA, NC = ndims(A), ndims(C)\n NC == length(indCinA) ||\n throw(IndexError(\"Invalid selection of $NC out of $NA: $indCinA\"))\n NA-NC == 2*length(cindA1) == 2*length(cindA2) ||\n throw(IndexError(\"invalid number of trace dimension\"))\n\n opA = (T <: Real || CA == :N) ? CUTENSOR_OP_IDENTITY : CUTENSOR_OP_CONJ\n opReduce = CUTENSOR_OP_ADD\n\n sizeA = i->size(A, i)\n strideA = i->stride(A, i)\n tracesize = sizeA.(cindA1)\n tracesize == sizeA.(cindA2) || throw(DimensionMismatch(\"non-matching trace sizes\"))\n size(C) == sizeA.(indCinA) || throw(DimensionMismatch(\"non-matching sizes\"))\n\n newstrides = (strideA.(indCinA)..., (strideA.(cindA1) .+ strideA.(cindA2))...)\n newsize = (size(C)..., tracesize...)\n descA = CuTensorDescriptor(A; op = opA, size = newsize, strides = newstrides)\n descC = CuTensorDescriptor(C; op = CUTENSOR_OP_IDENTITY)\n descD = descC\n typeCompute = cutensorComputeType(T)\n modeA = collect(Cint, 1:NA)\n modeC = collect(Cint, 1:NC)\n stream = CuDefaultStream()\n @workspace fallback=1<<13 size=@argout(\n cutensorReductionGetWorkspace(handle(),\n A, descA, modeA,\n C, descC, modeC,\n C, descC, modeC,\n opReduce, typeCompute,\n out(Ref{UInt64}(C_NULL)))\n )[] workspace->begin\n cutensorReduction(handle(),\n T[α], A, descA, modeA,\n T[β], C, descC, modeC,\n C, descC, modeC,\n opReduce, typeCompute,\n workspace, sizeof(workspace), stream)\n end\n return C\nend\n\nfunction contract!(α, A::CuArray, CA::Symbol,\n B::CuArray, CB::Symbol,\n β, C::CuArray,\n oindA::IndexTuple, cindA::IndexTuple,\n oindB::IndexTuple, cindB::IndexTuple,\n indCinoAB::IndexTuple, syms::Union{Nothing, NTuple{3,Symbol}} = nothing)\n\n pA = (oindA...,cindA...)\n (length(pA) == ndims(A) && isperm(pA)) ||\n throw(IndexError(\"invalid permutation of length $(ndims(A)): $pA\"))\n pB = (oindB...,cindB...)\n (length(pB) == ndims(B) && isperm(pB)) ||\n throw(IndexError(\"invalid permutation of length $(ndims(B)): $pB\"))\n (length(oindA) + length(oindB) == ndims(C)) ||\n throw(IndexError(\"non-matching output indices in contraction\"))\n (ndims(C) == length(indCinoAB) && isperm(indCinoAB)) ||\n throw(IndexError(\"invalid permutation of length $(ndims(C)): $indCinoAB\"))\n\n sizeA = i->size(A, i)\n sizeB = i->size(B, i)\n sizeC = i->size(C, i)\n\n csizeA = sizeA.(cindA)\n csizeB = sizeB.(cindB)\n osizeA = sizeA.(oindA)\n osizeB = sizeB.(oindB)\n\n csizeA == csizeB ||\n throw(DimensionMismatch(\"non-matching sizes in contracted dimensions\"))\n sizeAB = let osize = (osizeA..., osizeB...)\n i->osize[i]\n end\n sizeAB.(indCinoAB) == size(C) ||\n throw(DimensionMismatch(\"non-matching sizes in uncontracted dimensions\"))\n\n TC = eltype(C)\n\n CA == :N || CA == :C ||\n throw(ArgumentError(\"Value of conjA should be :N or :C instead of $CA\"))\n CB == :N || CB == :C ||\n throw(ArgumentError(\"Value of conjB should be :N or :C instead of $CB\"))\n\n opA = (TC <: Real || CA == :N) ? CUTENSOR_OP_IDENTITY : CUTENSOR_OP_CONJ\n opB = (TC <: Real || CB == :N) ? CUTENSOR_OP_IDENTITY : CUTENSOR_OP_CONJ\n opC = CUTENSOR_OP_IDENTITY\n\n strideA = i->stride(A, i)\n strideB = i->stride(B, i)\n\n cstrideA = strideA.(cindA)\n cstrideB = strideB.(cindB)\n ostrideA = strideA.(oindA)\n ostrideB = strideB.(oindB)\n\n descA = CuTensorDescriptor(A; op = opA, size = (osizeA..., csizeA...),\n strides = (ostrideA..., cstrideA...))\n descB = CuTensorDescriptor(B; op = opB, size = (osizeB..., csizeB...),\n strides = (ostrideB..., cstrideB...))\n descC = CuTensorDescriptor(C)\n T = eltype(C)\n typeCompute = cutensorComputeType(T)\n opOut = CUTENSOR_OP_IDENTITY\n\n NoA = length(osizeA)\n NoB = length(osizeB)\n Nc = length(csizeA)\n modeoA = ntuple(n->n, NoA)\n modeoB = ntuple(n->NoA+n, NoB)\n modec = ntuple(n->NoA+NoB+n, Nc)\n\n modeA = collect(Cint, (modeoA..., modec...))\n modeB = collect(Cint, (modeoB..., modec...))\n modeC = collect(Cint, indCinoAB)\n\n algo = CUTENSOR_ALGO_DEFAULT\n stream = CuDefaultStream()\n pref = CUTENSOR_WORKSPACE_RECOMMENDED\n\n alignmentRequirementA = Ref{UInt32}(C_NULL)\n cutensorGetAlignmentRequirement(handle(), A, descA, alignmentRequirementA)\n alignmentRequirementB = Ref{UInt32}(C_NULL)\n cutensorGetAlignmentRequirement(handle(), B, descB, alignmentRequirementB)\n alignmentRequirementC = Ref{UInt32}(C_NULL)\n cutensorGetAlignmentRequirement(handle(), C, descC, alignmentRequirementC)\n desc = Ref{cutensorContractionDescriptor_t}()\n cutensorInitContractionDescriptor(handle(),\n desc,\n descA, modeA, alignmentRequirementA[],\n descB, modeB, alignmentRequirementB[],\n descC, modeC, alignmentRequirementC[],\n descC, modeC, alignmentRequirementC[],\n typeCompute)\n\n find = Ref{cutensorContractionFind_t}()\n cutensorInitContractionFind(handle(), find, algo)\n\n @workspace fallback=1<<27 size=@argout(\n cutensorContractionGetWorkspace(handle(), desc, find, pref,\n out(Ref{UInt64}(C_NULL)))\n )[] workspace->begin\n plan_ref = Ref{cutensorContractionPlan_t}()\n cutensorInitContractionPlan(handle(), plan_ref, desc, find, sizeof(workspace))\n\n cutensorContraction(handle(), plan_ref, T[α], A, B, T[β], C, C,\n workspace, sizeof(workspace), stream)\n end\n\n return C\nend\n\n# overwrite similar_from_indices to return zero initialized arrays\nfunction similar_from_indices(T::Type, ind::IndexTuple, A::CuArray, CA::Symbol)\n sz = similarstructure_from_indices(T, ind, A, CA)\n return fill!(similar(A, T, sz), zero(T))\nend\nfunction similar_from_indices(T::Type, poA::IndexTuple, poB::IndexTuple,\n p1::IndexTuple, p2::IndexTuple,\n A::CuArray, B::CuArray, CA::Symbol, CB::Symbol)\n sz = similarstructure_from_indices(T, poA, poB, p1, p2, A, B, CA, CB)\n return fill!(similar(A, T, sz), zero(T))\nend\n\n# overwrite cached_similar_from_indices in order not to use cache for CuArray objects\nfunction cached_similar_from_indices(sym::Symbol, T::Type, p1::IndexTuple, p2::IndexTuple, A::CuArray, CA::Symbol)\n # also zero fill to avoid problems with cutensorElementwiseBinary\n return similar_from_indices(T, p1, p2, A, CA)\nend\n\nfunction cached_similar_from_indices(sym::Symbol, T::Type, poA::IndexTuple, poB::IndexTuple,\n p1::IndexTuple, p2::IndexTuple, A::CuArray, B::CuArray, CA::Symbol, CB::Symbol)\n # also zero fill to avoid problems with cutensorElementwiseBinary\n return similar_from_indices(T, poA, poB, p1, p2, A, B, CA, CB)\nend\n", "meta": {"hexsha": "52a99a9c44a5943cb3c5b27f0108dc4f4e12439a", "size": 10003, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/implementation/cuarray.jl", "max_stars_repo_name": "achuchmala/TensorOperations.jl", "max_stars_repo_head_hexsha": "7d25eb9a5620514e6bbe36d28f4b8d665e7193d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/implementation/cuarray.jl", "max_issues_repo_name": "achuchmala/TensorOperations.jl", "max_issues_repo_head_hexsha": "7d25eb9a5620514e6bbe36d28f4b8d665e7193d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/implementation/cuarray.jl", "max_forks_repo_name": "achuchmala/TensorOperations.jl", "max_forks_repo_head_hexsha": "7d25eb9a5620514e6bbe36d28f4b8d665e7193d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5375494071, "max_line_length": 114, "alphanum_fraction": 0.5990202939, "num_tokens": 2940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24896579559260787}} {"text": "using KernelAbstractions\nusing Oceananigans.Utils\nusing Oceananigans.Architectures: device, @hascuda, CPU, GPU, array_type\nusing Oceananigans.Fields: datatuple\nusing Oceananigans.BoundaryConditions: apply_x_bcs!, apply_y_bcs!, apply_z_bcs!\n\n@kernel function update_total_density!(total_density, grid, gases, tracers)\n i, j, k = @index(Global, NTuple)\n\n @inbounds total_density[i, j, k] = diagnose_density(i, j, k, grid, gases, tracers)\nend\n\n# This is for users. Do not use in time_stepping.jl as it doesn't make use of intermediate fields.\nfunction update_total_density!(model)\n\n density_update_event =\n launch!(model.architecture, model.grid, :xyz, update_total_density!,\n datatuple(model.total_density), model.grid, model.gases, datatuple(model.tracers),\n dependencies=Event(device(model.architecture)))\n\n wait(device(model.architecture), density_update_event)\n\n return nothing\nend\n\n#####\n##### Computing slow source terms (viscous dissipation, diffusion, and Coriolis terms).\n#####\n\nfunction compute_slow_source_terms!(slow_source_terms, arch, grid, thermodynamic_variable, gases, gravity, coriolis, closure, total_density, momenta, tracers, diffusivities, forcing, clock)\n\n slow_source_terms, total_density, momenta, tracers, diffusivities =\n datatuples(slow_source_terms, total_density, momenta, tracers, diffusivities)\n\n workgroup, worksize = work_layout(grid, :xyz)\n barrier = Event(device(arch))\n\n momentum_kernel! = compute_slow_momentum_source_terms!(device(arch), workgroup, worksize)\n tracer_kernel! = compute_slow_tracer_source_terms!(device(arch), workgroup, worksize)\n thermodynamic_variable_kernel! = compute_slow_thermodynamic_variable_source_terms!(device(arch), workgroup, worksize)\n\n momentum_event = momentum_kernel!(slow_source_terms, grid, coriolis, closure, total_density, momenta, tracers, diffusivities, forcing, clock, dependencies=barrier)\n\n events = [momentum_event]\n\n for (tracer_index, ρc_name) in enumerate(propertynames(tracers))\n ρc = getproperty(tracers, ρc_name)\n S_ρc = getproperty(slow_source_terms.tracers, ρc_name)\n forcing_ρc = getproperty(forcing, ρc_name)\n\n tracer_event = tracer_kernel!(S_ρc, grid, closure, tracer_index, total_density, ρc, momenta, tracers, diffusivities, forcing_ρc, clock, dependencies=barrier)\n push!(events, tracer_event)\n end\n\n thermodynamic_variable_event = thermodynamic_variable_kernel!(slow_source_terms.tracers[1], grid, thermodynamic_variable, gases, gravity, closure, total_density, momenta, tracers, diffusivities, dependencies=barrier)\n push!(events, thermodynamic_variable_event)\n\n wait(device(arch), MultiEvent(Tuple(events)))\n\n return nothing\nend\n\n@kernel function compute_slow_momentum_source_terms!(slow_source_terms, grid, coriolis, closure, total_density, momenta, tracers, diffusivities, forcing, clock)\n i, j, k = @index(Global, NTuple)\n\n @inbounds slow_source_terms.ρu[i, j, k] = ρu_slow_source_term(i, j, k, grid, coriolis, closure, total_density, momenta, diffusivities) + forcing.ρu(i, j, k, grid, clock, merge(momenta, tracers))\n @inbounds slow_source_terms.ρv[i, j, k] = ρv_slow_source_term(i, j, k, grid, coriolis, closure, total_density, momenta, diffusivities) + forcing.ρv(i, j, k, grid, clock, merge(momenta, tracers))\n @inbounds slow_source_terms.ρw[i, j, k] = ρw_slow_source_term(i, j, k, grid, coriolis, closure, total_density, momenta, diffusivities) + forcing.ρw(i, j, k, grid, clock, merge(momenta, tracers))\nend\n\n@kernel function compute_slow_tracer_source_terms!(S_ρc, grid, closure, tracer_index, total_density, ρc, momenta, tracers, diffusivities, forcing, clock)\n i, j, k = @index(Global, NTuple)\n\n @inbounds S_ρc[i, j, k] = ρc_slow_source_term(i, j, k, grid, closure, tracer_index, total_density, ρc, diffusivities) + forcing(i, j, k, grid, clock, merge(momenta, tracers))\nend\n\n@kernel function compute_slow_thermodynamic_variable_source_terms!(S_ρt, grid, thermodynamic_variable, gases, gravity, closure, total_density, momenta, tracers, diffusivities)\n i, j, k = @index(Global, NTuple)\n\n @inbounds S_ρt[i, j, k] += ρt_slow_source_term(i, j, k, grid, closure, thermodynamic_variable, gases, gravity, total_density, momenta, tracers, diffusivities)\nend\n\n#####\n##### Computing fast source terms (advection, pressure gradient, and buoyancy terms).\n#####\n\nfunction compute_fast_source_terms!(fast_source_terms, arch, grid, thermodynamic_variable, gases, gravity, advection_scheme, total_density, momenta, tracers, slow_source_terms)\n\n fast_source_terms, total_density, momenta, tracers, slow_source_terms =\n datatuples(fast_source_terms, total_density, momenta, tracers, slow_source_terms)\n\n workgroup, worksize = work_layout(grid, :xyz)\n barrier = Event(device(arch))\n\n momentum_kernel! = compute_fast_momentum_source_terms!(device(arch), workgroup, worksize)\n tracer_kernel! = compute_fast_tracer_source_terms!(device(arch), workgroup, worksize)\n thermodynamic_variable_kernel! = compute_fast_thermodynamic_variable_source_terms!(device(arch), workgroup, worksize)\n\n momentum_event = momentum_kernel!(fast_source_terms, grid, thermodynamic_variable, gases, gravity, advection_scheme, total_density, momenta, tracers, slow_source_terms, dependencies=barrier)\n\n events = [momentum_event]\n\n for ρc_name in propertynames(tracers)\n ρc = getproperty(tracers, ρc_name)\n F_ρc = getproperty(fast_source_terms.tracers, ρc_name)\n S_ρc = getproperty(slow_source_terms.tracers, ρc_name)\n\n tracer_event = tracer_kernel!(F_ρc, grid, advection_scheme, total_density, momenta, ρc, S_ρc, dependencies=barrier)\n push!(events, tracer_event)\n end\n \n thermodynamic_variable_event = thermodynamic_variable_kernel!(fast_source_terms.tracers[1], grid, thermodynamic_variable, gases, gravity, total_density, momenta, tracers, dependencies=barrier)\n push!(events, thermodynamic_variable_event)\n\n wait(device(arch), MultiEvent(Tuple(events)))\n\n return nothing\nend\n\n@kernel function compute_fast_momentum_source_terms!(fast_source_terms, grid, thermodynamic_variable, gases, gravity, advection_scheme, total_density, momenta, tracers, slow_source_terms)\n i, j, k = @index(Global, NTuple)\n\n @inbounds fast_source_terms.ρu[i, j, k] = ρu_fast_source_term(i, j, k, grid, thermodynamic_variable, gases, gravity, advection_scheme, total_density, momenta, tracers, slow_source_terms.ρu)\n @inbounds fast_source_terms.ρv[i, j, k] = ρv_fast_source_term(i, j, k, grid, thermodynamic_variable, gases, gravity, advection_scheme, total_density, momenta, tracers, slow_source_terms.ρv)\n @inbounds fast_source_terms.ρw[i, j, k] = ρw_fast_source_term(i, j, k, grid, thermodynamic_variable, gases, gravity, advection_scheme, total_density, momenta, tracers, slow_source_terms.ρw)\nend\n\n@kernel function compute_fast_tracer_source_terms!(F_ρc, grid, advection_scheme, total_density, momenta, ρc, S_ρc)\n i, j, k = @index(Global, NTuple)\n\n @inbounds F_ρc[i, j, k] = ρc_fast_source_term(i, j, k, grid, advection_scheme, total_density, momenta, ρc, S_ρc)\nend\n\n@kernel function compute_fast_thermodynamic_variable_source_terms!(F_ρt, grid, thermodynamic_variable, gases, gravity, total_density, momenta, tracers)\n i, j, k = @index(Global, NTuple)\n\n @inbounds F_ρt[i, j, k] += ρt_fast_source_term(i, j, k, grid, thermodynamic_variable, gases, gravity, total_density, momenta, tracers)\nend\n\n#####\n##### Calculating boundary tendency contributions\n#####\n\nfunction calculate_boundary_tendency_contributions!(source_terms, arch, momenta, tracers, clock, model_fields)\n\n barrier = Event(device(arch))\n\n events = []\n\n # Momentum fields\n momentum_source_terms = (source_terms.ρu, source_terms.ρv, source_terms.ρw)\n\n for (ρϕ_source_term, ρϕ) in zip(momentum_source_terms, momenta)\n x_bcs_event = apply_x_bcs!(ρϕ_source_term, ρϕ, arch, barrier, clock, model_fields)\n y_bcs_event = apply_y_bcs!(ρϕ_source_term, ρϕ, arch, barrier, clock, model_fields)\n z_bcs_event = apply_z_bcs!(ρϕ_source_term, ρϕ, arch, barrier, clock, model_fields)\n\n push!(events, x_bcs_event, y_bcs_event, z_bcs_event)\n end\n\n # Tracer fields\n for (ρϕ_source_term, ρϕ) in zip(source_terms.tracers, tracers)\n x_bcs_event = apply_x_bcs!(ρϕ_source_term, ρϕ, arch, barrier, clock, model_fields)\n y_bcs_event = apply_y_bcs!(ρϕ_source_term, ρϕ, arch, barrier, clock, model_fields)\n z_bcs_event = apply_z_bcs!(ρϕ_source_term, ρϕ, arch, barrier, clock, model_fields)\n\n push!(events, x_bcs_event, y_bcs_event, z_bcs_event)\n end\n\n events = filter(e -> typeof(e) <: Event, events)\n\n wait(device(arch), MultiEvent(Tuple(events)))\n\n return nothing\nend\n\n#####\n##### Advancing state variables\n#####\n\nfunction advance_state_variables!(state_variables, arch, grid, momenta, tracers, fast_source_terms; Δt)\n \n state_variables, momenta, tracers, fast_source_terms =\n datatuples(state_variables, momenta, tracers, fast_source_terms )\n\n workgroup, worksize = work_layout(grid, :xyz)\n barrier = Event(device(arch))\n\n momentum_kernel! = advance_momentum!(device(arch), workgroup, worksize)\n tracer_kernel! = advance_tracer!(device(arch), workgroup, worksize)\n\n momentum_event = momentum_kernel!(state_variables, grid, momenta, fast_source_terms, Δt, dependencies=barrier)\n\n events = [momentum_event]\n\n for ρc_name in propertynames(tracers)\n ρc = getproperty(tracers, ρc_name)\n ρc⁺ = getproperty(state_variables.tracers, ρc_name)\n F_ρc = getproperty(fast_source_terms.tracers, ρc_name)\n \n tracer_event = tracer_kernel!(ρc⁺, grid, ρc, F_ρc, Δt, dependencies=barrier)\n push!(events, tracer_event)\n end\n\n wait(device(arch), MultiEvent(Tuple(events)))\n\n return nothing\nend\n\n@kernel function advance_momentum!(momenta⁺, grid, momenta, fast_source_terms, Δt)\n i, j, k = @index(Global, NTuple)\n\n @inbounds momenta⁺.ρu[i, j, k] = momenta.ρu[i, j, k] + Δt * fast_source_terms.ρu[i, j, k]\n @inbounds momenta⁺.ρv[i, j, k] = momenta.ρv[i, j, k] + Δt * fast_source_terms.ρv[i, j, k]\n @inbounds momenta⁺.ρw[i, j, k] = momenta.ρw[i, j, k] + Δt * fast_source_terms.ρw[i, j, k]\nend\n\n@kernel function advance_tracer!(ρc⁺, grid, ρc, F_ρc, Δt)\n i, j, k = @index(Global, NTuple)\n\n @inbounds ρc⁺[i, j, k] = ρc[i, j, k] + Δt * F_ρc[i, j, k]\nend\n", "meta": {"hexsha": "0feae32817943813d638be484a7181aabae5dd55", "size": 10483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/time_stepping_kernels.jl", "max_stars_repo_name": "ali-ramadhan/Atmosfoolery.jl", "max_stars_repo_head_hexsha": "194d950d67756d09848dfca86ef38457ca30ba9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-17T01:03:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-16T19:11:42.000Z", "max_issues_repo_path": "src/time_stepping_kernels.jl", "max_issues_repo_name": "thabbott/JULES.jl", "max_issues_repo_head_hexsha": "194d950d67756d09848dfca86ef38457ca30ba9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 75, "max_issues_repo_issues_event_min_datetime": "2019-06-20T18:02:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-30T13:25:07.000Z", "max_forks_repo_path": "src/time_stepping_kernels.jl", "max_forks_repo_name": "ali-ramadhan/Atmosfoolery.jl", "max_forks_repo_head_hexsha": "194d950d67756d09848dfca86ef38457ca30ba9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.0089686099, "max_line_length": 220, "alphanum_fraction": 0.7427263188, "num_tokens": 2985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24896264174489585}} {"text": "export DenseConvDims\n\n\"\"\"\n DenseConvDims\n\nConcrete subclass of `ConvDims` for a normal, dense, conv2d/conv3d.\n\"\"\"\nstruct DenseConvDims{N, K, S, P, D} <: ConvDims{N}\n input_size::NTuple{N, Int}\n\n kernel_size::NTuple{K, Int}\n channels_in::Int\n channels_out::Int\n groupcount::Int\n\n stride::NTuple{S, Int}\n padding::NTuple{P, Int}\n dilation::NTuple{D, Int}\n flipkernel::Bool\nend\n\nfunction DenseConvDims(\n x_size::NTuple{M}, w_size::NTuple{M};\n stride = 1, padding = 0, dilation = 1, groups = 1,\n flipkernel::Bool = false,\n) where {M}\n sstride, ppadding, ddilation = check_spdf(\n x_size, w_size, stride, padding, dilation)\n\n # Ensure channels are equal\n if x_size[end - 1] != w_size[end - 1] * groups\n xs = x_size[end - 1]\n ws = w_size[end - 1]\n throw(DimensionMismatch(\"Input channels must match! ($xs vs. $ws)\"))\n end\n\n # Ensure groups are valid\n if x_size[end - 1] % w_size[end - 1] != 0 || w_size[end] % groups != 0\n throw(DimensionMismatch(\n \"Group count should be divisble by input and output channels ($groups vs. $(w_size[end-1:end]))\"))\n end\n\n DenseConvDims(\n x_size[1:(end - 2)],\n w_size[1:(end - 2)], x_size[end - 1], w_size[end], groups,\n sstride, ppadding, ddilation, flipkernel)\nend\n\nfunction DenseConvDims(x::AbstractArray, w::AbstractArray; kwargs...)\n if ndims(x) != ndims(w)\n throw(DimensionMismatch(\n \"Rank of x and w must match! ($(ndims(x)) vs. $(ndims(w)))\"))\n end\n return DenseConvDims(size(x), size(w); kwargs...)\nend\n\n# Useful for constructing a new DenseConvDims that has only a few elements different\n# from the original progenitor object that it inherits shapes from.\n@inline DenseConvDims(\n c::C; I=input_size(c), K=kernel_size(c),\n C_in=channels_in(c), C_out=channels_out(c), S=stride(c),\n P=padding(c), D=dilation(c), F=flipkernel(c), G=groupcount(c),\n) where C <: ConvDims = DenseConvDims(\n I,\n K, C_in, C_out, G,\n S, P, D, F)\n\n@inline groupcount(c::DenseConvDims) = c.groupcount\n@inline channels_in(c::DenseConvDims) = c.channels_in\n@inline channels_out(c::DenseConvDims) = c.channels_out\n\n@inline input_size(c::DenseConvDims) = c.input_size\n@inline kernel_size(c::DenseConvDims) = c.kernel_size\n\n@inline stride(c::DenseConvDims) = c.stride\n@inline padding(c::DenseConvDims) = c.padding\n@inline dilation(c::DenseConvDims) = c.dilation\n@inline flipkernel(c::DenseConvDims) = c.flipkernel\n\nfunction check_dims(x::NTuple{M}, w::NTuple{M}, y::NTuple{M}, cdims::DenseConvDims) where {M}\n # First, check that channel counts are all correct:\n @assert x[M-1] * groupcount(cdims) == channels_in(cdims) DimensionMismatch(\"Data input channel count ($(x[M-1]) vs. $(channels_in(cdims)))\")\n @assert y[M-1] == channels_out(cdims) ÷ groupcount(cdims) DimensionMismatch(\"Data output channel count ($(y[M-1]) vs. $(channels_out(cdims)))\")\n @assert w[M-1] * groupcount(cdims) == channels_in(cdims) DimensionMismatch(\"Kernel input channel count ($(w[M-1]) vs. $(channels_in(cdims)))\")\n @assert w[M] * groupcount(cdims) == channels_out(cdims) DimensionMismatch(\"Kernel output channel count ($(w[M]) vs. $(channels_out(cdims)))\")\n\n # Next, check that the spatial dimensions match up\n @assert x[1:M-2] == input_size(cdims) DimensionMismatch(\"Data input spatial size ($(x[1:M-2]) vs. $(input_size(cdims)))\")\n @assert y[1:M-2] == output_size(cdims) DimensionMismatch(\"Data output spatial size ($(y[1:M-2]) vs. $(output_size(cdims)))\")\n @assert w[1:M-2] == kernel_size(cdims) DimensionMismatch(\"Kernel spatial size ($(w[1:M-2]) vs. $(kernel_size(cdims)))\")\n\n # Check the groups match\n @assert channels_in(cdims) % groupcount(cdims) == 0 DimensionMismatch(\"Groups ($(groupcount(cdims))) should be divisble by input channels $(channels_in(cdims))\")\n\n # Finally, check that the batch size matches\n @assert x[M] == y[M] DimensionMismatch(\"Batch size ($(x[M]) vs. $(y[M]))\")\nend\n", "meta": {"hexsha": "8ceda7abe60d110e8d3d44b003ab3da2f5f6cd31", "size": 3992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dim_helpers/DenseConvDims.jl", "max_stars_repo_name": "pxl-th/NNlib.jl", "max_stars_repo_head_hexsha": "8a63b9cab0403dbad0ae2d214e72ddf49b19196b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dim_helpers/DenseConvDims.jl", "max_issues_repo_name": "pxl-th/NNlib.jl", "max_issues_repo_head_hexsha": "8a63b9cab0403dbad0ae2d214e72ddf49b19196b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dim_helpers/DenseConvDims.jl", "max_forks_repo_name": "pxl-th/NNlib.jl", "max_forks_repo_head_hexsha": "8a63b9cab0403dbad0ae2d214e72ddf49b19196b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7346938776, "max_line_length": 165, "alphanum_fraction": 0.6675851703, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24886648650160897}} {"text": "function mcmc(setup_mcmc::MCMCSetup, schedule::MCMCSchedule, setups::Vector{T}) where T <: ModelSetup\n workspaces = [create_workspace(setup) for setup in setups]\n wss, lls = [ws[1] for ws in workspaces], [ws[2] for ws in workspaces]\n θ = workspaces[1][3]\n ws_mcmc = create_workspace(setup_mcmc, schedule, θ)\n # adpt = adaptation_object(setup, ws) # adaptive auxiliary law currently not supported\n\n aux = nothing\n for step in schedule\n step.save && [save_imputed!(ws) for ws in wss]\n for i in step.idx\n if step.param_updt || typeof(ws_mcmc.updates[i]) <: Imputation\n wss = [next(ws, ws_mcmc.updates[i]) for ws in wss]\n lls, acc, θ = update!(ws_mcmc.updates[i], wss, θ, lls, step, aux)\n aux = aux_params(ws_mcmc.updates[i], aux)\n #TODO: make it nicer, currently we need a little dance here\n dance = typeof(ws_mcmc.updates[i]) <: Imputation\n dance && begin\n update!(ws_mcmc, acc[1], θ, i)\n for k in 2:length(setups)\n register_accpt!(ws_mcmc.updates[i], acc[k])\n end\n end\n !dance && update!(ws_mcmc, acc, θ, i)\n step.verbose && print(\"\\n\")\n end\n end\n step.verbose && print(\"-----------------------------------------------\",\n \"------\\n\")\n step.readjust && readjust!(ws_mcmc, step.iter)\n step.fuse && fuse!(ws_mcmc, schedule)\n # ll = adaptation!(ws, adpt, step.iter, ll) adaptation currently not supported\n end\n [display_summary(ws, ws_mcmc) for ws in wss]\n wss, ws_mcmc\nend\n\nfunction update!(updt::Imputation{NoBlocking}, wss::Vector{<:Workspace{OS}}, θ,\n lls, step, ::Any, headstart=false) where OS\n ρ, K = updt.ρs[1], length(wss)\n accpts = repeat([false], K)\n\n for k in 1:K\n ws = wss[k]\n # sample proposal starting point\n zᵒ, yᵒ = proposal_start_pt(ws, ws.P[1], ρ)\n\n # sample proposal path\n m = length(ws.WWᵒ)\n success = sample_segments!(1:m, ws, yᵒ, ρ, Val{headstart}())\n llᵒ = success ? (logpdf(ws.x0_prior, yᵒ) +\n path_log_likhd(OS(), ws.XXᵒ, ws.P, 1:m, ws.fpt) +\n lobslikelihood(ws.P[1], yᵒ)) : -Inf\n\n print_info(step, value(lls[k]), value(llᵒ), \"impute\")\n\n if accept_sample(llᵒ-lls[k], step.verbose)\n swap!(ws.XX, ws.XXᵒ, ws.WW, ws.WWᵒ, 1:m)\n set!(ws.z, zᵒ)\n lls[k] = llᵒ\n accpts[k] = true\n end\n end\n lls, accpts, θ\nend\n\nfunction update!(pu::ParamUpdate{MetropolisHastingsUpdt},\n wss::Vector{<:Workspace{OS}}, θ, lls, step,\n blocking::NoBlocking) where OS\n K = length(wss)\n\n #NOTE for now, let's sample parameter corresponding to a single path, this\n # will need to be changed for Mixed effect models\n θᵒ = rand(pu.t_kernel, θ, pu.updt_coord) # sample new parameter\n (logpdf(pu.priors, θᵒ) === -Inf) && (return lls, false, θ)\n\n llᵒs = copy(lls)\n zᵒs = [copy(ws.z.val) for ws in wss]\n for k in 1:K\n ws = wss[k]\n WW, Pᵒ, P, XXᵒ, XX, fpt = ws.WW, ws.Pᵒ, ws.P, ws.XXᵒ, ws.XX, ws.fpt\n m = length(WW)\n update_laws!(Pᵒ, θᵒ)\n pu.aux.recompute_ODEs && solve_back_rec!(blocking, pu.aux.solver, Pᵒ) # compute (H, Hν, c)\n\n # find white noise which for a given θᵒ gives a correct starting point\n y = XX[1].yy[1]\n zᵒs[k] = inv_start_pt(y, ws.x0_prior, Pᵒ[1])\n\n success = find_path_from_wiener!(XXᵒ, y, WW, Pᵒ, 1:m)\n\n llᵒs[k] = success ? (logpdf(ws.x0_prior, y) +\n path_log_likhd(OS(), XXᵒ, Pᵒ, 1:m, fpt) +\n lobslikelihood(Pᵒ[1], y)) : -Inf\n end\n ll, llᵒ = sum(lls), sum(llᵒs)\n print_info(step, value(ll), value(llᵒ))\n\n llr = ( llᵒ - ll + prior_kernel_contrib(pu, θ, θᵒ))\n\n # Accept / reject\n if accept_sample(llr, step.verbose)\n for k in 1:K\n ws = wss[k]\n WW, Pᵒ, P, XXᵒ, XX, fpt = ws.WW, ws.Pᵒ, ws.P, ws.XXᵒ, ws.XX, ws.fpt\n m = length(WW)\n swap!(XX, XXᵒ, P, Pᵒ, 1:m)\n set!(ws.z, zᵒs[k])\n end\n return llᵒs, true, θᵒ\n else\n return lls, false, θ\n end\nend\n\n\nfunction update!(pu::ParamUpdate{ConjugateUpdt}, wss::Vector{<:Workspace{OS}},\n θ, lls, step, blocking::NoBlocking) where OS\n K = length(wss)\n\n θᵒ = conjugate_draw(θ, [ws.XX for ws in wss], wss[1].P[1].Target, pu.priors[1], pu.updt_coord)\n\n total_ll_old = sum(lls)\n for k in 1:K\n ws = wss[k]\n WW, P, XX, fpt = ws.WW, ws.P, ws.XX, ws.fpt\n m = length(WW)\n\n update_laws!(P, θᵒ)\n pu.aux.recompute_ODEs && solve_back_rec!(blocking, pu.aux.solver, P) # compute (H, Hν, c)\n\n for i in 1:m # compute wiener path WW that generates XX\n inv_solve!(EulerMaruyamaBounded(), XX[i], WW[i], P[i])\n end\n # compute white noise that generates starting point\n y = XX[1].yy[1]\n z = inv_start_pt(y, ws.x0_prior, P[1])\n\n llᵒ = logpdf(ws.x0_prior, y)\n llᵒ += path_log_likhd(OS(), XX, P, 1:m, fpt; skipFPT=true)\n llᵒ += lobslikelihood(P[1], y)\n lls[k] = llᵒ\n set!(ws.z, z)\n end\n print_info(step, sum(total_ll_old), sum(lls))\n return lls, true, θᵒ\nend\n\nfunction conjugate_draw(θ, XX::Vector{<:Vector}, PT, prior, updtIdx)\n μ = mustart(updtIdx)\n 𝓦 = μ*μ'\n ϑ = SVector(thetaex(updtIdx, θ))\n for X in XX\n μ, 𝓦 = _conjugate_draw(ϑ, μ, 𝓦, X, PT, updtIdx)\n end\n Σ = inv(𝓦 + inv(Matrix(prior.Σ)))\n Σ = (Σ + Σ')/2 # eliminates numerical inconsistencies\n μ_post = Σ * (μ + Vector(prior.Σ\\prior.μ))\n ϑ = rand(Gaussian(μ_post, Σ))\n move_to_proper_place(ϑ, θ, updtIdx) # align so that dimensions agree\nend\n", "meta": {"hexsha": "23abcaeb62a0e472dae24cc280446791d3659fef", "size": 5948, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mcmc/repeated.jl", "max_stars_repo_name": "mmider/BridgeSDEInference.jl", "max_stars_repo_head_hexsha": "c18dbe9c45bba9ef1d19e70deec8754df2c05293", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-07-25T15:29:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T16:02:39.000Z", "max_issues_repo_path": "src/mcmc/repeated.jl", "max_issues_repo_name": "mmider/BridgeSDEInference.jl", "max_issues_repo_head_hexsha": "c18dbe9c45bba9ef1d19e70deec8754df2c05293", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2019-07-23T19:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T12:03:33.000Z", "max_forks_repo_path": "src/mcmc/repeated.jl", "max_forks_repo_name": "mmider/FitzHughNagumo.jl", "max_forks_repo_head_hexsha": "c18dbe9c45bba9ef1d19e70deec8754df2c05293", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-08-03T20:48:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T22:39:08.000Z", "avg_line_length": 36.7160493827, "max_line_length": 101, "alphanum_fraction": 0.546402152, "num_tokens": 2033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24886648650160892}} {"text": "module Processing\nimport FFTW\nusing EllipsisNotation\nimport Glob: glob\nimport Luna: Maths, Fields, PhysData\nimport Luna.PhysData: wlfreq, c\nimport Luna.Grid: AbstractGrid, RealGrid, EnvGrid, from_dict\nimport Luna.Output: AbstractOutput, HDF5Output\n\n\"\"\"\n Common(val)\n\nWrapper type to tell `scanproc` that `val` is the same for each simulation being processed,\nand so only needs to be returned once rather than for each simulation in the scan.\n\"\"\"\nstruct Common{dT}\n data::dT\nend\n\n\"\"\"\n VarLength(val)\n\nWrapper type to tell `scanproc` that the shape of `val` is different for each simulation being\nprocessed. Return values wrapped in `VarLength` will be placed in an array of arrays.\n\n!!! note\n While the **shape** of `val` can be different between simulations, the **type** must be\n the same, including the dimensionality and element type of arrays.\n\"\"\"\nstruct VarLength{dT}\n data::dT\nend\n\n\"\"\"\n scanproc(f, scanfiles)\n scanproc(f, directory)\n scanproc(f, directory, pattern)\n scanproc(f)\n\nIterate over the scan output files, apply the processing function `f(o::AbstractOutput)`,\nand collect the results in arrays.\n\nThe files can be given as:\n\n- a `Vector` of `AbstractString`s containing file paths\n- a directory to search for files according to the naming pattern of\n `Output.ScanHDF5Output`\n- a directory and a `glob` pattern\n\nIf nothing is specified, `scanproc` uses the current working directory.\n\n`f` can return a single value, an array, or a tuple/array of arrays/numbers. Arrays returned\nby `f` must either be of the same size for each processed file, or wrapped in a `VarLength`.\nValues returned by `f` which are guaranteed to be identical for each processed file can be\nwrapped in a `Common`, and `scanproc` only returns these once.\n\n# Example\n```julia\nEt, Eω = scanproc(\"path/to/scandir\") do output\n t, Et = getEt(output)\n ω, Eω = getEω(output)\n energyout = energyout = Processing.VarLength(output[\"stats\"][\"energy\"])\n Common(t), Et, Common(ω), Eω, energyout\nend\n```\n\"\"\"\nfunction scanproc(f, scanfiles::AbstractVector{<:AbstractString}; shape=nothing)\n local scanidcs, arrays\n scanfiles = sort(scanfiles)\n for (idx, fi) in enumerate(scanfiles)\n o = HDF5Output(fi)\n # wraptuple makes sure we definitely have a Tuple, even if f only returns one thing\n ret = wraptuple(f(o))\n if idx == 1 # initialise arrays\n isnothing(shape) && (shape = Tuple(o[\"meta\"][\"scanshape\"]))\n scanidcs = CartesianIndices(shape)\n arrays = _arrays(ret, shape)\n end\n for (ridx, ri) in enumerate(ret)\n _addret!(arrays[ridx], scanidcs[idx], ri)\n end\n end\n unwraptuple(arrays) # if f only returns one thing, we also only return one array\nend\n\nwraptuple(x::Tuple) = x\nwraptuple(x) = (x,)\n\nunwraptuple(x::Tuple{<:Any}) = x[1] # single-element Tuple\nunwraptuple(x) = x\n\nfunction _addret!(array, aidcs, ri)\n array[aidcs] = ri\nend\n\nfunction _addret!(array, aidcs, ri::AbstractArray)\n idcs = CartesianIndices(ri)\n array[idcs, aidcs] .= ri\nend\n\nfunction _addret!(array, aidcs, ri::VarLength)\n array[aidcs] = ri.data\nend\n\n_addret!(array, aidcs, ri::Common) = nothing\n\n# Default pattern for files named by ScanHDF5Output is [name]_[scanidx].h5 with 5 digits\ndefpattern = \"*_[0-9][0-9][0-9][0-9][0-9].h5\"\n\nfunction scanproc(f, directory::AbstractString=pwd(), pattern::AbstractString=defpattern;\n shape=nothing)\n scanfiles = glob(pattern, directory) # this returns absolute paths if directory given\n scanproc(f, scanfiles; shape=shape)\nend\n\n# Make array(s) with correct size to hold processing results\n_arrays(ret, shape) = Array{typeof(ret)}(undef, shape)\n_arrays(ret::AbstractArray, shape) = zeros(eltype(ret), (size(ret)..., shape...))\n_arrays(ret::Tuple, shape) = Tuple([_arrays(ri, shape) for ri in ret])\n_arrays(com::Common, shape) = com.data\n_arrays(vl::VarLength, shape) = Array{typeof(vl.data), length(shape)}(undef, shape)\n\n\"\"\"\n coherence(Eω; ndim=1)\n\nCalculate the first-order coherence function g₁₂ of the set of fields `Eω`. The ensemble\naverage is taken over the last `ndim` dimensions of `Eω`, other dimensions are preserved.\n\nSee J. M. Dudley and S. Coen, Optics Letters 27, 1180 (2002).\n\"\"\"\nfunction coherence(Eω; ndim=1)\n dimsize = size(Eω)[end-ndim+1:end]\n outsize = size(Eω)[1:end-ndim]\n prodidcs = CartesianIndices(dimsize)\n restidcs = CartesianIndices(outsize)\n coherence(Eω, prodidcs, restidcs)\nend\n\n# function barrier for speedup\nfunction coherence(Eω, prodidcs, restidcs)\n num = zeros(ComplexF64, size(restidcs))\n den1 = zeros(ComplexF64, size(restidcs))\n den2 = zeros(ComplexF64, size(restidcs))\n it = Iterators.product(prodidcs, prodidcs)\n for (idx1, idx2) in it\n Eω1 = Eω[restidcs, idx1]\n Eω2 = Eω[restidcs, idx2]\n @. num += conj(Eω1)*Eω2\n @. den1 += abs2(Eω1)\n @. den2 += abs2(Eω2)\n end\n @. abs(num/sqrt(den1*den2))\nend\n\n\"\"\"\n arrivaltime(grid, Eω; bandpass=nothing, method=:moment, oversampling=1)\n\nExtract the arrival time of the pulse in the wavelength limits `λlims`.\n\n# Arguments\n- `bandpass` : method to bandpass the field if required. See [`window_maybe`](@ref)\n- `method::Symbol` : `:moment` to use 1st moment to extract arrival time, `:peak` to use\n the time of peak power\n- `oversampling::Int` : If >1, oversample the time-domain field before extracting delay\n- `sumdims` : Single `Int` or `Tuple` of `Int`s. The time-domain power will be summed over\n these dimensions (e.g. modes) before extracting the arrival time.\n\"\"\"\nfunction arrivaltime(grid::AbstractGrid, Eω;\n bandpass=nothing, method=:moment, oversampling=1, sumdims=nothing)\n to, Eto = getEt(grid, Eω; oversampling=oversampling, bandpass=bandpass)\n Pt = abs2.(Eto)\n if !isnothing(sumdims)\n Pt = dropdims(sum(Pt; dims=sumdims); dims=sumdims)\n end\n arrivaltime(to, Pt; method=method)\nend\n\nfunction arrivaltime(t::AbstractVector, It::AbstractVector; method)\n if method == :moment\n Maths.moment(t, It)\n elseif method == :peak\n t[argmax(It)]\n else\n error(\"Unknown arrival time method $method\")\n end\nend\n\nfunction arrivaltime(t::AbstractVector, It::AbstractArray; method)\n out = Array{Float64, ndims(It)-1}(undef, size(It)[2:end])\n cidcs = CartesianIndices(size(It)[2:end])\n for ii in cidcs\n out[ii] = arrivaltime(t, It[:, ii]; method=method)\n end\n out\nend\n\n\"\"\"\n time_bandwidth(grid, Eω; bandpass=nothing, oversampling=1)\n\nExtract the time-bandwidth product, after bandpassing if required. The TBP\nis defined here as ΔfΔt where Δx is the FWHM of x. (In this definition, the TBP of \na perfect Gaussian pulse is ≈0.44). If `oversampling` > 1, the time-domain field is\noversampled before extracting the FWHM.\n\"\"\"\nfunction time_bandwidth(grid, Eω; bandpass=nothing, oversampling=1, sumdims=nothing)\n fwt = fwhm_t(grid, Eω; bandpass=bandpass, oversampling=oversampling, sumdims=nothing)\n fwf = fwhm_f(grid, Eω; bandpass=bandpass)\n fwt.*fwf\nend\n\n\n\"\"\"\n fwhm_t(grid::AbstractGrid, Eω; bandpass=nothing, oversampling=1)\n\nExtract the temporal FWHM. If `bandpass` is given, bandpass the fieldaccording to\n[`window_maybe`](@ref). If `oversampling` > 1, the time-domain field is oversampled before\nextracting the FWHM. If `sumdims` is given, the time-domain power is summed over these\ndimensions (e.g. modes) before extracting the FWHM.\n\"\"\"\nfunction fwhm_t(grid::AbstractGrid, Eω; bandpass=nothing, oversampling=1, sumdims=nothing)\n to, Eto = getEt(grid, Eω; oversampling=oversampling, bandpass=bandpass)\n Pt = abs2.(Eto)\n if !isnothing(sumdims)\n Pt = dropdims(sum(Pt; dims=sumdims); dims=sumdims)\n end\n fwhm(to, Pt)\nend\n\nfunction fwhm_t(output::AbstractOutput; kwargs...)\n grid = makegrid(output)\n fwhm_t(grid, output[\"Eω\"]; kwargs...)\nend\n\n\n\"\"\"\n fwhm_f(grid, Eω::Vector; bandpass=nothing, oversampling=1)\n\nExtract the frequency FWHM. If `bandpass` is given, bandpass the field according to\n[`window_maybe`](@ref). If `sumdims` is given, the energy density is summed over these\ndimensions (e.g. modes) before extracting the FWHM. \n\"\"\"\nfunction fwhm_f(grid::AbstractGrid, Eω; bandpass=nothing, oversampling=1, sumdims=nothing)\n Eω = window_maybe(grid.ω, Eω, bandpass)\n f, If = getIω(getEω(grid, Eω)..., :f)\n if !isnothing(sumdims)\n If = dropdims(sum(If; dims=sumdims); dims=sumdims)\n end\n fwhm(f, If)\nend\n\n\nfunction fwhm(x, I)\n out = Array{Float64, ndims(I)-1}(undef, size(I)[2:end])\n cidcs = CartesianIndices(size(I)[2:end])\n for ii in cidcs\n out[ii] = fwhm(x, I[:, ii])\n end\n out\nend\n\nfwhm(x::Vector, I::Vector) = Maths.fwhm(x, I)\n\n\"\"\"\n peakpower(grid, Eω; bandpass=nothing, oversampling=1)\n\nExtract the peak power. If `bandpass` is given, bandpass the field according to\n[`window_maybe`](@ref).\n\"\"\"\nfunction peakpower(grid, Eω; bandpass=nothing, oversampling=1)\n to, Eto = getEt(grid, Eω; oversampling=oversampling, bandpass=bandpass)\n dropdims(maximum(abs2.(Eto); dims=1); dims=1)\nend\n\n\n\"\"\"\n energy(grid, Eω; bandpass=nothing)\n\nExtract energy. If `bandpass` is given, bandpass the field according to\n[`window_maybe`](@ref).\n\"\"\"\nfunction energy(grid, Eω; bandpass=nothing)\n Eω = window_maybe(grid.ω, Eω, bandpass)\n _, energyω = Fields.energyfuncs(grid)\n _energy(Eω, energyω)\nend\n\nfunction energy(output::AbstractOutput; bandpass=nothing)\n grid = makegrid(output)\n energy(grid, output[\"Eω\"]; bandpass=bandpass)\nend\n\n_energy(Eω::Vector, energyω) = energyω(Eω)\n\nfunction _energy(Eω, energyω)\n out = Array{Float64, ndims(Eω)-1}(undef, size(Eω)[2:end])\n cidcs = CartesianIndices(size(Eω)[2:end])\n for ii in cidcs\n out[ii] = _energy(Eω[:, ii], energyω)\n end\n out\nend\n\n\"\"\"\n field_autocorrelation(Et; dims=1)\n\nCalculate the field autocorrelation of `Et`.\n\"\"\"\nfunction field_autocorrelation(Et, grid::EnvGrid; dims=1)\n FFTW.fftshift(FFTW.ifft(abs2.(FFTW.fft(Et, dims)), dims), dims)\nend\n\nfunction field_autocorrelation(Et, grid::RealGrid; dims=1)\n fac = FFTW.fftshift(FFTW.irfft(abs2.(FFTW.rfft(Et, dims)), length(grid.t), dims), dims)\n Maths.hilbert(fac, dim=dims)\nend\n\n\"\"\"\n intensity_autocorrelation(Et, grid)\n\nCalculate the intensity autocorrelation of `Et` over `grid`.\n\"\"\"\nfunction intensity_autocorrelation(Et, grid; dims=1)\n real.(FFTW.fftshift(FFTW.irfft(abs2.(FFTW.rfft(Fields.It(Et, grid), dims)), length(grid.t), dims), dims))\nend\n\n\"\"\"\n coherence_time(grid, Et; dims=1)\n\nGet the coherence time of a field `Et` over `grid`.\n\"\"\"\nfunction coherence_time(grid, Et; dims=1)\n Maths.fwhm(grid.t, abs2.(field_autocorrelation(Et, grid, dims=dims)))\nend\n\n\"\"\"\n specres(ω, Iω, specaxis, resolution, specrange; window=nothing, nsamples=10)\n\nSmooth the spectral energy density `Iω(ω)` to account for the given `resolution`\non the defined `specaxis` and `specrange`. The `window` function to use defaults\nto a Gaussian function with FWHM of `resolution`, and by default we sample `nsamples=10`\ntimes within each `resolution`.\n\nNote that you should prefer the `resolution` keyword of [`getIω`](@ref) instead of calling\nthis function directly.\n\nThe input `ω` and `Iω` should be as returned by [`getIω`](@ref) with `specaxis = :ω`.\n\nReturns the new specaxis grid and smoothed spectrum.\n\"\"\"\nfunction specres(ω, Iω, specaxis, resolution, specrange; window=nothing, nsamples=10)\n if isnothing(window)\n window = let ng=Maths.gaussnorm(fwhm=resolution), σ=resolution/(2*(2*log(2))^(1/2))\n (x,x0) -> exp(-0.5*((x - x0)/σ)^2)/ng\n end\n end\n if specaxis == :λ\n xg, Ix = _specres(ω, Iω, resolution, specrange, window, nsamples, wlfreq, wlfreq)\n elseif specaxis == :f\n xg, Ix = _specres(ω, Iω, resolution, specrange, window, nsamples, x -> x/(2π), x -> x*(2π))\n else\n error(\"`specaxis` must be one of `:λ` or `:f`\")\n end\n xg, Ix\nend\n\nfunction _specres(ω, Iω, resolution, xrange, window, nsamples, ωtox, xtoω)\n # build output grid and array\n x = ωtox.(ω)\n fxrange = extrema(x[(x .> 0) .& isfinite.(x)])\n if isnothing(xrange)\n xrange = fxrange\n else\n xrange = extrema(xrange)\n xrange = (max(xrange[1], fxrange[1]), min(xrange[2], fxrange[2]))\n end\n nxg = ceil(Int, (xrange[2] - xrange[1])/resolution*nsamples)\n xg = collect(range(xrange[1], xrange[2], length=nxg))\n rdims = size(Iω)[2:end]\n Ix = Array{Float64, ndims(Iω)}(undef, ((nxg,)..., rdims...))\n fill!(Ix, 0.0)\n cidcs = CartesianIndices(rdims)\n # we find a suitable nspan\n nspan = 1\n while window(nspan*resolution, 0.0)/window(0.0, 0.0) > 1e-8\n nspan += 1\n end\n # now we build arrays of start and end indices for the relevant frequency\n # band for each output. For a frequency grid this is a little inefficient\n # but for a wavelength grid, which has varying index ranges, this is essential\n # and I think having a common code is simpler/cleaner.\n istart = Array{Int,1}(undef,nxg)\n iend = Array{Int,1}(undef,nxg)\n δω = ω[2] - ω[1]\n i0 = argmin(abs.(ω))\n ωs = ω[i0]\n for i in 1:nxg\n i1 = i0 + round(Int, (xtoω(xg[i] + resolution*nspan) - ωs)/δω)\n i2 = i0 + round(Int, (xtoω(xg[i] - resolution*nspan) - ωs)/δω)\n # we want increasing indices\n if i1 > i2\n i1,i2 = i2,i1\n end\n # handle boundaries\n if i2 > length(ω)\n i2 = length(ω)\n end\n if i1 < i0\n i1 = i0\n end\n istart[i] = i1\n iend[i] = i2\n end\n # run the convolution kernel - the function barrier massively improves performance\n _specres_kernel!(Ix, cidcs, istart, iend, Iω, window, x, xg, δω)\n xg, Ix\nend\n\n\"\"\"\nConvolution kernel for each output point. We simply loop over all outer indices\nand output points. The inner loop adds up the contributions from the specified window\naround the target point. Note that this works without scaling also for wavelength ranges\nbecause the integral is still over a frequency grid (with appropriate frequency dependent\nintegration bounds).\n\"\"\"\nfunction _specres_kernel!(Ix, cidcs, istart, iend, Iω, window, x, xg, δω)\n @inbounds @fastmath for ii in cidcs\n for j in 1:size(Ix, 1)\n for k in istart[j]:iend[j]\n Ix[j,ii] += Iω[k,ii] * window(x[k], xg[j]) * δω\n end\n end\n end\n Ix[Ix .<= 0.0] .= minimum(Ix[Ix .> 0.0])\nend\n\nfunction _specrangeselect(x, Ix; specrange=nothing, sortx=false)\n cidcs = CartesianIndices(size(Ix)[2:end])\n if !isnothing(specrange)\n specrange = extrema(specrange)\n idcs = ((x .>= specrange[1]) .& (x .<= specrange[2]))\n x = x[idcs]\n Ix = Ix[idcs, cidcs]\n end\n if sortx\n idcs = sortperm(x)\n x = x[idcs]\n Ix = Ix[idcs, cidcs]\n end\n x, Ix\nend\n\n\"\"\"\n ωwindow_λ(ω, λlims; winwidth=:auto)\n\nCreate a ω-axis filtering window to filter in `λlims`. `winwidth`, if a `Number`, sets\nthe smoothing width of the window in rad/s.\n\"\"\"\nfunction ωwindow_λ(ω, λlims; winwidth=:auto)\n ωmin, ωmax = extrema(wlfreq.(λlims))\n winwidth == :auto && (winwidth = 64*abs(ω[2] - ω[1]))\n window = Maths.planck_taper(ω, ωmin-winwidth, ωmin, ωmax, ωmax+winwidth)\nend\n\n\"\"\"\n getIω(ω, Eω, specaxis; specrange=nothing, resolution=nothing)\n\nGet spectral energy density and x-axis given a frequency array `ω` and frequency-domain field\n`Eω`, assumed to be correctly normalised (see [`getEω`](@ref)). `specaxis` determines the\nx-axis:\n\n- :f -> x-axis is frequency in Hz and Iω is in J/Hz\n- :ω -> x-axis is angular frequency in rad/s and Iω is in J/(rad/s)\n- :λ -> x-axis is wavelength in m and Iω is in J/m\n\n# Keyword arguments\n- `specrange::Tuple` can be set to a pair of limits on the spectral range (in `specaxis` units).\n- `resolution::Real` is set, smooth the spectral energy density as defined by [`specres`](@ref).\n\nNote that if `resolution` and `specaxis=:λ` is set it is highly recommended to also set `specrange`.\n\"\"\"\nfunction getIω(ω, Eω, specaxis; specrange=nothing, resolution=nothing)\n sortx = false\n if specaxis == :ω || !isnothing(resolution)\n specx = ω\n Ix = abs2.(Eω)\n if !isnothing(resolution)\n return specres(ω, Ix, specaxis, resolution, specrange)\n end\n elseif specaxis == :f\n specx = ω./2π\n Ix = abs2.(Eω)*2π\n elseif specaxis == :λ\n specx = wlfreq.(ω)\n Ix = @. ω^2/(2π*c) * abs2.(Eω)\n sortx = true\n else\n error(\"Unknown specaxis $specaxis\")\n end\n if !isnothing(specrange) || sortx\n specx, Ix = _specrangeselect(specx, Ix, specrange=specrange, sortx=sortx)\n end\n return specx, Ix\nend\n\n\"\"\"\n getIω(output, specaxis[, zslice]; kwargs...)\n\nCalculate the correctly normalised frequency-domain field and convert it to spectral\nenergy density on x-axis `specaxis` (`:f`, `:ω`, or `:λ`). If `zslice` is given,\nreturs only the slices of `Eω` closest to the given distances. `zslice` can be a single\nnumber or an array. `specaxis` determines the\nx-axis:\n\n- :f -> x-axis is frequency in Hz and Iω is in J/Hz\n- :ω -> x-axis is angular frequency in rad/s and Iω is in J/(rad/s)\n- :λ -> x-axis is wavelength in m and Iω is in J/m\n\n# Keyword arguments\n- `specrange::Tuple` can be set to a pair of limits on the spectral range (in `specaxis` units).\n- `resolution::Real` is set, smooth the spectral energy density as defined by [`specres`](@ref).\n\nNote that `resolution` is set and `specaxis=:λ` it is highly recommended to also set `specrange`.\n\"\"\"\ngetIω(output::AbstractOutput, specaxis; kwargs...) = getIω(getEω(output)..., specaxis; kwargs...)\n\nfunction getIω(output::AbstractOutput, specaxis, zslice; kwargs...)\n ω, Eω, zactual = getEω(output, zslice)\n specx, Iω = getIω(ω, Eω, specaxis; kwargs...)\n return specx, Iω, zactual\nend\n\n\"\"\"\n getEω(output[, zslice])\n\nGet frequency-domain modal field from `output` with correct normalisation (i.e. \n`abs2.(Eω)`` gives angular-frequency spectral energy density in J/(rad/s)).\n\"\"\"\ngetEω(output::AbstractOutput, args...) = getEω(makegrid(output), output, args...)\ngetEω(grid, output) = getEω(grid, output[\"Eω\"])\n\nfunction getEω(grid::RealGrid, Eω::AbstractArray)\n ω = grid.ω[grid.sidx]\n Eω = Eω[grid.sidx, CartesianIndices(size(Eω)[2:end])]\n return ω, Eω*fftnorm(grid)\nend\n\nfunction getEω(grid::EnvGrid, Eω::AbstractArray)\n idcs = FFTW.fftshift(grid.sidx)\n Eωs = FFTW.fftshift(Eω, 1)\n ω = FFTW.fftshift(grid.ω)[idcs]\n Eω = Eωs[idcs, CartesianIndices(size(Eω)[2:end])]\n return ω, Eω*fftnorm(grid)\nend\n\nfunction getEω(grid, output, zslice)\n zidx = nearest_z(output, zslice)\n ω, Eω = getEω(grid, output[\"Eω\", .., zidx])\n return ω, Eω, output[\"z\"][zidx]\nend\n\nfftnorm(grid::RealGrid) = Maths.rfftnorm(grid.t[2] - grid.t[1])\nfftnorm(grid::EnvGrid) = Maths.fftnorm(grid.t[2] - grid.t[1])\n\n\"\"\"\n getEt(output[, zslice]; kwargs...)\n\nGet the envelope time-domain electric field (including the carrier wave) from the `output`.\nIf `zslice` is given, returs only the slices of `Eω` closest to the given distances. `zslice`\ncan be a single number or an array.\n\"\"\"\ngetEt(output::AbstractOutput, args...; kwargs...) = getEt(\n makegrid(output), output, args...; kwargs...)\n\n\"\"\"\n getEt(grid, Eω; trange=nothing, oversampling=4, bandpass=nothing, FTL=false)\n\nGet the envelope time-domain electric field (including the carrier wave) from the frequency-\ndomain field `Eω`. The field can be cropped in time using `trange`, it is oversampled by\na factor of `oversampling` (default 4) and can be bandpassed with `bandpass`\n(see [`window_maybe`](@ref)). If `FTL` is `true`, return the Fourier-transform limited pulse,\ni.e. remove any spectral phase.\n\nIf `zslice` is given, returs only the slices of `Eω` closest to the given distances. `zslice`\ncan be a single number or an array.\n\"\"\"\nfunction getEt(grid::AbstractGrid, Eω::AbstractArray;\n trange=nothing, oversampling=4, bandpass=nothing,\n FTL=false, propagate=nothing)\n t = grid.t\n Eω = window_maybe(grid.ω, Eω, bandpass)\n if FTL\n τ = length(grid.t) * (grid.t[2] - grid.t[1])/2\n Eω .= abs.(Eω) .* exp.(-1im .* grid.ω .* τ)\n end\n Eω = prop_maybe(grid, Eω, propagate)\n Etout = envelope(grid, Eω)\n if isnothing(trange)\n idcs = 1:length(t)\n else\n idcs = @. (t < max(trange...)) & (t > min(trange...))\n end\n to, Eto = Maths.oversample(t[idcs], Etout[idcs, ..], factor=oversampling)\n return to, Eto\nend\n\ngetEt(grid::AbstractGrid, output::AbstractOutput; kwargs...) = getEt(grid, output[\"Eω\"]; kwargs...)\n\nfunction getEt(grid::AbstractGrid, output::AbstractOutput, zslice;\n kwargs...)\n t = grid.t\n zidx = nearest_z(output, zslice)\n to, Eto = getEt(grid, output[\"Eω\", .., zidx]; kwargs...)\n return to, Eto, output[\"z\"][zidx]\nend\n\n\"\"\"\n AutoWindow(width, λmin, λmax, ω0fun; relative=false, ndims=1)\n\nWindow function generator which automatically tracks the central frequency in the spectral\nregion given by `λmin` and `λmax` and applies a window of a specific `width` around the peak.\nThe central frequency is found using the function `ω0fun(ω, Iω::AbstractVector)`, where\n`ω` and `Iω` are already cropped to within the wavelength limits given.\nIf `relative` is `true`, `width` is relative bandwidth instead of the wavelength width.\n`ndims` determines how many dimensions of the array to sum over. For a field array with size\n`(Nω, N1, N2, ...)`, the first dimension is always assumed to be frequency. `ndim=1` means\neach field to be analysed is 1-dimensional, so the window iterates over all of `(N1, N2, ...)`.\n`ndim=2` means each field to be analysed is 2-dimensional, `(Nω, N1)` in size, and will be \nsummed over its second dimension before finding the central frequency. The window iterates\nover all other dimensions, `(N2, ...)`.\n\nA `AutoWindow` automatically stores the limits of the windows it applies in the field `lims`.\n\"\"\"\nmutable struct AutoWindow\n width::Float64\n λmin::Float64\n λmax::Float64\n ω0fun\n relative::Bool\n ndims\n lims\nend\n\nfunction AutoWindow(width, λmin, λmax, ω0fun; relative=false, ndims=1)\n AutoWindow(width, λmin, λmax, ω0fun, relative, ndims, nothing)\nend\n\nfunction (pw::AutoWindow)(ω, Eω)\n cidcs = CartesianIndices(size(Eω)[(pw.ndims+1):end])\n out = similar(Eω)\n cropidcs = (ω .> wlfreq(pw.λmax)) .& (ω .< wlfreq(pw.λmin))\n cropω = ω[cropidcs]\n Iω = abs2.(Eω)\n limsA = zeros((2, size(Eω)[(pw.ndims+1):end]...))\n for cidx in cidcs\n Iω_this = Iω[.., Tuple(cidx)...]\n Iωsum = sum(Iω_this; dims=2:ndims(Iω_this))\n λ0 = wlfreq(pw.ω0fun(cropω, Iωsum[cropidcs]))\n lims = pw.relative ? λ0.*(1 .+ (-0.5, 0.5).*pw.width) : λ0 .+ (-0.5, 0.5).*pw.width\n window = ωwindow_λ(ω, lims)\n limsA[:, Tuple(cidx)...] .= lims\n out[.., Tuple(cidx)...] .= Eω[.., Tuple(cidx)...] .* window\n end\n pw.lims = limsA\n out\nend\n\n\"\"\"\n PeakWindow(width, λmin, λmax; relative=false, ndims=1)\n\nAn [`AutoWindow`](@ref) which uses the peak of the spectral energy density as the central\nfrequency. \n\"\"\"\nfunction PeakWindow(width, λmin, λmax; relative=false, ndims=1)\n ω0fun = (ω, Iω) -> ω[argmax(Iω)]\n AutoWindow(width, λmin, λmax, ω0fun; relative=relative, ndims=ndims)\nend\n\n\"\"\"\n CentroidWindow(width, λmin, λmax; relative=false, ndims=1, power=1)\n\nAn [`AutoWindow`](@ref) which uses the centroid (centre of mass or first moment) of the\nspectral energy density as the central frequency. Before calculating the centroid, the \nSED is raised to the `power` given.\n\"\"\"\nfunction CentroidWindow(width, λmin, λmax; relative=false, ndims=1, power=1)\n ω0fun = (ω, Iω) -> Maths.moment(ω, Iω.^power)\n AutoWindow(width, λmin, λmax, ω0fun; relative=relative, ndims=ndims)\nend\n\n\"\"\"\n window_maybe(ω, Eω, win)\n\nApply a frequency window to the field `Eω` if required. Possible values for `win`:\n\n- `nothing` : no window is applied\n- 4-`Tuple` of `Number`s : the 4 parameters for a `Maths.planck_taper` in **wavelength**\n- 3-`Tuple` of `Number`s : minimum, maximum **wavelength**, and smoothing in **radial frequency**\n- 2-`Tuple` of `Number`s : minimum and maximum **wavelength** with automatically chosen smoothing\n- `Vector{<:Real}` : a pre-defined window function (shape must match `ω`)\n- `PeakWindow` : automatically track the peak in a given range and apply the window around it\n- `window(ω, Eω)` : an arbitrary user-supplied window function\n\"\"\"\nwindow_maybe(ω, Eω, ::Nothing) = Eω\nwindow_maybe(ω, Eω, win::NTuple{4, Number}) = Eω.*Maths.planck_taper(\n ω, sort(wlfreq.(collect(win)))...)\nwindow_maybe(ω, Eω, win::NTuple{2, Number}) = Eω .* ωwindow_λ(ω, win)\nwindow_maybe(ω, Eω, win::NTuple{3, Number}) = Eω .* ωwindow_λ(ω, win[1:2]; winwidth=win[3])\nwindow_maybe(ω, Eω, window) = window(ω, Eω)\nwindow_maybe(ω, Eω, window::AbstractVector) = Eω.*window\n\nprop_maybe(grid, Eω, ::Nothing) = Eω\nprop_maybe(grid, Eω, propagator) = propagator(grid, Eω)\n\n\n\"\"\"\n envelope(grid, Eω)\n\nGet the envelope electric field including the carrier wave from the frequency-domain field\n`Eω` sampled on `grid`.\n\"\"\"\nenvelope(grid::RealGrid, Eω) = Maths.hilbert(FFTW.irfft(Eω, length(grid.t), 1))\nenvelope(grid::EnvGrid, Eω) = FFTW.ifft(Eω, 1) .* exp.(im.*grid.ω0.*grid.t)\n\n\"\"\"\n makegrid(output)\n\nCreate an `AbstractGrid` from the `\"grid\"` dictionary saved in `output`.\n\"\"\"\nfunction makegrid(output)\n if output[\"simulation_type\"][\"field\"] == \"field-resolved\"\n from_dict(RealGrid, output[\"grid\"])\n else\n from_dict(EnvGrid, output[\"grid\"])\n end\nend\n\n\"\"\"\n nearest_z(output, z)\n\nReturn the index of saved z-position(s) closest to the position(s) `z`. Output is always\nan array, even if `z` is a number.\n\"\"\"\nnearest_z(output, z::Number) = [argmin(abs.(output[\"z\"] .- z))]\nnearest_z(output, z) = [argmin(abs.(output[\"z\"] .- zi)) for zi in z]\n\nend", "meta": {"hexsha": "91d707141edf0d665d78e06ba4f54b287a21a86c", "size": 25957, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Processing.jl", "max_stars_repo_name": "jtravs/Luna.jl", "max_stars_repo_head_hexsha": "2658d01f9bb8469788d8929192eb10c47f1092c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-02T14:15:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T11:41:46.000Z", "max_issues_repo_path": "src/Processing.jl", "max_issues_repo_name": "jtravs/Luna.jl", "max_issues_repo_head_hexsha": "2658d01f9bb8469788d8929192eb10c47f1092c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-09-17T09:51:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:13:48.000Z", "max_forks_repo_path": "src/Processing.jl", "max_forks_repo_name": "jtravs/Luna.jl", "max_forks_repo_head_hexsha": "2658d01f9bb8469788d8929192eb10c47f1092c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-17T08:39:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T08:40:40.000Z", "avg_line_length": 34.7949061662, "max_line_length": 109, "alphanum_fraction": 0.6712254883, "num_tokens": 7959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24876810030794264}} {"text": "function auglag_kernel(n::Int, major_iter::Int, max_auglag::Int,\n line_start::Int, scale::Float64,\n mu_max::Float64,\n u_curr::CuDeviceArray{Float64,1}, v_curr::CuDeviceArray{Float64,1},\n l_curr::CuDeviceArray{Float64,1}, rho::CuDeviceArray{Float64,1},\n wRIij::CuDeviceArray{Float64,1},\n param::CuDeviceArray{Float64,2},\n _YffR::CuDeviceArray{Float64,1}, _YffI::CuDeviceArray{Float64,1},\n _YftR::CuDeviceArray{Float64,1}, _YftI::CuDeviceArray{Float64,1},\n _YttR::CuDeviceArray{Float64,1}, _YttI::CuDeviceArray{Float64,1},\n _YtfR::CuDeviceArray{Float64,1}, _YtfI::CuDeviceArray{Float64,1},\n frBound::CuDeviceArray{Float64,1}, toBound::CuDeviceArray{Float64,1})\n tx = threadIdx().x\n ty = threadIdx().y\n I = blockIdx().x\n\n x = @cuDynamicSharedMem(Float64, n)\n xl = @cuDynamicSharedMem(Float64, n, n*sizeof(Float64))\n xu = @cuDynamicSharedMem(Float64, n, (2*n)*sizeof(Float64))\n\n pij_idx = line_start + 8*(I-1)\n\n if tx == 1 && ty == 1\n @inbounds for i=1:n\n xl[i] = -Inf\n xu[i] = Inf\n end\n\n @inbounds begin\n xl[5] = frBound[2*(I-1)+1]\n xu[5] = frBound[2*I]\n xl[6] = toBound[2*(I-1)+1]\n xu[6] = toBound[2*I]\n xl[9] = -2*pi\n xu[9] = 2*pi\n xl[10] = -2*pi\n xu[10] = 2*pi\n\n x[1] = u_curr[pij_idx]\n x[2] = u_curr[pij_idx+1]\n x[3] = u_curr[pij_idx+2]\n x[4] = u_curr[pij_idx+3]\n x[5] = min(xu[5], max(xl[5], u_curr[pij_idx+4]))\n x[6] = min(xu[6], max(xl[6], u_curr[pij_idx+5]))\n x[7] = wRIij[2*(I-1)+1]\n x[8] = wRIij[2*I]\n x[9] = min(xu[9], max(xl[9], u_curr[pij_idx+6]))\n x[10] = min(xu[10], max(xl[10], u_curr[pij_idx+7]))\n end\n end\n\n @inbounds begin\n YffR = _YffR[I]; YffI = _YffI[I]\n YftR = _YftR[I]; YftI = _YftI[I]\n YttR = _YttR[I]; YttI = _YttI[I]\n YtfR = _YtfR[I]; YtfI = _YtfI[I]\n\n param[1,I] = l_curr[pij_idx]\n param[2,I] = l_curr[pij_idx+1]\n param[3,I] = l_curr[pij_idx+2]\n param[4,I] = l_curr[pij_idx+3]\n param[5,I] = l_curr[pij_idx+4]\n param[6,I] = l_curr[pij_idx+5]\n param[7,I] = rho[pij_idx]\n param[8,I] = rho[pij_idx+1]\n param[9,I] = rho[pij_idx+2]\n param[10,I] = rho[pij_idx+3]\n param[11,I] = rho[pij_idx+4]\n param[12,I] = rho[pij_idx+5]\n param[13,I] = v_curr[pij_idx]\n param[14,I] = v_curr[pij_idx+1]\n param[15,I] = v_curr[pij_idx+2]\n param[16,I] = v_curr[pij_idx+3]\n param[17,I] = v_curr[pij_idx+4]\n param[18,I] = v_curr[pij_idx+5]\n\n param[25,I] = l_curr[pij_idx+6]\n param[26,I] = l_curr[pij_idx+7]\n param[27,I] = rho[pij_idx+6]\n param[28,I] = rho[pij_idx+7]\n param[29,I] = v_curr[pij_idx+6]\n param[30,I] = v_curr[pij_idx+7]\n end\n\n if major_iter == 1\n @inbounds param[24,I] = 10.0\n mu = 10.0\n else\n @inbounds mu = param[24,I]\n end\n\n CUDA.sync_threads()\n\n eta = 1 / CUDA.pow(mu, 0.1)\n omega = 1 / mu\n max_feval = 500\n max_minor = 200\n gtol = 1e-6\n\n it = 0\n terminate = false\n\n while !terminate\n it += 1\n\n # Solve the branch problem.\n status, minor_iter = tron_kernel(n, 0, max_feval, max_minor, gtol, scale, false, x, xl, xu,\n param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n\n @inbounds begin\n # Check the termination condition.\n cviol1 = x[1] - (YffR*x[5] + YftR*x[7] + YftI*x[8])\n cviol2 = x[2] - (-YffI*x[5] - YftI*x[7] + YftR*x[8])\n cviol3 = x[3] - (YttR*x[6] + YtfR*x[7] - YtfI*x[8])\n cviol4 = x[4] - (-YttI*x[6] - YtfI*x[7] - YtfR*x[8])\n cviol5 = x[7]^2 + x[8]^2 - x[5]*x[6]\n cviol6 = x[9] - x[10] - atan(x[8], x[7])\n end\n\n cnorm = max(abs(cviol1), abs(cviol2), abs(cviol3), abs(cviol4), abs(cviol5), abs(cviol6))\n\n if cnorm <= eta\n if cnorm <= 1e-6\n terminate = true\n else\n if tx == 1 && ty == 1\n @inbounds begin\n param[19,I] += mu*cviol1\n param[20,I] += mu*cviol2\n param[21,I] += mu*cviol3\n param[22,I] += mu*cviol4\n param[23,I] += mu*cviol5\n param[31,I] += mu*cviol6\n end\n end\n\n eta = eta / CUDA.pow(mu, 0.9)\n omega = omega / mu\n end\n else\n mu = min(mu_max, mu*10)\n eta = 1 / CUDA.pow(mu, 0.1)\n omega = 1 / mu\n @inbounds param[24,I] = mu\n end\n\n if it >= max_auglag\n terminate = true\n end\n\n CUDA.sync_threads()\n end\n\n @inbounds begin\n u_curr[pij_idx] = x[1]\n u_curr[pij_idx+1] = x[2]\n u_curr[pij_idx+2] = x[3]\n u_curr[pij_idx+3] = x[4]\n u_curr[pij_idx+4] = x[5]\n u_curr[pij_idx+5] = x[6]\n wRIij[2*(I-1)+1] = x[7]\n wRIij[2*I] = x[8]\n u_curr[pij_idx+6] = x[9]\n u_curr[pij_idx+7] = x[10]\n param[24,I] = mu\n end\n\n CUDA.sync_threads()\n\n return\nend\n\nfunction auglag_kernel_cpu(n::Int, nline::Int, major_iter::Int, max_auglag::Int,\n line_start::Int, mu_max::Float64,\n u_curr::Array{Float64}, v_curr::Array{Float64},\n l_curr::Array{Float64}, rho::Array{Float64},\n wRIij::Array{Float64},\n param::Array{Float64},\n YffR::Array{Float64}, YffI::Array{Float64},\n YftR::Array{Float64}, YftI::Array{Float64},\n YttR::Array{Float64}, YttI::Array{Float64},\n YtfR::Array{Float64}, YtfI::Array{Float64},\n frBound::Array{Float64}, toBound::Array{Float64})\n avg_auglag_it = 0\n avg_minor_it = 0\n\n x = zeros(n)\n xl = zeros(n)\n xu = zeros(n)\n\n @inbounds for I=1:nline\n @inbounds for i=1:n\n xl[i] = -Inf\n xu[i] = Inf\n end\n\n xl[5] = frBound[2*(I-1)+1]\n xu[5] = frBound[2*I]\n xl[6] = toBound[2*(I-1)+1]\n xu[6] = toBound[2*I]\n xl[9] = -2*pi\n xu[9] = 2*pi\n xl[10] = -2*pi\n xu[10] = 2*pi\n\n pij_idx = line_start + 8*(I-1)\n\n x[1] = u_curr[pij_idx]\n x[2] = u_curr[pij_idx+1]\n x[3] = u_curr[pij_idx+2]\n x[4] = u_curr[pij_idx+3]\n x[5] = min(xu[5], max(xl[5], u_curr[pij_idx+4]))\n x[6] = min(xu[6], max(xl[6], u_curr[pij_idx+5]))\n x[7] = wRIij[2*(I-1)+1]\n x[8] = wRIij[2*I]\n x[9] = min(xu[9], max(xl[9], u_curr[pij_idx+6]))\n x[10] = min(xu[10], max(xl[10], u_curr[pij_idx+7]))\n\n param[1,I] = l_curr[pij_idx]\n param[2,I] = l_curr[pij_idx+1]\n param[3,I] = l_curr[pij_idx+2]\n param[4,I] = l_curr[pij_idx+3]\n param[5,I] = l_curr[pij_idx+4]\n param[6,I] = l_curr[pij_idx+5]\n param[7,I] = rho[pij_idx]\n param[8,I] = rho[pij_idx+1]\n param[9,I] = rho[pij_idx+2]\n param[10,I] = rho[pij_idx+3]\n param[11,I] = rho[pij_idx+4]\n param[12,I] = rho[pij_idx+5]\n param[13,I] = v_curr[pij_idx]\n param[14,I] = v_curr[pij_idx+1]\n param[15,I] = v_curr[pij_idx+2]\n param[16,I] = v_curr[pij_idx+3]\n param[17,I] = v_curr[pij_idx+4]\n param[18,I] = v_curr[pij_idx+5]\n\n if major_iter == 1\n param[24,I] = 10.0\n mu = 10.0\n else\n mu = param[24,I]\n end\n\n param[25,I] = l_curr[pij_idx+6]\n param[26,I] = l_curr[pij_idx+7]\n param[27,I] = rho[pij_idx+6]\n param[28,I] = rho[pij_idx+7]\n param[29,I] = v_curr[pij_idx+6]\n param[30,I] = v_curr[pij_idx+7]\n\n function eval_f_cb(x)\n f= eval_f_kernel_cpu(I, x, param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n return f\n end\n\n function eval_g_cb(x, g)\n eval_grad_f_kernel_cpu(I, x, g, param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n return\n end\n\n function eval_h_cb(x, mode, rows, cols, scale, lambda, values)\n eval_h_kernel_cpu(I, x, mode, scale, rows, cols, lambda, values,\n param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n return\n end\n\n eta = 1 / mu^0.1\n omega = 1 / mu\n max_feval = 500\n max_minor = 100\n gtol = 1e-6\n\n nele_hess = 33\n tron = ExaTron.createProblem(n, xl, xu, nele_hess, eval_f_cb, eval_g_cb, eval_h_cb;\n :tol => gtol, :matrix_type => :Dense, :max_minor => 200,\n :frtol => 1e-12)\n tron.x .= x\n it = 0\n avg_tron_minor = 0\n terminate = false\n\n while !terminate\n it += 1\n\n # Solve the branch problem.\n status = ExaTron.solveProblem(tron)\n x .= tron.x\n avg_tron_minor += tron.minor_iter\n\n # Check the termination condition.\n cviol1 = x[1] - (YffR[I]*x[5] + YftR[I]*x[7] + YftI[I]*x[8])\n cviol2 = x[2] - (-YffI[I]*x[5] - YftI[I]*x[7] + YftR[I]*x[8])\n cviol3 = x[3] - (YttR[I]*x[6] + YtfR[I]*x[7] - YtfI[I]*x[8])\n cviol4 = x[4] - (-YttI[I]*x[6] - YtfI[I]*x[7] - YtfR[I]*x[8])\n cviol5 = x[7]^2 + x[8]^2 - x[5]*x[6]\n cviol6 = x[9] - x[10] - atan(x[8], x[7])\n\n cnorm = max(abs(cviol1), abs(cviol2), abs(cviol3), abs(cviol4), abs(cviol5), abs(cviol6))\n\n if cnorm <= eta\n if cnorm <= 1e-6\n terminate = true\n else\n param[19,I] += mu*cviol1\n param[20,I] += mu*cviol2\n param[21,I] += mu*cviol3\n param[22,I] += mu*cviol4\n param[23,I] += mu*cviol5\n param[31,I] += mu*cviol6\n\n eta = eta / mu^0.9\n omega = omega / mu\n end\n else\n mu = min(mu_max, mu*10)\n eta = 1 / mu^0.1\n omega = 1 / mu\n param[24,I] = mu\n end\n\n if it >= max_auglag\n terminate = true\n end\n end\n\n avg_auglag_it += it\n avg_minor_it += (avg_tron_minor / it)\n u_curr[pij_idx] = x[1]\n u_curr[pij_idx+1] = x[2]\n u_curr[pij_idx+2] = x[3]\n u_curr[pij_idx+3] = x[4]\n u_curr[pij_idx+4] = x[5]\n u_curr[pij_idx+5] = x[6]\n wRIij[2*(I-1)+1] = x[7]\n wRIij[2*I] = x[8]\n u_curr[pij_idx+6] = x[9]\n u_curr[pij_idx+7] = x[10]\n param[24,I] = mu\n end\n\n return (avg_auglag_it / nline), (avg_minor_it / nline)\nend\n", "meta": {"hexsha": "8eca41131b9202dba307817a13baa9991ce41698", "size": 11327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/admm/auglag_kernel.jl", "max_stars_repo_name": "wzhangw/ExaTron.jl", "max_stars_repo_head_hexsha": "c5844f356876904c410b68bf2b20ba3a03597674", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-07T19:27:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:38:20.000Z", "max_issues_repo_path": "src/admm/auglag_kernel.jl", "max_issues_repo_name": "wzhangw/ExaTron.jl", "max_issues_repo_head_hexsha": "c5844f356876904c410b68bf2b20ba3a03597674", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-05-07T16:17:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T22:22:53.000Z", "max_forks_repo_path": "src/admm/auglag_kernel.jl", "max_forks_repo_name": "wzhangw/ExaTron.jl", "max_forks_repo_head_hexsha": "c5844f356876904c410b68bf2b20ba3a03597674", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-22T14:34:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T16:21:49.000Z", "avg_line_length": 32.9273255814, "max_line_length": 101, "alphanum_fraction": 0.4655248521, "num_tokens": 3997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.24866367336703463}} {"text": "module DiskArrayTools\nimport DiskArrays: AbstractDiskArray, eachchunk, haschunks, Chunked,\nestimate_chunksize, GridChunks, findints, readblock!, writeblock!\nusing Interpolations\nusing IterTools: imap\nusing Base.Iterators: product\nusing OffsetArrays: OffsetArray\n\n#Define a new chunk grid type for irregular, but still block-shaped grid\nstruct IrregularGridChunks{N} <: AbstractArray{CartesianIndices{N,NTuple{N,UnitRange{Int}}},N}\n cs::NTuple{N,Vector{UnitRange{Int}}}\n s::NTuple{N,Int}\nend\nBase.size(cs::IrregularGridChunks) = cs.s\nBase.size(cs::IrregularGridChunks,i) = cs.s[i]\nfunction IrregularGridChunks(cs::Vector{UnitRange{Int}}...)\n s = length.(cs)\n IrregularGridChunks((cs...,),s)\nend\nBase.eltype(::IrregularGridChunks{N}) where N = CartesianIndices{N,NTuple{N,UnitRange{Int}}}\nfunction Base.show(io::IO,g::IrregularGridChunks)\n stot = last.(g.cs)\n griddes = join(string.(g.s), \"x\")\n sizedes = join(string.(stot), \"x\")\n print(io,\"Irregular chunk grid of size $griddes over DiskArray of size $stot\")\nend\nfunction Base.getindex(cs::IrregularGridChunks{N},i::Vararg{Int, N}) where N\n rout = getindex.(cs.cs,i)\n CartesianIndices(rout)\nend\n\nexport DiskArrayStack, diskstack, ConcatDiskArray, CFDiskArray\nstruct DiskArrayStack{T,N,M,NO}<:AbstractDiskArray{T,N}\n arrays::Array{M,NO}\nend\nfunction diskstack(a::Array{M,N}) where {N,M<:AbstractArray{T,NO}} where {T,NO}\n length(unique(size.(a))) == 1 || error(\"All arrays in the stack must have the same size\")\n DiskArrayStack{T,N+NO,M,N}(a)\nend\nBase.size(r::DiskArrayStack) = (size(r.arrays[1])...,size(r.arrays)...)\nhaschunks(a::DiskArrayStack) = haschunks(a.arrays[1])\niscompressed(a::DiskArrayStack) = any(iscompressed,a.arrays)\nfunction eachchunk(a::DiskArrayStack{<:Any,<:Any,<:Any,NO}) where NO\n iterold = eachchunk(a.arrays[1])\n cs = (iterold.chunksize...,ntuple(one,NO)...)\n co = (iterold.offset...,ntuple(zero,NO)...)\n GridChunks(a,cs,offset=co)\nend\n\nfunction readblock!(a::DiskArrayStack{<:Any,N,<:Any,NO},aout,i::AbstractVector...) where {N,NO}\n\n innerinds = i[1:(N-NO)]\n\n outerinds = i[(N-NO+1):N]\n innercolon = map(_->(:), innerinds)\n iiter = CartesianIndices(outerinds)\n inum = CartesianIndices(size(iiter))\n foreach(zip(iiter,inum)) do (iouter,iret)\n arnow = a.arrays[iouter]\n if isa(arnow, AbstractDiskArray)\n readblock!(a.arrays[iouter],view(aout,innercolon...,iret.I...),innerinds...)\n else\n aout[innercolon...,iret.I...] = arnow[innerinds...]\n end\n end\n nothing\nend\n\nfunction writeblock!(a::DiskArrayStack{<:Any,N,<:Any,NO},v,i::AbstractVector...) where {N,NO}\n innerinds = i[1:(N-NO)]\n\n outerinds = i[(N-NO+1):N]\n innercolon = map(_->(:), innerinds)\n iiter = CartesianIndices(outerinds)\n inum = CartesianIndices(size(iiter))\n foreach(zip(iiter,inum)) do (iouter,iret)\n arnow = a.arrays[iouter]\n if isa(arnow, AbstractDiskArray)\n writeblock!(a.arrays[iouter],view(v,innercolon...,iret.I...),innerinds...)\n else\n arnow[innerinds...] = v[innercolon...,iret.I...]\n end\n end\n nothing\nend\n\nfunction Base.view(a::DiskArrayStack{<:Any,N,<:Any,NO},i...) where {N,NO}\n iinner = i[1:(N-NO)]\n ashort = map(view(a.arrays,i[(N-NO+1):N]...)) do ai\n view(ai,iinner...)\n end\n if ndims(ashort)==0\n ashort[]\n else\n diskstack(ashort)\n end\nend\n\nabstract type ResampledDiskArray{T,N} <: AbstractDiskArray{T,N} end\n\nfunction readblock!(a::ResampledDiskArray, aout, i::AbstractUnitRange...)\n parentranges = map((ir,ip)->ip[ir],i,a.newinds)\n rr = get_readinds(a,parentranges)\n atemp = a.a[rr...]\n atemp2 = OffsetArray(atemp,map(r->(first(r)-1),rr))\n resample_disk(a,aout,atemp2,parentranges)\nend\n\n\n\nstruct InterpolatedDiskArray{T,N,A<:AbstractArray{T,N},I,O,BC,CS<:Union{Nothing,GridChunks{N}}} <: ResampledDiskArray{T,N}\n a::A\n newinds::I\n meth::O\n bc::BC\n chunksize::CS\nend\nfixin(i,s) = max(1,min(s,i))\nfunction round_readinds(s,r,an)\n mi,ma = extrema(r)\n if mi == ma\n m = fixin(round(Int,mi),s)\n m:m\n else\n a = if an\n (round(Int,mi,RoundNearestTiesUp), -round(Int,-ma,RoundNearestTiesUp))\n else\n (floor(Int,mi),ceil(Int,ma))\n end\n fixin(a[1],s):fixin(a[2],s)\n end\nend\n\nfunction get_readinds(a::InterpolatedDiskArray,r)\n allnearest = all(i->isa(i,Union{Nothing,BSpline{Constant}}),a.meth)\n round_readinds.(size(a.a),r,allnearest)\nend\n\nallmeths(order::Tuple,newinds) = map(order,newinds) do o,ni\n ni === nothing ? NoInterp() : BSpline(o)\nend\nfunction allmeths(order, newinds)\n allorders = map(newinds) do _\n order\n end\n allmeths(allorders,newinds)\nend\nfunction InterpolatedDiskArray(a::AbstractArray,chunksize,newinds...; order=Linear(), bc=Flat())\n eltype(a) <: Union{Missing,Real,Complex} || error(\"Can only interpolate real or complex values\")\n s = size(a)\n ni2 = map((s,i)->i===nothing ? (1:s) : i,s,newinds)\n me = allmeths(order,newinds)\n InterpolatedDiskArray(a,ni2,me,bc,chunksize)\nend\nBase.size(a::InterpolatedDiskArray) = map(length,a.newinds)\nhaschunks(a::InterpolatedDiskArray{<:Any,<:Any,<:Any,<:Any,<:Any,<:Any,<:GridChunks}) = true\nhaschunks(a::InterpolatedDiskArray{<:Any,<:Any,<:Any,<:Any,<:Any,<:Any,Nothing}) = false\neachchunk(a::InterpolatedDiskArray{<:Any,<:Any,<:Any,<:Any,<:Any,<:Any,<:GridChunks}) = a.chunksize\n\nfunction resample_disk(a::InterpolatedDiskArray,aout,atemp,parentranges)\n meth = map((s,m)->s==1 ? NoInterp() : m,size(atemp),a.meth)\n if all(isequal(NoInterp()),meth)\n aout .= atemp.parent\n else\n fremap(aout,atemp,parentranges,meth,bc=a.bc)\n end\nend\n\nfunction fremap(xout,xin,newinds,ipmeth;bc = Flat())\n interp = extrapolate(interpolate(xin, ipmeth), bc)\n for (i,ic) in enumerate(Iterators.product(newinds...))\n xout[i]=interp(ic...)\n end\nend\n\n\n\n#Use of Sentinel missing value\nstruct CFDiskArray{T,N,ST,P<:AbstractArray{ST,N}} <: AbstractDiskArray{Union{T,Missing},N}\n a::P\n mv::ST\n add_offset::T\n scale_factor::T\nend\nfunction CFDiskArray(a::AbstractArray{T}, attr::Dict) where T\n mv = get(attr,\"missing_value\",get(attr,\"_FillValue\",typemax(T)))\n offs,sc = if haskey(attr,\"add_offset\") || haskey(attr,\"scale_factor\")\n offs = get(attr,\"add_offset\",zero(Float16))\n sc = get(attr,\"scale_factor\",one(Float16))\n promote(offs,sc)\n else\n zero(T), one(T)\n end\n CFDiskArray(a, T(mv), offs, sc)\nend\n\nBase.size(a::CFDiskArray, args...) = size(a.a, args...)\nhaschunks(a::CFDiskArray) = haschunks(a.a)\neachchunk(a::CFDiskArray) = eachchunk(a.a)\niscompressed(a::CFDiskArray) = iscompressed(a.a)\n\nfunction readblock!(a::CFDiskArray, aout, r::AbstractVector...)\n mv = a.mv\n sc,offs = a.scale_factor, a.add_offset\n broadcast!(j->scaleoffs(j,mv,sc,offs), aout, view(a.a,r...))\n nothing\nend\nscaleoffs(x,mv,sc,offs) = x==mv ? missing : x*sc+offs\nfunction writeblock!(a::CFDiskArray, v, r::AbstractVector...)\n mv = a.mv\n sc,offs = a.scale_factor, a.add_offset\n broadcast!(j->scaleoffsinv(j,mv,sc,offs), view(a.a,r...), v)\n nothing\nend\nscaleoffsinv(x,mv::Integer,sc,offs) = ismissing(x) ? mv : round(typeof(mv),(x-offs)/sc)\nscaleoffsinv(x,mv,sc,offs) = ismissing(x) ? mv : ((x-offs)/sc)\n\n\nstruct ConcatDiskArray{T,N,P} <: AbstractDiskArray{T,N}\n parents::P\n startinds::NTuple{N,Vector{Int}}\n size::NTuple{N,Int}\nend\n\nfunction ConcatDiskArray(arrays::AbstractArray)\n #First do some consistency checks\n arrinfo = map(arrays) do a\n eltype(a), size(a)\n end\n et = first(arrinfo)[1]\n nd = length(first(arrinfo)[2])\n sa = size.(arrays)\n all(i->i[1]==et,arrinfo) || error(\"Arrays don't have the same element type\")\n all(i->length(i[2])==nd, arrinfo) || error(\"Arrays don't have the same dimensions\")\n if ndims(arrays)i[id],ar)\n sl = sum(ari)\n r = cumsum(ari)\n pop!(pushfirst!(r,0))\n r.+1, sl\n end\n ConcatDiskArray{et,nd,typeof(arrays)}(arrays, (getindex.(si,1)...,),(getindex.(si,2)...,))\nend\n\nBase.size(a::ConcatDiskArray) = a.size\nhaschunks(::ConcatDiskArray) = Chunked()\nfunction readblock!(a::ConcatDiskArray, aout, inds::AbstractUnitRange...)\n #Find affected blocks and indices in blocks\n blockinds = map(inds, a.startinds, size(a.parents)) do i, si, s\n bi1 = max(searchsortedlast(si,first(i)),1)\n bi2 = min(searchsortedfirst(si,last(i)+1)-1,s)\n bi1:bi2\n end\n map(CartesianIndices(blockinds)) do cI\n myar = a.parents[cI]\n mysize = size(myar)\n array_range = map(cI.I, a.startinds, mysize, inds) do ii, si, ms, indstoread\n max(first(indstoread)-si[ii]+1,1) : min(last(indstoread)-si[ii]+1, ms)\n end\n outer_range = map(cI.I, a.startinds, array_range, inds) do ii, si, ar, indstoread\n (first(ar)+si[ii]-first(indstoread)):(last(ar)+si[ii]-first(indstoread))\n end\n aout[outer_range...] .= a.parents[cI][array_range...]\n end\nend\nfunction writeblock!(a::ConcatDiskArray, aout, inds::AbstractUnitRange...)\n error(\"No method yet for writing into a ConcatDiskArray\")\nend\n\nfunction eachchunk_fallback(aconc::ConcatDiskArray)\n nested = imap(zip(aconc.parents, Iterators.product(aconc.startinds...))) do (par, si)\n imap(eachchunk(par)) do cI\n cI .+ CartesianIndex(si.-1)\n end\n end\n Iterators.flatten(nested)\nend\n\n#This function will work for DiskArrayStack as well, we only need a fallback_chunksize function\nfunction eachchunk(aconc::ConcatDiskArray)\n fbchunks = eachchunk_fallback(aconc)\n nd = ndims(first(fbchunks))\n dout = ntuple(_->Dict{NTuple{nd-1,UnitRange{Int}},Set{UnitRange{Int}}}(),nd)\n foreach(fbchunks) do c\n map(enumerate(c.indices)) do (ind,r)\n other = (c.indices[1:ind-1]...,c.indices[ind+1:end]...)\n s = get!(dout[ind],other) do \n Set{UnitRange{Int}}()\n end\n push!(s,c.indices[ind])\n end\n end\n #First check if all \n uniqueranges = unique.(values.(dout)) # Here we give up\n if any(length.(uniqueranges) .> 1)\n return fbchunks\n end\n simplifyaxes = map(uniqueranges) do ur\n allr = first(ur)\n allr = sort!(collect(allr),by=first)\n l = length.(allr)\n if length(l)==1 \n allr,(cs = l[1], offs = 0, l = l[1])\n elseif all(isequal(l[2]),l[2:end-1]) && l[end]<=l[2]\n allr,(cs = l[2], offs = l[2]-l[1], l = allr[end][end])\n else\n allr,nothing\n end\n end\n if all(!isnothing,getindex.(simplifyaxes,2))\n grid = getindex.(simplifyaxes,2)\n cs,offs,l = getproperty.(grid,:cs),getproperty.(grid,:offs),getproperty.(grid,:l)\n return GridChunks(l,cs, offset = offs)\n else\n return IrregularGridChunks(getindex.(simplifyaxes,1)...)\n end\nend\nend # module\n", "meta": {"hexsha": "69201e7b7d7fc7428b8a35637f30ebdaf1a2619c", "size": 11313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DiskArrayTools.jl", "max_stars_repo_name": "felixcremer/DiskArrayTools.jl", "max_stars_repo_head_hexsha": "28584ab13c440ea3af0f719a2eb2987572fa3320", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DiskArrayTools.jl", "max_issues_repo_name": "felixcremer/DiskArrayTools.jl", "max_issues_repo_head_hexsha": "28584ab13c440ea3af0f719a2eb2987572fa3320", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DiskArrayTools.jl", "max_forks_repo_name": "felixcremer/DiskArrayTools.jl", "max_forks_repo_head_hexsha": "28584ab13c440ea3af0f719a2eb2987572fa3320", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3716814159, "max_line_length": 122, "alphanum_fraction": 0.6510209494, "num_tokens": 3632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.24848030850481534}} {"text": "# This file is a part of Julia. License is MIT: http://julialang.org/license\n\n#Period types\nvalue(x::Period) = x.value\n\n# The default constructors for Periods work well in almost all cases\n# P(x) = new((convert(Int64,x))\n# The following definitions are for Period-specific safety\nfor period in (:Year, :Month, :Week, :Day, :Hour, :Minute, :Second, :Millisecond)\n period_str = string(period)\n accessor_str = lowercase(period_str)\n # Convenience method for show()\n @eval _units(x::$period) = \" \" * $accessor_str * (abs(value(x)) == 1 ? \"\" : \"s\")\n # periodisless\n @eval periodisless(x::$period,y::$period) = value(x) < value(y)\n # AbstractString parsing (mainly for IO code)\n @eval $period(x::AbstractString) = $period(Base.parse(Int64,x))\n # Period accessors\n typ_str = period in (:Hour, :Minute, :Second, :Millisecond) ? \"DateTime\" : \"TimeType\"\n description = typ_str == \"TimeType\" ? \"`Date` or `DateTime`\" : \"`$typ_str`\"\n reference = period == :Week ? \" For details see [`$accessor_str(::$typ_str)`](:func:`$accessor_str`).\" : \"\"\n @eval begin\n @doc \"\"\"\n $($period_str)(dt::$($typ_str)) -> $($period_str)\n\n The $($accessor_str) part of a $($description) as a `$($period_str)`.$($reference)\n \"\"\" ->\n $period(dt::$(Symbol(typ_str))) = $period($(Symbol(accessor_str))(dt))\n\n @doc \"\"\"\n $($period_str)(v)\n\n Construct a `$($period_str)` object with the given `v` value. Input must be\n losslessly convertible to an `Int64`.\n \"\"\" $period(v)\n end\nend\n# Now we're safe to define Period-Number conversions\n# Anything an Int64 can convert to, a Period can convert to\nBase.convert{T<:Number}(::Type{T},x::Period) = convert(T,value(x))\nBase.convert{T<:Period}(::Type{T},x::Real) = T(x)\n\n#Print/show/traits\nBase.string{P<:Period}(x::P) = string(value(x),_units(x))\nBase.show(io::IO,x::Period) = print(io,string(x))\nBase.zero{P<:Period}(::Union{Type{P},P}) = P(0)\nBase.one{P<:Period}(::Union{Type{P},P}) = P(1)\nBase.typemin{P<:Period}(::Type{P}) = P(typemin(Int64))\nBase.typemax{P<:Period}(::Type{P}) = P(typemax(Int64))\n\n# Default values (as used by TimeTypes)\n\"\"\"\n default(p::Period) -> Period\n\nReturns a sensible \"default\" value for the input Period by returning `one(p)` for Year,\nMonth, and Day, and `zero(p)` for Hour, Minute, Second, and Millisecond.\n\"\"\"\nfunction default end\n\ndefault{T<:DatePeriod}(p::Union{T,Type{T}}) = one(p)\ndefault{T<:TimePeriod}(p::Union{T,Type{T}}) = zero(p)\n\n(-){P<:Period}(x::P) = P(-value(x))\nBase.isless{P<:Period}(x::P,y::P) = isless(value(x),value(y))\n=={P<:Period}(x::P,y::P) = value(x) == value(y)\n\n# Period Arithmetic, grouped by dimensionality:\nimport Base: div, fld, mod, rem, gcd, lcm, +, -, *, /, %, .+, .-, .*, .%\nfor op in (:+,:-,:lcm,:gcd)\n @eval ($op){P<:Period}(x::P,y::P) = P(($op)(value(x),value(y)))\nend\n\nfor op in (:/,:div,:fld)\n @eval begin\n ($op){P<:Period}(x::P,y::P) = ($op)(value(x),value(y))\n ($op){P<:Period}(x::P,y::Real) = P(($op)(value(x),Int64(y)))\n end\nend\n\nfor op in (:rem,:mod)\n @eval begin\n ($op){P<:Period}(x::P,y::P) = P(($op)(value(x),value(y)))\n ($op){P<:Period}(x::P,y::Real) = P(($op)(value(x),Int64(y)))\n end\nend\n\n/{P<:Period}(X::StridedArray{P}, y::P) = X ./ y\n%{P<:Period}(X::StridedArray{P}, y::P) = X .% y\n*{P<:Period}(x::P,y::Real) = P(value(x) * Int64(y))\n*(y::Real,x::Period) = x * y\n.*{P<:Period}(y::Real, X::StridedArray{P}) = X .* y\nfor (op,Ty,Tz) in ((:.*,Real,:P),\n (:./,:P,Float64), (:./,Real,:P),\n (:div,:P,Int64), (:div,Integer,:P),\n (:.%,:P,:P),\n (:mod,:P,:P))\n sop = string(op)\n op_ = sop[1] == '.' ? Symbol(sop[2:end]) : op\n @eval begin\n function ($op){P<:Period}(X::StridedArray{P},y::$Ty)\n Z = similar(X, $Tz)\n for (Idst, Isrc) in zip(eachindex(Z), eachindex(X))\n @inbounds Z[Idst] = ($op_)(X[Isrc],y)\n end\n return Z\n end\n end\nend\n\n# intfuncs\nBase.gcdx{T<:Period}(a::T,b::T) = ((g,x,y)=gcdx(value(a),value(b)); return T(g),x,y)\nBase.abs{T<:Period}(a::T) = T(abs(value(a)))\n\nperiodisless(::Period,::Year) = true\nperiodisless(::Period,::Month) = true\nperiodisless(::Year,::Month) = false\nperiodisless(::Period,::Week) = true\nperiodisless(::Year,::Week) = false\nperiodisless(::Month,::Week) = false\nperiodisless(::Period,::Day) = true\nperiodisless(::Year,::Day) = false\nperiodisless(::Month,::Day) = false\nperiodisless(::Week,::Day) = false\nperiodisless(::Period,::Hour) = false\nperiodisless(::Minute,::Hour) = true\nperiodisless(::Second,::Hour) = true\nperiodisless(::Millisecond,::Hour) = true\nperiodisless(::Period,::Minute) = false\nperiodisless(::Second,::Minute) = true\nperiodisless(::Millisecond,::Minute) = true\nperiodisless(::Period,::Second) = false\nperiodisless(::Millisecond,::Second) = true\nperiodisless(::Period,::Millisecond) = false\n\n# return (next coarser period, conversion factor):\ncoarserperiod{P<:Period}(::Type{P}) = (P,1)\ncoarserperiod(::Type{Millisecond}) = (Second,1000)\ncoarserperiod(::Type{Second}) = (Minute,60)\ncoarserperiod(::Type{Minute}) = (Hour,60)\ncoarserperiod(::Type{Hour}) = (Day,24)\ncoarserperiod(::Type{Day}) = (Week,7)\ncoarserperiod(::Type{Month}) = (Year,12)\n\n# Stores multiple periods in greatest to least order by type, not values,\n# canonicalized to eliminate zero periods, merge equal period types,\n# and convert more-precise periods to less-precise periods when possible\n\"\"\"\n CompoundPeriod\n\nA `CompoundPeriod` is useful for expressing time periods that are not a fixed multiple of\nsmaller periods. For example, \\\"a year and a day\\\" is not a fixed number of days, but can\nbe expressed using a `CompoundPeriod`. In fact, a `CompoundPeriod` is automatically\ngenerated by addition of different period types, e.g. `Year(1) + Day(1)` produces a\n`CompoundPeriod` result.\n\"\"\"\ntype CompoundPeriod <: AbstractTime\n periods::Array{Period,1}\n function CompoundPeriod(p::Vector{Period})\n n = length(p)\n if n > 1\n sort!(p, rev=true, lt=periodisless)\n # canonicalize p by merging equal period types and removing zeros\n i = j = 1\n while j <= n\n k = j+1\n while k <= n\n if typeof(p[j]) == typeof(p[k])\n p[j] += p[k]\n k += 1\n else\n break\n end\n end\n if p[j] != zero(p[j])\n p[i] = p[j]\n i += 1\n end\n j = k\n end\n n = i - 1 # new length\n elseif n == 1 && value(p[1]) == 0\n p = Period[]\n n = 0\n end\n # canonicalize Periods by pushing \"overflow\" into a coarser period.\n if n > 0\n pc = sizehint!(Period[], n)\n P = typeof(p[n])\n v = value(p[n])\n i = n - 1\n while true\n Pc, f = coarserperiod(P)\n if i > 0 && typeof(p[i]) == P\n v += value(p[i])\n i -= 1\n end\n v0 = f == 1 ? v : rem(v, f)\n v0 != 0 && push!(pc, P(v0))\n if v != v0\n P = Pc\n v = div(v - v0, f)\n elseif i > 0\n P = typeof(p[i])\n v = value(p[i])\n i -= 1\n else\n break\n end\n end\n p = reverse!(pc)\n n = length(p)\n else\n return new(resize!(p, n))\n end\n # reduce the amount of mixed positive/negative Periods.\n if n > 0\n pc = sizehint!(Period[], n)\n i = n\n while i > 0\n j = i\n\n # Determine sign of the largest period in this group which\n # can be converted into via coarserperiod.\n last = Union{}\n current = typeof(p[i])\n while i > 0 && current != last\n if typeof(p[i]) == current\n i -= 1\n end\n last, current = current, coarserperiod(current)[1]\n end\n s = sign(value(p[i + 1]))\n\n # Adjust all the periods in the group based upon the\n # largest period sign.\n P = typeof(p[j])\n v = 0\n while j > i\n Pc, f = coarserperiod(P)\n if j > 0 && typeof(p[j]) == P\n v += value(p[j])\n j -= 1\n end\n v0 = f == 1 ? v : mod(v, f * s)\n v0 != 0 && push!(pc, P(v0))\n if v != v0\n P = Pc\n v = div(v - v0, f)\n elseif j > 0\n P = typeof(p[j])\n v = 0\n else\n break\n end\n end\n end\n p = reverse!(pc)\n end\n return new(p)\n end\nend\n\n\"\"\"\n CompoundPeriod(periods) -> CompoundPeriod\n\nConstruct a `CompoundPeriod` from a `Vector` of `Period`s. The constructor will\nautomatically simplify the periods into a canonical form according to the following rules:\n\n* All `Period`s of the same type will be added together\n* Any `Period` large enough be partially representable by a coarser `Period` will be broken\n into multiple `Period`s (eg. `Hour(30)` becomes `Day(1) + Hour(6)`)\n* `Period`s with opposite signs will be combined when possible\n (eg. `Hour(1) - Day(1)` becomes `-Hour(23)`)\n\nDue to the canonicalization, `CompoundPeriod` is also useful for converting time periods\ninto more human-comprehensible forms.\n\n# Examples\n```julia\njulia> Dates.CompoundPeriod([Dates.Hour(12), Dates.Hour(13)])\n1 day, 1 hour\n\njulia> Dates.CompoundPeriod([Dates.Hour(-1), Dates.Minute(1)])\n-59 minutes\n\njulia> Dates.CompoundPeriod([Dates.Month(1), Dates.Week(-2)])\n1 month, -2 weeks\n\njulia> Dates.CompoundPeriod(Dates.Minute(50000)))\n4 weeks, 6 days, 17 hours, 20 minutes\n```\n\"\"\"\nCompoundPeriod{P<:Period}(p::Vector{P}) = CompoundPeriod(Array{Period}(p))\n\n\nBase.convert(::Type{CompoundPeriod}, x::Period) = CompoundPeriod(Period[x])\nfunction Base.string(x::CompoundPeriod)\n if isempty(x.periods)\n return \"empty period\"\n else\n s = \"\"\n for p in x.periods\n s *= \", \" * string(p)\n end\n return s[3:end]\n end\nend\nBase.show(io::IO,x::CompoundPeriod) = print(io,string(x))\n\n# E.g. Year(1) + Day(1)\n(+)(x::Period,y::Period) = CompoundPeriod(Period[x,y])\n(+)(x::CompoundPeriod,y::Period) = CompoundPeriod(vcat(x.periods,y))\n(+)(y::Period,x::CompoundPeriod) = x + y\n(+)(x::CompoundPeriod,y::CompoundPeriod) = CompoundPeriod(vcat(x.periods,y.periods))\n# E.g. Year(1) - Month(1)\n(-)(x::Period,y::Period) = CompoundPeriod(Period[x,-y])\n(-)(x::CompoundPeriod,y::Period) = CompoundPeriod(vcat(x.periods,-y))\n(-)(x::CompoundPeriod) = CompoundPeriod(-x.periods)\n(-)(y::Union{Period,CompoundPeriod},x::CompoundPeriod) = (-x) + y\n\nGeneralPeriod = Union{Period,CompoundPeriod}\n(+)(x::GeneralPeriod) = x\n(+){P<:GeneralPeriod}(x::StridedArray{P}) = x\n\nfor op in (:.+, :.-)\n op_ = Symbol(string(op)[2:end])\n @eval begin\n function ($op){P<:GeneralPeriod}(X::StridedArray{P},y::GeneralPeriod)\n Z = similar(X, CompoundPeriod)\n for (Idst, Isrc) in zip(eachindex(Z), eachindex(X))\n @inbounds Z[Idst] = ($op_)(X[Isrc],y)\n end\n return Z\n end\n ($op){P<:GeneralPeriod}(x::GeneralPeriod,Y::StridedArray{P}) = ($op)(Y,x) |> ($op_)\n ($op_){P<:GeneralPeriod}(x::GeneralPeriod,Y::StridedArray{P}) = ($op)(Y,x) |> ($op_)\n ($op_){P<:GeneralPeriod}(Y::StridedArray{P},x::GeneralPeriod) = ($op)(Y,x)\n ($op_){P<:GeneralPeriod, Q<:GeneralPeriod}(X::StridedArray{P}, Y::StridedArray{Q}) =\n reshape(CompoundPeriod[($op_)(x,y) for (x,y) in zip(X, Y)], promote_shape(size(X),size(Y)))\n end\nend\n\n(==)(x::CompoundPeriod, y::Period) = x == CompoundPeriod(y)\n(==)(y::Period, x::CompoundPeriod) = x == y\n(==)(x::CompoundPeriod, y::CompoundPeriod) = x.periods == y.periods\n\n# Capture TimeType+-Period methods\n(+)(a::TimeType,b::Period,c::Period) = (+)(a,b+c)\n(-)(a::TimeType,b::Period,c::Period) = (-)(a,b-c)\n(+)(a::TimeType,b::Period,c::Period,d::Period...) = (+)((+)(a,b+c),d...)\n(-)(a::TimeType,b::Period,c::Period,d::Period...) = (-)((-)(a,b-c),d...)\n\nfunction (+)(x::TimeType,y::CompoundPeriod)\n for p in y.periods\n x += p\n end\n return x\nend\n(+)(x::CompoundPeriod,y::TimeType) = y + x\n\nfunction (-)(x::TimeType,y::CompoundPeriod)\n for p in y.periods\n x -= p\n end\n return x\nend\n(-)(x::CompoundPeriod,y::TimeType) = y - x\n\n# Fixed-value Periods (periods corresponding to a well-defined time interval,\n# as opposed to variable calendar intervals like Year).\ntypealias FixedPeriod Union{Week,Day,Hour,Minute,Second,Millisecond}\n\n# like div but throw an error if remainder is nonzero\nfunction divexact(x,y)\n q,r = divrem(x, y)\n r == 0 || throw(InexactError())\n return q\nend\n\n# FixedPeriod conversions and promotion rules\nconst fixedperiod_conversions = [(Week,7),(Day,24),(Hour,60),(Minute,60),(Second,1000),(Millisecond,1)]\nfor i = 1:length(fixedperiod_conversions)\n (T,n) = fixedperiod_conversions[i]\n N = 1\n for j = i-1:-1:1 # less-precise periods\n (Tc,nc) = fixedperiod_conversions[j]\n N *= nc\n vmax = typemax(Int64) ÷ N\n vmin = typemin(Int64) ÷ N\n @eval function Base.convert(::Type{$T}, x::$Tc)\n $vmin ≤ value(x) ≤ $vmax || throw(InexactError())\n return $T(value(x)*$N)\n end\n end\n N = n\n for j = i+1:length(fixedperiod_conversions) # more-precise periods\n (Tc,nc) = fixedperiod_conversions[j]\n @eval Base.convert(::Type{$T}, x::$Tc) = $T(divexact(value(x), $N))\n @eval Base.promote_rule(::Type{$T},::Type{$Tc}) = $Tc\n N *= nc\n end\nend\n# have to declare thusly so that diagonal dispatch above takes precedence:\n(==){T<:FixedPeriod,S<:FixedPeriod}(x::T,y::S) = (==)(promote(x,y)...)\nBase.isless{T<:FixedPeriod,S<:FixedPeriod}(x::T,y::S) = isless(promote(x,y)...)\n\n# other periods with fixed conversions but which aren't fixed time periods\ntypealias OtherPeriod Union{Month,Year}\nlet vmax = typemax(Int64) ÷ 12, vmin = typemin(Int64) ÷ 12\n @eval function Base.convert(::Type{Month}, x::Year)\n $vmin ≤ value(x) ≤ $vmax || throw(InexactError())\n Month(value(x)*12)\n end\nend\nBase.convert(::Type{Year}, x::Month) = Year(divexact(value(x),12))\nBase.promote_rule(::Type{Year}, ::Type{Month}) = Month\n(==){T<:OtherPeriod,S<:OtherPeriod}(x::T,y::S) = (==)(promote(x,y)...)\nBase.isless{T<:OtherPeriod,S<:OtherPeriod}(x::T,y::S) = isless(promote(x,y)...)\n\n# truncating conversions to milliseconds and days:\ntoms(c::Millisecond) = value(c)\ntoms(c::Second) = 1000*value(c)\ntoms(c::Minute) = 60000*value(c)\ntoms(c::Hour) = 3600000*value(c)\ntoms(c::Day) = 86400000*value(c)\ntoms(c::Week) = 604800000*value(c)\ntoms(c::Month) = 86400000.0*30.436875*value(c)\ntoms(c::Year) = 86400000.0*365.2425*value(c)\ntoms(c::CompoundPeriod) = isempty(c.periods)?0.0 : Float64(sum(toms,c.periods))\ndays(c::Millisecond) = div(value(c),86400000)\ndays(c::Second) = div(value(c),86400)\ndays(c::Minute) = div(value(c),1440)\ndays(c::Hour) = div(value(c),24)\ndays(c::Day) = value(c)\ndays(c::Week) = 7*value(c)\ndays(c::Year) = 365.2425*value(c)\ndays(c::Month) = 30.436875*value(c)\ndays(c::CompoundPeriod) = isempty(c.periods)?0.0 : Float64(sum(days,c.periods))\n", "meta": {"hexsha": "98a2efbd1c6f3f8a57603f48eb5b966a19653d90", "size": 16052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "base/dates/periods.jl", "max_stars_repo_name": "habemus-papadum/julia", "max_stars_repo_head_hexsha": "581a034dd6c5b027d64f624f97242e07ea3d613b", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "base/dates/periods.jl", "max_issues_repo_name": "habemus-papadum/julia", "max_issues_repo_head_hexsha": "581a034dd6c5b027d64f624f97242e07ea3d613b", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base/dates/periods.jl", "max_forks_repo_name": "habemus-papadum/julia", "max_forks_repo_head_hexsha": "581a034dd6c5b027d64f624f97242e07ea3d613b", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5649202733, "max_line_length": 111, "alphanum_fraction": 0.5561300772, "num_tokens": 4751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24840810015529}} {"text": "# differentiated shock capturing functions\n\n# main entry point\n\"\"\"\n Main function for assembling the shock capturing terms into the Jacobian.\n\n **Inputs**\n\n * mesh\n * sbp\n * eqn\n * opts\n * capture: an [`AbstractShockCapturing`](@ref)\n * assem: an [`AssembleElementData`](@ref)\n\"\"\"\nfunction applyShockCapturing_diff(mesh::AbstractMesh, sbp::AbstractOperator,\n eqn::EulerData, opts,\n capture::AbstractVolumeShockCapturing,\n assem::AssembleElementData)\n\n # nothing to do here, call the implementation\n sensor = getShockSensor(capture)\n calcShockCapturing_diff(mesh, sbp, eqn, opts, sensor, capture, assem)\n\n return nothing\nend\n\n\nfunction applyShockCapturing_diff(mesh::AbstractMesh, sbp::AbstractOperator,\n eqn::EulerData{Tsol, Tres}, opts,\n capture::AbstractFaceShockCapturing,\n assem::AssembleElementData) where {Tsol, Tres}\n\n sensor = getShockSensor(capture)\n _applyShockCapturing_diff(mesh, sbp, eqn, opts, sensor, capture, assem)\n\n return nothing\nend\n\nfunction _applyShockCapturing_diff(mesh::AbstractMesh, sbp::AbstractOperator,\n eqn::EulerData{Tsol, Tres}, opts,\n sensor::AbstractShockSensor,\n capture::AbstractFaceShockCapturing,\n assem::AssembleElementData) where {Tsol, Tres}\n\n if mesh.commsize > 1 && \n getParallelData(eqn.shared_data) != PARALLEL_DATA_ELEMENT\n\n error(\"shock capturing requires PARALLEL_DATA_ELEMENT\")\n end\n\n assertReceivesWaited(eqn.shared_data) # parallel communication for the regular\n # face integrals should already have\n # finished parallel communication\n\n\n # re-using the shockmesh from one iteration to the next makes allows\n # the algorithm to re-use existing arrays that depend on the number of\n # elements with the shock in it.\n shockmesh = eqn.params.shockmesh\n reset(shockmesh)\n for i=1:mesh.numEl\n q_i = ro_sview(eqn.q, :, :, i)\n coords_i = ro_sview(mesh.coords, :, :, i)\n dxidx_i = ro_sview(mesh.dxidx, :, :, :, i)\n jac_i = ro_sview(mesh.jac, :, i)\n\n val = isShockElement(eqn.params, sbp, sensor, q_i, i, coords_i, dxidx_i,\n jac_i)\n if val\n # push to shockmesh\n push!(shockmesh, i)\n end\n end\n\n completeShockElements(mesh, shockmesh)\n\n allocateArrays(capture, mesh, shockmesh)\n \n # call shock capturing scheme\n calcShockCapturing_diff(mesh, sbp, eqn, opts, capture, shockmesh, assem)\n\n return nothing\nend\n\n\n\n#------------------------------------------------------------------------------\n# revq\n\n\"\"\"\n Reverse mode of `applyShockCapturing` wrt q\n\n **Inputs**\n\n * mesh\n * sbp\n * eqn\n * opts\n * data: an [`AbstractShockCaputring`](@ref) object\n\"\"\"\nfunction applyShockCapturing_revq(mesh::AbstractMesh, sbp::AbstractOperator,\n eqn::EulerData, opts,\n capture::AbstractVolumeShockCapturing)\n\n # unlike AbstractFaceShockCapturing, nothing to do here\n\n sensor = getShockSensor(capture)\n calcShockCapturing_revq(mesh, sbp, eqn, opts, sensor, capture)\n\n return nothing\nend\n\n\n# Face shock capturing version\nfunction applyShockCapturing_revq(mesh::AbstractMesh, sbp::AbstractOperator,\n eqn::EulerData, opts,\n capture::AbstractFaceShockCapturing)\n\n sensor = getShockSensor(capture)\n shockmesh = eqn.params.shockmesh\n setupShockCapturing(mesh, sbp, eqn, opts, sensor, capture, shockmesh)\n\n # call shock capturing scheme\n calcShockCapturing_revq(mesh, sbp, eqn, opts, capture, shockmesh)\n\n\n return nothing\nend\n\n\n#------------------------------------------------------------------------------\n# revm\n\n\"\"\"\n Reverse mode of `applyShockCapturing` wrt metrics\n\n **Inputs**\n\n * mesh\n * sbp\n * eqn\n * opts\n * data: an [`AbstractShockCaputring`](@ref) object\n\"\"\"\nfunction applyShockCapturing_revm(mesh::AbstractMesh, sbp::AbstractOperator,\n eqn::EulerData, opts,\n capture::AbstractVolumeShockCapturing)\n\n # unlike AbstractFaceShockCapturing, nothing to do here\n\n sensor = getShockSensor(capture)\n initForRevm(sensor)\n calcShockCapturing_revm(mesh, sbp, eqn, opts, sensor, capture)\n finishRevm(mesh, sbp, eqn, opts, sensor)\n\n return nothing\nend\n\nfunction applyShockCapturing_revm(mesh::AbstractMesh, sbp::AbstractOperator,\n eqn::EulerData, opts,\n capture::AbstractFaceShockCapturing)\n\n # unlike AbstractFaceShockCapturing, nothing to do here\n\n sensor = getShockSensor(capture)\n shockmesh = eqn.params.shockmesh\n initForRevm(sensor)\n setupShockCapturing(mesh, sbp, eqn, opts, sensor, capture, shockmesh)\n calcShockCapturing_revm(mesh, sbp, eqn, opts, capture, shockmesh)\n finishRevm(mesh, sbp, eqn, opts, sensor)\n\n return nothing\nend\n\n\n", "meta": {"hexsha": "575bd8e3ac92f24da584464c42f57b8e498a71f8", "size": 5076, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solver/euler/shock_capturing_diff.jl", "max_stars_repo_name": "OptimalDesignLab/PDESolver.jl", "max_stars_repo_head_hexsha": "328ef45f764ab99a9d5cc3c5e4c0a4c56b263279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-10-30T17:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T10:29:45.000Z", "max_issues_repo_path": "src/solver/euler/shock_capturing_diff.jl", "max_issues_repo_name": "tangwang-USTC/PDESolver.jl", "max_issues_repo_head_hexsha": "328ef45f764ab99a9d5cc3c5e4c0a4c56b263279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 163, "max_issues_repo_issues_event_min_datetime": "2015-07-14T19:15:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-08T21:24:41.000Z", "max_forks_repo_path": "src/solver/euler/shock_capturing_diff.jl", "max_forks_repo_name": "tangwang-USTC/PDESolver.jl", "max_forks_repo_head_hexsha": "328ef45f764ab99a9d5cc3c5e4c0a4c56b263279", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-05-20T15:36:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T17:57:33.000Z", "avg_line_length": 28.6779661017, "max_line_length": 81, "alphanum_fraction": 0.6306146572, "num_tokens": 1237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24829817838058502}} {"text": "\"\"\"\n$(SIGNATURES)\n\nKinetic flux vector splitting (KFVS) flux\n\"\"\"\nfunction flux_kfvs!(\n face::Interface1F,\n ctrL::T,\n ctrR::T,\n gas::AbstractProperty,\n vs::AbstractVelocitySpace1D,\n p,\n dt = 1.0,\n) where {T<:ControlVolume1F}\n\n dxL, dxR = p[1:2]\n\n flux_kfvs!(\n face.fw,\n face.ff,\n ctrL.f + ctrL.sf * dxL,\n ctrR.f - ctrR.sf * dxR,\n vs.u,\n vs.weights,\n dt,\n ctrL.sf,\n ctrR.sf,\n )\n\n return nothing\n\nend\n\nfunction flux_kfvs!(\n face::Interface2F,\n ctrL::T,\n ctrR::T,\n gas::AbstractProperty,\n vs::AbstractVelocitySpace1D,\n p,\n dt = 1.0,\n) where {T<:ControlVolume2F}\n\n dxL, dxR = p[1:2]\n\n flux_kfvs!(\n face.fw,\n face.fh,\n face.fb,\n ctrL.h .+ ctrL.sb .* dxL,\n ctrL.b .+ ctrL.sb .* dxL,\n ctrR.h .- ctrR.sb .* dxR,\n ctrR.b .- ctrR.sb .* dxR,\n vs.u,\n vs.weights,\n dt,\n ctrL.sh,\n ctrL.sb,\n ctrR.sh,\n ctrR.sb,\n )\n\n return nothing\n\nend\n\nfunction flux_kfvs!(\n face::Interface1F,\n ctrL::T,\n ctrR::T,\n gas::AbstractProperty,\n vs::AbstractVelocitySpace2D,\n p,\n dt = 1.0,\n) where {T<:ControlVolume1F}\n\n dxL, dxR, len, n, dirc = p[1:5]\n sfL = @view ctrL.sf[:, :, dirc]\n sfR = @view ctrR.sf[:, :, dirc]\n\n flux_kfvs!(\n face.fw,\n face.ff,\n ctrL.f + sfL * dxL,\n ctrR.f - sfR * dxR,\n vs.u .* n[1] .+ vs.v .* n[2],\n vs.v .* n[1] .- vs.u .* n[2],\n vs.weights,\n dt,\n len,\n sfL,\n sfR,\n )\n\n face.fw .= global_frame(face.fw, n)\n\n return nothing\n\nend\n\nfunction flux_kfvs!(\n face::Interface2F,\n ctrL::T,\n ctrR::T,\n gas::AbstractProperty,\n vs::AbstractVelocitySpace2D,\n p,\n dt = 1.0,\n) where {T<:ControlVolume2F}\n\n dxL, dxR, len, n, dirc = p[1:5]\n shL = @view ctrL.sh[:, :, dirc]\n sbL = @view ctrL.sb[:, :, dirc]\n shR = @view ctrR.sh[:, :, dirc]\n sbR = @view ctrR.sb[:, :, dirc]\n\n flux_kfvs!(\n face.fw,\n face.fh,\n face.fb,\n ctrL.h .+ shL .* dxL,\n ctrL.b .+ sbL .* dxL,\n ctrR.h .- shR .* dxR,\n ctrR.b .- sbR .* dxR,\n vs.u .* n[1] .+ vs.v .* n[2],\n vs.v .* n[1] .- vs.u .* n[2],\n vs.weights,\n dt,\n len,\n shL,\n sbL,\n shR,\n sbR,\n )\n\n face.fw .= global_frame(face.fw, n)\n\n return nothing\n\nend\n\nfunction flux_kfvs!(\n face::Interface1F,\n ctrL::T,\n ctrR::T,\n gas::AbstractProperty,\n vs::AbstractVelocitySpace3D,\n p,\n dt = 1.0,\n) where {T<:ControlVolume1F}\n\n dxL, dxR = p[1:2]\n\n if length(p) == 2 || p[3] == 1\n flux_kfvs!(\n face.fw,\n face.ff,\n ctrL.f + ctrL.sf * dxL,\n ctrR.f - ctrR.sf * dxR,\n vs.u,\n vs.v,\n vs.w,\n vs.weights,\n dt,\n 1.0,\n ctrL.sf,\n ctrR.sf,\n )\n else\n len, n, dirc = p[3:5]\n sfL = @view ctrL.sf[:, :, :, dirc]\n sfR = @view ctrR.sf[:, :, :, dirc]\n\n flux_kfvs!(\n face.fw,\n face.ff,\n ctrL.f + sfL * dxL,\n ctrR.f - sfR * dxR,\n vs.u .* n[1] .+ vs.v .* n[2],\n vs.v .* n[1] .- vs.u .* n[2],\n vs.w,\n vs.weights,\n dt,\n len,\n sfL,\n sfR,\n )\n face.fw .= global_frame(face.fw, n[1], n[2])\n end\n\n return nothing\n\nend\n\n# ------------------------------------------------------------\n# Low-level backends\n# ------------------------------------------------------------\n\n\"\"\"\n$(SIGNATURES)\n\nKinetic flux vector splitting (KFVS) flux\n\"\"\"\nfunction flux_kfvs(\n fL::Y,\n fR::Y,\n u::AV{<:FN},\n dt,\n sfL = zero(fL)::Y,\n sfR = zero(fR)::Y,\n) where {Y<:AV{<:FN}}\n\n ff = similar(fL)\n flux_kfvs!(ff, fL, fR, u, dt, sfL, sfR)\n\n return ff\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\nKinetic flux vector splitting (KFVS) flux\n\n- @args: particle distribution functions and their left/right slopes\n- @args: particle velocity quadrature points and weights\n- @args: time step and cell size\n\n1F1V for pure DOM\n\"\"\"\nfunction flux_kfvs!(\n ff::AV{<:FN},\n fL::Y,\n fR::Y,\n u::AV{<:FN},\n dt,\n sfL = zero(fL)::Y,\n sfR = zero(fR)::Y,\n) where {Y<:AV{<:FN}} # 1F1V flux for pure DOM\n\n # upwind reconstruction\n δ = heaviside.(u)\n\n f = @. fL * δ + fR * (1.0 - δ)\n sf = @. sfL * δ + sfR * (1.0 - δ)\n\n # calculate flux\n @. ff = dt * u * f - 0.5 * dt^2 * u^2 * sf\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\n1F1V\n\"\"\"\nfunction flux_kfvs!(\n fw::AV{<:FN},\n ff::AV{<:FN},\n fL::Z,\n fR::Z,\n u::A,\n ω::A,\n dt,\n sfL = zero(fL)::Z,\n sfR = zero(fR)::Z,\n) where {Z<:AV{<:FN},A<:AV{<:FN}}\n\n # upwind reconstruction\n δ = heaviside.(u)\n\n f = @. fL * δ + fR * (1.0 - δ)\n sf = @. sfL * δ + sfR * (1.0 - δ)\n\n # calculate fluxes\n @. ff = dt * u * f - 0.5 * dt^2 * u^2 * sf\n flux_conserve!(fw, ff, u, ω)\n #fw[1] = dt * sum(ω .* u .* f) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sf)\n #fw[2] = dt * sum(ω .* u .^ 2 .* f) - 0.5 * dt^2 * sum(ω .* u .^ 3 .* sf)\n #fw[3] = dt * 0.5 * sum(ω .* u .^ 3 .* f) - 0.5 * dt^2 * 0.5 * sum(ω .* u .^ 4 .* sf)\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\nMixture\n\"\"\"\nfunction flux_kfvs!(\n fw::AM{<:FN},\n ff::AM{<:FN},\n fL::Z,\n fR::Z,\n u::A,\n ω::A,\n dt,\n sfL = zero(fL)::Z,\n sfR = zero(fR)::Z,\n) where {Z<:AM{<:FN},A<:AM{<:FN}}\n\n for j in axes(fw, 2)\n _fw = @view fw[:, j]\n _ff = @view ff[:, j]\n _fL = @view fL[:, j]\n _fR = @view fR[:, j]\n _u = @view u[:, j]\n _ω = @view ω[:, j]\n _sfL = @view sfL[:, j]\n _sfR = @view sfR[:, j]\n\n flux_kfvs!(_fw, _ff, _fL, _fR, _u, _ω, dt, _sfL, _sfR)\n end\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\n2F1V\n\"\"\"\nfunction flux_kfvs!(\n fw::AV{<:FN},\n fh::Y,\n fb::Y,\n hL::Z,\n bL::Z,\n hR::Z,\n bR::Z,\n u::A,\n ω::A,\n dt,\n shL = zero(hL)::Z,\n sbL = zero(bL)::Z,\n shR = zero(hR)::Z,\n sbR = zero(bR)::Z,\n) where {Y<:AV{<:FN},Z<:AV{<:FN},A<:AV{<:FN}}\n\n # upwind reconstruction\n δ = heaviside.(u)\n\n h = @. hL * δ + hR * (1.0 - δ)\n b = @. bL * δ + bR * (1.0 - δ)\n\n sh = @. shL * δ + shR * (1.0 - δ)\n sb = @. sbL * δ + sbR * (1.0 - δ)\n\n # calculate fluxes\n @. fh = dt * u * h - 0.5 * dt^2 * u^2 * sh\n @. fb = dt * u * b - 0.5 * dt^2 * u^2 * sb\n flux_conserve!(fw, fh, fb, u, ω)\n #=fw[1] = dt * sum(ω .* u .* h) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sh)\n fw[2] = dt * sum(ω .* u .^ 2 .* h) - 0.5 * dt^2 * sum(ω .* u .^ 3 .* sh)\n fw[3] =\n dt * 0.5 * (sum(ω .* u .^ 3 .* h) + sum(ω .* u .* b)) -\n 0.5 * dt^2 * 0.5 * (sum(ω .* u .^ 4 .* sh) + sum(ω .* u .^ 2 .* sb))=#\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\nMixture\n\"\"\"\nfunction flux_kfvs!(\n fw::AM{<:FN},\n fh::Y,\n fb::Y,\n hL::Z,\n bL::Z,\n hR::Z,\n bR::Z,\n u::A,\n ω::A,\n dt,\n shL = zero(hL)::Z,\n sbL = zero(bL)::Z,\n shR = zero(hR)::Z,\n sbR = zero(bR)::Z,\n) where {Y<:AM{<:FN},Z<:AM{<:FN},A<:AM{<:FN}}\n\n for j in axes(fw, 2)\n _fw = @view fw[:, j]\n _fh = @view fh[:, j]\n _fb = @view fb[:, j]\n _hL = @view hL[:, j]\n _bL = @view bL[:, j]\n _hR = @view hR[:, j]\n _bR = @view bR[:, j]\n _u = @view u[:, j]\n _ω = @view ω[:, j]\n _shL = @view shL[:, j]\n _sbL = @view sbL[:, j]\n _shR = @view shR[:, j]\n _sbR = @view sbR[:, j]\n\n flux_kfvs!(_fw, _fh, _fb, _hL, _bL, _hR, _bR, _u, _ω, dt, _shL, _sbL, _shR, _sbR)\n end\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\n3F1V @ Rykov\n\"\"\"\nfunction flux_kfvs!(\n fw::AV{<:FN},\n fh::Y,\n fb::Y,\n fr::Y,\n hL::Z,\n bL::Z,\n rL::Z,\n hR::Z,\n bR::Z,\n rR::Z,\n u::A,\n ω::A,\n dt,\n shL = zero(hL)::Z,\n sbL = zero(bL)::Z,\n srL = zero(rL)::Z,\n shR = zero(hR)::Z,\n sbR = zero(bR)::Z,\n srR = zero(rR)::Z,\n) where {Y<:AV{<:FN},Z<:AV{<:FN},A<:AV{<:FN}}\n\n # upwind reconstruction\n δ = heaviside.(u)\n\n h = @. hL * δ + hR * (1.0 - δ)\n b = @. bL * δ + bR * (1.0 - δ)\n r = @. rL * δ + rR * (1.0 - δ)\n\n sh = @. shL * δ + shR * (1.0 - δ)\n sb = @. sbL * δ + sbR * (1.0 - δ)\n sr = @. srL * δ + srR * (1.0 - δ)\n\n # macro fluxes\n fw[1] = dt * sum(ω .* u .* h) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sh)\n fw[2] = dt * sum(ω .* u .^ 2 .* h) - 0.5 * dt^2 * sum(ω .* u .^ 3 .* sh)\n fw[3] =\n dt * 0.5 * (sum(ω .* u .^ 3 .* h) + sum(ω .* u .* b)) -\n 0.5 * dt^2 * 0.5 * (sum(ω .* u .^ 4 .* sh) + sum(ω .* u .^ 2 .* sb))\n fw[4] = dt * 0.5 * sum(ω .* u .* r) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sr)\n\n # micro fluxes\n @. fh = dt * u * h - 0.5 * dt^2 * u^2 * sh\n @. fb = dt * u * b - 0.5 * dt^2 * u^2 * sb\n @. fr = dt * u * r - 0.5 * dt^2 * u^2 * sr\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\n1F3V\n\"\"\"\nfunction flux_kfvs!(\n fw::AV{<:FN},\n ff::AA{<:FN,3},\n fL::Z,\n fR::Z,\n u::A,\n v::A,\n w::A,\n ω::A,\n dt::Real,\n len = 1.0::Real,\n sfL = zero(fL)::Z,\n sfR = zero(fR)::Z,\n) where {Z<:AA{<:FN,3},A<:AA{<:FN,3}}\n\n # upwind reconstruction\n δ = heaviside.(u)\n\n f = @. fL * δ + fR * (1.0 - δ)\n sf = @. sfL * δ + sfR * (1.0 - δ)\n\n # calculate fluxes\n @. ff = (dt * u * f - 0.5 * dt^2 * u^2 * sf) * len\n flux_conserve!(fw, ff, u, v, w, ω)\n #=fw[1] = dt * sum(ω .* u .* f) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sf)\n fw[2] = dt * sum(ω .* u .^ 2 .* f) - 0.5 * dt^2 * sum(ω .* u .^ 3 .* sf)\n fw[3] = dt * sum(ω .* u .* v .* f) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* v .* sf)\n fw[4] = dt * sum(ω .* u .* w .* f) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* w .* sf)\n fw[5] =\n dt * 0.5 * sum(ω .* u .* (u .^ 2 .+ v .^ 2 .+ w .^ 2) .* f) -\n 0.5 * dt^2 * 0.5 * sum(ω .* u .^ 2 .* (u .^ 2 .+ v .^ 2 .+ w .^ 2) .* sf)\n @. fw *= len=#\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\n4F1V\n\"\"\"\nfunction flux_kfvs!(\n fw::AV{<:FN},\n fh0::Y,\n fh1::Y,\n fh2::Y,\n fh3::Y,\n h0L::Z,\n h1L::Z,\n h2L::Z,\n h3L::Z,\n h0R::Z,\n h1R::Z,\n h2R::Z,\n h3R::Z,\n u::A,\n ω::A,\n dt,\n sh0L = zero(h0L)::Z,\n sh1L = zero(h1L)::Z,\n sh2L = zero(h2L)::Z,\n sh3L = zero(h3L)::Z,\n sh0R = zero(h0R)::Z,\n sh1R = zero(h1R)::Z,\n sh2R = zero(h2R)::Z,\n sh3R = zero(h3R)::Z,\n) where {Y<:AV{<:FN},Z<:AV{<:FN},A<:AV{<:FN}}\n\n # upwind reconstruction\n δ = heaviside.(u)\n\n h0 = @. h0L * δ + h0R * (1.0 - δ)\n h1 = @. h1L * δ + h1R * (1.0 - δ)\n h2 = @. h2L * δ + h2R * (1.0 - δ)\n h3 = @. h3L * δ + h3R * (1.0 - δ)\n\n sh0 = @. sh0L * δ + sh0R * (1.0 - δ)\n sh1 = @. sh1L * δ + sh1R * (1.0 - δ)\n sh2 = @. sh2L * δ + sh2R * (1.0 - δ)\n sh3 = @. sh3L * δ + sh3R * (1.0 - δ)\n\n # calculate fluxes\n fw[1] = dt * sum(ω .* u .* h0) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sh0)\n fw[2] = dt * sum(ω .* u .^ 2 .* h0) - 0.5 * dt^2 * sum(ω .* u .^ 3 .* sh0)\n fw[3] = dt * sum(ω .* u .* h1) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sh1)\n fw[4] = dt * sum(ω .* u .* h2) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sh2)\n fw[5] =\n dt * 0.5 * (sum(ω .* u .^ 3 .* h0) + sum(ω .* u .* h3)) -\n 0.5 * dt^2 * 0.5 * (sum(ω .* u .^ 4 .* sh0) + sum(ω .* u .^ 2 .* sh3))\n\n @. fh0 = dt * u * h0 - 0.5 * dt^2 * u^2 * sh0\n @. fh1 = dt * u * h1 - 0.5 * dt^2 * u^2 * sh1\n @. fh2 = dt * u * h2 - 0.5 * dt^2 * u^2 * sh2\n @. fh3 = dt * u * h3 - 0.5 * dt^2 * u^2 * sh3\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\nMixture\n\"\"\"\nfunction flux_kfvs!(\n fw::AM{<:FN},\n fh0::Y,\n fh1::Y,\n fh2::Y,\n fh3::Y,\n h0L::Z,\n h1L::Z,\n h2L::Z,\n h3L::Z,\n h0R::Z,\n h1R::Z,\n h2R::Z,\n h3R::Z,\n u::A,\n ω::A,\n dt,\n sh0L = zero(h0L)::Z,\n sh1L = zero(h1L)::Z,\n sh2L = zero(h2L)::Z,\n sh3L = zero(h3L)::Z,\n sh0R = zero(h0R)::Z,\n sh1R = zero(h1R)::Z,\n sh2R = zero(h2R)::Z,\n sh3R = zero(h3R)::Z,\n) where {Y<:AM{<:FN},Z<:AM{<:FN},A<:AM{<:FN}}\n\n for j in axes(fw, 2)\n _fw = @view fw[:, j]\n _fh0 = @view fh0[:, j]\n _fh1 = @view fh1[:, j]\n _fh2 = @view fh2[:, j]\n _fh3 = @view fh3[:, j]\n\n flux_kfvs!(\n _fw,\n _fh0,\n _fh1,\n _fh2,\n _fh3,\n h0L[:, j],\n h1L[:, j],\n h2L[:, j],\n h3L[:, j],\n h0R[:, j],\n h1R[:, j],\n h2R[:, j],\n h3R[:, j],\n u[:, j],\n ω[:, j],\n dt,\n sh0L[:, j],\n sh1L[:, j],\n sh2L[:, j],\n sh3L[:, j],\n sh0R[:, j],\n sh1R[:, j],\n sh2R[:, j],\n sh3R[:, j],\n )\n end\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\n1F2V\n\"\"\"\nfunction flux_kfvs!(\n fw::AV{<:FN},\n ff::Union{AV{<:FN},AM{<:FN}},\n fL::Z,\n fR::Z,\n u::A,\n v::A,\n ω::A,\n dt,\n len,\n sfL = zero(fL)::Z,\n sfR = zero(fR)::Z,\n) where {Z<:Union{AV{<:FN},AM{<:FN}},A<:Union{AV{<:FN},AM{<:FN}}}\n\n #--- upwind reconstruction ---#\n δ = heaviside.(u)\n\n f = @. fL * δ + fR * (1.0 - δ)\n sf = @. sfL * δ + sfR * (1.0 - δ)\n\n #--- calculate fluxes ---#\n @. ff = (dt * u * f - 0.5 * dt^2 * u^2 * sf) * len\n flux_conserve!(fw, ff, u, v, ω)\n #=fw[1] = dt * sum(ω .* u .* f) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sf)\n fw[2] = dt * sum(ω .* u .^ 2 .* f) - 0.5 * dt^2 * sum(ω .* u .^ 3 .* sf)\n fw[3] = dt * sum(ω .* v .* u .* f) - 0.5 * dt^2 * sum(ω .* v .* u .^ 2 .* sf)\n fw[4] =\n dt * 0.5 * sum(ω .* u .* (u .^ 2 .+ v .^ 2) .* f) -\n 0.5 * dt^2 * 0.5 * sum(ω .* u .^ 2 .* (u .^ 2 .+ v .^ 2) .* sf)\n fw .*= len=#\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\n2F2V\n\"\"\"\nfunction flux_kfvs!(\n fw::AV{<:FN},\n fh::Y,\n fb::Y,\n hL::Z,\n bL::Z,\n hR::Z,\n bR::Z,\n u::A,\n v::A,\n ω::A,\n dt,\n len,\n shL = zero(hL)::Z,\n sbL = zero(bL)::Z,\n shR = zero(hR)::Z,\n sbR = zero(bR)::Z,\n) where {\n Y<:Union{AV{<:FN},AM{<:FN}},\n Z<:Union{AV{<:FN},AM{<:FN}},\n A<:Union{AV{<:FN},AM{<:FN}},\n}\n\n #--- upwind reconstruction ---#\n δ = heaviside.(u)\n\n h = @. hL * δ + hR * (1.0 - δ)\n b = @. bL * δ + bR * (1.0 - δ)\n sh = @. shL * δ + shR * (1.0 - δ)\n sb = @. sbL * δ + sbR * (1.0 - δ)\n\n #--- calculate fluxes ---#\n @. fh = (dt * u * h - 0.5 * dt^2 * u^2 * sh) * len\n @. fb = (dt * u * b - 0.5 * dt^2 * u^2 * sb) * len\n flux_conserve!(fw, fh, fb, u, v, ω)\n #=fw[1] = dt * sum(ω .* u .* h) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sh)\n fw[2] = dt * sum(ω .* u .^ 2 .* h) - 0.5 * dt^2 * sum(ω .* u .^ 3 .* sh)\n fw[3] = dt * sum(ω .* v .* u .* h) - 0.5 * dt^2 * sum(ω .* v .* u .^ 2 .* sh)\n fw[4] =\n dt * 0.5 * (sum(ω .* u .* (u .^ 2 .+ v .^ 2) .* h) + sum(ω .* u .* b)) -\n 0.5 *\n dt^2 *\n 0.5 *\n (sum(ω .* u .^ 2 .* (u .^ 2 .+ v .^ 2) .* sh) + sum(ω .* u .^ 2 .* sb))\n fw .*= len=#\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\n3F2V\n\"\"\"\nfunction flux_kfvs!(\n fw::AV{<:FN},\n fh0::Y,\n fh1::Y,\n fh2::Y,\n h0L::Z,\n h1L::Z,\n h2L::Z,\n h0R::Z,\n h1R::Z,\n h2R::Z,\n u::A,\n v::A,\n ω::A,\n dt,\n len,\n sh0L = zero(h0L)::Z,\n sh1L = zero(h1L)::Z,\n sh2L = zero(h2L)::Z,\n sh0R = zero(h0R)::Z,\n sh1R = zero(h1R)::Z,\n sh2R = zero(h2R)::Z,\n) where {Y<:AM{<:FN},Z<:AM{<:FN},A<:AM{<:FN}}\n\n #--- upwind reconstruction ---#\n δ = heaviside.(u)\n\n h0 = @. h0L * δ + h0R * (1.0 - δ)\n h1 = @. h1L * δ + h1R * (1.0 - δ)\n h2 = @. h2L * δ + h2R * (1.0 - δ)\n sh0 = @. sh0L * δ + sh0R * (1.0 - δ)\n sh1 = @. sh1L * δ + sh1R * (1.0 - δ)\n sh2 = @. sh2L * δ + sh2R * (1.0 - δ)\n\n #--- calculate fluxes ---#\n fw[1] = dt * sum(ω .* u .* h0) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sh0)\n fw[2] = dt * sum(ω .* u .^ 2 .* h0) - 0.5 * dt^2 * sum(ω .* u .^ 3 .* sh0)\n fw[3] = dt * sum(ω .* u .* v .* h0) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* v .* sh0)\n fw[4] = dt * sum(ω .* u .* h1) - 0.5 * dt^2 * sum(ω .* u .^ 2 .* sh1)\n fw[5] =\n dt * 0.5 * (sum(ω .* u .* (u .^ 2 .+ v .^ 2) .* h0) + sum(ω .* u .* h2)) -\n 0.5 *\n dt^2 *\n 0.5 *\n (sum(ω .* u .^ 2 .* (u .^ 2 .+ v .^ 2) .* sh0) + sum(ω .* u .^ 2 .* sh2))\n\n fw .*= len\n @. fh0 = (dt * u * h0 - 0.5 * dt^2 * u^2 * sh0) * len\n @. fh1 = (dt * u * h1 - 0.5 * dt^2 * u^2 * sh1) * len\n @. fh2 = (dt * u * h2 - 0.5 * dt^2 * u^2 * sh2) * len\n\n return nothing\n\nend\n\n\"\"\"\n$(SIGNATURES)\n\nMixture\n\"\"\"\nfunction flux_kfvs!(\n fw::AM{<:FN},\n fh0::Y,\n fh1::Y,\n fh2::Y,\n h0L::Z,\n h1L::Z,\n h2L::Z,\n h0R::Z,\n h1R::Z,\n h2R::Z,\n u::A,\n v::A,\n ω::A,\n dt,\n len,\n sh0L = zero(h0L)::Z,\n sh1L = zero(h1L)::Z,\n sh2L = zero(h2L)::Z,\n sh0R = zero(h0R)::Z,\n sh1R = zero(h1R)::Z,\n sh2R = zero(h2R)::Z,\n) where {Y<:AA{<:FN,3},Z<:AA{<:FN,3},A<:AA{<:FN,3}}\n\n #--- reconstruct initial distribution ---#\n δ = heaviside.(u)\n\n h0 = @. h0L * δ + h0R * (1.0 - δ)\n h1 = @. h1L * δ + h1R * (1.0 - δ)\n h2 = @. h2L * δ + h2R * (1.0 - δ)\n\n sh0 = @. sh0L * δ + sh0R * (1.0 - δ)\n sh1 = @. sh1L * δ + sh1R * (1.0 - δ)\n sh2 = @. sh2L * δ + sh2R * (1.0 - δ)\n\n for j = 1:2\n fw[1, j] =\n dt * sum(ω[:, :, j] .* u[:, :, j] .* h0[:, :, j]) -\n 0.5 * dt^2 * sum(ω[:, :, j] .* u[:, :, j] .^ 2 .* sh0[:, :, j])\n fw[2, j] =\n dt * sum(ω[:, :, j] .* u[:, :, j] .^ 2 .* h0[:, :, j]) -\n 0.5 * dt^2 * sum(ω[:, :, j] .* u[:, :, j] .^ 3 .* sh0[:, :, j])\n fw[3, j] =\n dt * sum(ω[:, :, j] .* v[:, :, j] .* u[:, :, j] .* h0[:, :, j]) -\n 0.5 * dt^2 * sum(ω[:, :, j] .* u[:, :, j] .^ 2 .* v[:, :, j] .* sh0[:, :, j])\n fw[4, j] =\n dt * sum(ω[:, :, j] .* u[:, :, j] .* h1[:, :, j]) -\n 0.5 * dt^2 * sum(ω[:, :, j] .* u[:, :, j] .^ 2 .* sh1[:, :, j])\n fw[5, j] =\n dt *\n 0.5 *\n (\n sum(\n ω[:, :, j] .* u[:, :, j] .* (u[:, :, j] .^ 2 .+ v[:, :, j] .^ 2) .*\n h0[:, :, j],\n ) + sum(ω[:, :, j] .* u[:, :, j] .* h2[:, :, j])\n ) -\n 0.5 *\n dt^2 *\n 0.5 *\n (\n sum(\n ω[:, :, j] .* u[:, :, j] .^ 2 .* (u[:, :, j] .^ 2 .+ v[:, :, j] .^ 2) .*\n sh0[:, :, j],\n ) + sum(ω[:, :, j] .* u[:, :, j] .^ 2 .* sh2[:, :, j])\n )\n\n @. fh0[:, :, j] =\n dt * u[:, :, j] * h0[:, :, j] - 0.5 * dt^2 * u[:, :, j]^2 * sh0[:, :, j]\n @. fh1[:, :, j] =\n dt * u[:, :, j] * h1[:, :, j] - 0.5 * dt^2 * u[:, :, j]^2 * sh1[:, :, j]\n @. fh2[:, :, j] =\n dt * u[:, :, j] * h2[:, :, j] - 0.5 * dt^2 * u[:, :, j]^2 * sh2[:, :, j]\n end\n\n @. fw *= len\n @. fh0 *= len\n @. fh1 *= len\n @. fh2 *= len\n\n return nothing\n\nend\n", "meta": {"hexsha": "75627c9fe114b03f189f3932fefe9c2b00d014f5", "size": 18986, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Flux/flux_kfvs.jl", "max_stars_repo_name": "vavrines/KineticBase.jl", "max_stars_repo_head_hexsha": "d00cefe073346a3bab3b4d3577a95631e320dc9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Flux/flux_kfvs.jl", "max_issues_repo_name": "vavrines/KineticBase.jl", "max_issues_repo_head_hexsha": "d00cefe073346a3bab3b4d3577a95631e320dc9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Flux/flux_kfvs.jl", "max_forks_repo_name": "vavrines/KineticBase.jl", "max_forks_repo_head_hexsha": "d00cefe073346a3bab3b4d3577a95631e320dc9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4531073446, "max_line_length": 92, "alphanum_fraction": 0.3758032234, "num_tokens": 8298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2482290706214576}} {"text": "\"\"\"\nmain : the code you run to double-encode... the \"main loop\" of optimization.\n\"\"\"\n\nmodule main\n\ninclude(\"utils.jl\")\ninclude(\"types.jl\")\ninclude(\"lookup.jl\")\ninclude(\"std_setup.jl\")\ninclude(\"math.jl\")\ninclude(\"optimize.jl\")\ninclude(\"mrf.jl\")\n\nusing ArgParse, Logging, JLD, StatsBase, Distributions, Random, Statistics\n\nfunction convert_to_saveable(cur_pop)\n\tnew_pop = types.SaveChrome[]\n\n\tfor indiv in cur_pop\n\t\tpush!(new_pop, types.SaveChrome(indiv.path, indiv.full_sequence,\n\t\t\t\t\t\t\t\t\t\tindiv.deg_nuc, indiv.deg_map, indiv.deg_trns, indiv.deg_trne, indiv.deg_d, indiv.deg_skip, indiv.deg_insert,\n\t\t\t\t\t\t\t\t\t\tindiv.mark_nuc, indiv.mark_map, indiv.mark_trns, indiv.mark_trne, indiv.mark_d, indiv.mark_skip, indiv.mark_insert,\n\t\t\t\t\t\t\t\t\t\tindiv.deg_prob, indiv.deg_base_E, indiv.deg_seq,\n\t\t\t\t\t\t\t\t\t\tindiv.mark_prob, indiv.mark_base_E, indiv.mark_seq, indiv.first_weight))\n\tend\n\n\treturn new_pop\nend\n\n\"\"\"\nset_up_and_optimize is the code that sets up appropriate information about genes we want to target for double-encoding and\norchestrates the initial HMM double-encoding solution and then iteratively improves on that with greedy pseudolikelihood improvements.\nCode also logs information through Logging package.\nGenes are often referred to as mark/deg. This is historic from times of thinking of \"marker\" genes and \"designated essential gene\".\nAt this point this distinction is not meaningful but is kept to avoid equally arbitrary x_name, y_name conventions.\nArguments:\n\tmark_name : gene ID for 'mark' gene. Needed as a key for looking up some values associated with genes in text files.\n\tdeg_name : gene ID for 'deg' gene.\n\tmark/deg_grem : path to MRF parameter files, usually a JLD/CSV file.\n\tmark/deg_hmm : path to HMM files, usually .hmm files.\n\tpop_size : size of population, i.e. number of individual HMM solutions to greedily optimize.\n\tframe : p1/p2.\n\tmax_iter : maximum number of iterations.\n\tX_range/Y_range: positions along gene to consider for double-encoding... useful if you want to restrict where double-encoding can occur.\n\t\t\t\t\t\tRanges are defined in terms of the end of the sequence, so if you have a 70 aa sequence you want to start at position 80,\n\t\t\t\t\t\tset the range to be something like 150:151. Generally some buffer around this value (i.e. 150:160) is useful.\n\t\t\t\t\t\tDon't set, or set to false if you don't care where the genes overlap.\n\"\"\"\nfunction set_up_and_optimize(log_io, rand_barcode, out_path, mark_name, deg_name, mark_grem, deg_grem, mark_hmm, deg_hmm, pop_size, frame, max_iter, X_range=false, Y_range=false; rand_weights = false, actually_mrf = true)\n\n\t@debug(\"Beginning run.\")\n\t@debug(Libc.strftime(time()))\n\t@debug(Libc.strftime(time()))\n\n\tprintln(\"The random barcode on this run is: $rand_barcode\")\n\t@debug(\"The random barcode on this run is: $rand_barcode\")\n\n\tdo_cull = false #culling reduces number of sequences we optimize over time. Just a trick to save time if you want top-performers only.\n\tfull_even_window = 20\n\thalf_window = div(full_even_window, 2) #window statistics to see if scores still decreasing (sometimes used).\n\tlast_few_sf = Float64[]\n\tlast_few_cs = Float64[]\n\n\t#Looks up mean/std. dev of family pseudolikelihoods, pre-computed.\n\tmu_mark, sig_mark = lookup.mu_sig(deg_name, \"psls/\")\n\tmu_deg, sig_deg = lookup.mu_sig(mark_name, \"psls/\")\n\n\t@debug(\"Stat param vars (mark / deg):\\t$(mu_mark)\\t$(sig_mark)\\t$(mu_deg)\\t$(sig_deg)\")\n\n\tif true #replacing try/catch.\n\t\tgen_samples = true #this is true if starting from scratch (general case), false if we have some candidates to optimize ahead of time.\n\t\tpopulation = types.Chromosome[]\n\t\tlocal mark_grem_prot, deg_grem_prot\n\t\tif !gen_samples\n\t\t\tpopulation = load(\"trpE_population.jld\")[\"population\"][1:100] #[1:100]\n\t\t\tmark_gremodel, deg_gremodel = std_setup.short_set_up(mark_name, deg_name, mark_grem, deg_grem, mark_hmm, deg_hmm, length(population), rand_barcode, frame)\n\t\t\tdeg_nNodes, mark_nNodes = deg_gremodel.nNodes, mark_gremodel.nNodes\n\t\telse\n\t\t\t#Generate population of sampled hmm starting points.\n\t\t\tif X_range == false || Y_range == false #we require both to be there...\n\t\t\t\t@debug(\"Doing standard full set up...\")\n\t\t\t\tmark_gremodel, deg_gremodel, population, mark_grem_prot, deg_grem_prot = std_setup.full_set_up(out_path, mark_name, mark_hmm, mark_grem, deg_name, deg_hmm, deg_grem, pop_size, 1200, 1200, rand_barcode, frame)\n\t\t\telse\n\t\t\t\t@debug(\"The x range is $X_range\")\n\t\t\t\t@debug(\"The y range is $Y_range\")\n\t\t\t\tmark_gremodel, deg_gremodel, population, mark_grem_prot, deg_grem_prot = std_setup.full_sample_set_up(out_path, mark_name, mark_hmm, mark_grem, deg_name, deg_hmm, deg_grem, pop_size, 1200, 1200, rand_barcode, X_range, Y_range, frame)\n\t\t\tend\n\t\t\tdeg_nNodes, mark_nNodes = deg_gremodel.nNodes, mark_gremodel.nNodes\n\t\tend\n\n\t\t#Look through generated candidates, check their fitness values and their correctness.\n\t\tsuccess_chrom, fdp, fmp, fitness_values, indie_deg_maps, indie_mark_maps, deg_ull, deg_pv_w1, deg_pv_w2, deg_prot_mat, mark_ull, mark_pv_w1, mark_pv_w2, mark_prot_mat = optimize.assess_founders(population, mark_gremodel.nNodes, mark_gremodel.w1, mark_gremodel.w2, deg_gremodel.nNodes, deg_gremodel.w1, deg_gremodel.w2)\n\n\t\t@debug(\"Num success... $(length(success_chrom))\")\n\n\t\tif actually_mrf\n\t\t\tfounding_fitness_values = fitness_values[1:end]\n\n\t\t\tmark_base_energy = mrf.basic_energy_calc(mark_grem_prot, mark_gremodel.w1, mark_gremodel.w2)\n\t\t\tdeg_base_energy = mrf.basic_energy_calc(deg_grem_prot, deg_gremodel.w1, deg_gremodel.w2)\n\n\t\t\t#Now we load this info into an ExChrome type object.\n\t\t\tcur_pop = types.ExChrome[]\n\t\t\tfor i in 1:length(success_chrom)\n\t\t\t\told = success_chrom[i]\n\t\t\t\tif rand_weights\n\t\t\t\t\tnew_chrom = types.ExChrome(old.path, old.full_sequence, old.deg_nuc, indie_deg_maps[i], old.deg_trns, old.deg_trne,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\told.deg_d, old.deg_skip, old.deg_insert, old.mark_nuc, indie_mark_maps[i], old.mark_trns, old.mark_trne,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\told.mark_d, old.mark_skip, old.mark_insert, fdp[i], deg_base_energy, deg_prot_mat[i:i, 1:end], utils.aa_vec_to_seq(deg_prot_mat[i:i, 1:end]), deg_ull[i], deg_pv_w1[i], deg_pv_w2[i:i, 1:end], fmp[i], mark_base_energy,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmark_prot_mat[i:i, 1:end], utils.aa_vec_to_seq(mark_prot_mat[i:i, 1:end]), mark_ull[i], mark_pv_w1[i], mark_pv_w2[i:i, 1:end], rand())\n\t\t\t\telse\n\t\t\t\t\tnew_chrom = types.ExChrome(old.path, old.full_sequence, old.deg_nuc, indie_deg_maps[i], old.deg_trns, old.deg_trne,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\told.deg_d, old.deg_skip, old.deg_insert, old.mark_nuc, indie_mark_maps[i], old.mark_trns, old.mark_trne,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\told.mark_d, old.mark_skip, old.mark_insert, fdp[i], deg_base_energy, deg_prot_mat[i:i, 1:end], utils.aa_vec_to_seq(deg_prot_mat[i:i, 1:end]), deg_ull[i], deg_pv_w1[i], deg_pv_w2[i:i, 1:end], fmp[i], mark_base_energy,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmark_prot_mat[i:i, 1:end], utils.aa_vec_to_seq(mark_prot_mat[i:i, 1:end]), mark_ull[i], mark_pv_w1[i], mark_pv_w2[i:i, 1:end], 0.5)\n\t\t\t\tend\n\t\t\t\tpush!(cur_pop, new_chrom)\n\t\t\tend\n\n\t\t\t#There are occasionally differences between HMM/MRF models of the proteins, mostly because HMMs are more flexible with insertions.\n\t\t\t#This generates mappings between positions in either data type.\n\t\t\tmark_hmm_to_grem_map = std_setup.get_explicit_mapping(mark_grem_prot, mark_hmm)\n\t\t\tdeg_hmm_to_grem_map = std_setup.get_explicit_mapping(deg_grem_prot, deg_hmm)\n\n\t\t\t@debug(\"Hey the explicit mapping for mark_hmm_to_grem is $mark_hmm_to_grem_map\")\n\t\t\t@debug(\"Hey the explicit mapping for deg_hmm_to_grem is $deg_hmm_to_grem_map\")\n\t\t\t#So now everything is in an extended chromosome object.\n\n\t\t\tchanged_seq = length(cur_pop)\n\t\t\tno_change_iters = 0\n\t\t\titer = 0;\n\n\t\t\t#Let's keep track of optimization history.\n\t\t\thistory_matrix = zeros(Float32, round(Int64, pop_size * 1.2), max_iter)\n\n\t\t\tprintln(\"Beginning long-range optimization.\")\n\t\t\t@debug(\"About to start optimization.\")\n\t\t\t@debug(Libc.strftime(time()))\n\n\t\t\tstop_early = false #a condition to evaluate every (few) iteration(s) to see if it's worth continuing a run. When true, we clean up and move to next gene pair.\n\t\t\tnot_worth_continuing = false\n\n\t\t\t#Okay let's set up the energy normal distributions...\n\n\t\t\tdeg_energy_mu, deg_energy_sig = lookup.get_energy_params(deg_name, \"energies/\")\n\t\t\tmark_energy_mu, mark_energy_sig = lookup.get_energy_params(mark_name, \"energies/\")\n\n\t\t\tmark_energy_normal = Normal(mark_energy_mu, mark_energy_sig)\n\t\t\tdeg_energy_normal = Normal(deg_energy_mu, deg_energy_sig)\n\n\t\t\twhile (iter == 0 || (iter < max_iter)) #&& !(stop_early) # && minimum((fitness_values)) > 400 && no_change_iters < 100)\n\t\t\t\tsfv = sort(fitness_values)\n\t\t\t\t#best_50 = sfv[50]\n\n\t\t\t\tif iter % 50 == 0\n\t\t\t\t\tprintln(\"Step $(iter) of $(max_iter)...\")\n\t\t\t\tend\n\t\t\t\t@debug(\"Iteration $iter out of $max_iter\")\n\t\t\t\t@debug(\"Mean fitness is: $(mean((fitness_values)))\")\n\t\t\t\t@debug(\"Bottom five are $(sfv[1:5])\")\n\t\t\t\t@debug(\"... and top five are $(sfv[end-5:end]).\")\n\t\t\t\t@debug(\"Number of sequences that were changed: $changed_seq\")\n\t\t\t\tflush(log_io)\n\n\t\t\t\t#iterated conditional modes, multi-site keep-track = icm_multi_kt. keep track = store values of changes to sequence.\n\t\t\t\tif do_cull\n\t\t\t\t\tif iter < div(max_iter, 4)\n\t\t\t\t\t\t#println(\"$iter : no cutoff\")\n\t\t\t\t\t\tcur_pop, changed_seq = optimize.icm_multi_kt(cur_pop, deg_gremodel, mark_gremodel) #, deg_energy_normal, mark_energy_normal)\n\t\t\t\t\telseif iter >= div(max_iter, 4) && iter < div(max_iter, 2)\n\t\t\t\t\t\t#println(\"$iter : cutoff is $(sfv[div(length(sfv), 2)])\")\n\t\t\t\t\t\tcur_pop, changed_seq = optimize.icm_multi_kt(cur_pop, deg_gremodel, mark_gremodel; score_cutoff = sfv[div(length(sfv), 2)])\n\t\t\t\t\telseif iter >= div(max_iter, 2)\n\t\t\t\t\t\t#println(\"$iter : cutoff is $(sfv[div(length(sfv), 4)])\")\n\t\t\t\t\t\tcur_pop, changed_seq = optimize.icm_multi_kt(cur_pop, deg_gremodel, mark_gremodel; score_cutoff = sfv[div(length(sfv), 4)])\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tcur_pop, changed_seq = optimize.icm_multi_kt(cur_pop, deg_gremodel, mark_gremodel)\n\t\t\t\tend\n\n\t\t\t\tfitness_values = optimize.assess_pop(cur_pop)\n\t\t\t\tsummed_fitness = sum(fitness_values) #one of the things we should be watching.\n\n\t\t\t\tpush!(last_few_sf, summed_fitness)\n\t\t\t\tpush!(last_few_cs, changed_seq)\n\n\t\t\t\tindiv_count = 1\n\t\t\t\tfor indiv in fitness_values #history matrix stores values of function being optimized over time.\n\t\t\t\t\thistory_matrix[indiv_count, iter + 1] = indiv\n\t\t\t\t\tindiv_count += 1\n\t\t\t\tend\n\n\t\t\t\t#This was originally just code to test the pseudolikelihoods decreasing correctly. It does.\n\t\t\t\t#Now it's still sorta somewhat useful to log a few values of sequences in both deg/mark as optimization goes.\n\t\t\t\tif (mod(iter, 50) == 0 && iter != 0)\n\t\t\t\t\t@debug(\"Second opinion, these should be ~0.\")\n\t\t\t\t\tfor i_count in 1:5\n\t\t\t\t\t\t#for the record this is not a good way to generate random numbers.\n\t\t\t\t\t\t#doesn't go from 1 to end.\n\t\t\t\t\t\ti = i_count #round(Int64, rand() * (length(cur_pop) - 1) + 1)\n\n\t\t\t\t\t\tbel_deg = cur_pop[i].deg_prob\n\t\t\t\t\t\tbel_mrk = cur_pop[i].mark_prob\n\t\t\t\t\t\t#Sort of assuming that end-1 is because of a \"*\" at stop codon being added.\n\t\t\t\t\t\tif length(strip(cur_pop[i].deg_seq, '*')) == deg_nNodes && length(strip(cur_pop[i].mark_seq, '*')) == mark_nNodes\n\t\t\t\t\t\t\tcal_deg = mrf.psl(strip(cur_pop[i].deg_seq, '*'), deg_gremodel.w1, deg_gremodel.w2, false)\n\t\t\t\t\t\t\tcal_mrk = mrf.psl(strip(cur_pop[i].mark_seq, '*'), mark_gremodel.w1, mark_gremodel.w2, false)\n\t\t\t\t\t\t\t@debug(\"DEG: $bel_deg vs. $cal_deg\")\n\t\t\t\t\t\t\t@debug(\"MRK: $bel_mrk vs. $cal_mrk\")\n\t\t\t\t\t\t\t@debug(abs(bel_deg - cal_deg) < 1e-2)\n\t\t\t\t\t\t\t@debug(abs(bel_mrk - cal_mrk) < 1e-2)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t@debug(\"Proteins not correct length!\")\n\t\t\t\t\t\t\t@debug(cur_pop[i].mark_seq)\n\t\t\t\t\t\t\t@debug(cur_pop[i].deg_seq)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tif changed_seq == 0\n\t\t\t\t\tno_change_iters += 1\n\t\t\t\telse\n\t\t\t\t\tno_change_iters = 0\n\t\t\t\tend\n\t\t\t\titer += 1\n\t\t\t\t@debug(\"\\n\")\n\t\t\tend\n\n\t\t\t#So we're done the iterated conditional modes step. Now we report everything...\n\t\t\t@debug(\"Done while loop...\")\n\t\t\t@debug(Libc.strftime(time()))\n\n\t\t\t@debug(\"Let us save the history matrix!\")\n\t\t\tsave(\"$out_path/$(mark_name)_$(deg_name)_$frame/opt_his_mat_$(rand_barcode).jld\", \"hist_mat\", history_matrix)\n\n\t\t\tdeg_significance = false\n\t\t\tmark_significance = false #this sees if we get any hits worth keeping at all. If yes we save full population.\n\t\t\tall_cal_deg_scores = Float64[]\n\t\t\tall_cal_mark_scores = Float64[]\n\t\t\t#If no we save just a few (top 10) individuals. These are top-6 overall + top-2 in deg and top-2 in mark.\n\t\t\tout_file = open(\"$out_path/$(mark_name)_$(deg_name)_$frame/all_final_fitness_$(rand_barcode).txt\", \"w\")\n\t\t\twrite(out_file, \"Ind. #\\tMark Score\\tDeg Score\\tMark Sign\\tDeg Sign\\n\")\n\t\t\tfor last_indi in 1:length(cur_pop)\n\t\t\t\trep_deg = cur_pop[last_indi].deg_prob\n\t\t\t\trep_mrk = cur_pop[last_indi].mark_prob\n\t\t\t\tif length(strip(cur_pop[last_indi].deg_seq, '*')) == deg_nNodes && length(strip(cur_pop[last_indi].mark_seq, '*')) == mark_nNodes\n\t\t\t\t\tcal_deg = abs(mrf.psl(strip(cur_pop[last_indi].deg_seq, '*'), deg_gremodel.w1, deg_gremodel.w2, false))\n\t\t\t\t\tcal_mrk = abs(mrf.psl(strip(cur_pop[last_indi].mark_seq, '*'), mark_gremodel.w1, mark_gremodel.w2, false))\n\t\t\t\t\tspecial_deg = \"-\"\n\t\t\t\t\tif cal_deg < mu_deg + sig_deg\n\t\t\t\t\t\tspecial_deg = \"***!\"\n\t\t\t\t\t\tdeg_significance = true\n\t\t\t\t\telseif cal_deg < mu_deg + 2*sig_deg\n\t\t\t\t\t\tspecial_deg = \"**.\"\n\t\t\t\t\t\tdeg_significance = true\n\t\t\t\t\telseif cal_deg < mu_deg + 3*sig_deg\n\t\t\t\t\t\tspecial_deg = \"*?\"\n\t\t\t\t\t\tdeg_significance = true\n\t\t\t\t\telseif cal_deg < mu_deg + 4*sig_deg #we don't mind keeping these.\n\t\t\t\t\t\tdeg_significance = true\n\t\t\t\t\tend\n\t\t\t\t\tspecial_mark = \"-\"\n\t\t\t\t\tif cal_mrk < mu_mark + sig_mark\n\t\t\t\t\t\tspecial_mark = \"***!\"\n\t\t\t\t\t\tmark_significance = true\n\t\t\t\t\telseif cal_mrk < mu_mark + 2*sig_mark\n\t\t\t\t\t\tspecial_mark = \"**.\"\n\t\t\t\t\t\tmark_significance = true\n\t\t\t\t\telseif cal_mrk < mu_mark + 3*sig_mark\n\t\t\t\t\t\tspecial_mark = \"*?\"\n\t\t\t\t\t\tmark_significance = true\n\t\t\t\t\telseif cal_mrk < mu_mark + 4*sig_mark #we don't mind keeping these.\n\t\t\t\t\t\tmark_significance = true\n\t\t\t\t\tend\n\t\t\t\t\tpush!(all_cal_mark_scores, cal_mrk)\n\t\t\t\t\tpush!(all_cal_deg_scores, cal_deg)\n\t\t\t\t\twrite(out_file, \"$(last_indi)\\t$(cal_mrk)\\t$(cal_deg)\\t$special_mark\\t$special_deg\\n\")\n\t\t\t\telse\n\t\t\t\t\tpush!(all_cal_mark_scores, Inf)\n\t\t\t\t\tpush!(all_cal_deg_scores, Inf)\n\t\t\t\t\twrite(out_file, \"$(last_indi)\\t-1.0\\t-1.0\\t/\\t/\\n\")\n\t\t\t\tend\n\t\t\tend\n\t\t\tclose(out_file)\n\n\t\t\tcal_deg_p = sortperm(all_cal_deg_scores)\n\t\t\tcal_mark_p = sortperm(all_cal_mark_scores)\n\t\t\tcal_both_p = sortperm(fitness_values)\n\n\t\t\t@debug(Libc.strftime(time()))\n\t\t\tif true #deg_significance && mark_significance\n\t\t\t\t@debug(\"Let's save our optimized population...\")\n\t\t\t\tsaved_pop = convert_to_saveable(cur_pop)\n\t\t\t\tsave(\"$out_path/$(mark_name)_$(deg_name)_$frame/saved_pop_$(rand_barcode).jld\", \"variants\", saved_pop)\n\t\t\telse #We want just a subset.\n\t\t\t\t@debug(\"We'll save 12 interesting members of the population.\")\n\t\t\t\tselected_pop = ExChrome[]\n\t\t\t\tfor ijk in 1:3\n\t\t\t\t\tpush!(selected_pop, cur_pop[cal_deg_p[ijk]])\n\t\t\t\t\tpush!(selected_pop, cur_pop[cal_mark_p[ijk]])\n\t\t\t\tend\n\t\t\t\tfor ijk in 1:6\n\t\t\t\t\tpush!(selected_pop, cur_pop[cal_both_p[ijk]])\n\t\t\t\tend\n\t\t\t\tsave(\"$out_path/$(mark_name)_$(deg_name)_$frame/top_pop_$(rand_barcode).jld\", \"variants\", selected_pop)\n\t\t\tend\n\n\t\t\t@debug(\"And we'll also output our top twelve sequences...\")\n\t\t\tout_file = open(\"$out_path/$(mark_name)_$(deg_name)_$frame/top_twelve_$(rand_barcode).fa\", \"w\")\n\n\t\t\tfor ijk in 1:3\n\t\t\t\tdeg_ind = cal_deg_p[ijk]\n\t\t\t\twrite(out_file, \">TOP_DEG_d (ind $deg_ind ) (fit: $(fitness_values[deg_ind])) (deg: $(all_cal_deg_scores[deg_ind])) (mark: $(all_cal_mark_scores[deg_ind]))\\n\")\n\t\t\t\twrite(out_file, \"$(cur_pop[deg_ind].deg_seq)\\n\")\n\t\t\t\twrite(out_file, \">TOP_DEG_m (ind $deg_ind ) (fit: $(fitness_values[deg_ind])) (deg: $(all_cal_deg_scores[deg_ind])) (mark: $(all_cal_mark_scores[deg_ind]))\\n\")\n\t\t\t\twrite(out_file, \"$(cur_pop[deg_ind].mark_seq)\\n\")\n\t\t\tend\n\t\t\tfor ijk in 1:3\n\t\t\t\tdeg_ind = cal_mark_p[ijk]\n\t\t\t\twrite(out_file, \">TOP_MARK_d (ind $deg_ind ) (fit: $(fitness_values[deg_ind])) (deg: $(all_cal_deg_scores[deg_ind])) (mark: $(all_cal_mark_scores[deg_ind]))\\n\")\n\t\t\t\twrite(out_file, \"$(cur_pop[deg_ind].deg_seq)\\n\")\n\t\t\t\twrite(out_file, \">TOP_MARK_m (ind $deg_ind ) (fit: $(fitness_values[deg_ind])) (deg: $(all_cal_deg_scores[deg_ind])) (mark: $(all_cal_mark_scores[deg_ind]))\\n\")\n\t\t\t\twrite(out_file, \"$(cur_pop[deg_ind].mark_seq)\\n\")\n\t\t\tend\n\t\t\tfor ijk in 1:6\n\t\t\t\tdeg_ind = cal_both_p[ijk]\n\t\t\t\twrite(out_file, \">TOP_GEN_d (ind $deg_ind ) (fit: $(fitness_values[deg_ind])) (deg: $(all_cal_deg_scores[deg_ind])) (mark: $(all_cal_mark_scores[deg_ind]))\\n\")\n\t\t\t\twrite(out_file, \"$(cur_pop[deg_ind].deg_seq)\\n\")\n\t\t\t\twrite(out_file, \">TOP_GEN_m (ind $deg_ind ) (fit: $(fitness_values[deg_ind])) (deg: $(all_cal_deg_scores[deg_ind])) (mark: $(all_cal_mark_scores[deg_ind]))\\n\")\n\t\t\t\twrite(out_file, \"$(cur_pop[deg_ind].mark_seq)\\n\")\n\t\t\tend\n\t\t\tclose(out_file)\n\t\tend\n\n\t\t@debug(\"REALLY DONE!\")\n\n\t\t@debug(Libc.strftime(time()))\n\n\tend\nend\n\nfunction parse_commandline()\n\ts = ArgParseSettings()\n\t@add_arg_table s begin\n\t\t\"commands\"\n\t\t\thelp = \"positional argument, path to file with tab-delimited commands to run (default: example.txt)\"\n\t\t\tdefault = \"example.txt\"\n\t\t\"--num\"\n\t\t\thelp = \"optional, experimentally used for running multiple jobs at once\"\n\t\t\tdefault = \"0\"\n\t\t\"--threads\"\n\t\t\thelp = \"optional, experimentally used for running multiple jobs at once\"\n\t\t\tdefault = \"1\"\n\tend\n\treturn parse_args(s)\nend\n\nfunction run_file()\n\tparsed_args = parse_commandline()\n\n\tcommand_file = parsed_args[\"commands\"]\n\tnum = parsed_args[\"num\"]\n\tthreads = parsed_args[\"threads\"]\n\n\trun_i = parse(Int64, num)\n\tNUM_THREADS = parse(Int64, threads)\n\n\tif NUM_THREADS > 1\n\t\tsleep(rand() * 2) #randomly delay start to de-synchronize starts of runs.\n\tend\n\n\tif isfile(command_file)\n\t\tin_file = open(command_file)\n\t\tin_read = readlines(in_file)\n\t\tclose(in_file)\n\n\t\t#This is an additional file that records errors independent of individual log files.\n\t\tproblem_file = open(\"problem_runs_$(run_i).txt\", \"w\")\n\n\t\tline_count = 0\n\t\tfor line in in_read #\n\t\t\tline_count += 1\n\t\t\tif line[1] != '#' && (line_count % NUM_THREADS == run_i)\n\t\t\t\ttry\n\t\t\t\t\trun_args = split(line, \"\\t\")\n\t\t\t\t\tout_dir, short, long, short_jld, long_jld, short_hmm, long_hmm, pop_size, frame, num_iter = run_args\n\n\t\t\t\t\trand_barcode = Random.randstring()\n\n\t\t\t\t\tthe_out_path = \"$out_dir/$(short)_$(long)_$frame/\"\n\t\t\t\t\tif !(isdir(the_out_path))\n\t\t\t\t\t\trun(`mkdir -p $the_out_path`)\n\t\t\t\t\tend\n\n\t\t\t\t\tlog_io = open(\"$out_dir/$(short)_$(long)_$frame/log_$(rand_barcode).txt\", \"w+\")\n\n\t\t\t\t\tlogger = SimpleLogger(log_io, Logging.Debug)\n\t\t\t\t\tglobal_logger(logger)\n\n\t\t\t\t\twith_logger(logger) do\n\t\t\t\t\t\tpop_size = parse(Int64, pop_size)\n\t\t\t\t\t\tnum_iter = parse(Int64, num_iter)\n\t\t\t\t\t\tset_up_and_optimize(log_io, rand_barcode, out_dir, short, long, short_jld, long_jld, short_hmm, long_hmm, pop_size, frame, num_iter)\n\t\t\t\t\tend\n\n\t\t\t\t\tflush(log_io)\n\t\t\t\t\tclose(log_io)\n\t\t\t\tcatch y\n\t\t\t\t\twrite(problem_file, \"$line $y\")\n\t\t\t\tend\n\n\t\t\tend\n\t\tend\n\t\tclose(problem_file)\n\telse\n\t\tprintln(\"$command_file does not exist. Exiting.\")\n\tend\n\nend\n\n@time run_file()\n\nend\n", "meta": {"hexsha": "39d5ca3475b2f46473cf54eecae9ff20ad142d00", "size": 18925, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "main/main.jl", "max_stars_repo_name": "khyox/CAMEOS", "max_stars_repo_head_hexsha": "a675e24a31716231484c8d2959f93c90059504df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-21T00:04:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T00:04:36.000Z", "max_issues_repo_path": "main/main.jl", "max_issues_repo_name": "BiosecSFA/CAMEOS", "max_issues_repo_head_hexsha": "a675e24a31716231484c8d2959f93c90059504df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/main.jl", "max_forks_repo_name": "BiosecSFA/CAMEOS", "max_forks_repo_head_hexsha": "a675e24a31716231484c8d2959f93c90059504df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6344339623, "max_line_length": 320, "alphanum_fraction": 0.7076882431, "num_tokens": 5530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.41869690935568676, "lm_q1q2_score": 0.24814766765434407}} {"text": "module FieldModule\n\nusing Printf: @printf\nusing UserExceptionModule: UserError\nusing CoordsModule: Coords,LatLonCoords,DirectionIndicator,Generic1DCoords\nusing GridModule: Grid,LatLonGrid, for_all, wrap_coords, coords_in_grid,for_all_with_line_breaks\nusing GridModule: UnstructuredGrid\nusing InteractiveUtils: subtypes\nusing SpecialDirectionCodesModule\nusing MergeTypesModule\nimport Base.maximum\nimport Base.*\nimport Base./\nimport Base.+\nimport Base.==\nimport Base.isapprox\nimport Base.fill!\nimport Base.show\nimport Base.round\nimport Base.convert\nimport Base.sum\nimport Base.Broadcast\nusing InteractiveUtils\n\nabstract type Field{T} end\n\nfunction get(field::Field{T},coords::Coords) where {T}\n throw(UserError())\nend\n\nfunction set!(field::Field,coords::Coords)\n throw(UserError())\nend\n\nfunction fill!(field::Field)\n throw(UserError())\nend\n\nfunction maximum(field::Field)\n throw(UserError())\nend\n\nfunction +(lfield::Field,rfield::Field)\n throw(UserError())\nend\n\nfunction *(lfield::Field,value::T) where {T<:Number}\n throw(UserError())\nend\n\nfunction /(lfield::Field,value::T) where {T<:Number}\n throw(UserError())\nend\n\nfunction ==(lfield::Field,rfield::Field)\n throw(UserError())\nend\n\nfunction sum(field::Field)\n throw(UserError())\nend\n\n# This could be done by overloading broadcast but this is overcomplicated\n# Assumes result is fractional and hence returns a field of floating point numbers\nfunction elementwise_divide(lfield::Field{T},rfield::Field{T}) where {T}\n return Field{Float64}(lfield.grid,lfield.data./rfield.data)::Field{Float64}\nend\n\n# This could be done by overloading broadcast but this is overcomplicated\nfunction equals(lfield::Field,value::T) where {T}\n return Field{Bool}(lfield.grid,Bool.(lfield.data .== value))::Field{Bool}\nend\n\nfunction isapprox(lfield::Field,rfield::Field;\n rtol::Real=atol>0 ? 0 : sqrt(eps),\n atol::Real,nans::Bool)\n throw(UserError())\nend\n\nfunction invert(field::Field)\n throw(UserError())\nend\n\nfunction add_offset(field::Field,offset::T,skip_offset_on_values::Vector{T}) where {T}\n throw(UserError())\nend\n\nfunction round!(type::DataType,field::Field{T}) where {T}\n throw(UserError())\nend\n\nfunction add_offset(field::T2,offset::T,skip_offset_on_values::Vector{T}) where {T,T2<:Field{T}}\n for_all(get_grid(field)) do coords::Coords\n if ! (field(coords) in skip_offset_on_values)\n set!(field,coords,field(coords)+offset)\n end\n end\nend\n\nfunction divide(field::T2,divisor::T) where {T,T2<:Field{T}}\n for_all(get_grid(field)) do coords::Coords\n set!(field,coords,field(coords)/divisor)\n end\nend\n\nget_grid(obj::T) where {T <: Field} =\n obj.grid::Grid\n\nget_data(obj::T) where {T <: Field} =\n obj.data::Array\n\nfunction repeat(field::Field{T}, count::Integer) where {T}\n array::Array{Field{T},1} = Array{Field{T},1}(undef,count)\n for i in 1:count\n array[i] = deepcopy(field)\n end\n return array\nend\n\n\nstruct LatLonField{T} <: Field{T}\n data::Array{T,2}\n grid::LatLonGrid\n function LatLonField{T}(grid::LatLonGrid,value::T) where {T}\n data::Array{T,2} = value == zero(T) ? zeros(T,grid.nlat,grid.nlon) :\n ones(T,grid.nlat,grid.nlon)*value\n return new(data,grid)\n end\n function LatLonField{MergeTypes}(grid::LatLonGrid,value::MergeTypes)\n data::Array{MergeTypes,2} = zeros(MergeTypes,grid.nlat,grid.nlon)\n fill!(data,value)\n return new(data,grid)\n end\n function LatLonField{T}(grid::LatLonGrid,values::AbstractArray{T,2}) where {T}\n if size(values,1) != grid.nlat ||\n size(values,2) != grid.nlon\n error(\"Values provided don't match selected grid\")\n end\n return new(values,grid)\n end\n function LatLonField{MergeTypes}(grid::LatLonGrid,\n integer_field::LatLonField{T}) where {T<:Signed}\n grid = get_grid(integer_field)\n merge_type_field = LatLonField{MergeTypes}(grid,null_mtype)\n for_all(grid) do coords::Coords\n element::MergeTypes = MergeTypes(get(integer_field,coords))\n set!(merge_type_field,coords,element)\n end\n return new(merge_type_field.data,grid)\n end\nend\n\nstruct UnstructuredField{T} <: Field{T}\n data::Array{T,1}\n grid::UnstructuredGrid\n function UnstructuredField{T}(grid::UnstructuredGrid,value::T) where {T}\n data::Array{T,1} = value == zero(T) ? zeros(T,grid.ncells) :\n ones(T,grid.ncells)*value\n return new(data,grid)\n end\n function UnstructuredField{MergeTypes}(grid::UnstructuredGrid,value::MergeTypes)\n data::Array{MergeTypes,1} = zeros(MergeTypes,grid.ncells)\n fill!(data,value)\n return new(data,grid)\n end\n function UnstructuredField{T}(grid::UnstructuredGrid,values::AbstractArray{T,1}) where {T}\n if size(values,1) != grid.ncells\n error(\"Values provided don't match selected grid\")\n end\n return new(values,grid)\n end\n function UnstructuredField{MergeTypes}(grid::UnstructuredGrid,\n integer_field::UnstructuredField{T}) where {T<:Signed}\n grid = get_grid(integer_field)\n merge_type_field = UnstructuredField{MergeTypes}(grid,null_mtype)\n for_all(grid) do coords::Coords\n element::MergeTypes = MergeTypes(get(integer_field,coords))\n set!(merge_type_field,coords,element)\n end\n return new(merge_type_field.data,grid)\n end\nend\n\nLatLonField{T}(grid::LatLonGrid) where {T} = LatLonField{T}(grid,zeros(T,grid.nlat,grid.nlon))\n\nUnstructuredField{T}(grid::UnstructuredGrid) where {T} = UnstructuredField{T}(grid,zeros(T,grid.ncells))\n\nField{T}(grid::LatLonGrid,value::T) where {T} = LatLonField{T}(grid::LatLonGrid,value::T)\nField{T}(grid::LatLonGrid) where {T} = LatLonField{T}(grid::LatLonGrid)\n\nField{T}(grid::UnstructuredGrid,value::T) where {T} = UnstructuredField{T}(grid::UnstructuredGrid,\n value::T)\nField{T}(grid::UnstructuredGrid) where {T} = UnstructuredField{T}(grid::UnstructuredGrid)\n\nField{T}(grid::LatLonGrid,values::AbstractArray{T,2}) where {T} =\n LatLonField{T}(grid::LatLonGrid,values::AbstractArray{T,2})\nField{T}(grid::UnstructuredGrid,values::AbstractArray{T,1}) where {T} =\n UnstructuredField{T}(grid::UnstructuredGrid,\n values::AbstractArray{T,1})\n\nField{MergeTypes}(grid::LatLonGrid,integer_field::LatLonField{T}) where {T<:Signed} =\n LatLonField{MergeTypes}(grid::LatLonGrid,integer_field::LatLonField{T})\nField{MergeTypes}(grid::UnstructuredGrid,integer_field::UnstructuredField{T}) where {T<:Signed} =\n UnstructuredField{MergeTypes}(grid::UnstructuredGrid,integer_field::UnstructuredField{T})\n\nconvert(::Type{Field{MergeTypes}},x::T2) where {T<:Signed,T2<:Field{T}} = Field{MergeTypes}(get_grid(x),x)\n\n\nfunction (latlon_field::LatLonField{T})(coords::LatLonCoords) where {T}\n return latlon_field.data[coords.lat,coords.lon]::T\nend\n\nfunction get(latlon_field::LatLonField{T},coords::LatLonCoords) where {T}\n return latlon_field(coords)::T\nend\n\nfunction set!(latlon_field::LatLonField{T},coords::LatLonCoords,value::T) where {T}\n latlon_field.data[coords.lat,coords.lon] = value\nend\n\nfunction +(lfield::LatLonField{T},rfield::LatLonField{T}) where {T}\n return LatLonField{T}(lfield.grid,lfield.data + rfield.data)\nend\n\nfunction *(lfield::Field,value::T) where {T<:Number}\n return LatLonField{T}(lfield.grid,lfield.data * value)\nend\n\nfunction /(lfield::Field,value::T) where {T<:Number}\n return LatLonField{T}(lfield.grid,lfield.data / value)\nend\n\nfunction ==(lfield::LatLonField{T},rfield::LatLonField{T}) where {T}\n return (lfield.data == rfield.data)::Bool\nend\n\nLatLonFieldOrUnstructuredField = Union{LatLonField{T},UnstructuredField{T}} where {T}\n\nfunction sum(field::T) where {T<:LatLonFieldOrUnstructuredField}\n return sum(field.data)\nend\n\nfunction isapprox(lfield::LatLonField{T},rfield::LatLonField{T};\n rtol::Real=atol>0 ? 0 : sqrt(eps),\n atol::Real=0.0,nans::Bool=false) where {T}\n return isapprox(lfield.data,rfield.data,\n rtol=rtol,atol=atol,nans=nans)::Bool\nend\n\nfunction invert(field::LatLonField{T}) where {T}\n return LatLonField{T}(field.grid,.!field.data)\nend\n\nfunction round(type::DataType,field::LatLonField{T}) where {T}\n return LatLonField{type}(field.grid,round.(type,field.data))\nend\n\nfunction maximum(field::LatLonField)\n return maximum(field.data)\nend\n\nfunction show(io::IO,field::LatLonField{T}) where {T <: Number}\n for_all_with_line_breaks(field.grid) do coords::Coords\n if T <: AbstractFloat\n @printf(io,\"%6.2f\",field(coords))\n elseif T == Bool\n print(io,field(coords) ? \" X \" : \" - \")\n else\n @printf(io,\"%4.0f\",field(coords))\n end\n print(io,\" \")\n end\nend\n\nfunction fill!(field::LatLonField{T},value::T) where {T}\n return fill!(field.data,value)\nend\n\nfunction (unstructured_field::UnstructuredField{T})(coords::Generic1DCoords) where {T}\n return unstructured_field.data[coords.index]::T\nend\n\nfunction get(unstructured_field::UnstructuredField{T},coords::Generic1DCoords) where {T}\n return unstructured_field(coords)::T\nend\n\nfunction set!(unstructured_field::UnstructuredField{T},coords::Generic1DCoords,value::T) where {T}\n unstructured_field.data[coords.index] = value\nend\n\nfunction +(lfield::UnstructuredField{T},rfield::UnstructuredField{T}) where {T}\n return UnstructuredField{T}(lfield.grid,lfield.data + rfield.data)\nend\n\nfunction *(lfield::UnstructuredField,value::T) where {T<:Number}\n return UnstructuredField{T}(lfield.grid,lfield.data * value)\nend\n\nfunction /(lfield::UnstructuredField,value::T) where {T<:Number}\n return UnstructuredField{T}(lfield.grid,lfield.data / value)\nend\n\nfunction ==(lfield::UnstructuredField{T},rfield::UnstructuredField{T}) where {T}\n return (lfield.data == rfield.data)::Bool\nend\n\nfunction isapprox(lfield::UnstructuredField{T},rfield::UnstructuredField{T};\n rtol::Real=atol>0 ? 0 : sqrt(eps),\n atol::Real=0.0,nans::Bool=false) where {T}\n return isapprox(lfield.data,rfield.data,\n rtol=rtol,atol=atol,nans=nans)::Bool\nend\n\nfunction invert(field::UnstructuredField{T}) where {T}\n return UnstructuredField{T}(field.grid,.!field.data)\nend\n\nfunction round(type::DataType,field::UnstructuredField{T}) where {T}\n return UnstructuredField{type}(field.grid,round.(type,field.data))\nend\n\nfunction maximum(field::UnstructuredField)\n return maximum(field.data)\nend\n\nfunction fill!(field::UnstructuredField{T},value::T) where {T}\n return fill!(field.data,value)\nend\n\nfunction show(io::IO,field::UnstructuredField{T}) where {T <: Number}\n for_all_with_line_breaks(field.grid) do coords::Coords\n if T <: AbstractFloat\n @printf(io,\"%6.2f\",field(coords))\n elseif T == Bool\n print(io,field(coords) ? \" X \" : \" - \")\n else\n @printf(io,\"%4.0f\",field(coords))\n end\n print(io,\" \")\n end\nend\n\nabstract type DirectionIndicators end\n\nfunction get(field::DirectionIndicators,coords::Coords)\n throw(UserError())\nend\n\nfunction set!(field::DirectionIndicators,coords::Coords)\n throw(UserError())\nend\n\nstruct LatLonDirectionIndicators <: DirectionIndicators\n next_cell_coords::Array{LatLonField{Int64},1}\n function LatLonDirectionIndicators(dir_based_rdirs::LatLonField{Int64})\n grid = dir_based_rdirs.grid\n nlat = dir_based_rdirs.grid.nlat\n nlon = dir_based_rdirs.grid.nlon\n lat_indices::LatLonField{Int64} =\n LatLonField{Int64}(grid,zeros(Int64,nlat,nlon))\n lon_indices::LatLonField{Int64} =\n LatLonField{Int64}(grid,zeros(Int64,nlat,nlon))\n for_all(grid) do coords::LatLonCoords\n dir_based_rdir::Int64 = dir_based_rdirs(coords)\n if dir_based_rdir == dir_based_indicator_ocean\n set!(lat_indices,coords,coord_base_indicator_ocean)\n set!(lon_indices,coords,coord_base_indicator_ocean)\n elseif dir_based_rdir == dir_based_indicator_outflow\n set!(lat_indices,coords,coord_base_indicator_outflow)\n set!(lon_indices,coords,coord_base_indicator_outflow)\n elseif dir_based_rdir == dir_based_indicator_truesink\n set!(lat_indices,coords,coord_base_indicator_truesink)\n set!(lon_indices,coords,coord_base_indicator_truesink)\n elseif dir_based_rdir == dir_based_indicator_lake\n set!(lat_indices,coords,coord_base_indicator_lake)\n set!(lon_indices,coords,coord_base_indicator_lake)\n elseif 1 <= dir_based_rdir <= 9\n lat_offset::Int64 = dir_based_rdir in [7,8,9] ? -1 :\n (dir_based_rdir in [1,2,3] ? 1 : 0)\n lon_offset::Int64 = dir_based_rdir in [7,4,1] ? -1 :\n (dir_based_rdir in [9,6,3] ? 1 : 0)\n destination_coords::LatLonCoords = LatLonCoords(coords.lat + lat_offset,\n coords.lon + lon_offset)\n destination_coords = wrap_coords(grid,destination_coords)\n if ! coords_in_grid(grid,destination_coords)\n error(\"Direction based direction indicator points out of grid\")\n end\n set!(lat_indices,coords,destination_coords.lat)\n set!(lon_indices,coords,destination_coords.lon)\n else\n error(\"Invalid direction based direction indicator\")\n end\n end\n new(LatLonField{Int64}[lat_indices,lon_indices])\n end\nend\n\nstruct UnstructuredFieldDirectionIndicators <: DirectionIndicators\n next_cell_coords::UnstructuredField{Int64}\nend\n\nfunction (latlon_direction_indicators::LatLonDirectionIndicators)(coords::LatLonCoords)\n return DirectionIndicator(LatLonCoords(latlon_direction_indicators.next_cell_coords[1](coords),\n latlon_direction_indicators.next_cell_coords[2](coords)))\nend\n\nfunction get(latlon_direction_indicators::LatLonDirectionIndicators,coords::LatLonCoords)\n return latlon_direction_indicators(coords)\nend\n\n\nfunction set!(latlon_direction_indicators::DirectionIndicators,\n coords::LatLonCoords,direction::DirectionIndicator)\n next_cell_coords = get_next_cell_coords(direction,coords)\n set!(latlon_direction_indicators.next_cell_coords[1],coords,next_cell_coords.lat)\n set!(latlon_direction_indicators.next_cell_coords[2],coords,next_cell_coords.lon)\nend\n\nfunction fill!(field::LatLonField{T},value::T) where {T}\n return fill!(field.data,value)\nend\n\nstruct UnstructuredDirectionIndicators <: DirectionIndicators\n next_cell_coords::UnstructuredField{Int64}\nend\n\nfunction (unstructured_direction_indicators::UnstructuredDirectionIndicators)(coords::Generic1DCoords)\n return DirectionIndicator(Generic1DCoords(unstructured_direction_indicators.next_cell_coords(coords)))\nend\n\nfunction get(unstructured_direction_indicators::UnstructuredDirectionIndicators,\n coords::Generic1DCoords)\n return unstructured_direction_indicators(coords)\nend\n\n\nfunction set!(unstructured_direction_indicators::UnstructuredDirectionIndicators,\n coords::Generic1DCoords,direction::DirectionIndicator)\n next_cell_coords = get_next_cell_coords(direction,coords)\n set!(unstructured_direction_indicators.next_cell_coords,coords,next_cell_coords.index)\nend\n\n\n#Cannot define functors on abstract types in Julia yet. Use this\n#workaround - needs to be at end of file as it only acts on subtypes of\n#Field/DirectionIndicators that are already defined\n\nfor T in subtypes(Field)\n @eval function (field::$T)(coords::Coords) throw(UserError()) end\nend\n\nfor T in subtypes(DirectionIndicators)\n @eval function (direction_indicators::$T)(coords::Coords) throw(UserError()) end\nend\n\nend\n", "meta": {"hexsha": "298b8157bf6849ee3a002f8535d9c2f055f66f66", "size": 15516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Dynamic_HD_Julia_Code/FieldModule.jl", "max_stars_repo_name": "ThomasRiddick/DynamicHD", "max_stars_repo_head_hexsha": "bff378a49ff6c709dc59c2d6835852e1083df20a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-04T07:51:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T07:51:18.000Z", "max_issues_repo_path": "Dynamic_HD_Julia_Code/FieldModule.jl", "max_issues_repo_name": "ThomasRiddick/DynamicHD", "max_issues_repo_head_hexsha": "bff378a49ff6c709dc59c2d6835852e1083df20a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-27T22:12:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T10:16:47.000Z", "max_forks_repo_path": "Dynamic_HD_Julia_Code/FieldModule.jl", "max_forks_repo_name": "ThomasRiddick/DynamicHD", "max_forks_repo_head_hexsha": "bff378a49ff6c709dc59c2d6835852e1083df20a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9518599562, "max_line_length": 106, "alphanum_fraction": 0.722093323, "num_tokens": 4123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.24801663865091342}} {"text": "include(\"../../configs.jl\")\ninclude(\"../core/metrics.jl\")\n\nfunction encode_gt_and_get_indices(gt, priors, losses, pos_thold, neg_thold)\n variances = size(priors, 2) == 102300 ? [1, 1] : [0.2, 0.1]\n iou_vals = iou(gt[1:4,:], _to_min_max_form(priors))\n # selecting positive prior boxes \n pos_pairs = findall(iou_vals .>= pos_thold)\n pos_gt = zeros(15, length(pos_pairs))\n gt_idx = getindex.(pos_pairs, [1 2])[:, 2]\n prior_idx = getindex.(pos_pairs, [1 2])[:, 1]\n \n # enlarging gt matrix to match selected anchors\n pos_gt .= gt[:,gt_idx]\n num_poses = length(prior_idx)\n if num_poses == 0 \n # if no positive anchor boxes are found, then no loss will be calculated\n return nothing, nothing, nothing\n end\n \n #selecting negative prior boxes\n max_prior_vals, max_prior_idx = findmax(iou_vals; dims=2) \n neg_indices = getindex.(findall(max_prior_vals .<= neg_thold), [1 2])[:,1]\n neg_indices = neg_indices[sortperm(losses[neg_indices])]\n \n neg_cnt = ohem_ratio * num_poses\n neg_cnt = neg_cnt < 1 ? 1 : neg_cnt \n neg_indices = neg_indices[1:neg_cnt]\n \n # gt bbox conversion\n selected_priors = priors[:,prior_idx]\n \n pos_gt[1:4,:] = _to_center_length_form(pos_gt[1:4,:])\n pos_gt[3:4,:] = log.(pos_gt[3:4,:] ./ selected_priors[3:4,:]) ./ variances[1]\n \n pos_gt[1:2,:] = (pos_gt[1:2,:] .- selected_priors[1:2,:]) ./ (variances[2] .* selected_priors[3:4,:])\n pos_gt[5:6,:] = (pos_gt[5:6,:] .- selected_priors[1:2,:]) ./ (variances[2] .* selected_priors[3:4,:])\n pos_gt[7:8,:] = (pos_gt[7:8,:] .- selected_priors[1:2,:]) ./ (variances[2] .* selected_priors[3:4,:])\n pos_gt[9:10,:] = (pos_gt[9:10,:] .- selected_priors[1:2,:]) ./ (variances[2] .* selected_priors[3:4,:])\n pos_gt[11:12,:] = (pos_gt[11:12,:] .- selected_priors[1:2,:]) ./ (variances[2] .* selected_priors[3:4,:])\n pos_gt[13:14,:] = (pos_gt[13:14,:] .- selected_priors[1:2,:]) ./ (variances[2] .* selected_priors[3:4,:])\n \n # print(\"Pos_indices: \", prior_idx, \"&& Neg_indices: \", neg_indices, \"\\n\")\n return pos_gt, prior_idx, neg_indices\nend\n\nfunction nms(scores, points; thold=0.4)\n x1 = points[1,:]; y1 = points[2,:]; x2 = points[3,:]; y2 = points[4,:];\n \n areas = (x2 - x1) .* (y2 - y1)\n order = sortperm(scores, rev=true) \n keep = []\n \n for i in order\n if keep == []\n push!(keep, i)\n else\n iou_vals = iou(points[:,i:i], points[:,keep])\n val, idx = findmax(iou_vals, dims=1)\n if val[1] <= thold\n push!(keep, i)\n end\n end \n end\n return keep\nend\n\n\"\"\"\nConversion from: \n(center_x, center_y, width, height) --> (min_x, min_y, max_x, max_y)\n\"\"\"\nfunction _to_min_max_form(boxes)\n init_shape = size(boxes)\n boxes = reshape(boxes, (size(boxes)[1], prod(size(boxes)[2:end]))) # converting to 2D\n half_lens = boxes[3:4,:] ./ 2\n return reshape(cat(boxes[1:2,:] .- half_lens, boxes[1:2,:] .+ half_lens, dims=1), init_shape)\nend\n\n\"\"\"\nConversion from: \n(min_x, min_y, max_x, max_y) --> (center_x, center_y, width, height)\n\"\"\"\nfunction _to_center_length_form(boxes)\n init_shape = size(boxes)\n boxes = reshape(boxes, (size(boxes)[1], prod(size(boxes)[2:end]))) # converting to 2D\n lengths = boxes[3:4,:] .- boxes[1:2,:]\n return reshape(cat(boxes[1:2,:] .+ (lengths ./ 2), lengths, dims=1), init_shape)\nend\n\n\n\"\"\"\nReturns the anchor boxes with their center_x, center_y, width, height information.\n\"\"\"\nfunction _get_priorboxes(num_anchors, anchor_info, img_size)\n feature_maps = [Int(ceil(img_size / scale[\"stride\"])) for scale in anchor_info]\n num_proposals = num_anchors * sum([i*i for i in feature_maps])\n anchors = zeros(4, num_proposals)\n\n counter = 1\n for (idx, f) in enumerate(feature_maps)\n scaler = anchor_info[idx][\"stride\"]\n for h in 1:f \n cy = (h - 0.5) * scaler\n for w in 1:f\n cx = (w - 0.5) * scaler\n for s in anchor_info[idx][\"anchors\"]\n anchors[:,counter] = [cx cy s s]\n counter += 1\n end\n end\n end\n end\n return anchors\nend\n\n\"\"\"\nDecoder functions:\nThe main motivation is that the network does not directly predict the proposals but\nthe combination of prediction and prior anchor box style and rescaling gives the actual\nbounding box and landmark coordinations.\n\"\"\"\nfunction decode_points(bboxes, landmarks, priors)\n if length(size(priors)) == 2\n priors = reshape(priors, (size(priors)..., 1))\n end\n decoded_bboxes = _decode_bboxes(bboxes, priors)\n decoded_landmarks = _decode_landmarks(landmarks, priors)\n return decoded_bboxes, decoded_landmarks\nend\n\n\nfunction _decode_bboxes(bbox, priors)\n variances = size(priors, 2) > 100000 ? [1, 1] : [0.2, 0.1]\n if length(size(priors)) == 2\n priors = reshape(priors, (size(priors)..., 1))\n end\n centers = priors[1:2,:,:] .+ bbox[1:2,:,:] .* variances[2] .* priors[3:4,:,:]\n lengths = exp.(bbox[3:4,:,:] .* variances[1]) .* priors[3:4,:,:]\n return cat(centers, lengths, dims=1)\nend\n\nfunction _decode_landmarks(landmarks, priors)\n variances = size(priors, 2) > 100000 ? [1, 1] : [0.2, 0.1]\n if length(size(priors)) == 2\n priors = reshape(priors, (size(priors)..., 1))\n end\n lm1 = priors[1:2,:,:] .+ landmarks[1:2,:,:] .* variances[2] .* priors[3:4,:,:]\n lm2 = priors[1:2,:,:] .+ landmarks[3:4,:,:] .* variances[2] .* priors[3:4,:,:]\n lm3 = priors[1:2,:,:] .+ landmarks[5:6,:,:] .* variances[2] .* priors[3:4,:,:]\n lm4 = priors[1:2,:,:] .+ landmarks[7:8,:,:] .* variances[2] .* priors[3:4,:,:]\n lm5 = priors[1:2,:,:] .+ landmarks[9:10,:,:] .* variances[2] .* priors[3:4,:,:]\n return cat(lm1, lm2, lm3, lm4, lm5, dims=1)\nend", "meta": {"hexsha": "cd20edc63893c707f7aa8f84c49f9fe31d0889ef", "size": 5834, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BBTNet/utils/box_processes.jl", "max_stars_repo_name": "barisbatuhan/retinaface", "max_stars_repo_head_hexsha": "9139fb0135d119022be4e529876147d094330e31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BBTNet/utils/box_processes.jl", "max_issues_repo_name": "barisbatuhan/retinaface", "max_issues_repo_head_hexsha": "9139fb0135d119022be4e529876147d094330e31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BBTNet/utils/box_processes.jl", "max_forks_repo_name": "barisbatuhan/retinaface", "max_forks_repo_head_hexsha": "9139fb0135d119022be4e529876147d094330e31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1307189542, "max_line_length": 109, "alphanum_fraction": 0.5987315735, "num_tokens": 1904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.2479907167165414}} {"text": "module TiledArrays\n\n# Ceiling division\ncdiv(a::Integer, b::Integer) = cdiv(promote(a, b)...)\ncdiv(a::T, b::T) where {T<:Integer} = one(T) + div(a - one(T), b)\n\n# Opposite of `Base.tail`.\n# Keep all but the last element in a tuple.\nhead(x, y...) = (x, head(y...)...)\nhead(x) = ()\n\n# # Type traits for describing if there's something scary going on with the strides.\n# # For now, assume memory strides are monotonically increasing such that the underlying\n# # array describes a contiguous block of memory.\n# abstract type AbstractStrides end\n# struct DenseStrides <: AbstractStrides end\n\nstruct Tile\n dim::Int\n size::Int\nend\nBase.show(io::IO, tile::Tile) = print(io, \"Tile($(tile.dim), $(tile.size))\")\n\n# Note that `NonBlockedLayout <: MemoryLayout`, but without any tiling, allowing\n# for specific handling of the easy case.\nconst MemoryLayout{N} = Tuple{Vararg{Union{Int,Tile},N}} where {N}\nconst NonBlockedLayout{N} = Tuple{Vararg{Int,N}} where {N}\n\n# Utility function for removing all \"Tile\"s from the front of an array.\nfunction strip_leading_tiles(x::Tuple{Vararg{Union{Int,Tile},N}}) where {N}\n return strip_leading_tiles(x...)\nend\n\nfunction strip_leading_tiles(x::Tile, y::Vararg{Union{Int,Tile},N}) where {N}\n return strip_leading_tiles(y...)\nend\n\nstrip_leading_tiles(x::Int, y::Vararg{Union{Int,Tile},N}) where {N} = (x, y...)\n\n#####\n##### Layout Validation\n#####\n\n# Validation\n# Invariants to maintain:\n#\n# 1. We must have exactly one occurance of an Integer index.\n# 2. All `Tile` indexes must occur BEFORE the corresponding Integer index.\n# 3. Each `Tile` index must have a corresponding Integer index\nfunction validate(layout::MemoryLayout{N}) where {N}\n @nospecialize\n\n # Pass 1 - Make sure there are no nonpositive indices.\n # Also, find the maximum index.\n maximum_index = 0\n for desc in layout\n if isa(desc, Int)\n desc <= 0 && error(\"Found non-positive index: $desc\")\n maximum_index = max(maximum_index, desc)\n elseif isa(desc, Tile)\n desc.dim <= 0 && error(\"Found non-positive tile index: $desc\")\n maximum_index = max(maximum_index, desc.dim)\n else\n # Should never happen due to type restrictions.\n error(\"Unreachable reached\")\n end\n end\n\n # Pass 2 - Check invariants.\n for index in Base.OneTo(maximum_index)\n saw_int = false\n saw_tile = false\n for desc in layout\n if isa(desc, Int) && desc == index\n saw_int && error(\"Integer index $index occurs more than once!\")\n saw_int = true\n elseif isa(desc, Tile) && desc.dim == index\n saw_int && error(\n \"Integer index $index occurs before its corresponding tile index!\"\n )\n saw_tile = true\n end\n end\n # We saw a tile but not an int, throw error\n saw_tile &&\n !saw_int &&\n error(\"Found tile with index $index with no corresponding Int\")\n\n # We didn't find anything\n !saw_tile && !saw_int && error(\"Found no entry with index $index\")\n end\n return true\nend\n\n#####\n##### Adjust indexes for padding.\n#####\n\nunchecked_divrem(x::Int, y::Int) = (Base.sdiv_int(x, y), Base.srem_int(x, y))\n\n# Note: not necessarily safe since we are using the unchecked integer division functions.\n# Also, `index` should already be converted from index-1 to index-0.\nfunction adjust_for_padding(\n size::NTuple{N,Int}, padded_size::NTuple{N,Int}, index::NTuple{N,Int}\n) where {N}\n return ntuple(i -> adjust_for_padding(size[i], padded_size[i], index[i]), Val(N))\nend\n\nfunction adjust_for_padding(size::Int, padded_size::Int, index::Int)\n size == padded_size && return index\n a, b = unchecked_divrem(index, size)\n return (a * padded_size) + b\nend\n\n#####\n##### Index Conversion Logic\n#####\n\n# Expand the index according to the given layout.\n# NOTE: `I` should be post padding adjusting if necessary.\nfunction splitindex(::Val{T}, I::Tuple{Vararg{Int,N}}) where {T,N}\n return _splitindex(T, I)\nend\n\n# Work from the first index to the last.\n# At each step, strip off the index we processed from `layout` and recurse.\n#\n# When `layout[1]` is an Integer, we just return the corresponding index from `I`.\n#\n# When `layout[1]` is a Tile, then we grab the corresponding index from `I`,\n# `divrem` that value, then reconstruct `I` with the reduced index.\n#\n# NB: This depends on Julia's super agressive constant propagation heuristics when dealing\n# with simplifying tuple recursive functions to generate great assembly code.\n@inline function _splitindex(layout::MemoryLayout, I::Tuple{Vararg{Int,N}}) where {N}\n v, _I = process(layout[1], I)\n return (v, _splitindex(Base.tail(layout), _I)...)\nend\n\n### Base case - last item should never be a `Tile`.\n@inline function _splitindex(layout::Tuple{Int}, I::Tuple{Vararg{Int,N}}) where {N}\n return (I[layout[1]],)\nend\n\nfunction _splitindex(::Tuple{Tile}, I::Tuple{Vararg{Int,N}}) where {N}\n return error(\"Malformed memory layout with a `Tile` in the tail position!\")\nend\n\n@inline process(x::Int, I::Tuple{Vararg{Int,N}}) where {N} = (I[x], I)\n@inline function process(x::Tile, I::Tuple{Vararg{Int,N}}) where {N}\n outer, inner = unchecked_divrem(I[x.dim], x.size)\n return (inner, ntuple(i -> i == x.dim ? outer : I[i], Val(N)))\nend\n\n#####\n##### Obtaining full dimensions\n#####\n\n# Move layout from type domain to value domain, providing \"const\" information to the\n# compiler.\n@inline dims(valT::Val{T}, size::Tuple{Vararg{Int,N}}) where {T,N} = _dims(T, size)\n\n@inline function _dims(layout::MemoryLayout, size::Tuple{Vararg{Int,N}}) where {N}\n v, _size = _dimcheck(layout[1], size)\n return (v, _dims(Base.tail(layout), _size)...)\nend\n\n# Bottom of recursion.\n@inline _dims(layout::Tuple{Int}, size::Tuple{Vararg{Int,N}}) where {N} = (size[layout[1]],)\n\n@inline _dimcheck(x::Int, size::Tuple{Vararg{Int,N}}) where {N} = (size[x], size)\n@inline function _dimcheck(x::Tile, size::Tuple{Vararg{Int,N}}) where {N}\n newdim = cdiv(size[x.dim], x.size)\n return (x.size, ntuple(i -> i == x.dim ? newdim : size[i], Val(N)))\nend\n\n#####\n##### Users of \"dims\"\n#####\n\n# NB: Cannot extend `Base.strides` because a `MemoryLayout` can potentially just be a tuple\n# of Ints, so we'd be committing type piracy.\nfunction _strides(valT::Val{T}, size::Tuple{Vararg{Int,N}}) where {T,N}\n # Drop the last value from `dims`.\n return cumprod((one(Int), head(dims(valT, size)...)...))\nend\n\nfunction fullsize(valT::Val{T}, size::Tuple{Vararg{Int,N}}) where {T,N}\n # Constant propagation to the rescue.\n # If the layout is non-blocked, just standard or permuted, then there is no\n # over-allocation necessary.\n if isa(T, NonBlockedLayout)\n return prod(size)\n # Otherwise, we need to compute the full dimensions, which could include zero padding\n # to keep the inner blocksizes constant.\n else\n return prod(dims(valT, size))\n end\nend\n\n#####\n##### Linear Offset\n#####\n\nfunction getoffset(\n valT::Val{T},\n size::Tuple{Vararg{Int,N}}, # Padded Size\n I::Tuple{Vararg{Int,N}}, # Post-padded index\n) where {T,N}\n Base.@_inline_meta\n strides = _strides(valT, size)\n index = splitindex(valT, I)\n offset = zero(Int)\n for i in eachindex(strides)\n @inbounds offset += strides[i] * index[i]\n end\n return offset\nend\n\n# Generates indices into a tiled array.\n# Parameters:\n#\n# `L`: Layout type parameter.\n# `N`: Number of Dims.\nstruct TiledIndexer{L,N}\n size::NTuple{N,Int}\n padded_size::NTuple{N,Int}\nend\n\nfunction TiledIndexer{L}(size::NTuple{N,Int}, padded_size::NTuple{N,Int}) where {L,N}\n return TiledIndexer{L,N}(size, padded_size)\nend\n\nfunction genindex(x::TiledIndexer{L,N}, I::NTuple{N,Int}) where {L,N}\n return 1 + getoffset(\n Val(L), x.padded_size, adjust_for_padding(x.size, x.padded_size, I .- 1)\n )\nend\n\n# function genindex(x::TiledIndexer{L,N,Nothing}, I::NTuple{N,Int}) where {L,N}\n# return getoffset(Val(N), x.size, I)\n# end\n\n# #####\n# ##### Tiled Array\n# #####\n#\n# struct TiledArray{T,L,N} <: AbstractArray{T,N}\n# parent::Vector{T}\n# size::NTuple{N,Int}\n# end\n# Base.parent(A::TiledArray) = A.parent\n#\n# function TiledArray{T,L}(::UndefInitializer, size::Tuple{Vararg{Int,N}}) where {T,L,N}\n# # Allocate enough room for the whole layout.\n# parent = Vector{T}(undef, fullsize(Val(L), size))\n# return TiledArray{T,L,N}(parent, size)\n# end\n#\n# layout(::Type{<:TiledArray{<:Any,L}}) where {L} = L\n# layout(x::T) where {T<:TiledArray} = layout(T)\n# vlayout(x) = Val(layout(x))\n#\n# # Array interface\n# @inline Base.size(x::TiledArray) = x.size\n# Base.IndexStyle(::Type{<:TiledArray}) = Base.IndexCartesian()\n# Base.@propagate_inbounds function Base.getindex(\n# A::TiledArray{T,L,N}, I::Vararg{Int,N}; strides = nothing\n# ) where {T,L,N}\n# @boundscheck checkbounds(A, I...)\n# offset = getoffset(vlayout(A), size(A), I, strides) + one(Int)\n# return @inbounds(getindex(parent(A), offset))\n# end\n#\n# Base.@propagate_inbounds function Base.setindex!(\n# A::TiledArray{T,L,N}, v, I::Vararg{Int,N}; strides = nothing\n# ) where {T,L,N}\n# @boundscheck checkbounds(A, I...)\n# offset = getoffset(vlayout(A), size(A), I, strides) + one(Int)\n# return @inbounds setindex!(parent(A), v, offset)\n# end\n\nend # module\n", "meta": {"hexsha": "73f4407ba5c75a19484bc7b71db8e19b1616d152", "size": 9398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tiledarrays.jl", "max_stars_repo_name": "hildebrandmw/OneDNN.jl", "max_stars_repo_head_hexsha": "0319b93e5ddab16ff3a331cab1a6894b382a30b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tiledarrays.jl", "max_issues_repo_name": "hildebrandmw/OneDNN.jl", "max_issues_repo_head_hexsha": "0319b93e5ddab16ff3a331cab1a6894b382a30b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tiledarrays.jl", "max_forks_repo_name": "hildebrandmw/OneDNN.jl", "max_forks_repo_head_hexsha": "0319b93e5ddab16ff3a331cab1a6894b382a30b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0915492958, "max_line_length": 93, "alphanum_fraction": 0.6522664397, "num_tokens": 2671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.24795610126175754}} {"text": "# ======================\n# Dependencies\n# ======================\n\nusing LinearAlgebra, SparseArrays, # modules from the Julia standard library\n Reexport, # see @reexport macro below\n RecipesBase, # plotting\n Parameters, # structs with kwargs\n StaticArrays, # statically sized arrays\n RecursiveArrayTools # vector of arrays type\n\n# manipulate function definition expressions\nusing ExprTools: splitdef, combinedef\n\n# the reexport macro ensures that the names exported by the following libraries\n# are made available after loading ReachabilityAnalysis\n@reexport using HybridSystems,\n IntervalMatrices,\n LazySets,\n MathematicalSystems,\n TaylorIntegration\n\n# required to avoid conflicts with MathematicalSystems\nusing LazySets: LinearMap, AffineMap, ResetMap\n\n# required to avoid conflicts with IntervalMatrices\nusing LazySets: Interval, radius, sample, ∅, dim, scale, scale!\n\n# in-place set operations\nusing LazySets: linear_map!\n\n# LazySets internal functions frequently used\nusing LazySets.Arrays: projection_matrix, SingleEntryVector\nusing LazySets.Approximations: AbstractDirections\nusing LazySets: @commutative\n\n# aliases for intervals\nconst IM = IntervalMatrices\nimport IntervalArithmetic\nconst IA = IntervalArithmetic\nconst TimeInterval = IA.Interval{Float64}\nimport TaylorModels\nconst TM = TaylorModels\n\n# method extensions for Taylor model reach-sets\nimport TaylorModels: domain, remainder, polynomial, get_order, evaluate\n\n# aliases for set types\nconst CPA = CartesianProductArray\n\n# convenience union for dispatch on structs that are admissible as initial sets or inputs\nconst AdmissibleSet = Union{LazySet, UnionSet, UnionSetArray, IA.Interval, IA.IntervalBox}\n\n# method extensions\nimport LazySets: dim, overapproximate, box_approximation, project, Projection,\n intersection, directions, linear_map, LinearMap, _split, split!,\n set, array, _isapprox\n\nimport MathematicalSystems: discretize\nimport Base: ∈, ∩, convert, isdisjoint\nimport LinearAlgebra: normalize\n\nimport CommonSolve: solve # common solve name\n\n# ======================\n# Useful constants\n# ======================\n\n@inline zeroBox(m) = IntervalBox(zeroI, m)\n@inline unitBox(m) = IntervalBox(IA.Interval(0.0, 1.0), m)\n@inline symBox(n::Integer) = IntervalBox(symI, n)\nconst zeroI = IA.Interval(0.0) # TODO use number type\nconst oneI = IA.Interval(1.0)\nconst symI = IA.Interval(-1.0, 1.0)\n\n# Interval constructor given a float\nLazySets.Interval(x::Float64) = Interval(interval(x))\n\n# common aliases for system's names\nconst LCS = LinearContinuousSystem\nconst LDS = LinearDiscreteSystem\nconst CLCS = ConstrainedLinearContinuousSystem\nconst CLDS = ConstrainedLinearDiscreteSystem\nconst CLCCS = ConstrainedLinearControlContinuousSystem\nconst CLCDS = ConstrainedLinearControlDiscreteSystem\nconst ACS = AffineContinuousSystem\nconst ADS = AffineDiscreteSystem\nconst CACCS = ConstrainedAffineControlContinuousSystem\nconst CACDS = ConstrainedAffineControlDiscreteSystem\nconst CACS = ConstrainedAffineContinuousSystem\nconst CADS = ConstrainedAffineDiscreteSystem\nconst BBCS = BlackBoxContinuousSystem\nconst CBBCS = ConstrainedBlackBoxContinuousSystem\nconst CBBCCS = ConstrainedBlackBoxControlContinuousSystem\nconst SOLCS = SecondOrderLinearContinuousSystem\nconst SOACS = SecondOrderAffineContinuousSystem\nconst SOCLCCS = SecondOrderConstrainedLinearControlContinuousSystem\nconst SOCACCS = SecondOrderConstrainedAffineControlContinuousSystem\nconst SecondOrderSystem = Union{SOLCS, SOACS, SOCLCCS, SOCACCS}\nconst NonlinearSystem = Union{BBCS, CBBCS, CBBCCS}\n\n@inline function _isapprox(Δt::TimeInterval, Δs::TimeInterval)\n return (inf(Δt) ≈ inf(Δs)) && (sup(Δt) ≈ sup(Δs))\nend\n\nconst VecOrTuple = Union{<:AbstractVector{Int}, NTuple{D, Int}} where {D}\nconst VecOrTupleOrInt = Union{<:AbstractVector{Int}, NTuple{D, Int}, Int} where {D}\n\n# ======================\n# Optional dependencies\n# ======================\n\nusing Requires\n\nfunction __init__()\n # numerical differential equations suite\n @require DifferentialEquations = \"0c46a032-eb83-5123-abaf-570d42b7fbaa\" include(\"init_DifferentialEquations.jl\")\n\n # exponentiation methods using Krylov subspace approximations\n @require ExponentialUtilities = \"d4d017d3-3776-5f7e-afef-a10c40355c18\" include(\"init_ExponentialUtilities.jl\")\n\n # methods that require optimization modeling and solvers\n @require JuMP = \"4076af6c-e467-56ae-b986-b466b2749572\" include(\"init_JuMP.jl\")\n\n # tools for symbolic computation\n #@require ModelingToolkit = \"961ee093-0014-501f-94e3-6117800e7a78\" include(\"init_ModelingToolkit.jl\")\n @require Symbolics = \"0c5d862f-8b57-4792-8d23-62f2024744c7\" include(\"init_Symbolics.jl\")\n\n # tools for symbolic algebra\n @require MultivariatePolynomials = \"102ac46a-7ee4-5c85-9060-abc95bfdeaa3\" include(\"init_MultivariatePolynomials.jl\")\n\n # sparse dynamic representation of multivariate polynomials\n @require DynamicPolynomials = \"7c1d4256-1411-5781-91ec-d7bc3513ac07\" include(\"init_DynamicPolynomials.jl\")\nend\n\n# ===========================\n# Utility macros\n# ===========================\n\n\"\"\"\n @requires(module_name)\n\nConvenience macro to annotate that a package is required to use a certain function.\n\n### Input\n\n- `module_name` -- name of the required package\n\n### Output\n\nThe macro expands to an assertion that checks whether the module `module_name` is\nknown in the calling scope.\n\n### Notes\n\nUsage:\n\n```julia\nfunction foo(...)\n @require MyPackage\n ... # functionality that requires MyPackage to be loaded\nend\n```\n\"\"\"\nmacro requires(module_name)\n m = Meta.quot(Symbol(module_name))\n return esc(:(@assert isdefined(@__MODULE__, $m) \"package `$($m)` is required \" *\n \"for this function; do `using $($m)` and try again\"))\nend\n", "meta": {"hexsha": "2216f80e5377831348b0e4b8be8e0bd4b16e16b3", "size": 5915, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Initialization/init.jl", "max_stars_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_stars_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-15T10:47:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T10:36:28.000Z", "max_issues_repo_path": "src/Initialization/init.jl", "max_issues_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_issues_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2020-01-14T18:26:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T07:57:50.000Z", "max_forks_repo_path": "src/Initialization/init.jl", "max_forks_repo_name": "lyg1597/ReachabilityAnalysis.jl", "max_forks_repo_head_hexsha": "2fdd273e895166dc1bec727bb2cfa209d198927f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-10T12:21:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-10T12:21:07.000Z", "avg_line_length": 34.7941176471, "max_line_length": 120, "alphanum_fraction": 0.7372781065, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24781622205339127}} {"text": "function _process_reaction_phrase(phrase_array::Array{String,1})\n\n tmp_string = \"\"\n for phrase in phrase_array\n tmp_string*=\"$(phrase) + \"\n end\n\n # cutoff -\n tmp_string = tmp_string |> rstrip\n\n # cutoff the trailing + \n return (tmp_string[1:end-1] |> rstrip)\nend\n\nfunction build_stoichiometric_matrix(model::Dict{Symbol,Any})\n\n try\n\n # get the reaction table -\n reaction_table = model[:reactions]\n reaction_id_array = reaction_table[!, :reaction_number]\n compound_id_array = model[:compounds][!,:compound_id]\n\n # now - let's build the stm -\n number_of_species = length(compound_id_array)\n number_of_reactions = length(reaction_id_array)\n stoichiometric_matrix = zeros(number_of_species, number_of_reactions)\n\n # build the array -\n for reaction_index = 1:number_of_reactions\n\n # what is my reaction id?\n reaction_id = reaction_id_array[reaction_index]\n\n # get row from the reaction table -\n df_reaction = filter(:reaction_number => x -> (x == reaction_id), reaction_table)\n\n # grab the stm dictionary -\n stm_dictionary = df_reaction[1, :stoichiometric_dictionary]\n\n # ok, lets see if we have these species -\n for species_index = 1:number_of_species\n\n # species code -\n species_symbol = compound_id_array[species_index]\n if (haskey(stm_dictionary, species_symbol) == true)\n stm_coeff_value = stm_dictionary[species_symbol]\n stoichiometric_matrix[species_index, reaction_index] = stm_coeff_value\n end\n end\n end\n\n # return -\n return (compound_id_array, reaction_id_array, stoichiometric_matrix)\n catch error\n\n # what is our error policy? => for now, just print the message\n error_message = sprint(showerror, error, catch_backtrace())\n println(error_message)\n\n end\nend\n\nfunction find_compound_index(model::Dict{Symbol,Any}, \n search::Pair{Symbol,String})\n\n # get the compounds table -\n compounds_table = model[:compounds]\n\n # get list of compound names -\n tmp_array = compounds_table[!,search.first] |> collect\n\t\n # do we have this name? (if yes, then return index)\n return findfirst(x->x==search.second,tmp_array)\nend\n\nfunction find_reaction_index(model::Dict{Symbol,Any}, \n search::Pair{Symbol,String})\n\n # get the compounds table -\n reaction_table = model[:reactions]\n\n # get list of compound names -\n tmp_array = reaction_table[!,search.first] |> collect\n\t\n # do we have this name? (if yes, then return index)\n return findfirst(x->x==search.second,tmp_array)\nend\n\nfunction update_flux_bounds_directionality(MODEL,default_flux_bounds)\n\n # get the ΔG table -> for now, just use the mean value -\n ΔG_table = MODEL[:ΔG]\n\n # how many reactions do we have ΔG data for?\n (number_of_reactions,_) = size(ΔG_table)\n for reaction_index = 1:number_of_reactions\n \n # get ΔG value -\n μ_ΔG_value = ΔG_table[reaction_index,:μ_ΔG]\n\n # get the corresponding reaction number -\n reaction_id = ΔG_table[reaction_index, :reaction_number]\n\n # what index is this?\n index_in_bounds_array = find_reaction_index(MODEL,:reaction_number=>reaction_id)\n if (isempty(index_in_bounds_array) == false)\n \n # backward?\n is_reversible = -1*(sign(μ_ΔG_value)) <= 0.0 ? true : false \n if (is_reversible == false)\n default_flux_bounds[index_in_bounds_array,1] = 0.0\n end\n end\n end\n\n return default_flux_bounds\nend\n\nfunction translation_reaction_string_to_human(model::Dict{Symbol,Any})\n\n # get the compound table -\n compound_table = model[:compounds]\n reaction_table = model[:reactions]\n\n # build a translation table -\n (number_of_compounds, _) = size(compound_table) \n compound_translation_table = Dict{String,String}()\n for compound_index = 1:number_of_compounds\n kegg_name = compound_table[compound_index, :compound_id]\n human_name = compound_table[compound_index, :compound_name]\n compound_translation_table[kegg_name] = human_name\n end\n\n # hack: -\n compound_translation_table[\"C00138\"] = \"Reduced ferredoxin\"\n compound_translation_table[\"C00139\"] = \"Oxidized ferredoxin\"\n\n # number of _reactions -\n (number_of_reactions, _) = size(reaction_table)\n\n # initialze space -\n tmp_reaction_string_array = Array{String,1}(undef,number_of_reactions)\n\n # just so we are safe - copy the old strings into the tmp array in case something doesn't work\n for reaction_index = 1:number_of_reactions\n old_string = reaction_table[reaction_index, :reaction_markup]\n tmp_reaction_string_array[reaction_index] = old_string\n end\n\n # init some tmp storage -\n tmp_reactant_phrase_array = Array{String,1}()\n tmp_product_phrase_array = Array{String,1}()\n\n # main loop - here we go .... let's do this ...\n for reaction_index = 1:number_of_reactions\n \n # grab the st dictionary for this reaction -\n stoichiometric_dictionary = reaction_table[reaction_index, :stoichiometric_dictionary]\n for (key,value) in stoichiometric_dictionary\n\n # look up this key in the translation table -\n human_key = get(compound_translation_table, key, \"?\")\n\n if (abs(value) != 1)\n tmp_phrase = \"$(abs(value)) $(human_key)\"\n else\n tmp_phrase = \"$(human_key)\"\n end\n\n if (value<0)\n push!(tmp_reactant_phrase_array, tmp_phrase)\n else\n push!(tmp_product_phrase_array, tmp_phrase)\n end\n end\n\n # build new reaction string ...\n reactant_string = _process_reaction_phrase(tmp_reactant_phrase_array)\n product_string = _process_reaction_phrase(tmp_product_phrase_array)\n full_reaction_string = \"$(reactant_string) <=> $(product_string)\"\n tmp_reaction_string_array[reaction_index] = full_reaction_string\n \n # empty -\n empty!(tmp_reactant_phrase_array)\n empty!(tmp_product_phrase_array)\n end\n\n return tmp_reaction_string_array\nend", "meta": {"hexsha": "f3131eaa9234f8e307e3a52f29dc384e59954cea", "size": 6324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "project/src/Base.jl", "max_stars_repo_name": "agansky/ENGRI-1120-Cornell-Varner", "max_stars_repo_head_hexsha": "1a2103ed3a9cd94a677f09083c1bbef27db90a86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T20:05:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T20:05:45.000Z", "max_issues_repo_path": "project/src/Base.jl", "max_issues_repo_name": "agansky/ENGRI-1120-Cornell-Varner", "max_issues_repo_head_hexsha": "1a2103ed3a9cd94a677f09083c1bbef27db90a86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/src/Base.jl", "max_forks_repo_name": "agansky/ENGRI-1120-Cornell-Varner", "max_forks_repo_head_hexsha": "1a2103ed3a9cd94a677f09083c1bbef27db90a86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-11-10T20:59:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T06:58:07.000Z", "avg_line_length": 33.2842105263, "max_line_length": 98, "alphanum_fraction": 0.6590765338, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24781554514906315}} {"text": "function dh_simulation(LP::AbstractLProblem{T}, p::Float64, nTrials::Int64, alg::OrdinaryDiffEqAlgorithm, logger::Logger{T1,T2} = Logger{:no, :cmd}(), interval::Int64 = 1, offset1::Int64 = 0; links = (:all,:all), axes = [:x, :y, :z], kwargs...) where {T<:PureClassicalApprox,T1,T2}\n assert(nTrials > 0)\n RNGarray = initRNG(nprocs())\n path_part = @sprintf(\"Dis Tm%.2f dt%.3f del%d Obs%s Pr%.3f/\", LP.Tmax, LP.tstep, LP.delimiter, get_string(LP.rules.str_vec), p)\n filenames = Vector{String}()\n A = LP.A\n l = LP.cb.affect!.save_func.len\n tspan = (0.0, LP.Tmax*LP.delimiter)\n t_means = collect(0.0:LP.tstep:(LP.Tmax*LP.delimiter))\n saved_values = SavedValues(t_means, [zeros(l) for i in eachindex(t_means)])\n for thread = (offset1+1):(offset1+nprocs())\n push!(filenames, get_string(nTrials, thread, alg))\n end\n log_o, save_os = set_Logging(LP, nTrials, logger, A, path_part, filenames)\n cf_vals0 = LP.cf_vals\n @sync for i in workers()\n @spawnat i begin\n global cf_vals = cf_vals0\n global RNG = RNGarray[i]\n end\n end\n iter = get_status(log_o)\n offset = get_offset(log_o)\n if iter > 0\n load_data!(cf_vals0, save_os[1])\n for i in workers()\n @spawnat i load_data!(cf_vals, save_os[i])\n end\n end\n t0 = time()-offset\n while iter 0)\n RNGarray = initRNG(nprocs()+1)\n path_part = @sprintf(\"Dis Tm%.2f dt%.3f del%d Obs%s Pr%.3f/\", LP.Tmax, LP.tstep, LP.delimiter, get_string(LP.rules.str_vec), p)\n filenames = Vector{String}()\n A = HybridApprox(LP.A.L, copy(LP.A.q_spins), LP.A.name)\n l = LP.cb.affect!.save_func.len\n tspan = (0.0, LP.Tmax*LP.delimiter)\n t_means = collect(0.0:LP.tstep:(LP.Tmax*LP.delimiter))\n saved_values = SavedValues(t_means, [zeros(l) for i in eachindex(t_means)])\n for thread = (offset1+1):(offset1+nprocs())\n push!(filenames, get_string(nTrials, thread, alg))\n end\n log_o, save_os = set_Logging(LP, nTrials, logger, LP.A, path_part, filenames)\n cf_vals0 = LP.cf_vals\n @sync for i in workers()\n @spawnat i begin\n global cf_vals = cf_vals0\n global RNG = RNGarray[i]\n end\n end\n iter = get_status(log_o)\n offset = get_offset(log_o)\n if iter > 0\n load_data!(cf_vals0, save_os[1])\n for i in workers()\n @spawnat i load_data!(cf_vals, save_os[i])\n end\n end\n t0 = time()-offset\n while iter 0)\n RNGarray = initRNG(nprocs()+1)\n path_part = @sprintf(\"Dis Tm%.2f dt%.3f del%d Obs%s Pr%.3f/\", Tmax, tstep, delimiter, get_string(LP.rules.str_vec), p)\n filenames = Vector{String}()\n for thread = (offset1+1):(offset1+nprocs())\n push!(filenames, get_string(nTrials, thread, alg))\n end\n log_o, save_os = set_Logging(LP, nTrials, logger, A, path_part, filenames)\n cf_vals0 = LP.cf_vals\n @sync for i in workers()\n @spawnat i begin\n global cf_vals = cf_vals0\n global RNG = RNGarray[i]\n end\n end\n iter = get_status(log_o)\n offset = get_offset(log_o)\n if iter > 0\n load_data!(cf_vals0, save_os[1])\n for i in workers()\n @spawnat i load_data!(cf_vals, save_os[i])\n end\n end\n t0 = time()-offset\n ##############################\n while iter>> 1\n @inbounds if (forward && v[m] < x) || (!forward && v[m] > x)\n lo = m\n else\n hi = m\n end\n end\n return hi\nend\n\n@inline function _searchsortedlast(v::AbstractVector, x, lo::Integer, forward::Bool)\n u = oftype(lo, 1)\n lo = lo - u\n hi = length(v) + u\n @inbounds while lo < hi - u\n m = (lo + hi) >>> 1\n @inbounds if (forward && v[m] > x) || (!forward && v[m] < x)\n hi = m\n else\n lo = m\n end\n end\n return lo\nend\n\n@inline function _ode_addsteps!(integrator,f=integrator.f,always_calc_begin = false,allow_calc_end = true,force_calc_end = false)\n if !(typeof(integrator.cache) <: CompositeCache)\n DiffEqBase.addsteps!(integrator.k,integrator.tprev,integrator.uprev,integrator.u,\n integrator.dt,f,integrator.p,integrator.cache,\n always_calc_begin,allow_calc_end,force_calc_end)\n else\n DiffEqBase.addsteps!(integrator.k,integrator.tprev,integrator.uprev,integrator.u,\n integrator.dt,f,integrator.p,\n @inbounds(integrator.cache.caches[integrator.cache.current]),\n always_calc_begin,allow_calc_end,force_calc_end)\n end\nend\n@inline DiffEqBase.addsteps!(integrator::ODEIntegrator,args...) = _ode_addsteps!(integrator,args...)\n\n@inline function ode_interpolant(Θ,integrator::DiffEqBase.DEIntegrator,idxs,deriv)\n DiffEqBase.addsteps!(integrator)\n if !(typeof(integrator.cache) <: CompositeCache)\n val = ode_interpolant(Θ,integrator.dt,integrator.uprev,integrator.u,integrator.k,integrator.cache,idxs,deriv)\n else\n val = composite_ode_interpolant(Θ,integrator,integrator.cache.caches,integrator.cache.current,idxs,deriv)\n end\n val\nend\n\n@generated function composite_ode_interpolant(Θ, integrator, caches::T, current, idxs, deriv) where {T <: Tuple}\n expr = Expr(:block)\n for i in 1:length(T.types)\n push!(expr.args, quote\n if $i == current\n return ode_interpolant(Θ,integrator.dt,integrator.uprev,integrator.u,integrator.k,caches[$i],idxs,deriv)\n end\n end)\n end\n push!(expr.args, quote\n throw(\"Cache $current is not available. There are only $(length(caches)) caches.\")\n end)\n return expr\nend\n\n@inline function ode_interpolant!(val,Θ,integrator::DiffEqBase.DEIntegrator,idxs,deriv)\n DiffEqBase.addsteps!(integrator)\n if !(typeof(integrator.cache) <: CompositeCache)\n ode_interpolant!(val,Θ,integrator.dt,integrator.uprev,integrator.u,integrator.k,integrator.cache,idxs,deriv)\n else\n ode_interpolant!(val,Θ,integrator.dt,integrator.uprev,integrator.u,integrator.k,integrator.cache.caches[integrator.cache.current],idxs,deriv)\n end\nend\n\n@generated function composite_ode_interpolant!(val, Θ, integrator, caches::T, current, idxs, deriv) where {T <: Tuple}\n expr = Expr(:block)\n for i in 1:length(T.types)\n push!(expr.args, quote\n if $i == current\n return ode_interpolant!(val,Θ,integrator.dt,integrator.uprev,integrator.u,integrator.k,caches[$i],idxs,deriv)\n end\n end)\n end\n push!(expr.args, quote\n throw(\"Cache $current is not available. There are only $(length(caches)) caches.\")\n end)\n return expr\nend\n\n@inline function current_interpolant(t::Number,integrator::DiffEqBase.DEIntegrator,idxs,deriv)\n Θ = (t-integrator.tprev)/integrator.dt\n ode_interpolant(Θ,integrator,idxs,deriv)\nend\n\n@inline function current_interpolant(t,integrator::DiffEqBase.DEIntegrator,idxs,deriv)\n Θ = (t.-integrator.tprev)./integrator.dt\n [ode_interpolant(ϕ,integrator,idxs,deriv) for ϕ in Θ]\nend\n\n@inline function current_interpolant!(val,t::Number,integrator::DiffEqBase.DEIntegrator,idxs,deriv)\n Θ = (t-integrator.tprev)/integrator.dt\n ode_interpolant!(val,Θ,integrator,idxs,deriv)\nend\n\n@inline function current_interpolant!(val,t,integrator::DiffEqBase.DEIntegrator,idxs,deriv)\n Θ = (t.-integrator.tprev)./integrator.dt\n [ode_interpolant!(val,ϕ,integrator,idxs,deriv) for ϕ in Θ]\nend\n\n@inline function current_extrapolant(t::Number,integrator::DiffEqBase.DEIntegrator,idxs=nothing,deriv=Val{0})\n Θ = (t-integrator.tprev)/(integrator.t-integrator.tprev)\n ode_extrapolant(Θ,integrator,idxs,deriv)\nend\n\n@inline function current_extrapolant!(val,t::Number,integrator::DiffEqBase.DEIntegrator,idxs=nothing,deriv=Val{0})\n Θ = (t-integrator.tprev)/(integrator.t-integrator.tprev)\n ode_extrapolant!(val,Θ,integrator,idxs,deriv)\nend\n\n@inline function current_extrapolant(t::AbstractArray,integrator::DiffEqBase.DEIntegrator,idxs=nothing,deriv=Val{0})\n Θ = (t.-integrator.tprev)./(integrator.t-integrator.tprev)\n [ode_extrapolant(ϕ,integrator,idxs,deriv) for ϕ in Θ]\nend\n\n@inline function current_extrapolant!(val,t,integrator::DiffEqBase.DEIntegrator,idxs=nothing,deriv=Val{0})\n Θ = (t.-integrator.tprev)./(integrator.t-integrator.tprev)\n [ode_extrapolant!(val,ϕ,integrator,idxs,deriv) for ϕ in Θ]\nend\n\n@inline function ode_extrapolant!(val,Θ,integrator::DiffEqBase.DEIntegrator,idxs,deriv)\n DiffEqBase.addsteps!(integrator)\n if !(typeof(integrator.cache) <: CompositeCache)\n ode_interpolant!(val,Θ,integrator.t-integrator.tprev,integrator.uprev2,integrator.uprev,integrator.k,integrator.cache,idxs,deriv)\n else\n composite_ode_extrapolant!(val,Θ,integrator,integrator.cache.caches,integrator.cache.current,idxs,deriv)\n end\nend\n\n@generated function composite_ode_extrapolant!(val, Θ, integrator, caches::T, current, idxs, deriv) where {T <: Tuple}\n expr = Expr(:block)\n for i in 1:length(T.types)\n push!(expr.args, quote\n if $i == current\n return ode_interpolant!(val,Θ,integrator.t-integrator.tprev,integrator.uprev2,integrator.uprev,integrator.k,caches[$i],idxs,deriv)\n end\n end)\n end\n push!(expr.args, quote\n throw(\"Cache $current is not available. There are only $(length(caches)) caches.\")\n end)\n return expr\nend\n\n\n@inline function ode_extrapolant(Θ,integrator::DiffEqBase.DEIntegrator,idxs,deriv)\n DiffEqBase.addsteps!(integrator)\n if !(typeof(integrator.cache) <: CompositeCache)\n ode_interpolant(Θ,integrator.t-integrator.tprev,integrator.uprev2,integrator.uprev,integrator.k,integrator.cache,idxs,deriv)\n else\n composite_ode_extrapolant(Θ,integrator,integrator.cache.caches,integrator.cache.current,idxs,deriv)\n end\nend\n\n@generated function composite_ode_extrapolant(Θ, integrator, caches::T, current, idxs, deriv) where {T <: Tuple}\n expr = Expr(:block)\n for i in 1:length(T.types)\n push!(expr.args, quote\n if $i == current\n return ode_interpolant(Θ,integrator.t-integrator.tprev,integrator.uprev2,integrator.uprev,integrator.k,caches[$i],idxs,deriv)\n end\n end)\n end\n push!(expr.args, quote\n throw(\"Cache $current is not available. There are only $(length(caches)) caches.\")\n end)\n return expr\nend\n\n\"\"\"\node_interpolation(tvals,ts,timeseries,ks)\n\nGet the value at tvals where the solution is known at the\ntimes ts (sorted), with values timeseries and derivatives ks\n\"\"\"\nfunction ode_interpolation(tvals,id,idxs,deriv,p,continuity::Symbol=:left)\n @unpack ts,timeseries,ks,f,cache = id\n @inbounds tdir = sign(ts[end]-ts[1])\n idx = sortperm(tvals,rev=tdir<0)\n\n # start the search thinking it's ts[1]-ts[2]\n i₋ = 1\n i₊ = 2\n vals = map(idx) do j\n t = tvals[j]\n\n if continuity === :left\n # we have i₋ = i₊ = 1 if t = ts[1], i₊ = i₋ + 1 = lastindex(ts) if t > ts[end],\n # and otherwise i₋ and i₊ satisfy ts[i₋] < t ≤ ts[i₊]\n i₊ = min(lastindex(ts), _searchsortedfirst(ts,t,i₊,tdir > 0))\n i₋ = i₊ > 1 ? i₊ - 1 : i₊\n else\n # we have i₋ = i₊ - 1 = 1 if t < ts[1], i₊ = i₋ = lastindex(ts) if t = ts[end],\n # and otherwise i₋ and i₊ satisfy ts[i₋] ≤ t < ts[i₊]\n i₋ = max(1, _searchsortedlast(ts,t,i₋,tdir > 0))\n i₊ = i₋ < lastindex(ts) ? i₋ + 1 : i₋\n end\n\n dt = ts[i₊] - ts[i₋]\n Θ = iszero(dt) ? oneunit(t) / oneunit(dt) : (t-ts[i₋]) / dt\n\n if typeof(cache) <: (FunctionMapCache) || typeof(cache) <: FunctionMapConstantCache\n return ode_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],0,cache,idxs,deriv)\n elseif !id.dense\n return linear_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],idxs,deriv)\n elseif typeof(cache) <: CompositeCache\n DiffEqBase.addsteps!(ks[i₊],ts[i₋],timeseries[i₋],timeseries[i₊],dt,f,p,cache.caches[id.alg_choice[i₊]]) # update the kcurrent\n return ode_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache.caches[id.alg_choice[i₊]],idxs,deriv)\n else\n DiffEqBase.addsteps!(ks[i₊],ts[i₋],timeseries[i₋],timeseries[i₊],dt,f,p,cache) # update the kcurrent\n return ode_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache,idxs,deriv)\n end\n end\n invpermute!(vals, idx)\n DiffEqArray(vals, tvals)\nend\n\n\"\"\"\node_interpolation(tvals,ts,timeseries,ks)\n\nGet the value at tvals where the solution is known at the\ntimes ts (sorted), with values timeseries and derivatives ks\n\"\"\"\nfunction ode_interpolation!(vals,tvals,id,idxs,deriv,p,continuity::Symbol=:left)\n @unpack ts,timeseries,ks,f,cache = id\n @inbounds tdir = sign(ts[end]-ts[1])\n idx = sortperm(tvals,rev=tdir<0)\n\n # start the search thinking it's in ts[1]-ts[2]\n i₋ = 1\n i₊ = 2\n @inbounds for j in idx\n t = tvals[j]\n\n if continuity === :left\n # we have i₋ = i₊ = 1 if t = ts[1], i₊ = i₋ + 1 = lastindex(ts) if t > ts[end],\n # and otherwise i₋ and i₊ satisfy ts[i₋] < t ≤ ts[i₊]\n i₊ = min(lastindex(ts), _searchsortedfirst(ts,t,i₊,tdir > 0))\n i₋ = i₊ > 1 ? i₊ - 1 : i₊\n else\n # we have i₋ = i₊ - 1 = 1 if t < ts[1], i₊ = i₋ = lastindex(ts) if t = ts[end],\n # and otherwise i₋ and i₊ satisfy ts[i₋] ≤ t < ts[i₊]\n i₋ = max(1, _searchsortedlast(ts,t,i₋,tdir > 0))\n i₊ = i₋ < lastindex(ts) ? i₋ + 1 : i₋\n end\n\n dt = ts[i₊] - ts[i₋]\n Θ = iszero(dt) ? oneunit(t) / oneunit(dt) : (t-ts[i₋]) / dt\n\n if typeof(cache) <: (FunctionMapCache) || typeof(cache) <: FunctionMapConstantCache\n if eltype(timeseries) <: AbstractArray\n ode_interpolant!(vals[j],Θ,dt,timeseries[i₋],timeseries[i₊],0,cache,idxs,deriv)\n else\n vals[j] = ode_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],0,cache,idxs,deriv)\n end\n elseif !id.dense\n if eltype(timeseries) <: AbstractArray\n linear_interpolant!(vals[j],Θ,dt,timeseries[i₋],timeseries[i₊],idxs,deriv)\n else\n vals[j] = linear_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],idxs,deriv)\n end\n elseif typeof(cache) <: CompositeCache\n DiffEqBase.addsteps!(ks[i₊],ts[i₋],timeseries[i₋],timeseries[i₊],dt,f,p,cache.caches[id.alg_choice[i₊]]) # update the kcurrent\n if eltype(timeseries) <: AbstractArray\n ode_interpolant!(vals[j],Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache.caches[id.alg_choice[i₊]],idxs,deriv)\n else\n vals[j] = ode_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache.caches[id.alg_choice[i₊]],idxs,deriv)\n end\n else\n DiffEqBase.addsteps!(ks[i₊],ts[i₋],timeseries[i₋],timeseries[i₊],dt,f,p,cache) # update the kcurrent\n if eltype(vals[j]) <: AbstractArray\n ode_interpolant!(vals[j],Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache,idxs,deriv)\n else\n vals[j] = ode_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache,idxs,deriv)\n end\n end\n end\n\n vals\nend\n\n\"\"\"\node_interpolation(tval::Number,ts,timeseries,ks)\n\nGet the value at tval where the solution is known at the\ntimes ts (sorted), with values timeseries and derivatives ks\n\"\"\"\nfunction ode_interpolation(tval::Number,id,idxs,deriv,p,continuity::Symbol=:left)\n @unpack ts,timeseries,ks,f,cache = id\n @inbounds tdir = sign(ts[end]-ts[1])\n\n if continuity === :left\n # we have i₋ = i₊ = 1 if tval = ts[1], i₊ = i₋ + 1 = lastindex(ts) if tval > ts[end],\n # and otherwise i₋ and i₊ satisfy ts[i₋] < tval ≤ ts[i₊]\n i₊ = min(lastindex(ts), _searchsortedfirst(ts,tval,2,tdir > 0))\n i₋ = i₊ > 1 ? i₊ - 1 : i₊\n else\n # we have i₋ = i₊ - 1 = 1 if tval < ts[1], i₊ = i₋ = lastindex(ts) if tval = ts[end],\n # and otherwise i₋ and i₊ satisfy ts[i₋] ≤ tval < ts[i₊]\n i₋ = max(1, _searchsortedlast(ts,tval,1,tdir > 0))\n i₊ = i₋ < lastindex(ts) ? i₋ + 1 : i₋\n end\n\n @inbounds begin\n dt = ts[i₊] - ts[i₋]\n Θ = iszero(dt) ? oneunit(tval) / oneunit(dt) : (tval-ts[i₋]) / dt\n\n if typeof(cache) <: (FunctionMapCache) || typeof(cache) <: FunctionMapConstantCache\n val = ode_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],0,cache,idxs,deriv)\n elseif !id.dense\n val = linear_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],idxs,deriv)\n elseif typeof(cache) <: CompositeCache\n DiffEqBase.addsteps!(ks[i₊],ts[i₋],timeseries[i₋],timeseries[i₊],dt,f,p,cache.caches[id.alg_choice[i₊]]) # update the kcurrent\n val = ode_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache.caches[id.alg_choice[i₊]],idxs,deriv)\n else\n DiffEqBase.addsteps!(ks[i₊],ts[i₋],timeseries[i₋],timeseries[i₊],dt,f,p,cache) # update the kcurrent\n val = ode_interpolant(Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache,idxs,deriv)\n end\n end\n\n val\nend\n\n\"\"\"\node_interpolation!(out,tval::Number,ts,timeseries,ks)\n\nGet the value at tval where the solution is known at the\ntimes ts (sorted), with values timeseries and derivatives ks\n\"\"\"\nfunction ode_interpolation!(out,tval::Number,id,idxs,deriv,p,continuity::Symbol=:left)\n @unpack ts,timeseries,ks,f,cache = id\n @inbounds tdir = sign(ts[end]-ts[1])\n\n if continuity === :left\n # we have i₋ = i₊ = 1 if tval = ts[1], i₊ = i₋ + 1 = lastindex(ts) if tval > ts[end],\n # and otherwise i₋ and i₊ satisfy ts[i₋] < tval ≤ ts[i₊]\n i₊ = min(lastindex(ts), _searchsortedfirst(ts,tval,2,tdir > 0))\n i₋ = i₊ > 1 ? i₊ - 1 : i₊\n else\n # we have i₋ = i₊ - 1 = 1 if tval < ts[1], i₊ = i₋ = lastindex(ts) if tval = ts[end],\n # and otherwise i₋ and i₊ satisfy ts[i₋] ≤ tval < ts[i₊]\n i₋ = max(1, _searchsortedlast(ts,tval,1,tdir > 0))\n i₊ = i₋ < lastindex(ts) ? i₋ + 1 : i₋\n end\n\n @inbounds begin\n dt = ts[i₊] - ts[i₋]\n Θ = iszero(dt) ? oneunit(tval) / oneunit(dt) : (tval-ts[i₋]) / dt\n\n if typeof(cache) <: (FunctionMapCache) || typeof(cache) <: FunctionMapConstantCache\n ode_interpolant!(out,Θ,dt,timeseries[i₋],timeseries[i₊],0,cache,idxs,deriv)\n elseif !id.dense\n linear_interpolant!(out,Θ,dt,timeseries[i₋],timeseries[i₊],idxs,deriv)\n elseif typeof(cache) <: CompositeCache\n DiffEqBase.addsteps!(ks[i₊],ts[i₋],timeseries[i₋],timeseries[i₊],dt,f,p,cache.caches[id.alg_choice[i₊]]) # update the kcurrent\n ode_interpolant!(out,Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache.caches[id.alg_choice[i₊]],idxs,deriv)\n else\n DiffEqBase.addsteps!(ks[i₊],ts[i₋],timeseries[i₋],timeseries[i₊],dt,f,p,cache) # update the kcurrent\n ode_interpolant!(out,Θ,dt,timeseries[i₋],timeseries[i₊],ks[i₊],cache,idxs,deriv)\n end\n end\n\n out\nend\n\n\"\"\"\nBy default, Hermite interpolant so update the derivative at the two ends\n\"\"\"\nfunction DiffEqBase.addsteps!(k,t,uprev,u,dt,f,p,cache,always_calc_begin = false,allow_calc_end = true,force_calc_end = false)\n if length(k)<2 || always_calc_begin\n if typeof(cache) <: OrdinaryDiffEqMutableCache\n rtmp = similar(u, eltype(eltype(k)))\n f(rtmp,uprev,p,t)\n copyat_or_push!(k,1,rtmp)\n f(rtmp,u,p,t+dt)\n copyat_or_push!(k,2,rtmp)\n else\n copyat_or_push!(k,1,f(uprev,p,t))\n copyat_or_push!(k,2,f(u,p,t+dt))\n end\n end\n nothing\nend\n\n\"\"\"\node_interpolant and ode_interpolant! dispatch\n\"\"\"\nfunction ode_interpolant(Θ,dt,y₀,y₁,k,cache,idxs,T::Type{Val{TI}}) where TI\n _ode_interpolant(Θ,dt,y₀,y₁,k,cache,idxs,T)\nend\n\nfunction ode_interpolant(Θ,dt,y₀,y₁,k,cache::OrdinaryDiffEqMutableCache,idxs,T::Type{Val{TI}}) where TI\n if typeof(idxs) <: Number || typeof(y₀) <: Union{Number,SArray}\n # typeof(y₀) can be these if saveidxs gives a single value\n _ode_interpolant(Θ,dt,y₀,y₁,k,cache,idxs,T)\n elseif typeof(idxs) <: Nothing\n out = oneunit(Θ) .* y₁\n _ode_interpolant!(out,Θ,dt,y₀,y₁,k,cache,idxs,T)\n else\n out = oneunit(Θ) .* y₁[idxs]\n _ode_interpolant!(out,Θ,dt,y₀,y₁,k,cache,idxs,T)\n end\nend\n\nfunction ode_interpolant!(out,Θ,dt,y₀,y₁,k,cache,idxs,T::Type{Val{TI}}) where TI\n _ode_interpolant!(out,Θ,dt,y₀,y₁,k,cache,idxs,T)\nend\n\n##################### Hermite Interpolants\n\n# If no dispatch found, assume Hermite\nfunction _ode_interpolant(Θ,dt,y₀,y₁,k,cache,idxs,T::Type{Val{TI}}) where TI\n hermite_interpolant(Θ,dt,y₀,y₁,k,Val{typeof(cache) <: OrdinaryDiffEqMutableCache},idxs,T)\nend\n\nfunction _ode_interpolant!(out,Θ,dt,y₀,y₁,k,cache,idxs,T::Type{Val{TI}}) where TI\n hermite_interpolant!(out,Θ,dt,y₀,y₁,k,idxs,T)\nend\n\n\"\"\"\nHairer Norsett Wanner Solving Ordinary Differential Euations I - Nonstiff Problems Page 190\n\nHerimte Interpolation, chosen if no other dispatch for ode_interpolant\n\"\"\"\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,::Type{Val{false}},idxs::Nothing,T::Type{Val{0}}) # Default interpolant is Hermite\n #@.. (1-Θ)*y₀+Θ*y₁+Θ*(Θ-1)*((1-2Θ)*(y₁-y₀)+(Θ-1)*dt*k[1] + Θ*dt*k[2])\n @inbounds (1-Θ)*y₀+Θ*y₁+Θ*(Θ-1)*((1-2Θ)*(y₁-y₀)+(Θ-1)*dt*k[1] + Θ*dt*k[2])\nend\n\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,::Type{Val{true}},idxs::Nothing,T::Type{Val{0}}) # Default interpolant is Hermite\n #@.. (1-Θ)*y₀+Θ*y₁+Θ*(Θ-1)*((1-2Θ)*(y₁-y₀)+(Θ-1)*dt*k[1] + Θ*dt*k[2])\n @inbounds @.. (1-Θ)*y₀+Θ*y₁+Θ*(Θ-1)*((1-2Θ)*(y₁-y₀)+(Θ-1)*dt*k[1] + Θ*dt*k[2])\nend\n\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,cache,idxs,T::Type{Val{0}}) # Default interpolant is Hermite\n # return @.. (1-Θ)*y₀[idxs]+Θ*y₁[idxs]+Θ*(Θ-1)*((1-2Θ)*(y₁[idxs]-y₀[idxs])+(Θ-1)*dt*k[1][idxs] + Θ*dt*k[2][idxs])\n return (1-Θ)*y₀[idxs]+Θ*y₁[idxs]+Θ*(Θ-1)*((1-2Θ)*(y₁[idxs]-y₀[idxs])+(Θ-1)*dt*k[1][idxs] + Θ*dt*k[2][idxs])\nend\n\n@muladd function hermite_interpolant!(out,Θ,dt,y₀,y₁,k,idxs::Nothing,T::Type{Val{0}}) # Default interpolant is Hermite\n @inbounds @.. out = (1-Θ)*y₀+Θ*y₁+Θ*(Θ-1)*((1-2Θ)*(y₁-y₀)+(Θ-1)*dt*k[1] + Θ*dt*k[2])\n #@inbounds for i in eachindex(out)\n # out[i] = (1-Θ)*y₀[i]+Θ*y₁[i]+Θ*(Θ-1)*((1-2Θ)*(y₁[i]-y₀[i])+(Θ-1)*dt*k[1][i] + Θ*dt*k[2][i])\n #end\n #out\nend\n\n@muladd function hermite_interpolant!(out,Θ,dt,y₀,y₁,k,idxs,T::Type{Val{0}}) # Default interpolant is Hermite\n @views @.. out = (1-Θ)*y₀[idxs]+Θ*y₁[idxs]+Θ*(Θ-1)*((1-2Θ)*(y₁[idxs]-y₀[idxs])+(Θ-1)*dt*k[1][idxs] + Θ*dt*k[2][idxs])\n #@inbounds for (j,i) in enumerate(idxs)\n # out[j] = (1-Θ)*y₀[i]+Θ*y₁[i]+Θ*(Θ-1)*((1-2Θ)*(y₁[i]-y₀[i])+(Θ-1)*dt*k[1][i] + Θ*dt*k[2][i])\n #end\n #out\nend\n\n\"\"\"\nHerimte Interpolation, chosen if no other dispatch for ode_interpolant\n\"\"\"\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,::Type{Val{false}},idxs::Nothing,T::Type{Val{1}}) # Default interpolant is Hermite\n #@.. k[1] + Θ*(-4*dt*k[1] - 2*dt*k[2] - 6*y₀ + Θ*(3*dt*k[1] + 3*dt*k[2] + 6*y₀ - 6*y₁) + 6*y₁)/dt\n @inbounds k[1] + Θ*(-4*dt*k[1] - 2*dt*k[2] - 6*y₀ + Θ*(3*dt*k[1] + 3*dt*k[2] + 6*y₀ - 6*y₁) + 6*y₁)/dt\nend\n\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,::Type{Val{true}},idxs::Nothing,T::Type{Val{1}}) # Default interpolant is Hermite\n @inbounds @.. k[1] + Θ*(-4*dt*k[1] - 2*dt*k[2] - 6*y₀ + Θ*(3*dt*k[1] + 3*dt*k[2] + 6*y₀ - 6*y₁) + 6*y₁)/dt\nend\n\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,cache,idxs,T::Type{Val{1}}) # Default interpolant is Hermite\n # return @.. k[1][idxs] + Θ*(-4*dt*k[1][idxs] - 2*dt*k[2][idxs] - 6*y₀[idxs] + Θ*(3*dt*k[1][idxs] + 3*dt*k[2][idxs] + 6*y₀[idxs] - 6*y₁[idxs]) + 6*y₁[idxs])/dt\n return k[1][idxs] + Θ*(-4*dt*k[1][idxs] - 2*dt*k[2][idxs] - 6*y₀[idxs] + Θ*(3*dt*k[1][idxs] + 3*dt*k[2][idxs] + 6*y₀[idxs] - 6*y₁[idxs]) + 6*y₁[idxs])/dt\nend\n\n@muladd function hermite_interpolant!(out,Θ,dt,y₀,y₁,k,idxs::Nothing,T::Type{Val{1}}) # Default interpolant is Hermite\n @inbounds @.. out = k[1] + Θ*(-4*dt*k[1] - 2*dt*k[2] - 6*y₀ + Θ*(3*dt*k[1] + 3*dt*k[2] + 6*y₀ - 6*y₁) + 6*y₁)/dt\n #@inbounds for i in eachindex(out)\n # out[i] = k[1][i] + Θ*(-4*dt*k[1][i] - 2*dt*k[2][i] - 6*y₀[i] + Θ*(3*dt*k[1][i] + 3*dt*k[2][i] + 6*y₀[i] - 6*y₁[i]) + 6*y₁[i])/dt\n #end\n #out\nend\n\n@muladd function hermite_interpolant!(out,Θ,dt,y₀,y₁,k,idxs,T::Type{Val{1}}) # Default interpolant is Hermite\n @views @.. out = k[1][idxs] + Θ*(-4*dt*k[1][idxs] - 2*dt*k[2][idxs] - 6*y₀[idxs] + Θ*(3*dt*k[1][idxs] + 3*dt*k[2][idxs] + 6*y₀[idxs] - 6*y₁[idxs]) + 6*y₁[idxs])/dt\n #@inbounds for (j,i) in enumerate(idxs)\n # out[j] = k[1][i] + Θ*(-4*dt*k[1][i] - 2*dt*k[2][i] - 6*y₀[i] + Θ*(3*dt*k[1][i] + 3*dt*k[2][i] + 6*y₀[i] - 6*y₁[i]) + 6*y₁[i])/dt\n #end\n #out\nend\n\n\"\"\"\nHerimte Interpolation, chosen if no other dispatch for ode_interpolant\n\"\"\"\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,::Type{Val{false}},idxs::Nothing,T::Type{Val{2}}) # Default interpolant is Hermite\n #@.. (-4*dt*k[1] - 2*dt*k[2] - 6*y₀ + Θ*(6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁) + 6*y₁)/(dt*dt)\n @inbounds (-4*dt*k[1] - 2*dt*k[2] - 6*y₀ + Θ*(6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁) + 6*y₁)/(dt*dt)\nend\n\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,::Type{Val{true}},idxs::Nothing,T::Type{Val{2}}) # Default interpolant is Hermite\n #@.. (-4*dt*k[1] - 2*dt*k[2] - 6*y₀ + Θ*(6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁) + 6*y₁)/(dt*dt)\n @inbounds @.. (-4*dt*k[1] - 2*dt*k[2] - 6*y₀ + Θ*(6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁) + 6*y₁)/(dt*dt)\nend\n\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,cache,idxs,T::Type{Val{2}}) # Default interpolant is Hermite\n #out = similar(y₀,axes(idxs))\n #@views @.. out = (-4*dt*k[1][idxs] - 2*dt*k[2][idxs] - 6*y₀[idxs] + Θ*(6*dt*k[1][idxs] + 6*dt*k[2][idxs] + 12*y₀[idxs] - 12*y₁[idxs]) + 6*y₁[idxs])/(dt*dt)\n @views out = (-4*dt*k[1][idxs] - 2*dt*k[2][idxs] - 6*y₀[idxs] + Θ*(6*dt*k[1][idxs] + 6*dt*k[2][idxs] + 12*y₀[idxs] - 12*y₁[idxs]) + 6*y₁[idxs])/(dt*dt)\n out\nend\n\n@muladd function hermite_interpolant!(out,Θ,dt,y₀,y₁,k,idxs::Nothing,T::Type{Val{2}}) # Default interpolant is Hermite\n @inbounds @.. out = (-4*dt*k[1] - 2*dt*k[2] - 6*y₀ + Θ*(6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁) + 6*y₁)/(dt*dt)\n #@inbounds for i in eachindex(out)\n # out[i] = (-4*dt*k[1][i] - 2*dt*k[2][i] - 6*y₀[i] + Θ*(6*dt*k[1][i] + 6*dt*k[2][i] + 12*y₀[i] - 12*y₁[i]) + 6*y₁[i])/(dt*dt)\n #end\n #out\nend\n\n@muladd function hermite_interpolant!(out,Θ,dt,y₀,y₁,k,idxs,T::Type{Val{2}}) # Default interpolant is Hermite\n @views @.. out = (-4*dt*k[1][idxs] - 2*dt*k[2][idxs] - 6*y₀[idxs] + Θ*(6*dt*k[1][idxs] + 6*dt*k[2][idxs] + 12*y₀[idxs] - 12*y₁[idxs]) + 6*y₁[idxs])/(dt*dt)\n #@inbounds for (j,i) in enumerate(idxs)\n # out[j] = (-4*dt*k[1][i] - 2*dt*k[2][i] - 6*y₀[i] + Θ*(6*dt*k[1][i] + 6*dt*k[2][i] + 12*y₀[i] - 12*y₁[i]) + 6*y₁[i])/(dt*dt)\n #end\n #out\nend\n\n\"\"\"\nHerimte Interpolation, chosen if no other dispatch for ode_interpolant\n\"\"\"\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,::Type{Val{false}},idxs::Nothing,T::Type{Val{3}}) # Default interpolant is Hermite\n #@.. (6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁)/(dt*dt*dt)\n @inbounds (6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁)/(dt*dt*dt)\nend\n\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,::Type{Val{true}},idxs::Nothing,T::Type{Val{3}}) # Default interpolant is Hermite\n #@.. (6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁)/(dt*dt*dt)\n @inbounds @.. (6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁)/(dt*dt*dt)\nend\n\n@muladd function hermite_interpolant(Θ,dt,y₀,y₁,k,cache,idxs,T::Type{Val{3}}) # Default interpolant is Hermite\n #out = similar(y₀,axes(idxs))\n #@views @.. out = (6*dt*k[1][idxs] + 6*dt*k[2][idxs] + 12*y₀[idxs] - 12*y₁[idxs])/(dt*dt*dt)\n @views out = (6*dt*k[1][idxs] + 6*dt*k[2][idxs] + 12*y₀[idxs] - 12*y₁[idxs])/(dt*dt*dt)\n out\nend\n\n@muladd function hermite_interpolant!(out,Θ,dt,y₀,y₁,k,idxs::Nothing,T::Type{Val{3}}) # Default interpolant is Hermite\n @inbounds @.. out = (6*dt*k[1] + 6*dt*k[2] + 12*y₀ - 12*y₁)/(dt*dt*dt)\n #for i in eachindex(out)\n # out[i] = (6*dt*k[1][i] + 6*dt*k[2][i] + 12*y₀[i] - 12*y₁[i])/(dt*dt*dt)\n #end\n #out\nend\n\n@muladd function hermite_interpolant!(out,Θ,dt,y₀,y₁,k,idxs,T::Type{Val{3}}) # Default interpolant is Hermite\n @views @.. out = (6*dt*k[1][idxs] + 6*dt*k[2][idxs] + 12*y₀[idxs] - 12*y₁[idxs])/(dt*dt*dt)\n #for (j,i) in enumerate(idxs)\n # out[j] = (6*dt*k[1][i] + 6*dt*k[2][i] + 12*y₀[i] - 12*y₁[i])/(dt*dt*dt)\n #end\n #out\nend\n\n######################## Linear Interpolants\n\n@muladd @inline function linear_interpolant(Θ,dt,y₀,y₁,idxs::Nothing,T::Type{Val{0}})\n Θm1 = (1-Θ)\n @.. Θm1*y₀ + Θ*y₁\nend\n\n@muladd @inline function linear_interpolant(Θ,dt,y₀,y₁,idxs,T::Type{Val{0}})\n Θm1 = (1-Θ)\n @.. Θm1*y₀[idxs] + Θ*y₁[idxs]\nend\n\n@muladd @inline function linear_interpolant!(out,Θ,dt,y₀,y₁,idxs::Nothing,T::Type{Val{0}})\n Θm1 = (1-Θ)\n @.. out = Θm1*y₀ + Θ*y₁\n out\nend\n\n@muladd @inline function linear_interpolant!(out,Θ,dt,y₀,y₁,idxs,T::Type{Val{0}})\n Θm1 = (1-Θ)\n @views @.. out = Θm1*y₀[idxs] + Θ*y₁[idxs]\n out\nend\n\n\"\"\"\nLinear Interpolation\n\"\"\"\n@inline function linear_interpolant(Θ,dt,y₀,y₁,idxs::Nothing,T::Type{Val{1}})\n (y₁ - y₀)/dt\nend\n\n@inline function linear_interpolant(Θ,dt,y₀,y₁,idxs,T::Type{Val{1}})\n @.. (y₁[idxs] - y₀[idxs])/dt\nend\n\n@inline function linear_interpolant!(out,Θ,dt,y₀,y₁,idxs::Nothing,T::Type{Val{1}})\n @.. out = (y₁ - y₀)/dt\n out\nend\n\n@inline function linear_interpolant!(out,Θ,dt,y₀,y₁,idxs,T::Type{Val{1}})\n @views @.. out = (y₁[idxs] - y₀[idxs])/dt\n out\nend\n", "meta": {"hexsha": "103513b988e4647afdd2bd0a856a83c5319fe28c", "size": 25549, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dense/generic_dense.jl", "max_stars_repo_name": "jgreener64/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "14bd5885de76cadfdebbae6d7ee5346efb765f91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-23T14:29:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T12:22:08.000Z", "max_issues_repo_path": "src/dense/generic_dense.jl", "max_issues_repo_name": "ErikQQY/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "8af792fef61c537e462819b61cd5a58dda6b1bd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dense/generic_dense.jl", "max_forks_repo_name": "ErikQQY/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "8af792fef61c537e462819b61cd5a58dda6b1bd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9439102564, "max_line_length": 165, "alphanum_fraction": 0.6464049474, "num_tokens": 9982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2478155451490631}} {"text": "\"\"\"测试不同的粒度,bubble的区别\"\"\"\n\n\nusing Plots\nusing MARY_fRG.Basics\nusing MARY_fRG.Drawers\nusing MARY_fRG.Fermi\nusing MARY_fRG.Fermi.Patch\nusing MARY_fRG.Fermi.Kagome\nusing MARY_fRG.FlowEquation\n\n\n\"\"\"筛选tris\"\"\"\nfunction fliter(Γ4::Gamma4{T, P}, lval) where {T, P}\n lamb = Γ4.λ_0 * exp(-lval)\n resltris::Vector{P} = []\n reslpats::Vector{Int64} = []\n cert = 1#length(Γ4.ltris) > 2000000 ? 5 : 15\n mintri = missing\n minpat = missing\n mineng = 10.\n for (tri, pat) in zip(Γ4.ltris, Γ4.lpats)\n if pat != 1\n continue\n end\n engs = [Γ4.model.dispersion[bidx](\n tri.center.x, tri.center.y) / lamb for bidx in 1:1:Γ4.model.bandnum\n ]\n #如果还有可能有贡献\n if minimum(abs.(engs)) < cert #&& minimum(abs.(engs2)) > cert # && pat == 1# && minimum(abs.(engs)) > 0.1\n push!(resltris, tri)\n push!(reslpats, pat)\n end\n #if minimum(abs.(engs)) < mineng\n # mintri = tri\n # minpat = pat\n # mineng = minimum(abs.(engs))\n #end\n end\n #\n #resltris = [mintri]#resltris[1:1]\n #reslpats = [minpat]#reslpats[1:1]\n #\n ltris_pat = Vector{typeof(resltris)}(undef, Γ4.patchnum)\n for idx in 1:1:Γ4.patchnum\n ltris_pat[idx] = []\n end\n #\n for (tri, pat) in zip(resltris, reslpats)\n push!(ltris_pat[pat], tri)\n end\n #\n return Gamma4(\n Γ4.model,\n Γ4.λ_0,\n Γ4.V,\n Γ4.k4tab,\n Γ4.patchnum,\n Γ4.patches,\n resltris, reslpats, nothing, ltris_pat\n )\nend\n\n\nfunction refine(Γ4::Gamma4{T, P}) where {T, P}\n resltris::Vector{P} = []\n reslpats::Vector{Int64} = []\n resltris = refine_list_triangle(Γ4.ltris, 5)\n reslpats = group_ltris_into_patches_mt(resltris, Γ4.model.brillouin, Γ4.patchnum)\n #\n #resltris = [mintri]#resltris[1:1]\n #reslpats = [minpat]#reslpats[1:1]\n #\n ltris_pat = Vector{typeof(resltris)}(undef, Γ4.patchnum)\n for idx in 1:1:Γ4.patchnum\n ltris_pat[idx] = []\n end\n #\n for (tri, pat) in zip(resltris, reslpats)\n push!(ltris_pat[pat], tri)\n end\n #\n return Gamma4(\n Γ4.model,\n Γ4.λ_0,\n Γ4.V,\n Γ4.k4tab,\n Γ4.patchnum,\n Γ4.patches,\n resltris, reslpats, nothing, ltris_pat\n )\nend\n\n\nfunction run_rftf()\n model = common_square_lattice(0.20)\n disp = model.dispersion[1]\n lval = 15.\n #500\n Γ4_5 = TFGamma4(\n model, 8.0, 16, 500\n )\n Γ4_5.V .+= 1.0\n Γ4_5_1 = fliter(Γ4_5, 11.0)\n Γ4_5_2 = fliter(Γ4_5, 12.0)\n println(length(Γ4_5_1.ltris))\n println(length(Γ4_5_2.ltris))\n #fliter2\n bubbval_fs = Array{Float64, 2}(undef, Γ4_5_2.patchnum, Γ4_5_2.patchnum)\n lamb = Γ4_5_2.λ_0 * exp(-lval)\n println(\"lamb \", lamb)\n Threads.@threads for idxs in CartesianIndices(bubbval_fs)\n i2, i3 = Tuple(idxs)\n k2, k3 = Γ4_5_2.patches[1][i2], Γ4_5_2.patches[1][i3]\n q_fs = Γ4_5_2.model.kadd(k3, -k2)\n bubbres = pi_αβ_plus_tf(\n Γ4_5_2.ltris, area(Γ4_5_2.model.brillouin),\n lamb, q_fs, Γ4_5_2.model.dispersion[1],\n Γ4_5_2.model.dispersion[1], Γ4_5_2.model.kadd\n )\n bubbval_fs[i2, i3] = bubbres\n end\n plt = heatmap(1e5*bubbval_fs)\n @savepng plt \"bubb_5_2_2\"\n #fliter1\n bubbval_fs = Array{Float64, 2}(undef, Γ4_5_1.patchnum, Γ4_5_1.patchnum)\n lamb = Γ4_5_1.λ_0 * exp(-lval)\n Threads.@threads for idxs in CartesianIndices(bubbval_fs)\n i2, i3 = Tuple(idxs)\n k2, k3 = Γ4_5_1.patches[1][i2], Γ4_5_1.patches[1][i3]\n q_fs = Γ4_5_1.model.kadd(k3, -k2)\n bubbres = pi_αβ_plus_tf(\n Γ4_5_1.ltris, area(Γ4_5_1.model.brillouin),\n lamb, q_fs, Γ4_5_1.model.dispersion[1],\n Γ4_5_1.model.dispersion[1], Γ4_5_1.model.kadd\n )\n bubbval_fs[i2, i3] = bubbres\n end\n plt = heatmap(1e5*bubbval_fs)\n @savepng plt \"bubb_5_2_1\"\n #fliter3\n ltris3::Vector{Basics.AbstractTriangle{:RT}} = []\n ltris4::Vector{Basics.AbstractTriangle{:RT}} = []\n for tri in Γ4_5_1.ltris\n if !any(map((x)->x==tri, Γ4_5_2.ltris))\n push!(ltris4, tri)\n end\n end\n #push!(ltris3, Γ4_5_2.ltris[1])\n #println(Γ4_5_2.ltris[1])\n #println(disp(Γ4_5_2.ltris[1].center.x, Γ4_5_2.ltris[1].center.y))\n #push!(ltris3, Γ4_5_2.ltris[2])\n push!(ltris3, Γ4_5_2.ltris[3])\n #push!(ltris3, ltris4[1])\n push!(ltris3, ltris4[2])\n println(disp(ltris4[2].center.x, ltris4[2].center.y))\n #push!(ltris3, ltris4[3])\n println(length(ltris3))\n bubbval_fs = Array{Float64, 2}(undef, Γ4_5_1.patchnum, Γ4_5_1.patchnum)\n lamb = Γ4_5_1.λ_0 * exp(-lval)\n Threads.@threads for idxs in CartesianIndices(bubbval_fs)\n i2, i3 = Tuple(idxs)\n k2, k3 = Γ4_5_1.patches[1][i2], Γ4_5_1.patches[1][i3]\n q_fs = Γ4_5_1.model.kadd(k3, -k2)\n bubbres = pi_αβ_plus_tf(\n ltris3, area(Γ4_5_1.model.brillouin),\n lamb, q_fs, Γ4_5_1.model.dispersion[1],\n Γ4_5_1.model.dispersion[1], Γ4_5_1.model.kadd\n )\n bubbval_fs[i2, i3] = bubbres\n end\n plt = heatmap(1e5*bubbval_fs)\n @savepng plt \"bubb_5_2_3\"\n return\n #plt = draw_points([tri.center for tri in Γ4_5.ltris])\n #abses = [abs(disp(tri.center.x, tri.center.y)) for tri in Γ4_5.ltris]\n #println(minimum(abses))\n #abscount = 0\n #for ae in abses\n # if ae < 0.01\n # abscount += 1\n # end\n #end\n #println(abscount)\n #@savepng plt \"diffe1\"\n println(Γ4_5.ltris[1])\n bubb_pp_5, bubb_fs_5, bubb_ex_5 = all_bubble_tf_mt(Γ4_5, lval)\n println(\"500时的贡献 \", sum(abs.(bubb_fs_5.V)))\n println(\"500时最大\", findmax(abs.(bubb_fs_5.V)))\n k1, k2 = Γ4_5.patches[1][12], Γ4_5.patches[1][4]\n println(k1)\n println(k2)\n kprim = Γ4_5.model.kadd(k1, k2)\n println(kprim)\n kprim = Γ4_5.model.kadd(kprim, -Γ4_5.ltris[1].center)\n println(kprim)\n println(\"kprim disp \", Γ4_5.model.dispersion[1](kprim.x, kprim.y))\n \n return\n ###\n #100\n Γ4_1 = TFGamma4(\n model, 8.0, 16, 800\n )\n Γ4_1.V .+= 1.0\n #Γ4_1 = fliter_away_surface(Γ4_1, 10.0)\n #plt = draw_points([tri.center for tri in Γ4_1.ltris])\n #@savepng plt \"diffe3\"\n #Γ4_1 = TFGamma4_addition_ltris_mt(Γ4_1, 10.0)\n Γ4_1 = fliter(Γ4_1, 12.0)\n #println(Γ4_1.ltris)\n #plt = draw_polygon(Γ4_1.ltris)\n #plot!(plt, aspect_ratio=:equal)\n #@savepng plt \"diffe4\"\n Γ4_1 = refine(Γ4_1)\n #println(Γ4_1.ltris)\n plt = draw_polygon(Γ4_1.ltris)\n #plot!(plt, aspect_ratio=:equal)\n #@savepng plt \"diffe5\"\n Γ4_1 = fliter(Γ4_1, 12.0)\n abses = [abs(disp(tri.center.x, tri.center.y)) for tri in Γ4_1.ltris]\n println(minimum(abses))\n abscount = 0\n for ae in abses\n if ae < 0.01\n abscount += 1\n end\n end\n println(abscount)\n #println(minimum([abs(disp(tri.center.x, tri.center.y)) for tri in Γ4_1.ltris]))\n plt = draw_points([tri.center for tri in Γ4_1.ltris])\n @savepng plt \"diffe2\"\n println(Γ4_1.ltris[1])\n k1, k2 = Γ4_1.patches[1][11], Γ4_1.patches[1][3]\n println(k1)\n println(k2)\n kprim = Γ4_1.model.kadd(k1, k2)\n println(kprim)\n kprim = Γ4_1.model.kadd(kprim, -Γ4_1.ltris[1].center)\n println(kprim)\n println(\"kprim disp \", Γ4_1.model.dispersion[1](kprim.x, kprim.y))\n bubb_pp_1, bubb_fs_1, bubb_ex_1 = all_bubble_tf_mt(Γ4_1, lval)\n println(\"200时的贡献 \", sum(abs.(bubb_pp_1.V)))\n println(\"200时最大\", findmax(abs.(bubb_pp_1.V)))\n #500和100的差\n diffe = bubb_pp_5.V - bubb_pp_1.V\n diffe = abs.(diffe)\n println(sum(diffe))\n println(sum(abs.(bubb_pp_1.V)))\n #refine\n #Γ4_r = TFGamma4_addition_ltris_mt(Γ4_1, lval)\n #bubb_pp_r, bubb_fs_r, bubb_ex_r = all_bubble_tf_mt(Γ4_r, lval)\n ##500和100的差\n #diffe = bubb_pp_5.V - bubb_pp_r.V\n #diffe = abs.(diffe)\n #println(sum(diffe))\nend\n\n\n#run_rftf()\n\n\n\nfunction run_rf_ult()\n #model = common_square_lattice(0.20)\n model = upperband_kagome_lattice(-0.2)\n disp = model.dispersion[1]\n lval = 17.\n #500\n Γ4_5 = TFGamma4(\n model, 8.0, 24, 500\n )\n Γ4_5.V .+= 1.0\n #Γ4_5 = fliter(Γ4_5, 12.0)\n #plt = draw_points([tri.center for tri in Γ4_5.ltris])\n #abses = [abs(disp(tri.center.x, tri.center.y)) for tri in Γ4_5.ltris]\n #println(minimum(abses))\n #abscount = 0\n #for ae in abses\n # if ae < 0.01\n # abscount += 1\n # end\n #end\n #println(abscount)\n #@savepng plt \"diffe1\"\n println(Γ4_5.ltris[1])\n bubb_pp_5, bubb_fs_5, bubb_ex_5 = all_bubble_tf_mt(Γ4_5, lval)\n println(\"500时的贡献 \", sum(abs.(bubb_pp_5.V)))\n println(\"500时最大\", findmax(abs.(bubb_pp_5.V)))\n ###\n #100\n Γ4_1 = TFGamma4(\n model, 8.0, 24, 200\n )\n Γ4_1.V .+= 1.0\n bubb_pp_1, bubb_fs_1, bubb_ex_1 = all_bubble_tf_mt(Γ4_1, lval)\n println(\"200时的贡献 \", sum(abs.(bubb_pp_1.V)))\n println(\"200时最大\", findmax(abs.(bubb_pp_1.V)))\n ###\n #ult\n Γ4_1 = fliter_away_surface(Γ4_1, 6.0)\n Γ4_1 = refine_to_surface(Γ4_1)\n while length(Γ4_1.ltris) < 1000000\n Γ4_1 = refine_to_surface(Γ4_1)\n end\n plt = draw_points([tri.center for tri in Γ4_1.ltris])\n @savepng plt \"diffe6\"\n println(\"tri大小\", length(Γ4_1.ltris))\n maxi, mini = engpeak_to_surface(Γ4_1)\n println(maxi, \" \", mini)\n bubb_pp_u, bubb_fs_u, bubb_ex_u = all_bubble_tf_ult_mt(Γ4_1, maxi)\n println(\"ult时的贡献 \", sum(abs.(bubb_pp_u.V)))\n println(\"ult时最大\", findmax(abs.(bubb_pp_u.V)))\n #500和100的差\n diffe = bubb_pp_5.V - bubb_pp_1.V\n diffe = abs.(diffe)\n println(sum(diffe))\n println(sum(abs.(bubb_pp_1.V)))\n #500个ult的差\n diffe = bubb_pp_5.V - bubb_pp_u.V\n diffe = abs.(diffe)\n println(sum(diffe))\n println(sum(abs.(bubb_pp_u.V)))\n #ult和500的画图\n plt = heatmap(1e5*bubb_pp_u.V[1, 1, 1, 1, 1, :, :])\n png(plt, \"bubb_u1\")\n plt = heatmap(1e5*bubb_pp_u.V[1, 1, 1, 1, 2, :, :])\n png(plt, \"bubb_u2\")\n plt = heatmap(1e5*bubb_pp_u.V[1, 1, 1, 1, 3, :, :])\n png(plt, \"bubb_u3\")\n plt = heatmap(1e5*bubb_pp_u.V[1, 1, 1, 1, 4, :, :])\n png(plt, \"bubb_u4\")\n plt = heatmap(1e5*bubb_pp_5.V[1, 1, 1, 1, 1, :, :])\n png(plt, \"bubb_51\")\n plt = heatmap(1e5*bubb_pp_5.V[1, 1, 1, 1, 2, :, :])\n png(plt, \"bubb_52\")\n plt = heatmap(1e5*bubb_pp_5.V[1, 1, 1, 1, 3, :, :])\n png(plt, \"bubb_53\")\n plt = heatmap(1e5*bubb_pp_5.V[1, 1, 1, 1, 4, :, :])\n png(plt, \"bubb_54\")\n println(Γ4_1.patches[1][1], Γ4_1.patches[1][4], Γ4_1.patches[1][9])\nend\n\n\nrun_rf_ult()\n", "meta": {"hexsha": "408cb77ae3b37ba050b92f23bd2a04afd6d2bbed", "size": 10487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_bubble/test_difference.jl", "max_stars_repo_name": "maryprimary/mary_frg.jl", "max_stars_repo_head_hexsha": "981b2bd3e7ac04823a102567ab7c9de1fd482c33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_bubble/test_difference.jl", "max_issues_repo_name": "maryprimary/mary_frg.jl", "max_issues_repo_head_hexsha": "981b2bd3e7ac04823a102567ab7c9de1fd482c33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_bubble/test_difference.jl", "max_forks_repo_name": "maryprimary/mary_frg.jl", "max_forks_repo_head_hexsha": "981b2bd3e7ac04823a102567ab7c9de1fd482c33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3092485549, "max_line_length": 113, "alphanum_fraction": 0.598264518, "num_tokens": 4357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24756165565773547}} {"text": "using StructArrays\nusing ChainRulesCore: NoTangent\n\nstruct ∇getindex{T,S}\n xs::T\n i::S\nend\n\nfunction (g::∇getindex)(Δ)\n Δ′ = zero(g.xs)\n Δ′[g.i...] = Δ\n (ChainRulesCore.NoTangent(), Δ′, map(_ -> nothing, g.i)...)\nend\n\nfunction ChainRulesCore.rrule(g::∇getindex, Δ)\n g(Δ), Δ′′->(nothing, Δ′′[1][g.i...])\nend\n\nfunction ChainRulesCore.rrule(::typeof(getindex), xs::Array, i...)\n xs[i...], ∇getindex(xs, i)\nend\n\nfunction reversediff(f, xs...)\n y, f☆ = ∂⃖(f, xs...)\n return tuple(y, tail(f☆(dx(y)))...)\nend\n\nfunction reversediff_array(f, xs::Vector...)\n fieldarrays(StructArray(reversediff(f, x...) for x in zip(xs...)))\nend\n\nfunction reversediff_array(f, xs::Vector)\n fieldarrays(StructArray(reversediff(f, x) for x in xs))\nend\n\nfunction assert_gf(f)\n @assert sizeof(sin) == 0\nend\n\nfunction ChainRulesCore.rrule(::typeof(assert_gf), f)\n assert_gf(f), Δ->begin\n (NoTangent(), NoTangent())\n end\nend\n\n#=\nfunction ChainRulesCore.rrule(::typeof(map), f, xs::Vector...)\n assert_gf(f)\n primal, dual = reversediff_array(f, xs...)\n primal, Δ->begin\n (NoTangent(), NoTangent(), ntuple(i->map(*, getfield(dual, i), Δ), length(dual))...)\n end\nend\n=#\n\n# Disable thunk versions of ChainRules, which interfere with higher order AD\n\nfunction rrule_times(::typeof(*), A::AbstractVecOrMat, B::AbstractVecOrMat)\n function times_pullback(Ȳ)\n return (NoTangent(), Ȳ * Base.adjoint(B), Base.adjoint(A) * Ȳ)\n end\n return A * B, times_pullback\nend\n\nfunction rrule_times(::typeof(*), A::AbstractVector{<:ChainRules.CommutativeMulNumber}, B::AbstractMatrix{<:ChainRules.CommutativeMulNumber})\n function times_pullback(Ȳ)\n return (NoTangent(), Ȳ * Base.adjoint(B), Base.adjoint(A) * Ȳ)\n end\n return A * B, times_pullback\nend\n\nrrule_times(::typeof(*), args...) = rrule(*, args...)\n\nfunction (::∂⃖{N})(f::typeof(*), args...) where {N}\n if N == 1\n z = rrule_times(f, args...)\n if z === nothing\n return ∂⃖recurse{1}()(f, args...)\n end\n return z\n else\n ∂⃖p = ∂⃖{minus1(N)}()\n @destruct z, z̄ = ∂⃖p(rrule_times, f, args...)\n if z === nothing\n return ∂⃖recurse{N}()(f, args...)\n else\n return ∂⃖rrule{N}()(z, z̄)\n end\n end\nend\n\nfunction ChainRulesCore.frule((_, ∂A, ∂B), ::typeof(*), A::AbstractMatrix{<:Real}, B::AbstractVector{<:Real})\n return (A * B, ∂A * B + A * ∂B)\nend\n\n#=\nfunction ChainRulesCore.rrule(::typeof(map), f, xs::Vector)\n assert_gf(f)\n arrs = reversediff_array(f, xs)\n primal = getfield(arrs, 1)\n primal, let dual = getfield(arrs, 2)\n Δ->(NoTangent(), NoTangent(), map(*, dual, unthunk(Δ)))\n end\nend\n=#\n\n#=\nfunction ChainRulesCore.rrule(::typeof(map), f, xs::Vector, ys::Vector)\n assert_gf(f)\n arrs = reversediff_array(f, xs, ys)\n primal = getfield(arrs, 1)\n primal, let dual = tail(arrs)\n Δ->(NoTangent(), NoTangent(), map(*, getfield(dual, 1), Δ), map(*, getfield(dual, 2), Δ))\n end\nend\n=#\n\nxsum(x::Vector) = sum(x)\nfunction ChainRulesCore.rrule(::typeof(xsum), x::Vector)\n xsum(x), let xdims=size(x)\n Δ->(NoTangent(), xfill(Δ, xdims...))\n end\nend\n\nxfill(x, dims...) = fill(x, dims...)\nfunction ChainRulesCore.rrule(::typeof(xfill), x, dim)\n xfill(x, dim), Δ->(NoTangent(), xsum(Δ), NoTangent())\nend\n\nstruct NonDiffEven{N, O, P}; end\nstruct NonDiffOdd{N, O, P}; end\n\n(::NonDiffOdd{N, O, P})(Δ) where {N, O, P} = (ntuple(_->ZeroTangent(), N), NonDiffEven{N, plus1(O), P}())\n(::NonDiffEven{N, O, P})(Δ...) where {N, O, P} = (ZeroTangent(), NonDiffOdd{N, plus1(O), P}())\n(::NonDiffOdd{N, O, O})(Δ) where {N, O} = ntuple(_->ZeroTangent(), N)\n\n# This should not happen\n(::NonDiffEven{N, O, O})(Δ...) where {N, O} = error()\n\n@Base.pure function ChainRulesCore.rrule(::typeof(Core.apply_type), head, args...)\n Core.apply_type(head, args...), NonDiffOdd{plus1(plus1(length(args))), 1, 1}()\nend\n\nfunction ChainRulesCore.rrule(::typeof(Core.tuple), args...)\n Core.tuple(args...), Δ->Core.tuple(NoTangent(), Δ...)\nend\n\n# TODO: What to do about these integer rules\n@ChainRulesCore.non_differentiable Base.rem(a::Integer, b::Type)\n\nChainRulesCore.canonicalize(::ChainRulesCore.ZeroTangent) = ChainRulesCore.ZeroTangent()\n\n# Skip AD'ing through the axis computation\nfunction ChainRules.rrule(::typeof(Base.Broadcast.instantiate), bc::Base.Broadcast.Broadcasted)\n return Base.Broadcast.instantiate(bc), Δ->begin\n Core.tuple(NoTangent(), Δ)\n end\nend\n\n\nusing StaticArrays\n\n# Force the static arrays constructor to use a vector representation of\n# the cotangent space.\n\nstruct to_tuple{N}; end\n@generated function (::to_tuple{N})(Δ) where {N}\n :( (NoTangent(), Core.tuple( $( ( :(Δ[$i]) for i = 1:N )...) )) )\nend\n(::to_tuple)(Δ::SArray) = getfield(Δ, :data)\n\nfunction ChainRules.rrule(::Type{SArray{S, T, N, L}}, x::NTuple{L,T}) where {S, T, N, L}\n SArray{S, T, N, L}(x), to_tuple{L}()\nend\n\nfunction ChainRules.rrule(::Type{SArray{S, T, N, L}}, x::NTuple{L,Any}) where {S, T, N, L}\n SArray{S, T, N, L}(x), to_tuple{L}()\nend\n\nfunction ChainRules.frule((_, ∂x), ::Type{SArray{S, T, N, L}}, x::NTuple{L,T}) where {S, T, N, L}\n SArray{S, T, N, L}(x), SArray{S, T, N, L}(∂x)\nend\n\nfunction ChainRules.frule((_, ∂x), ::Type{SArray{S, T, N, L}}, x::NTuple{L,Any}) where {S, T, N, L}\n SArray{S, T, N, L}(x), SArray{S}(∂x)\nend\n\n@ChainRulesCore.non_differentiable StaticArrays.promote_tuple_eltype(T)\n\nfunction ChainRules.frule((_, ∂A), ::typeof(getindex), A::AbstractArray, args...)\n getindex(A, args...), getindex(∂A, args...)\nend\n\nfunction ChainRules.rrule(::typeof(map), ::typeof(+), A::AbstractArray, B::AbstractArray)\n map(+, A, B), Δ->(NoTangent(), NoTangent(), Δ, Δ)\nend\n\nfunction ChainRules.rrule(::typeof(map), ::typeof(+), A::AbstractVector, B::AbstractVector)\n map(+, A, B), Δ->(NoTangent(), NoTangent(), Δ, Δ)\nend\n\nfunction ChainRules.rrule(AT::Type{<:Array{T,N}}, x::AbstractArray{S,N}) where {T,S,N}\n # We're leaving these in the eltype that the cotangent vector already has.\n # There isn't really a good reason to believe we should convert to the\n # original array type, so don't unless explicitly requested.\n AT(x), Δ->(NoTangent(), Δ)\nend\n\nfunction ChainRules.rrule(AT::Type{<:Array}, undef::UndefInitializer, args...)\n # We're leaving these in the eltype that the cotangent vector already has.\n # There isn't really a good reason to believe we should convert to the\n # original array type, so don't unless explicitly requested.\n AT(undef, args...), Δ->(NoTangent(), NoTangent(), ntuple(_->NoTangent(), length(args))...)\nend\n\nfunction unzip_tuple(t::Tuple)\n map(x->x[1], t), map(x->x[2], t)\nend\n\nfunction ChainRules.rrule(::typeof(unzip_tuple), args::Tuple)\n unzip_tuple(args), Δ->(NoTangent(), map((x,y)->(x,y), Δ...))\nend\n\nstruct BackMap{T}\n f::T\nend\n(f::BackMap{N})(args...) where {N} = ∂⃖¹(getfield(f, :f), args...)\nback_apply(x, y) = x(y)\nback_apply_zero(x) = x(Zero())\n\nfunction ChainRules.rrule(::typeof(map), f, args::Tuple)\n a, b = unzip_tuple(map(BackMap(f), args))\n function back(Δ)\n (fs, xs) = unzip_tuple(map(back_apply, b, Δ))\n (NoTangent(), sum(fs), xs)\n end\n function back(Δ::ZeroTangent)\n (fs, xs) = unzip_tuple(map(back_apply_zero, b))\n (NoTangent(), sum(fs), xs)\n end\n a, back\nend\n\nfunction ChainRules.rrule(::typeof(Base.ntuple), f, n)\n a, b = unzip_tuple(ntuple(BackMap(f), n))\n a, function (Δ)\n (NoTangent(), sum(map(back_apply, b, Δ)), NoTangent())\n end\nend\n\nfunction ChainRules.frule(_, ::Type{Vector{T}}, undef::UndefInitializer, dims::Int...) where {T}\n Vector{T}(undef, dims...), zeros(T, dims...)\nend\n\n@ChainRules.non_differentiable Base.:(|)(a::Integer, b::Integer)\n@ChainRules.non_differentiable Base.throw(err)\n@ChainRules.non_differentiable Core.Compiler.return_type(args...)\nChainRulesCore.canonicalize(::NoTangent) = NoTangent()\n\n# Disable thunking at higher order (TODO: These should go into ChainRulesCore)\nfunction ChainRulesCore.rrule(::Type{Thunk}, thnk)\n z, ∂z = ∂⃖¹(thnk)\n z, Δ->(NoTangent(), ∂z(Δ)...)\nend\n\nfunction ChainRulesCore.rrule(::Type{InplaceableThunk}, add!!, val)\n val, Δ->(NoTangent(), NoTangent(), Δ)\nend\n", "meta": {"hexsha": "4d22c1726bbab5d41822d269d50a4fa482568e53", "size": 8255, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/extra_rules.jl", "max_stars_repo_name": "atiyo/Diffractor.jl", "max_stars_repo_head_hexsha": "bc22ad68a59b2f013d9f934de00bb7a2c1edf605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 245, "max_stars_repo_stars_event_min_datetime": "2021-07-26T16:02:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T20:20:16.000Z", "max_issues_repo_path": "src/extra_rules.jl", "max_issues_repo_name": "atiyo/Diffractor.jl", "max_issues_repo_head_hexsha": "bc22ad68a59b2f013d9f934de00bb7a2c1edf605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2021-07-26T21:32:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T16:16:04.000Z", "max_forks_repo_path": "src/extra_rules.jl", "max_forks_repo_name": "atiyo/Diffractor.jl", "max_forks_repo_head_hexsha": "bc22ad68a59b2f013d9f934de00bb7a2c1edf605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-07-27T13:50:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T23:21:02.000Z", "avg_line_length": 30.687732342, "max_line_length": 141, "alphanum_fraction": 0.6336765597, "num_tokens": 2728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2474388945535826}} {"text": "\"\"\"\n\nnew optimazation idea - try to put all data in boolean arrays in shared memory when getting means\nnext we would need only to read shared memory - yet first one need to check wheather there would be enough shmem on device\n\n\n\ncalculating intercalss correlation\n\"\"\"\nmodule InterClassCorrKernel\n\nusing CUDA, ..CUDAGpuUtils ,..IterationUtils,..ReductionUtils , ..MemoryUtils,..CUDAAtomicUtils\n\nexport prepareInterClassCorrKernel,calculateInterclassCorr\n\n\"\"\"\npreparation for the interclass correlation kernel - we prepare the GPU arrays - in this kernel they are small , calculate required loop iterations \nand using occupancy API calculate optimal number of threads and blocks for both kernels \nalso return arguments lists for both kernels\n\"\"\"\nfunction prepareInterClassCorrKernel()\n mainArrDims= (2,2,2)\n sumOfGold= CUDA.zeros(1);\n sumOfSegm= CUDA.zeros(1);\n sswTotal= CUDA.zeros(1);\n ssbTotal= CUDA.zeros(1);\n numberToLooFor= 1\n totalNumbOfVoxels= (mainArrDims[1]*mainArrDims[2]*mainArrDims[3])\n pixPerSlice = mainArrDims[1]*mainArrDims[2]\n iterLoop=5\n argsMain=(sumOfGold,sumOfSegm\n ,sswTotal\n ,ssbTotal\n ,iterLoop,pixPerSlice,totalNumbOfVoxels\n ,numberToLooFor )\n get_shmem(threads) = 4*33+3 #the same for both kernels\n threads,blocks =getThreadsAndBlocksNumbForKernel(get_shmem, kernel_InterClassCorr,(CUDA.zeros(2,2,2),CUDA.zeros(2,2,2),argsMain...))\n totalNumbOfVoxels= (mainArrDims[1]*mainArrDims[2]*mainArrDims[3])\n pixPerSlice= cld(totalNumbOfVoxels,blocks)\n iterLoop = UInt32(fld(pixPerSlice, threads[1]*threads[2]))\n\n argsMain=(sumOfGold,sumOfSegm\n ,sswTotal\n ,ssbTotal\n ,iterLoop,pixPerSlice,totalNumbOfVoxels\n ,numberToLooFor )\n\n\n return(argsMain, threads,blocks, totalNumbOfVoxels)\nend\n\n\n\n\n\n\n\n\n\n\"\"\"\ncalculates slicewise and global interclass correlation metric\n\"\"\"\nfunction calculateInterclassCorr(flatGold\n ,flatSegm,threads,blocks\n ,args,numberToLooFor)::Float64\n mainArrDims= size(flatGold)\n totalNumbOfVoxels= length(flatGold)\n pixPerSlice= cld(totalNumbOfVoxels,blocks)\n iterLoop = UInt32(fld(pixPerSlice, threads[1]*threads[2]))\n #resetting\n for i in 1:4 \n CUDA.fill!(args[i],0)\n end\n argsMain=(args[1],args[2]\n ,args[3]\n ,args[4]\n ,iterLoop,pixPerSlice,totalNumbOfVoxels\n ,numberToLooFor ) \n\n@cuda threads=threads blocks=blocks cooperative = true kernel_InterClassCorr(flatGold,flatSegm,argsMain...)\n\n # println(\"grandMean[1] $(grandMean[1]) \\n\")\n# @cuda threads=threads blocks=blocks kernel_InterClassCorr(flatGold ,flatSegm,args... )\n ssw = args[3][1]/args[7];\n ssb = args[4][1]/(args[7]-1) * 2;\n \n return (ssb - ssw)/(ssb + ssw);\n \nend\n\n\n\"\"\"\nadapted from https://github.com/JuliaGPU/CUDA.jl/blob/afe81794038dddbda49639c8c26469496543d831/src/mapreduce.jl\ngoldBoolGPU - array holding data of gold standard bollean array\nsegmBoolGPU - boolean array with the data we want to compare with gold standard\nic - holding single value for global interclass correlation\nintermediateRes- array holding slice wise results for ic\nloopNumb - number of times the single lane needs to loop in order to get all needed data\nsliceEdgeLength - length of edge of the slice we need to square this number to get number of pixels in a slice\namountOfWarps - how many warps we can stick in the block\n\"\"\"\n\nfunction kernel_InterClassCorr(flatGold ,flatSegm,sumOfGold,sumOfSegm\n ,sswTotal\n ,ssbTotal\n ,iterLoop,pixPerSlice,totalNumbOfVoxels\n ,numberToLooFor )\n grid_handle = this_grid()\n\n #for storing results from warp reductions\n shmemSum = @cuStaticSharedMem(Float32, (32,2)) #thread local values that are meant to store some results - like means ... \n grandMeanShmem = @cuStaticSharedMem(Float32, (1)) \n offsetIter = UInt8(1)\n\n locValA = Float32(0)\n locValB = Float32(0)\n #reset shared memory\n @ifY 1 shmemSum[threadIdxX(),1]=0 ; @ifY 2 shmemSum[threadIdxX(),2]=0\n sync_threads()\n\n #first we add 1 for each spot we have true - so we will get sum - and from sum we can get mean\n @iterateLinearlyMultipleBlocks(iterLoop,pixPerSlice,totalNumbOfVoxels,begin\n locValA += flatGold[i]==numberToLooFor \n locValB += flatSegm[i]==numberToLooFor\n end)#for\n @redWitAct(offsetIter,shmemSum, locValA,+, locValB,+ )\n sync_threads()\n @addAtomic(shmemSum, sumOfGold,sumOfSegm)\n ### sums should be in place\nsync_grid(grid_handle)\ngrandMeanShmem[1]= ( (sumOfGold[1]/totalNumbOfVoxels) + (sumOfSegm[1]/totalNumbOfVoxels ))/2\nlocValA = 0\nlocValB = 0\n@ifY 1 shmemSum[threadIdxX(),1]=0 ; \n@ifY 2 shmemSum[threadIdxX(),2]=0 ;\nsync_threads()\n\n@iterateLinearlyMultipleBlocks(iterLoop,pixPerSlice,totalNumbOfVoxels,begin\nm = ((flatGold[i]==numberToLooFor) +(flatSegm[i]==numberToLooFor))/2 \nlocValA += (((flatGold[i]==numberToLooFor)- m)^2) +(((flatSegm[i]==numberToLooFor)- m )^2) \nlocValB += ((m - grandMeanShmem[1])^2)\nend)#for\n#now we accumulated ssw and locValB - we need to reduce it\noffsetIter = UInt8(1)\n@redWitAct(offsetIter,shmemSum, locValA,+, locValB,+ )\nsync_threads()\n@addAtomic(shmemSum, sswTotal,ssbTotal)\nreturn nothing\n\nend\n\n\n# function kernel_InterClassCorr(flatGold\n# ,flatSegm,\n# sumOfGold,sumOfSegm\n# ,sswTotal\n# ,ssbTotal\n# ,iterLoop,pixPerSlice,totalNumbOfVoxels\n# ,numberToLooFor,grandMean )\n \n# #for storing results from warp reductions\n# shmemSum = @cuStaticSharedMem(Float32, (33,2)) #thread local values that are meant to store some results - like means ... \n# @ifY 1 shmemSum[threadIdxX(),1]=0 ; \n# @ifY 2 shmemSum[threadIdxX(),2]=0 ;\n# sync_threads()\n# locValA = Float32(0.0)\n# locValB = Float32(0.0)\n\n# @iterateLinearlyMultipleBlocks(iterLoop,pixPerSlice,totalNumbOfVoxels,begin\n# m = ((flatGold[i]==numberToLooFor) +(flatSegm[i]==numberToLooFor))/2 \n# locValA += (((flatGold[i]==numberToLooFor)- m)^2) +(((flatSegm[i]==numberToLooFor)- m )^2) \n# locValB += ((m - grandMean[1])^2)\n# end)#for\n# #now we accumulated ssw and locValB - we need to reduce it\n# offsetIter = UInt8(1)\n# @redWitAct(offsetIter,shmemSum, locValA,+, locValB,+ )\n# sync_threads()\n# @addAtomic(shmemSum, sswTotal,ssbTotal)\n# return nothing\n\n\n# end\n\n\n\n\n\n# function kernel_InterClassCorr_means(goldlGPU,segmGPU \n# ,sumOfGold,sumOfSegm\n# ,sswTotal\n# ,ssbTotal\n# ,iterLoop,pixPerSlice,totalNumbOfVoxels\n# ,numberToLooFor )\n\n# locValA = UInt32(0)\n# locValB = UInt32(0)\n# offsetIter= UInt8(1)\n# shmemSum = @cuStaticSharedMem(UInt16, (33,2)) #thread local values that are meant to store some results - like means ... \n# @ifY 1 shmemSum[threadIdxX(),1]= 0\n# @ifY 2 shmemSum[threadIdxX(),2]= 0\n# sync_threads()\n\n# @iterateLinearlyMultipleBlocks(iterLoop,pixPerSlice,totalNumbOfVoxels,\n# #inner expression\n# begin\n# #updating variables needed to calculate means\n# locValA += goldlGPU[i]==numberToLooFor \n# locValB += segmGPU[i]==numberToLooFor\n# end) \n\n# #tell what variables are to be reduced and by what operation\n# @redWitAct(offsetIter,shmemSum, locValA,+, locValB,+ )\n# sync_threads()\n# @addAtomic(shmemSum, sumOfGold, sumOfSegm)\n\n# return nothing\n# end\n\n\n\n# function kernel_InterClassCorr(goldlGPU,segmGPU \n# ,sumOfGold,sumOfSegm\n# ,sswTotal\n# ,ssbTotal\n# ,iterLoop,pixPerSlice,totalNumbOfVoxels\n# ,numberToLooFor )\n# grandMean = @cuStaticSharedMem(Float32, (1)) \n# @ifXY 1 3 grandMean[1]= ( (sumOfGold[1]/totalNumbOfVoxels) + (sumOfSegm[1]/totalNumbOfVoxels ))/2\n# ssw = Float32(0)\n# ssb = Float32(0)\n# m = Float32(0)\n# offsetIter= UInt8(1)\n# shmemSum = @cuStaticSharedMem(Float32, (33,2)) #thread local values that are meant to store some results - like means ... \n# @ifY 1 shmemSum[threadIdxX(),1]= 0\n# @ifY 2 shmemSum[threadIdxX(),2]= 0\n# sync_threads()\n# @iterateLinearlyMultipleBlocks(iterLoop,pixPerSlice,totalNumbOfVoxels,\n# #inner expression\n# begin\n# m = ((goldlGPU[i]==numberToLooFor) +(segmGPU[i]==numberToLooFor))/2 \n# ssw += (((goldlGPU[i]==numberToLooFor)- m)^2) +(((segmGPU[i]==numberToLooFor)- m )^2) \n# ssb += ((m - grandMean[1])^2)\n# end) \n\n# #tell what variables are to be reduced and by what operation\n# @redWitAct(offsetIter,shmemSum, ssw,+, ssb,+ )\n# sync_threads()\n# @addAtomic(shmemSum, sswTotal,ssbTotal)\n\n\n# return nothing\n\n\n\n# end\n\n\n# \"\"\"\n# calculates slicewise and global interclass correlation metric\n\n# threadsForMeans, threadsForMain - tuples indicating dimensionality of thread block \n# bsically all needed arguments apart from gold standard and algorithm 3 dm arrays and numberToLooFor should be given by prepareInterClassCorrKernel\n# \"\"\"\n# function calculateInterclassCorr(goldGPU,segmGPU,argsMain, threadsMain, blocksMain,threadsMean,blocksMean,argsMean, totalNumbOfVoxels)::Float64\n\n \n# ## resetting some entries to 0 \n# for i in 1:4\n# CUDA.fill!(argsMain[i],0)\n# end\n \n# @cuda threads=threadsMean blocks=blocksMean kernel_InterClassCorr_means(goldGPU,segmGPU,argsMean...)\n# @cuda threads=threadsMain blocks=blocksMain kernel_InterClassCorr(goldGPU,segmGPU,argsMain...)\n\n# print(\"before correction ssw $(argsMain[4][1]) ssb $(argsMain[5][1])\")\n\n# ssw = argsMain[4][1]/totalNumbOfVoxels;\n# ssb = (argsMain[5][1]/(totalNumbOfVoxels-1)) * 2;\n# print(\"ssw $(ssw) ssb $(ssb)\")\n# # return (ssb - ssw)/(ssb + ssw);\n# return (ssb - ssw)/(ssb + ssw);\n \n# end\n\n\n# function kernel_InterClassCorr(goldlGPU,segmGPU \n# ,sumOfGold,sumOfSegm\n# ,sswTotal\n# ,ssbTotal\n# ,iterLoop,pixPerSlice,totalNumbOfVoxels\n# ,numberToLooFor )\n\n# grid_handle = this_grid()\n\n# locValA = Float32(0)\n# locValB = Float32(0)\n# offsetIter= 1\n# grandMean = @cuStaticSharedMem(Float32, (1)) \n# grandMeanSq = @cuStaticSharedMem(Float32, (1)) \n# halfMingrandSq = @cuStaticSharedMem(Float32, (1)) \n# oneMingrandSq = @cuStaticSharedMem(Float32, (1)) \n\n# shmemSum = @cuStaticSharedMem(Float32, (33,2)) #thread local values that are meant to store some results - like means ... \n# @ifY 1 shmemSum[threadIdxX(),1]= Float32(0)\n# @ifY 2 shmemSum[threadIdxX(),2]= Float32(0)\n\n# sync_threads()\n# @iterateLinearlyMultipleBlocks(iterLoop,pixPerSlice,totalNumbOfVoxels,\n# #inner expression\n# begin\n# #updating variables needed to calculate means\n# locValA += goldlGPU[i]==numberToLooFor \n# locValB += segmGPU[i]==numberToLooFor\n# end) \n\n# #tell what variables are to be reduced and by what operation\n# @redWitAct(offsetIter,shmemSum, locValA,+, locValB,+ )\n# sync_threads()\n# @addAtomic(shmemSum, sumOfGold, sumOfSegm)\n\n# # @ifX 1 if(threadIdxY()>22 ) CUDA.@cuprint \"aaa idY $(threadIdxY()) \\n\" end\n\n# sync_grid(grid_handle)\n# #by now we should have all means \n# @ifXY 1 3 grandMean[1]= ( (sumOfGold[1]/totalNumbOfVoxels) + (sumOfSegm[1]/totalNumbOfVoxels ))/2\n# @ifXY 2 3 grandMeanSq[1]= ((( (sumOfGold[1]/totalNumbOfVoxels) + (sumOfSegm[1]/totalNumbOfVoxels ))/2))^2\n# @ifXY 3 3 halfMingrandSq[1]= (0.5- (( (sumOfGold[1]/totalNumbOfVoxels) + (sumOfSegm[1]/totalNumbOfVoxels ))/2))^2\n# @ifXY 4 3 oneMingrandSq[1]= (1- (( (sumOfGold[1]/totalNumbOfVoxels) + (sumOfSegm[1]/totalNumbOfVoxels ))/2))^2\n\n# @ifXY 1 1 CUDA.@cuprint \" \"\n\n# @ifY 1 shmemSum[threadIdxX(),1]= Float32(0)\n# @ifY 2 shmemSum[threadIdxX(),2]= Float32(0)\n# sync_threads()\n# locValA = 0\n# locValB = 0\n# # m = Float32(0)\n# sync_threads()\n\n# @iterateLinearlyMultipleBlocks(iterLoop,pixPerSlice,totalNumbOfVoxels,\n# begin\n# boolGold = segmGPU[i]==numberToLooFor\n# boolSegm = goldlGPU[i]==numberToLooFor\n# if(boolGold && boolSegm)\n# # CUDA.@cuprint \"aa \"\n# locValB = locValB+oneMingrandSq[1] \n# elseif(boolGold ⊻ boolSegm)\n# locValA =locValA+ (0.25)\n# locValB += halfMingrandSq[1]#((0.5 - grandMean[1])*(0.5 - grandMean[1]) )\n# else\n# locValB =locValB+ grandMeanSq[1] \n# end \n\n# # elseif(boolGold || boolSegm)\n# # m = 0.5#((boolGold ) +(boolSegm) )/2 \n# # locValA += 0.25\n# # locValB += ((0.5 - grandMean[1])^2)\n# # else\n# # locValB += grandMean[1]^2\n\n# # end \n# end ) \n# #tell what variables are to be reduced and by what operation\n# offsetIter= 1\n# @redWitAct(offsetIter,shmemSum, locValA,+, locValB,+ )\n# sync_threads()\n# @addAtomic(shmemSum, sswTotal,ssbTotal)\n# # #now we will have sum of all entries in given slice that comply to our predicate\n# # #next we need to reduce values\n# # while(offsetIter <32) \n# # @inbounds locValA+=shfl_down_sync(FULL_MASK, locValA, offsetIter) \n# # @inbounds locValB+=shfl_down_sync(FULL_MASK, locValB, offsetIter) \n# # offsetIter<<= 1\n# # end\n# # # @ifX 1 if(threadIdxY()>22 ) CUDA.@cuprint \"bbb idY $(threadIdxY()) \\n\" end\n# # #@ifX 1 if(blockIdxX()==1 ) CUDA.@cuprint \"bbb idY $(threadIdxY()) \\n\" end\n# # #@ifY 1 if(blockIdxX()==1 ) CUDA.@cuprint \"bbb idX $(threadIdxX()) \\n\" end\n\n# # # @ifX 1 if(blockIdxX()==1 ) CUDA.@cuprint \"bbb idY $(threadIdxY()) \\n\" end\n# # #@ifY 1 if(blockIdxX()==1 ) CUDA.@cuprint \"bbb idX $(threadIdxX()) \\n\" end\n\n# # # now we have sums in first threads of the warp we need to pass it to shared memory\n# # if(threadIdxX()==1)\n# # #TODO() try to do full reduction without those atomics \n# # @inboundsCUDA.@atomic sswTotal[1]+=locValA\n# # @inboundsCUDA.@atomic ssbTotal[1]+=locValB\n# # end\n# # sync_threads()\n\n# # sync_warp(active_mask())\n\n# # #finally reduce from shared memory\n# # if(threadIdxY()==1)\n# # offsetIter = UInt8(1)\n# # while(offsetIter <32) \n# # @inbounds shmemSum[threadIdxX(),1]+=shfl_down_sync(FULL_MASK, shmemSum[threadIdxX(),1], offsetIter) \n# # @inbounds shmemSum[threadIdxX(),2]+=shfl_down_sync(FULL_MASK, shmemSum[threadIdxX(),2], offsetIter) \n# # offsetIter<<= 1\n# # end\n# # end \n\n\n\n# # @ifXY 1 1 CUDA.@cuprint \"shmemSum[1,1] $(shmemSum[1,1]) \\n \"\n# # sync_threads()\n# # @addAtomic(shmemSum, sswTotal,ssbTotal)\n \n\n# return nothing\n\n\n\n# end\n\n\n\n\nend#InterClassCorrKernel\n\n\n\n\n\n\n\n \n# #offset for lloking for values in source arrays \n# offset = (pixelNumberPerSlice*(blockIdx().x-1))\n# #for storing results from warp reductions\n# shmemSum = @cuStaticSharedMem(Float32, (33,2)) #thread local values that are meant to store some results - like means ... \n# @ifY 1 shmemSum[threadIdxX(),1]=0 ; @ifY 2 shmemSum[threadIdxX(),2]=0 ;@ifY 3 shmemSum[threadIdxX(),2]=0\n# sync_threads()\n# ssw::Float32 = Float32(0.0)\n# ssb::Float32 = Float32(0.0)\n\n# @unroll for k in UInt16(0):loopNumb\n# if(threadIdxX()+(threadIdxY()-1)*32+k*1024 <=pixelNumberPerSlice)\n# ind =offset+ threadIdxX()+(threadIdxY()-1)*32+k*1024 \n# m = ((flatGold[ind]==numberToLooFor) +(flatSegm[ind]==numberToLooFor))/2 \n# ssw += (((flatGold[ind]==numberToLooFor)- m)^2) +(((flatSegm[ind]==numberToLooFor)- m )^2) \n# ssb += ((m - grandMean[1])^2)\n# end#if \n# end#for\n# #now we accumulated ssw and ssb - we need to reduce it\n# offsetIter = UInt8(1)\n# while(offsetIter <32) \n# @inbounds ssw+=shfl_down_sync(FULL_MASK, ssw, offsetIter) \n# @inbounds ssb+=shfl_down_sync(FULL_MASK, ssb, offsetIter) \n# offsetIter<<= 1\n# end\n# # now we have sums in first threads of the warp we need to pass it to shared memory\n# if(threadIdxX()==1)\n# @inbounds shmemSum[threadIdxY(),1]+=ssw\n# @inbounds shmemSum[threadIdxY(),2]+=ssb\n# end\n# sync_threads()\n# #finally reduce from shared memory\n# if(threadIdxY()==1)\n# offsetIter = UInt8(1)\n# while(offsetIter <32) \n# @inbounds shmemSum[threadIdxX(),1]+=shfl_down_sync(FULL_MASK, shmemSum[threadIdxX(),1], offsetIter) \n# @inbounds shmemSum[threadIdxX(),2]+=shfl_down_sync(FULL_MASK, shmemSum[threadIdxX(),2], offsetIter) \n# offsetIter<<= 1\n# end\n# end \n# sync_threads()sswTotal,ssbTotal\n #now in shmemSum[1,1] we should have ssw and in shmemSum[1,2] ssb\n# @ifXY 1 1 @inboundsCUDA.@atomic sswTotal[]+= shmemSum[1,1]\n# @ifXY 1 2 @inboundsCUDA.@atomic ssbTotal[]+= shmemSum[1,2]\n# @ifXY 1 3 begin\n# sswInner = shmemSum[1,2]/totalNumbOfVoxels;\n# ssbInner = shmemSum[1,1]/(totalNumbOfVoxels-1) * 2\n# @inbounds iccPerSlice[blockIdxX()]=(ssb - ssw)/(ssb + ssw)\n# end \n # # ####### now we have ssw and ssb calculated both global and per slice\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# \"\"\"\n# adapted from https://github.com/JuliaGPU/CUDA.jl/blob/afe81794038dddbda49639c8c26469496543d831/src/mapreduce.jl\n# goldGPU - array holding data of gold standard array\n# segmGPU - array with the data we want to compare with gold standard\n# ic - holding single value for global interclass correlation\n# intermediateRes- array holding slice wise results for ic\n# loopXdim,loopYdim,loopZdim - number of times we need to loop over each dimension in order to get all needed data\n# sliceEdgeLength - length of edge of the slice we need to square this number to get number of pixels in a slice\n# amountOfWarps - how many warps we can stick in the block\n# \"\"\"\n\n# function kernel_InterClassCorr_means(goldlGPU\n# ,segmGPU\n# ,iterLoop,pixPerSlice,totalNumbOfVoxels\n# ,sumOfGold\n# ,sumOfSegm\n# ,numberToLooFor )\n \n# locValA = UInt32(0)\n# locValB = UInt32(0)\n# offsetIter= UInt8(1)\n# shmemSum = @cuStaticSharedMem(UInt16, (33,2)) #thread local values that are meant to store some results - like means ... \n# @iterateLinearlyMultipleBlocks(iterLoop,pixPerSlice,totalNumbOfVoxels,\n# #inner expression\n# begin\n# #updating variables needed to calculate means\n# locValA += goldlGPU[i]==numberToLooFor \n# locValB += segmGPU[i]==numberToLooFor\n# end) \n\n# #tell what variables are to be reduced and by what operation\n# @redWitAct(offsetIter,shmemSum, locValA,+, locValB,+ )\n# sync_threads()\n# @addAtomic(shmemSum, sumOfGold, sumOfSegm)\n\n# # #offset for lloking for values in source arrays \n# # offset = (pixelNumberPerSlice*(blockIdx().x-1))\n# # #for storing results from warp reductions\n# # shmemSum = @cuStaticSharedMem(UInt16, (33,2)) #thread local values that are meant to store some results - like means ... \n# # offsetIter = UInt8(1)\n\n# # locValA = UInt32(0)\n# # locValB = UInt32(0)\n# # #reset shared memory\n# # @ifY 1 shmemSum[threadIdxX(),1]=0 ; @ifY 2 shmemSum[threadIdxX(),2]=0\n# # sync_threads()\n\n# # #first we add 1 for each spot we have true - so we will get sum - and from sum we can get mean\n# # @unroll for k in 0:loopNumb\n# # if(threadIdxX()+(threadIdxY()-1)*32+k*1024 <=pixelNumberPerSlice)\n# # ind =offset+ threadIdxX()+(threadIdxY()-1)*32+k*1024\n# # locValA += flatGold[ind]==numberToLooFor \n# # locValB += flatSegm[ind]==numberToLooFor\n# # end#if \n# # end#for\n \n\n# # #now we will have sum of all entries in given slice that comply to our predicate\n# # #next we need to reduce values\n# # offsetIter = UInt8(1)\n# # while(offsetIter <32) \n# # @inbounds locValA+=shfl_down_sync(FULL_MASK, locValA, offsetIter) \n# # @inbounds locValB+=shfl_down_sync(FULL_MASK, locValB, offsetIter) \n# # offsetIter<<= 1\n# # end\n# # # now we have sums in first threads of the warp we need to pass it to shared memory\n# # if(threadIdxX()==1)\n\n# # @inbounds shmemSum[threadIdxY(),1]+=locValA\n# # @inbounds shmemSum[threadIdxY(),2]+=locValB\n# # end\n# # sync_threads()\n# # #finally reduce from shared memory\n# # if(threadIdxY()==1)\n# # offsetIter = UInt8(1)\n# # while(offsetIter <32) \n# # @inbounds shmemSum[threadIdxX(),1]+=shfl_down_sync(FULL_MASK, shmemSum[threadIdxX(),1], offsetIter) \n# # @inbounds shmemSum[threadIdxX(),2]+=shfl_down_sync(FULL_MASK, shmemSum[threadIdxX(),2], offsetIter) \n# # offsetIter<<= 1\n# # end\n# # end \n# # sync_threads()\n \n# # #now in shmemSum[1,1] we should have sum of values complying with our predicate in gold mask and in shmemSum[1,2] values of other mask\n# # #we need to add now those to the globals \n# # @ifXY 1 1 @inboundsCUDA.@atomic sumOfGold[]+= shmemSum[1,1]\n# # @ifXY 1 2 @inboundsCUDA.@atomic sumOfSegm[]+= shmemSum[1,2]\n\n# return nothing\n# end\n\n", "meta": {"hexsha": "928f5a810d982909797cc6b5aaeb217c0e82e913", "size": 21216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/InterClassCorrKernel.jl", "max_stars_repo_name": "jakubMitura14/NuclearMedEval", "max_stars_repo_head_hexsha": "bf4502118d833dcd4c5de630594941801e984935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/InterClassCorrKernel.jl", "max_issues_repo_name": "jakubMitura14/NuclearMedEval", "max_issues_repo_head_hexsha": "bf4502118d833dcd4c5de630594941801e984935", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/InterClassCorrKernel.jl", "max_forks_repo_name": "jakubMitura14/NuclearMedEval", "max_forks_repo_head_hexsha": "bf4502118d833dcd4c5de630594941801e984935", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5163511188, "max_line_length": 149, "alphanum_fraction": 0.6464460784, "num_tokens": 6894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2474388945535825}} {"text": "\"\"\"\n energy_balance(object::T,meteo::Atmosphere,constants = Constants())\n energy_balance(object::Array{AbstractComponentModel},meteo::Atmosphere,constants = Constants())\n energy_balance!(object::AbstractComponentModel,meteo::Atmosphere,constants = Constants())\n\nComputes the energy balance of a component based on the type of the model it was parameterized\nwith in `object.energy`.\n\nAt the moment, two models are implemented in the package:\n\n- [`Monteith`](@ref): the model found in Monteith and Unsworth (2013)\n- `Missing`: if no computation of the energy balance is needed\n\n# Arguments\n\n- `object::Union{AbstractComponentModel,Array{AbstractComponentModel},\nDict{String,AbstractComponentModel}}`: a [`Component`](@ref) struct, or a Dict/Array of.\n- `meteo::Union{Atmosphere,Weather}`: meteorology structure, see [`Atmosphere`](@ref) or\n[`Weather`](@ref)\n- `constants = Constants()`: physical constants. See [`Constants`](@ref) for more details\n\n# Note\n\nSome models need input values for some variables. For example [`Monteith`](@ref) requires a\nvalue for `Rₛ`, `d` and `skyFraction`. If you read the models from a file, you can\nuse [`init_status!`](@ref) (see examples).\n\n\n# Examples\n\n```julia\nmeteo = Atmosphere(T = 20.0, Wind = 1.0, P = 101.3, Rh = 0.65)\n\n# Using the model of Monteith and Unsworth (2013) for energy, Farquhar et al. (1980) for\n# photosynthesis, and Medlyn et al. (2011) for stomatal conductance:\nleaf = LeafModels(energy = Monteith(),\n photosynthesis = Fvcb(),\n stomatal_conductance = Medlyn(0.03, 12.0),\n Rₛ = 13.747, skyFraction = 1.0, PPFD = 1500.0, d = 0.03)\n\nenergy_balance(leaf,meteo)\n\n# Using a model file:\nmodel = read_model(\"a-model-file.yml\")\n\n# An example model file is available here:\n# \"https://raw.githubusercontent.com/VEZY/PlantBiophysics/main/test/inputs/models/plant_coffee.yml\"\n\n# Initialising the mandatory variables:\ninit_status!(model, Rₛ = 13.747, skyFraction = 1.0, PPFD = 1500.0, Tₗ = 25.0, d = 0.03)\n\n# NB: To know which variables has to be initialised according to the models used, you can use\n# `to_initialise(leaf)`\n\n# Running a simulation for all component types in the same scene:\nenergy_balance!(model, meteo)\n\nmodel[\"Leaf\"].status.Rn\nmodel[\"Leaf\"].status.A\nmodel[\"Leaf\"].status.Cᵢ\n```\n\n# References\n\nDuursma, R. A., et B. E. Medlyn. 2012. « MAESPA: a model to study interactions between water\nlimitation, environmental drivers and vegetation function at tree and stand levels, with an\nexample application to [CO2] × drought interactions ». Geoscientific Model Development 5 (4):\n919‑40. https://doi.org/10.5194/gmd-5-919-2012.\n\nMonteith, John L., et Mike H. Unsworth. 2013. « Chapter 13 - Steady-State Heat Balance: (i)\nWater Surfaces, Soil, and Vegetation ». In Principles of Environmental Physics (Fourth Edition),\nedited by John L. Monteith et Mike H. Unsworth, 217‑47. Boston: Academic Press.\n\nSchymanski, Stanislaus J., et Dani Or. 2017. « Leaf-Scale Experiments Reveal an Important\nOmission in the Penman–Monteith Equation ». Hydrology and Earth System Sciences 21 (2): 685‑706.\nhttps://doi.org/10.5194/hess-21-685-2017.\n\nVezy, Rémi, Mathias Christina, Olivier Roupsard, Yann Nouvellon, Remko Duursma, Belinda Medlyn,\nMaxime Soma, et al. 2018. « Measuring and modelling energy partitioning in canopies of varying\ncomplexity using MAESPA model ». Agricultural and Forest Meteorology 253‑254 (printemps): 203‑17.\nhttps://doi.org/10.1016/j.agrformet.2018.02.005.\n\"\"\"\nfunction energy_balance!(object::AbstractComponentModel, meteo::Atmosphere, constants = Constants())\n is_init = is_initialised(object)\n !is_init && error(\"Some variables must be initialized before simulation\")\n\n net_radiation!(object, meteo, constants)\n return nothing\nend\n\n# Same as above but non-mutating\nfunction energy_balance(object::AbstractComponentModel, meteo::Atmosphere, constants = Constants())\n object_tmp = copy(object)\n energy_balance!(object_tmp, meteo, constants)\n return object_tmp.status\nend\n\n# energy_balance over several objects (e.g. all leaves of a plant) in an Array\nfunction energy_balance!(object::O, meteo::Atmosphere, constants = Constants()) where O <: AbstractArray{<:AbstractComponentModel}\n\n for i in values(object)\n energy_balance!(i, meteo, constants)\n end\n\n return nothing\nend\n\n# same as the above but non-mutating\nfunction energy_balance(\n object::O,\n meteo::M,\n constants = Constants()\n ) where {O <: Union{AbstractArray{<:AbstractComponentModel},AbstractDict{N,<:AbstractComponentModel} where N},M <: Union{Atmosphere,Weather}}\n\n # Copy the objects only once before the computation for performance reasons:\n object_tmp = copy(object)\n\n # Computation:\n energy_balance!(object_tmp, meteo, constants)\n\n # --- Extracting the outputs: ---\n\n # Pre-allocating the outputs:\n output = [i.status for i in object_tmp]\n\n for (i, obj) in enumerate(object_tmp)\n output[i] = obj.status\n end\n\n output = DataFrame([NamedTuple(i) for i in output])\n\n return output\nend\n\n# energy_balance over several objects (e.g. all leaves of a plant) in a kind of Dict.\nfunction energy_balance!(object::O, meteo::Atmosphere, constants = Constants()) where O <: AbstractDict{N,<:AbstractComponentModel} where N\n\n for (k, v) in object\n energy_balance!(v, meteo, constants)\n end\n\n return nothing\nend\n\n# same as the above but non-mutating. In this case we add a column with the component name 😃\nfunction energy_balance(\n object::O,\n meteo::M,\n constants = Constants()\n ) where {O <: Union{AbstractArray{<:AbstractComponentModel},AbstractDict{N,<:AbstractComponentModel} where N},M <: Union{Atmosphere,Weather}}\n\n # Copy the objects only once before the computation for performance reasons:\n object_tmp = copy(object)\n\n # Computation:\n energy_balance!(object_tmp, meteo, constants)\n\n # --- Extracting the outputs: ---\n\n # Pre-allocating the outputs:\n output = Dict([k => v.status for (k, v) in object_tmp])\n \n for (k, v) in object_tmp\n output[k] = v.status\n end\n\n output = DataFrame([(NamedTuple(v)..., component = k) for (k, v) in output])\n\n return output\nend\n\n# energy_balance over several meteo time steps (called Weather) and possibly several components.\n# Only allowed for components given as a subtype of AbstractDict to track components names in the\n# outputs\nfunction energy_balance!(\n object::T,\n meteo::Weather,\n constants = Constants()\n ) where T <: Union{AbstractDict{N,<:AbstractComponentModel} where N}\n\n # Pre-allocating the time-step outputs:\n timestep_tmp = Dict([k => v.status for (k, v) in object])\n\n # Pre-allocating the general DataFrame with the first time-step results:\n energy_balance!(object, meteo.data[1], constants)\n\n for (k, v) in object\n timestep_tmp[k] = v.status\n end\n\n output_timestep = DataFrame([(NamedTuple(v)..., component = k) for (k, v) in timestep_tmp])\n\n # Actually pre-allocating the DF:\n output = repeat(output_timestep, length(meteo.data))\n output.time_step = repeat(1:length(meteo.data), inner = size(output_timestep, 1))\n\n # Computing for all following time-steps:\n for (i, meteo_i) in enumerate(meteo.data[2:end])\n energy_balance!(object, meteo_i, constants)\n\n for (k, v) in object\n timestep_tmp[k] = v.status\n end\n\n output_timestep = DataFrame([(NamedTuple(v)..., component = k) for (k, v) in timestep_tmp])\n\n # Update the values of the global output:\n output[output.time_step .== i,Not(:time_step)] = output_timestep\n end\n\n return output\nend\n\n# energy_balance over several meteo time steps (same as above) but non-mutating\nfunction energy_balance(\n object::T,\n meteo::Weather,\n constants = Constants()\n ) where T <: Union{AbstractDict{N,<:AbstractComponentModel} where N}\n\n object_tmp = copy(object)\n\n return energy_balance!(object_tmp, meteo, constants)\nend\n", "meta": {"hexsha": "abbc5c30dd63c516525a022276830ab38953e1e8", "size": 7971, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/energy/energy_balance.jl", "max_stars_repo_name": "SimonTreillou/PlantBiophysics.jl", "max_stars_repo_head_hexsha": "70688f412467a379ed59fac34995f05f88ba8762", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/energy/energy_balance.jl", "max_issues_repo_name": "SimonTreillou/PlantBiophysics.jl", "max_issues_repo_head_hexsha": "70688f412467a379ed59fac34995f05f88ba8762", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/energy/energy_balance.jl", "max_forks_repo_name": "SimonTreillou/PlantBiophysics.jl", "max_forks_repo_head_hexsha": "70688f412467a379ed59fac34995f05f88ba8762", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4266666667, "max_line_length": 145, "alphanum_fraction": 0.7115794756, "num_tokens": 2144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24743888792571198}} {"text": "@cache struct SSPRK22Cache{uType,rateType,StageLimiter,StepLimiter} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\nend\n\nstruct SSPRK22ConstantCache <: OrdinaryDiffEqConstantCache end\n\nfunction alg_cache(alg::SSPRK22,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n SSPRK22Cache(u,uprev,k,fsalfirst,alg.stage_limiter!,alg.step_limiter!)\nend\n\nalg_cache(alg::SSPRK22,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits} = SSPRK22ConstantCache()\n\n\n@cache struct SSPRK33Cache{uType,rateType,StageLimiter,StepLimiter} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\nend\n\nstruct SSPRK33ConstantCache <: OrdinaryDiffEqConstantCache end\n\nfunction alg_cache(alg::SSPRK33,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n SSPRK33Cache(u,uprev,k,fsalfirst,alg.stage_limiter!,alg.step_limiter!)\nend\n\nalg_cache(alg::SSPRK33,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits} = SSPRK33ConstantCache()\n\n@cache struct KYKSSPRK42Cache{uType,rateType,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n tmp::uType\n fsalfirst::rateType\n tab::TabType\n end\n\nstruct KYKSSPRK42ConstantCache{T, T2} <: OrdinaryDiffEqConstantCache\n α20::T\n α21::T\n α30::T\n α32::T\n α40::T\n α43::T\n β10::T\n β21::T\n β30::T\n β32::T\n β40::T\n β43::T\n c1::T2\n c2::T2\n c3::T2\nend\n\nfunction KYKSSPRK42ConstantCache(T, T2)\n α20 = T(0.394806441339829)\n α21 = T(0.605193558660171)\n α30 = T(0.002797307087390)\n α32 = T(0.997202692912610)\n α40 = T(0.252860909354373)\n α43 = T(0.747139090645627)\n β10 = T(0.406584463657504)\n β21 = T(0.246062298456822)\n β30 = T(0.013637216641451)\n β32 = T(0.405447122055692)\n β40 = T(0.016453567333598)\n β43 = T(0.303775146447707)\n c1 = T2(0.406584463657504)\n c2 = T2(0.4921245969136438)\n c3 = T2(0.9098323119879613)\n KYKSSPRK42ConstantCache(α20, α21, α30, α32, α40, α43, β10, β21, β30, β32, β40, β43, c1, c2, c3)\nend\n\nfunction alg_cache(alg::KYKSSPRK42,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n tmp = zero(u)\n k = zero(rate_prototype)\n fsalfirst = zero(rate_prototype)\n tab = KYKSSPRK42ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n KYKSSPRK42Cache(u,uprev,k,tmp, fsalfirst,tab)\nend\n\nfunction alg_cache(alg::KYKSSPRK42,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n KYKSSPRK42ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n@cache struct SSPRK53Cache{uType,rateType,StageLimiter,StepLimiter,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n tmp::uType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n tab::TabType\nend\n\nstruct SSPRK53ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache\n α30::T\n α32::T\n α40::T\n α43::T\n α52::T\n α54::T\n β10::T\n β21::T\n β32::T\n β43::T\n β54::T\n c1::T2\n c2::T2\n c3::T2\n c4::T2\n\n function SSPRK53ConstantCache(T, T2)\n α30 = T(0.355909775063327)\n α32 = T(0.644090224936674)\n α40 = T(0.367933791638137)\n α43 = T(0.632066208361863)\n α52 = T(0.237593836598569)\n α54 = T(0.762406163401431)\n β10 = T(0.377268915331368)\n β21 = T(0.377268915331368)\n β32 = T(0.242995220537396)\n β43 = T(0.238458932846290)\n β54 = T(0.287632146308408)\n c1 = T2(0.377268915331368)\n c2 = T2(0.754537830662736)\n c3 = T2(0.728985661612188)\n c4 = T2(0.699226135931670)\n\n new{T,T2}(α30, α32, α40, α43, α52, α54, β10, β21, β32, β43, β54, c1, c2, c3, c4)\n end\nend\n\nfunction alg_cache(alg::SSPRK53,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n tmp = zero(u)\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n tab = SSPRK53ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SSPRK53Cache(u,uprev,k,fsalfirst,tmp,alg.stage_limiter!,alg.step_limiter!,tab)\nend\n\nfunction alg_cache(alg::SSPRK53,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SSPRK53ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n@cache struct SHLDDRK52Cache{uType,rateType,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n tmp::uType\n fsalfirst::rateType\n tab::TabType\nend\n\nstruct SHLDDRK52ConstantCache{T1,T2} <: OrdinaryDiffEqConstantCache\n α2::T1\n α3::T1\n α4::T1\n α5::T1\n β1::T1\n β2::T1\n β3::T1\n β4::T1\n β5::T1\n c2::T2\n c3::T2\n c4::T2\n c5::T2\nend\n\nfunction SHLDDRK52ConstantCache(T1,T2)\n α2 = T1(-0.6913065)\n α3 = T1(-2.655155)\n α4 = T1(-0.8147688)\n α5 = T1(-0.6686587)\n β1 = T1(0.1)\n β2 = T1(0.75)\n β3 = T1(0.7)\n β4 = T1(0.479313)\n β5 = T1(0.310392)\n c2 = T2(0.1)\n c3 = T2(0.3315201)\n c4 = T2(0.4577796)\n c5 = T2(0.8666528)\n SHLDDRK52ConstantCache(α2, α3, α4, α5, β1, β2, β3, β4, β5, c2, c3, c4, c5)\nend\n\nfunction alg_cache(alg::SHLDDRK52,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SHLDDRK52ConstantCache(constvalue(uBottomEltypeNoUnits),constvalue(tTypeNoUnits))\nend\n\nfunction alg_cache(alg::SHLDDRK52,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n tmp = zero(u)\n k = zero(rate_prototype)\n fsalfirst = zero(rate_prototype)\n tab = SHLDDRK52ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SHLDDRK52Cache(u,uprev,k,tmp,fsalfirst,tab)\nend\n\n@cache mutable struct SHLDDRK_2NCache{uType,rateType,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n tmp::uType\n fsalfirst::rateType\n tab::TabType\n step::Int\nend\n\nmutable struct SHLDDRK_2NConstantCache{T1,T2} <: OrdinaryDiffEqConstantCache\n α21::T1\n α31::T1\n α41::T1\n α51::T1\n β11::T1\n β21::T1\n β31::T1\n β41::T1\n β51::T1\n c21::T2\n c31::T2\n c41::T2\n c51::T2\n\n α22::T1\n α32::T1\n α42::T1\n α52::T1\n α62::T1\n β12::T1\n β22::T1\n β32::T1\n β42::T1\n β52::T1\n β62::T1\n c22::T2\n c32::T2\n c42::T2\n c52::T2\n c62::T2\n\n step::Int\nend\n\nfunction SHLDDRK_2NConstantCache(T1,T2)\n α21 = T1(-0.6051226)\n α31 = T1(-2.0437564)\n α41 = T1(-0.7406999)\n α51 = T1(-4.4231765)\n β11 = T1(0.2687454)\n β21 = T1(0.8014706)\n β31 = T1(0.5051570)\n β41 = T1(0.5623568)\n β51 = T1(0.0590065)\n c21 = T2(0.2687454)\n c31 = T2(0.5852280)\n c41 = T2(0.6827066)\n c51 = T2(1.1646854)\n\n α22 = T1(-0.4412737)\n α32 = T1(-1.0739820)\n α42 = T1(-1.7063570)\n α52 = T1(-2.7979293)\n α62 = T1(-4.0913537)\n β12 = T1(0.1158488)\n β22 = T1(0.3728769)\n β32 = T1(0.7379536)\n β42 = T1(0.5798110)\n β52 = T1(1.0312849)\n β62 = T1(0.15)\n c22 = T2(0.1158485)\n c32 = T2(0.3241850)\n c42 = T2(0.6193208)\n c52 = T2(0.8034472)\n c62 = T2(0.9184166)\n SHLDDRK_2NConstantCache(α21, α31, α41, α51, β11, β21, β31, β41, β51, c21, c31, c41, c51, α22, α32, α42, α52, α62, β12, β22, β32, β42, β52, β62, c22, c32, c42, c52, c62, 1)\nend\n\nfunction alg_cache(alg::SHLDDRK_2N,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SHLDDRK_2NConstantCache(constvalue(uBottomEltypeNoUnits),constvalue(tTypeNoUnits))\nend\n\nfunction alg_cache(alg::SHLDDRK_2N,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n tmp = zero(u)\n k = zero(rate_prototype)\n fsalfirst = zero(rate_prototype)\n tab = SHLDDRK_2NConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SHLDDRK_2NCache(u,uprev,k,tmp,fsalfirst,tab,1)\nend\n\n@cache struct SSPRK53_2N1Cache{uType,rateType,StageLimiter,StepLimiter,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n tab::TabType\nend\n\nstruct SSPRK53_2N1ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache\n α40::T\n α43::T\n β10::T\n β21::T\n β32::T\n β43::T\n β54::T\n c1::T2\n c2::T2\n c3::T2\n c4::T2\n\n function SSPRK53_2N1ConstantCache(T, T2)\n α40 = T(0.571403511494104)\n α43 = T(0.428596488505896)\n β10 = T(0.443568244942995)\n β21 = T(0.291111420073766)\n β32 = T(0.270612601278217)\n β43 = T(0.110577759392786)\n β54 = T(0.458557505351052)\n c1 = T2(0.443568244942995)\n c2 = T2(0.734679665016762)\n c3 = T2(1.005292266294979)\n c4 = T2(0.541442494648948)\n\n new{T,T2}(α40, α43,β10, β21, β32, β43, β54, c1, c2, c3, c4)\n end\nend\n\nfunction alg_cache(alg::SSPRK53_2N1,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n tab = SSPRK53_2N1ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SSPRK53_2N1Cache(u,uprev,k,fsalfirst,alg.stage_limiter!,alg.step_limiter!,tab)\nend\n\nfunction alg_cache(alg::SSPRK53_2N1,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SSPRK53_2N1ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n\n@cache struct SSPRK53_2N2Cache{uType,rateType,StageLimiter,StepLimiter,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n tab::TabType\nend\n\nstruct SSPRK53_2N2ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache\n α30::T\n α32::T\n α50::T\n α54::T\n β10::T\n β21::T\n β32::T\n β43::T\n β54::T\n c1::T2\n c2::T2\n c3::T2\n c4::T2\n\n function SSPRK53_2N2ConstantCache(T, T2)\n α30 = T(0.682342861037239)\n α32 = T(0.317657138962761)\n α50 = T(0.045230974482400)\n α54 = T(0.954769025517600)\n β10 = T(0.465388589249323)\n β21 = T(0.465388589249323)\n β32 = T(0.124745797313998)\n β43 = T(0.465388589249323)\n β54 = T(0.154263303748666)\n c1 = T2(0.465388589249323)\n c2 = T2(0.930777178498646)\n c3 = T2(0.420413812847710)\n c4 = T2(0.885802402097033)\n\n new{T,T2}(α30, α32,α50,α54,β10, β21, β32, β43, β54, c1, c2, c3, c4)\n end\nend\n\nfunction alg_cache(alg::SSPRK53_2N2,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n tab = SSPRK53_2N2ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SSPRK53_2N2Cache(u,uprev,k,fsalfirst,alg.stage_limiter!,alg.step_limiter!,tab)\nend\n\nfunction alg_cache(alg::SSPRK53_2N2,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SSPRK53_2N2ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n@cache struct SSPRK53_HCache{uType,rateType,StageLimiter,StepLimiter,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n tmp::uType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n tab::TabType\nend\n\nstruct SSPRK53_HConstantCache{T,T2} <: OrdinaryDiffEqConstantCache\n α30::T\n α32::T\n α40::T\n α41::T\n α43::T\n β10::T\n β21::T\n β32::T\n β43::T\n β54::T\n c1::T2\n c2::T2\n c3::T2\n c4::T2\n\n function SSPRK53_HConstantCache(T,T2)\n α30 = T(0.308684154602513)\n α32 = T(0.691315845397487)\n α40 = T(0.280514990468574)\n α41 = T(0.270513101776498)\n α43 = T(0.448971907754928)\n β10 = T(0.377268915331368)\n β21 = T(0.377268915331368)\n β32 = T(0.260811979144498)\n β43 = T(0.169383144652957)\n β54 = T(0.377268915331368)\n c1 = T2(0.377268915331368)\n c2 = T2(0.754537830662737)\n c3 = T2(0.782435937433493)\n c4 = T2(0.622731084668631)\n\n new{T,T2}(α30, α32, α40, α41, α43, β10, β21, β32, β43, β54, c1, c2, c3, c4)\n end\nend\n\nfunction alg_cache(alg::SSPRK53_H,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n tmp = zero(u)\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n tab = SSPRK53_HConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SSPRK53_HCache(u,uprev,k,fsalfirst,tmp,alg.stage_limiter!,alg.step_limiter!,tab)\nend\n\nfunction alg_cache(alg::SSPRK53_H,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SSPRK53_HConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n\n\n@cache struct SSPRK63Cache{uType,rateType,StageLimiter,StepLimiter,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n tmp::uType\n u₂::uType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n tab::TabType\nend\n\nstruct SSPRK63ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache\n α40::T\n α41::T\n α43::T\n α62::T\n α65::T\n β10::T\n β21::T\n β32::T\n β43::T\n β54::T\n β65::T\n c1::T2\n c2::T2\n c3::T2\n c4::T2\n c5::T2\n\n function SSPRK63ConstantCache(T, T2)\n α40 = T(0.476769811285196)\n α41 = T(0.098511733286064)\n α43 = T(0.424718455428740)\n α62 = T(0.155221702560091)\n α65 = T(0.844778297439909)\n β10 = T(0.284220721334261)\n β21 = T(0.284220721334261)\n β32 = T(0.284220721334261)\n β43 = T(0.120713785765930)\n β54 = T(0.284220721334261)\n β65 = T(0.240103497065900)\n c1 = T2(0.284220721334261)\n c2 = T2(0.568441442668522)\n c3 = T2(0.852662164002783)\n c4 = T2(0.510854218958172)\n c5 = T2(0.795074940292433)\n\n new{T,T2}(α40, α41, α43, α62, α65, β10, β21, β32, β43, β54, β65, c1, c2, c3, c4, c5)\n end\nend\n\nfunction alg_cache(alg::SSPRK63,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n tmp = zero(u)\n u₂ = zero(u)\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n tab = SSPRK63ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SSPRK63Cache(u,uprev,k,fsalfirst,tmp,u₂,alg.stage_limiter!,alg.step_limiter!,tab)\nend\n\nfunction alg_cache(alg::SSPRK63,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SSPRK63ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n\n@cache struct SSPRK73Cache{uType,rateType,StageLimiter,StepLimiter,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n tmp::uType\n u₁::uType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n tab::TabType\nend\n\nstruct SSPRK73ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache\n α40::T\n α43::T\n α50::T\n α51::T\n α54::T\n α73::T\n α76::T\n β10::T\n β21::T\n β32::T\n β43::T\n β54::T\n β65::T\n β76::T\n c1::T2\n c2::T2\n c3::T2\n c4::T2\n c5::T2\n c6::T2\n\n function SSPRK73ConstantCache(T, T2)\n α40 = T(0.184962588071072)\n α43 = T(0.815037411928928)\n α50 = T(0.180718656570380)\n α51 = T(0.314831034403793)\n α54 = T(0.504450309025826)\n α73 = T(0.120199000000000)\n α76 = T(0.879801000000000)\n β10 = T(0.233213863663009)\n β21 = T(0.233213863663009)\n β32 = T(0.233213863663009)\n β43 = T(0.190078023865845)\n β54 = T(0.117644805593912)\n β65 = T(0.233213863663009)\n β76 = T(0.205181790464579)\n c1 = T2(0.233213863663009)\n c2 = T2(0.466427727326018)\n c3 = T2(0.699641590989027)\n c4 = T2(0.760312095463379)\n c5 = T2(0.574607439040817)\n c6 = T2(0.807821302703826)\n\n new{T,T2}(α40, α43, α50, α51, α54, α73, α76, β10, β21, β32, β43, β54, β65, β76, c1, c2, c3, c4, c5, c6)\n end\nend\n\nfunction alg_cache(alg::SSPRK73,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n tmp = zero(u)\n u₁ = zero(u)\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n tab = SSPRK73ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SSPRK73Cache(u,uprev,k,fsalfirst,tmp,u₁,alg.stage_limiter!,alg.step_limiter!,tab)\nend\n\nfunction alg_cache(alg::SSPRK73,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SSPRK73ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n\n@cache struct SSPRK83Cache{uType,rateType,StageLimiter,StepLimiter,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n tmp::uType\n u₂::uType\n u₃::uType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n tab::TabType\nend\n\nstruct SSPRK83ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache\n α50::T\n α51::T\n α54::T\n α61::T\n α65::T\n α72::T\n α73::T\n α76::T\n β10::T\n β21::T\n β32::T\n β43::T\n β54::T\n β65::T\n β76::T\n β87::T\n c1::T2\n c2::T2\n c3::T2\n c4::T2\n c5::T2\n c6::T2\n c7::T2\n\n function SSPRK83ConstantCache(T, T2)\n α50 = T(0.421366967085359)\n α51 = T(0.005949401107575)\n α54 = T(0.572683631807067)\n α61 = T(0.004254010666365)\n α65 = T(0.995745989333635)\n α72 = T(0.104380143093325)\n α73 = T(0.243265240906726)\n α76 = T(0.652354615999950)\n β10 = T(0.195804015330143)\n β21 = T(0.195804015330143)\n β32 = T(0.195804015330143)\n β43 = T(0.195804015330143)\n β54 = T(0.112133754621673)\n β65 = T(0.194971062960412)\n β76 = T(0.127733653231944)\n β87 = T(0.195804015330143)\n c1 = T2(0.195804015330143)\n c2 = T2(0.391608030660286)\n c3 = T2(0.587412045990429)\n c4 = T2(0.783216061320572)\n c5 = T2(0.561833689734037)\n c6 = T2(0.755247658555329)\n c7 = T2(0.804195984669857)\n\n new{T,T2}(α50, α51, α54, α61, α65, α72, α73, α76, β10, β21, β32, β43, β54, β65, β76, β87, c1, c2, c3, c4, c5, c6, c7)\n end\nend\n\nfunction alg_cache(alg::SSPRK83,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n tmp = zero(u)\n u₂ = zero(u)\n u₃ = zero(u)\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n tab = SSPRK83ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SSPRK83Cache(u,uprev,k,fsalfirst,tmp,u₂,u₃,alg.stage_limiter!,alg.step_limiter!,tab)\nend\n\nfunction alg_cache(alg::SSPRK83,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SSPRK83ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n\n@cache struct SSPRK43Cache{uType,rateType,uNoUnitsType,StageLimiter,StepLimiter,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n utilde::uType\n atmp::uNoUnitsType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n tab::TabType\nend\n\nstruct SSPRK43ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache\n one_third_u::T\n two_thirds_u::T\n half_u::T\n half_t::T2\n\n function SSPRK43ConstantCache(T, T2)\n one_third_u = inv(T(3))\n two_thirds_u = 2 * one_third_u\n half_u = T(0.5)\n half_t = T2(0.5)\n\n new{T,T2}(one_third_u, two_thirds_u, half_u, half_t)\n end\nend\n\nfunction alg_cache(alg::SSPRK43,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n utilde = zero(u)\n atmp = similar(u,uEltypeNoUnits)\n tab = SSPRK43ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SSPRK43Cache(u,uprev,k,fsalfirst,utilde,atmp,alg.stage_limiter!,alg.step_limiter!,tab)\nend\n\nfunction alg_cache(alg::SSPRK43,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SSPRK43ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n\n@cache struct SSPRK432Cache{uType,rateType,uNoUnitsType,StageLimiter,StepLimiter} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n utilde::uType\n atmp::uNoUnitsType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\nend\n\nstruct SSPRK432ConstantCache <: OrdinaryDiffEqConstantCache end\n\nfunction alg_cache(alg::SSPRK432,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n utilde = zero(u)\n atmp = similar(u,uEltypeNoUnits)\n SSPRK432Cache(u,uprev,k,fsalfirst,utilde,atmp,alg.stage_limiter!,alg.step_limiter!)\nend\n\nalg_cache(alg::SSPRK432,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits} = SSPRK432ConstantCache()\n\n\n@cache mutable struct SSPRKMSVS32Cache{uType,rateType,dtArrayType,dtType,StageLimiter,StepLimiter} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n fsalfirst::rateType\n u_2::uType\n u_1::uType\n k::rateType\n tmp::uType\n dts::dtArrayType\n dtf::dtArrayType\n μ::dtType\n v_n::Float64\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n step::Int\nend\n\n@cache mutable struct SSPRKMSVS32ConstantCache{uType,dtArrayType,dtType} <: OrdinaryDiffEqConstantCache\n u_2::uType\n u_1::uType\n dts::dtArrayType\n dtf::dtArrayType\n μ::dtType\n v_n::Float64\n step::Int\nend\n\nfunction alg_cache(alg::SSPRKMSVS32,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n fsalfirst = zero(rate_prototype)\n dts = fill(zero(dt),3)\n dtf = fill(zero(dt),2)\n μ = zero(dt)\n u_2 = zero(u)\n u_1 = zero(u)\n k = zero(rate_prototype)\n tmp = zero(u)\n SSPRKMSVS32Cache(u,uprev,fsalfirst,u_2,u_1,k,tmp,dts,dtf,μ,0.5,alg.stage_limiter!,alg.step_limiter!,1)\nend\n\nfunction alg_cache(alg::SSPRKMSVS32,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n dts = fill(zero(dt),3)\n dtf = fill(zero(dt),2)\n μ = zero(dt)\n u_2 = u\n u_1 = u\n SSPRKMSVS32ConstantCache(u_2,u_1,dts,dtf,μ,0.5,1)\nend\n\n\n@cache mutable struct SSPRKMSVS43Cache{uType,rateType,StageLimiter,StepLimiter} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n fsalfirst::rateType\n u_3::uType\n u_2::uType\n u_1::uType\n k::rateType\n k1::rateType\n k2::rateType\n k3::rateType\n tmp::uType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n step::Int\nend\n\n@cache mutable struct SSPRKMSVS43ConstantCache{uType,rateType} <: OrdinaryDiffEqConstantCache\n u_3::uType\n u_2::uType\n u_1::uType\n k1::rateType\n k2::rateType\n k3::rateType\n step::Int\nend\n\nfunction alg_cache(alg::SSPRKMSVS43,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n fsalfirst = zero(rate_prototype)\n u_3 = zero(u)\n u_2 = zero(u)\n u_1 = zero(u)\n k = zero(rate_prototype)\n k1 = zero(rate_prototype)\n k2 = zero(rate_prototype)\n k3 = zero(rate_prototype)\n tmp = zero(u)\n SSPRKMSVS43Cache(u,uprev,fsalfirst,u_3,u_2,u_1,k,k1,k2,k3,tmp,alg.stage_limiter!,alg.step_limiter!,1)\nend\n\nfunction alg_cache(alg::SSPRKMSVS43,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n u_3 = u\n u_2 = u\n u_1 = u\n k1 = rate_prototype\n k2 = rate_prototype\n k3 = rate_prototype\n SSPRKMSVS43ConstantCache(u_3,u_2,u_1,k1,k2,k3,1)\nend\n\n\n@cache struct SSPRK932Cache{uType,rateType,uNoUnitsType,StageLimiter,StepLimiter} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n utilde::uType\n atmp::uNoUnitsType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\nend\n\nstruct SSPRK932ConstantCache <: OrdinaryDiffEqConstantCache end\n\nfunction alg_cache(alg::SSPRK932,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n utilde = zero(u)\n atmp = similar(u,uEltypeNoUnits)\n SSPRK932Cache(u,uprev,k,fsalfirst,utilde,atmp,alg.stage_limiter!,alg.step_limiter!)\nend\n\nalg_cache(alg::SSPRK932,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits} = SSPRK932ConstantCache()\n\n\n@cache struct SSPRK54Cache{uType,rateType,StageLimiter,StepLimiter,TabType} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n k₃::rateType\n u₂::uType\n u₃::uType\n tmp::uType # should be u₄, but tmp is needed for callbacks\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\n tab::TabType\nend\n\nstruct SSPRK54ConstantCache{T,T2} <: OrdinaryDiffEqConstantCache\n β10::T\n α20::T\n α21::T\n β21::T\n α30::T\n α32::T\n β32::T\n α40::T\n α43::T\n β43::T\n α52::T\n α53::T\n β53::T\n α54::T\n β54::T\n c1::T2\n c2::T2\n c3::T2\n c4::T2\n\n function SSPRK54ConstantCache(T, T2)\n β10 = T(0.391752226571890)\n α20 = T(0.444370493651235)\n α21 = T(0.555629506348765)\n β21 = T(0.368410593050371)\n α30 = T(0.620101851488403)\n α32 = T(0.379898148511597)\n β32 = T(0.251891774271694)\n α40 = T(0.178079954393132)\n α43 = T(0.821920045606868)\n β43 = T(0.544974750228521)\n α52 = T(0.517231671970585)\n α53 = T(0.096059710526147)\n β53 = T(0.063692468666290)\n α54 = T(0.386708617503269)\n β54 = T(0.226007483236906)\n c1 = T2(0.391752226571890)\n c2 = T2(0.586079689311540)\n c3 = T2(0.474542363121400)\n c4 = T2(0.935010630967653)\n\n new{T,T2}(β10, α20, α21, β21, α30, α32, β32, α40, α43, β43, α52, α53, β53, α54, β54, c1, c2, c3, c4)\n end\nend\n\nfunction alg_cache(alg::SSPRK54,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n u₂ = zero(u)\n u₃ = zero(u)\n tmp = zero(u)\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n k₃ = zero(rate_prototype)\n tab = SSPRK54ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\n SSPRK54Cache(u,uprev,k,fsalfirst,k₃,u₂,u₃,tmp,alg.stage_limiter!,alg.step_limiter!,tab)\nend\n\nfunction alg_cache(alg::SSPRK54,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n SSPRK54ConstantCache(constvalue(uBottomEltypeNoUnits), constvalue(tTypeNoUnits))\nend\n\n\n@cache struct SSPRK104Cache{uType,rateType,StageLimiter,StepLimiter} <: OrdinaryDiffEqMutableCache\n u::uType\n uprev::uType\n k::rateType\n fsalfirst::rateType\n k₄::rateType\n tmp::uType\n stage_limiter!::StageLimiter\n step_limiter!::StepLimiter\nend\n\nstruct SSPRK104ConstantCache <: OrdinaryDiffEqConstantCache end\n\nfunction alg_cache(alg::SSPRK104,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{true}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits}\n tmp = zero(u)\n k = zero(rate_prototype)\n if calck\n fsalfirst = similar(k)\n else\n fsalfirst = k\n end\n k₄ = zero(rate_prototype)\n SSPRK104Cache(u,uprev,k,fsalfirst,k₄,tmp,alg.stage_limiter!,alg.step_limiter!)\nend\n\nalg_cache(alg::SSPRK104,u,rate_prototype,::Type{uEltypeNoUnits},::Type{uBottomEltypeNoUnits},::Type{tTypeNoUnits},uprev,uprev2,f,t,dt,reltol,p,calck,::Val{false}) where {uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits} = SSPRK104ConstantCache()\n", "meta": {"hexsha": "714edc4e4bff582286c8584fd204d6190fbd7131", "size": 30881, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/caches/ssprk_caches.jl", "max_stars_repo_name": "ordicker/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "6fdc99fa4da79633e0161f0bb8aaff3f39cd39bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 216, "max_stars_repo_stars_event_min_datetime": "2020-04-09T12:02:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:51:07.000Z", "max_issues_repo_path": "src/caches/ssprk_caches.jl", "max_issues_repo_name": "ordicker/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "6fdc99fa4da79633e0161f0bb8aaff3f39cd39bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 381, "max_issues_repo_issues_event_min_datetime": "2020-03-26T11:41:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:05:58.000Z", "max_forks_repo_path": "src/caches/ssprk_caches.jl", "max_forks_repo_name": "ordicker/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "6fdc99fa4da79633e0161f0bb8aaff3f39cd39bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 66, "max_forks_repo_forks_event_min_datetime": "2020-03-30T11:07:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T23:01:12.000Z", "avg_line_length": 29.7504816956, "max_line_length": 245, "alphanum_fraction": 0.7309996438, "num_tokens": 12581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2474121502691017}} {"text": "\"\"\"\n`Model`\n\nA struct representing a model.\n\n**Fields**\n- `variable_names`: Variable names (e.g. `[\"X\", \"Y\", \"Z\"]`).\n- `parameter_names`: Parameter names (e.g. `[\"v\", \"d1\", \"d2\"]`).\n- `problem`: `ODEProblem` or `SDEProblem` or `JumpProblem`.\n- `solver_algorithm`: Solver used to solve the `problem`` (e.g. `SOSRI()`).\n- `solver_parameters`: Parameters passed to the solver (e,g, `(saveat=0.1,)`)\n- `input`: Input to the model representedas a tuple with two elements. The first\n element is a matrix representing the input events and the second element is\n a string that specifies, which parameter is manipulated by the events.\n- `output`: Function that transforms `DifferentialEqualtions` solution\n into a matrix. Rows are time steps and columns are variables.\n\n**Functions**\n- `set_initial_conditions`\n- `set_timespan`\n- `create_model`\n- `set_solver`\n- `get_parameter_index`\n- `get_parameter_value`\n- `set_parameter_value`\n- `set_input`\n- `simulate_population`\n\"\"\"\nstruct Model\n variable_names::Vector{String}\n parameter_names::Vector{String}\n problem::Union{ODEProblem, SDEProblem, JumpProblem}\n solver_algorithm::Any\n solver_parameters::NamedTuple\n input::Tuple{Matrix{Float64}, String}\n output::Function\nend\n\n\n\"\"\"\n`_set_model_property(model::Model; kwargs...)`\n\nCreate a new copy of `model` with replaced fields as specified by the keyword\n arguments.\n\"\"\"\nfunction _set_model_property(model::Model; kwargs...)\n\n # Iterate all possible fields of Model struct\n fields = []\n for field in fieldnames(Model)\n\n # If the field is in kwargs, use it, otherwise use the original value\n if field in keys(kwargs)\n push!(fields, deepcopy(kwargs[field]))\n else\n push!(fields, deepcopy(getproperty(model, field)))\n end\n\n end\n\n # Create a model with new fields\n return Model(fields...)\n\nend\n\n\nfunction _get_problem_property(problem, property_name)\n\n # Property name must be a symbol\n property_name = Symbol(property_name)\n\n # For JumpProblem access problem.prob, otherwise problem directly\n if problem isa JumpProblem\n property = getproperty(problem.prob, property_name)\n else\n property = getproperty(problem, property_name)\n end\n\n # Return the found property\n return property\n\nend\n\n\nfunction _get_problem_property(model::Model, property_name)\n\n return _get_problem_property(model.problem, property_name)\n\nend\n\n\nfunction _set_problem_property(model::Model; kwargs...)\n\n # Remake problem with the new properties\n new_problem = remake(model.problem; kwargs...)\n\n # Replace the problem in the model\n new_model = _set_model_property(model, problem=new_problem)\n \n return new_model\nend\n\n\n\"\"\"\n`set_initial_conditions(model::Model, u0)`\n\nSet initial conditions for a model.\n\"\"\"\nfunction set_initial_conditions(model::Model, u0)\n return _set_problem_property(model; u0=u0)\nend\n\n\n\"\"\"\n`set_timespan(model::Model, tspan)`\n\nSet timespan for a model.\n\"\"\"\nfunction set_timespan(model::Model, tspan)\n return _set_problem_property(model; tspan=tspan)\nend\n\n\nfunction set_output(model::Model, output)\n return _set_model_property(model; output=output)\nend\n\n\n\"\"\"\n`create_model`\n\nCreate a model based on the `DifferentialEqualtions` problem.\n\n**Arguments**\n- `variable_names`: Variable names (e.g. `[\"X\", \"Y\", \"Z\"]`).\n- `parameter_names`: Parameter names (e.g. `[\"v\", \"d1\", \"d2\"]`).\n- `problem`: `ODEProblem` or `SDEProblem` or `JumpProblem`.\n\n**Returns**\n- `model`: Model represented as a `Model` struct.\n\"\"\"\nfunction create_model(variable_names, parameter_names, problem)\n\n # Check that variable names match the length of the initial state\n u0 = _get_problem_property(problem, \"u0\")\n if length(variable_names) != length(u0)\n error(\"Incorrect number of variable names!\")\n end\n\n # Check that parameter names match the length of the parameter vector\n p = _get_problem_property(problem, \"p\")\n if length(parameter_names) != length(p)\n error(\"Incorrect number of parameter names!\")\n end\n\n # Set up a default algorithm based on the problem type\n if problem isa ODEProblem\n solver_algorithm = Tsit5()\n elseif problem isa SDEProblem\n solver_algorithm = SOSRI()\n elseif problem isa JumpProblem\n solver_algorithm = SSAStepper()\n else\n error(\"Unknown problem type!\")\n end\n\n # Set up the other default parameters the do not depend on the problem type\n solver_parameters = (saveat=0.1,)\n input = (Matrix{Float64}(undef, 0, 0), \"\")\n output = sol -> Matrix(sol[:, :]')\n\n # Create the Model struct\n model = Model(\n variable_names,\n parameter_names,\n problem,\n solver_algorithm,\n solver_parameters,\n input,\n output\n )\n\n return model\n \nend\n\n\n\"\"\"\n`set_solver(model::Model, algorithm=nothing; merge_kwargs=true, kwargs...)`\n\nSet solver algorithm and its properties.\n\n**Arguments**\n- `model`: Model.\n\n**Optional Arguments**\n- `algorithm`: Solver algorithm (e.g. `Tsit5()` or `SOSRI()`).\n\n**Keyword Arguments**\n- `merge_kwargs`: If `false`, the original arguments are deleted.\n- `kwargs...`: Solver parameters.\n\n**Returns**\n- `new_model`: Model with updated solver algorithm and parameters.\n\"\"\"\nfunction set_solver(model::Model, algorithm=nothing; merge_kwargs=true, kwargs...)\n \n if :callback in keys(kwargs)\n error(\"Callback is reserved for the input function!\")\n end\n\n if isnothing(algorithm)\n # If the algorithm was not specified, use to original one\n solver_algorithm = model.solver_algorithm\n else\n # If the algorithm was specified, use the new one\n solver_algorithm = algorithm\n end\n\n if length(kwargs) > 0\n # If any kwargs were passed, add them to the solver_parameters\n\n if merge_kwargs\n # Merge kwargs with the existing parameters\n solver_parameters = merge(model.solver_parameters, NamedTuple(kwargs))\n else\n # Replace the old parameters with the new ones\n if :callback in keys(model.solver_parameters)\n # Preserve callback\n callback = model.solver_parameters[:callback]\n solver_parameters = merge(NamedTuple(kwargs), (callback=callback,))\n else\n solver_parameters = NamedTuple(kwargs)\n end\n end\n\n else\n # If no kwargs were passed, just copy the original ones\n solver_parameters = model.solver_parameters\n\n end\n\n # Build a new model\n new_model = _set_model_property(model; solver_algorithm=solver_algorithm,\n solver_parameters=solver_parameters)\n\n return new_model\n\nend\n\n\n\"\"\"\nSet callback to the solver parameters.\n\"\"\"\nfunction _set_callback(model::Model, callback)\n\n # Merge callback with existing solver parameters\n solver_parameters = merge(model.solver_parameters, (callback=callback,))\n\n # Build a new model\n new_model = _set_model_property(model; solver_parameters=solver_parameters)\n\n return new_model\n\nend\n\n\n\"\"\"\n`get_parameter_index(model::Model, parameter_name::String)`\n\nFind index of the specified parameter.\n\n**Arguments**\n- `model`: Model.\n- `parameter_name`: Name of the parameter.\n\n**Returns**\n- `index`: Index indicating the position of the parameter.\n\"\"\"\nfunction get_parameter_index(model::Model, parameter_name::String)\n\n parameter_names = model.parameter_names\n index = findfirst(parameter_names .== parameter_name)\n if isnothing(index)\n error(\"Parameter '$(parameter_name)' is not in the model!\")\n end\n return index\n\nend\n\n\n\"\"\"\n`get_parameter_value(model::Model, parameter_name::String)`\n\nGet a parameter value.\n\n**Arguments**\n- `model`: Model.\n- `parameter_name`: Name of the parameter.\n\n**Returns**\n- `parameter_value`: Value of the parameter.\n\"\"\"\nfunction get_parameter_value(model::Model, parameter_name::String)\n \n index = get_parameter_index(model, parameter_name)\n parameter_values = _get_problem_property(model, \"p\")\n return parameter_values[index]\n\nend\n\n\n\"\"\"\n`set_parameter_value(model::Model, name::String, value::Number)`\n\nSet a parameter value.\n\n**Arguments**\n- `model`: Model.\n- `name`: Name of the parameter. Can also be in the form of \"d1=d2=d3\", which\n sets all parameters d1, d2, and d3 to the same value.\n- `value`: New value for the parameter.\n\n**Returns**\n- `new_model`: Copy of `model` with updated parameter value.\n\"\"\"\nfunction set_parameter_value(model::Model, name::String, value::Number)\n\n # Get array of parameter values\n parameter_values = _get_problem_property(model, \"p\")\n\n if occursin(\"=\", name)\n # If \"=\" occurs in `name`, split the string into individual parameters\n name_array = String.(split(name, \"=\"))\n for name_split in name_array\n # Set each parameter to `value`\n index = get_parameter_index(model, name_split)\n parameter_values[index] = value\n end\n else\n # Set the desired parameter to `value`\n index = get_parameter_index(model, name)\n parameter_values[index] = value\n end\n\n # Rebuild the model with the new parameter value\n new_model = _set_problem_property(model, p=parameter_values)\n return new_model\n\nend\n\n\n\"\"\"\n`model::Model, name_array::Array, value_array::Array`\n\nSet parameter values.\n\n**Arguments**\n- `model`: Model.\n- `name_array`: Parameter names. Can also be in the form of \"d1=d2=d3\", which\n sets all parameters d1, d2, and d3 to the same value.\n- `value_array`: New values for the parameters.\n\n**Returns**\n- `new_model`: Copy of `model` with updated parameter values.\n\"\"\"\nfunction set_parameter_value(model::Model, name_array::Array, value_array::Array)\n\n # The input arrays must have the same length\n if length(name_array) != length(value_array)\n error(\"The array of parameter names and values must have the same length!\")\n end\n\n # Set the parameters\n new_model = deepcopy(model)\n for (name, value) in zip(name_array, value_array)\n new_model = set_parameter_value(new_model, name, value)\n end\n\n return new_model\n\nend\n\n\n\"\"\"\n`_create_callback(events::Matrix, i)`\n\nGenerate `PresetTimeCallback` from `events` modyfing `i`-th parameter.\n\"\"\"\nfunction _create_callback(events::Matrix, i)\n\n p = NaN # holds the original value of the parameter\n\n # Initialization at the beginning of the integration\n initialize = function (c, u, t, integrator)\n\n # Protect the original parameters from overwriting\n integrator.p = copy(integrator.p) \n\n # Save the default parameter\n p = integrator.p[i]\n\n # Set the parameter to 0\n integrator.p[i] = 0.0\n\n end\n\n # Set the parameter to its default value at the beginning of the event\n tstops_on = events[:, 1]\n affect_on! = (integrator) -> integrator.p[i] = p\n callback_on = PresetTimeCallback(tstops_on, affect_on!,\n save_positions=(false, false), initialize=initialize)\n\n # Set the parameter to zero at the end of the event\n tstops_off = events[:, 2]\n affect_off! = (integrator) -> integrator.p[i] = 0.0\n callback_off = PresetTimeCallback(tstops_off, affect_off!,\n save_positions=(false, false))\n\n return CallbackSet(callback_on, callback_off)\n\nend\n\n\n\"\"\"\n`_events_to_function(events::Matrix)`\n\nConvert `events` to a function.\n\"\"\"\nfunction _events_to_function(events::Matrix)\n N = size(events, 1)\n function fun(t)\n for i = 1:N\n if events[i, 1] <= t < events[i, 2]\n return 1.0\n end\n end\n return 0.0\n end\n return fun\nend\n\n\n\"\"\"\n`_create_discrete_callback(events::Matrix, i)`\n\nGenerate `DiscreteCallback` from `events` modyfing `i`-th parameter.\n\"\"\"\nfunction _create_discrete_callback(events::Matrix, i)\n\n p = NaN # holds the original value of the parameter\n\n # Initialization at the beginning of the integration\n initialize = function (c, u, t, integrator)\n\n # Protect the original parameters from overwriting\n integrator.p = copy(integrator.p) \n\n # Save the default parameter\n p = integrator.p[i]\n\n # Set the parameter to 0\n integrator.p[i] = 0.0\n\n end\n\n # Convert the events to a function\n fun = _events_to_function(events)\n\n # Call the function at every step of the integration\n affect! = (integrator) -> integrator.p[i] = fun(integrator.t)*p\n condition = (u, t, integrator) -> true\n callback = DiscreteCallback(condition, affect!; initialize=initialize,\n save_positions=(false, false))\n\n return callback\n\nend\n\n\n\"\"\"\n`set_input(model::Model, events::Matrix, parameter_name=\"I\")`\n\nSet input to the model.\n\n**Arguments**\n- `model`: Model.\n- `events`: Matrix representing the input square function.\n- `parameter_name`: Parameter that is being modified by the input.\n\"\"\"\nfunction set_input(model::Model, events::Matrix, parameter_name=\"I\")\n\n parameter_index = get_parameter_index(model, parameter_name)\n\n # Create a callback\n if model.problem isa Union{ODEProblem, SDEProblem}\n # Use PresetTimeCallback for ODE and SDE models\n callback = _create_callback(events, parameter_index)\n elseif model.problem isa JumpProblem\n # Use DiscreteCallback for Jump models\n callback = _create_discrete_callback(events, parameter_index)\n end\n\n # Build a new model with the specified input\n new_model = _set_callback(model, callback)\n new_model = _set_model_property(new_model, input=(events, parameter_name))\n\n return new_model\n\nend\n\n\n\"\"\"\n`simulate_population(model::Model, trajectories=1; save_trajectories=true,\n show_progress=false)`\n\nSimulate a population.\n\n**Arguments**\n- `model`: Model.\n\n**Optional Arguments**\n- `trajectories`: Number of trajectories to simulate.\n\n**Keyword Arguments**\n- `save_trajectories`: If `false`, only mean is saved.\n- `show_progress`: If `true`, show a progress bar in the terminal.\n\"\"\"\nfunction simulate_population(model::Model, trajectories=1;\n save_trajectories=true, show_progress=false)\n\n # Make sure that the original model is not modified\n model = deepcopy(model)\n\n # Prepare variables for PopulationSolution fields\n t = Vector{Float64}(undef, 0) # time\n m = Matrix{Float64}(undef, 0, 0) # mean\n U = Array{Float64, 3}(undef, 0, 0, 0) # trajectories\n events = model.input[1] # events\n \n # Initialize the porgress meter\n if show_progress\n progress_meter = ProgressMeter.Progress(trajectories; barlen=20)\n end\n\n # Simulate trajectories\n success_arr = fill(false, trajectories) # success for individual trajectories\n lk = ReentrantLock()\n Threads.@threads for i = 1:trajectories\n\n model2 = deepcopy(model)\n\n # Solve the problem\n sol2 = solve(model2.problem, model2.solver_algorithm; model2.solver_parameters...)\n\n # Check if the simulation was successful\n if model2.problem isa Union{ODEProblem, SDEProblem}\n success_arr[i] = sol2.retcode == :Success\n elseif model2.problem isa JumpProblem\n success_arr[i] = sol2.retcode == :Default\n else\n error(\"Unknown model type!\")\n end\n\n # Save the solution if the current simulation was successful\n if success_arr[i]\n\n lock(lk) do\n\n # Save time\n if isempty(t)\n t = sol2.t\n end\n\n # Map solution to a matrix\n x = model2.output(sol2)\n\n # Add the trajectory contribution to the mean\n if isempty(m)\n # Initialize the mean vector\n m = (x ./ trajectories)\n else\n # Add solution to the mean vector\n m .+= (x ./ trajectories)\n end\n\n # Save the individual trajectory\n if save_trajectories\n if isempty(U)\n # Initialize the matrix for individual trajectories\n nsamples = size(x, 1)\n nvariables = size(x, 2)\n U = fill(NaN, nsamples, nvariables, trajectories)\n end\n # Add the current trajectory to the trajectory list\n U[:, :, i] = x\n end\n\n end\n\n else\n # Stop the simulation if the current simulation was unsuccessful\n break\n end\n\n if show_progress\n lock(lk) do\n ProgressMeter.next!(progress_meter)\n end\n end\n\n end\n\n # Build the output struct\n success = all(success_arr)\n solution = PopulationSolution(t, m, U, events, success)\n\n return solution\n\nend\n\n\n\"\"\"\n`scan`\n\nScan parameters of a model.\n\n**Arguments**\n- `model`: Model.\n- `parameter_names`: Parameter names to scan.\n- `parameter_values`: Parameter values for each parameter to scan over.\n- `summary_function`: A function that takes in a model, evaluates it, and\n returns some parameters. If the function is called without any arguments,\n it returns the names of the parameters as a vector of strings. For example\n ```\n julia> summary_function(model)\n [1.1, 2.2, 3.3]\n julia> summary_function()\n [\"Period\", \"Amplitude\", \"Phase\"]\n ```\n\n**Keyword Arguments**\n- `show_progress`: If `true`, show a progress bar in the terminal.\n\n**Returns**\n- `df`: Dataframe with results.\n\"\"\"\nfunction scan(model::Model, parameter_names, parameter_values,\n summary_function; show_progress=false)\n\n # Protect the original model from overwriting\n model = deepcopy(model)\n\n # Find all possible parameter combinations\n parameter_value_combinations = find_all_combinations(parameter_values)\n n = size(parameter_value_combinations, 1)\n \n # Initialize summary matrix\n summary_names = summary_function()\n scan_summary = fill(NaN, n, length(summary_names))\n\n # Initialize progress bar\n if show_progress\n progressmeter = ProgressMeter.Progress(n; barlen=20)\n end\n\n # Iterate all parameter value combinations\n lk = ReentrantLock()\n Threads.@threads for i = 1:n\n\n # Set model parameters\n pmodel = set_parameter_value(model, parameter_names, parameter_value_combinations[i, :])\n\n # Evaluate the sumary function\n pmodel_summary = summary_function(pmodel)\n\n # Save the model summary to the overall matrix\n scan_summary[i, :] = pmodel_summary\n\n # Update progress bar\n if show_progress\n lock(lk) do\n ProgressMeter.next!(progressmeter)\n end\n end\n\n end\n\n # Build the output dataframe\n matrix = hcat(parameter_value_combinations, scan_summary)\n names = vcat(parameter_names, summary_names)\n df = DataFrame(matrix, names)\n\n return df\n\nend\n\n\n\"\"\"\n`estimate_binary_arnold_tongue`\n\nUse binary search to estimate arnold tongue for a model.\n\n**Arguments**\n- `model`: Model.\n- `periods`: A two-element array like `[minimal_period, maximal_period]`.\n- `amplitudes`: Input amplitudes to scan.\n\n**Keyword Arguments**\n- `trajectories`: Number of trajectories in a population.\n- `i_solution`: Number of the state to use to estimate the period.\n- `n_lags`: Number of lags used to estimate the autocorrelation functions.\n- `input_parameter_name`: Name of the parameter that control the input amplitude.\n- `min_time`: Minimal time to consider (to remove the effect of initial conditions).\n- `max_time`: Maximal time of the simulation.\n- `show_progress`: If true, show a progress bar in the terminal.\n- `period_error`: Maximal allowed output period deviation from the input period.\n- `boundary_error`: Maximal allowed error to estimate the boundary between the\n entrained and unentrained regions.\n- `maximal_error_attempts`: How many attempts should be given to an errored simulation.\n\"\"\"\nfunction estimate_binary_arnold_tongue(model::Model, periods, amplitudes;\n trajectories=1, i_solution=1, n_lags=1000, input_parameter_name=\"I\",\n min_time=nothing, max_time=nothing, show_progress=false, period_error=0.01,\n boundary_error=0.01, maximal_error_attempts=0)\n\n # Protect the original model from overwriting\n model = deepcopy(model)\n\n # Set the maximal time of the simulation\n if !isnothing(max_time)\n model = set_timespan(model, (0.0, max_time))\n end\n\n # Get minimal and maximal amplitude and the number of periods to scan\n minimal_amplitude = amplitudes[1]\n maximal_amplitude = amplitudes[end]\n n_periods = length(periods)\n\n # Each element is the minimal amplitude of entrainment for the given period\n entrainment_amplitudes = fill(NaN, n_periods)\n \n # Initialize a progress bar\n if show_progress\n progressmeter = ProgressMeter.Progress(n_periods; barlen=20)\n end\n\n # Iterate all period-amplitude combinations\n lk = ReentrantLock()\n Threads.@threads for i = 1:n_periods # Threads.@threads \n\n # Set the forcing (input) period\n forcing_period = periods[i]\n \n # Create events for the current forcing period\n if model.problem isa JumpProblem\n end_time = model.problem.prob.tspan[2]\n else\n end_time = model.problem.tspan[2]\n end\n nevents = end_time / forcing_period + 1\n events = create_events([(:DD, forcing_period*0.5),\n (:LD, nevents, forcing_period*0.5, forcing_period*0.5)])\n \n # Set offset (solution before this time is discarted)\n if isnothing(min_time)\n offset = end_time*0.5\n else\n offset = min_time\n end\n \n # pmodel = deepcopy(model)\n pmodel = set_input(model, events, input_parameter_name)\n \n \"\"\"\n This function will be optimized using the binary boundary search. It\n simulates the model for the given forcing amplitude and returns `true`\n if the model is entrained and `false` if the model is unentrained.\n \"\"\"\n function fun(forcing_amplitude)\n \n # Set the forcing amplitude and events to the model\n pmodel = set_parameter_value(pmodel, input_parameter_name, forcing_amplitude)\n\n # Simulate the population\n solution = PopulationSolution()\n success = false\n counter = 0\n while !success\n try\n # lock(lk) do\n solution = simulate_population(pmodel, trajectories;\n save_trajectories=false)\n # end\n success = true\n catch err\n counter += 1\n if counter >= maximal_error_attempts\n @warn \"[LAST] Simulation threw an error: $err\"\n solution = PopulationSolution()\n success = true\n else\n @warn \"[$counter] Simulation threw an error: $err\"\n end\n end \n end\n\n # If the simulation was successful, estimate the period\n if solution.success\n \n # Discard the simulation start\n solution = select_time(solution, mintime=offset)\n t = solution.time\n m = solution.mean[:, i_solution]\n \n R_period, _ = estimate_period(t, m; n_lags=n_lags)\n \n return abs(R_period - forcing_period) <= period_error\n\n else\n\n return false\n\n end\n\n end\n\n # Perform binary search\n entrainment_amplitudes[i] = binary_boundary_search(fun,\n [minimal_amplitude, maximal_amplitude], boundary_error)\n\n # Update the progress bar\n if show_progress\n ProgressMeter.next!(progressmeter)\n end\n\n end\n\n # Create the output dataframe\n arnold_tongue = DataFrame(periods=periods, amplitudes=entrainment_amplitudes)\n \n return arnold_tongue\n\nend\n", "meta": {"hexsha": "ca58dfb253a6d8048e4732bab0bc4bd1fd7502fb", "size": 24052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Model.jl", "max_stars_repo_name": "vkumpost/stoosc", "max_stars_repo_head_hexsha": "2a1fd4dc3adf9e6066877aa4134530f9d79a16cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Model.jl", "max_issues_repo_name": "vkumpost/stoosc", "max_issues_repo_head_hexsha": "2a1fd4dc3adf9e6066877aa4134530f9d79a16cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Model.jl", "max_forks_repo_name": "vkumpost/stoosc", "max_forks_repo_head_hexsha": "2a1fd4dc3adf9e6066877aa4134530f9d79a16cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4639053254, "max_line_length": 96, "alphanum_fraction": 0.6564111093, "num_tokens": 5444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.24730548838310124}} {"text": "\nexport LightSource, DistantLight, PointLight, DiskLight\n\n\n################################\n# Visibility Tester is a ray from point to light source\n\n\"\"\"\n VisibilityTester(p1::Point3, p2::Point3, eps1::Float64, eps2::Float64)\n\nReturns a ray to test intersection on the line segment from `p1` to `p2` with the given ray\nepsilon values.\n\n\"\"\"\nfunction VisibilityTester(p1::Point3, p2::Point3, eps1::Float64, eps2::Float64)\n distance = norm(p2-p1)\n return Ray(p1, (p2-p1)/distance, eps1, distance*(1.0 - eps2), 1)\nend\n\n\n\"\"\"\n VisibilityTester(origin::Point3, direction::Vector3, eps::Float64)\n\nReturns a ray to test intersection on the line segment from `origin` infinitely far in the\ngiven direction, with a given ray epsilon.\n\n\"\"\"\nfunction VisibilityTester(origin::Point3, direction::Vector3, eps::Float64)\n return Ray(origin, direction, eps, Inf, 1)\nend\n\n\n\n\n\n\n################################\n# Point light\n\n\n\"\"\"\n PointLight{S<:Spectrum} <: LightSource\n\nPoint light source. It's located at a given point and radiates isotropically. The intensity\nvalue given is interpreted as the intensity in Watts/m^2 at a distance of 1 meter.\n\n# Fields\n\n- `position::Point3`, the location of the light source.\n- `intensity::S`, the intensity at a distance of 1 meter in Watts/m^2.\n- `light_to_world::Transformation`, transformation to shift the location of the light\n source.\n- `world_to_light::Transformation`, inverse transformation of the above.\n\n\"\"\"\nstruct PointLight{S<:Spectrum} <: LightSource\n position::Point3\n intensity::S\n light_to_world::Transformation\n world_to_light::Transformation\nend\n\n\n\"\"\"\n PointLight(L::Spectrum, l2w::Transformation)\n\n\nCreate a new `PointLight` with the given spectrum, located at the origin but shifted by\nthe given `Transformation`.\n\n\"\"\"\nfunction PointLight(L::Spectrum, l2w::Transformation)\n PointLight(l2w(Point3(0)), L, l2w, inv(l2w))\nend\n\n\n\"\"\"\n sample_L(light::PointLight, p::Point3)\n\nGet an intensity sample from the given `DistantLight` and a ray from the light towards the\ngiven point. The sample is always the same since the light source is a uniform parallel\nlight.\n\nReturns:\n\n- Intensity `Spectrum`\n- Direction `Vector3` of the light.\n- A weight coefficient which is always 1.0\n- A ray from the light source to the given point.\n\n\"\"\"\nfunction sample_L(light::PointLight, p::Point3)\n distance = norm(light.position - p)\n L = light.intensity / distance^2\n pdf = 1.0\n vis = VisibilityTester(p, light.position, 2e-5, 0.0)\n return L, pdf, vis\nend\n\n\n\"\"\"\n generate_ray(light::PointLight, bounds::BoundingSphere, S::Sample)\n\nReturns a ray from the light source at the given `BoundingSphere`, parametrized by the\ngiven random sample.\n\n\"\"\"\nfunction generate_ray(light::PointLight, bounds::BoundingSphere, S::Sample)\n ray = ray_from_point(bounds.radius, S.imgX, S.imgY)\n return light.light_to_world(ray)\nend\n\n\n################################\n# Distanct light source\n\n\"\"\"\n DistantLight{S<:Spectrum} <: LightSource\n \nA point light source infinitely far away, i.e. parallel rays with a given intensity spectrum\ninterpreted as Watts / m^2.\n\nBy default the light source is \"located\" infinitely far away along the positive Z axis and\nthe light rays travel in the -Z direction.\n\n# Fields\n\n- `intensity::S`, the intensity of the light in Watts/m^2.\n- `light_to_world::Transformation`, transformation to define the direction of the light\n source.\n- `world_to_light::Transformation`, inverse transformation of the above.\n\n\n\"\"\"\nstruct DistantLight{S<:Spectrum} <: LightSource\n intensity::S\n light_to_world::Transformation\n world_to_light::Transformation\nend\n\n\n\"\"\"\n function DistantLight(L::Spectrum, l2w::Transformation)\n\nCreate a new `DistantLight` given the intensity spectrum (in units of Watts / m^2) and\na `Transformation` used to rotate the direction of the light.\n \n\"\"\"\nfunction DistantLight(L::Spectrum, l2w::Transformation)\n DistantLight(L, l2w, inv(l2w))\nend\n\n\n\"\"\"\n sample_L(light::DistantLight, p::Point3)\n\nGet an intensity sample from the given `DistantLight` and a ray from the light towards the\ngiven point. The sample is always the same since the light source is a uniform parallel\nlight.\n\nReturns:\n\n- Intensity `Spectrum`\n- A weight coefficient which is always 1.0\n- A ray from the light source to the given point.\n\n\"\"\"\nfunction sample_L(light::DistantLight, p::Point3)\n return light.intensity, 1.0, VisibilityTester(p, light.light_to_world(NEG_Z_AXIS), 1e-9)\nend\n\n\n\"\"\"\n generate_ray(light::DistantLight, bounds::BoundingSphere, S::Sample)\n\nReturns a ray from the light source at the given `BoundingSphere`, parametrized by the\ngiven random sample.\n\n\"\"\"\nfunction generate_ray(light::DistantLight, bounds::BoundingSphere, S::Sample)\n ray = ray_parallel(bounds.radius, S.imgX, S.imgY)\n shift = translation(bounds.center)\n return shift(light.light_to_world(ray))\nend\n\n\n\n\n\n\n\n\n###### ########################\n# TODO: Area light\nstruct AreaLight <: LightSource end\n\n\n\n\n################################\n# Disk Light (TODO)\n\n\"\"\"\n DiskLight{S<:Spectrum} <: LightSource\n\nA light source which is a uniformly illuminated disk far away. Expressed in terms of its\nangular radius. By default it's in the positive Z direction, and can be rotated with\na transformation.\n\n# Fields:\n\n- `radius::Float64`, angular radius (in radians) of the source\n- `intensity::S`, \n- `light_to_world::Transformation`, transformation to adjust the direction of the source.\n Chosen to rotate the +Z axis into the desired direction of the light.\n- `world_to_light::Transformation`, inverse transformation of the above\n\n\"\"\"\nstruct DiskLight{S<:Spectrum} <: LightSource \n radius::Float64\n intensity::S\n light_to_world::Transformation\n world_to_light::Transformation\nend\n\n\n\"\"\"\n DiskLight(direction::Vector3, radius::Float64, intensity::Spectrum)\n\nCreate new `DiskLight` in the desired direction, angular radius and intensity.\n\n\"\"\"\nfunction DiskLight(direction::Vector3, radius::Float64, intensity::Spectrum)\n rot_z = rotate_z_to(direction)\n Ω = 2π * (1 - cos(radius))\n return DiskLight(radius, Ω.*intensity, rot_z, inv(rot_z))\nend\n\n\n\n@inline solid_angle(D::DiskLight) = 2π * (1 - cos(D.radius))\n\n\n\n\nsample_L(light::DiskLight, p::Point3) = sample_L(light, p, rand(), rand())\n\nfunction sample_L(light::DiskLight, p::Point3, u1::Real, u2::Real)\n direction = light.light_to_world(disk_light_sample(light.radius, u1, u2))\n return light.intensity, 1.0, VisibilityTester(p, direction, 2e-9)\nend\n\n\n\"\"\"\n disk_light_sample(radius::Real, u1::Real, u2::Real)\n\nCreate a vector which points from origin to a point on the surface of a disk with given\nangular radius centered on the +Z axis. It is parametrized by two numbers, `u1` and `u2`,\nwhich range from zero to one. Using uniform random numbers will result in the surface of\nthe disk to be uniformly sampled.\n\n\"\"\"\nfunction disk_light_sample(radius::Real, u1::Real, u2::Real)\n cos_th = cos(radius)\n z = cos_th + (1.0 - cos_th) * u1\n phi = 2π * u2\n r = sqrt(1.0 - z^2)\n return Vector3(r*cos(phi), r*sin(phi), z)\nend\n\n\n\"\"\"\n generate_ray(light::DiskLight, bounds::BoundingSphere, S::Sample)\n\nReturns a ray from the light source at the given `BoundingSphere`, parametrized by the\ngiven random sample.\n\n\"\"\"\nfunction generate_ray(light::DiskLight, bounds::BoundingSphere, S::Sample)\n # Pick a direction, i.e. a point on the (infinitely distant) disk\n # and make the transformation to rotate Z into that direction\n V = disk_light_sample(light.radius, S.lensU, S.lensV)\n rot = light.light_to_world * rotate_z_to(V)\n \n # Make a ray from infinitely far along the Z axis and rotate it into the direction \n # given by T. Also shift it relative to the origin of the bounding sphere.\n \n ray = ray_parallel(bounds.radius, S.imgX, S.imgY)\n T = translation(bounds.center) * rot\n return T(ray)\nend\n\n\n\n", "meta": {"hexsha": "43e07957adf615a46f3a07478394bfb6bc206707", "size": 7903, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lights.jl", "max_stars_repo_name": "dronir/GRAYTR", "max_stars_repo_head_hexsha": "5919ce3685faa2f913f9743cacccc79f4f67defe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-19T16:11:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-19T22:21:29.000Z", "max_issues_repo_path": "src/lights.jl", "max_issues_repo_name": "dronir/GRAYTR", "max_issues_repo_head_hexsha": "5919ce3685faa2f913f9743cacccc79f4f67defe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lights.jl", "max_forks_repo_name": "dronir/GRAYTR", "max_forks_repo_head_hexsha": "5919ce3685faa2f913f9743cacccc79f4f67defe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7898305085, "max_line_length": 92, "alphanum_fraction": 0.7128938378, "num_tokens": 2022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2472079494859962}} {"text": "function gamesize(g::AirDefenseGame)\r\n ncity, ndp, nap, ndpdc, ndpac, ndc, nac = g.ncity, g.ndp, g.nap, g.ndpdc, g.ndpac, g.ndc, g.nac\r\n nIc1 = 1\r\n nIa2 = binomial(ndp, ndpac)\r\n nIa5 = nIa2 * binomial(ndp, nac) * binomial(ndp, ndc)\r\n nIc3 = 1\r\n nId4 = binomial(ndp, ndpdc) * (2 ^ ndp)\r\n nIa = @sprintf(\"%.2E\", nIa2 + nIa5)\r\n nId = @sprintf(\"%.2E\", nId4)\r\n na1c = binomial(ndp, ndpdc)\r\n na2c = binomial(ndp, ndpac)\r\n na3a = binomial(ndpac, nac)\r\n na4c = 2 ^ nac\r\n na5d = binomial(ndpdc, ndc)\r\n na6a = binomial(ncity, nap)\r\n nas = [na1c, na2c, na3a, na4c, na5d, na6a]\r\n leafnodes = @sprintf(\"%.2E\", prod(nas))\r\n nnodes = @sprintf(\"%.2E\", sum(cumprod(nas)))\r\n (nIa, nId, leafnodes, nnodes)\r\nend\r\n\r\n# N : player indices (nature not included)\r\ngetplayers(g::AirDefenseGame) = 1:2\r\n\r\n# Player index of current node (note: this is distinct from which player is currently updating CFR)\r\nfunction getplayer(depth::Int64)\r\n (depth == 6 || depth == 3) ? 2 : (depth == 5) ? 1 : 3\r\n # 1 = defender, 2 = attacker, 3 = nature\r\nend\r\n\r\nactions(depth::Int64, An::Vector{UnitRange{Int64}}) = An[depth]\r\nactions(depth::Int64, A::Vector{Vector{Vector{Int64}}}) = 1:length(A[depth])\r\n\r\nfunction numactions(I::Int64, ni_stage, na_stage)\r\n if I in 1:ni_stage[3]\r\n return na_stage[3] # na3a\r\n elseif I in (ni_stage[3] + 1):(ni_stage[3] + ni_stage[5])\r\n return na_stage[5] # na5d\r\n elseif I in (ni_stage[3] + ni_stage[5] + 1):(ni_stage[3] + ni_stage[5] + ni_stage[6])\r\n return na_stage[6] # na5a\r\n else\r\n @warn \"Infoset $I not found.\"\r\n return 0\r\n end\r\nend\r\n\r\nterminal(depth::Int64) = depth == 7\r\n\r\nfunction details(h::SVector, A)\r\n len = findfirst(x -> x == 0, h) - 1\r\n (len == nothing) && (len = length(h))\r\n df = DataFrame(Stage = Int[], Domain = String[], Player = String[], ActionNumber = Int[], Action = Array[])\r\n for i = 1:len\r\n stage = i\r\n domain = (i == 6) ? \"Physical\" : \"Cyber\"\r\n p = getplayer(h[1:i])\r\n pstring = p == 2 ? \"Attacker\" : p == 1 ? \"Defender\" : \"Chance\"\r\n push!(df, (stage, domain, pstring, h[i], A[i][h[i]]))\r\n end\r\n df\r\nend\r\n\r\nfunction infoset(h::SVector, depth::Int64, g::AirDefenseGame, gs::GameSet) # btime: ~150 ns\r\n # findfirst benchmarks faster than numerically calculating infoset (see earlier commit)\r\n A, ni_stage, na_stage, sensors, iadsdefenses = gs.A, gs.ni_stage, gs.na_stage, gs.sensors, gs.iadsdefenses\r\n cyber_attacks, cyber_defenses = A[3], A[5]\r\n ndp, nac = g.ndp, g.nac\r\n len = depth - 1\r\n if len == 5\r\n defended_iads = getindex(gs.A[1][h[1]], gs.A[5][h[5]])\r\n idc = findfirst(x -> x == defended_iads, iadsdefenses)\r\n niadsdefenses = length(gs.iadsdefenses)\r\n return sum(ni_stage[1:5]) + (h[2] - 1) * na_stage[3] * niadsdefenses + (h[3] - 1) * niadsdefenses + idc\r\n elseif len == 4\r\n nsensor = length(sensors) # number of combinations of sensed cyber attacks\r\n sensed = getindex(gs.A[2][h[2]], getindex(A[3][h[3]], A[4][h[4]] .== 2)) # ndp id's of sensed attacks\r\n isensor = findfirst(x -> x == sensed, sensors) # infoset id of that combination\r\n return sum(ni_stage[1:4]) + (h[1] - 1) * nsensor + isensor\r\n elseif len == 2\r\n return h[2]\r\n else\r\n player = getplayer(h)\r\n @warn \"No infoset found. Chance node? h = $h, player = $player.\"\r\n return 0\r\n end\r\nend\r\n\r\n#TODO: Make these probabilities more rational?\r\nfunction chance(depth::Int64, a::Int64, g::AirDefenseGame, gs::GameSet)\r\n len = depth - 1\r\n if len == 3 # nature determines defense cyber SA\r\n nsensed = sum(gs.A[4][a] .== 2) # number of sensed attacks\r\n return (g.psc ^ nsensed) * (1 - g.psc)^(g.nac - nsensed)\r\n elseif len == 1 # nature deals offensive capes\r\n return 1.0 / gs.na_stage[2]\r\n elseif len == 0 # nature deals defensive capes\r\n return 1.0 / gs.na_stage[1]\r\n else\r\n @warn \"Node at depth $depth not a chance node.\"\r\n return 0.0\r\n end\r\nend\r\n\r\nfunction leafutility(h::SVector, player::Int64, πi::Float64, πo::Float64, g::AirDefenseGame, gs::GameSet)\r\n c1, c2, ac, c4, dc, ap = h\r\n attacked_cities = @view gs.A[6][h[6]][:]\r\n defended_iads = getindex(g.iads, getindex(gs.A[1][h[1]], gs.A[5][h[5]]))\r\n attacked_iads = getindex(g.iads, getindex(gs.A[2][h[2]], gs.A[3][h[3]]))\r\n leaf_value = utility(g, gs.C, defended_iads, attacked_iads, attacked_cities)\r\n u = player == 1 ? leaf_value * πo : -1.0 * leaf_value * πo\r\n return u\r\nend\r\n\r\n# convert behavioral strategy to realization strategy (i.e. sequence form?)\r\nfunction real_strat_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\n length(σ) != ni && @warn \"Unexpected behavioral strategy length: $(length(σ)).\"\r\n σ1 = σ[(ni_stage[3] + 1):sum(ni_stage[1:5])]\r\n σ2 = vcat(σ[1:ni_stage[3]], σ[(sum(ni_stage[1:5]) + 1):end])\r\n rp1 = zeros(Float64, ns1)\r\n rp2 = zeros(Float64, ns2)\r\n rp1[1], rp2[1] = 1.0, 1.0\r\n for (i, s1) in enumerate(σ1)\r\n rp1[nextseqI1[i]] .= rp1[seqI1[i]] .* s1\r\n end\r\n for (i, s2) in enumerate(σ2)\r\n rp2[nextseqI2[i]] .= rp2[seqI2[i]] .* s2\r\n end\r\n return (rp1, rp2)\r\nend\r\n\r\nfunction real_strat_struct_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\n length(σ) != ni && @warn \"Unexpected behavioral strategy length: $(length(σ)).\"\r\n σ1 = σ[(ni_stage[3] + 1):sum(ni_stage[1:5])]\r\n σ2 = vcat(σ[1:ni_stage[3]], σ[(sum(ni_stage[1:5]) + 1):end])\r\n rp1_struct, rp2_struct = similar(σ1), similar(σ2)\r\n rp1, rp2 = real_strat_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\n for (i, s1) in enumerate(σ1)\r\n rp1_struct[i] = rp1[nextseqI1[i]]\r\n end\r\n for (i, s2) in enumerate(σ2)\r\n rp2_struct[i] = rp2[nextseqI2[i]]\r\n end\r\n return (rp1_struct, rp2_struct)\r\nend\r\n\r\nfunction real_strat_struct_combined_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\n σ1 = σ[(ni_stage[3] + 1):sum(ni_stage[1:5])]\r\n σ2 = vcat(σ[1:ni_stage[3]], σ[(sum(ni_stage[1:5]) + 1):end])\r\n rp1_struct, rp2_struct = similar(σ1), similar(σ2)\r\n rp1, rp2 = real_strat_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\n for (i, s1) in enumerate(σ1)\r\n rp1_struct[i] = rp1[nextseqI1[i]]\r\n end\r\n for (i, s2) in enumerate(σ2)\r\n rp2_struct[i] = rp2[nextseqI2[i]]\r\n end\r\n rp_struct = similar(σ)\r\n rp_struct[1:ni_stage[3]] .= rp2_struct[1:ni_stage[3]]\r\n rp_struct[(ni_stage[3] + 1):sum(ni_stage[1:5])] .= rp1_struct\r\n rp_struct[(sum(ni_stage[1:5]) + 1):end] .= rp2_struct[(ni_stage[3] + 1):end]\r\n return rp_struct\r\nend\r\n\r\nfunction real_strat(σ::Vector{Vector{Float64}}, gs::GameSet, gos::GameOptSet)\r\n ni, ni_stage, ns1, ns2 = gs.ni, gs.ni_stage, gos.ns1, gos.ns2\r\n seqI1, seqI2, nextseqI1, nextseqI2 = gos.seqI1, gos.seqI2, gos.nextseqI1, gos.nextseqI2\r\n return real_strat_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\nend\r\n\r\nfunction real_strat(σ::Vector{Vector{Float64}}, g::AirDefenseGame)\r\n A, _, na_stage = build_action(g)\r\n ni, ni1, ni2, ni_stage = build_info(g)\r\n ns1, ns2, ns1_stage, ns2_stage = build_nseq(g, na_stage, ni_stage)\r\n _, _, (seqI1, seqI2), (nextseqI1, nextseqI2) = build_Iset(g, A, na_stage, ns1_stage, ns2_stage, ni1, ni2, ns1, ns2)\r\n return real_strat_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\nend\r\n\r\nfunction real_strat_struct(σ::Vector{Vector{Float64}}, g::AirDefenseGame)\r\n A, _, na_stage = build_action(g)\r\n ni, ni1, ni2, ni_stage = build_info(g)\r\n ns1, ns2, ns1_stage, ns2_stage = build_nseq(g, na_stage, ni_stage)\r\n _, _, (seqI1, seqI2), (nextseqI1, nextseqI2) = build_Iset(g, A, na_stage, ns1_stage, ns2_stage, ni1, ni2, ns1, ns2)\r\n return real_strat_struct_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\nend\r\n\r\nfunction real_strat_struct_combined(σ::Vector{Vector{Float64}}, g::AirDefenseGame)\r\n A, _, na_stage = build_action(g)\r\n ni, ni1, ni2, ni_stage = build_info(g)\r\n ns1, ns2, ns1_stage, ns2_stage = build_nseq(g, na_stage, ni_stage)\r\n _, _, (seqI1, seqI2), (nextseqI1, nextseqI2) = build_Iset(g, A, na_stage, ns1_stage, ns2_stage, ni1, ni2, ns1, ns2)\r\n return real_strat_struct_combined_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\nend\r\n\r\nfunction real_strat_struct_combined(σ::Vector{Vector{Float64}}, gs::GameSet, seqvals)\r\n ni, ni_stage = gs.ni, gs.ni_stage\r\n ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2 = seqvals\r\n return real_strat_struct_combined_calc(σ, ni, ni_stage, ns1, ns2, seqI1, seqI2, nextseqI1, nextseqI2)\r\nend\r\n\r\n# build consraint set on sequence-form strategy for CCFR\r\nfunction build_ccfr_constraints(g, σfix, conf::Float64, sd::Float64)\r\n noise = Normal(0, sd)\r\n hw = quantile(noise, 1 - (1 - conf) / 2)\r\n σlb = [max.(σi .- hw, 0.0) for σi in σfix]\r\n σub = [min.(σi .+ hw, 1.0) for σi in σfix]\r\n rp2fix = real_strat_struct(σfix, g)[2]\r\n rp2lb = real_strat_struct(σlb, g)[2]\r\n rp2ub = real_strat_struct(σub, g)[2]\r\n !all(rp2lb .<= rp2fix .<= rp2ub) && @warn \"Sequence-form strategy out of bounds.\"\r\n constraint_coeff = [[1, -1 .* rp2lb[i][j]] for i in 1:length(rp2lb), j in 1:length(rep2lb[i])]\r\n constraint_coeff = vcat(hcat(ones(length(rp2fix)), -1 .* rp2lb), hcat(-1 .* ones(length(rp2fix)), rp2ub))\r\n @show length(constraint_coeff), length(constraint_coeff[:,1])\r\n grad_constraint_coeff = hcat(constraint_coeff[:,1], zeros(length(constraint_coeff[:,1])))\r\n return constraint_coeff, grad_constraint_coeff\r\nend\r\n", "meta": {"hexsha": "1780c978507917020beb8c3b2c00d436790daf0a", "size": 9672, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ops_methods.jl", "max_stars_repo_name": "ajkeith/Cyber-Air-Defense", "max_stars_repo_head_hexsha": "856b833e7c6cbfe389b2ec1b21edb5d6e6ee97e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-09-25T16:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:21:35.000Z", "max_issues_repo_path": "src/ops_methods.jl", "max_issues_repo_name": "ajkeith/Cyber-Air-Defense", "max_issues_repo_head_hexsha": "856b833e7c6cbfe389b2ec1b21edb5d6e6ee97e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-08T14:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T00:42:16.000Z", "max_forks_repo_path": "src/ops_methods.jl", "max_forks_repo_name": "ajkeith/CFR_ICADS", "max_forks_repo_head_hexsha": "856b833e7c6cbfe389b2ec1b21edb5d6e6ee97e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-25T16:52:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T16:52:02.000Z", "avg_line_length": 44.7777777778, "max_line_length": 120, "alphanum_fraction": 0.6260339123, "num_tokens": 3514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2472010434254796}} {"text": "\n\"\"\"\nType representing a third-order tensor\n\"\"\"\nstruct ThirdOrderTensorValue{D1,D2,D3,T,L} <: MultiValue{Tuple{D1,D2,D3},T,3,L}\n data::NTuple{L,T}\n function ThirdOrderTensorValue{D1,D2,D3,T}(data::NTuple{L,T}) where {D1,D2,D3,T,L}\n @assert L == D1*D2*D3\n new{D1,D2,D3,T,L}(data)\n end\nend\n\n# Empty ThirdOrderTensorValue constructor\n\nThirdOrderTensorValue() = ThirdOrderTensorValue{0,0,0,Int}(NTuple{0,Int}())\nThirdOrderTensorValue{0,0,0}() = ThirdOrderTensorValue{0,0,0,Int}(NTuple{0,Int}())\nThirdOrderTensorValue{0,0,0,T}() where{T} = ThirdOrderTensorValue{0,0,0,T}(NTuple{0,T}())\nThirdOrderTensorValue(data::NTuple{0}) = ThirdOrderTensorValue{0,0,0,Int}(data)\nThirdOrderTensorValue{0,0,0}(data::NTuple{0}) = ThirdOrderTensorValue{0,0,0,Int}(data)\n\n# ThirdOrderTensorValue single NTuple argument constructor\n\n@generated function ThirdOrderTensorValue(data::NTuple{L,T}) where {L,T}\n D=Int(cbrt(L))\n quote\n ThirdOrderTensorValue{$D,$D,$D,T}(data)\n end\nend\nThirdOrderTensorValue{D}(data::NTuple{L,T}) where {D,L,T} = ThirdOrderTensorValue{D,D,D,T}(data)\nThirdOrderTensorValue{D1,D2,D3}(data::NTuple{L,T}) where {D1,D2,D3,L,T} = ThirdOrderTensorValue{D1,D2,D3,T}(data)\nThirdOrderTensorValue{D1,D2,D3,T1}(data::NTuple{L,T2}) where {D1,D2,D3,L,T1,T2} = ThirdOrderTensorValue{D1,D2,D3,T1}(NTuple{L,T1}(data))\nThirdOrderTensorValue{D1,D2,D3,T1,L}(data::NTuple{L,T2}) where {D1,D2,D3,L,T1,T2} = ThirdOrderTensorValue{D1,D2,D3,T1}(NTuple{L,T1}(data))\n\n# ThirdOrderTensorValue single Tuple argument constructor\n\nThirdOrderTensorValue(data::Tuple) = ThirdOrderTensorValue(promote(data...))\nThirdOrderTensorValue{D}(data::Tuple) where {D} = ThirdOrderTensorValue{D,D,D}(promote(data...))\nThirdOrderTensorValue{D1,D2,D3}(data::Tuple) where {D1,D2,D3} = ThirdOrderTensorValue{D1,D2,D3}(promote(data...))\nThirdOrderTensorValue{D1,D2,D3,T1}(data::Tuple) where {D1,D2,D3,T1} = ThirdOrderTensorValue{D1,D2,D3,T1}(NTuple{length(data),T1}(data))\nThirdOrderTensorValue{D1,D2,D3,T1,L}(data::Tuple) where {D1,D2,D3,T1,L} = ThirdOrderTensorValue{D1,D2,D3,T1}(NTuple{L,T1}(data))\n\n# ThirdOrderTensorValue Vararg constructor\n\nThirdOrderTensorValue(data...) = ThirdOrderTensorValue(data)\nThirdOrderTensorValue{D}(data...) where {D} = ThirdOrderTensorValue{D}(data)\nThirdOrderTensorValue{D1,D2,D3}(data...) where {D1,D2,D3} = ThirdOrderTensorValue{D1,D2,D3}(data)\nThirdOrderTensorValue{D1,D2,D3,T1}(data...) where {D1,D2,D3,T1} = ThirdOrderTensorValue{D1,D2,D3,T1}(data)\nThirdOrderTensorValue{D1,D2,D3,T1,L}(data...) where {D1,D2,D3,T1,L} = ThirdOrderTensorValue{D1,D2,D3,T1}(data)\n\n# ThirdOrderTensorValue single AbstractArray{3,T} argument constructor\n\nThirdOrderTensorValue(data::AbstractArray{T,3}) where {T} = ((D1,D2,D3)=size(data);L=length(data);ThirdOrderTensorValue{D1,D2,D3,T}(NTuple{L,T}(data)))\nThirdOrderTensorValue{D}(data::AbstractArray{T,3}) where {D,T} = (L=length(data);ThirdOrderTensorValue{D,D,D,T}(NTuple{L,T}(data)))\nThirdOrderTensorValue{D1,D2,D3}(data::AbstractArray{T,3}) where {D1,D2,D3,T} = (L=length(data);ThirdOrderTensorValue{D1,D2,D3,T}(NTuple{L,T}(data)))\nThirdOrderTensorValue{D1,D2,D3,T1}(data::AbstractArray{T2,3}) where {D1,D2,D3,T1,T2} = (L=length(data);ThirdOrderTensorValue{D1,D2,D3,T1}(NTuple{L,T1}(data)))\nThirdOrderTensorValue{D1,D2,D3,T1,L}(data::AbstractArray{T2,3}) where {D1,D2,D3,T1,T2,L} = ThirdOrderTensorValue{D1,D2,D3,T1}(NTuple{L,T1}(data))\n\n###############################################################\n# Conversions (ThirdOrderTensorValue)\n###############################################################\n\n# Direct conversion\nconvert(::Type{<:ThirdOrderTensorValue{D1,D2,D3,T}}, arg::AbstractArray) where {D1,D2,D3,T} = ThirdOrderTensorValue{D1,D2,D3,T}(arg)\nconvert(::Type{<:ThirdOrderTensorValue{D1,D2,D3,T}}, arg::Tuple) where {D1,D2,D3,T} = ThirdOrderTensorValue{D1,D2,D3,T}(arg)\n\n# Inverse conversion\nconvert(::Type{<:SMatrix{D1,D2,D3,T}}, arg::ThirdOrderTensorValue) where {D1,D2,D3,T} = SMatrix{D1,D2,D3,T}(Tuple(arg))\nconvert(::Type{<:MMatrix{D1,D2,D3,T}}, arg::ThirdOrderTensorValue) where {D1,D2,D3,T} = MMatrix{D1,D2,D3,T}(Tuple(arg))\nconvert(::Type{<:NTuple{L,T1}}, arg::ThirdOrderTensorValue) where {L,T1} = NTuple{L,T1}(Tuple(arg))\n\n# Internal conversion\nconvert(::Type{<:ThirdOrderTensorValue{D1,D2,D3,T}}, arg::ThirdOrderTensorValue{D1,D2,D3}) where {D1,D2,D3,T} = ThirdOrderTensorValue{D1,D2,D3,T}(Tuple(arg))\nconvert(::Type{<:ThirdOrderTensorValue{D1,D2,D3,T}}, arg::ThirdOrderTensorValue{D1,D2,D3,T}) where {D1,D2,D3,T} = arg\n\n# other\n\nchange_eltype(::Type{ThirdOrderTensorValue{D1,D2,D3,T1,L}},::Type{T2}) where {D1,D2,D3,T1,T2,L} = ThirdOrderTensorValue{D1,D2,D3,T2,L}\nchange_eltype(::T,::Type{T2}) where {T<:ThirdOrderTensorValue,T2} = change_eltype(T,T2)\n\nzero(::Type{<:ThirdOrderTensorValue{D1,D2,D3,T}}) where {D1,D2,D3,T} = ThirdOrderTensorValue{D1,D2,D3,T}(tfill(zero(T),Val{D1*D2*D3}()))\nzero(::ThirdOrderTensorValue{D1,D2,D3,T}) where {D1,D2,D3,T} = zero(ThirdOrderTensorValue{D1,D2,D3,T})\n\nMutable(::Type{<:ThirdOrderTensorValue{D1,D2,D3,T}}) where {D1,D2,D3,T} = MArray{Tuple{D1,D2,D3},T}\nMutable(::ThirdOrderTensorValue{D1,D2,D3,T}) where {D1,D2,D3,T} = Mutable(ThirdOrderTensorValue{D1,D2,D3,T})\nmutable(a::ThirdOrderTensorValue{D1,D2,D3}) where {D1,D2,D3} = MArray{Tuple{D1,D2,D3}}(a.data)\n\n###############################################################\n# Introspection (ThirdOrderTensorValue)\n###############################################################\n\neltype(::Type{<:ThirdOrderTensorValue{D1,D2,D3,T}}) where {D1,D2,D3,T} = T\neltype(::ThirdOrderTensorValue{D1,D2,D3,T}) where {D1,D2,D3,T} = eltype(ThirdOrderTensorValue{D1,D2,D3,T})\n\nsize(::Type{<:ThirdOrderTensorValue{D1,D2,D3}}) where {D1,D2,D3} = (D1,D2,D3)\nsize(::ThirdOrderTensorValue{D1,D2,D3}) where {D1,D2,D3} = size(ThirdOrderTensorValue{D1,D2,D3})\n\nlength(::Type{<:ThirdOrderTensorValue{D1,D2,D3}}) where {D1,D2,D3} = D1*D2*D3\nlength(::ThirdOrderTensorValue{D1,D2,D3}) where {D1,D2,D3} = length(ThirdOrderTensorValue{D1,D2,D3})\n\nnum_components(::Type{<:ThirdOrderTensorValue{D1,D2,D3}}) where {D1,D2,D3} = length(ThirdOrderTensorValue{D1,D2,D3})\nnum_components(::ThirdOrderTensorValue{D1,D2,D3}) where {D1,D2,D3} = num_components(ThirdOrderTensorValue{D1,D2,D3})\n\n", "meta": {"hexsha": "3180480a946acaaf5136d9a6a46295e629b0e438", "size": 6312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TensorValues/ThirdOrderTensorValueTypes.jl", "max_stars_repo_name": "Paulms/Gridap.jl", "max_stars_repo_head_hexsha": "962da3b03647a3017fb2684f88106eae49db9051", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TensorValues/ThirdOrderTensorValueTypes.jl", "max_issues_repo_name": "Paulms/Gridap.jl", "max_issues_repo_head_hexsha": "962da3b03647a3017fb2684f88106eae49db9051", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T08:20:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T08:20:09.000Z", "max_forks_repo_path": "src/TensorValues/ThirdOrderTensorValueTypes.jl", "max_forks_repo_name": "Paulms/Gridap.jl", "max_forks_repo_head_hexsha": "962da3b03647a3017fb2684f88106eae49db9051", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-10T06:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T07:54:42.000Z", "avg_line_length": 61.2815533981, "max_line_length": 158, "alphanum_fraction": 0.6939163498, "num_tokens": 2250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2472010434254796}} {"text": "module IdealGas\ninclude(\"Constants.jl\")\ninclude(\"Utils.jl\")\nusing LightXML\n\nabstract type ComponentDefinition end\nabstract type ThermoData end\n\nstruct Gasphase <: ComponentDefinition \n species::Array{String,1}\nend\n\nstruct NASAThermo <: ThermoData\n name::String\n phase::String\n composition::Dict{String,Int64}\n molWt::Float64\n ltl::Float64\n htl::Float64\n cmt::Float64\n ltp::Array{Float64,1}\n htp::Array{Float64,1}\nend\n\n#This array will be order as per ig.species\nstruct SpeciesThermoObj\n molwt::Array{Float64,1}\n thermo_all::Array{NASAThermo}\nend\nexport SpeciesThermoObj\n\n\n\"\"\"\n Tuple of element weights. This is used for the calculation of molecular weights\n\"\"\"\nelementWeight = ( H = 1.00794e-3, He = 4.002602e-3, Li = 6.941e-3, Be = 9.012182e-3, B = 1.811e-3,\n C = 12.011e-3, N = 14.00674e-3, O = 15.9994e-3, F = 18.9984032e-3, Ne = 20.1797e-3,\n Na = 22.98977e-3, Mg = 24.3050e-3, Al = 26.98154e-3, Si = 28.0855e-3, P = 30.97376e-3,\n S = 32.066e-3, Cl = 35.4527e-3, Ar = 39.948e-3, K = 39.0983e-3, Ca = 40.078e-3,\n Sc = 44.95591e-3, Ti = 47.88e-3, V = 50.9415e-3, Cr = 51.9961e-3, Mn = 54.9381e-3,\n Fe = 55.847e-3, Co = 58.9332e-3, Ni = 58.69e-3, Cu = 63.546e-3, Zn = 65.39e-3,\n Ga = 69.723e-3, Ge = 72.61e-3, As = 74.92159e-3, Se = 78.96e-3, Br = 79.904e-3,\n Kr = 83.80e-3, Rb = 85.4678e-3, Sr = 87.62e-3, Y = 88.90585e-3, Zr = 91.224e-3,\n Nb = 92.90638e-3, Mo = 95.94e-3, Tc = 97.9072e-3, Ru = 101.07e-3, Rh = 102.9055e-3,\n Pd = 106.42e-3, Ag = 107.8682e-3, Cd = 112.411e-3, In = 114.82e-3, Sn = 118.710e-3,\n Sb = 121.75e-3, Te = 127.6e-3, I = 126.90447e-3, Xe = 131.29e-3, Cs = 132.90543e-3,\n Ba = 137.327e-3, La = 138.9055e-3, Ce = 140.115e-3, Pr = 140.90765e-3, Nd = 144.24e-3,\n Pm = 144.9127e-3, Sm = 150.36e-3, Eu = 151.965e-3, Gd = 157.25e-3, Tb = 158.92534e-3,\n Dy = 162.50e-3, Ho = 164.93032e-3, Er = 167.26e-3, Tm = 168.93421e-3, Yb = 173.04e-3,\n Lu = 174.967e-3, Hf = 178.49e-3, Ta = 180.9479e-3, W = 183.85e-3, Re = 186.207e-3,\n Pt = 195.08e-3, Au = 196.96654e-3, Hg = 200.59e-3, Tl = 204.3833e-3, Pb = 207.2e-3,\n Bi = 208.98037e-3, Po = 208.9824e-3, At = 209.9871e-3, Rn = 222.0176e-3,\n Fr = 223.0197e-3, Ra = 226.0254e-3, Ac = 227.0279e-3, Th = 232.0381e-3,\n Pa = 231.03588e-3, U = 238.0508e-3, Np = 237.0482e-3, Pu = 244.0482e-3\n )\n\n\n\"\"\"\nget_element_weight(el)\n\nfunction to return the element weights\n# Usage:\n get_element_weight(el)\n- 'el::String' : Element name\n\"\"\"\nget_element_weight(el::String) = elementWeight[Symbol(titlecase(strip(el)))] \n\n\n\"\"\"\nFunction to create thermo object. The function reads the therm.dat file and \nparses the content based on the ideal gas object to create the thermo data object\nThe function returns SpeciesThermoObj\n# Usage:\n create_thermo() or\n create_thermo(file_path)\n- 'ig::Gasphase' : Gasphase object obtained using the call create_gasphase\n- 'file_path': relative path to the therm.dat file\n\"\"\"\nfunction create_thermo(species::Array{T,1}, thermo_file::AbstractString ) where T <: AbstractString\n #Create an array of thermo objects which stores the thermo data of all species\n species_thermo = Dict{String,NASAThermo}()\n molecular_weights_vector = Array{Float64,1}() \n \n open(thermo_file) do io\n lno = 0\n local species_name, phase, mol_wt,LT,HT,CT\n comp = Dict{String,Int64}()\n local poly_coeff = Array{Float64,1}()\n while !eof(io)\n data_string = readline(io) \n if length(data_string) != 0\n if SubString(data_string,1,3) == \"END\"\n break\n else\n sp = uppercase(strip(SubString(data_string,1,18)))\n if sp in species\n lno = 1\n species_name, phase,comp, mol_wt,LT,HT,CT = parase_thermo_species_data(data_string) \n lno += 1\n empty!(poly_coeff)\n elseif lno > 1 && lno < 5\n append!(poly_coeff,parse_thermo_polynomials(lno,data_string))\n lno += 1\n if lno > 4\n nasa_thermo = NASAThermo(species_name,phase,comp ,mol_wt,LT,HT,CT,poly_coeff[8:14],poly_coeff[1:7]) \n species_thermo[nasa_thermo.name] = nasa_thermo \n end\n end\n end\n end\n end\n end \n species_thermo_array = Array{NASAThermo,1}()\n for sp in species\n push!(species_thermo_array,species_thermo[sp])\n end\n for td in species_thermo_array\n push!(molecular_weights_vector,td.molWt)\n end\n \n return SpeciesThermoObj(molecular_weights_vector, species_thermo_array) \nend\n\n\"\"\"\nFunction for parsing the first line of thermo data.\n It returns the species name, phase, molecular weight, high \n temperature, low temperature and Common temperature limits\n Not for external calls\n# Usage:\n parase_thermo_species_data(data_string) \n\"\"\"\nfunction parase_thermo_species_data(data_string::AbstractString)\n species_name = uppercase(strip(SubString(data_string,1,18)))\n a1 = split(strip(SubString(data_string,25,29)))\n a2 = split(strip(SubString(data_string,30,34)))\n a3 = split(strip(SubString(data_string,35,39)))\n a4 = split(strip(SubString(data_string,40,44)))\n elements_data = (a1,a2,a3,a4)\n mol_wt::Float64 = 0\n composition = Dict{String,Int64}()\n for el in elements_data\n if !isempty(el)\n mol_wt += parse(Float64,el[2])*get_element_weight(String(el[1])) \n composition[String(el[1])] = parse(Int64,el[2])\n end\n end\n phase = String(SubString(data_string,45,45))\n if length(phase)==0\n throw(error(\"Phase not specified for species $spname\"))\n end\n LTs = String(SubString(data_string,46,57))\n if length(LTs) == 0\n throw(error(\"Low temperature limit not specified for species $spname\"))\n end\n HTs = String(SubString(data_string,58,67))\n if length(HTs) == 0\n throw(error(\"High temperature limit not specified for species $spname\"))\n end\n CTs = String(SubString(data_string,68,75))\n if length(CTs)==0\n throw(error(\"Common temperature limit not specified for species $spname\"))\n end\n LT = parse(Float64, LTs)\n HT = parse(Float64, HTs)\n CT = parse(Float64, CTs) \n return (species_name,phase, composition ,mol_wt,LT,HT,CT)\nend\n\n\n\"\"\"\nThis function will parse the polynomials\n Not for external calls\n\"\"\"\nfunction parse_thermo_polynomials(lno::Int64, thdata::AbstractString)\n poly_data = Array{Float64,1}()\n if lno == 2\n push!(poly_data,parse(Float64,String(SubString(thdata,1,15))))\n push!(poly_data,parse(Float64,String(SubString(thdata,16,30))))\n push!(poly_data,parse(Float64,String(SubString(thdata,31,45))))\n push!(poly_data,parse(Float64,String(SubString(thdata,46,60))))\n push!(poly_data,parse(Float64,String(SubString(thdata,61,75))))\n elseif lno == 3\n push!(poly_data,parse(Float64,String(SubString(thdata,1,15))))\n push!(poly_data,parse(Float64,String(SubString(thdata,16,30))))\n push!(poly_data,parse(Float64,String(SubString(thdata,31,45))))\n push!(poly_data,parse(Float64,String(SubString(thdata,46,60))))\n push!(poly_data,parse(Float64,String(SubString(thdata,61,75))))\n elseif lno == 4\n push!(poly_data,parse(Float64,String(SubString(thdata,1,15))))\n push!(poly_data,parse(Float64,String(SubString(thdata,16,30))))\n push!(poly_data,parse(Float64,String(SubString(thdata,31,45))))\n push!(poly_data,parse(Float64,String(SubString(thdata,46,60))))\n end\n return poly_data\nend\n\n\n\"\"\"\nCalculate the specific heat of pure species J/mol-K\n# Usage-1:\n cp(thermo,T) \n- 'thermo::NASAThermo': NASAThermo of the species\n- 'T::Float64': Temperature in K at which the property is required \n# Usage-2:\n cp(sp,T,thermo,ig)\n- 'sp::String' : species name\n- 'T::Float64' : Temperature K\n- 'thermo::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'ig::Gasphase ' : Gasphase object\n\"\"\"\nfunction cp(thermo::NASAThermo, T::Float64)\n TVec = [T^i for i in 0:4] \n T < thermo.cmt ? sum(thermo.ltp[1:5] .* TVec)*R : sum(thermo.htp[1:5] .* TVec)*R\nend\ncp(sp::String,T::Float64,thermoObj::SpeciesThermoObj,species_list::Array{String,1}) = cp(thermoObj.thermo_all[get_index(sp,species_list)],T)\n\n\n\n\"\"\"\nCalculates the enthalpy of pure species J/mol\n# Usage-1:\n H(thermo,T)\n- 'thermo::NASAThermo': NASAThermo of the species\n- 'T::Float64': Temperature in K at which the property is required \n# Usage-2:\n H(sp,T,thermo,ig)\n- 'sp::String' : species name\n- 'T::Float64' : Temperature K\n- 'thermo::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'ig::Gasphase ' : Gasphase object\n\"\"\"\nfunction H(thermo::NASAThermo, T::Float64)\n TVec = [1, T/2.0, T^2/3.0, T^3/4.0, T^4/5.0, 1.0/T] \n T < thermo.cmt ? sum(thermo.ltp[1:6] .* TVec)*R*T : sum(thermo.htp[1:6] .* TVec)*R*T\nend\nH(sp::String,T::Float64,thermoObj::SpeciesThermoObj,species_list::Array{String,1}) = H(thermoObj.thermo_all[get_index(sp,species_list)],T)\n\n\n\"\"\"\nCalculates the entropy of pure species J/mol-K\n# Usage-1:\n S(thermo,T)\n- 'thermo::NASAThermo': NASAThermo of the species\n- 'T::Float64': Temperature in K at which the property is required \n# Usage-2:\n S(sp,T,thermo,ig)\n- 'sp::String' : species name\n- 'T::Float64' : Temperature K\n- 'thermo::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'ig::Gasphase ' : Gasphase object\n\"\"\"\nfunction S(thermo::NASAThermo, T::Float64)\n TVec = [log(T), T, T^2/2.0, T^3/3.0, T^4/4.0] \n if T < thermo.cmt\n return (sum(thermo.ltp[1:5] .* TVec) + thermo.ltp[7])*R\n else\n return (sum(thermo.htp[1:5] .* TVec) + thermo.htp[7])*R\n end\nend\nS(sp::String,T::Float64,thermoObj::SpeciesThermoObj,species_list::Array{String,1}) = S(thermoObj.thermo_all[get_index(sp,species_list)],T)\n\n\n\"\"\"\nCalculates the specific heat of all species in J/mol-K\n# Usage\n cp_all(td,T)\n- 'thermoObj::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'T::Float64' : Temperature in K at which the property is rquired\n\"\"\"\nfunction cp_all(thermoObj::SpeciesThermoObj,T::Float64)\n return map(x->cp(x,T),thermoObj.thermo_all)\nend\n\n\n\"\"\"\nCalculates the enthalpy of all species in J/mol\n# Usage\n H_all(td,T)\n- 'thermoObj::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'T::Float64' : Temperature in K at which the property is rquired\n\"\"\"\nfunction H_all(thermoObj::SpeciesThermoObj,T::Float64)\n return map(x->H(x,T),thermoObj.thermo_all)\nend\n\n\n\"\"\"\nCalculates the entropy of all species in J/mol-K\n# Usage\n S_all(td,T)\n- 'thermoObj::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'T::Float64' : Temperature in K at which the property is rquired\n\"\"\"\nfunction S_all(thermoObj::SpeciesThermoObj,T::Float64)\n return map(x->S(x,T),thermoObj.thermo_all)\nend\n\n\"\"\"\nCalculates the enthalpy of a mixture J/mol\n# Usage\n Hmix(td,T,mlf)\n- 'thermoObj::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'T::Float64' : Temperature in K\n- 'mlf::Array{Float64,1}' : species mole fractions \n\"\"\"\nfunction Hmix(thermoObj::SpeciesThermoObj,T::Float64,mlf::Array{Float64,1}) \n all_species_h = H_all(thermoObj,T) \n return sum(all_species_h .* mlf) \nend\n\n\"\"\"\nCalculates the specific heat of a mixture in J/mol-K\n# Usage\n cpmix(td,T,mlf)\n- 'thermoObj::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'T::Float64' : Temperature in K\n- 'mlf::Array{Float64,1}' : species mole fractions \n\"\"\"\nfunction cpmix(thermoObj::SpeciesThermoObj,T::Float64,mlf::Array{Float64,1})\n all_species_cp = S_all(thermoObj,T)\n return sum(all_species_cp .* mlf)\nend\n\n\"\"\"\nCalculates the entropy of a muxture in J/mol-K\n# Usage\n Smix(thermoObj,T,p,mlf)\n- 'thermoObj::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'T::Float64' : Temperature in K \n- 'p::Float64' : total pressure Pa\n- 'mlf::Array{Float64,1} ': mole fractions\n\"\"\"\nfunction Smix(thermoObj::SpeciesThermoObj,T::Float64,p::Float64,mlf::Array{Float64,1})\n all_species_s = S_all(thermoObj,T)\n xp = mlf .* (p/p_std)\n #logterm = [x <= 0 ? 0 : log(x) for x in xp]\n logterm = collect(map(x->x <= 0 ? 0 : log(x) ,xp))\n return sum((all_species_s - (logterm .* R)) .* mlf)\nend\n\n\"\"\"\nCalculates the Gibbs free energy of a muxture in J/mol\n# Usage\n Gmix(thermoObj,T,p,mlf)\n- 'thermoObj::SpeciesThermoObj' : Structure of SpeciesThermoObj\n- 'T::Float64' : Temperature in K \n- 'p::Float64' : total pressure Pa\n- 'mlf::Array{Float64,1} ': mole fractions\n\"\"\"\nfunction Gmix(thermoObj::SpeciesThermoObj, T::Float64,p::Float64,mlf::Array{Float64,1})\n hmix = Hmix(thermoObj,T,mlf)\n smix = Smix(thermoObj,T,p,mlf)\n return hmix - T*smix\nend\n\n\n#end of module IdealGas\nend", "meta": {"hexsha": "36ab480623cbcc76b88c7229b8937b987e5595ca", "size": 13329, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IdealGas.jl", "max_stars_repo_name": "vinodjanardhanan/ReactionEngine.jl", "max_stars_repo_head_hexsha": "4526a68c550abdfd4f2546f358ab171d4c7c54ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IdealGas.jl", "max_issues_repo_name": "vinodjanardhanan/ReactionEngine.jl", "max_issues_repo_head_hexsha": "4526a68c550abdfd4f2546f358ab171d4c7c54ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IdealGas.jl", "max_forks_repo_name": "vinodjanardhanan/ReactionEngine.jl", "max_forks_repo_head_hexsha": "4526a68c550abdfd4f2546f358ab171d4c7c54ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2318435754, "max_line_length": 155, "alphanum_fraction": 0.6310300848, "num_tokens": 4449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24720104342547958}} {"text": "function get_generator_data(data::OPFData; use_gpu=false)\n ngen = length(data.generators)\n\n if use_gpu\n pgmin = CuArray{Float64}(undef, ngen)\n pgmax = CuArray{Float64}(undef, ngen)\n qgmin = CuArray{Float64}(undef, ngen)\n qgmax = CuArray{Float64}(undef, ngen)\n c2 = CuArray{Float64}(undef, ngen)\n c1 = CuArray{Float64}(undef, ngen)\n c0 = CuArray{Float64}(undef, ngen)\n else\n pgmin = Array{Float64}(undef, ngen)\n pgmax = Array{Float64}(undef, ngen)\n qgmin = Array{Float64}(undef, ngen)\n qgmax = Array{Float64}(undef, ngen)\n c2 = Array{Float64}(undef, ngen)\n c1 = Array{Float64}(undef, ngen)\n c0 = Array{Float64}(undef, ngen)\n end\n\n Pmin = Float64[data.generators[g].Pmin for g in 1:ngen]\n Pmax = Float64[data.generators[g].Pmax for g in 1:ngen]\n Qmin = Float64[data.generators[g].Qmin for g in 1:ngen]\n Qmax = Float64[data.generators[g].Qmax for g in 1:ngen]\n coeff0 = Float64[data.generators[g].coeff[3] for g in 1:ngen]\n coeff1 = Float64[data.generators[g].coeff[2] for g in 1:ngen]\n coeff2 = Float64[data.generators[g].coeff[1] for g in 1:ngen]\n copyto!(pgmin, Pmin)\n copyto!(pgmax, Pmax)\n copyto!(qgmin, Qmin)\n copyto!(qgmax, Qmax)\n copyto!(c0, coeff0)\n copyto!(c1, coeff1)\n copyto!(c2, coeff2)\n\n return pgmin,pgmax,qgmin,qgmax,c2,c1,c0\nend\n\nfunction get_bus_data(data::OPFData; use_gpu=false)\n nbus = length(data.buses)\n\n FrIdx = [l for b=1:nbus for l in data.FromLines[b]]\n ToIdx = [l for b=1:nbus for l in data.ToLines[b]]\n GenIdx = [g for b=1:nbus for g in data.BusGenerators[b]]\n FrStart = accumulate(+, vcat([1], [length(data.FromLines[b]) for b=1:nbus]))\n ToStart = accumulate(+, vcat([1], [length(data.ToLines[b]) for b=1:nbus]))\n GenStart = accumulate(+, vcat([1], [length(data.BusGenerators[b]) for b=1:nbus]))\n\n Pd = Float64[data.buses[i].Pd for i=1:nbus]\n Qd = Float64[data.buses[i].Qd for i=1:nbus]\n\n if use_gpu\n cuFrIdx = CuArray{Int}(undef, length(FrIdx))\n cuToIdx = CuArray{Int}(undef, length(ToIdx))\n cuGenIdx = CuArray{Int}(undef, length(GenIdx))\n cuFrStart = CuArray{Int}(undef, length(FrStart))\n cuToStart = CuArray{Int}(undef, length(ToStart))\n cuGenStart = CuArray{Int}(undef, length(GenStart))\n cuPd = CuArray{Float64}(undef, nbus)\n cuQd = CuArray{Float64}(undef, nbus)\n\n copyto!(cuFrIdx, FrIdx)\n copyto!(cuToIdx, ToIdx)\n copyto!(cuGenIdx, GenIdx)\n copyto!(cuFrStart, FrStart)\n copyto!(cuToStart, ToStart)\n copyto!(cuGenStart, GenStart)\n copyto!(cuPd, Pd)\n copyto!(cuQd, Qd)\n\n return cuFrStart,cuFrIdx,cuToStart,cuToIdx,cuGenStart,cuGenIdx,cuPd,cuQd\n else\n return FrStart,FrIdx,ToStart,ToIdx,GenStart,GenIdx,Pd,Qd\n end\nend\n\nfunction get_branch_data(data::OPFData; use_gpu=false)\n buses = data.buses\n lines = data.lines\n BusIdx = data.BusIdx\n nline = length(data.lines)\n ybus = Ybus{Array{Float64}}(computeAdmitances(data.lines, data.buses, data.baseMVA; VI=Array{Int}, VD=Array{Float64})...)\n frBound = [ x for l=1:nline for x in (buses[BusIdx[lines[l].from]].Vmin^2, buses[BusIdx[lines[l].from]].Vmax^2) ]\n toBound = [ x for l=1:nline for x in (buses[BusIdx[lines[l].to]].Vmin^2, buses[BusIdx[lines[l].to]].Vmax^2) ]\n\n if use_gpu\n cuYshR = CuArray{Float64}(undef, length(ybus.YshR))\n cuYshI = CuArray{Float64}(undef, length(ybus.YshI))\n cuYffR = CuArray{Float64}(undef, nline)\n cuYffI = CuArray{Float64}(undef, nline)\n cuYftR = CuArray{Float64}(undef, nline)\n cuYftI = CuArray{Float64}(undef, nline)\n cuYttR = CuArray{Float64}(undef, nline)\n cuYttI = CuArray{Float64}(undef, nline)\n cuYtfR = CuArray{Float64}(undef, nline)\n cuYtfI = CuArray{Float64}(undef, nline)\n cuFrBound = CuArray{Float64}(undef, 2*nline)\n cuToBound = CuArray{Float64}(undef, 2*nline)\n copyto!(cuYshR, ybus.YshR)\n copyto!(cuYshI, ybus.YshI)\n copyto!(cuYffR, ybus.YffR)\n copyto!(cuYffI, ybus.YffI)\n copyto!(cuYftR, ybus.YftR)\n copyto!(cuYftI, ybus.YftI)\n copyto!(cuYttR, ybus.YttR)\n copyto!(cuYttI, ybus.YttI)\n copyto!(cuYtfR, ybus.YtfR)\n copyto!(cuYtfI, ybus.YtfI)\n copyto!(cuFrBound, frBound)\n copyto!(cuToBound, toBound)\n\n return cuYshR, cuYshI, cuYffR, cuYffI, cuYftR, cuYftI,\n cuYttR, cuYttI, cuYtfR, cuYtfI, cuFrBound, cuToBound\n else\n return ybus.YshR, ybus.YshI, ybus.YffR, ybus.YffI, ybus.YftR, ybus.YftI,\n ybus.YttR, ybus.YttI, ybus.YtfR, ybus.YtfI, frBound, toBound\n end\nend\n\nfunction init_solution!(env::AdmmEnv, sol::SolutionOneLevel, ybus::Ybus, rho_pq, rho_va)\n data, model = env.data, env.model\n\n lines = data.lines\n buses = data.buses\n BusIdx = data.BusIdx\n ngen = length(data.generators)\n nline = length(data.lines)\n\n YffR = ybus.YffR; YffI = ybus.YffI\n YttR = ybus.YttR; YttI = ybus.YttI\n YftR = ybus.YftR; YftI = ybus.YftI\n YtfR = ybus.YtfR; YtfI = ybus.YtfI\n\n for g=1:ngen\n pg_idx = model.gen_mod.gen_start + 2*(g-1)\n CUDA.@allowscalar sol.v_curr[pg_idx] = 0.5*(data.generators[g].Pmin + data.generators[g].Pmax)\n CUDA.@allowscalar sol.v_curr[pg_idx+1] = 0.5*(data.generators[g].Qmin + data.generators[g].Qmax)\n end\n\n sol.rho .= rho_pq\n fill!(sol.u_curr, 0.0)\n fill!(sol.v_curr, 0.0)\n\n for l=1:nline\n wij0 = (buses[BusIdx[lines[l].from]].Vmax^2 + buses[BusIdx[lines[l].from]].Vmin^2) / 2\n wji0 = (buses[BusIdx[lines[l].to]].Vmax^2 + buses[BusIdx[lines[l].to]].Vmin^2) / 2\n wR0 = sqrt(wij0 * wji0)\n\n pij_idx = model.line_start + 8*(l-1)\n CUDA.@allowscalar sol.u_curr[pij_idx] = YffR[l] * wij0 + YftR[l] * wR0\n CUDA.@allowscalar sol.u_curr[pij_idx+1] = -YffI[l] * wij0 - YftI[l] * wR0\n CUDA.@allowscalar sol.u_curr[pij_idx+2] = YttR[l] * wji0 + YtfR[l] * wR0\n CUDA.@allowscalar sol.u_curr[pij_idx+3] = -YttI[l] * wji0 - YtfI[l] * wR0\n #=\n u_curr[pij_idx+4] = wij0\n u_curr[pij_idx+5] = wji0\n u_curr[pij_idx+6] = 0.0\n u_curr[pij_idx+7] = 0.0\n =#\n # wRIij[2*(l-1)+1] = wR0\n # wRIij[2*l] = 0.0\n\n CUDA.@allowscalar sol.v_curr[pij_idx+4] = wij0\n CUDA.@allowscalar sol.v_curr[pij_idx+5] = wji0\n CUDA.@allowscalar sol.v_curr[pij_idx+6] = 0.0\n CUDA.@allowscalar sol.v_curr[pij_idx+7] = 0.0\n\n sol.rho[pij_idx+4:pij_idx+7] .= rho_va\n end\n\n sol.l_curr .= 0\n return\nend\n\nfunction copy_data_kernel(n::Int, dest::CuDeviceArray{Float64,1}, src::CuDeviceArray{Float64,1})\n tx = threadIdx().x + (blockDim().x * (blockIdx().x - 1))\n\n if tx <= n\n dest[tx] = src[tx]\n end\n return\nend\n\nfunction update_multiplier_kernel(n::Int, l_curr::CuDeviceArray{Float64,1},\n u_curr::CuDeviceArray{Float64,1},\n v_curr::CuDeviceArray{Float64,1},\n rho::CuDeviceArray{Float64,1})\n tx = threadIdx().x + (blockDim().x * (blockIdx().x - 1))\n\n if tx <= n\n l_curr[tx] += rho[tx] * (u_curr[tx] - v_curr[tx])\n end\n return\nend\n\nfunction primal_residual_kernel(n::Int, rp::CuDeviceArray{Float64,1},\n u_curr::CuDeviceArray{Float64,1},\n v_curr::CuDeviceArray{Float64,1})\n tx = threadIdx().x + (blockDim().x * (blockIdx().x - 1))\n\n if tx <= n\n rp[tx] = u_curr[tx] - v_curr[tx]\n end\n\n return\nend\n\nfunction dual_residual_kernel(n::Int, rd::CuDeviceArray{Float64,1},\n v_prev::CuDeviceArray{Float64,1},\n v_curr::CuDeviceArray{Float64,1},\n rho::CuDeviceArray{Float64,1})\n tx = threadIdx().x + (blockDim().x * (blockIdx().x - 1))\n\n if tx <= n\n rd[tx] = -rho[tx] * (v_curr[tx] - v_prev[tx])\n end\n\n return\nend\n\nfunction check_linelimit_violation(data::OPFData, u)\n lines = data.lines\n nline = length(data.lines)\n line_start = 2*length(data.generators) + 1\n\n rateA_nviols = 0\n rateA_maxviol = 0.0\n rateC_nviols = 0\n rateC_maxviol = 0.0\n\n for l=1:nline\n pij_idx = line_start + 8*(l-1)\n ij_val = 0.0\n ji_val = 0.0\n CUDA.@allowscalar ij_val = u[pij_idx]^2 + u[pij_idx+1]^2\n CUDA.@allowscalar ji_val = u[pij_idx+2]^2 + u[pij_idx+3]^2\n\n limit = (lines[l].rateA / data.baseMVA)^2\n if limit > 0 && limit < 1e10\n if ij_val > limit || ji_val > limit\n rateA_nviols += 1\n rateA_maxviol = max(rateA_maxviol, max(ij_val - limit, ji_val - limit))\n end\n end\n\n limit = (lines[l].rateC / data.baseMVA)^2\n if limit > 0 && limit < 1e10\n if ij_val > limit || ji_val > limit\n rateC_nviols += 1\n rateC_maxviol = max(rateC_maxviol, max(ij_val - limit, ji_val - limit))\n end\n end\n end\n rateA_maxviol = sqrt(rateA_maxviol)\n rateC_maxviol = sqrt(rateC_maxviol)\n\n return rateA_nviols, rateA_maxviol, rateC_nviols, rateC_maxviol\nend\n\n\"\"\"\n admm_restart!\n\nThis function restarts the ADMM with a given `env::AdmmEnv` containing solutions and all the other parameters.\n\"\"\"\nadmm_restart!(env::AdmmEnv; options...) = admm_solve!(env, env.solution; options...)\n\nfunction admm_solve!(env::AdmmEnv, sol::SolutionOneLevel; iterlim=800, scale=1e-4)\n if env.use_gpu\n CUDA.device!(env.gpu_no)\n end\n\n data, par, mod = env.data, env.params, env.model\n\n shift_lines = 0\n shmem_size = sizeof(Float64)*(14*mod.n+3*mod.n^2) + sizeof(Int)*(4*mod.n)\n\n nblk_gen = div(mod.gen_mod.ngen, 32, RoundUp)\n nblk_br = mod.nline\n nblk_bus = div(mod.nbus, 32, RoundUp)\n\n it = 0\n time_gen = time_br = time_bus = 0.0\n\n @time begin\n while it < iterlim\n it += 1\n\n if !env.use_gpu\n sol.u_prev .= sol.u_curr\n sol.v_prev .= sol.v_curr\n sol.l_prev .= sol.l_curr\n\n tcpu = generator_kernel(mod.gen_mod, data.baseMVA, sol.u_curr, sol.v_curr, sol.l_curr, sol.rho)\n time_gen += tcpu.time\n\n if env.use_polar\n tcpu = @timed auglag_it, tron_it = polar_kernel_cpu(mod.n, mod.nline, mod.line_start, scale,\n sol.u_curr, sol.v_curr, sol.l_curr, sol.rho,\n shift_lines, env.membuf, mod.YffR, mod.YffI, mod.YftR, mod.YftI,\n mod.YttR, mod.YttI, mod.YtfR, mod.YtfI, mod.FrBound, mod.ToBound)\n else\n tcpu = @timed auglag_it, tron_it = auglag_kernel_cpu(mod.n, mod.nline, it, par.max_auglag, mod.line_start, par.mu_max,\n sol.u_curr, sol.v_curr, sol.l_curr, sol.rho,\n shift_lines, env.membuf, mod.YffR, mod.YffI, mod.YftR, mod.YftI,\n mod.YttR, mod.YttI, mod.YtfR, mod.YtfI, mod.FrBound, mod.ToBound)\n end\n time_br += tcpu.time\n\n tcpu = @timed bus_kernel_cpu(data.baseMVA, mod.nbus, mod.gen_mod.gen_start, mod.line_start,\n mod.FrStart, mod.FrIdx, mod.ToStart, mod.ToIdx, mod.GenStart,\n mod.GenIdx, mod.Pd, mod.Qd, sol.u_curr, sol.v_curr, sol.l_curr, sol.rho, mod.YshR, mod.YshI)\n time_bus += tcpu.time\n\n sol.l_curr .+= sol.rho .* (sol.u_curr .- sol.v_curr)\n sol.rd .= -sol.rho .* (sol.v_curr .- sol.v_prev)\n sol.rp .= sol.u_curr .- sol.v_curr\n #sol.rp_old .= sol.u_prev .- sol.v_prev\n\n primres = norm(sol.rp)\n dualres = norm(sol.rd)\n\n eps_pri = sqrt(length(sol.l_curr))*par.ABSTOL + par.RELTOL*max(norm(sol.u_curr), norm(-sol.v_curr))\n eps_dual = sqrt(length(sol.u_curr))*par.ABSTOL + par.RELTOL*norm(sol.l_curr)\n\n (par.verbose > 0) && @printf(\"[CPU] %10d %.6e %.6e %.6e %.6e %6.2f %6.2f\\n\",\n it, primres, dualres, eps_pri, eps_dual, auglag_it, tron_it)\n\n if primres <= eps_pri && dualres <= eps_dual\n break\n end\n else\n @cuda threads=64 blocks=(div(mod.nvar-1, 64)+1) copy_data_kernel(mod.nvar, sol.u_prev, sol.u_curr)\n @cuda threads=64 blocks=(div(mod.nvar-1, 64)+1) copy_data_kernel(mod.nvar, sol.v_prev, sol.v_curr)\n @cuda threads=64 blocks=(div(mod.nvar-1, 64)+1) copy_data_kernel(mod.nvar, sol.l_prev, sol.l_curr)\n CUDA.synchronize()\n\n tgpu = generator_kernel(mod.gen_mod, data.baseMVA, sol.u_curr, sol.v_curr, sol.l_curr, sol.rho)\n\n time_gen += tgpu.time\n if env.use_polar\n tgpu = CUDA.@timed @cuda threads=32 blocks=nblk_br shmem=shmem_size polar_kernel(mod.n, mod.nline, mod.line_start, scale,\n sol.u_curr, sol.v_curr, sol.l_curr, sol.rho,\n shift_lines, env.membuf, mod.YffR, mod.YffI, mod.YftR, mod.YftI,\n mod.YttR, mod.YttI, mod.YtfR, mod.YtfI, mod.FrBound, mod.ToBound)\n else\n tgpu = CUDA.@timed @cuda threads=32 blocks=nblk_br shmem=shmem_size auglag_kernel(mod.n, it, par.max_auglag, mod.line_start, scale, par.mu_max,\n sol.u_curr, sol.v_curr, sol.l_curr, sol.rho,\n shift_lines, env.membuf, mod.YffR, mod.YffI, mod.YftR, mod.YftI,\n mod.YttR, mod.YttI, mod.YtfR, mod.YtfI, mod.FrBound, mod.ToBound)\n end\n time_br += tgpu.time\n tgpu = CUDA.@timed @cuda threads=32 blocks=nblk_bus bus_kernel(data.baseMVA, mod.nbus, mod.gen_mod.gen_start, mod.line_start,\n mod.FrStart, mod.FrIdx, mod.ToStart, mod.ToIdx, mod.GenStart,\n mod.GenIdx, mod.Pd, mod.Qd, sol.u_curr, sol.v_curr, sol.l_curr,\n sol.rho, mod.YshR, mod.YshI)\n time_bus += tgpu.time\n\n @cuda threads=64 blocks=(div(mod.nvar-1, 64)+1) update_multiplier_kernel(mod.nvar, sol.l_curr, sol.u_curr, sol.v_curr, sol.rho)\n @cuda threads=64 blocks=(div(mod.nvar-1, 64)+1) primal_residual_kernel(mod.nvar, sol.rp, sol.u_curr, sol.v_curr)\n @cuda threads=64 blocks=(div(mod.nvar-1, 64)+1) dual_residual_kernel(mod.nvar, sol.rd, sol.v_prev, sol.v_curr, sol.rho)\n CUDA.synchronize()\n\n gpu_primres = CUDA.norm(sol.rp)\n gpu_dualres = CUDA.norm(sol.rd)\n\n gpu_eps_pri = sqrt(length(sol.l_curr))*par.ABSTOL + par.RELTOL*max(CUDA.norm(sol.u_curr), CUDA.norm(sol.v_curr))\n gpu_eps_dual = sqrt(length(sol.u_curr))*par.ABSTOL + par.RELTOL*CUDA.norm(sol.l_curr)\n\n (par.verbose > 0) && @printf(\"[GPU] %10d %.6e %.6e %.6e %.6e\\n\", it, gpu_primres, gpu_dualres, gpu_eps_pri, gpu_eps_dual)\n\n if gpu_primres <= gpu_eps_pri && gpu_dualres <= gpu_eps_dual\n break\n end\n end\n end\n end\n\n u_curr = zeros(mod.nvar)\n copyto!(u_curr, sol.u_curr)\n objval = sum(data.generators[g].coeff[data.generators[g].n-2]*(data.baseMVA*u_curr[mod.gen_mod.gen_start+2*(g-1)])^2 +\n data.generators[g].coeff[data.generators[g].n-1]*(data.baseMVA*u_curr[mod.gen_mod.gen_start+2*(g-1)]) +\n data.generators[g].coeff[data.generators[g].n]\n for g in 1:mod.gen_mod.ngen)::Float64\n sol.objval = objval\n\n if it < iterlim\n sol.status = HAS_CONVERGED\n else\n sol.status = MAXIMUM_ITERATIONS\n end\n\n if par.verbose > 0\n rateA_nviols, rateA_maxviol, rateC_nviols, rateC_maxviol = check_linelimit_violation(data, u_curr)\n @printf(\" ** Line limit violations\\n\")\n @printf(\"RateA number of violations = %d (%d)\\n\", rateA_nviols, mod.nline)\n @printf(\"RateA maximum violation = %.2f\\n\", rateA_maxviol)\n @printf(\"RateC number of violations = %d (%d)\\n\", rateC_nviols, mod.nline)\n @printf(\"RateC maximum violation = %.2f\\n\", rateC_maxviol)\n\n @printf(\" ** Time\\n\")\n @printf(\"Generator = %.2f\\n\", time_gen)\n @printf(\"Branch = %.2f\\n\", time_br)\n @printf(\"Bus = %.2f\\n\", time_bus)\n @printf(\"Total = %.2f\\n\", time_gen + time_br + time_bus)\n\n @printf(\"Objective value = %.6e\\n\", objval)\n end\n return\nend\n\nfunction admm_rect_gpu(case::String; iterlim=800, rho_pq=400.0, rho_va=40000.0, scale=1e-4,\n use_gpu=false, use_polar=true, gpu_no=0, verbose=1)\n env = AdmmEnv(case, use_gpu, rho_pq, rho_va; use_polar=use_polar, gpu_no=gpu_no, verbose=verbose,)\n admm_restart!(env, iterlim=iterlim, scale=scale)\n return env\nend\n\n# TODO: This needs revised to use AdmmEnv.\nfunction admm_rect_gpu_mpi(\n case::String;\n iterlim=800, rho_pq=400.0, rho_va=40000.0, scale=1e-4, use_gpu=false, use_polar=true, gpu_no=1,\n comm::MPI.Comm=MPI.COMM_WORLD,\n)\n data = opf_loaddata(case)\n\n ngen = length(data.generators)\n nline = length(data.lines)\n nbus = length(data.buses)\n nvar = 2*ngen + 8*nline\n if use_gpu\n @assert MPI.has_cuda()\n end\n\n # MPI settings\n root = 0\n is_master = MPI.Comm_rank(comm) == root\n n_processes = MPI.Comm_size(comm)\n nlines_local = div(nline, n_processes, RoundUp)\n nlines_padded = n_processes * nlines_local\n\n nvar_padded = 2*ngen + 8 * nlines_padded\n\n baseMVA = data.baseMVA\n n = (use_polar == true) ? 4 : 10\n mu_max = 1e8\n rho_max = 1e6\n rho_min_pq = 5.0\n rho_min_w = 5.0\n eps_rp = 1e-4\n eps_rp_min = 1e-5\n rt_inc = 2.0\n rt_dec = 2.0\n eta = 0.99\n Kf = 100\n Kf_mean = 10\n\n if use_gpu\n CUDA.device!(MPI.Comm_rank(comm) % CUDA.ndevices())\n end\n\n ybus = Ybus{Array{Float64}}(computeAdmitances(data.lines, data.buses, data.baseMVA; VI=Array{Int}, VD=Array{Float64})...)\n\n pgmin, pgmax, qgmin, qgmax, c2, c1, c0 = get_generator_data(data)\n YshR, YshI, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI, FrBound, ToBound = get_branch_data(data)\n FrStart, FrIdx, ToStart, ToIdx, GenStart, GenIdx, Pd, Qd = get_bus_data(data)\n\n cu_pgmin, cu_pgmax, cu_qgmin, cu_qgmax, cu_c2, cu_c1, cu_c0 = get_generator_data(data; use_gpu=use_gpu)\n cuYshR, cuYshI, cuYffR, cuYffI, cuYftR, cuYftI, cuYttR, cuYttI, cuYtfR, cuYtfI, cuFrBound, cuToBound = get_branch_data(data; use_gpu=use_gpu)\n cu_FrStart, cu_FrIdx, cu_ToStart, cu_ToIdx, cu_GenStart, cu_GenIdx, cu_Pd, cu_Qd = get_bus_data(data; use_gpu=use_gpu)\n\n gen_start = 1\n line_start = 2*ngen + 1\n\n # Allocations\n u_curr = zeros(nvar_padded)\n v_curr = zeros(nvar_padded)\n l_curr = zeros(nvar_padded)\n u_prev = zeros(nvar_padded)\n v_prev = zeros(nvar_padded)\n l_prev = zeros(nvar_padded)\n rho = zeros(nvar_padded)\n rd = zeros(nvar_padded)\n rp = zeros(nvar_padded)\n rp_old = zeros(nvar_padded)\n rp_k0 = zeros(nvar_padded)\n param = zeros(31, nlines_padded)\n wRIij = zeros(2*nline)\n\n init_values(data, ybus, gen_start, line_start,\n rho_pq, rho_va, u_curr, v_curr, l_curr, rho, wRIij)\n\n\n if use_gpu\n cu_u_curr = CuArray{Float64}(undef, nvar_padded)\n cu_v_curr = CuArray{Float64}(undef, nvar_padded)\n cu_l_curr = CuArray{Float64}(undef, nvar_padded)\n cu_u_prev = CuArray{Float64}(undef, nvar_padded)\n cu_v_prev = CuArray{Float64}(undef, nvar_padded)\n cu_l_prev = CuArray{Float64}(undef, nvar_padded)\n cu_rho = CuArray{Float64}(undef, nvar_padded)\n cu_rd = CuArray{Float64}(undef, nvar_padded)\n cu_rp = CuArray{Float64}(undef, nvar_padded)\n cu_rp_old = CuArray{Float64}(undef, nvar_padded)\n cu_rp_k0 = CuArray{Float64}(undef, nvar_padded)\n cuParam = CuArray{Float64}(undef, (31, nlines_padded))\n cuWRIij = CuArray{Float64}(undef, 2*nline)\n\n copyto!(cu_u_curr, u_curr)\n copyto!(cu_v_curr, v_curr)\n copyto!(cu_l_curr, l_curr)\n copyto!(cu_rho, rho)\n copyto!(cuParam, param)\n copyto!(cuWRIij, wRIij)\n end\n\n # MPI: Global info\n if use_gpu\n u_lines_root = @view cu_u_curr[line_start:end]\n l_lines_root = @view cu_l_curr[line_start:end]\n v_lines_root = @view cu_v_curr[line_start:end]\n rho_lines_root = cu_rho[line_start:end]\n else\n u_lines_root = @view u_curr[line_start:end]\n l_lines_root = @view l_curr[line_start:end]\n v_lines_root = @view v_curr[line_start:end]\n rho_lines_root = @view rho[line_start:end]\n end\n # MPI: Local info\n # We need only to transfer info about lines\n if use_gpu\n u_local = CUDA.zeros(Float64, 8 * nlines_local)\n v_local = CUDA.zeros(Float64, 8 * nlines_local)\n l_local = CUDA.zeros(Float64, 8 * nlines_local)\n rho_local = CUDA.zeros(Float64, 8 * nlines_local)\n else\n u_local = zeros(8 * nlines_local)\n v_local = zeros(8 * nlines_local)\n l_local = zeros(8 * nlines_local)\n rho_local = zeros(8 * nlines_local)\n end\n\n MPI.Scatter!(u_lines_root, u_local, root, comm)\n MPI.Scatter!(rho_lines_root, rho_local, root, comm)\n\n max_auglag = 50\n\n nblk_gen = div(ngen, 32, RoundUp)\n nblk_br = nline\n nblk_br_local = nlines_local\n nblk_bus = div(nbus, 32, RoundUp)\n\n ABSTOL = 1e-6\n RELTOL = 1e-5\n\n it = 0\n time_gen = time_br = time_bus = 0\n time_br_scatter = time_br_gather = 0\n\n h_u_curr = zeros(nvar)\n h_param = zeros(31, nline)\n h_wRIij = zeros(2*nline)\n\n shift_lines = MPI.Comm_rank(comm) * nlines_local\n # GPU settings\n shmem_size = sizeof(Float64)*(14*n+3*n^2) + sizeof(Int)*(4*n)\n\n while it < iterlim\n it += 1\n\n # CPU code\n if !use_gpu\n\n if is_master\n u_prev .= u_curr\n v_prev .= v_curr\n l_prev .= l_curr\n tcpu = @timed generator_kernel_cpu(baseMVA, ngen, gen_start, u_curr, v_curr, l_curr, rho,\n pgmin, pgmax, qgmin, qgmax, c2, c1)\n time_gen += tcpu.time\n end\n\n # MPI routines to be implemented:\n # - Broadcast cu_v_curr and cu_l_curr to GPUs.\n # - Collect cu_u_curr.\n # - div(nblk_br / number of GPUs, RoundUp)\n # scatter / gather\n\n tcpu_mpi = @timed begin\n MPI.Scatter!(v_lines_root, v_local, root, comm)\n MPI.Scatter!(l_lines_root, l_local, root, comm)\n end\n time_br_scatter += tcpu_mpi.time\n\n nlines_actual = min(nlines_local, nline - shift_lines)\n tcpu = @timed auglag_it, tron_it = polar_kernel_cpu(n, nlines_actual, 1, scale,\n u_local, v_local, l_local, rho_local,\n shift_lines, param, YffR, YffI, YftR, YftI,\n YttR, YttI, YtfR, YtfI, FrBound, ToBound)\n\n time_br += tcpu.time\n tcpu_mpi = @timed MPI.Gather!(u_local, u_lines_root, root, comm)\n time_br_gather += tcpu_mpi.time\n\n if is_master\n tcpu = @timed bus_kernel_cpu(baseMVA, nbus, gen_start, line_start,\n FrStart, FrIdx, ToStart, ToIdx, GenStart,\n GenIdx, Pd, Qd, u_curr, v_curr, l_curr, rho, YshR, YshI)\n time_bus += tcpu.time\n\n l_curr .+= rho .* (u_curr .- v_curr)\n rd .= -rho .* (v_curr .- v_prev)\n rp .= u_curr .- v_curr\n #rp_old .= u_prev .- v_prev\n\n primres = norm(rp)\n dualres = norm(rd)\n\n eps_pri = sqrt(length(l_curr))*ABSTOL + RELTOL*max(norm(u_curr), norm(-v_curr))\n eps_dual = sqrt(length(u_curr))*ABSTOL + RELTOL*norm(l_curr)\n\n @printf(\"[CPU] %10d %.6e %.6e %.6e %.6e %6.2f %6.2f\\n\",\n it, primres, dualres, eps_pri, eps_dual, auglag_it, tron_it)\n end\n # GPU code\n else\n if is_master\n @cuda threads=64 blocks=(div(nvar-1, 64)+1) copy_data_kernel(nvar, cu_u_prev, cu_u_curr)\n @cuda threads=64 blocks=(div(nvar-1, 64)+1) copy_data_kernel(nvar, cu_v_prev, cu_v_curr)\n @cuda threads=64 blocks=(div(nvar-1, 64)+1) copy_data_kernel(nvar, cu_l_prev, cu_l_curr)\n CUDA.synchronize()\n\n tgpu = CUDA.@timed @cuda threads=32 blocks=nblk_gen generator_kernel(baseMVA, ngen, gen_start,\n cu_u_curr, cu_v_curr, cu_l_curr, cu_rho,\n cu_pgmin, cu_pgmax, cu_qgmin, cu_qgmax, cu_c2, cu_c1)\n\n time_gen += tgpu.time\n end\n\n # - Broadcast cu_v_curr and cu_l_curr to GPUs.\n tgpu_mpi = @timed begin\n MPI.Scatter!(v_lines_root, v_local, root, comm)\n MPI.Scatter!(l_lines_root, l_local, root, comm)\n end\n time_br_scatter += tgpu_mpi.time\n\n # - div(nblk_br / number of GPUs, RoundUp)\n nblk_br_actual = min(nblk_br_local, nline - shift_lines)\n tgpu = CUDA.@timed @cuda threads=32 blocks=nblk_br_actual shmem=shmem_size polar_kernel(n, nline, 1, scale,\n u_local, v_local, l_local, rho_local,\n shift_lines, cuParam, cuYffR, cuYffI, cuYftR, cuYftI,\n cuYttR, cuYttI, cuYtfR, cuYtfI, cuFrBound, cuToBound\n )\n time_br += tgpu.time\n\n # - Collect cu_u_curr.\n tgpu_mpi = @timed MPI.Gather!(u_local, u_lines_root, root, comm)\n time_br_gather += tgpu_mpi.time\n\n if is_master\n tgpu = CUDA.@timed @cuda threads=32 blocks=nblk_bus bus_kernel(baseMVA, nbus, gen_start, line_start,\n cu_FrStart, cu_FrIdx, cu_ToStart, cu_ToIdx, cu_GenStart,\n cu_GenIdx, cu_Pd, cu_Qd, cu_u_curr, cu_v_curr, cu_l_curr,\n cu_rho, cuYshR, cuYshI)\n time_bus += tgpu.time\n @cuda threads=64 blocks=(div(nvar-1, 64)+1) update_multiplier_kernel(nvar, cu_l_curr, cu_u_curr, cu_v_curr, cu_rho)\n @cuda threads=64 blocks=(div(nvar-1, 64)+1) primal_residual_kernel(nvar, cu_rp, cu_u_curr, cu_v_curr)\n @cuda threads=64 blocks=(div(nvar-1, 64)+1) dual_residual_kernel(nvar, cu_rd, cu_v_prev, cu_v_curr, cu_rho)\n CUDA.synchronize()\n\n gpu_primres = CUDA.norm(cu_rp)\n gpu_dualres = CUDA.norm(cu_rd)\n\n gpu_eps_pri = sqrt(length(l_curr))*ABSTOL + RELTOL*max(CUDA.norm(cu_u_curr), CUDA.norm(cu_v_curr))\n gpu_eps_dual = sqrt(length(u_curr))*ABSTOL + RELTOL*CUDA.norm(cu_l_curr)\n\n @printf(\"[GPU] %10d %.6e %.6e %.6e %.6e\\n\", it, gpu_primres, gpu_dualres, gpu_eps_pri, gpu_eps_dual)\n end\n end\n end\n\n if use_gpu\n copyto!(u_curr, cu_u_curr)\n end\n\n rank = MPI.Comm_rank(comm)\n @printf(\" ** Time\\n\")\n @printf(\"[%d] Generator = %.2f\\n\", rank, time_gen)\n @printf(\"[%d] Branch = %.2f\\n\", rank, time_br)\n @printf(\"[%d] Bus = %.2f\\n\", rank, time_bus)\n @printf(\"[%d] G+Br+Bus = %.2f\\n\", rank, time_gen + time_br + time_bus)\n @printf(\"[%d] Scatter = %.2f\\n\", rank, time_br_scatter)\n @printf(\"[%d] Gather = %.2f\\n\", rank, time_br_gather)\n @printf(\"[%d] MPI(S+G) = %.2f\\n\", rank, time_br_scatter + time_br_gather)\n\n if is_master\n objval = sum(data.generators[g].coeff[data.generators[g].n-2]*(baseMVA*u_curr[gen_start+2*(g-1)])^2 +\n data.generators[g].coeff[data.generators[g].n-1]*(baseMVA*u_curr[gen_start+2*(g-1)]) +\n data.generators[g].coeff[data.generators[g].n]\n for g in 1:ngen)\n @printf(\"Objective value = %.6e\\n\", objval)\n end\n\n return\nend\n", "meta": {"hexsha": "a95b906cbe5cf401d56d2fbc4d7e2096340f79db", "size": 29264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/admm/acopf_admm_gpu.jl", "max_stars_repo_name": "wzhangw/ExaTron.jl", "max_stars_repo_head_hexsha": "c5844f356876904c410b68bf2b20ba3a03597674", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-07T19:27:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:38:20.000Z", "max_issues_repo_path": "src/admm/acopf_admm_gpu.jl", "max_issues_repo_name": "wzhangw/ExaTron.jl", "max_issues_repo_head_hexsha": "c5844f356876904c410b68bf2b20ba3a03597674", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-05-07T16:17:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T22:22:53.000Z", "max_forks_repo_path": "src/admm/acopf_admm_gpu.jl", "max_forks_repo_name": "wzhangw/ExaTron.jl", "max_forks_repo_head_hexsha": "c5844f356876904c410b68bf2b20ba3a03597674", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-22T14:34:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T16:21:49.000Z", "avg_line_length": 41.4504249292, "max_line_length": 163, "alphanum_fraction": 0.5684458721, "num_tokens": 8943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.24708377318878272}} {"text": "#=\nCopyright (c) 2015, Intel Corporation\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of Intel Corporation nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n=#\n\ninclude(\"../../../src/Sparso.jl\")\nusing Sparso\n\nfunction abiatic(Hdmat, d, nqbits, T)\n total_time = -time()\n\n nsets = 2^nqbits\n Phi0at0 = 1/sqrt(2^nqbits)*ones(nsets)\n\n ode_time = -time()\n\n h = 0.01\n rtol = 1e-6\n\n # Compute the constants once\n c30 = 3/8\n c31 = -im*3/32\n c32 = -im*9/32\n c40 = 12/13\n c41 = -im*1932/2197\n c42 = im*7200/2197\n c43 = -im*7296/2197\n c51 = -im*439/216\n c52 = im*8\n c53 = -im*3680/513\n c54 = im*845/4104\n c61 = im*8/27\n c62 = -im*2\n c63 = im*3544/2565\n c64 = -im*1859/4104\n c65 = im*11/40\n cz1 = -im*16/135\n cz3 = -im*6656/12825\n cz4 = -im*28561/56430\n cz5 = im*9/50\n cz6 = -im*2/55\n ce1 = -im*1/360\n ce3 = im*128/4275\n ce4 = im*2197/75240\n ce5 = -im*1/50\n ce6 = -im*2/55\n\n # Absolute tolerance\n atol = 1e-13\n alpha_val = 0.8\n k = 0\n # Initial time moment\n i = 1\n Tv = zeros(0)\n push!(Tv, 0)\n t = 0\n # Initial condition\n meanenergy = zeros(1)\n variance = zeros(1)\n meanenergy[1] = dot(vec(abs(Phi0at0).^2), d)\n variance[1] = dot(vec(abs(Phi0at0).^2), (d - meanenergy[1]).^2)\n wi = Phi0at0\n # If it is the last iteration, then lastit = 1, otherwise lastit = 0\n lastit = 0\n spmv_time = 0\n\n while lastit == 0\n # Stretch the step if within 10% of b-t\n if t + 1.1*h > T\n h = T - t\n lastit = 1\n end\n \n # Compute the step\n s = t/T # real\n w = wi\n spmv_time -= time()\n s1 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + 0.25*h)/T\n w = wi + -im*0.25*h*s1\n spmv_time -= time()\n s2 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + c30*h)/T\n w = wi + c31*h*s1 + c32*h*s2\n spmv_time -= time()\n s3 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + c40*h)/T\n w = wi + c41*h*s1 + c42*h*s2 + c43*h*s3\n spmv_time -= time()\n s4 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + h)/T\n w = wi + c51*h*s1 + c52*h*s2 + c53*h*s3 + c54*h*s4\n spmv_time -= time()\n s5 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + 0.5*h)/T\n w = wi + c61*h*s1 + c62*h*s2 + c63*h*s3 + c64*h*s4 + c65*h*s5\n spmv_time -= time()\n s6 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n z = wi + h*(cz1*s1 + cz3*s3 + cz4*s4 + cz5*s5 + cz6*s6)\n e = h * norm(ce1*s1 + ce3*s3 + ce4*s4 + ce5*s5 + ce6*s6) # real\n \n # Target tolerance for this step\n target_tol = rtol*norm(wi) + atol\n if e <= target_tol # In case the tolerance is met\n t = t + h\n h = alpha_val*h*(target_tol/e)^0.2\n i = i + 1\n push!(Tv, t)\n wi = z\n push!(meanenergy, dot(abs(z).^2, d))\n push!(variance, dot(abs(z).^2, (d - meanenergy[end]).^2))\n k = 0\n elseif k == 0 # Tolerance is not met for the first time in this step\n h = alpha_val*h*(target_tol/e)^0.2\n k = k + 1\n lastit = 0\n else # Tolerance is not met more than once in this step\n h = h/2\n lastit = 0\n end\n end\n\n println(size(Tv))\n\n ode_time += time()\n\n lanczos_time = -time()\n spectralgap = zeros(length(Tv))\n\n nit = min(30, nsets)\n\n x0 = rand(nsets)\n\n alpha = zeros(nit)\n beta = zeros(nit + 1)\n\n for i = 1:length(Tv)\n s = Tv[i]/T\n\n q0 = zeros(nsets)\n q1 = x0/norm(x0)\n\n for k = 1:nit\n spmv_time -= time()\n uk = -(1 - s)*Hdmat*q1 + s*d.*q1\n spmv_time += time()\n\n alpha[k] = dot(q1, uk)\n uk -= beta[k]*q0 + alpha[k]*q1\n beta[k + 1] = norm(uk)\n if beta[k + 1] == 0\n println(\"Error\")\n return\n end\n\n q0 = q1\n q1 = uk/beta[k + 1]\n end\n\n TT = SymTridiagonal(alpha, beta[2:nit])\n\n Dt = sort(eig(TT)[1], 1)\n Dt = [Dt[1]; Dt[end]]\n\n spectralgap[i] = abs(Dt[1] - Dt[2])^2\n end\n lanczos_time += time()\n\n optimalenergy = minimum(d)\n\n total_time += time()\n\n @printf(\"%10s%10s%12s%12s%12s\\n\", \"time\", \"eigengap\", \"optimal\", \"meanenergy\", \"variance\");\n for i = length(Tv):length(Tv)\n @printf(\"%10.2f%10.4f%12.4f%12.4f%12.4f\\n\", Tv[i], spectralgap[i], optimalenergy, meanenergy[i], variance[i])\n end\n\n println(\"total_time = $(total_time) ode_time = $(ode_time) lanczos_time = $(lanczos_time) spmv_time = $(spmv_time)\")\nend\n\nfunction print_result(Tv, spectralgap, optimalenergy, meanenergy, variance)\n @printf(\"%10s%10s%12s%12s%12s\\n\", \"time\", \"eigengap\", \"optimal\", \"meanenergy\", \"variance\");\n for i = length(Tv):length(Tv)\n @printf(\"%10.2f%10.4f%12.4f%12.4f%12.4f\\n\", Tv[i], spectralgap[i], optimalenergy, meanenergy[i], variance[i])\n end\nend\n\nfunction abiatic_sa(Hdmat, d, nqbits, T)\n total_time = -time()\n\n set_matrix_property(Dict(\n :Hdmat => SA_SYMM_VALUED | SA_STRUCTURE_ONLY, \n )\n )\n\n nsets = 2^nqbits\n Phi0at0 = 1/sqrt(2^nqbits)*ones(nsets)\n\n ode_time = -time()\n\n h = 0.01\n rtol = 1e-6\n\n # Compute the constants once\n c30 = 3/8\n c31 = -im*3/32\n c32 = -im*9/32\n c40 = 12/13\n c41 = -im*1932/2197\n c42 = im*7200/2197\n c43 = -im*7296/2197\n c51 = -im*439/216\n c52 = im*8\n c53 = -im*3680/513\n c54 = im*845/4104\n c61 = im*8/27\n c62 = -im*2\n c63 = im*3544/2565\n c64 = -im*1859/4104\n c65 = im*11/40\n cz1 = -im*16/135\n cz3 = -im*6656/12825\n cz4 = -im*28561/56430\n cz5 = im*9/50\n cz6 = -im*2/55\n ce1 = -im*1/360\n ce3 = im*128/4275\n ce4 = im*2197/75240\n ce5 = -im*1/50\n ce6 = -im*2/55\n\n # Absolute tolerance\n atol = 1e-13\n alpha_val = 0.8\n k = 0\n # Initial time moment\n i = 1\n Tv = zeros(0)\n push!(Tv, 0)\n t = 0\n # Initial condition\n meanenergy = zeros(1)\n variance = zeros(1)\n meanenergy[1] = dot(vec(abs(Phi0at0).^2), d)\n variance[1] = dot(vec(abs(Phi0at0).^2), (d - meanenergy[1]).^2)\n wi = Array{Complex128}(Phi0at0)\n # If it is the last iteration, then lastit = 1, otherwise lastit = 0\n lastit = 0\n spmv_time = 0\n\n s1 = Array{Complex128}(length(d))\n s2 = Array{Complex128}(length(d))\n s3 = Array{Complex128}(length(d))\n s4 = Array{Complex128}(length(d))\n s5 = Array{Complex128}(length(d))\n s6 = Array{Complex128}(length(d))\n\n while lastit == 0\n # Stretch the step if within 10% of b-t\n if t + 1.1*h > T\n h = T - t\n lastit = 1\n end\n \n # Compute the step\n s = t/T # real\n w = wi\n spmv_time -= time()\n s1 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + 0.25*h)/T\n w = wi + -im*0.25*h*s1\n spmv_time -= time()\n s2 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + c30*h)/T\n w = wi + c31*h*s1 + c32*h*s2\n spmv_time -= time()\n s3 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + c40*h)/T\n w = wi + c41*h*s1 + c42*h*s2 + c43*h*s3\n spmv_time -= time()\n s4 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + h)/T\n w = wi + c51*h*s1 + c52*h*s2 + c53*h*s3 + c54*h*s4\n spmv_time -= time()\n s5 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n s = (t + 0.5*h)/T\n w = wi + c61*h*s1 + c62*h*s2 + c63*h*s3 + c64*h*s4 + c65*h*s5\n spmv_time -= time()\n s6 = -(1 - s)*Hdmat*w + s*d.*w\n spmv_time += time()\n\n z = wi + h*(cz1*s1 + cz3*s3 + cz4*s4 + cz5*s5 + cz6*s6)\n e = h * norm(ce1*s1 + ce3*s3 + ce4*s4 + ce5*s5 + ce6*s6) # real\n \n # Target tolerance for this step\n target_tol = rtol*norm(wi) + atol\n if e <= target_tol # In case the tolerance is met\n t = t + h\n h = alpha_val*h*(target_tol/e)^0.2\n i = i + 1\n push!(Tv, t)\n wi = z\n push!(meanenergy, dot(abs(z).^2, d))\n push!(variance, dot(abs(z).^2, (d - meanenergy[end]).^2))\n k = 0\n elseif k == 0 # Tolerance is not met for the first time in this step\n h = alpha_val*h*(target_tol/e)^0.2\n k = k + 1\n lastit = 0\n else # Tolerance is not met more than once in this step\n h = h/2\n lastit = 0\n end\n end\n\n println(size(Tv))\n\n ode_time += time()\n\n lanczos_time = -time()\n spectralgap = zeros(length(Tv))\n\n nit = min(30, nsets)\n\n x0 = rand(nsets)\n\n alpha = zeros(nit)\n beta = zeros(nit + 1)\n\n uk = Array{Float64}(length(d))\n\n dot_time = 0\n for i = 1:length(Tv)\n s = Tv[i]/T\n\n q0 = zeros(nsets)\n q1 = x0/norm(x0)\n\n for k = 1:nit\n spmv_time -= time()\n uk = -(1 - s)*Hdmat*q1 + s*d.*q1\n spmv_time += time()\n\n alpha[k] = dot(q1, uk)\n uk -= beta[k]*q0 + alpha[k]*q1\n beta[k + 1] = norm(uk)\n if beta[k + 1] == 0\n println(\"Error\")\n return\n end\n\n q0 = q1\n #q1 = uk/beta[k + 1]\n q1 = Sparso.WAXPB(1/beta[k+1], uk, 0) \n end\n\n TT = SymTridiagonal(alpha, beta[2:nit])\n\n Dt = sort(eig(TT)[1], 1)\n Dt = [Dt[1]; Dt[end]]\n\n spectralgap[i] = abs(Dt[1] - Dt[2])^2\n end\n lanczos_time += time()\n\n optimalenergy = minimum(d)\n\n total_time += time()\n\n print_result(Tv, spectralgap, optimalenergy, meanenergy, variance)\n\n println(\"total_time = $(total_time) ode_time = $(ode_time) lanczos_time = $(lanczos_time) spmv_time = $(spmv_time)\")\nend\n\nnqbits = parse(Int, ARGS[1])\nT = parse(Int, ARGS[2])\n\nnsets = 2^nqbits\nd = 4*collect(-nsets/2 : nsets/2 - 1)\n\ntunnelstr = -1\n\nhdmat_time = -time()\nHdmat = zeros(nsets, nsets)\nfor i=1:nsets\n for j=0:nqbits-1\n flip = (i - 1)$(1 << j) # flip jth bit in zero-based indexing\n Hdmat[i,flip+1] = 1\n end\nend\nHdmat = SparseMatrixCSC{Float64, Int32}(sparse(Hdmat))\n\nif length(ARGS) == 3\n test = ARGS[3]\nelse\n test = \"julia\"\nend\n\nif test == \"julia\"\n println(\"compiler warmup (ignored): \")\n srand(0)\n println(@time(abiatic(Hdmat, d, nqbits, T)))\n\n println(\"\\nRUN: \")\n srand(0)\n println(@time(abiatic(Hdmat, d, nqbits, T)))\nelse\n if test == \"call-repl\"\n set_options(SA_ENABLE, SA_USE_SPMP, SA_REPLACE_CALLS)\n elseif test == \"context\"\n set_options(SA_ENABLE, SA_USE_SPMP, SA_CONTEXT, SA_REPLACE_CALLS)\n elseif test == \"reorder\"\n set_options(SA_ENABLE, SA_USE_SPMP, SA_CONTEXT, SA_REORDER, SA_REPLACE_CALLS)\n elseif test == \"verbose\"\n set_options(SA_ENABLE, SA_USE_SPMP, SA_VERBOSE, SA_CONTEXT, SA_REORDER, SA_REPLACE_CALLS)\n end\n\n println(\"compiler warmup (ignored): \")\n srand(0)\n println(@time(@acc abiatic_sa(Hdmat, d, nqbits, T)))\n\n println(\"\\nRUN: \")\n srand(0)\n println(@time(@acc abiatic_sa(Hdmat, d, nqbits, T)))\nend\n", "meta": {"hexsha": "c3bc94652cdbfa9943b33849d73fedb268400607", "size": 11841, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/perf/adiabatic/adiabatic.jl", "max_stars_repo_name": "IntelLabs/Sparso", "max_stars_repo_head_hexsha": "570e7a18a96045e490f4ebf27ea948592e0bfa0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-07-11T15:11:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T00:32:08.000Z", "max_issues_repo_path": "test/perf/adiabatic/adiabatic.jl", "max_issues_repo_name": "IntelLabs/Sparso", "max_issues_repo_head_hexsha": "570e7a18a96045e490f4ebf27ea948592e0bfa0b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-09-15T13:37:36.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-09T19:30:32.000Z", "max_forks_repo_path": "test/perf/adiabatic/adiabatic.jl", "max_forks_repo_name": "IntelLabs/Sparso", "max_forks_repo_head_hexsha": "570e7a18a96045e490f4ebf27ea948592e0bfa0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-03T03:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-03T03:11:19.000Z", "avg_line_length": 25.1936170213, "max_line_length": 118, "alphanum_fraction": 0.574191369, "num_tokens": 4378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.2470329750071109}} {"text": "include(\"definitions.jl\")\r\ninclude(\"updateFunctions.jl\")\r\ninclude(\"utility.jl\")\r\n\r\nfunction sparseSCVB0_lda(documents::Array{SparseDocument,1},\r\n numWords::Int64,\r\n numDocuments::Int64,\r\n numTopics::Int64,\r\n numDocumentIterations::Int,\r\n burnInPerDoc::Int,\r\n minibatchSize::Int,\r\n Alpha::Float64,\r\n Beta::Float64,\r\n dict,\r\n tau::Float64,\r\n kappa::Float64,\r\n tau2::Float64,\r\n kappa2::Float64,\r\n scale::Float64,\r\n sampleSize::Int,\r\n time_limit::Float64,\r\n miniEpoch::Int,\r\n numDocuments_miniEpoch::Int64,\r\n\t\t\t\t\t\t sparsity::Float64)\r\n\r\n# sparse stochastic collapsed variational Bayes (sparseSCVB0) for LDA\r\n Alpha = ones(1,numTopics).*Alpha;\r\n Beta = ones(numWords,1).*Beta;\r\n\r\n # initialization of sparseSCVB0 specific model parameters\r\n #documentTopicCounts, wordTopicCounts, topicCounts, topicMem, sparseCounts = initialize(documents, numWords,numTopics,numDocuments);\r\n sparseVBparams=initialize(documents,Alpha, Beta, numTopics,numWords,numDocumentIterations,numDocuments);\r\n miniBatchesPerCorpus = numDocuments ./ minibatchSize;\r\n stepSize = scale ./ (tau^kappa); # step size for global expected counts\r\n #stepSize2 = 0.0; # initializing step size for local expected counts to make it soft local scope\r\n\r\n wordTopicCounts_hat = zeros(numWords,numTopics);\r\n topicCounts_hat = zeros(1,numTopics);\r\n iter = 0;\r\n\r\n saved_topics = Array{Array{Float64,2}}(0)\r\n saved_Totaltopics = Array{Array{Float64,2}}(0)\r\n saved_time = Float64[]\r\n saved_iters = Int64[]\r\n #saved_docTopics = Array{Array{Float64,2}}(0)\r\n\r\n prev_doc = 0; # to track miniEpoch docs\r\n doc_counter = 0;\r\n # main sparse stochastic collapsed variational Bayes (sparseSCVB0) loop\r\n while (sparseVBparams.wallClockTime < time_limit) && (doc_counter 0 \"At least 1 of recurrent or external input connections are needed\"\n\n # NOTE: it's not possible to have independent distal synapses for each presynaptic input,\n # because we need a single address space for postsynaptic segments. Otherwise,\n # it would be impossible to mix signals from multiple sources.\n N_presynaptic= recurrent ? Nₙ + distal_input_size : distal_input_size\n Nseg_init= 0\n\n TemporalMemory(params,\n DistalSynapses(N_presynaptic, Nc, k;\n Nseg_init= Nseg_init, params= DistalSynapseParams(params)),\n TMState(Nₙ,Nseg_init),\n recurrent)\nend\n\nNₙ(tm::TemporalMemory)= tm.params.Nₙ\nreset!(tm::TemporalMemory)= begin\n reset!(tm.distalSynapses)\n reset!(tm.previous)\nend\n\n\"\"\"\n`step!(tm::TemporalMemory, c, distal_input=[])` evolves the Temporal Memory to the next timestep\ngiven the minicolumn activations and any distal input.\nReturns the state of the region's neurons: active, predictive, bursting (minicolumns)\n\nSee also: [`tm_activate`](@ref), [`tm_predict`](@ref)\n\"\"\"\n# Given a column activation pattern `c` (SP output), step the TM\nfunction step!(tm::TemporalMemory, c, distal_input=falses(0))\n s= tm.distalSynapses; p= tm.previous\n\n α, B, WN= tm_activate(tm, c, p.Π)\n # If recurrent, concatenate distal input activity with this layer's activity\n distal_input= tm.recurrent ? [α;distal_input] : distal_input\n Π, Πₛ, Mₛ, ovp_Mₛ= tm_predict(tm, distal_input)\n\n # Learn\n WS, WS_burst= calculate_WS!(s, p.Πₛ,p.ovp_Mₛ,α,B)\n # Update winner neurons with entries from bursting columns\n WN[NS(s)*WS_burst .> 0].= true\n step!(s, p.WN,WS, α, p.α,p.Mₛ,p.ovp_Mₛ)\n update_TMState!(p, Nseg=Nₛ(s),\n α=α, Π=Π, WN=WN, Πₛ=Πₛ, Mₛ=Mₛ, ovp_Mₛ=ovp_Mₛ)\n return (\n active= α,\n predictive= Π,\n bursting= B\n )\nend\n\n\"\"\"\nActive and predictive cells given the minicolumn activations and any distal input.\n\nSee also: [`tm_activate`](@ref), [`tm_predict`](@ref)\n\"\"\"\n(tm::TemporalMemory)(c, distal_input=falses(0))= begin\n α= tm_activate(tm,c,tm.previous.Π)[1]\n # If recurrent, concatenate distal input activity with this layer's activity\n distal_input= tm.recurrent ? [α;distal_input] : distal_input\n (\n active= α,\n predictive= tm_predict(tm,distal_input)[1]\n )\nend\n\n\"\"\"\n`tm_activate(tm::TemporalMemory, c, Π)` calculates\n\n1. which minicolumns burst,\n2. which neurons in the layer are activated\n3. which become predictive\n\nfor minicolumn activation `c` (size `Nc`) given by the [`SpatialPooler`](@ref)\nand the previously predictive neurons `Π` (size `Nₙ`).\n\n# Returns\n\n1. `a`: neuron activation (`Nₙ`)\n2. `B`: bursting minicolumns (`Nc`)\n3. `WN`: \"winning\" neurons (`Nₙ`)\n\nSee also: [`tm_predict`](@ref), [`DistalSynapses`](@ref)\n\"\"\"\nfunction tm_activate(tm::TemporalMemory, c, Π)\n @unpack Nc, k = tm.params\n\n # bursting minicolumns (Nc)\n burst(c,Π)= c .& .!@percolumn(any, Π, k)\n # minicolumns with a predictive neuron (k × Nc)\n predicted(c,Π)= @percolumn(&,Π,c, k)\n # activation for the whole layer given the predicted/bursting neurons\n activate(A_pred, B)= (A_pred .| B')|> vec\n # cache parts of the output because they're used 2 times\n B= burst(c,Π) # Nc\n A_pred= predicted(c,Π) # k × Nc\n return activate(A_pred,B), B, A_pred|>vec\nend\n\n\"\"\"\n`tm_predict(tm::TemporalMemory, α)` calculates which neurons will be predictive at the next step\ngiven the currently active neurons + distal input `α`.\n`size(a)` must match the presynaptic length of `tm.distalSynapses`.\n\n# Returns\n\n1. `Π`: predictive neurons (`Nₙ`)\n2. `Πₛ`: predictive dendritic segments ('Nₛ') (caching)\n3. `Mₛ`: matching dendritic segments (`Nₛ`) (learning)\n4. `ovp_Mₛ`: subthreshold-matching dendritic segments (`Nₛ`) (learning)\n\"\"\"\nfunction tm_predict(tm::TemporalMemory, α::CellActivity)\n @unpack θ_stimulus_activate, θ_stimulus_learn = tm.params\n distal= tm.distalSynapses\n\n # Segment depolarization (prediction)\n Πₛ= Wd(distal)'α .> θ_stimulus_activate\n # Neuron depolarization (prediction)\n Π(Πₛ)= NS(distal)*Πₛ .> 0 # NOTE: params.θ_segment_act instead of 0\n # Sub-threshold segment stimulation sufficient for learning\n ovp_Mₛ= distal.Dd'α\n Mₛ= ovp_Mₛ .> θ_stimulus_learn\n return Π(Πₛ),Πₛ, Mₛ,ovp_Mₛ\nend", "meta": {"hexsha": "dc89e4f5256e41eb36195e0de365247c63adb6d2", "size": 7914, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TemporalMemory.jl", "max_stars_repo_name": "Oblynx/HierarchicalTemporalMemory.jl", "max_stars_repo_head_hexsha": "2f927431c619b6ecac1aefd7f3f0312aac745f56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-06-09T09:01:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T19:34:30.000Z", "max_issues_repo_path": "src/TemporalMemory.jl", "max_issues_repo_name": "Oblynx/HierarchicalTemporalMemory.jl", "max_issues_repo_head_hexsha": "2f927431c619b6ecac1aefd7f3f0312aac745f56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2019-06-20T15:16:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T18:55:49.000Z", "max_forks_repo_path": "src/TemporalMemory.jl", "max_forks_repo_name": "Oblynx/HierarchicalTemporalMemory.jl", "max_forks_repo_head_hexsha": "2f927431c619b6ecac1aefd7f3f0312aac745f56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-04-13T16:37:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T07:04:27.000Z", "avg_line_length": 35.8099547511, "max_line_length": 138, "alphanum_fraction": 0.7249178671, "num_tokens": 2451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.24703296844699482}} {"text": "# Simulate a 2D actomyosin network\n# Alex Tam, 12/10/2020\n\n# Simulate network\n\"Control function for actomyosin network simulations\"\nfunction actomyosin_network(parN, parA, parM, par, trial)\n # Specify domain width\n Lxx::Float64 = 2.5; Lxy::Float64 = 0; Lyx::Float64 = 0; Lyy::Float64 = 2.5; # Actual domain widths\n # Pre-allocate\n Force = [[0.0, 0.0, 0.0, 0.0] for idx in 1:parN.nT]; # [pN] Network force\n Curvature = [0.0 for idx in 1:parN.nT]; # Mean network curvature\n Index = [0.0 for idx in 1:parN.nT]; # Mean two-filament index\n Filament_Speed = [0.0 for idx in 1:parN.nT]; # [μm/s] Mean filament node speed\n Motor_Speed = [0.0 for idx in 1:parN.nT]; # [μm/s] Mean motor head speed\n Angle_ROC = [0.0 for idx in 1:parN.nT]; # [rad/s] Mean rate of change of angle\n Motor_Pos = [0.0 for idx in 1:parN.nT]; # [--] Mean myosin motor head position\n Motor_Angle = [0.0 for idx in 1:parN.nT]; # [rad] Mean angle between filaments at motor binding site\n Bins = Vector{Float64}(); Hist = Vector{Int}(); # [μm, --] Pre-allocate paired-distance histogram\n # Generate initial conditions\n state = State{Float64}(Vector{Vector{Vector}}(), Vector{Vector}()); # Initialise empty State struct\n mm = Vector{Myosin_Motor}(); # Pre-allocate empty myosin motors\n af, state = actin_ic(state, parN, parA, Lxx, Lyy); # Initialise actin filaments\n xl = intersection_search(state, af, mm); # Initialise cross-links\n mm, xl, state = myosin_ic(state, mm, parN, xl, Lxx, Lxy, Lyx, Lyy); # Initialise myosin motors\n state_old = state; # Store initial state to compute force\n # Time-stepping\n animation = @animate for i = 1:parN.nT\n # Write final DOF vector to file\n if i == parN.nT\n dof = build_dof(state);\n writedlm(\"dof-$par-trial-$trial-$i.csv\", dof);\n end\n # Compute network characteristics\n Curvature[i] = curvature(af, state, Lxx, Lxy, Lyx, Lyy); # savefig(\"actomyosin_curvature-$par-trial-$trial.svg\"); # Mean filament curvature\n Index[i] = two_filament_index(mm, state, Lxx, Lxy, Lyx, Lyy); # savefig(\"actomyosin_2f_index-$par-trial-$trial.svg\"); # Mean two-filament index\n Bins, Hist = pcf(af, state, Lxx, Lyy); savefig(\"actomyosin_pcf-$par-trial-$trial.svg\"); # Paired distances between filament nodes\n Filament_Speed[i] = filament_speed(parN, af, state, state_old, Lxx, Lxy, Lyx, Lyy); # savefig(\"actomyosin_filament_speed-$par-trial-$trial.svg\"); # Filament node speeds\n Motor_Speed[i] = motor_speed(parN, mm, state, state_old, Lxx, Lxy, Lyx, Lyy); # savefig(\"actomyosin_motor_speed-$par-trial-$trial.svg\"); # Motor head speeds\n Angle_ROC[i] = motor_angle_roc(parN, mm, state, state_old, Lxx, Lxy, Lyx, Lyy); # savefig(\"actomyosin_angle_roc-$par-trial-$trial.svg\"); # Angle rate of change\n Motor_Pos[i] = motor_position(mm, state); # savefig(\"actomyosin_angle_roc-$par-trial-$trial.svg\"); # Myosin motor head positions\n Motor_Angle[i] = motor_angle(mm, state, parN, Lxx, Lxy, Lyx, Lyy); # savefig(\"actomyosin_angle_roc-$par-trial-$trial.svg\"); # Myosin motor angles\n Force[i] = network_force(state, state_old, af, xl, mm, parN, parA, parM, Lxx, Lxy, Lyx, Lyy); # Force\n # Draw network\n draw_network(state, af, xl, mm, parN, parA, Force[i], Lxx, Lxy, Lyx, Lyy);\n if i == 1\n savefig(\"actomyosin_ic-par-$par-trial-$trial.svg\"); # Save image of initial condition\n end\n # Simulate one time step\n if i != parN.nT # Ensure correct looping sequence\n # Turnover and polymerisation\n af, mm, state = actin_turnover(state, af, mm, parN, parA, Lxx, Lyy);\n af = segment_translations(state, af); # Update filament translations\n xl = intersection_search(state, af, mm); # Update cross-links\n mm, xl, state = myosin_turnover(state, xl, mm, parN, parM, Lxx, Lxy, Lyx, Lyy); # Myosin binding/unbinding\n # Compute solution and store data\n state_old = state; # Store current state for energy functional\n new_dof = optimise_network(state_old, af, xl, mm, parN, parA, parM, Lxx, Lxy, Lyx, Lyy); # Compute network solution\n state = build_state(new_dof, af, mm); # Construct State from vector\n end\n end\n # Output .gif and image of the network\n gif(animation, \"actomyosin-par-$par-trial-$trial.gif\", fps = 10); savefig(\"actomyosin_end-par-$par-trial-$trial.svg\");\n # Plot quantities versus time\n draw_stress(parN, Force, parN.nT, Lxx, Lyy); savefig(\"actomyosin_stress-par-$par-trial-$trial.svg\"); # Stress components\n times, Bulk_Stress, Bulk_Stress_Int = draw_bulk_stress(parN, Force, parN.nT, Lxx, Lyy); savefig(\"actomyosin_bulk_stress-par-$par-trial-$trial.svg\"); # Bulk stress\n @printf(\"Time-averaged bulk stress is %f pN/μm*s.\\n\", Bulk_Stress_Int[end]/times[end])\n # Compute time-integrated network statistics\n Curvature_Int, Index_Int, Filament_Speed_Int, Motor_Speed_Int, Angle_ROC_Int, Motor_Pos_Int, Motor_Angle_Int = integrated_statistics(parN, Curvature, Index, Filament_Speed, Motor_Speed, Angle_ROC, Motor_Pos, Motor_Angle)\n # Save mean stress and spatial measures time series data to files\n writedlm(\"times.csv\", times);\n writedlm(\"stress-par-$par-trial-$trial.csv\", Bulk_Stress);\n writedlm(\"curvature-par-$par-trial-$trial.csv\", Curvature);\n writedlm(\"index-par-$par-trial-$trial.csv\", Index);\n writedlm(\"filament_speed-par-$par-trial-$trial.csv\", Filament_Speed);\n writedlm(\"motor_speed-par-$par-trial-$trial.csv\", Motor_Speed);\n writedlm(\"motor_pos-par-$par-trial-$trial.csv\", Motor_Pos);\n writedlm(\"motor_angle-par-$par-trial-$trial.csv\", Motor_Angle);\n return state, af, mm, xl, Bulk_Stress_Int[end]/times[end], Curvature_Int[end]/times[end], Index_Int[end]/times[end], Filament_Speed_Int[end]/times[end], Motor_Speed_Int[end]/times[end], Angle_ROC_Int[end]/times[end], Motor_Pos_Int[end]/times[end], Motor_Angle_Int[end]/times[end], Bins, Hist\nend\n", "meta": {"hexsha": "a06ca2088a11adce5ac431ff604d4223e6fc0051", "size": 6021, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "actomyosin_network.jl", "max_stars_repo_name": "alex-tam/actomyosin_network", "max_stars_repo_head_hexsha": "bb0faf59396fcb41abb345a1b03464874b0ec647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "actomyosin_network.jl", "max_issues_repo_name": "alex-tam/actomyosin_network", "max_issues_repo_head_hexsha": "bb0faf59396fcb41abb345a1b03464874b0ec647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "actomyosin_network.jl", "max_forks_repo_name": "alex-tam/actomyosin_network", "max_forks_repo_head_hexsha": "bb0faf59396fcb41abb345a1b03464874b0ec647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.2625, "max_line_length": 295, "alphanum_fraction": 0.6807839229, "num_tokens": 1865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.24695336085346806}} {"text": "using MathOptInterface\nconst MOI = MathOptInterface\nconst AFF = MOI.ScalarAffineFunction{Cdouble}\nconst EQ = MOI.EqualTo{Cdouble}\nconst AFFEQ = MOI.ConstraintIndex{AFF,EQ}\n\nmutable struct Optimizer <: MOI.AbstractOptimizer\n objective_constant::Cdouble\n objective_sign::Int\n blockdims::Vector{CSDP_INT}\n varmap::Vector{Tuple{Int, Int, Int}} # Variable Index vi -> blk, i, j\n num_entries::Dict{Tuple{Int, Int}, Int}\n b::Vector{Cdouble}\n C::blockmatrix\n problem::Union{Nothing, LoadingProblem}\n X::blockmatrix\n y::Union{Nothing, Vector{Cdouble}}\n Z::blockmatrix\n status::CSDP_INT\n pobj::Cdouble\n dobj::Cdouble\n solve_time::Float64\n silent::Bool\n options::Dict{Symbol, Any}\n function Optimizer(; kwargs...)\n optimizer = new(\n zero(Cdouble), 1, CSDP_INT[], Tuple{Int, Int, Int}[],\n Dict{Tuple{Int, Int}, Int}(), Cdouble[],\n blockmatrix(), nothing, blockmatrix(), nothing, blockmatrix(),\n -1, NaN, NaN, NaN, false, Dict{Symbol, Any}())\n for (key, value) in kwargs\n MOI.set(optimizer, MOI.RawOptimizerAttribute(String(key)), value)\n end\n # May need to call `free_loaded_prob` and `free_loading_prob`.\n finalizer(MOI.empty!, optimizer)\n return optimizer\n end\nend\n\nvarmap(optimizer::Optimizer, vi::MOI.VariableIndex) = optimizer.varmap[vi.value]\n\nfunction MOI.supports(optimizer::Optimizer, param::MOI.RawOptimizerAttribute)\n return Symbol(param.name) in ALLOWED_OPTIONS\nend\nfunction MOI.set(optimizer::Optimizer, param::MOI.RawOptimizerAttribute, value)\n if !(param.name isa String)\n Base.depwarn(\n \"passing `$(param.name)` to `MOI.RawOptimizerAttribute` as type \" *\n \"`$(typeof(param.name))` is deprecated. Use a string instead.\",\n Symbol(\"MOI.set\")\n )\n end\n if !MOI.supports(optimizer, param)\n throw(MOI.UnsupportedAttribute(param))\n end\n optimizer.options[Symbol(param.name)] = value\nend\nfunction MOI.get(optimizer::Optimizer, param::MOI.RawOptimizerAttribute)\n # TODO: This gives a poor error message if the name of the parameter is invalid.\n if !(param.name isa String)\n Base.depwarn(\n \"passing `$(param.name)` to `MOI.RawOptimizerAttribute` as type \" *\n \"`$(typeof(param.name))` is deprecated. Use a string instead.\",\n Symbol(\"MOI.set\")\n )\n end\n return optimizer.options[Symbol(param.name)]\nend\n\nMOI.supports(::Optimizer, ::MOI.Silent) = true\nfunction MOI.set(optimizer::Optimizer, ::MOI.Silent, value::Bool)\n optimizer.silent = value\nend\nMOI.get(optimizer::Optimizer, ::MOI.Silent) = optimizer.silent\n\nMOI.get(::Optimizer, ::MOI.SolverName) = \"CSDP\"\n# See table \"Return codes for easy_sdp() and CSDP\" in `doc/csdpuser.pdf`.\nconst RAW_STATUS = [\n \"Problem solved to optimality.\",\n \"Problem is primal infeasible.\",\n \"Problem is dual infeasible.\",\n \"Problem solved to near optimality.\",\n \"Maximum iterations reached.\",\n \"Stuck at edge of primal feasibility.\",\n \"Stuck at edge of dual feasibility.\",\n \"Lack of progress.\",\n \"X, Z, or O is singular.\",\n \"NaN or Inf values encountered.\",\n \"Program stopped by signal (SIXCPU, SIGTERM, etc.)\"]\n\nfunction MOI.get(optimizer::Optimizer, ::MOI.RawStatusString)\n return RAW_STATUS[optimizer.status + 1]\nend\nfunction MOI.get(optimizer::Optimizer, ::MOI.SolveTimeSec)\n return optimizer.solve_time\nend\n\nfunction MOI.is_empty(optimizer::Optimizer)\n return iszero(optimizer.objective_constant) &&\n isone(optimizer.objective_sign) &&\n isempty(optimizer.blockdims) &&\n isempty(optimizer.varmap) &&\n isempty(optimizer.num_entries) &&\n isempty(optimizer.b) &&\n iszero(optimizer.C.nblocks) &&\n optimizer.C.blocks == C_NULL &&\n optimizer.problem === nothing\nend\n\nfunction MOI.empty!(optimizer::Optimizer)\n optimizer.objective_constant = zero(Cdouble)\n optimizer.objective_sign = 1\n empty!(optimizer.blockdims)\n empty!(optimizer.varmap)\n empty!(optimizer.num_entries)\n empty!(optimizer.b)\n if optimizer.problem !== nothing\n if optimizer.y !== nothing\n free_loaded_prob(optimizer.problem, optimizer.X, optimizer.y, optimizer.Z)\n end\n free_loading_prob(optimizer.problem)\n end\n optimizer.problem = nothing\n optimizer.C.nblocks = 0\n optimizer.C.blocks = C_NULL\n optimizer.X.nblocks = 0\n optimizer.X.blocks = C_NULL\n optimizer.y = nothing\n optimizer.Z.nblocks = 0\n optimizer.Z.blocks = C_NULL\n optimizer.status = -1\n optimizer.pobj = 0.0\n optimizer.dobj = 0.0\nend\n\nfunction MOI.supports(\n optimizer::Optimizer,\n ::Union{MOI.ObjectiveSense,\n MOI.ObjectiveFunction{AFF}})\n return true\nend\n\nMOI.supports_add_constrained_variables(::Optimizer, ::Type{MOI.Reals}) = false\n\nconst SupportedSets = Union{MOI.Nonnegatives, MOI.PositiveSemidefiniteConeTriangle}\nMOI.supports_add_constrained_variables(::Optimizer, ::Type{<:SupportedSets}) = true\nfunction MOI.supports_constraint(::Optimizer, ::Type{AFF}, ::Type{EQ})\n return true\nend\n\nfunction _new_block(optimizer::Optimizer, set::MOI.Nonnegatives)\n push!(optimizer.blockdims, -MOI.dimension(set))\n blk = length(optimizer.blockdims)\n for i in 1:MOI.dimension(set)\n push!(optimizer.varmap, (blk, i, i))\n end\nend\n\nfunction _new_block(optimizer::Optimizer, set::MOI.PositiveSemidefiniteConeTriangle)\n push!(optimizer.blockdims, set.side_dimension)\n blk = length(optimizer.blockdims)\n for i in 1:set.side_dimension\n for j in 1:i\n push!(optimizer.varmap, (blk, i, j))\n end\n end\nend\n\nfunction _add_constrained_variables(optimizer::Optimizer, set::SupportedSets)\n offset = length(optimizer.varmap)\n _new_block(optimizer, set)\n ci = MOI.ConstraintIndex{MOI.VectorOfVariables, typeof(set)}(offset + 1)\n return [MOI.VariableIndex(i) for i in offset .+ (1:MOI.dimension(set))], ci\nend\n\nfunction _error(start, stop)\n error(start, \". Use `MOI.instantiate(CSDP.Optimizer, with_bridge_type = Float64)` \", stop)\nend\n\nfunction constrain_variables_on_creation(\n dest::MOI.ModelLike,\n src::MOI.ModelLike,\n index_map::MOI.Utilities.IndexMap,\n ::Type{S},\n) where {S<:MOI.AbstractVectorSet}\n for ci_src in\n MOI.get(src, MOI.ListOfConstraintIndices{MOI.VectorOfVariables,S}())\n f_src = MOI.get(src, MOI.ConstraintFunction(), ci_src)\n if !allunique(f_src.variables)\n _error(\"Cannot copy constraint `$(ci_src)` as variables constrained on creation because there are duplicate variables in the function `$(f_src)`\",\n \"to bridge this by creating slack variables.\")\n elseif any(vi -> haskey(index_map, vi), f_src.variables)\n _error(\"Cannot copy constraint `$(ci_src)` as variables constrained on creation because some variables of the function `$(f_src)` are in another constraint as well.\",\n \"to bridge constraints having the same variables by creating slack variables.\")\n else\n set = MOI.get(src, MOI.ConstraintSet(), ci_src)::S\n vis_dest, ci_dest = _add_constrained_variables(dest, set)\n index_map[ci_src] = ci_dest\n for (vi_src, vi_dest) in zip(f_src.variables, vis_dest)\n index_map[vi_src] = vi_dest\n end\n end\n end\nend\n\nfunction count_entry(optimizer::Optimizer, con_idx::Integer, blk::Integer)\n key = (con_idx, blk)\n optimizer.num_entries[key] = get(optimizer.num_entries, key, 0) + 1\nend\n\n# Loads objective coefficient α * vi\nfunction load_objective_term!(optimizer::Optimizer, α, vi::MOI.VariableIndex)\n blk, i, j = varmap(optimizer, vi)\n # in SDP format, it is max and in MPB Conic format it is min\n coef = optimizer.objective_sign * α\n if i != j\n coef /= 2\n end\n addentry(optimizer.problem, 0, blk, i, j, coef, true)\nend\n\nfunction MOI.copy_to(dest::Optimizer, src::MOI.ModelLike)\n MOI.empty!(dest)\n index_map = MOI.Utilities.IndexMap()\n\n # Step 1) Compute the dimensions of what needs to be allocated\n constrain_variables_on_creation(\n dest,\n src,\n index_map,\n MOI.Nonnegatives,\n )\n constrain_variables_on_creation(\n dest,\n src,\n index_map,\n MOI.PositiveSemidefiniteConeTriangle,\n )\n vis_src = MOI.get(src, MOI.ListOfVariableIndices())\n if length(vis_src) < length(index_map.var_map)\n _error(\"Free variables are not supported by CSDP\",\n \"to bridge free variables into `x - y` where `x` and `y` are nonnegative.\")\n end\n cis_src = MOI.get(src, MOI.ListOfConstraintIndices{AFF,EQ}())\n dest.b = Vector{Cdouble}(undef, length(cis_src))\n funcs = Vector{AFF}(undef, length(cis_src))\n for (k, ci_src) in enumerate(cis_src)\n funcs[k] = MOI.get(src, MOI.CanonicalConstraintFunction(), ci_src)\n set = MOI.get(src, MOI.ConstraintSet(), ci_src)\n if isempty(funcs[k].terms)\n throw(ArgumentError(\"Empty constraint $cis_src: $(funcs[k])-in-$set. Not supported by CSDP.\"))\n end\n if !iszero(MOI.constant(funcs[k]))\n throw(MOI.ScalarFunctionConstantNotZero{\n Cdouble, AFF, EQ}(\n MOI.constant(funcs[k])))\n end\n for t in funcs[k].terms\n if !iszero(t.coefficient)\n blk, _, _ = varmap(dest, index_map[t.variable])\n count_entry(dest, k, blk)\n end\n end\n dest.b[k] = MOI.constant(set)\n index_map[ci_src] = AFFEQ(k)\n end\n\n # Step 2) Allocate CSDP datastructures\n dummy = isempty(dest.b)\n if dummy\n # See https://github.com/coin-or/Csdp/issues/2\n dest.b = [one(Cdouble)]\n dest.blockdims = [dest.blockdims; CSDP_INT(-1)]\n count_entry(dest, 1, length(dest.blockdims))\n end\n dest.C.nblocks = length(dest.blockdims)\n num_entries = zeros(CSDP_INT, length(dest.b), length(dest.blockdims))\n for (key, value) in dest.num_entries\n num_entries[key...] = value\n end\n dest.problem = allocate_loading_prob(Ref(dest.C), dest.blockdims, length(dest.b), num_entries, 3)\n if dummy\n # See https://github.com/coin-or/Csdp/issues/2\n duplicate = addentry(dest.problem, 1, length(dest.blockdims), 1, 1, 1.0, true)\n @assert !duplicate\n end\n\n # Step 3) Load data in the datastructures\n for k in eachindex(funcs)\n setconstant(dest.problem, k, dest.b[k])\n for term in funcs[k].terms\n if !iszero(term.coefficient)\n blk, i, j = varmap(dest, index_map[term.variable])\n coef = term.coefficient\n if i != j\n coef /= 2\n end\n duplicate = addentry(dest.problem, k, blk, i, j, coef, true)\n @assert !duplicate\n end\n end\n end\n\n # Throw error for variable attributes\n MOI.Utilities.pass_attributes(dest, src, index_map, vis_src)\n # Throw error for constraint attributes\n MOI.Utilities.pass_attributes(dest, src, index_map, cis_src)\n\n # Pass objective attributes and throw error for other ones\n model_attributes = MOI.get(src, MOI.ListOfModelAttributesSet())\n for attr in model_attributes\n if attr != MOI.ObjectiveSense() && attr != MOI.ObjectiveFunction{AFF}()\n throw(MOI.UnsupportedAttribute(attr))\n end\n end\n # We make sure to set `objective_sign` first before setting the objective\n if MOI.ObjectiveSense() in model_attributes\n sense = MOI.get(src, MOI.ObjectiveSense())\n dest.objective_sign = sense == MOI.MIN_SENSE ? -1 : 1\n end\n if MOI.ObjectiveFunction{AFF}() in model_attributes\n func = MOI.get(src, MOI.ObjectiveFunction{AFF}())\n obj = MOI.Utilities.canonical(func)\n dest.objective_constant = obj.constant\n for term in obj.terms\n if !iszero(term.coefficient)\n load_objective_term!(dest, term.coefficient, index_map[term.variable])\n end\n end\n end\n return index_map\nend\n\nfunction MOI.optimize!(optimizer::Optimizer)\n write_prob(optimizer)\n\n start_time = time()\n optimizer.y = loaded_initsoln(optimizer.problem, length(optimizer.b), Ref(optimizer.X), Ref(optimizer.Z))\n\n options = optimizer.options\n if optimizer.silent\n options = copy(options)\n options[:printlevel] = 0\n end\n\n optimizer.status, optimizer.pobj, optimizer.dobj = loaded_sdp(\n optimizer.problem, optimizer.objective_sign * optimizer.objective_constant,\n Ref(optimizer.X), optimizer.y, Ref(optimizer.Z), options,\n )\n optimizer.solve_time = time() - start_time\n return\nend\n\nfunction MOI.get(m::Optimizer, ::MOI.TerminationStatus)\n status = m.status\n if status == -1\n return MOI.OPTIMIZE_NOT_CALLED\n elseif status == 0\n return MOI.OPTIMAL\n elseif status == 1\n return MOI.INFEASIBLE\n elseif status == 2\n return MOI.DUAL_INFEASIBLE\n elseif status == 3\n return MOI.ALMOST_OPTIMAL\n elseif status == 4\n return MOI.ITERATION_LIMIT\n elseif 5 <= status <= 7\n return MOI.SLOW_PROGRESS\n elseif 8 <= status <= 9\n return MOI.NUMERICAL_ERROR\n else\n error(\"Internal library error: status=$status\")\n end\nend\n\nfunction MOI.get(m::Optimizer, attr::MOI.PrimalStatus)\n if attr.result_index > MOI.get(m, MOI.ResultCount())\n return MOI.NO_SOLUTION\n end\n status = m.status\n if status == 0\n return MOI.FEASIBLE_POINT\n elseif status == 1\n return MOI.INFEASIBLE_POINT\n elseif status == 2\n return MOI.INFEASIBILITY_CERTIFICATE\n elseif status == 3\n return MOI.NEARLY_FEASIBLE_POINT\n elseif 4 <= status <= 9\n return MOI.UNKNOWN_RESULT_STATUS\n else\n error(\"Internal library error: status=$status\")\n end\nend\n\nfunction MOI.get(m::Optimizer, attr::MOI.DualStatus)\n if attr.result_index > MOI.get(m, MOI.ResultCount())\n return MOI.NO_SOLUTION\n end\n status = m.status\n if status == 0\n return MOI.FEASIBLE_POINT\n elseif status == 1\n return MOI.INFEASIBILITY_CERTIFICATE\n elseif status == 2\n return MOI.INFEASIBLE_POINT\n elseif status == 3\n return MOI.NEARLY_FEASIBLE_POINT\n elseif 4 <= status <= 9\n return MOI.UNKNOWN_RESULT_STATUS\n else\n error(\"Internal library error: status=$status\")\n end\nend\n\nMOI.get(m::Optimizer, ::MOI.ResultCount) = 1\nfunction MOI.get(m::Optimizer, attr::MOI.ObjectiveValue)\n MOI.check_result_index_bounds(m, attr)\n return m.objective_sign * m.pobj\nend\nfunction MOI.get(m::Optimizer, attr::MOI.DualObjectiveValue)\n MOI.check_result_index_bounds(m, attr)\n return m.objective_sign * m.dobj\nend\nstruct PrimalSolutionMatrix <: MOI.AbstractModelAttribute end\nMOI.is_set_by_optimize(::PrimalSolutionMatrix) = true\nMOI.get(optimizer::Optimizer, ::PrimalSolutionMatrix) = optimizer.X\n\nstruct DualSolutionVector <: MOI.AbstractModelAttribute end\nMOI.is_set_by_optimize(::DualSolutionVector) = true\nMOI.get(optimizer::Optimizer, ::DualSolutionVector) = optimizer.y\n\nstruct DualSlackMatrix <: MOI.AbstractModelAttribute end\nMOI.is_set_by_optimize(::DualSlackMatrix) = true\nMOI.get(optimizer::Optimizer, ::DualSlackMatrix) = optimizer.Z\n\nfunction block(optimizer::Optimizer, ci::MOI.ConstraintIndex{MOI.VectorOfVariables})\n return optimizer.varmap[ci.value][1]\nend\nfunction dimension(optimizer::Optimizer, ci::MOI.ConstraintIndex{MOI.VectorOfVariables})\n blockdim = optimizer.blockdims[block(optimizer, ci)]\n if blockdim < 0\n return -blockdim\n else\n return MOI.dimension(MOI.PositiveSemidefiniteConeTriangle(blockdim))\n end\nend\nfunction vectorize_block(M, blk::Integer, s::Type{MOI.Nonnegatives})\n return diag(block(M, blk))\nend\nfunction vectorize_block(M::AbstractMatrix{Cdouble}, blk::Integer, s::Type{MOI.PositiveSemidefiniteConeTriangle}) where T\n B = block(M, blk)\n d = LinearAlgebra.checksquare(B)\n n = MOI.dimension(MOI.PositiveSemidefiniteConeTriangle(d))\n v = Vector{Cdouble}(undef, n)\n k = 0\n for j in 1:d\n for i in 1:j\n k += 1\n v[k] = B[i, j]\n end\n end\n @assert k == n\n return v\nend\n\nfunction MOI.get(optimizer::Optimizer, attr::MOI.VariablePrimal, vi::MOI.VariableIndex)\n MOI.check_result_index_bounds(optimizer, attr)\n blk, i, j = varmap(optimizer, vi)\n return block(MOI.get(optimizer, PrimalSolutionMatrix()), blk)[i, j]\nend\n\nfunction MOI.get(optimizer::Optimizer, attr::MOI.ConstraintPrimal,\n ci::MOI.ConstraintIndex{MOI.VectorOfVariables, S}) where S<:SupportedSets\n MOI.check_result_index_bounds(optimizer, attr)\n return vectorize_block(MOI.get(optimizer, PrimalSolutionMatrix()), block(optimizer, ci), S)\nend\nfunction MOI.get(optimizer::Optimizer, attr::MOI.ConstraintPrimal, ci::AFFEQ)\n MOI.check_result_index_bounds(optimizer, attr)\n return optimizer.b[ci.value]\nend\n\nfunction MOI.get(optimizer::Optimizer, attr::MOI.ConstraintDual,\n ci::MOI.ConstraintIndex{MOI.VectorOfVariables, S}) where S<:SupportedSets\n MOI.check_result_index_bounds(optimizer, attr)\n return vectorize_block(MOI.get(optimizer, DualSlackMatrix()), block(optimizer, ci), S)\nend\nfunction MOI.get(optimizer::Optimizer, attr::MOI.ConstraintDual, ci::AFFEQ)\n MOI.check_result_index_bounds(optimizer, attr)\n return -MOI.get(optimizer, DualSolutionVector())[ci.value]\nend\n", "meta": {"hexsha": "de2979f9b844ce00b0ce7fd36363b6e777457549", "size": 17551, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MOI_wrapper.jl", "max_stars_repo_name": "jump-dev/CSDP.jl", "max_stars_repo_head_hexsha": "8d57402a1300f0ed7fa296ac98020a6a231de313", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-09T19:45:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T18:53:00.000Z", "max_issues_repo_path": "src/MOI_wrapper.jl", "max_issues_repo_name": "jump-dev/CSDP.jl", "max_issues_repo_head_hexsha": "8d57402a1300f0ed7fa296ac98020a6a231de313", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-06-13T15:50:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T00:39:12.000Z", "max_forks_repo_path": "src/MOI_wrapper.jl", "max_forks_repo_name": "jump-dev/CSDP.jl", "max_forks_repo_head_hexsha": "8d57402a1300f0ed7fa296ac98020a6a231de313", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-06T19:57:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:00:05.000Z", "avg_line_length": 35.6004056795, "max_line_length": 178, "alphanum_fraction": 0.6707879893, "num_tokens": 4517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.24695335048495257}} {"text": "\n\"\"\"\nThis function creates a PowerSystems ThermalStandard unit.\n\"\"\"\nfunction create_PSY_generator(gen::ThermalGenEMIS{<: BuildPhase}, sys::PSY.System)\n\n tech = get_tech(gen)\n base_power = get_maxcap(gen)\n\n buses = PSY.get_components(PSY.Bus, sys)\n project_bus = PSY.Bus[]\n\n for b in buses\n if PSY.get_number(b) == get_bus(tech)\n push!(project_bus, b)\n end\n end\n\n PSY_gen = PSY.ThermalStandard(\n get_name(gen), # name\n true, # available\n true, # status\n project_bus[1], # bus\n get_maxcap(gen) / base_power, # active power\n 1.0, # reactive power\n get_maxcap(gen) / base_power, # rating\n (min = get_mincap(gen) / base_power, max = get_maxcap(gen) / base_power), # active power limits\n nothing, # reactive power limits\n (up = get_ramp_limits(tech)[:up] / (base_power * 60), down = get_ramp_limits(tech)[:down] / (base_power * 60)), # ramp limits\n get_operation_cost(tech), # operation cost\n base_power, # base power\n get_time_limits(tech), # up and down time limits\n PSY.PrimeMovers.Symbol(get_type(tech)), # primemover\n PSY.ThermalFuels.Symbol(get_fuel(tech)), # fuel type\n )\n return PSY_gen\nend\n\n\"\"\"\nThis function creates a PowerSystems RenewableDispatch unit.\n\"\"\"\nfunction create_PSY_generator(gen::RenewableGenEMIS{<: BuildPhase}, sys::PSY.System)\n tech = get_tech(gen)\n base_power = get_maxcap(gen)\n\n if get_type(tech) == \"WT\"\n primemover = PSY.PrimeMovers.WT\n elseif get_type(tech) == \"PVe\"\n primemover = PSY.PrimeMovers.PVe\n end\n\n buses = PSY.get_components(PSY.Bus, sys)\n project_bus = PSY.Bus[]\n\n for b in buses\n if PSY.get_number(b) == get_bus(tech)\n push!(project_bus, b)\n end\n end\n\n PSY_gen = PSY.RenewableDispatch(\n get_name(gen), # name\n true, # available\n project_bus[1], # bus\n get_maxcap(gen) / base_power, # active power\n 1.0, # reactive power\n get_maxcap(gen) / base_power, # rating\n primemover, # primemover\n nothing, # reactivepower limits\n 1.0, # power factor\n get_operation_cost(tech),\n base_power, # base power\n )\n return PSY_gen\nend\n\n\"\"\"\nThis function creates a PowerSystems GenericBattery unit.\n\"\"\"\nfunction create_PSY_generator(gen::BatteryEMIS{<: BuildPhase}, sys::PSY.System)\n tech = get_tech(gen)\n base_power = get_maxcap(gen)\n\n buses = PSY.get_components(PSY.Bus, sys)\n project_bus = PSY.Bus[]\n\n for b in buses\n if PSY.get_number(b) == get_bus(tech)\n push!(project_bus, b)\n end\n end\n\n PSY_gen = PSY.GenericBattery(\n get_name(gen), # name\n true, # available\n project_bus[1], # bus\n PSY.PrimeMovers.Symbol(get_type(tech)), # primemover\n get_soc(tech) / (get_maxcap(gen) * base_power), #initial state of charge\n (min = get_storage_capacity(tech)[:min] / (get_maxcap(gen) * base_power), max = get_storage_capacity(tech)[:max] / (get_maxcap(gen) * base_power)), # state of charge limits\n get_maxcap(gen) / base_power, # rating\n get_maxcap(gen) / base_power, # active power\n (min = get_input_active_power_limits(tech)[:min] / base_power, max = get_input_active_power_limits(tech)[:max] / base_power), # input active power limits\n (min = get_output_active_power_limits(tech)[:min] / base_power, max = get_output_active_power_limits(tech)[:max] / base_power), # output active power limits\n get_efficiency(tech), # efficiency\n 1.0, # reactive power\n nothing, # reactive power limits\n base_power, # base power\n )\n return PSY_gen\nend\n", "meta": {"hexsha": "997e37e5d20d8ad239b26582f5ef75d6d96f2339", "size": 3818, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/struct_creators/simulation_structs/siip_psy_device_creator.jl", "max_stars_repo_name": "NREL/EMISAgentSimulation.jl", "max_stars_repo_head_hexsha": "8217a2e8eb2abc9fc2a8dde3f3c09c22e3b0b332", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-14T11:02:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T04:33:08.000Z", "max_issues_repo_path": "src/struct_creators/simulation_structs/siip_psy_device_creator.jl", "max_issues_repo_name": "NREL/EMISAgentSimulation.jl", "max_issues_repo_head_hexsha": "8217a2e8eb2abc9fc2a8dde3f3c09c22e3b0b332", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/struct_creators/simulation_structs/siip_psy_device_creator.jl", "max_forks_repo_name": "NREL/EMISAgentSimulation.jl", "max_forks_repo_head_hexsha": "8217a2e8eb2abc9fc2a8dde3f3c09c22e3b0b332", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3963963964, "max_line_length": 180, "alphanum_fraction": 0.6215295966, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.2467439580784915}} {"text": "\n\"\"\"\nAbstract supertype for organ parameters. \nExtend to add additional components to organ parameters.\n\"\"\"\nabstract type AbstractParams end\n\n\"\"\"\nModel parameters that vary between organs\n\"\"\"\n@default_kw @flattenable @selectable struct Params{As,Sh,Al,Ma,Tr,Re,Ge,Pr} <: AbstractParams\n # Field | Default | _ | Selectable Types\n assimilation_pars::As | ConstantCAssim() | _ | Union{Nothing,AbstractAssim}\n scaling_pars::Sh | nothing | _ | Union{Nothing,AbstractScaling}\n allometry_pars::Al | nothing | _ | Union{Nothing,AbstractAllometry}\n maturity_pars::Ma | nothing | _ | Union{Nothing,AbstractMaturity}\n activetrans_pars::Tr | nothing | _ | Union{Nothing,ActiveTranslocation}\n passivetrans_pars::Re | LosslessPassiveTranslocation() | _ | PassiveTranslocation\n germination_pars::Ge | nothing | _ | Union{Nothing,AbstractGermination}\n production_pars::Pr | nothing | _ | Union{Nothing,AbstractProduction}\nend\n\nfor fn in fieldnames(Params)\n @eval $fn(p::Params) = p.$fn\nend\n\n\n\"\"\"\nAstract supertype for shared parameters. \nExtend to change the components that are shared.\n\"\"\"\nabstract type AbstractSharedParams end\n\n\"\"\"\n SharedParams(su_pars, core_pars, resorption_pars, tempcorr_pars, catabolism_pars)\n\nModel parameters shared between organs.\n\n# FieldMetadata macros\n- `@default_kw` provides default values and constructors, \n- `@selectable` provides the set of types that can be used for the parameter,\n so that they can be selected in a live interface.\n\"\"\"\n@default_kw @selectable struct SharedParams{SU,Co,Fe,Te,Ca} <: AbstractSharedParams\n # Field | Default | Selectable Types\n su_pars::SU | ParallelComplementarySU() | AbstractSynthesizingUnit\n core_pars::Co | DEBCore() | _\n resorption_pars::Fe | nothing | Union{Nothing,AbstractResorption}\n tempcorr_pars::Te | nothing | Union{Nothing,AbstractTemperatureCorrection}\n catabolism_pars::Ca | CatabolismCN() | AbstractCatabolism\nend\n\nfor fn in fieldnames(SharedParams)\n @eval $fn(p::SharedParams) = p.$fn\nend\n\n\n###########################################################################################\n# Variables\n\n\"\"\"\nModel variables. \nAllow storing and accessing variables for use by multiple components.\n\"\"\"\nabstract type AbstractVars end\n\n\"\"\"\n PlottableVars()\n\nPlottable model variables. These are vectors witih values for each time-step,\nto allow plotting and model introspection.\n\"\"\"\n@udefault_kw @units @plottable struct PlottableVars{F,R,E,T,WP,H,TS} <: AbstractVars\n scaling::F | [0.0] | _ | _\n rate::R | [0.0] | mol*mol^-1*d^-1 | _\n E_ctb::E | [0.0] | mol/hr | _\n θE::F | [0.0] | _ | _\n temp::T | [0.0] | K | _\n tempcorrection::F | [0.0] | _ | _\n swp::WP | [0.0] | kPa | _\n soilcorrection::F | [0.0] | _ | _\n height::H | [0.0] | m | _\n tstep::TS | [1] | _ | false\nend\n\n\n\"\"\"\n Vars()\n\nMutable struct to allow storing variables\nfor use by multiple components.\n\"\"\"\n@udefault_kw @units mutable struct Vars{F,R,E,T,WP,H} <: AbstractVars\n scaling::F | 0.0 | _\n rate::R | 0.0 | mol*mol^-1*d^-1\n θE::F | 0.0 | _\n E_ctb::E | 0.0 | mol/hr \n temp::T | 0.0 | K\n tempcorrection::F | 0.0 | _\n swp::WP | 0.0 | kPa\n soilcorrection::F | 0.0 | _\n height::H | 0.0 | m\nend\n\ntstep(v::PlottableVars) = v.tstep[1]\ntstep(v::Vars) = nothing\n\nset_tstep!(v::PlottableVars, val) = v.tstep[1] = val\nset_tstep!(v::Vars, val) = nothing\n\ndepth(v) = height(v)\n\nbuild_vars(vars::Vars, tspan) = vars\nbuild_vars(vars::PlottableVars, tspan) = begin\n len = length(tspan)\n len <= length(vars.rate) && return vars\n\n for fname in fieldnames(typeof(vars))\n varvec = getfield(vars, fname)\n append!(varvec, fill(getfield(vars, fname)[1], len - length(varvec)))\n end\n vars\nend\n\n###########################################################################################\n# Organs and Organisms\n\n\"\"\"\nAbstract supertype for organs. Inherit from it if you need to difine\nbehaviour different to that or [`Organ`](@ref).\n\"\"\"\nabstract type AbstractOrgan{P,S} end\n\nparams(o::AbstractOrgan) = o.params\nshared(o::AbstractOrgan) = o.shared\nvars(o::AbstractOrgan) = o.vars\nflux(o::AbstractOrgan) = o.J\n\n#= κ functions allow modular addition of destinations for catabolised flux, \nby default maturity and active translocation. If those components are\nnot used the flux fraction will be allocated to κsoma. =#\n\nκtra(o::AbstractOrgan) = κtra(activetrans_pars(o))\nκtra(o::Nothing) = 0.0\n\nκmat(o::AbstractOrgan) = κmat(maturity_pars(o))\nκmat(::Nothing) = 0.0\n\nκsoma(o::AbstractOrgan) = oneunit(κtra(o)) - κtra(o) - κmat(o)\n\n# Define `scaling` and `setscaling` etc. methods\nfor fn in fieldnames(Vars)\n setfn = Symbol.(:set_, fn, :!)\n @eval $fn(o::AbstractOrgan) = $fn(vars(o))\n @eval $setfn(o::AbstractOrgan, x) = $setfn(vars(o), x)\n @eval @inline ($fn)(vars::PlottableVars) = vars.$fn[tstep(vars)]\n @eval @inline ($setfn)(vars::PlottableVars, val) = vars.$fn[tstep(vars)] = val\n @eval @inline ($fn)(vars::Vars) = vars.$fn\n @eval @inline ($setfn)(vars::Vars, val) = vars.$fn = val\nend\n\n#= Forward variable and parameter getter/setter methods\nso they can be acessesed/set directly from the organ,\nwithout knowning where they are actually stored. =#\ntstep(o::AbstractOrgan) = tstep(vars(o))\nset_tstep!(o::AbstractOrgan, t) = set_tstep!(vars(o), t)\n\nfor fn in fieldnames(DEBCore)\n @eval $fn(p::SharedParams) = $fn(core_pars(p))\n @eval $fn(o::AbstractOrgan{<:Any,<:SharedParams}) = $fn(shared(o))\nend\n\nfor fn in fieldnames(SharedParams)\n @eval $fn(o::AbstractOrgan{<:Any,<:SharedParams}) = $fn(shared(o))\nend\n\nfor fn in fieldnames(Params)\n @eval $fn(o::AbstractOrgan{<:Params}) = $fn(params(o))\nend\n\n\"\"\"\n Organ(params, shared, vars, J)\n\nBasic model components. For a plants, organs might be roots, stem and leaves\n\"\"\"\nstruct Organ{P,S,V,F} <: AbstractOrgan{P,S}\n params::P\n shared::S\n vars::V\n J::F\nend\n\"\"\"\n Organ(params, shared, records)\n\nConstruct an organ from parameters, shared parameters and\nviews into records arrays for vaiable and flux matrices.\n\"\"\"\nOrgan(params::AbstractParams, shared::AbstractSharedParams, records) = begin\n vars = records.vars\n set_tstep!(vars, 1)\n J = view(records.J, Ti(1))\n Organ(params, shared, vars, J)\nend\n\n\n# Records hold vars and flux, allowing storage of each \n# timestep for plotting if PlottableVars are used.\nabstract type AbstractRecords end\n\n@plottable struct PlottableRecords{V,F} <: AbstractRecords\n vars::V | true\n J::F | false\nend\nPlottableRecords(vars::PlottableVars, J::AbstractArray) =\n PlottableRecords{map(typeof,(vars,J))...}(vars, J)\nPlottableRecords(vars::PlottableVars, fluxval::Number, fluxaxes::Tuple, tspan::AbstractRange) = begin\n vars = build_vars(vars, tspan)\n J = build_flux(fluxval, fluxaxes..., tspan)\n PlottableRecords(vars, J)\nend\n\n@plottable struct Records{V,F} <: AbstractRecords\n vars::V | false\n J::F | false\nend\nRecords(vars::Vars, J::AbstractArray) =\n Records{map(typeof,(vars,J))...}(vars, J)\nRecords(vars::Vars, fluxval::Number, fluxaxes::Tuple) = begin\n J = build_flux(fluxval, fluxaxes...)\n Records{map(typeof, (vars,J))...}(vars, J)\nend\n\nbuild_flux(fluxval, x::Tuple, y::Tuple) = begin\n dims = X(Val(x)), Y(Val(y))\n A = zeros(typeof(fluxval), map(length, dims)...)\n DimensionalArray(A, dims)\nend\nbuild_flux(fluxval, x::Tuple, y::Tuple, time::AbstractRange) = begin\n dims = X(Val(x)), Y(Val(y)), Ti(time)\n A = zeros(typeof(fluxval), map(length, dims)...)\n DimensionalArray(A, dims)\nend\n\n\n\"\"\"\nA an Organism is a model object for modelling the growth\nof a single organism.\n\nIt can be run as a functor:\n\n```julia\n(o::AbstactOrganism)(du, u, p, t) =\n...\n```\n\nSo that it can be passed into DifferentialEquations.jl solvers\nif required.\n\nWhere `du` is the flux to be updated, `u` is the current state, \n`p` are new model paremeters or `nothing`, and `t` is the current\ntime step. See model.jl for implemntations.\n\nWhen julia 1.5 is released this will be implemented for any \n`AbstactOrganism`, but for now it is only implemented for `Plant`\ndue to current limitations in Julia.\n\"\"\"\nabstract type AbstractOrganism end\n\nparams(o::AbstractOrganism) = o.params\nshared(o::AbstractOrganism) = o.shared\nrecords(o::AbstractOrganism) = o.records\norgans(o::AbstractOrganism) = o.organs\nenvironment(o::AbstractOrganism) = o.environment\nenvironment_start(o::AbstractOrganism) = o.environment_start\ndead(o::AbstractOrganism) = o.dead[]\nset_dead!(o::AbstractOrganism, val) = o.dead[] = val\n\n\"\"\"\n define_organs(o::AbstractOrganism, t)\n\nOrgans are constructed with views of Records and J Arrays at time t\n\"\"\"\ndefine_organs(o::AbstractOrganism, t) =\n define_organs(params(o), shared(o), records(o), t)\ndefine_organs(params::Tuple, shared, records::Tuple, t) =\n map((p, r) -> Organ(p, shared, r), params, records)\n\nupdate_organs(organs, t) = update_organs(vars(first(organs)), organs, t)\nupdate_organs(::Vars, organs, t) = organs\nupdate_organs(::PlottableVars, organs, t) = begin\n i = floor(Int, ustrip(t))\n map(organs) do organ\n organ.vars.tstep[1] = i\n J = organ.J\n data = J.data\n @set! data.indices[3] = i\n @set! data.offset1 = (i - 1) * length(data.indices[1]) * length(data.indices[2]) \n # Setfield.jl isn't type-stable, DD `rebuild` is better\n @set! organ.J = DimensionalData.rebuild(J, data)\n organ\n end\nend\n\n\"\"\"\n Plant(params, shared, records, environment, environment_start, dead)\n Plant(states=(:V, :C, :N),\n transformations=(:asi, :gro, :mai, :rej, :res),\n params=(ShootParamsCN(), RootParamsCN()),\n vars=(Vars(), Vars()),\n shared=SharedParams(),\n records=nothing,\n environment=nothing,\n time=0.0hr:1.0hr:8760.0hr,\n environment_start=Ref(1.0hr),\n dead=Ref(false))\n\n\nPlant model.\n\n`params` are a tuple of Parameters objects, one for each organ.\n\n`shared` is a struct of parameters shared between organs.\n\n`vars`: can be `Vars` or `PlottableVars` or custom struct with additional variables.\n `PlottableVars` will be stored for each timestep for plotting.\n\n`environment` can be `nothing`, or a `MicroclimPoint` or `MicroclimControl`\nfrom Microclimates.jl\n\n`time` determines the timespan over which `PlottableVars` will be constructed.\nit isn't used with regular `Vars`.\n\nIf 4 state model is used, pass in\n```julia\nstates=(:V, :E, :C, :N),\n```\n\nSimilarly, if additional components like Maturity or ActiveTranslocation \nare used, their state label needs to be passed in:\n\n```julia\ntransformations=(:asi, :gro, :mai, :mat, :rej, :tra, :res),\n```\n\"\"\"\n@flattenable @description mutable struct Plant{P,S,R,O,E,ES,D} <: AbstractOrganism\n params::P | true | \"Model parameters\"\n shared::S | true | \"Parameters shared between organs\"\n records::R | false | \"Plotable variables stored in arrays and sliced for each timestep on demand\"\n organs::O | false | \"\"\n environment::E | false | \"Environment object, provides environmental variables for each timestep\"\n environment_start::ES | false | \"Start index of environmental data\"\n dead::D | false | \"`Bool` flag: has the plant died\"\n Plant(params::P, shared::S, records::R, organs::O, environment::E, environment_start::ES, dead::D) where {P,S,R,O,E,ES,D} = begin\n organs = define_organs(params, shared, records, 0)\n new{P,S,R,typeof(organs),E,ES,D}(params, shared, records, organs, environment, environment_start, dead)\n end\nend\nPlant(; states=(:V, :C, :N),\n transformations=(:asi, :gro, :mai, :rej, :tra, :res),\n params=(\n Params(assimilation_pars=KooijmanSLAPhotosynthesis()),\n Params(assimilation_pars=NAssim()),\n ),\n vars=(Vars(), Vars()),\n shared=SharedParams(),\n environment=nothing,\n time=0.0hr:1.0hr:8760.0hr,\n records=nothing,\n environment_start=Ref(0.0hr),\n dead=Ref(false)\n ) = begin\n fluxaxes = states, transformations\n fluxval = 1.0mol/hr\n records = build_records(records, vars, fluxval, fluxaxes, time)\n Plant(params, shared, records, nothing, environment, environment_start, dead)\nend\n\nbuild_records(records::AbstractRecords, args...) = records\nbuild_records(records::Nothing, vars::Tuple, fluxval, fluxaxes, tspan) =\n map(vars) do v\n build_records(v, fluxval, fluxaxes, tspan)\n end\nbuild_records(vars::Vars, fluxval::Number, fluxaxes::Tuple, tspan::AbstractRange) =\n Records(vars, fluxval, fluxaxes)\nbuild_records(vars::PlottableVars, fluxval::Number, fluxaxes::Tuple, tspan::AbstractRange) =\n PlottableRecords(vars, fluxval, fluxaxes, tspan)\n\n\n\n# Define a SubArray constructor so we can increment the time index\nConstructionBase.constructorof(::Type{A}) where A<:SubArray{T,N,P,I,L} where {T,N,P,I,L} =\n (parent, indices, offset1, stride1) -> begin\n SubArray{eltype(parent),ndims(parent),typeof(parent),typeof(indices),L}(parent, indices, offset1, stride1)\n end\n", "meta": {"hexsha": "1e0a169754978c678087cb80856d5caa05fa43b9", "size": 13688, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/organism.jl", "max_stars_repo_name": "elchudi/DynamicEnergyBudgets.jl", "max_stars_repo_head_hexsha": "e6969bd10407e4beb3bf60ca2b769ee96bd9d213", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-03T13:42:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-03T13:42:30.000Z", "max_issues_repo_path": "src/organism.jl", "max_issues_repo_name": "elchudi/DynamicEnergyBudgets.jl", "max_issues_repo_head_hexsha": "e6969bd10407e4beb3bf60ca2b769ee96bd9d213", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-16T13:34:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T20:14:43.000Z", "max_forks_repo_path": "src/organism.jl", "max_forks_repo_name": "elchudi/DynamicEnergyBudgets.jl", "max_forks_repo_head_hexsha": "e6969bd10407e4beb3bf60ca2b769ee96bd9d213", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-06-21T06:17:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T13:46:15.000Z", "avg_line_length": 34.653164557, "max_line_length": 133, "alphanum_fraction": 0.6396113384, "num_tokens": 3790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24659796173180124}} {"text": "# MIT License\r\n\r\n# Copyright (c) 2021 Dr. William A. Pisani\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n# SOFTWARE.\r\n\"\"\"\r\n impropers(bonds::Array{Array{Int64,N} where N,1}) -> Array{NTuple{4,Int64},1}\r\n\r\nDetermines the impropers of a molecule or molecular system given the bonds.\r\n\"\"\"\r\nfunction impropers(bonds::Array{Array{Int64,N} where N,1})\r\n println(\"Determining impropers...\")\r\n count_atomid1s = countmap(atomid[1] for atomid in bonds)\r\n count_atomid2s = countmap(atomid[2] for atomid in bonds)\r\n count_atomids = mergewith(+,count_atomid1s,count_atomid2s)\r\n\r\n # Get atomids with 3 or more bonds, those atoms have impropers\r\n atomids = [key for (key,value) in count_atomids if value >= 3]\r\n\r\n improper_array = Tuple{Int64,Int64,Int64,Int64}[]\r\n\r\n # Find atom ids connected to improper atoms\r\n for atomid in atomids\r\n atomid_connections = []\r\n for bond in bonds\r\n if atomid == bond[1]\r\n push!(atomid_connections,bond[2])\r\n elseif atomid == bond[2]\r\n push!(atomid_connections,bond[1])\r\n end\r\n end\r\n\r\n # Now that connections are found, get combinations of impropers\r\n if length(atomid_connections) == 3 # If only three bonds\r\n imp = (atomid_connections[1],atomid,atomid_connections[2],atomid_connections[3])\r\n push!(improper_array,imp)\r\n\r\n elseif length(atomid_connections) == 4 # If four bonds\r\n imp = (atomid_connections[1],atomid,atomid_connections[2],atomid_connections[3]) # 1-2-3\r\n push!(improper_array,imp)\r\n\r\n imp = (atomid_connections[2],atomid,atomid_connections[3],atomid_connections[4]) # 2-3-4\r\n push!(improper_array,imp)\r\n\r\n imp = (atomid_connections[1],atomid,atomid_connections[2],atomid_connections[4]) # 1-2-4\r\n push!(improper_array,imp)\r\n\r\n imp = (atomid_connections[1],atomid,atomid_connections[3],atomid_connections[4]) # 1-3-4\r\n push!(improper_array,imp)\r\n\r\n end\r\n end\r\n println(\"Impropers determined!\")\r\n return improper_array\r\nend", "meta": {"hexsha": "a9856ff9e9f9d28456a0c8bc78f6d332552ccc22", "size": 3133, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Get_Topology_From_Bonds/impropers.jl", "max_stars_repo_name": "wapisani/CompMatSciTools", "max_stars_repo_head_hexsha": "8d04a5ca3e91020686a2eec40be6bba4f6d31102", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Get_Topology_From_Bonds/impropers.jl", "max_issues_repo_name": "wapisani/CompMatSciTools", "max_issues_repo_head_hexsha": "8d04a5ca3e91020686a2eec40be6bba4f6d31102", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Get_Topology_From_Bonds/impropers.jl", "max_forks_repo_name": "wapisani/CompMatSciTools", "max_forks_repo_head_hexsha": "8d04a5ca3e91020686a2eec40be6bba4f6d31102", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T01:40:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T01:40:04.000Z", "avg_line_length": 44.1267605634, "max_line_length": 101, "alphanum_fraction": 0.6836897542, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24638901993027698}} {"text": "\nconst ERFA_DPI = 3.141592653589793\nconst ERFA_D2PI = 6.283185307179586\nconst ERFA_DR2D = 57.29577951308232\nconst ERFA_DD2R = 0.017453292519943295\nconst ERFA_DR2AS = 206264.80624709636\nconst ERFA_DAS2R = 4.84813681109536e-6\nconst ERFA_DS2R = 7.27220521664304e-5\nconst ERFA_TURNAS = 1.296e6\nconst ERFA_DMAS2R = ERFA_DAS2R / 1000.0\nconst ERFA_DTY = 365.242198781\nconst ERFA_DAYSEC = 86400.0\nconst ERFA_DJY = 365.25\nconst ERFA_DJC = 36525.0\nconst ERFA_DJM = 365250.0\nconst ERFA_DJ00 = 2.451545e6\nconst ERFA_DJM0 = 2.4000005e6\nconst ERFA_DJM00 = 51544.5\nconst ERFA_DJM77 = 43144.0\nconst ERFA_TTMTAI = 32.184\nconst ERFA_DAU = 1.4959787e11\nconst ERFA_CMPS = 2.99792458e8\nconst ERFA_AULT = 499.004782\nconst ERFA_DC = ERFA_DAYSEC / ERFA_AULT\nconst ERFA_ELG = 6.969290134e-10\nconst ERFA_ELB = 1.550519768e-8\nconst ERFA_TDB0 = -6.55e-5\nconst ERFA_SRS = 1.97412574336e-8\n\n# Skipping MacroDefinition: ERFA_DINT ( A ) ( ( A ) < 0.0 ? ceil ( A ) : floor ( A ) )\n# Skipping MacroDefinition: ERFA_DNINT ( A ) ( ( A ) < 0.0 ? ceil ( ( A ) - 0.5 ) : floor ( ( A ) + 0.5 ) )\n# Skipping MacroDefinition: ERFA_DSIGN ( A , B ) ( ( B ) < 0.0 ? - fabs ( A ) : fabs ( A ) )\n# Skipping MacroDefinition: ERFA_GMAX ( A , B ) ( ( ( A ) > ( B ) ) ? ( A ) : ( B ) )\n# Skipping MacroDefinition: ERFA_GMIN ( A , B ) ( ( ( A ) < ( B ) ) ? ( A ) : ( B ) )\n\nconst ERFA_WGS84 = 1\nconst ERFA_GRS80 = 2\nconst ERFA_WGS72 = 3\n\nimmutable Array_3_Cdouble\n d1::Cdouble\n d2::Cdouble\n d3::Cdouble\nend\n\nzero(::Type{Array_3_Cdouble}) = Array_3_Cdouble(fill(zero(Cdouble),3)...)\n\nimmutable Array_3_Array_3_Cdouble\n d1::Array_3_Cdouble\n d2::Array_3_Cdouble\n d3::Array_3_Cdouble\nend\n\nzero(::Type{Array_3_Array_3_Cdouble}) = Array_3_Array_3_Cdouble(fill(zero(Array_3_Cdouble),3)...)\n\ntype eraASTROM\n pmt::Cdouble\n eb::Array_3_Cdouble\n eh::Array_3_Cdouble\n em::Cdouble\n v::Array_3_Cdouble\n bm1::Cdouble\n bpn::Array_3_Array_3_Cdouble\n along::Cdouble\n phi::Cdouble\n xpl::Cdouble\n ypl::Cdouble\n sphi::Cdouble\n cphi::Cdouble\n diurab::Cdouble\n eral::Cdouble\n refa::Cdouble\n refb::Cdouble\nend\n\nimmutable Array_2_Array_3_Cdouble\n d1::Array_3_Cdouble\n d2::Array_3_Cdouble\nend\n\nzero(::Type{Array_2_Array_3_Cdouble}) = Array_2_Array_3_Cdouble(fill(zero(Array_3_Cdouble),2)...)\n\nimmutable eraLDBODY\n bm::Cdouble\n dl::Cdouble\n pv::Array_2_Array_3_Cdouble\nend\n\nimmutable Array_4_Cint\n d1::Cint\n d2::Cint\n d3::Cint\n d4::Cint\nend\n\nzero(::Type{Array_4_Cint}) = Array_4_Cint(fill(zero(Cint),4)...)\n\nimmutable Array_2_Cdouble\n d1::Cdouble\n d2::Cdouble\nend\n\nzero(::Type{Array_2_Cdouble}) = Array_2_Cdouble(fill(zero(Cdouble),2)...)\n", "meta": {"hexsha": "641e1721f542c2bb51608a48bae09696afcafab8", "size": 2662, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/erfa_common.jl", "max_stars_repo_name": "nirinA/ERFA.jl", "max_stars_repo_head_hexsha": "4356db65995be41703ad33457c72544182b2c136", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/erfa_common.jl", "max_issues_repo_name": "nirinA/ERFA.jl", "max_issues_repo_head_hexsha": "4356db65995be41703ad33457c72544182b2c136", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/erfa_common.jl", "max_forks_repo_name": "nirinA/ERFA.jl", "max_forks_repo_head_hexsha": "4356db65995be41703ad33457c72544182b2c136", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5961538462, "max_line_length": 107, "alphanum_fraction": 0.6994740796, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.24606851654690745}} {"text": "\"\"\" \n mutable struct Replica{AS<:AbstractSampler}\n\nReplica type for replica exchange Monte Carlo. A Sunny sampler type must\nbe provided during construction.\n\"\"\"\nmutable struct Replica{AS <: AbstractSampler}\n rank::Int64 # MPI rank of sampler is ∈ [0, N_ranks-1]\n N_ranks::Int64 # Total number of MPI ranks (samplers, replicas) \n N_rex_up::Int64 # Count of total number of attempted exchanges btw. replicas (i, i+1)\n rex_dir::Int64 # Replica's current exchange direction (\"up\"=2, \"down\"=1)\n α::Float64 # The current value for control parameter\n nn_ranks::Vector{Int64} # MPI ranks of nearest-neighbor samplers, -1 signals no neighbor\n label::Int64 # Label for replica control parameter tracking. Starts as N_ranks+rank+1,\n # and updates as swaps occur. Label is < 0 when last α is most recently\n # visited and > 0 when first α most recently visited\n N_up::Int64 # Number of exchanges with replica most recently visiting first α\n N_down::Int64 # Number of exchanges with replica most recently visiting last α\n sampler::AS # Sampler containing/updating this replica's system\nend\n\n\"\"\"\nInitialize MPI and return process rank, number of ranks\n\"\"\"\nfunction init_MPI()\n if !MPI.Initialized()\n MPI.Init()\n end\n return (MPI.Comm_rank(MPI.COMM_WORLD), MPI.Comm_size(MPI.COMM_WORLD))\nend\n\n\"\"\"\nConstructor which initializes MPI communicator and sets sampler. -> Use on\nsingle communicator with no groups for now\n\"\"\"\nfunction Replica(sampler::AS, α::Float64) where {AS <: AbstractSampler}\n # MPI must be initialized by user after importing MPI\n if !MPI.Initialized()\n println(\"\"\"MPI not initialized. Please add \"MPI.Init()\" at start of script\"\"\")\n exit(-1)\n end\n\n rank = MPI.Comm_rank(MPI.COMM_WORLD)\n N_ranks = MPI.Comm_size(MPI.COMM_WORLD)\n\n Random.seed!(round(Int64, time()*1000))\n\n # Even rank exch. down when rex_dir==1, up when rex_dir==2\n nn_ranks = [rank-1, rank+1]\n\n # First and last replicas only exch. in one dir.\n for i in 1:2\n if (nn_ranks[i] < 0) || (nn_ranks[i] > N_ranks-1)\n nn_ranks[i] = -1\n end\n end\n\n # Start extremal ranks with up/down trip direction\n if rank == 0\n label = 1\n elseif rank == N_ranks-1\n label = -N_ranks\n else\n label = N_ranks + rank+1\n end\n\n # Start even ranks exchanging down\n rex_dir = (rank % 2 == 0) ? 1 : 2\n\n return Replica(rank, N_ranks, 0, rex_dir, α, nn_ranks, label, 0, 0, 0, sampler)\nend\n\n\"\"\"\nPropose and accept/reject a replica exchange. -> Swap spin configurations\ninstead of the α's for now (no bookkeeping or master proc. needed). -> Use\ndeterministic even/odd scheme.\n\"\"\"\nfunction replica_exchange!(replica::Replica)\n # First and last replicas only exch. in one dir.\n if replica.nn_ranks[replica.rex_dir] < 0\n return false\n end\n \n if replica.rex_dir == 2\n replica.N_rex_up += 1\n end\n\n # Rank of exchange partner\n rex_rank = replica.nn_ranks[replica.rex_dir]\n\n # Action of this rank's configuration\n S_curr = running_energy(replica.sampler) / get_temp(replica.sampler)\n\n # Backup current configuration\n backup_sites = deepcopy(replica.sampler.system.sites)\n\n # Swap trial configuration with partner\n MPI.Sendrecv!(\n backup_sites, rex_rank, 1,\n replica.sampler.system.sites, rex_rank, 1,\n MPI.COMM_WORLD\n )\n\n # This rank's action with partner's configuration\n S_exch = energy(replica.sampler.system) / get_temp(replica.sampler)\n\n # change in action due to exchange\n ΔS = S_curr - S_exch\n\n # Calculate exchange probability\n rex_accept = false\n if replica.rank < rex_rank\n rex_ΔS = MPI.Recv(Float64, rex_rank, 2, MPI.COMM_WORLD)[1]\n ln_P = ΔS + rex_ΔS\n\n # Replica exchange acceptance criterion\n if (ln_P >= 0) || (rand() < exp(ln_P))\n rex_accept = true\n end\n\n MPI.Send(rex_accept, rex_rank, 3, MPI.COMM_WORLD)\n else\n MPI.Send(ΔS, rex_rank, 2, MPI.COMM_WORLD)\n\n rex_accept = MPI.Recv(Bool, rex_rank, 3, MPI.COMM_WORLD)[1]\n end\n\n # Reject exchange\n if !rex_accept\n replica.sampler.system.sites .= backup_sites\n return false\n end\n\n # Recalculate energy and magnetization of new state\n reset_running_energy!(replica.sampler)\n reset_running_mag!(replica.sampler)\n\n return true\nend\n\n\"\"\"\nExchange labels between two replicas. \n\nEach replica has a label that starts as (N_ranks + rank+1) until the replica\nreaches an extremal temperature, after which the label ∈ [1, N_ranks]. Labels\nare > 0 after most recently visiting first α and < 0 after most recently \nvisiting lasst α\n\nThe label trip direction (±) is used to calculate replica flow for FBOPT and\nused to track all replica trajectories.\n\nTODO: use to calculate average round-trip time for replicas\n\"\"\"\nfunction label_exchange!(replica::Replica, rex_rank::Int64)\n # Exchange labels\n rex_label = [0]\n MPI.Sendrecv!(\n [replica.label], rex_rank, 4,\n rex_label, rex_rank, 4, \n MPI.COMM_WORLD\n )\n replica.label = rex_label[1]\n\n # Set label of replica as initialized (has trip direction)\n if (replica.rank == 0) || (replica.rank == replica.N_ranks-1)\n if replica.label > replica.N_ranks\n replica.label -= replica.N_ranks\n end\n end\n\n # Change the trip direction when α extrema are reached\n if (replica.rank == 0) && (replica.label < 0)\n replica.label *= -1\n elseif (replica.rank == replica.N_ranks-1) && (replica.label > 0)\n replica.label *= -1\n end\n\n return nothing\nend\n\n\"\"\"\nGather data from each process and print to specified filename\n-> only handle 1D data buffer right now\n\"\"\"\nfunction gather_print(replica::Replica, data, fname::String)\n # Have root (rank 0) gather data from all processes\n data_all = MPI.Gather(data, 0, MPI.COMM_WORLD)\n\n # Write gathered data to file w/ column formatting\n if replica.rank == 0\n data_all = reshape(data_all, :, replica.N_ranks)\n\n f = open(fname, \"w\")\n for data_c in eachcol(data_all)\n for val in data_c \n print(f, val, \"\\t\")\n end\n print(f, \"\\n\")\n end\n close(f)\n end\n\n return nothing\nend\n\n\"\"\"\nPrint xyz formatted (Lx, Ly, Lz, Sx, Sy, Sz) configurations to file \n\"\"\"\nfunction xyz_to_file(sys::SpinSystem, output::IOStream)\n sites = reinterpret(reshape, Float64, sys.lattice)\n spins = reinterpret(reshape, Float64, sys.sites)\n xyz = vcat(sites, spins)\n xyz = reshape(xyz, 6, :)\n\n for c in eachcol(xyz)\n @printf(output, \"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\", c...)\n end\n println(output, \"\")\n\n return nothing\nend\n\n\"\"\" \nUpdate α schedule using feedback-optimization scheme from\nKatzgraber et. al. (https://arxiv.org/pdf/cond-mat/0602085v3.pdf).\n\nNote: use f(α) that goes from fist α → last α instead of original paper\nNote: use (k-1)/(M-1) as target for integral in Eq. 11 instead of k/M \n\"\"\"\nfunction feedback_update!(replica::Replica, set_α!::F; w::Float64=0.0, dα′::Float64=1e-5) where {F <: Function}\n # Storage for collecting updated α\n _α = [replica.α]\n\n # Replica flow\n N_labeled = (replica.N_up + replica.N_down)\n f = (N_labeled > 0) ? replica.N_down/N_labeled : 0.0\n\n # Gather α and replica flow 'f' from all replicas\n all_α_and_f = MPI.Gather([replica.α, f], 0, MPI.COMM_WORLD)\n\n if replica.rank == 0\n all_α_and_f = reshape(all_α_and_f, :, replica.N_ranks)\n α = all_α_and_f[1, :]\n f = all_α_and_f[2, :]\n \n M = replica.N_ranks\n L = collect(range(0, 1.0, length=M))\n\n # Use 'smoothed replica flow' from Hamze et. al. (https://arxiv.org/pdf/1004.2840.pdf)\n fs = (1-w).*f .+ (w .* L)\n\n # Use crude linear approximation for df/dα\n Δf = fs[2:end] .- fs[1:end-1] \n Δf[Δf .< 0] .= 0.0\n\n Δα = α[2:end] .- α[1:end-1]\n\n # Calculated normalized density for adjusted α's\n η = sqrt.( (Δf ./ Δα) ./ Δα )\n C = sum(η .* Δα)\n η ./= C\n\n # New α's have fixed end points\n α_new = zeros(M)\n α_new[1] = α[1]\n α_new[M] = α[M]\n\n α′= α[1]\n cηf = 0.0\n pos = 2\n\n # find new α's using Eq. 11 from Katzgraber et. al.\n for i in 1:M-1\n for j in 1:Int(round(Δα[i]/dα′))\n cηf += η[i]*dα′\n α′+= dα′\n\n if (cηf >= L[pos]) && (pos < M)\n α_new[pos] = α′\n pos += 1\n end\n end\n end\n\n # Send out updated α to all replicas\n MPI.Scatter!(MPI.UBuffer(α_new, 1), _α, 0, MPI.COMM_WORLD)\n else\n MPI.Scatter!(nothing, _α, 0, MPI.COMM_WORLD)\n end\n\n # Assign new value of α and set in replica sampler\n # -> corresponds to update of kT or other Hamiltonian parameter\n set_α!(replica, _α[1])\n\n return nothing\nend\n\n\"\"\"\nRun a feedback-optimized parallel tempering simulation and return an optimized\ntemperature set. No measurements are made, but this is used to diagnose replica\nflow in PT simulations. \n\n# Arguments\n- `replica::Replica`: Replica type that contains MPI info and system data\n\n- `set_α!::Function`: User-provided function for setting control parameters\n in the replica's sampler or system. Needs form: set_α!(::Replica, ::Float64)\n\n- `therm_mcs::Int64`: Number of initial thermalization MC sweeps\n\n- `rex_interval::Int64`: Number of MC sweeps between replica exchange attempts\n\n- `max_mcs_opt::Int64`: Maximum number of MC sweeps to allow during optimization\n\n- `update_interval::Int64`: Number of MC sweeps between feedback updates\n\n- `w::Float64`: Damping factor (w ∈ [0,1]) for feedback updates: 0 gives\n aggressive updates, 1 gives leaves set of α unchanged\n\n- `dα′::Float64`: Step size for integration during feedback update\n\n- `print_ranks_trajectory::Vector{Float64}`: If an MPI rank is in this array, the \n timeseries for the replica starting with this rank will printed to file\n\n- `trajectory_interval::Int64`: Number of replica exchange attempts between printed\n timeseries points\n\n\"\"\"\nfunction run_FBO!(\n replica::Replica,\n set_α!::F;\n therm_mcs::Int64=1000,\n rex_interval::Int64=1,\n max_mcs::Int64=500_000,\n update_interval::Int64=100_000,\n w::Float64=0.0,\n dα′::Float64=1e-5,\n print_ranks_trajectory::Vector{Int64}=Int64[],\n trajectory_interval::Int64=500_000\n) where {F <: Function}\n\n # Initialize energy and equilibrate replica to it's distribution\n reset_running_energy!(replica.sampler)\n reset_running_mag!(replica.sampler)\n\n thermalize!(replica.sampler, therm_mcs)\n\n replica.sampler.nsweeps = 1\n\n rex_accepts = zeros(Int64, 2)\n N_updates = 0\n N_rex = 0\n\n # Start feedback optimization simulation\n for mcs in 1:max_mcs\n sample!(replica.sampler)\n\n if (replica.rank == 0) && (mcs % 1000 == 0)\n println(\"FBO \", mcs, \" mcs\")\n end\n\n # Attempt replica exchange\n if mcs % rex_interval == 0\n N_rex += 1\n\n if replica_exchange!(replica)\n rex_accepts[replica.rex_dir] += 1\n\n # Exchange labels\n label_exchange!(replica, replica.nn_ranks[replica.rex_dir])\n end\n\n # Record replica flow \n if replica.nn_ranks[replica.rex_dir] != -1\n if replica.label < 0\n replica.N_down += 1\n elseif replica.label < replica.N_ranks+1\n replica.N_up += 1\n end\n end\n\n # Print out replica exchange timeseries -- inefficient IO\n if (N_rex % trajectory_interval == 0) && (abs(replica.label)-1 in print_ranks_trajectory)\n if replica.label <= replica.N_ranks\n fname = @sprintf(\"FBO-update%03d_trajectory%03d.dat\", N_updates, abs(replica.label)-1)\n output = open(fname, \"a\")\n println(output, replica.rank)\n close(output)\n end\n end\n\n # Alternate up/down pairs of replicas for exchanges\n replica.rex_dir = 3 - replica.rex_dir\n end\n\n if mcs % update_interval == 0\n # Replica flow 'f' and smoothed replica flow 'fs'\n N_labeled = (replica.N_up + replica.N_down)\n f = (N_labeled > 0) ? replica.N_down/N_labeled : 0.0\n fs = (1-w)*f + w*replica.rank/(replica.N_ranks-1)\n\n # Acceptance rate between replicas i and i+1\n A = (replica.rank == replica.N_ranks-1) ? 0.0 : rex_accepts[2]/replica.N_rex_up\n\n # Print out α, replica flow, and acceptance rates for each update\n fname = @sprintf(\"FBO-update%03d.dat\", N_updates)\n gather_print(\n replica,\n [replica.α, fs, A],\n fname\n )\n\n # Perform feedback optimization for control parameters\n feedback_update!(replica, set_α!; w=w, dα′=dα′)\n\n N_updates += 1\n rex_accepts[1] = rex_accepts[2] = 0\n reset_stats!(replica)\n end\n end\n\n rex_accepts[1] = rex_accepts[2] = 0\n reset_stats!(replica)\n\n # Return a vector of optimized α's\n return MPI.Allgather([replica.α], MPI.COMM_WORLD)\nend\n\n\"\"\"\nReset the exchange statistics and labels stored in replica\n\"\"\"\nfunction reset_stats!(replica::Replica)\n replica.N_up = replica.N_down = 0\n replica.N_rex_up = 0\n\n # Reset label\n if replica.rank == 0\n replica.label = 1\n elseif replica.rank == replica.N_ranks-1\n replica.label = -replica.N_ranks\n else\n replica.label = replica.N_ranks + replica.rank+1\n end\n return nothing\nend\n\n\"\"\"\nStart a parallel tempering (PT) simulation that saves measured averages,\nhistograms, minimal energies, and configurations.\n\nRun w/ the command \"mpiexec -n [n_procs] julia --project [julia_script.jl]\".\n\n# Arguments\n- `replica::Replica`: Replica type that contains MPI info and system data\n\n- `therm_mcs::Int64`: Number of initial thermalization MC sweeps\n\n- `measure_interval::Int64`: Number of MC sweeps between measurements\n\n- `rex_interval::Int64`: Number of MC sweeps between replica exchange attempts\n\n- `max_mcs::Int64`: Maximum number of MC sweeps to allow during simulation\n\n- `bin_size::Float64`: Width in energy space for each histogram bin\n\n- `print_hist::Bool`: Print energy histograms to file for each rank if true\n\n- `print_xyz_ranks::Vector{Float64}`: If an MPI rank is in this array, the xyz\n coordinates for new minimal energies are printed to file\n\n- `print_ranks_trajectory::Vector{Float64}`: If an MPI rank is in this array, the \n timeseries for the replica starting with this rank will printed to file\n\n- `trajectory_interval::Int64`: Number of replica exchange attempts between printed\n timeseries points\n\n- `measure_replica_flow::Bool`: If true, then the flux of downward replica flow in \n α space is measured and printed after the simulation\n\n\"\"\"\nfunction run_REMC!(\n replica::Replica; \n therm_mcs::Int64=1000, \n measure_interval::Int64=10, \n rex_interval::Int64=1, \n max_mcs::Int64=1_000_000, \n bin_size::Float64=1.0, \n print_hist::Bool=false, \n print_xyz_ranks::Vector{Int64}=Int64[],\n print_ranks_trajectory::Vector{Int64}=Int64[],\n trajectory_interval::Int64=1_000_000,\n measure_replica_flow::Bool=false\n)\n # Initialize energy and equilibrate replica to it's distribution\n reset_running_energy!(replica.sampler)\n reset_running_mag!(replica.sampler)\n\n thermalize!(replica.sampler, therm_mcs)\n \n replica.sampler.nsweeps = 1\n\n # Manually include these basic measurements for now\n U = 0.0\n U² = 0.0\n M⃗ = [0.0, 0.0, 0.0]\n M = 0.0\n M² = 0.0\n C = 0.0\n X = 0.0\n\n system_size = length(replica.sampler.system)\n Emin = typemax(Float64)\n E_hist = BinnedArray{Float64, Int64}(bin_size=bin_size)\n m_hist = BinnedArray{Float64, Int64}(bin_size=1.0)\n rex_accepts = zeros(Int64, 2)\n N_measure = 0\n N_rex = 0\n\n # Start PT with finite length\n for mcs in 1:max_mcs\n sample!(replica.sampler)\n\n # Crude progress printing to stdout\n if (replica.rank == 0) && (mcs % 1000 == 0)\n println(\"REMC \", mcs, \" mcs\")\n end\n\n # Attempt replica exchange\n if mcs % rex_interval == 0 \n N_rex += 1\n\n if replica_exchange!(replica)\n rex_accepts[replica.rex_dir] += 1\n\n # Exchange labels\n if measure_replica_flow\n label_exchange!(replica, replica.nn_ranks[replica.rex_dir])\n end\n end\n\n # Record replica flow (for quality evaluation) \n if measure_replica_flow && replica.nn_ranks[replica.rex_dir] != -1\n if replica.label < 0\n replica.N_down += 1\n elseif replica.label < replica.N_ranks+1\n replica.N_up += 1\n end\n end\n\n # Print out replica exchange timeseries -- inefficient IO\n if (N_rex % trajectory_interval == 0) && (abs(replica.label)-1 in print_ranks_trajectory)\n if replica.label <= replica.N_ranks\n fname = @sprintf(\"trajectory%03d.dat\", abs(replica.label)-1)\n rex_output = open(fname, \"a\")\n println(rex_output, replica.rank)\n close(rex_output)\n end\n end\n\n # Alternate up/down pairs of replicas for exchanges\n replica.rex_dir = 3 - replica.rex_dir\n end\n\n # Measurements\n if mcs % measure_interval == 0\n E = running_energy(replica.sampler)\n m⃗ = running_mag(replica.sampler)\n m = norm(m⃗)\n\n # New minimum energy measured\n if E < Emin\n Emin = E\n\n # Print out evolution of Emin w.r.t MC time\n f = open(@sprintf(\"Emin%03d.dat\", replica.rank), \"a\")\n println(f, mcs,\" \",Emin)\n close(f)\n\n # Overwrite Emin coordinates in saved file\n if replica.rank in print_xyz_ranks\n xyz_output = open(@sprintf(\"Emin%03d.xyz\", replica.rank), \"w\")\n xyz_to_file(replica.sampler.system, xyz_output)\n close(xyz_output)\n end\n end\n\n U += E\n U² += E^2\n M⃗ .+= m⃗\n M += m\n M² += m^2\n N_measure += 1\n\n # Histograms for energy and magnetization\n E_hist[E] += 1\n m_hist[m] += 1\n end\n end\n\n # Normalize averages\n kT = get_temp(replica.sampler)\n U /= N_measure\n U² /= N_measure\n M⃗ ./= N_measure\n M /= N_measure\n M² /= N_measure\n C = 1.0/kT^2 * (U² - U^2)\n X = 1.0/kT * (M² - M^2)\n\n # Acceptance rate between replicas i and i+1\n A = (replica.rank == replica.N_ranks-1) ? 0.0 : rex_accepts[2]/replica.N_rex_up\n\n # Gather and print: rank, \"down\" exch. accepts, \"up\" exch. accepts, acceptance ratio \n gather_print(\n replica, \n [replica.α, A], \n \"replica_exchanges.dat\"\n )\n\n # Gather and print thermodynamic measurements\n gather_print(\n replica, \n [replica.α, (M⃗ ./ system_size)..., M/system_size, X/system_size, U/system_size, C/system_size], \n \"measurements.dat\"\n )\n\n # Write histogram to file for each process if specified\n if print_hist\n f = open(@sprintf(\"E-hist%03d.dat\", replica.rank), \"w\")\n println(f, E_hist)\n close(f)\n f = open(@sprintf(\"m-hist%03d.dat\", replica.rank), \"w\")\n println(f, m_hist)\n close(f)\n end\n \n # Print replica flow 'f' to file\n if measure_replica_flow\n N_labeled = (replica.N_up + replica.N_down) \n f = (N_labeled > 0) ? replica.N_down/N_labeled : 0.0\n\n gather_print(\n replica,\n [replica.α, f],\n \"replica_flow.dat\"\n )\n end\n\n return :SUCCESS\nend\n\n", "meta": {"hexsha": "8c79056db9f48796e7bbc91ffc6742f5891395b7", "size": 20331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ReplicaExchangeMC.jl", "max_stars_repo_name": "sakibmatin/Sunny.jl", "max_stars_repo_head_hexsha": "d2d25638872b1f1edee60e56382e46859a63e422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-03T20:35:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:06:13.000Z", "max_issues_repo_path": "src/ReplicaExchangeMC.jl", "max_issues_repo_name": "sakibmatin/Sunny.jl", "max_issues_repo_head_hexsha": "d2d25638872b1f1edee60e56382e46859a63e422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-11-01T17:43:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T17:28:34.000Z", "max_forks_repo_path": "src/ReplicaExchangeMC.jl", "max_forks_repo_name": "sakibmatin/Sunny.jl", "max_forks_repo_head_hexsha": "d2d25638872b1f1edee60e56382e46859a63e422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-02T19:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:29:43.000Z", "avg_line_length": 31.1825153374, "max_line_length": 111, "alphanum_fraction": 0.6103487285, "num_tokens": 5538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24605921495046956}} {"text": "using Random\nusing CUDAdrv\nusing CUDAnative\nusing CuArrays\nusing StaticArrays\nusing GPUifyLoops # for @unroll macro\n\n# Base.@propagate_inbounds function Base.getindex(v::MArray, i::Int)\n# @boundscheck checkbounds(v,i)\n# T = eltype(v)\n# \n# @assert isbitstype(T) \"Only isbits is supported on the device\"\n# return GC.@preserve v begin\n# ptr = pointer_from_objref(v)\n# dptr = reinterpret(CUDAnative.DevicePtr{T, CUDAnative.AS.Local}, ptr)\n# unsafe_load(dptr, i)\n# end\n# end\n# \n# Base.@propagate_inbounds function Base.setindex!(v::MArray, val, i::Int)\n# @boundscheck checkbounds(v,i)\n# T = eltype(v)\n# \n# @assert isbitstype(T) \"Only isbits is supported on the device\"\n# GC.@preserve v begin\n# ptr = pointer_from_objref(v)\n# dptr = reinterpret(CUDAnative.DevicePtr{T, CUDAnative.AS.Local}, ptr)\n# unsafe_store!(dptr, convert(T, val), i)\n# end\n# \n# return val\n# end\n\nfor (f, T) in Base.Iterators.product((:add, :mul, :sub), (Float32, Float64))\n name = Symbol(\"$(f)_float_contract\")\n if T === Float32\n llvmt = \"float\"\n elseif T === Float64\n llvmt = \"double\"\n end\n\n ir = \"\"\"\n %x = f$f contract $llvmt %0, %1\n ret $llvmt %x\n \"\"\"\n @eval begin\n # the @pure is necessary so that we can constant propagate.\n Base.@pure function $name(a::$T, b::$T)\n @Base._inline_meta\n Base.llvmcall($ir, $T, Tuple{$T, $T}, a, b)\n end\n end\nend\n\nimport Base: +, *, -\n\n+(a::Float64, b::Float64) = add_float_contract(a, b)\n+(a::Float32, b::Float32) = add_float_contract(a, b)\n*(a::Float64, b::Float64) = mul_float_contract(a, b)\n*(a::Float32, b::Float32) = mul_float_contract(a, b)\n-(a::Float64, b::Float64) = sub_float_contract(a, b)\n-(a::Float32, b::Float32) = sub_float_contract(a, b)\n\n# note the order of the fields below is also assumed in the code.\nconst _nstate = 5\nconst _ρ, _U, _V, _W, _E = 1:_nstate\n\nconst _nvgeo = 14\nconst _ξx, _ηx, _ζx, _ξy, _ηy, _ζy, _ξz, _ηz, _ζz, _MJ, _MJI,\n _x, _y, _z = 1:_nvgeo\n\nBase.@irrational grav 9.81 BigFloat(9.81)\nBase.@irrational gdm1 0.4 BigFloat(0.4)\n\nfunction volumerhs!(::Val{N}, rhs, Q, vgeo, gravity, D, nelem) where {N}\n Nq = N + 1\n Np = Nq ^ 3\n\n s_D = @cuStaticSharedMem eltype(D) (Nq, Nq)\n s_F = @cuStaticSharedMem eltype(Q) (Nq, Nq, _nstate)\n s_G = @cuStaticSharedMem eltype(Q) (Nq, Nq, _nstate)\n\n r_rhsρ = MArray{Tuple{Nq},eltype(rhs)}(undef)\n r_rhsU = MArray{Tuple{Nq},eltype(rhs)}(undef)\n r_rhsV = MArray{Tuple{Nq},eltype(rhs)}(undef)\n r_rhsW = MArray{Tuple{Nq},eltype(rhs)}(undef)\n r_rhsE = MArray{Tuple{Nq},eltype(rhs)}(undef)\n\n e = blockIdx().x\n j = threadIdx().y\n i = threadIdx().x\n\n common_gid = i + (j-1)*Nq + (e-1)*Np*_nvgeo\n common_qid = i + (j-1)*Nq + (e-1)*Np*_nstate\n\n # fetch D into shared\n @inbounds s_D[i, j] = D[i, j]\n\n @inbounds @unroll for k in 1:Nq\n r_rhsρ[k] = zero(eltype(rhs))\n r_rhsU[k] = zero(eltype(rhs))\n r_rhsV[k] = zero(eltype(rhs))\n r_rhsW[k] = zero(eltype(rhs))\n r_rhsE[k] = zero(eltype(rhs))\n end\n\n @inbounds @unroll for k in 1:Nq\n sync_threads()\n\n gid = common_gid + (k-1)*Nq*Nq\n\n # Load values will need into registers\n MJ = ldg(vgeo, gid + (_MJ - 1) * Np)\n ξx = ldg(vgeo, gid + (_ξx - 1) * Np)\n ξy = ldg(vgeo, gid + (_ξy - 1) * Np)\n ξz = ldg(vgeo, gid + (_ξz - 1) * Np)\n ηx = ldg(vgeo, gid + (_ηx - 1) * Np)\n ηy = ldg(vgeo, gid + (_ηy - 1) * Np)\n ηz = ldg(vgeo, gid + (_ηz - 1) * Np)\n ζx = ldg(vgeo, gid + (_ζx - 1) * Np)\n ζy = ldg(vgeo, gid + (_ζy - 1) * Np)\n ζz = ldg(vgeo, gid + (_ζz - 1) * Np)\n z = ldg(vgeo, gid + (_z - 1) * Np)\n\n qid = common_qid + (k-1)*Nq*Nq\n\n U = ldg(Q, qid + (_U - 1) * Np)\n V = ldg(Q, qid + (_V - 1) * Np)\n W = ldg(Q, qid + (_W - 1) * Np)\n ρ = ldg(Q, qid + (_ρ - 1) * Np)\n E = ldg(Q, qid + (_E - 1) * Np)\n\n P = gdm1*(E - (U^2 + V^2 + W^2)/(2*ρ) - ρ*gravity*z)\n\n ρinv = 1 / ρ\n\n fluxρ_x = U\n fluxU_x = ρinv * U * U + P\n fluxV_x = ρinv * U * V\n fluxW_x = ρinv * U * W\n fluxE_x = ρinv * U * (E + P)\n\n fluxρ_y = V\n fluxU_y = ρinv * V * U\n fluxV_y = ρinv * V * V + P\n fluxW_y = ρinv * V * W\n fluxE_y = ρinv * V * (E + P)\n\n fluxρ_z = W\n fluxU_z = ρinv * W * U\n fluxV_z = ρinv * W * V\n fluxW_z = ρinv * W * W + P\n fluxE_z = ρinv * W * (E + P)\n\n s_F[i, j, _ρ] = MJ * (ξx * fluxρ_x + ξy * fluxρ_y + ξz * fluxρ_z)\n s_F[i, j, _U] = MJ * (ξx * fluxU_x + ξy * fluxU_y + ξz * fluxU_z)\n s_F[i, j, _V] = MJ * (ξx * fluxV_x + ξy * fluxV_y + ξz * fluxV_z)\n s_F[i, j, _W] = MJ * (ξx * fluxW_x + ξy * fluxW_y + ξz * fluxW_z)\n s_F[i, j, _E] = MJ * (ξx * fluxE_x + ξy * fluxE_y + ξz * fluxE_z)\n\n s_G[i, j, _ρ] = MJ * (ηx * fluxρ_x + ηy * fluxρ_y + ηz * fluxρ_z)\n s_G[i, j, _U] = MJ * (ηx * fluxU_x + ηy * fluxU_y + ηz * fluxU_z)\n s_G[i, j, _V] = MJ * (ηx * fluxV_x + ηy * fluxV_y + ηz * fluxV_z)\n s_G[i, j, _W] = MJ * (ηx * fluxW_x + ηy * fluxW_y + ηz * fluxW_z)\n s_G[i, j, _E] = MJ * (ηx * fluxE_x + ηy * fluxE_y + ηz * fluxE_z)\n\n r_Hρ = MJ * (ζx * fluxρ_x + ζy * fluxρ_y + ζz * fluxρ_z)\n r_HU = MJ * (ζx * fluxU_x + ζy * fluxU_y + ζz * fluxU_z)\n r_HV = MJ * (ζx * fluxV_x + ζy * fluxV_y + ζz * fluxV_z)\n r_HW = MJ * (ζx * fluxW_x + ζy * fluxW_y + ζz * fluxW_z)\n r_HE = MJ * (ζx * fluxE_x + ζy * fluxE_y + ζz * fluxE_z)\n\n # one shared access per 10 flops\n @unroll for n = 1:Nq\n Dnk = s_D[n, k]\n\n r_rhsρ[n] += Dnk * r_Hρ\n r_rhsU[n] += Dnk * r_HU\n r_rhsV[n] += Dnk * r_HV\n r_rhsW[n] += Dnk * r_HW\n r_rhsE[n] += Dnk * r_HE\n end\n\n r_rhsW[k] -= MJ * ρ * gravity\n\n sync_threads()\n\n # loop of ξ-grid lines\n @unroll for n = 1:Nq\n Dni = s_D[n, i]\n Dnj = s_D[n, j]\n\n r_rhsρ[k] += Dni * s_F[n, j, _ρ]\n r_rhsρ[k] += Dnj * s_G[i, n, _ρ]\n\n r_rhsU[k] += Dni * s_F[n, j, _U]\n r_rhsU[k] += Dnj * s_G[i, n, _U]\n\n r_rhsV[k] += Dni * s_F[n, j, _V]\n r_rhsV[k] += Dnj * s_G[i, n, _V]\n\n r_rhsW[k] += Dni * s_F[n, j, _W]\n r_rhsW[k] += Dnj * s_G[i, n, _W]\n\n r_rhsE[k] += Dni * s_F[n, j, _E]\n r_rhsE[k] += Dnj * s_G[i, n, _E]\n end\n end\n\n @inbounds @unroll for k in 1:Nq\n gid = common_gid + (k-1)*Nq*Nq\n MJI = ldg(vgeo, gid + (_MJI - 1) * Np)\n\n qid = common_qid + (k-1)*Nq*Nq\n\n rhs[qid + (_U - 1) * Np] += MJI*r_rhsU[k]\n rhs[qid + (_V - 1) * Np] += MJI*r_rhsV[k]\n rhs[qid + (_W - 1) * Np] += MJI*r_rhsW[k]\n rhs[qid + (_ρ - 1) * Np] += MJI*r_rhsρ[k]\n rhs[qid + (_E - 1) * Np] += MJI*r_rhsE[k]\n end\n\n nothing\nend\n\nfunction main()\n N = 4\n nelem = 4000\n ntrials = 1\n DFloat = Float32\n\n rnd = MersenneTwister(0)\n\n Nq = N + 1\n Q = 1 .+ CuArray(rand(rnd, DFloat, Nq, Nq, Nq, _nstate, nelem))\n Q[:, :, :, _E, :] .+= 20\n vgeo = CuArray(rand(rnd, DFloat, Nq, Nq, Nq, _nvgeo, nelem))\n\n # Make sure the entries of the mass matrix satisfy the inverse relation\n vgeo[:, :, :, _MJ, :] .+= 3\n vgeo[:, :, :, _MJI, :] .= 1 ./ vgeo[:, :, :, _MJ, :]\n\n D = CuArray(rand(rnd, DFloat, Nq, Nq))\n\n rhs = CuArray(zeros(DFloat, Nq, Nq, Nq, _nstate, nelem))\n\n @cuda(threads=(N+1, N+1), blocks=nelem, maxregs=255,\n volumerhs!(Val(N), rhs, Q, vgeo, DFloat(grav), D, nelem))\n\n CUDAdrv.@profile begin\n @cuda(threads=(N+1, N+1), blocks=nelem, maxregs=255,\n volumerhs!(Val(N), rhs, Q, vgeo, DFloat(grav), D, nelem))\n end\n\n CUDAnative.@device_code dir=\"jlir\" begin\n @cuda(threads=(N+1, N+1), blocks=nelem, maxregs=255,\n volumerhs!(Val(N), rhs, Q, vgeo, DFloat(grav), D, nelem))\n end\n\n nothing\nend\n\nmain()\n", "meta": {"hexsha": "659c54858546a453e8a1fc2c08c6a80bde5e372a", "size": 8096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/volumerhs-small/volumerhs.jl", "max_stars_repo_name": "lcw/Heptapus.jl", "max_stars_repo_head_hexsha": "29292bec5fcf5c57bcf9057f19310ebcf24c95c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-03-28T12:35:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T20:23:23.000Z", "max_issues_repo_path": "examples/volumerhs-small/volumerhs.jl", "max_issues_repo_name": "lcw/Heptapus.jl", "max_issues_repo_head_hexsha": "29292bec5fcf5c57bcf9057f19310ebcf24c95c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-05-02T17:52:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-11T17:59:26.000Z", "max_forks_repo_path": "examples/volumerhs-small/volumerhs.jl", "max_forks_repo_name": "lcw/Heptapus.jl", "max_forks_repo_head_hexsha": "29292bec5fcf5c57bcf9057f19310ebcf24c95c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-03-26T21:22:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:20:23.000Z", "avg_line_length": 30.6666666667, "max_line_length": 79, "alphanum_fraction": 0.5164278656, "num_tokens": 3295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.24600160722756806}} {"text": "### Abstract MALA state\n\nabstract MALAState{F<:VariateForm} <: LMCSamplerState{F}\n\n### MALA state subtypes\n\n## UnvMALAState holds the internal state (\"local variables\") of the MALA sampler for univariate parameters\n\ntype UnvMALAState <: MALAState{Univariate}\n pstate::ParameterState{Continuous, Univariate} # Parameter state used internally by MALA\n tune::MCTunerState\n ratio::Real\n μ::Real\n\n function UnvMALAState(pstate::ParameterState{Continuous, Univariate}, tune::MCTunerState, ratio::Real, μ::Real)\n if !isnan(ratio)\n @assert ratio > 0 \"Acceptance ratio should be positive\"\n end\n new(pstate, tune, ratio, μ)\n end\nend\n\nUnvMALAState(pstate::ParameterState{Continuous, Univariate}, tune::MCTunerState=BasicMCTune()) =\n UnvMALAState(pstate, tune, NaN, NaN)\n\n## MuvMALAState holds the internal state (\"local variables\") of the MALA sampler for multivariate parameters\n\ntype MuvMALAState <: MALAState{Multivariate}\n pstate::ParameterState{Continuous, Multivariate} # Parameter state used internally by MALA\n tune::MCTunerState\n ratio::Real\n μ::RealVector\n\n function MuvMALAState(pstate::ParameterState{Continuous, Multivariate}, tune::MCTunerState, ratio::Real, μ::RealVector)\n if !isnan(ratio)\n @assert ratio > 0 \"Acceptance ratio should be positive\"\n end\n new(pstate, tune, ratio, μ)\n end\nend\n\nMuvMALAState(pstate::ParameterState{Continuous, Multivariate}, tune::MCTunerState=BasicMCTune()) =\n MuvMALAState(pstate, tune, NaN, Array(eltype(pstate), pstate.size))\n\n### Metropolis-adjusted Langevin Algorithm (MALA)\n\nimmutable MALA <: LMCSampler\n driftstep::Real\n\n function MALA(driftstep::Real)\n @assert driftstep > 0 \"Drift step is not positive\"\n new(driftstep)\n end\nend\n\nMALA() = MALA(1.)\n\n### Initialize MALA sampler\n\n## Initialize parameter state\n\nfunction initialize!{F<:VariateForm}(\n pstate::ParameterState{Continuous, F},\n parameter::Parameter{Continuous, F},\n sampler::MALA\n)\n parameter.uptogradlogtarget!(pstate)\n @assert isfinite(pstate.logtarget) \"Log-target not finite: initial value out of support\"\n @assert all(isfinite(pstate.gradlogtarget)) \"Gradient of log-target not finite: initial values out of support\"\nend\n\n## Initialize MALA state\n\nsampler_state(\n parameter::Parameter{Continuous, Univariate},\n sampler::MALA,\n tuner::MCTuner,\n pstate::ParameterState{Continuous, Univariate},\n vstate::VariableStateVector\n) =\n UnvMALAState(generate_empty(pstate), tuner_state(parameter, sampler, tuner))\n\nsampler_state(\n parameter::Parameter{Continuous, Multivariate},\n sampler::MALA,\n tuner::MCTuner,\n pstate::ParameterState{Continuous, Multivariate},\n vstate::VariableStateVector\n) =\n MuvMALAState(generate_empty(pstate), tuner_state(parameter, sampler, tuner))\n\n## Reset parameter state\n\nfunction reset!(\n pstate::ParameterState{Continuous, Univariate},\n x::Real,\n parameter::Parameter{Continuous, Univariate},\n sampler::MALA\n)\n pstate.value = x\n parameter.uptogradlogtarget!(pstate)\nend\n\nfunction reset!(\n pstate::ParameterState{Continuous, Multivariate},\n x::RealVector,\n parameter::Parameter{Continuous, Multivariate},\n sampler::MALA\n)\n pstate.value = copy(x)\n parameter.uptogradlogtarget!(pstate)\nend\n\nBase.show(io::IO, sampler::MALA) = print(io, \"MALA sampler: drift step = $(sampler.driftstep)\")\n\nBase.writemime(io::IO, ::MIME\"text/plain\", sampler::MALA) = show(io, sampler)\n", "meta": {"hexsha": "65a480801a1b1e7900dfd1146f7ff248bc93dd7b", "size": 3372, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/samplers/MALA.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Lora.jl-278398fc-db6b-536a-86ef-0b56cf867102", "max_stars_repo_head_hexsha": "d187fb6d15893413c1737dd07dafd08947edafdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/samplers/MALA.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Lora.jl-278398fc-db6b-536a-86ef-0b56cf867102", "max_issues_repo_head_hexsha": "d187fb6d15893413c1737dd07dafd08947edafdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/samplers/MALA.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Lora.jl-278398fc-db6b-536a-86ef-0b56cf867102", "max_forks_repo_head_hexsha": "d187fb6d15893413c1737dd07dafd08947edafdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8205128205, "max_line_length": 121, "alphanum_fraction": 0.7505931198, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24597395361641353}} {"text": "# version 0.1\n\nmodule EcoEvo3D\n\nusing StatsBase\n\nfunction getSampleFromArray(items)\n return sample(items)\nend\n\nfunction readLocations(filename)\n\tdat = readdlm(filename,'\\t');\n\t@inbounds w = hcat(dat[:,2],dat[:,3]);\n\tw;\nend\n\nfunction readDistanceMatrix(filename)\n\tdat = readdlm(filename,' ');\n\tdat;\nend\n\nfunction changediagonal!(MA,nrows,value)\n\t@inbounds for(i in 1:nrows)\n\t\t@inbounds MA[i,i]=value;\n\tend\nend\n\nfunction createMRM(MRM,Sti,Sp,ts)\n\tMRM = [Sti Sp 1 ts];\n\tMRM;\nend\n\nfunction createMC(MC,Sti,Sp,ts)\n\tMC = [Sti Sp 1 ts];\n\treturn MC;\nend\n\nfunction createMA(MA,Sti,Stj,Sp,anaG)\n\tMA = [Sti Stj Sp anaG];\n\treturn MA;\nend\n\nfunction updateMC(MC)\n\tif length(MC)>0\n\t\tMC[:,3] = MC[:,3].+1;#event: -1 for extinction; 1 for speciation\n\tend\n\treturn MC;\nend\n\nfunction updateMA(MA)\n\tif length(MA)>0\n\t\tMA[:,4] = MA[:,4] .- 1;\n\tend\n\treturn MA;\nend\n\nfunction checkIfThereIsMRM(MRM,Sti,Sp,ts)\n\tif length(MRM)==0\n\t\tMRM = createMRM(MRM,Sti,Sp,ts);\n\telse\n\t\tpos = find( (MRM[:,1].==Sti) & (MRM[:,2].==Sp))\n\t\tif length(pos)==0\n\t\t\tMRM = cat(1,MRM,[Sti Sp 1 ts]);\n\t\tend\n\tend\n\treturn MRM;\nend\n\nfunction checkIfThereIsMC(MC,Sti,Sp,ts)\n\tif length(MC)==0\n\t\tMC = createMC(MC,Sti,Sp,ts);\n\telse\n\t\tpos = find( (MC[:,1].==Sti) & (MC[:,2].==Sp))#position in the matrix MA referred to the presence of individuals of species 'Sp' coming from site 'Stj' to site 'Sti'\n\t\tif length(pos)==0\n\t\t\tMC = cat(1,MC,[Sti Sp 1 ts]);\n\t\tend\n\tend\n\treturn MC;\nend\n\nfunction GetGammaRichness(R,S)\n\trichnessspeciesR = [];\n\t#%gamma richness\n\tfor (i in 1:S)\n\t\tAR = sort(R[i])\n\t\trichnessspeciesR = [richnessspeciesR; unique(AR)];\n\tend;\n\textantR = length(unique(sort(richnessspeciesR)));\n\tgamma = extantR;\n\n\treturn gamma;\nend\n\nfunction OutputPerGeneration(outputfilepergen,ri,cost,J,G,S,k,anaG,retG,mr,ml,v,lakesIsolation,lakesArea,gamma,alpharich,SpecANA,SpecCLA,SpecMR,DispersalRich)\n\tfor i in 1:S\n\t\twritedlm(outputfilepergen, [ri cost J G k anaG retG mr ml v gamma i lakesIsolation[i] lakesArea[i] alpharich[i] SpecANA[i] SpecCLA[i] SpecMR[i] DispersalRich[i]],' ');\n\tend\n\tflush(outputfilepergen);#To print in the output file each realization\n\treturn;\nend\n\nfunction printPhylogeny(phylogenyfile,old,new,ts,ri)\n\twritedlm(phylogenyfile,[ri old new ts],' ');\n flush(phylogenyfile);\nend\n\nfunction UAB(MA,MC)\n\tMC = updateMC(MC);\n\tMA = updateMA(MA);\n\treturn MC,MA;\nend\n\nfunction UAC(MA)\n\tMA = updateMA(MA);\n\treturn MA;\nend\n\nfunction UARM(MA,MC)\n\tMC = updateMC(MC);\n\tMA = updateMA(MA);\n\treturn MC,MA;\nend\n\nfunction UALM(MA,MC,R,Sti,Stj,Sp,anaG,retG,ts)\n\tMC = updateMC(MC);\n\tMA = updateMA(MA);\n\n\tif length(MA)==0 #Si no hay MA\n \tMA = createMA(MA,Sti,Stj,Sp,anaG);#Create MA\n\telse#Si hay MA\n\t\tpos = find( (MA[:,1].==Sti) & (MA[:,2].==Stj) & (MA[:,3].==Sp))#position in the matrix MA referred to the presence of individuals of species 'Sp' coming from site 'Stj' to site 'Sti'\n\t\tif length(pos)==0 #No hay la linea\n\t\t\tindalive = length(find(R[Sti].==Sp))#Hay individuos de la specie sp vivos en el sitio Sti\n\t\t\tif (indalive == 0) #Checking if there are individuals of species 'Sp' alive in site 'Sti'\n# \t\t\tprintln(\"<<<<<<<<<<< A D D R O W T O A N A G E N E S I S <<<<<<<<<<<<<<<<<\");\n\t\t\t\tMA = cat(1,MA,[Sti Stj Sp anaG]);#Create the row in MA matrix, starting by 1\n \t\t\tend\n\t\telse #Ya hay la linea\n#\t\t\tprintln(\"<<<<<<<<<<< R E T A R D A N A G E N E S I S <<<<<<<<<<<<<<<<<\");\n\t\t\tMA[pos,4] = MA[pos,4] .+ retG;#retards anagenesis by increasing the remaining\n\t\tend\n\tend\n \treturn MC,MA,R;\nend\n\n########################\n\nfunction checkAna(MA,R,anaG,lastspecies,listofanagenesis,ts,phylogenyfile,ri)\n\tpos = [];\n\tif length(MA)>0\n\t\tpos = find(MA[:,4] .== 0)#find the anagenesis events \n\t\tif length(pos)>0#is there was an anagenesis event\n\t\t @inbounds for (p in pos)\n \t\t\tSti=round(Integer,MA[p,1]);#pos represents the rows of the matrix. p is one row. MA[p,1] is the target site\n \t\t\tStj=round(Integer,MA[p,2]);#pos represents the rows of the matrix. p is one row. MA[p,2] is the source site\n\t\t \tSp=round(Integer,MA[p,3]);#pos represents the rows of the matrix. p is one row. MA[p,3] is the ancient species\n\t\t\t MA, R, lastspecies,listofanagenesis = AnagenesisSpeciation(MA,R,Sti,Stj,Sp,lastspecies,listofanagenesis,ts,phylogenyfile,ri);#speciation in target site\n#\t\t\t MA, R, lastspecies,listofanagenesis = MA, R, lastspecies, listofanagenesis;\n\t\t end\n\t end\n end\n return MA,R,lastspecies,listofanagenesis;\nend\n\nfunction AnagenesisSpeciation(MA,R,Sti,Stj,Sp,lastspecies,listofanagenesis,ts,phylogenyfile,ri)\n\tnewspeciesAna = lastspecies + 1;#the id of the new species\n\tancientindividuals = find( R[Sti].==Sp )#the position of all the individuals of the ancient species 'Sp' in the target site\n\tR[Sti][ancientindividuals] = newspeciesAna;#the speciation itself: all the individuals of former species 'Sp' in the target site are now from a new species 'newspeciesAna'\n println(\"new ANAgenesis Speciation : Species \",newspeciesAna,\" - time: \",ts);\n \tpos = find( (MA[:,1].==Sti) & (MA[:,3].==Sp))#position in the matrix MA referred to the presence of individuals of species 'Sp' in site 'Sti'\n\tMA = MA[1:size(MA,1).!=pos,:];#Borra la linea 'pos' de la matriz MA!!\n\tprintPhylogeny(phylogenyfile,Sp,newspeciesAna,ts,ri);\n\n \tif length(listofanagenesis)>0\n\t\tlistofanagenesis = cat(1,listofanagenesis,[Sti newspeciesAna]);\n\telse\n\t\tlistofanagenesis = cat(1,[Sti newspeciesAna]);\n\tend\n\n\treturn MA,R,newspeciesAna,listofanagenesis;\nend\n\nfunction CladogenesisEvent(MC,R,Sti,Individual,lastspecies,ts,phylogenyfile,ri)\n\tnewspeciesClado = lastspecies + 1;\n\tprintPhylogeny(phylogenyfile,R[Sti][Individual],newspeciesClado,ts,ri);\n println(\"new CLADOgenesis Speciation : Species \",newspeciesClado,\" - time: \",ts);\n \tR[Sti][Individual] = newspeciesClado;\n\tMC = checkIfThereIsMC(MC,Sti,newspeciesClado,ts);\n\treturn MC,R,newspeciesClado;\nend\n\nfunction LocalMigrationEvent(R,KillHab,MigrantHab,KillInd,Dc,Ji,S)\n\tMigrantSpecies = -1;\n\n\tallpos = find(Dc[KillHab,:] .>= MigrantHab);#All the sites at a distance lower than the threshold 'MigrantHab'\n\tkr = minimum(allpos[find(allpos .!= KillHab)]);\n\tMigrantInd = rand(1:Ji[kr]);\n\tMigrantSpecies = R[kr][MigrantInd];\n# println(\"LOCAL Migration\");\n\tR[KillHab][KillInd] = R[kr][MigrantInd];\n\treturn kr,R,MigrantSpecies;\nend;\n\nfunction RegionalMigrationEvent(MRM,R,Sti,Individual,ts,lastspecies)\n newspeciesMR = lastspecies + 1;\n R[Sti][Individual] = newspeciesMR;\n println(\"new RegionalMig Speciation: Species \",newspeciesMR,\" - time: \",ts)\n MRM = checkIfThereIsMRM(MRM,Sti,newspeciesMR,ts);\n\n return MRM,R,newspeciesMR;\nend;\n\nfunction BirthEvent(R,BirthLocal,KillInd,KillHab)\n\tR[KillHab][KillInd] = R[KillHab][BirthLocal];\n\treturn R;\nend\n\nfunction calculateSpeciationMA(listofanagenesis,R)\n\tS = length(R);#number of sites equals the number of rows in R\n\tspeciatedMA = zeros(S);\n\tif (length(listofanagenesis) > 0)\n\t\t@inbounds for i in 1:S\n\t\t\t@inbounds speciesR = unique(sort(R[i]))';\n\t\t\tpos = find(listofanagenesis[:,1].== i);\n\t\t\tif length(pos)>0\n\t\t\t\tspeciesMA = listofanagenesis[pos,2];\n\t\t\t\tspeciatedMA[i] = length(setdiff(speciesMA,setdiff(speciesMA,speciesR))');\n\t\t\tend\n\t\tend\n\tend\n\treturn speciatedMA;\nend\n\n\nfunction calculateSpeciationMC(MC,R,S,k,Ji)\n\tspeciatedMC = zeros(S);\n\tif (length(MC) > 0)\n\t\t@inbounds for i in 1:S\n\t\t@inbounds speciesR = unique(sort(R[i]))';\n\t\t\tpos = find( (MC[:,1].== i) & (MC[:,3].>= k) );#Only the species that are in the system for more than k time steps (Protracted)\n\t\t\tif length(pos)>0\n\t\t\t\tspeciesMC = unique(sort(MC[pos,2]));\n\t\t\t\tspeciatedMC[i] = length(setdiff(speciesMC,setdiff(speciesMC,speciesR))');\n\t\t\tend\n\t\tend\n\tend\n\treturn speciatedMC;\nend\n\nfunction calculateSpeciationMR(MRM,R,S,Ji)\n\tspeciatedMRM = zeros(S);\n\tif (length(MRM) > 0)\n\t\t@inbounds for i in 1:S\n @inbounds speciesR = unique(sort(R[i]))';\n pos = find(MRM[:,1].== i);#check for site i\n if length(pos)>0\n speciesMRM = unique(sort(MRM[pos,2]));\n @inbounds speciatedMRM[i] = length(setdiff(speciesMRM,setdiff(speciesMRM,speciesR))');\n end\n\t\tend\n\tend\n#\twritedlm(\"MRMmatrix.dat\",MRM,' ');\n\treturn speciatedMRM;\nend\n\nfunction richnessanalysis!(S,R,Ji,richnessspeciesR,alpharich)\n\t#%gamma richness\n\t@inbounds for (i in 1:S)\n\t\t@inbounds AR = sort(R[i]);\n\t\trichnessspeciesR = [richnessspeciesR; unique(AR)];\n\t\t@inbounds alpharich[i] = length(unique(AR));\n\tend;\n\tgamma = length(unique(sort(richnessspeciesR)));\n\treturn gamma,alpharich;\nend\n\nfunction normalizeDc!(Dc,S)\n for(i in 1:S)\n Dc[i,:] = Dc[i,:]/maximum(Dc[i,:]);\n end\nend\n\nfunction repeatval(x,N)\n return map(v -> v=x,1:N);\nend\n\n#Each site starts with one different species\nfunction initialPopulation(R,Ji)\n lastspecies = 0;\n for(iJ in Ji)#iterating over columns\n lastspecies = lastspecies+1;\n popi = repeatval(lastspecies,iJ);\n push!(R,popi);\n end\n return R,lastspecies;\nend\n\nfunction dynamic(seed,nreal,Gmax,J,v,mr,ml,anaG,retG,distmatfile,verticesdata,model)\n\tDI = readDistanceMatrix(distmatfile);#the location of the points of the landscape.\n\tDc = cumsum(DI,2);#Should we divide\n dT = sum(DI,2);\n\tconst S = length(DI[:,1]);#Number of sites\n normalizeDc!(Dc,S);\n#### To get the cost\n substring = distmatfile[search(distmatfile,'_')+1:end];\n modelstop = search(substring,'_');\n coststop = search(substring,'t');\n\tconst cost = float(substring[coststop+1:modelstop-1]);\n\n\tsitesdata = readdlm(verticesdata,' ',header=true)[1];#Proportion of individuals of each site\n#\tPj = ones(S);#Proportion of individuals of each site - if an input file is not defined, the proportion is the same for each site\n lakesVolume = sitesdata[:,2];\n lakesArea = sitesdata[:,3];\n\tPj = lakesVolume;#In case we define different carrying capacities for each site we consider the volume of the lakes (third column)\n\tmins = find(sitesdata.==minimum(sitesdata[:,1]));#the first column represents the height of the lakes\n\tentrypoint = mins[rand(1:length(mins))];\n\tt=1;#Sites have different sizes and are located at different height.\n\tJi=round(Integer,J * Pj/sum(Pj));\n\n\toutputfilepergen = open(string(\"RichnessPerGen_AnaG_\",anaG,\"_retG_\",retG,\"_cost_\",cost,\"_MR_\",signif(mr,3),\"_VR_\",signif(v,3),\".txt\"),\"a\")\n\twritedlm(outputfilepergen, [\"Real Cost J G Gi anaG retG mr ml v gamma Site dT lakeArea alpharich SpecANA SpecCLA SpecMR DispersalRich\"]);\n\n\toutputfile = open(string(\"RichnessPerSite_AnaG_\",anaG,\"_retG_\",retG,\"_cost_\",cost,\"_MR_\",signif(mr,3),\"_VR_\",signif(v,3),\".txt\"),\"a\")\n\twritedlm(outputfile,[\"Real Cost Model J G anaG retG Site lakeArea Ji dT mr ml v gamma alpharich SpecANA SpecCLA SpecMR DispersalRich\"]);\n\n\tphylogenyfile = open(string(\"Phylogeny_AnaG_\",anaG,\"_retG_\",retG,\"_cost_\",cost,\"_MR_\",signif(mr,3),\"_VR_\",signif(v,3),\".txt\"),\"a\")\n\twritedlm(phylogenyfile,[\"Repl Ancestral Derived Age\"]);\n\n @inbounds for (ri in 1:nreal)#realizations\n \t lastspecies = 0;\n \tts=0;\n R=[];\n R,lastspecies = initialPopulation(R,Ji)\n\t MA = Array(Number,0,0);#Matrix to calculate Anagenesis speciation (MA = [Sti, Stj, S, C])\n\t MC = Array(Number,0,0);#Matrix to control Cladogenesis speciation (MC = [Sti, S, E])\n\t MRM = Array(Number,0,0);#Matrix to control events of Regional Migration (MRM = [Sti, S, ts])\n\t\tsrand(seed+(7*ri));\n\t\tlistofanagenesis = Array(Number,0,0);\n\n\t\t#%Resources\n#\t\tG = rand(15:Gmax);#Minimum of 15 generations\n\t\tG = Gmax;#Minimum of 15 generations\n\n\t\t@inbounds for (k = 1:G)#%population-metapopulation-metacommunity dynamics (not-tracking multitrophic metacommunity dynamics!)\n\t\t\t@inbounds for (j = 1:J)#For each individual in each site\n\t\t\t\tts = ts+1;#Time step increases\n\t\t\t\tmvb = rand();\n\t\t \t\t#Demography - Resources\n \t\t\t\tKillHab = rand(1:S);#which site to kill\n\t\t\t\tKillInd = rand(1:Ji[KillHab]);#which individual to kill\n \t\t\tKillIndEntryPoint = rand(1:Ji[entrypoint]);\n\t\t\t\tMigrantHab = rand()*maximum(Dc[KillHab,:]);\n\t\t\t\tBirthLocal = getSampleFromArray(1:length(R[KillHab]));#which individual to born\n\n\t\t\t\tif mvb <= ml;#Local Migration event\n\t\t\t\t\tkr,R,MigrantSpecies = LocalMigrationEvent(R,KillHab,MigrantHab,KillInd,Dc,Ji,S);\n\t\t\t\t\tMC,MA,R = UALM(MA,MC,R,KillHab,kr,MigrantSpecies,anaG,retG,ts);#Update Anagenesis after Local Migration event\n\t\t\t\telseif (ml < mvb <= (ml+mr));#Regional Migration event\n\t\t\t\t\tMRM,R,lastspecies = RegionalMigrationEvent(MRM,R,entrypoint,KillIndEntryPoint,ts,lastspecies);#Speciation through the entry point\n\t\t\t\t\tMC,MA = UARM(MA,MC);#Update Anagenesis after Regional Migration event\n\t\t\t\telseif ((ml+mr) < mvb <= (ml+mr+v))\n\t\t\t\t\tif(v > 0)#we only simulate Cladogenesis when the probability is higher than 0\n\t\t\t\t\t\tMC,R,lastspecies = CladogenesisEvent(MC,R,KillHab,KillInd,lastspecies,ts,phylogenyfile,ri);\n\t\t\t\t\t\tMA = UAC(MA);#Update Anagenesis after Cladogenesis Speciation\n\t\t\t\t\tend\n\t\t\t\telse #Birth event\n\t\t\t\t\tR = BirthEvent(R,BirthLocal,KillInd,KillHab);#Birth event\n\t\t\t\t\tMC,MA = UAB(MA,MC);#Update MA after Birth event\n\t\t \t\tend;\n####ANAGENESIS\n\t\t\t\tlengthlistbefore = length(listofanagenesis);#Size of Anagenesis Matrix before checking for Anagenesis\n\t\t\t\tMA,R,lastspecies,listofanagenesis = checkAna(MA,R,anaG,lastspecies,listofanagenesis,ts,phylogenyfile,ri); #After the update of matrix MA, we check for events of Anagenesis\n\t\t\t\tlengthlistafter = length(listofanagenesis);#Size of Anagenesis Matrix after checking for Anagenesis\n####CLADOGENESIS\n#\t\t\t\tif ((lengthlistafter - lengthlistbefore) > 0)#If there is at least one Anagenesis Speciation Event\n#\t\t\t\t\tmvc = rand();\n#\t\t\t\t\tif (mvc <= v);#Probability to occur a Cladogenesis Speciation event\n#\t\t\t\t\t\tallInd = find(R[St,:].==lastspecies);#All individuals from the new species\n#\t\t\t\t\t\tif (length(allInd)>0)\n#\t\t\t\t\t\t\tKillInd = allInd[rand(1:length(allInd))];#Randomly choose an individual from the new species\n#\t\t\t\t\t\t\tMC,R,lastspecies = CladogenesisEvent(MC,R,KillHab,KillInd,lastspecies,ts,phylogenyfile,ri);#Cladogenesis event\n#\t\t\t\t\t\t\tMA = UAC(MA);#Update Anagenesis after Cladogenesis Speciation event\n#\t\t\t\t\t\tend #if allInd\n#\t\t\t\t\tend #if mvc\n#\t\t\t\tend #if lengthlistafter\n\t\t\tend;#end S*Ji\n\t\t\trichnessspeciesR = [];\n\t\t\talpharich = zeros(S);\n\t\t\tgamma,alpharich = richnessanalysis!(S,R,Ji,richnessspeciesR,alpharich);\n\t\t\tSpecANA = calculateSpeciationMA(listofanagenesis,R);\n\t\t\tSpecCLA = calculateSpeciationMC(MC,R,S,anaG,Ji);\n\t\t\tSpecMR = calculateSpeciationMR(MRM,R,S,Ji);\n\t\t\tDispersalRich = alpharich - (SpecANA + SpecCLA + SpecMR);\n\t\t\tOutputPerGeneration(outputfilepergen,ri,cost,J,G,S,k,anaG,retG,mr,ml,v,dT,lakesArea,gamma,alpharich,SpecANA,SpecCLA,SpecMR,DispersalRich);\n\t\tend;#end Gmax\n\n\t\t#To analyze the resulting richness\n\t\trichnessspeciesR = [];\n\t\talpharich = zeros(S);\n\t\tgamma,alpharich = richnessanalysis!(S,R,Ji,richnessspeciesR,alpharich);\n\t\tSpecANA = calculateSpeciationMA(listofanagenesis,R);\n\t\tSpecCLA = calculateSpeciationMC(MC,R,S,anaG,Ji);\n\t\tSpecMR = calculateSpeciationMR(MRM,R,S,Ji);\n\t\tDispersalRich = alpharich - (SpecANA + SpecCLA + SpecMR);\n#\t\tmatrixfile = open(\"Rmatrix.txt\",\"a\");\n\t\tfor i in 1:S\n\t\t\twritedlm(outputfile,[ri cost model J G anaG retG i lakesArea[i] Ji[i] dT[i] mr ml v gamma alpharich[i] SpecANA[i] SpecCLA[i] SpecMR[i] DispersalRich[i]],' ');\n# for j in 1:length(R[i])\n#\t print(matrixfile,R[i][j],' ');\n#\t\t\tend\n#\t print(matrixfile,'\\n');\n\t\tend\n\t\tflush(outputfile);\n#\t\tANAfile = open(\"ANAmatrix.txt\",\"a\");\n#\t\tMRMfile = open(\"MRMmatrix.txt\",\"a\");\n#\t\trowsANA = size(listofanagenesis,1);rowsMRM = size(MRM,1);\n#\t\tcolsANA = size(listofanagenesis,2);colsMRM = size(MRM,2);\n#\t\tfor i in 1:rowsANA #number of rows\n#\t\t\tfor j in 1:colsANA\n#\t print(ANAfile,listofanagenesis[i,j],' ');\n#\t\t\tend\t\n#\t print(ANAfile,'\\n');\n#\t\tend\n#\t\tfor i in 1:rowsMRM #number of rows\n#\t\t\tfor j in 1:colsMRM\n#\t print(MRMfile,MRM[i,j],' ');\n#\t\t\tend\t\n#\t print(MRMfile,'\\n');\n#\t\tend\n\n\tend#%ri\n\tclose(outputfile);\n\tclose(outputfilepergen);\n\tclose(phylogenyfile);\n#\tclose(logfile);\nend#ecoevo3d function\n\nend #module\n", "meta": {"hexsha": "51f68812204076c76dbd0869de1f64673aaad467", "size": 15929, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EcoEvo3D.jl", "max_stars_repo_name": "cndesantana/EcoEvo3D.jl", "max_stars_repo_head_hexsha": "9af77c557e9bbc74cb8d73da3c6281b5955b47ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-08T20:05:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-08T20:05:21.000Z", "max_issues_repo_path": "src/EcoEvo3D.jl", "max_issues_repo_name": "cndesantana/EcoEvo3D", "max_issues_repo_head_hexsha": "9af77c557e9bbc74cb8d73da3c6281b5955b47ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/EcoEvo3D.jl", "max_forks_repo_name": "cndesantana/EcoEvo3D", "max_forks_repo_head_hexsha": "9af77c557e9bbc74cb8d73da3c6281b5955b47ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.284738041, "max_line_length": 184, "alphanum_fraction": 0.6903760437, "num_tokens": 5217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2458689177634208}} {"text": "using ForwardDiff: value\n\n\"\"\"\n AbstractObsScheme\n\nTypes inheriting from abstract type `AbstractObsScheme` define the scheme\naccording to which a stochastic process has been observed\n\"\"\"\nabstract type AbstractObsScheme end\n\n\n\"\"\"\n PartObs <: AbstractObsScheme\n\nType acting as a flag for partially observed diffusions\n\"\"\"\nstruct PartObs <: AbstractObsScheme end\n\n\n\"\"\"\n FPT <: AbstractObsScheme\n\nObservation scheme in which only first passage times are observed\n\"\"\"\nstruct FPT <: AbstractObsScheme end\n\n\"\"\"\n ParamUpdateType\n\nTypes inheriting from abstract type `ParamUpdateType` define the way in which\nparameters are to be updated by the MCMC sampler\n\"\"\"\nabstract type ParamUpdateType end\n\n\"\"\"\n ConjugateUpdt <: ParamUpdateType\n\nType acting as a flag for update from full conditional (conjugate to a prior)\n\"\"\"\nstruct ConjugateUpdt <: ParamUpdateType end\n\n\"\"\"\n MetropolisHastingsUpdt <: ParamUpdateType\n\nFlag for performing update according to Metropolis Hastings step\n\"\"\"\nstruct MetropolisHastingsUpdt <: ParamUpdateType end\n\n\n\"\"\"\n setBlocking(𝔅::NoBlocking, ::Any, ::Any, ::Any, ::Any)\n\nNo blocking is to be done, do nothing\n\"\"\"\nsetBlocking(𝔅::NoBlocking, ::Any, ::Any, ::Any, ::Any) = 𝔅\n\n\n\"\"\"\n setBlocking(::ChequeredBlocking, blockingParams, P, WW, XX)\n\nBlocking pattern is chosen to be a chequerboard.\n\"\"\"\nfunction setBlocking(::ChequeredBlocking, blockingParams, P, WW, XX)\n ChequeredBlocking(blockingParams..., P, WW, XX)\nend\n\n\"\"\"\n FPTInfo{S,T}\n\nThe struct\n```\nstruct FPTInfo{S,T}\n condCoord::NTuple{N,S}\n upCrossing::NTuple{N,Bool}\n autoRenewed::NTuple{N,Bool}\n reset::NTuple{N,T}\nend\n```\nserves as a container for the information regarding first passage time\nobservations. `condCoord` is an NTuple of coordinates that are conditioned on\nthe first passage time nature of the observations. `upCrossing` indicates\nwhether observations of the corresponding coordinate are up-crossings or\ndown-crossings. `autoRenewed` indicates whether process starts from the\nrenewed state (i.e. normally the process is unconstrained until it hits level\n`reset` for the first time, however `autoRenewed` process is constrained on the\nfirst passage time from the very beginnig). `reset` level is the level that\nneeds to be reached before the process starts to be conditioned on the first\npassage time.\n\"\"\"\nstruct FPTInfo{S,T,N}\n condCoord::NTuple{N,S}\n upCrossing::NTuple{N,Bool}\n autoRenewed::NTuple{N,Bool}\n reset::NTuple{N,T}\n\n FPTInfo(condCoord::NTuple{N,S}, upCrossing::NTuple{N,Bool},\n reset::NTuple{N,T},\n autoRenewed::NTuple{N,Bool} = Tuple(fill(false,length(condCoord)))\n ) where {S,T,N} = new{S,T,N}(condCoord, upCrossing,\n autoRenewed, reset)\nend\n\n\n\"\"\"\n checkSingleCoordFpt(XXᵒ, c, cidx, fpt)\n\nVerify whether coordinate `c` (with index number `cidx`) of path `XXᵒ`.yy\nadheres to the first passage time observation scheme specified by the object\n`fpt`.\n\"\"\"\nfunction checkSingleCoordFpt(XXᵒ, c, cidx, fpt)\n k = length(XXᵒ.yy)\n thrsd = XXᵒ.yy[end][c]\n renewed = fpt.autoRenewed[cidx]\n s = fpt.upCrossing[cidx] ? 1 : -1\n for i in 1:k\n if !renewed && (s*XXᵒ.yy[i][c] <= s*fpt.reset[cidx])\n renewed = true\n elseif renewed && (s*XXᵒ.yy[i][c] > s*thrsd)\n return false\n end\n end\n return renewed\nend\n\n\n\"\"\"\n checkFpt(::PartObs, XXᵒ, fpt)\n\nFirst passage time constrains are automatically satisfied for the partially\nobserved scheme\n\"\"\"\ncheckFpt(::PartObs, XXᵒ, fpt) = true\n\n\n\"\"\"\n checkFpt(::FPT, XXᵒ, fpt)\n\nVerify whether path `XXᵒ`.yy adheres to the first passage time observation\nscheme specified by the object `fpt`.\n\"\"\"\nfunction checkFpt(::FPT, XXᵒ, fpt)\n for (cidx, c) in enumerate(fpt.condCoord)\n if !checkSingleCoordFpt(XXᵒ, c, cidx, fpt)\n return false\n end\n end\n return true\nend\n\n\n\"\"\"\n checkFullPathFpt(::PartObs, ::Any, ::Any, ::Any)\n\nFirst passage time constrains are automatically satisfied for the partially\nobserved scheme\n\"\"\"\ncheckFullPathFpt(::PartObs, ::Any, ::Any, ::Any) = true\n\n\n\"\"\"\n checkFullPathFpt(::PartObs, XXᵒ, m, fpt)\n\nVerify whether all paths in the range `iRange`, i.e. `XXᵒ`[i].yy, i in `iRange`\nadhere to the first passage time observation scheme specified by the object\n`fpt`\n\"\"\"\nfunction checkFullPathFpt(::FPT, XXᵒ, iRange, fpt)\n for i in iRange\n if !checkFpt(FPT(), XXᵒ[i], fpt[i])\n return false\n end\n end\n return true\nend\n\n\"\"\"\n findProposalLaw(xx, tt, P˟, P̃, Ls, Σs; dt=1/5000, timeChange=true,\n solver::ST=Ralston3())\n\nInitialise the object with proposal law and all the necessary containers needed\nfor the simulation of the guided proposals\n\"\"\"\nfunction findProposalLaw(::Type{K}, xx, tt, P˟, P̃, Ls, Σs, τ; dt=1/5000,\n solver::ST=Ralston3(),\n changePt::ODEChangePt=NoChangePt()) where {K,ST}\n m = length(xx) - 1\n P = Array{ContinuousTimeProcess,1}(undef,m)\n for i in m:-1:1\n numPts = Int64(ceil((tt[i+1]-tt[i])/dt))+1\n t = τ(tt[i], tt[i+1]).( range(tt[i], stop=tt[i+1], length=numPts) )\n P[i] = ( (i==m) ? GuidPropBridge(K, t, P˟, P̃[i], Ls[i], xx[i+1], Σs[i];\n changePt=changePt, solver=ST()) :\n GuidPropBridge(K, t, P˟, P̃[i], Ls[i], xx[i+1], Σs[i],\n P[i+1].H[1], P[i+1].Hν[1], P[i+1].c[1];\n changePt=changePt, solver=ST()) )\n end\n P\nend\n\n\n\"\"\"\n initialise(::ObsScheme, P, m, y::StartingPtPrior{T}, ::S, fpt)\n\nInitialise the workspace for MCMC algorithm. Initialises containers for driving\nWiener processes `WWᵒ` & `WW`, for diffusion processes `XXᵒ` & `XX`, for\ndiffusion Law `Pᵒ` (parametetrised by proposal parameters) and defines the type\nof Wiener process `Wnr`.\n\"\"\"\nfunction initialise(::ObsScheme, P, m, yPr::StartingPtPrior{T}, ::S,\n fpt) where {ObsScheme <: AbstractObsScheme,T,S}\n y = startPt(yPr)\n Pᵒ = deepcopy(P)\n TW = typeof(sample([0], Wiener{S}()))\n TX = typeof(SamplePath([], zeros(T, 0)))\n XXᵒ = Vector{TX}(undef,m)\n WWᵒ = Vector{TW}(undef,m)\n Wnr = Wiener{S}()\n for i in 1:m\n WWᵒ[i] = Bridge.samplepath(P[i].tt, zero(S))\n sample!(WWᵒ[i], Wnr)\n XXᵒ[i] = solve(Euler(), y, WWᵒ[i], P[i])\n while !checkFpt(ObsScheme(), XXᵒ[i], fpt[i])\n sample!(WWᵒ[i], Wnr)\n solve!(Euler(), XXᵒ[i], y, WWᵒ[i], P[i])\n end\n y = XXᵒ[i].yy[end]\n end\n y = startPt(yPr)\n ll = logpdf(yPr, y)\n ll += pathLogLikhd(ObsScheme(), XXᵒ, P, 1:m, fpt, skipFPT=true)\n ll += lobslikelihood(P[1], y)\n\n XX = deepcopy(XXᵒ)\n WW = deepcopy(WWᵒ)\n # needed for proper initialisation of the Crank-Nicolson scheme\n yPr = invStartPt(y, yPr, P[1])\n\n Wnr, WWᵒ, WW, XXᵒ, XX, Pᵒ, ll, yPr\nend\n\n\n\"\"\"\n savePath!(Paths, XX, saveMe, skip)\n\nIf `saveMe` flag is true, then save the entire path spanning all segments in\n`XX`. Only 1 in every `skip` points is saved to reduce storage space.\n\"\"\"\nfunction savePath!(Paths, XX, saveMe, skip)\n if saveMe\n push!(Paths, collect(Iterators.flatten(XX[i].yy[1:skip:end-1]\n for i in 1:length(XX))))\n end\nend\n\n\n\"\"\"\n acceptSample(logThreshold, verbose=false)\n\nMake a random MCMC decision for whether to accept a sample or reject it.\n\"\"\"\nfunction acceptSample(logThreshold, verbose=false)\n if rand(Exponential(1.0)) > -logThreshold # Reject if NaN\n verbose && print(\"\\t ✓\\n\")\n return true\n else\n verbose && print(\"\\t .\\n\")\n return false\n end\nend\n\n\n\"\"\"\n solveBackRec!(P, solver::ST=Ralston3()) where ST\n\nSolve backward recursion to find H, Hν, c and Q, which together define r̃(t,x)\nand p̃(x, 𝓓) under the auxiliary law, when no blocking is done\n\"\"\"\nfunction solveBackRec!(::NoBlocking, P, solver::ST=Ralston3()) where ST\n m = length(P)\n gpupdate!(P[m]; solver=ST())\n for i in (m-1):-1:1\n gpupdate!(P[i], P[i+1].H[1], P[i+1].Hν[1], P[i+1].c[1]; solver=ST())\n end\nend\n\n\n\"\"\"\n solveBackRec!(P, solver::ST=Ralston3()) where ST\n\nSolve backward recursion to find H, Hν, c and Q, which together define r̃(t,x)\nand p̃(x, 𝓓) under the auxiliary law, when blocking is done\n\"\"\"\nfunction solveBackRec!(𝔅::BlockingSchedule, P, solver::ST=Ralston3()) where ST\n for block in reverse(𝔅.blocks[𝔅.idx])\n gpupdate!(P[block[end]]; solver=ST())\n for i in reverse(block[1:end-1])\n gpupdate!(P[i], P[i+1].H[1], P[i+1].Hν[1], P[i+1].c[1]; solver=ST())\n end\n end\nend\n\n\"\"\"\n proposalStartPt(::BlockingSchedule, ::Val{1}, ::Any, yPr, P, ρ)\n\nSet a new starting point for the proposal path when sampling the first block in\na blocking scheme.\n\n...\n# Arguments\n- `::BlockingSchedule`: indicator that a blocking scheme is used\n- `::Val{1}`: indicator that it's the first block, so starting point needs updating\n- `yPr`: prior over the starting point\n- `P`: diffusion law\n- `ρ`: memory parameter in the Crank-Nicolson scheme\n...\n\"\"\"\nfunction proposalStartPt(::BlockingSchedule, ::Val{1}, ::Any, yPr, P, ρ)\n proposalStartPt(NoBlocking(), nothing, nothing, yPr, P, ρ)\nend\n\n\"\"\"\n proposalStartPt(::BlockingSchedule, ::Any, y₀, yPr, ::Any, ::Any)\n\nDefault behaviour of dealing with a starting point in the blocking scheme is\nto do nothing\n\"\"\"\nfunction proposalStartPt(::BlockingSchedule, ::Any, y₀, yPr, ::Any, ::Any)\n y₀, yPr\nend\n\n\"\"\"\n proposalStartPt(::NoBlocking, ::Any, y₀, yPr, P, ρ)\n\nSet a new starting point for the proposal path when no blocking is done\n...\n# Arguments\n- `::NoBlocking`: indicator that no blocking is done\n- `yPr`: prior over the starting point\n- `P`: diffusion law\n- `ρ`: memory parameter in the Crank-Nicolson scheme\n...\n\"\"\"\nfunction proposalStartPt(::NoBlocking, ::Any, ::Any, yPr, P, ρ)\n yPrᵒ = rand(yPr, ρ)\n y = startPt(yPrᵒ, P)\n y, yPrᵒ\nend\n\n\"\"\"\n printInfo(verbose::Bool, it::Integer, ll, llᵒ, msg=\"update\")\n\nPrint information to the console about current likelihood values\n\n...\n# Arguments\n- `verbose`: flag for whether to print anything at all\n- `it`: iteration of the Markov chain\n- `ll`: likelihood of the previous, accepted sample\n- `llᵒ`: likelihood of the proposal sample\n- `msg`: message to start with\n...\n\"\"\"\nfunction printInfo(verbose::Bool, it::Integer, ll, llᵒ, msg=\"update\")\n verbose && print(msg, \": \", it, \" ll \", round(ll, digits=3), \" \",\n round(llᵒ, digits=3), \" diff_ll: \", round(llᵒ-ll,digits=3))\nend\n\n\n\"\"\"\n pathLogLikhd(::ObsScheme, XX, P, iRange, fpt; skipFPT=false)\n\nCompute likelihood for path `XX` to be observed under `P`. Only segments with\nindex numbers in `iRange` are considered. `fpt` contains relevant info about\nchecks regarding adherence to first passage time pattern. `skipFPT` if set to\n`true` can skip the step of checking adherence to fpt pattern (used for\nconjugate updates, or any updates that keep `XX` unchanged)\n\"\"\"\nfunction pathLogLikhd(::ObsScheme, XX, P, iRange, fpt; skipFPT=false\n ) where ObsScheme <: AbstractObsScheme\n ll = 0.0\n for i in iRange\n ll += llikelihood(LeftRule(), XX[i], P[i])\n end\n !skipFPT && (ll = checkFullPathFpt(ObsScheme(), XX, iRange, fpt) ? ll : -Inf)\n ll\nend\n\n\"\"\"\n swap!(A, Aᵒ, iRange)\n\nSwap contents between containers A & Aᵒ in the index range iRange\n\"\"\"\nfunction swap!(A, Aᵒ, iRange)\n for i in iRange\n A[i], Aᵒ[i] = Aᵒ[i], A[i]\n end\nend\n\n\"\"\"\n swap!(A, Aᵒ, B, Bᵒ, iRange)\n\nSwap contents between containers A & Aᵒ in the index range iRange, do the same\nfor containers B & Bᵒ\n\"\"\"\nfunction swap!(A, Aᵒ, B, Bᵒ, iRange)\n swap!(A, Aᵒ, iRange)\n swap!(B, Bᵒ, iRange)\nend\n\n\"\"\"\n crankNicolson!(yᵒ, y, ρ)\n\nPreconditioned Crank Nicolson update with memory parameter `ρ`, previous vector\n`y` and new vector `yᵒ`\n\"\"\"\ncrankNicolson!(yᵒ, y, ρ) = (yᵒ .= √(1-ρ)*yᵒ + √(ρ)*y)\n\n\n\"\"\"\n sampleSegment!(i, Wnr, WW, WWᵒ, P, y, XX, ρ)\n\nSample `i`th path segment using preconditioned Crank-Nicolson scheme\n...\n# Arguments\n- `i`: index of the segment to be sampled\n- `Wnr`: type of the Wiener process\n- `WW`: containers with old Wiener paths\n- `WWᵒ`: containers where proposal Wiener paths will be stored\n- `P`: laws of the diffusion to be sampled\n- `y`: starting point of the segment\n- `XX`: containers for proposal diffusion path\n- `ρ`: memory parameter for the Crank-Nicolson scheme\n...\n\"\"\"\nfunction sampleSegment!(i, Wnr, WW, WWᵒ, P, y, XX, ρ)\n sample!(WWᵒ[i], Wnr)\n crankNicolson!(WWᵒ[i].yy, WW[i].yy, ρ)\n solve!(Euler(), XX[i], y, WWᵒ[i], P[i])\n XX[i].yy[end]\nend\n\n\n\"\"\"\n sampleSegments!(iRange, Wnr, WW, WWᵒ, P, y, XX, ρ)\n\nSample paths segments in index range `iRange` using preconditioned\nCrank-Nicolson scheme\n...\n# Arguments\n- `iRange`: range of indices of the segments that need to be sampled\n- `Wnr`: type of the Wiener process\n- `WW`: containers with old Wiener paths\n- `WWᵒ`: containers where proposal Wiener paths will be stored\n- `P`: laws of the diffusion to be sampled\n- `y`: starting point of the segment\n- `XX`: containers for proposal diffusion path\n- `ρ`: memory parameter for the Crank-Nicolson scheme\n...\n\"\"\"\nfunction sampleSegments!(iRange, Wnr, WW, WWᵒ, P, y, XX, ρ)\n for i in iRange\n y = sampleSegment!(i, Wnr, WW, WWᵒ, P, y, XX, ρ)\n end\nend\n\n\n\"\"\"\n impute!(::ObsScheme, 𝔅::NoBlocking, Wnr, yPr, WWᵒ, WW, XXᵒ, XX, P, ll, fpt;\n ρ=0.0, verbose=false, it=NaN, headStart=false) where\n ObsScheme <: AbstractObsScheme -> acceptedLogLikhd, acceptDecision\n\nImputation step of the MCMC scheme (without blocking).\n...\n# Arguments\n- `::ObsScheme`: observation scheme---first-passage time or partial observations\n- `Wnr`: type of the Wiener process\n- `yPr`: prior over the starting point of the diffusion path\n- `WWᵒ`: containers for proposal Wiener paths\n- `WW`: containers with old Wiener paths\n- `XXᵒ`: containers for proposal diffusion paths\n- `XX`: containers with old diffusion paths\n- `P`: laws of the diffusion path (proposal and target)\n- `11`: log-likelihood of the old (previously accepted) diffusion path\n- `fpt`: info about first-passage time conditioning\n- `ρ`: memory parameter for the Crank-Nicolson scheme\n- `verbose`: whether to print updates info while sampling\n- `it`: iteration index of the MCMC algorithm\n- `headStart`: flag for whether to 'ease into' fpt conditions\n...\n\"\"\"\nfunction impute!(::ObsScheme, 𝔅::NoBlocking, Wnr, yPr, WWᵒ, WW, XXᵒ, XX, P, ll,\n fpt; ρ=0.0, verbose=false, it=NaN, headStart=false,\n solver::ST=Ralston3()) where\n {ObsScheme <: AbstractObsScheme, ST}\n # sample proposal starting point\n yᵒ, yPrᵒ = proposalStartPt(𝔅, nothing, nothing, yPr, P[1], ρ)\n\n # sample proposal path\n m = length(WWᵒ)\n yᵗᵉᵐᵖ = copy(yᵒ)\n for i in 1:m\n sampleSegment!(i, Wnr, WW, WWᵒ, P, yᵗᵉᵐᵖ, XXᵒ, ρ)\n if headStart\n while !checkFpt(ObsScheme(), XXᵒ[i], fpt[i])\n sampleSegment!(i, Wnr, WW, WWᵒ, P, yᵗᵉᵐᵖ, XXᵒ, ρ)\n end\n end\n yᵗᵉᵐᵖ = XXᵒ[i].yy[end]\n end\n\n llᵒ = logpdf(yPrᵒ, yᵒ)\n llᵒ += pathLogLikhd(ObsScheme(), XXᵒ, P, 1:m, fpt)\n llᵒ += lobslikelihood(P[1], yᵒ)\n\n printInfo(verbose, it, value(ll), value(llᵒ), \"impute\")\n\n if acceptSample(llᵒ-ll, verbose)\n swap!(XX, XXᵒ, WW, WWᵒ, 1:m)\n return llᵒ, true, 𝔅, yPrᵒ\n else\n return ll, false, 𝔅, yPr\n end\nend\n\n\n#NOTE deprecated\n\"\"\"\n swapXX!(𝔅::ChequeredBlocking, XX)\n\nSwap containers between `XX` and `𝔅.XX`\n\"\"\"\nfunction swapXX!(𝔅::BlockingSchedule, XX)\n for block in 𝔅.blocks[𝔅.idx]\n swap!(XX, 𝔅.XX, block)\n end\nend\n\n#NOTE deprecated\n\"\"\"\n swapXX!(𝔅::NoBlocking, XX)\n\nnothing to do\n\"\"\"\nswapXX!(𝔅::NoBlocking, XX) = nothing\n\n\n\"\"\"\n noiseFromPath!(𝔅::BlockingSchedule, XX, WW, P)\n\nCompute driving Wiener noise `WW` from path `XX` drawn under law `P`\n\"\"\"\nfunction noiseFromPath!(𝔅::BlockingSchedule, XX, WW, P)\n for block in 𝔅.blocks[𝔅.idx]\n for i in block\n invSolve!(Euler(), XX[i], WW[i], P[i])\n end\n end\nend\n\n\n\"\"\"\n startPtLogPdf(::Val{1}, yPr::StartingPtPrior, y)\n\nCompute the log-likelihood contribution of the starting point for a given prior\nunder a blocking scheme (intended to be used with a first block only)\n\"\"\"\nstartPtLogPdf(::Val{1}, yPr::StartingPtPrior, y) = logpdf(yPr, y)\n\n\"\"\"\n startPtLogPdf(::Any, yPr::StartingPtPrior, y)\n\nDefault contribution to log-likelihood from the startin point under blocking\n\"\"\"\nstartPtLogPdf(::Any, yPr::StartingPtPrior, y) = 0.0\n\n\n#NOTE deprecated\n\"\"\"\n impute!(::ObsScheme, 𝔅::ChequeredBlocking, Wnr, y, WWᵒ, WW, XXᵒ, XX, P, ll,\n fpt; ρ=0.0, verbose=false, it=NaN, headStart=false) where\n ObsScheme <: AbstractObsScheme -> acceptedLogLikhd, acceptDecision\n\nImputation step of the MCMC scheme (without blocking).\n...\n# Arguments\n- `::ObsScheme`: observation scheme---first-passage time or partial observations\n- `𝔅`: object with relevant information about blocking\n- `Wnr`: type of the Wiener process\n- `yPr`: prior over the starting point of the diffusion path\n- `WWᵒ`: containers for proposal Wiener paths\n- `WW`: containers with old Wiener paths\n- `XXᵒ`: containers for proposal diffusion paths\n- `XX`: containers with old diffusion paths\n- `P`: laws of the diffusion path (proposal and target)\n- `11`: log-likelihood of the old (previously accepted) diffusion path\n- `fpt`: info about first-passage time conditioning\n- `ρ`: memory parameter for the Crank-Nicolson scheme\n- `verbose`: whether to print updates info while sampling\n- `it`: iteration index of the MCMC algorithm\n- `headStart`: flag for whether to 'ease into' fpt conditions\n...\n\"\"\"\nfunction impute!_deprecated(::ObsScheme, 𝔅::ChequeredBlocking, Wnr, yPr, WWᵒ, WW, XXᵒ, XX,\n P, ll, fpt; ρ=0.0, verbose=false, it=NaN, headStart=false,\n solver::ST=Ralston3()) where\n {ObsScheme <: AbstractObsScheme, ST}\n θ = params(P[1].Target) # current parameter\n 𝔅 = next(𝔅, XX, θ)\n solveBackRec!(𝔅, 𝔅.P, ST()) # compute (H, Hν, c) for given blocks\n\n swapXX!(𝔅, XX) # move current path to object 𝔅\n noiseFromPath!(𝔅, 𝔅.XX, 𝔅.WW, 𝔅.P) # find noise WW that generates XX under 𝔅\n\n # compute white noise generating starting point under 𝔅\n yPr𝔅 = invStartPt(𝔅.XX[1].yy[1], yPr, 𝔅.P[1])\n\n for (blockIdx, block) in enumerate(𝔅.blocks[𝔅.idx])\n blockFlag = Val{block[1]}()\n y = 𝔅.XX[block[1]].yy[1] # current starting point\n\n # set the starting point for the block\n yᵒ, yPrᵒ = proposalStartPt(𝔅, blockFlag, y, yPr𝔅, 𝔅.P[block[1]], ρ)\n\n # sample path in block\n sampleSegments!(block, Wnr, 𝔅.WW, 𝔅.WWᵒ, 𝔅.P, yᵒ, 𝔅.XXᵒ, ρ)\n setEndPtManually!(𝔅, blockIdx, block)\n\n # loglikelihoods\n llᵒ = startPtLogPdf(blockFlag, yPrᵒ, yᵒ)\n llᵒ += pathLogLikhd(ObsScheme(), 𝔅.XXᵒ, 𝔅.P, block, fpt)\n llᵒ += lobslikelihood(𝔅.P[block[1]], yᵒ)\n\n llPrev = startPtLogPdf(blockFlag, yPr𝔅, y)\n llPrev += pathLogLikhd(ObsScheme(), 𝔅.XX, 𝔅.P, block, fpt; skipFPT=true)\n llPrev += lobslikelihood(𝔅.P[block[1]], y)\n\n printInfo(verbose, it, value(llPrev), value(llᵒ), \"impute\")\n if acceptSample(llᵒ-llPrev, verbose)\n swap!(𝔅.XX, 𝔅.XXᵒ, block)\n registerAccpt!(𝔅, blockIdx, true)\n yPr𝔅 = yPrᵒ # can do something non-trivial only for the first block\n else\n registerAccpt!(𝔅, blockIdx, false)\n end\n end\n swapXX!(𝔅, XX) # move accepted path from object 𝔅 to general container XX\n noiseFromPath!(𝔅, XX, WW, P) # compute noise WW that generated XX under law P\n # compute white noise generating starting point under P\n y = XX[1].yy[1]\n yPr = invStartPt(y, yPr𝔅, P[1])\n\n ll = logpdf(yPr, y) # starting point contribution\n ll += pathLogLikhd(ObsScheme(), XX, P, 1:length(P), fpt; skipFPT=true)\n ll += lobslikelihood(P[1], y)\n\n # acceptance indicator does not matter for sampling with blocking\n return ll, true, 𝔅, yPr\nend\n\n\n\"\"\"\n impute!(::ObsScheme, 𝔅::ChequeredBlocking, Wnr, y, WWᵒ, WW, XXᵒ, XX, P, ll,\n fpt; ρ=0.0, verbose=false, it=NaN, headStart=false) where\n ObsScheme <: AbstractObsScheme -> acceptedLogLikhd, acceptDecision\n\nImputation step of the MCMC scheme (without blocking).\n...\n# Arguments\n- `::ObsScheme`: observation scheme---first-passage time or partial observations\n- `𝔅`: object with relevant information about blocking\n- `Wnr`: type of the Wiener process\n- `yPr`: prior over the starting point of the diffusion path\n- `WWᵒ`: containers for proposal Wiener paths\n- `WW`: containers with old Wiener paths\n- `XXᵒ`: containers for proposal diffusion paths\n- `XX`: containers with old diffusion paths\n- `P`: laws of the diffusion path (proposal and target)\n- `11`: log-likelihood of the old (previously accepted) diffusion path\n- `fpt`: info about first-passage time conditioning\n- `ρ`: memory parameter for the Crank-Nicolson scheme\n- `verbose`: whether to print updates info while sampling\n- `it`: iteration index of the MCMC algorithm\n- `headStart`: flag for whether to 'ease into' fpt conditions\n...\n\"\"\"\nfunction impute!(::ObsScheme, 𝔅::ChequeredBlocking, Wnr, yPr, WWᵒ, WW, XXᵒ, XX,\n P, ll, fpt; ρ=0.0, verbose=false, it=NaN, headStart=false,\n solver::ST=Ralston3()\n ) where {ObsScheme <: AbstractObsScheme, ST}\n θ = params(𝔅.P[1].Target) # current parameter\n 𝔅 = next(𝔅, 𝔅.XX, θ)\n solveBackRec!(𝔅, 𝔅.P, ST()) # compute (H, Hν, c) for given blocks\n noiseFromPath!(𝔅, 𝔅.XX, 𝔅.WW, 𝔅.P) # find noise WW that generates XX under 𝔅.P\n\n # compute white noise generating starting point under 𝔅\n yPr = invStartPt(𝔅.XX[1].yy[1], yPr, 𝔅.P[1])\n\n ll_total = 0.0\n for (blockIdx, block) in enumerate(𝔅.blocks[𝔅.idx])\n blockFlag = Val{block[1]}()\n y = 𝔅.XX[block[1]].yy[1] # accepted starting point\n\n # proposal starting point for the block (can be non-y only for the first block)\n yᵒ, yPrᵒ = proposalStartPt(𝔅, blockFlag, y, yPr, 𝔅.P[block[1]], ρ)\n\n # sample path in block\n sampleSegments!(block, Wnr, 𝔅.WW, 𝔅.WWᵒ, 𝔅.P , yᵒ, 𝔅.XXᵒ, ρ)\n setEndPtManually!(𝔅, blockIdx, block)\n\n # starting point, path and observations contribution\n llᵒ = startPtLogPdf(blockFlag, yPrᵒ, yᵒ)\n llᵒ += pathLogLikhd(ObsScheme(), 𝔅.XXᵒ, 𝔅.P, block, fpt)\n llᵒ += lobslikelihood(𝔅.P[block[1]], yᵒ)\n\n llPrev = startPtLogPdf(blockFlag, yPr, y)\n llPrev += pathLogLikhd(ObsScheme(), 𝔅.XX, 𝔅.P, block, fpt; skipFPT=true)\n llPrev += lobslikelihood(𝔅.P[block[1]], y)\n\n printInfo(verbose, it, value(llPrev), value(llᵒ), \"impute\")\n if acceptSample(llᵒ-llPrev, verbose)\n swap!(𝔅.XX, 𝔅.XXᵒ, block)\n registerAccpt!(𝔅, blockIdx, true)\n yPr = yPrᵒ # can do something non-trivial only for the first block\n ll_total += llᵒ\n else\n registerAccpt!(𝔅, blockIdx, false)\n ll_total += llPrev\n end\n end\n # acceptance indicator does not matter for sampling with blocking\n return ll_total, true, 𝔅, yPr\nend\n\n\"\"\"\n updateLaws!(Ps, θᵒ)\n\nSet new parameter `θᵒ` for the laws in vector `Ps`\n\"\"\"\nfunction updateLaws!(Ps, θᵒ)\n m = length(Ps)\n for i in 1:m\n Ps[i] = GuidPropBridge(Ps[i], θᵒ)\n end\nend\n\n\"\"\"\n updateTargetLaws!(𝔅::NoBlocking, θᵒ)\n\nNothing to do\n\"\"\"\nupdateTargetLaws!(𝔅::NoBlocking, θᵒ) = nothing\n\n\"\"\"\n updateTargetLaws!(𝔅::BlockingSchedule, θᵒ)\n\nSet new parameter `θᵒ` for the target laws in blocking object `𝔅`\n\"\"\"\nfunction updateTargetLaws!(𝔅::BlockingSchedule, θᵒ)\n for block in 𝔅.blocks[𝔅.idx]\n for i in block\n 𝔅.P[i] = GuidPropBridge(𝔅.P[i], θᵒ)\n end\n end\nend\n\n\"\"\"\n updateProposalLaws!(𝔅::BlockingSchedule, θᵒ)\n\nSet new parameter `θᵒ` for the proposal laws inside blocking object `𝔅`\n\"\"\"\nfunction updateProposalLaws!(𝔅::BlockingSchedule, θᵒ)\n for block in 𝔅.blocks[𝔅.idx]\n for i in block\n 𝔅.Pᵒ[i] = GuidPropBridge(𝔅.Pᵒ[i], θᵒ)\n end\n end\nend\n\n\"\"\"\n findPathFromWiener!(XX, y, WW, P, iRange)\n\nFind path `XX` (that starts from `y`) that is generated under law `P` from the\nWiener process `WW`. Only segments with indices in range `iRange` are considered\n\"\"\"\nfunction findPathFromWiener!(XX, y, WW, P, iRange)\n for i in iRange\n solve!(Euler(), XX[i], y, WW[i], P[i])\n y = XX[i].yy[end]\n end\nend\n\n\n\"\"\"\n priorKernelContrib(tKern, priors, θ, θᵒ)\n\nContribution to the log-likelihood ratio from transition kernel `tKernel` and\n`priors`.\n\"\"\"\nfunction priorKernelContrib(tKern, priors, θ, θᵒ)\n llr = logpdf(tKern, θᵒ, θ) - logpdf(tKern, θ, θᵒ)\n for prior in priors\n llr += logpdf(prior, θᵒ) - logpdf(prior, θ)\n end\n llr\nend\n\n\n\"\"\"\n setEndPtManually!(𝔅::BlockingSchedule, blockIdx, block)\n\nManually set the end-point of the proposal path under blocking so that it agrees\nwith the end-point of the previously accepted path. If it is the last block,\nthen do nothing\n\"\"\"\nfunction setEndPtManually!(𝔅::BlockingSchedule, blockIdx, block)\n if blockIdx < length(𝔅.blocks[𝔅.idx])\n 𝔅.XXᵒ[block[end]].yy[end] = 𝔅.XX[block[end]].yy[end]\n end\nend\n\n\n\"\"\"\n updateParam!(::ObsScheme, ::MetropolisHastingsUpdt, tKern, θ, ::UpdtIdx,\n yPr, WW, Pᵒ, P, XXᵒ, XX, ll, prior, fpt, recomputeODEs;\n solver::ST=Ralston3(), verbose=false,\n it=NaN) where {ObsScheme <: AbstractObsScheme, ST, UpdtIdx}\n -> acceptedLogLikhd, acceptDecision\nUpdate parameters\n...\n# Arguments\n- `::ObsScheme`: observation scheme---first-passage time or partial observations\n- `::MetropolisHastingsUpdt()`: type of the parameter update\n- `tKern`: transition kernel\n- `θ`: current value of the parameter\n- `updtIdx`: object declaring indices of the updated parameter\n- `yPr`: prior over the starting point of the diffusion path\n- `WW`: containers with Wiener paths\n- `Pᵒ`: container for the laws of the diffusion path with new parametrisation\n- `P`: laws of the diffusion path with old parametrisation\n- `XXᵒ`: containers for proposal diffusion paths\n- `XX`: containers with old diffusion paths\n- `11`: likelihood of the old (previously accepted) parametrisation\n- `priors`: list of priors\n- `fpt`: info about first-passage time conditioning\n- `recomputeODEs`: whether auxiliary law depends on the updated params\n- `verbose`: whether to print updates info while sampling\n- `it`: iteration index of the MCMC algorithm\n...\n\"\"\"\nfunction updateParam!(::ObsScheme, ::MetropolisHastingsUpdt, 𝔅::NoBlocking,\n tKern, θ, ::UpdtIdx, yPr, WW, Pᵒ, P, XXᵒ, XX, ll, priors,\n fpt, recomputeODEs; solver::ST=Ralston3(), verbose=false,\n it=NaN) where {ObsScheme <: AbstractObsScheme, ST, UpdtIdx}\n m = length(WW)\n θᵒ = rand(tKern, θ, UpdtIdx()) # sample new parameter\n updateLaws!(Pᵒ, θᵒ)\n recomputeODEs && solveBackRec!(NoBlocking(), Pᵒ, ST()) # compute (H, Hν, c)\n\n # find white noise which for a given θᵒ gives a correct starting point\n y = XX[1].yy[1]\n yPrᵒ = invStartPt(y, yPr, Pᵒ[1])\n\n findPathFromWiener!(XXᵒ, y, WW, Pᵒ, 1:m)\n\n llᵒ = logpdf(yPrᵒ, y)\n llᵒ += pathLogLikhd(ObsScheme(), XXᵒ, Pᵒ, 1:m, fpt)\n llᵒ += lobslikelihood(Pᵒ[1], y)\n\n printInfo(verbose, it, ll, llᵒ)\n\n llr = ( llᵒ - ll + priorKernelContrib(tKern, priors, θ, θᵒ))\n\n # Accept / reject\n if acceptSample(llr, verbose)\n swap!(XX, XXᵒ, P, Pᵒ, 1:m)\n return llᵒ, true, θᵒ, yPrᵒ\n else\n return ll, false, θ, yPr\n end\nend\n\n\n\"\"\"\n updateParam!(::ObsScheme, ::MetropolisHastingsUpdt, tKern, θ, ::UpdtIdx,\n yPr, WW, Pᵒ, P, XXᵒ, XX, ll, prior, fpt, recomputeODEs;\n solver::ST=Ralston3(), verbose=false,\n it=NaN) where {ObsScheme <: AbstractObsScheme, ST, UpdtIdx}\n -> acceptedLogLikhd, acceptDecision\nUpdate parameters\n...\n# Arguments\n- `::ObsScheme`: observation scheme---first-passage time or partial observations\n- `::MetropolisHastingsUpdt()`: type of the parameter update\n- `tKern`: transition kernel\n- `θ`: current value of the parameter\n- `updtIdx`: object declaring indices of the updated parameter\n- `yPr`: prior over the starting point of the diffusion path\n- `WW`: containers with Wiener paths\n- `Pᵒ`: container for the laws of the diffusion path with new parametrisation\n- `P`: laws of the diffusion path with old parametrisation\n- `XXᵒ`: containers for proposal diffusion paths\n- `XX`: containers with old diffusion paths\n- `11`: likelihood of the old (previously accepted) parametrisation\n- `priors`: list of priors\n- `fpt`: info about first-passage time conditioning\n- `recomputeODEs`: whether auxiliary law depends on the updated params\n- `verbose`: whether to print updates info while sampling\n- `it`: iteration index of the MCMC algorithm\n...\n\"\"\"\nfunction updateParam!(::ObsScheme, ::MetropolisHastingsUpdt,\n 𝔅::ChequeredBlocking, tKern, θ, ::UpdtIdx,\n yPr, WW, Pᵒ, P, XXᵒ, XX, ll, priors, fpt, recomputeODEs;\n solver::ST=Ralston3(), verbose=false,\n it=NaN) where {ObsScheme <: AbstractObsScheme, ST, UpdtIdx}\n m = length(WW)\n θᵒ = rand(tKern, θ, UpdtIdx()) # sample new parameter\n updateProposalLaws!(𝔅, θᵒ) # update law `Pᵒ` accordingly\n solveBackRec!(𝔅, 𝔅.Pᵒ, ST()) # compute (H, Hν, c)\n\n llᵒ = logpdf(yPr, 𝔅.XX[1].yy[1])\n for (blockIdx, block) in enumerate(𝔅.blocks[𝔅.idx])\n y = 𝔅.XX[block[1]].yy[1]\n findPathFromWiener!(𝔅.XXᵒ, y, 𝔅.WW, 𝔅.Pᵒ, block)\n setEndPtManually!(𝔅, blockIdx, block)\n\n # Compute log-likelihood ratio\n llᵒ += pathLogLikhd(ObsScheme(), 𝔅.XXᵒ, 𝔅.Pᵒ, block, fpt)\n llᵒ += lobslikelihood(𝔅.Pᵒ[block[1]], y)\n end\n printInfo(verbose, it, ll, llᵒ)\n\n llr = ( llᵒ - ll + priorKernelContrib(tKern, priors, θ, θᵒ))\n\n # Accept / reject\n if acceptSample(llr, verbose)\n swap!(𝔅.XX, 𝔅.XXᵒ, 𝔅.P, 𝔅.Pᵒ, 1:m)\n return llᵒ, true, θᵒ, yPr\n else\n return ll, false, θ, yPr\n end\nend\n\n\nfetchTargetLaw(𝔅::NoBlocking, P) = P[1].Target\n\nfetchTargetLaw(𝔅::BlockingSchedule, P) = 𝔅.P[1].Target\n\n\n\"\"\"\n updateParam!(::PartObs, ::ConjugateUpdt, tKern, θ, ::UpdtIdx, yPr, WW, Pᵒ,\n P, XXᵒ, XX, ll, priors, fpt, recomputeODEs;\n solver::ST=Ralston3(), verbose=false, it=NaN\n ) -> acceptedLogLikhd, acceptDecision\nUpdate parameters\nsee the definition of updateParam!(…, ::MetropolisHastingsUpdt, …) for the\nexplanation of the arguments.\n\"\"\"\nfunction updateParam!(::ObsScheme, ::ConjugateUpdt, 𝔅::NoBlocking,\n tKern, θ, ::UpdtIdx, yPr, WW, Pᵒ, P, XXᵒ, XX, ll, priors,\n fpt, recomputeODEs; solver::ST=Ralston3(), verbose=false,\n it=NaN) where {ObsScheme <: AbstractObsScheme, ST, UpdtIdx}\n m = length(P)\n ϑ = conjugateDraw(θ, XX, P[1].Target, priors[1], UpdtIdx()) # sample new parameter\n θᵒ = moveToProperPlace(ϑ, θ, UpdtIdx()) # align so that dimensions agree\n\n updateLaws!(P, θᵒ)\n recomputeODEs && solveBackRec!(NoBlocking(), P, ST()) # compute (H, Hν, c)\n\n for i in 1:m # compute wiener path WW that generates XX\n invSolve!(Euler(), XX[i], WW[i], P[i])\n end\n # compute white noise that generates starting point\n y = XX[1].yy[1]\n yPr = invStartPt(y, yPr, P[1])\n\n llᵒ = logpdf(yPr, y)\n llᵒ += pathLogLikhd(ObsScheme(), XX, P, 1:m, fpt; skipFPT=true)\n llᵒ += lobslikelihood(P[1], y)\n printInfo(verbose, it, value(ll), value(llᵒ))\n return llᵒ, true, θᵒ, yPr\nend\n\n\n\"\"\"\n updateParam!(::PartObs, ::ConjugateUpdt, tKern, θ, ::UpdtIdx, yPr, WW, Pᵒ,\n P, XXᵒ, XX, ll, priors, fpt, recomputeODEs;\n solver::ST=Ralston3(), verbose=false, it=NaN\n ) -> acceptedLogLikhd, acceptDecision\nUpdate parameters\nsee the definition of updateParam!(…, ::MetropolisHastingsUpdt, …) for the\nexplanation of the arguments.\n\"\"\"\nfunction updateParam!(::ObsScheme, ::ConjugateUpdt, 𝔅::BlockingSchedule,\n tKern, θ, ::UpdtIdx, yPr, WW, Pᵒ, P, XXᵒ, XX, ll, priors,\n fpt, recomputeODEs; solver::ST=Ralston3(), verbose=false,\n it=NaN) where {ObsScheme <: AbstractObsScheme, ST, UpdtIdx}\n m = length(P)\n ϑ = conjugateDraw(θ, 𝔅.XX, 𝔅.P[1].Target, priors[1], UpdtIdx()) # sample new parameter\n θᵒ = moveToProperPlace(ϑ, θ, UpdtIdx()) # align so that dimensions agree\n\n updateTargetLaws!(𝔅, θᵒ)\n recomputeODEs && solveBackRec!(𝔅, 𝔅.P, ST())\n for i in 1:m # compute wiener path WW that generates XX\n invSolve!(Euler(), 𝔅.XX[i], 𝔅.WW[i], 𝔅.P[i])\n end\n # compute white noise that generates starting point\n y = 𝔅.XX[1].yy[1]\n yPr = invStartPt(y, yPr, 𝔅.P[1])\n llᵒ = logpdf(yPr, y)\n for block in 𝔅.blocks[𝔅.idx]\n llᵒ += pathLogLikhd(ObsScheme(), 𝔅.XX, 𝔅.P, block, fpt; skipFPT=true)\n llᵒ += lobslikelihood(𝔅.P[block[1]], 𝔅.XX[block[1]].yy[1])\n end\n printInfo(verbose, it, value(ll), value(llᵒ))\n return llᵒ, true, θᵒ, yPr\nend\n\n\n\"\"\"\n mcmc(::ObsScheme, obs, obsTimes, yPr::StartingPtPrior, w, P˟, P̃, Ls, Σs,\n numSteps, tKernel, priors; fpt=fill(NaN, length(obsTimes)-1), ρ=0.0,\n dt=1/5000, timeChange=true, saveIter=NaN, verbIter=NaN,\n updtCoord=(Val((true,)),), paramUpdt=true, skipForSave=1,\n updtType=(MetropolisHastingsUpdt(),), solver::ST=Ralston3(), warmUp=0)\n\nGibbs sampler alternately imputing unobserved parts of the path and updating\nunknown coordinates of the parameter vector (the latter only if paramUpdt==true)\n...\n# Arguments\n- `::ObsScheme`: observation scheme---first-passage time or partial observations\n- `obs`: vector with observations\n- `obsTimes`: times of the observations\n- `yPr`: prior over the starting point of the diffusion path\n- `w`: dummy variable whose type must agree with the type of the Wiener process\n- `P˟`: law of the target diffusion (with initial θ₀ set)\n- `P̃`: law of the auxiliary process (with initial θ₀ set)\n- `Ls`: vector of observation operators (one per each observation)\n- `Σs`: vector of covariance matrices of the noise (one per each observaiton)\n- `numSteps`: number of mcmc iterations\n- `tKernel`: transition kernel (also with initial θ₀ set)\n- `priors`: a list of lists of priors\n- `τ`: time-change transformation\n- `fpt`: info about first-passage time conditioning\n- `ρ`: memory parameter for the Crank-Nicolson scheme\n- `dt`: time-distance for the path imputation\n- `saveIter`: save path `XX` once every `saveIter` many iterations\n- `verbIter`: print out progress info once every `verbIter` many iterations\n- `updtCoord`: list of objects declaring indices of to-be-updated parameters\n- `paramUpdt`: flag for whether to update parameters at all\n- `skipForSave`: when saving paths, save only one in every `skipForSave` points\n- `updtType`: list of types of updates to cycle through\n- `solver`: numerical solver used for computing backward ODEs\n- `warmUp`: number of steps for which no parameter update is to be made\n...\n\"\"\"\nfunction mcmc(::Type{K}, ::ObsScheme, obs, obsTimes, yPr::StartingPtPrior, w,\n P˟, P̃, Ls, Σs, numSteps, tKernel, priors, τ;\n fpt=fill(NaN, length(obsTimes)-1), ρ=0.0, dt=1/5000, saveIter=NaN,\n verbIter=NaN, updtCoord=(Val((true,)),), paramUpdt=true,\n skipForSave=1, updtType=(MetropolisHastingsUpdt(),),\n blocking::Blocking=NoBlocking(),\n blockingParams=([], 0.1, NoChangePt()),\n solver::ST=Ralston3(), changePt::CP=NoChangePt(), warmUp=0\n ) where {K, ObsScheme <: AbstractObsScheme, ST, Blocking, CP}\n P = findProposalLaw( K, obs, obsTimes, P˟, P̃, Ls, Σs, τ; dt=dt, solver=ST(),\n changePt=CP(getChangePt(blockingParams[3])) )\n m = length(obs)-1\n updtLen = length(updtCoord)\n Wnr, WWᵒ, WW, XXᵒ, XX, Pᵒ, ll, yPr = initialise(ObsScheme(), P, m, yPr, w,\n fpt)\n Paths = []\n accImpCounter = 0\n accUpdtCounter = [0 for i in 1:updtLen]\n θ = params(P˟)\n θchain = Vector{typeof(θ)}(undef, (numSteps-warmUp)*updtLen+1)\n θchain[1] = copy(θ)\n recomputeODEs = [any([e in dependsOnParams(P[1].Pt) for e\n in idx(uc)]) for uc in updtCoord]\n\n updtStepCounter = 1\n 𝔅 = setBlocking(blocking, blockingParams, P, WW, XX)\n display(𝔅)\n for i in 1:numSteps\n verbose = (i % verbIter == 0)\n i > warmUp && savePath!(Paths, blocking == NoBlocking() ? XX : 𝔅.XX,\n (i % saveIter == 0), skipForSave)\n ll, acc, 𝔅, yPr = impute!(ObsScheme(), 𝔅, Wnr, yPr, WWᵒ, WW, XXᵒ, XX,\n P, ll, fpt, ρ=ρ, verbose=verbose, it=i,\n solver=ST())\n accImpCounter += 1*acc\n if paramUpdt && i > warmUp\n for j in 1:updtLen\n (ll, acc, θ,\n yPr) = updateParam!(ObsScheme(), updtType[j], 𝔅, tKernel, θ,\n updtCoord[j], yPr, WW, Pᵒ, P, XXᵒ, XX, ll,\n priors[j], fpt, recomputeODEs[j];\n solver=ST(), verbose=verbose, it=i)\n accUpdtCounter[j] += 1*acc\n updtStepCounter += 1\n θchain[updtStepCounter] = copy(θ)\n verbose && print(\"\\n\")\n end\n verbose && print(\"------------------------------------------------\",\n \"------\\n\")\n end\n end\n displayAcceptanceRate(𝔅)\n Time = collect(Iterators.flatten(p.tt[1:skipForSave:end-1] for p in P))\n θchain, accImpCounter/numSteps, accUpdtCounter./numSteps, Paths, Time\nend\n", "meta": {"hexsha": "977afebc641fcf96d02b07dea1a964da0910b22e", "size": 38136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mcmc.jl", "max_stars_repo_name": "mschauer/BridgeSDEInference.jl", "max_stars_repo_head_hexsha": "a5859fb56fb03c665f9f925dc8b3fd6003773ae3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mcmc.jl", "max_issues_repo_name": "mschauer/BridgeSDEInference.jl", "max_issues_repo_head_hexsha": "a5859fb56fb03c665f9f925dc8b3fd6003773ae3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mcmc.jl", "max_forks_repo_name": "mschauer/BridgeSDEInference.jl", "max_forks_repo_head_hexsha": "a5859fb56fb03c665f9f925dc8b3fd6003773ae3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2641509434, "max_line_length": 92, "alphanum_fraction": 0.6348332284, "num_tokens": 12397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2458689177634208}} {"text": "\n\"\"\"\n@axpy\n@ascal\n@dot\n\nBLAS Level 1 functions.\n\"\"\"\n\nmacro axpy(a, x, y)\n expr = quote\n let u = $(esc(a))\n for i in eachindex($(esc(x)))\n @inbounds $(esc(y))[i] += u * $(esc(x))[i]\n end\n end\n end\n expr\nend\n\nmacro scal(a, x)\n expr = quote\n let u = $(esc(a))\n for i in eachindex($(esc(x)))\n @inbounds $(esc(x))[i] *= u\n end\n end\n end\n expr\nend\n\nmacro dot(x, y)\n expr = quote\n s = 0\n for i in eachindex($(esc(x)))\n @inbounds s += $(esc(x))[i] * $(esc(y))[i]\n end\n s\n end\n expr\nend\n\n\"\"\"\nitime(t)\n\nGet interval time from a given cumulative time vector t.\nThe first element is t[1]\n\nRetuen value:\ndt: interval time vector\nmaxt: maximum interval time\n\"\"\"\n\nfunction itime(t::AbstractVector{Tv}) where Tv\n dt = similar(t)\n prev = Tv(0)\n maxt = Tv(0)\n @inbounds for i = eachindex(t)\n dt[i] = t[i] - prev\n prev = t[i]\n if dt[i] > maxt\n maxt = dt[i]\n end\n end\n return dt, maxt\nend\n", "meta": {"hexsha": "a0882238317a5d5c88efc18b6ef2d3c44ed95243", "size": 1094, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/_common.jl", "max_stars_repo_name": "JuliaReliab/NMarkov.jl", "max_stars_repo_head_hexsha": "cdaacdfe9801af84ea5f6a9cbb4108d77e2a8a0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/_common.jl", "max_issues_repo_name": "JuliaReliab/NMarkov.jl", "max_issues_repo_head_hexsha": "cdaacdfe9801af84ea5f6a9cbb4108d77e2a8a0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-07T06:12:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-07T06:13:58.000Z", "max_forks_repo_path": "src/_common.jl", "max_forks_repo_name": "JuliaReliab/NMarkov.jl", "max_forks_repo_head_hexsha": "cdaacdfe9801af84ea5f6a9cbb4108d77e2a8a0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.328358209, "max_line_length": 58, "alphanum_fraction": 0.478976234, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.24586891776342076}} {"text": "\n\"\"\"\n`module JAC.RayleighCompton` \n ... a submodel of JAC that contains all methods for computing elastic Rayleigh and inelastic Compton photon scattering cross sections.\n\"\"\"\nmodule RayleighCompton\n\n using Printf, ..AngularMomentum, ..AtomicState, ..Basics, ..Defaults, ..ManyElectron, ..Radial, ..TableStrings\n\n\n \"\"\"\n `struct RayleighCompton.Settings` ... defines a type for the settings in estimating lastic Rayleigh and inelastic Compton \n photon scattering cross sections\n\n + multipoles ::Array{EmMultipole} ... Specifies the multipoles of the radiation field that are to be included.\n + gauges ::Array{UseGauge} ... Specifies the gauges to be included into the computations.\n + photonEnergies ::Array{Float64,1} ... List of photon energies in units defined by the user.\n + green ::Array{GreenChannel,1} ... Precalculated and user-specified Green function of the ion.\n + calcAngular ::Bool ... Calculate the angular distribution of the fluorescence photon.\n + calcStokes ::Bool ... Calculate the Stokes parameters of the Rayleigh-scattered photon.\n + printBefore ::Bool ... True, if all energies and lines are printed before their evaluation.\n + incidentStokes ::ExpStokes ... Stokes parameters of the incident radiation.\n + solidAngles ::Array{SolidAngle,1} ... List of solid angles [(theta_1, pho_1), ...]. \n + lineSelection ::LineSelection ... Specifies the selected levels, if any.\n\n \"\"\"\n struct Settings \n multipoles ::Array{EmMultipole}\n gauges ::Array{UseGauge}\n photonEnergies ::Array{Float64,1} \n green ::Array{AtomicState.GreenChannel,1}\n calcAngular ::Bool\n calcStokes ::Bool\n printBefore ::Bool \n incidentStokes ::ExpStokes \n solidAngles ::Array{SolidAngle,1}\n lineSelection ::LineSelection\n end \n\n\n \"\"\"\n `RayleighCompton.Settings()` ... constructor for the default values of Rayleigh-Compton photon-scattering estimates.\n \"\"\"\n function Settings()\n Settings(EmMultipole[], UseGauge[], GreenChannel[], 0., false, false, false, ExpStokes(), SolidAngle[], LineSelection() )\n end\n\n\n # `Base.show(io::IO, settings::RayleighCompton.Settings)` ... prepares a proper printout of the variable settings::RayleighCompton.Settings.\n function Base.show(io::IO, settings::RayleighCompton.Settings) \n println(io, \"multipoles: $(settings.multipoles) \")\n println(io, \"gauges: $(settings.gauges) \")\n println(io, \"photonEnergies: $(settings.photonEnergies) \")\n println(io, \"green: (settings.green) \")\n println(io, \"calcAngular: $(settings.calcAngular) \")\n println(io, \"calcStokes: $(settings.calcStokes) \")\n println(io, \"printBefore: $(settings.printBefore) \")\n println(io, \"incidentStokes: $(settings.incidentStokes) \")\n println(io, \"solidAngles: $(settings.solidAngles) \")\n println(io, \"lineSelection: $(settings.lineSelection) \")\n end\n\n\n \"\"\"\n `struct RayleighCompton.ReducedChannel` \n ... defines a type for a Rayleigh-Compton reduced channel/ U^(K, Compton) amplitude to help characterize the scattering of \n a single photon with well-defined multipolarities; in JAC, a Rayleigh-Compton channel is characterized by a reduced amplitude \n U^(K, Compton) (level_f, multipole_2, J_nu, omega, multipole_1, level_i).\n\n + K ::AngularJ64 ... Rank K of the channel.\n + multipole1 ::EmMultipole ... Multipole of the incoming photon.\n + multipole2 ::EmMultipole ... Multipole of the outgoing, scattered photon.\n + gauge ::EmGauge ... Gauge for dealing with the (coupled) radiation field.\n + omega1 ::Float64 ... Photon frequency of multipole1.\n + omega2 ::Float64 ... Photon frequency of multipole2.\n + omega ::Float64 ... Photon frequency in denominator.\n + Jsym ::LevelSymmetry ... Symmetry J_nu of the intermediate levels.\n + amplitude ::Complex{Float64} ... Two-photon reduced amplitude associated with the given channel.\n \"\"\"\n struct ReducedChannel\n K ::AngularJ64\n multipole1 ::EmMultipole\n multipole2 ::EmMultipole\n gauge ::EmGauge \n omega1 ::Float64\n omega2 ::Float64\n omega ::Float64\n Jsym ::LevelSymmetry\n amplitude ::Complex{Float64}\n end\n\n\n \"\"\"\n `struct RayleighCompton.Line` ... defines a type for a Rayleigh-Compton scattering line that may include the definition of channels.\n\n + initialLevel ::Level ... initial-(state) level\n + finalLevel ::Level ... final-(state) level\n + inOmega ::Float64 ... Energy of the incoming photon.\n + outOmega ::Float64 ... Energy of the outgoing, scattered photon.\n + crossSection ::EmProperty ... Cross section for this photoionization.\n + channels ::Array{RayleighCompton.ReducedChannel,1} ... List of (reduced) RayleighCompton.Channels of this line.\n \"\"\"\n struct Line\n initialLevel ::Level\n finalLevel ::Level\n inOmega ::Float64\n outOmega ::Float64\n crossSection ::EmProperty\n channels ::Array{RayleighCompton.ReducedChannel,1}\n end\n\n\n # `Base.show(io::IO, line::RayleighCompton.Line)` ... prepares a proper printout of the variable line::RayleighCompton.Line.\n function Base.show(io::IO, line::RayleighCompton.Line) \n println(io, \"initialLevel: $(line.initialLevel) \")\n println(io, \"finalLevel: $(line.finalLevel) \")\n println(io, \"inOmega: $(line.inOmega) \")\n println(io, \"outOmega: $(line.outOmega) \")\n println(io, \"crossSection: $(line.crossSection) \")\n println(io, \"channels: $(line.channels) \")\n end\n\n\n \"\"\"\n `RayleighCompton.computeAmplitudesProperties(line::RayleighCompton.Line, grid::Radial.Grid, settings::RayleighCompton.Settings)` \n ... to compute all amplitudes and properties of the given line; a line::RayleighCompton.Line is returned for which \n the amplitudes and properties are now evaluated.\n \"\"\"\n function computeAmplitudesProperties(line::RayleighCompton.Line, grid::Radial.Grid, settings::RayleighCompton.Settings)\n newChannels = RayleighCompton.ReducedChannel[]\n for ch in line.channels\n amplitude = RayleighCompton.computeReducedAmplitude(ch.K, line.finalLevel, ch.multipole2, ch.omega2, ch.Jsym, ch.omega, \n ch.multipole1, ch.omega1, line.initialLevel, ch.gauge, grid, settings.green)\n push!( newChannels, ReducedChannel(ch.K, ch.multipole1, ch.multipole2, ch.gauge, ch.omega1, ch.omega2, ch.omega, ch.Jsym, amplitude) )\n end\n cs_Cou = 0.; cs_Bab = 0.\n crossSection = EmProperty(cs_Cou, cs_Bab)\n newLine = RayleighCompton.Line(line.initialLevel, line.finalLevel, line.inOmega, line.outOmega, crossSection, newChannels)\n return( newLine )\n end\n\n\n \"\"\"\n `RayleighCompton.computeLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, grid::Radial.Grid, settings::RayleighCompton.Settings; output=true)` \n ... to compute the Rayleigh-Compton transition amplitudes and all properties as requested by the given settings. A list of \n lines::Array{RayleighCompton.Lines} is returned.\n \"\"\"\n function computeLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, grid::Radial.Grid, settings::RayleighCompton.Settings; output=true)\n println(\"\")\n printstyled(\"RayleighCompton.computeLines(): The computation of Rayleigh-Compton reduced amplitudes starts now ... \\n\", color=:light_green)\n printstyled(\"----------------------------------------------------------------------------------------------------- \\n\", color=:light_green)\n println(\"\")\n #\n lines = RayleighCompton.determineLines(finalMultiplet, initialMultiplet, settings)\n # Display all selected pathways before the computations start\n if settings.printBefore RayleighCompton.displayLines(stdout, lines) end\n # Calculate all reduced amplitudes and requested properties\n newLines = RayleighCompton.Line[]\n for line in lines\n newLine = RayleighCompton.computeAmplitudesProperties(line, grid, settings) \n push!( newLines, newLine)\n end\n # Print all results to screen\n RayleighCompton.displayCrossSections(stdout, newLines, settings)\n if settings.calcAngular RayleighCompton.displayAngular(stdout, newLines, settings) end\n if settings.calcStokes RayleighCompton.displayStokesParameters(stdout, newLines, settings) end\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n if printSummary \n if settings.calcAngular RayleighCompton.displayAngular(stdout, newLines, settings) end\n if settings.calcStokes RayleighCompton.displayStokesParameters(stdout, newLines, settings) end\n end\n \n if output return( lines )\n else return( nothing )\n end\n end\n\n\n \"\"\"\n `RayleighCompton.computeReducedAmplitude(K::AngularJ64, finalLevel::Level, multipole2::EmMultipole, omega2::Float64, Jsym::LevelSymmetry, \n omega::Float64, multipole1::EmMultipole, omega1::Float64, initialLevel::Level, gauge::EmGauge, \n grid::Radial.Grid, greenChannels::Array{AtomicState.GreenChannel,1})` \n ... to compute the reduced amplitudes U^(K, Compton) as well as all properties of the given line; \n a line::RayleighCompton.Line is returned for which the reduced amplitudes and properties are now evaluated.\n \"\"\"\n function computeReducedAmplitude(K::AngularJ64, finalLevel::Level, multipole2::EmMultipole, omega2::Float64, Jsym::LevelSymmetry, \n omega::Float64, multipole1::EmMultipole, omega1::Float64, initialLevel::Level, gauge::EmGauge, \n grid::Radial.Grid, greenChannels::Array{AtomicState.GreenChannel,1})\n amplitude = 0.0im\n return( amplitude )\n end\n \n\n \"\"\"\n `RayleighCompton.determineChannels(finalLevel::Level, initialLevel::Level, inOmega::Float64, outOmega::Float64, settings::RayleighCompton.Settings)` \n ... to determine a list of Rayleigh-Compton ReducedChannelChannel's for a transitions from the initial to final level and by taking \n into account the particular settings of for this computation; an Array{RayleighCompton.ReducedChannelChannel,1} is returned.\n \"\"\"\n function determineChannels(finalLevel::Level, initialLevel::Level, inOmega::Float64, outOmega::Float64, settings::RayleighCompton.Settings)\n channels = RayleighCompton.ReducedChannel[]; \n symi = LevelSymmetry(initialLevel.J, initialLevel.parity); symf = LevelSymmetry(finalLevel.J, finalLevel.parity) \n for mp1 in settings.multipoles\n for mp2 in settings.multipoles\n symmetries = AngularMomentum.allowedTotalSymmetries(symf, mp2, mp1, symi)\n Klist = oplus(symf.J, symi.J)\n for symn in symmetries\n for gauge in settings.gauges\n # Include further restrictions if appropriate\n if string(mp1)[1] == 'E' || string(mp2)[1] == 'E' && gauge == Basics.UseCoulomb\n for K in Klist push!(channels, ReducedChannel(K, mp1, mp2, Basics.Coulomb, inOmega, outOmega, inOmega, symn, 0.) ) end \n elseif string(mp1)[1] == 'E' || string(mp2)[1] == 'E' && gauge == Basics.UseBabushkin \n for K in Klist push!(channels, ReducedChannel(K, mp1, mp2, Basics.Babushkin, inOmega, outOmega, inOmega, symn, 0.) ) end\n elseif string(mp1)[1] == 'M' && string(mp2)[1] == 'M'\n for K in Klist push!(channels, ReducedChannel(K, mp1, mp2, Basics.Magnetic, inOmega, outOmega, inOmega, symn, 0.) ) end\n end\n end\n end \n end\n end\n # Unify channels\n return( channels ) \n end\n\n\n \"\"\"\n `RayleighCompton.determineLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, settings::RayleighCompton.Settings)` \n ... to determine a list of RayleighCompton Line's for elastic scattering or Raman-type transitions between the levels from \n the given initial- and final-state multiplets and by taking into account the particular selections and settings for \n this computation; an Array{RayleighCompton.Line,1} is returned. Apart from the level specification, all physical \n properties are set to zero during the initialization process. \n \"\"\"\n function determineLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, settings::RayleighCompton.Settings)\n lines = RayleighCompton.Line[]\n for iLevel in initialMultiplet.levels\n for fLevel in finalMultiplet.levels\n if Basics.selectLevelPair(iLevel, fLevel, settings.lineSelection)\n for omega in settings.photonEnergies\n inOmega = Defaults.convertUnits(\"energy: to atomic\", omega) \n outOmega = inOmega - (fLevel.energy - iLevel.energy); if outOmega <= 0. continue end \n channels = RayleighCompton.determineChannels(fLevel, iLevel, inOmega, outOmega, settings) \n if length(channels) == 0 continue end\n push!( lines, RayleighCompton.Line(iLevel, fLevel, inOmega, outOmega, EmProperty(0., 0.), channels) )\n end\n end\n end\n end\n return( lines )\n end\n\n\n \"\"\"\n `RayleighCompton.displayAngular(stream::IO, lines::Array{RayleighCompton.Line,1}, settings::RayleighCompton.Settings)` \n ... to display a list of lines and the angle-differential cross sections for the selected solid angles. \n A neat table of all selected transitions, energies and solid angles is printed but nothing is returned otherwise.\n \"\"\"\n function displayAngular(stream::IO, lines::Array{RayleighCompton.Line,1}, settings::RayleighCompton.Settings)\n nx = 127\n println(stream, \" \")\n println(stream, \" Angular distribution of the selected Rayleigh-Compton scattering lines at seleced solid angles: ... to be adapted !!\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"; sc = \" \"\n sa = sa * TableStrings.center(16, \"i-level-f\"; na=2); sb = sb * TableStrings.hBlank(18)\n sa = sa * TableStrings.center(16, \"i--J^P--f\"; na=7); sb = sb * TableStrings.hBlank(23)\n sa = sa * TableStrings.center(20, \"i -- Energy -- f\"; na=3); \n sb = sb * TableStrings.center(20, TableStrings.inUnits(\"energy\"); na=5)\n sa = sa * TableStrings.center(24, \"omega-in omega-out\"; na=2); \n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=1)\n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=6)\n println(stream, sa[1:end]); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for line in lines\n sa = \"\"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4)\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.initialLevel.energy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.finalLevel.energy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.inOmega)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.outOmega)) * \" \"\n println(stream, sa )\n end\n println(\" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\n\n \"\"\"\n `RayleighCompton.displayCrossSections(stream::IO, lines::Array{RayleighCompton.Line,1}, settings::RayleighCompton.Settings)` \n ... to display a list of lines and their cross sections as they were selected by the settings. A neat table of all selected \n transitions, energies and cross sections is printed but nothing is returned otherwise.\n \"\"\"\n function displayCrossSections(stream::IO, lines::Array{RayleighCompton.Line,1}, settings::RayleighCompton.Settings)\n nx = 127\n println(stream, \" \")\n println(stream, \" Cross sections of the selected Rayleigh-Compton scattering lines:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"; sc = \" \"\n sa = sa * TableStrings.center(16, \"i-level-f\"; na=2); sb = sb * TableStrings.hBlank(18)\n sa = sa * TableStrings.center(16, \"i--J^P--f\"; na=7); sb = sb * TableStrings.hBlank(23)\n sa = sa * TableStrings.center(20, \"i -- Energy -- f\"; na=3); \n sb = sb * TableStrings.center(20, TableStrings.inUnits(\"energy\"); na=5)\n sa = sa * TableStrings.center(24, \"omega-in omega-out\"; na=2); \n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=1)\n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=6)\n sa = sa * TableStrings.center(28, \"Cou -- cross section -- Bab\"; na=0); \n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"cross section\"); na=3)\n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"cross section\"); na=4)\n println(stream, sa[1:end]); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for line in lines\n sa = \"\"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4)\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.initialLevel.energy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.finalLevel.energy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.inOmega)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.outOmega)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"cross section: from atomic\", line.crossSection.Coulomb)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"cross section: from atomic\", line.crossSection.Babushkin)) * \" \"\n println(stream, sa )\n end\n println(\" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\n\n \"\"\"\n `RayleighCompton.displayLines(stream::IO, lines::Array{RayleighCompton.Line,1})` \n ... to display a list of lines and channels that have been selected due to the prior settings. A neat table of all selected \n transitions and energies is printed but nothing is returned otherwise.\n \"\"\"\n function displayLines(stream::IO, lines::Array{RayleighCompton.Line,1})\n nx = 157\n println(stream, \" \")\n println(stream, \" Selected Rayleigh-Compton scacttering lines and (reduced) channels:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"; sc = \" \"\n sa = sa * TableStrings.center(16, \"i-level-f\"; na=2); sb = sb * TableStrings.hBlank(18)\n sa = sa * TableStrings.center(16, \"i--J^P--f\"; na=7); sb = sb * TableStrings.hBlank(23)\n sa = sa * TableStrings.center(20, \"i -- Energy -- f\"; na=3); \n sb = sb * TableStrings.center(20, TableStrings.inUnits(\"energy\"); na=5)\n sa = sa * TableStrings.center(24, \"omega-in omega-out\"; na=0); \n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=1)\n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=4)\n sa = sa * TableStrings.center(11, \"No channels\"; na=2); sb = sb * TableStrings.hBlank(11) \n sa = sa * TableStrings.flushleft(60, \"List of multipoles & intermediate level symmetries\"; na=1) \n sb = sb * TableStrings.flushleft(60, \"(K-rank, multipole_1, Jsym, multipole_2, gauge), ...\"; na=1)\n println(stream, sa[1:end]); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for line in lines\n sa = \"\"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4)\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.initialLevel.energy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.finalLevel.energy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.inOmega)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.outOmega)) * \" \"\n sc = \" \" * string(length(line.channels)) * \" \"\n sa = sa * sc[end-12:end]\n mpGaugeList = Tuple{AngularJ64, Basics.EmMultipole, LevelSymmetry, Basics.EmMultipole, Basics.EmGauge}[]\n for channel in line.channels\n push!( mpGaugeList, (channel.K, channel.multipole1, channel.Jsym, channel.multipole2, channel.gauge) )\n end\n wa = TableStrings.twoPhotonGaugeTupels(60, mpGaugeList)\n if length(wa) > 0 sb = sa * wa[1]; println( sb ) end \n for i = 1:length(wa)\n sb = TableStrings.hBlank( length(sa) ); sb = sb * wa[i]; println(stream, sb )\n end\n end\n println(\" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\n\n \"\"\"\n `RayleighCompton.displayStokesParameters(stream::IO, lines::Array{RayleighCompton.Line,1}, settings::RayleighCompton.Settings)` \n ... to display a list of lines and the Stokes parameters at the selected solid angles. \n A neat table of all selected transitions, energies and solid angles is printed but nothing is returned otherwise.\n \"\"\"\n function displayStokesParameters(stream::IO, lines::Array{RayleighCompton.Line,1}, settings::RayleighCompton.Settings)\n nx = 127\n println(stream, \" \")\n println(stream, \" StokesParameters of the selected Rayleigh-Compton scattering lines at seleced solid angles: ... to be adapted !!\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"; sc = \" \"\n sa = sa * TableStrings.center(16, \"i-level-f\"; na=2); sb = sb * TableStrings.hBlank(18)\n sa = sa * TableStrings.center(16, \"i--J^P--f\"; na=7); sb = sb * TableStrings.hBlank(23)\n sa = sa * TableStrings.center(20, \"i -- Energy -- f\"; na=3); \n sb = sb * TableStrings.center(20, TableStrings.inUnits(\"energy\"); na=5)\n sa = sa * TableStrings.center(24, \"omega-in omega-out\"; na=2); \n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=1)\n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=6)\n println(stream, sa[1:end]); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for line in lines\n sa = \"\"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4)\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.initialLevel.energy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.finalLevel.energy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.inOmega)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.outOmega)) * \" \"\n println(stream, sa )\n end\n println(\" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\nend # module\n", "meta": {"hexsha": "1d7a7167344764956a5a9f691918670f1253a858", "size": 26841, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-RayleighCompton.jl", "max_stars_repo_name": "mfherbst/JAC.jl", "max_stars_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module-RayleighCompton.jl", "max_issues_repo_name": "mfherbst/JAC.jl", "max_issues_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-RayleighCompton.jl", "max_forks_repo_name": "mfherbst/JAC.jl", "max_forks_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.7553444181, "max_line_length": 160, "alphanum_fraction": 0.5931597183, "num_tokens": 6418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.24564155301056115}} {"text": "################################################################################\n#\n# Field access\n#\n################################################################################\n\nfunction elem_type(::Type{RelOrdQuoRing{T1, T2, T3}}) where { T1, T2, T3 }\n S = elem_type(T1)\n return RelOrdQuoRingElem{T1, T2, T3, S}\nend\n\nfunction elem_type(::RelOrdQuoRing{T1, T2, T3}) where { T1, T2, T3 }\n S = elem_type(T1)\n return RelOrdQuoRingElem{T1, T2, T3, S}\nend\n\nbase_ring(Q::RelOrdQuoRing) = Q.base_ring\n\nideal(Q::RelOrdQuoRing) = Q.ideal\n\nbasis_pmatrix(Q::RelOrdQuoRing) = Q.basis_pmatrix\n\nparent(x::RelOrdQuoRingElem) = x.parent\n\nparent_type(::Type{RelOrdQuoRingElem{T1, T2, T3, S}}) where { T1, T2, T3, S } = RelOrdQuoRing{T1, T2, T3}\n\n################################################################################\n#\n# Hashing\n#\n################################################################################\n\nhash(x::RelOrdQuoRingElem, h::UInt) = hash(x.elem, h)\n\n################################################################################\n#\n# Copying\n#\n################################################################################\n\nBase.deepcopy_internal(x::RelOrdQuoRingElem, dict::IdDict) =\n RelOrdQuoRingElem(parent(x), Base.deepcopy_internal(x.elem, dict))\n\n################################################################################\n#\n# I/O\n#\n################################################################################\n\nfunction show(io::IO, Q::RelOrdQuoRing)\n print(io, \"Quotient of $(base_ring(Q))\")\nend\n\nfunction show(io::IO, x::RelOrdQuoRingElem)\n print(io, \"$(x.elem)\")\nend\n\n################################################################################\n#\n# Parent object overloading\n#\n################################################################################\n\nfunction (Q::RelOrdQuoRing{T1, T2, T3})(x::RelOrdQuoRingElem{T1, T2, T3, S}) where { T1, T2, T3, S }\n parent(x) !== Q && error(\"Cannot coerce element into quotient ring\")\n return x\nend\n\nfunction (Q::RelOrdQuoRing{T1, T2, T3})(x::S) where { T1, T2, T3, S }\n parent(x) !== base_ring(Q) && error(\"Cannot coerce element into the quotient ring\")\n return RelOrdQuoRingElem(Q, x)\nend\n\nfunction (Q::RelOrdQuoRing)(x::Integer)\n return Q(base_ring(Q)(x))\nend\n\nfunction (Q::RelOrdQuoRing)(x::fmpz)\n return Q(base_ring(Q)(x))\nend\n\n################################################################################\n#\n# Quotient function\n#\n################################################################################\n\nfunction quo(O::Union{NfRelOrd, AlgAssRelOrd}, I::Union{NfRelOrdIdl, AlgAssRelOrdIdl})\n @assert order(I) === O\n # We should check that I is not zero\n Q = RelOrdQuoRing(O, I)\n f = RelOrdQuoMap(O, Q)\n return Q, f\nend\n\nNemo.ResidueRing(O::Union{NfRelOrd, AlgAssRelOrd}, I::Union{NfRelOrdIdl, AlgAssRelOrdIdl}) = RelOrdQuoRing(O, I)\n\n################################################################################\n#\n# Parent check\n#\n################################################################################\n\nfunction check_parent(x::RelOrdQuoRingElem, y::RelOrdQuoRingElem)\n if parent(x) !== parent(y)\n error(\"Elements must have same parents\")\n end\n return true\nend\n\n################################################################################\n#\n# Arithmetic\n#\n################################################################################\n\nfunction +(x::RelOrdQuoRingElem, y::RelOrdQuoRingElem)\n check_parent(x, y)\n return parent(x)(x.elem + y.elem)\nend\n\nfunction -(x::RelOrdQuoRingElem, y::RelOrdQuoRingElem)\n check_parent(x, y)\n return parent(x)(x.elem - y.elem)\nend\n\nfunction -(x::RelOrdQuoRingElem)\n return parent(x)(-x.elem)\nend\n\nfunction *(x::RelOrdQuoRingElem, y::RelOrdQuoRingElem)\n check_parent(x, y)\n return parent(x)(x.elem * y.elem)\nend\n\nfunction mul!(z::RelOrdQuoRingElem, x::RelOrdQuoRingElem, y::RelOrdQuoRingElem)\n z.elem = mul!(z.elem, x.elem, y.elem)\n z.elem = mod!(z.elem, parent(z))\n return z\nend\n\nfunction add!(z::RelOrdQuoRingElem, x::RelOrdQuoRingElem, y::RelOrdQuoRingElem)\n z.elem = add!(z.elem, x.elem, y.elem)\n z.elem = mod!(z.elem, parent(z))\n return z\nend\n\nfunction *(x::Integer, y::RelOrdQuoRingElem)\n return parent(y)(x * y.elem)\nend\n\n*(x::RelOrdQuoRingElem, y::Integer) = y*x\n\nfunction *(x::fmpz, y::RelOrdQuoRingElem)\n return parent(y)(x * y.elem)\nend\n\n*(x::RelOrdQuoRingElem, y::fmpz) = y*x\n\nfunction ^(a::RelOrdQuoRingElem, f::fmpz)\n if fits(Int, f)\n return a^Int(f)\n end\n f == 0 && return one(parent(a))\n f == 1 && return deepcopy(a)\n if f < 0\n f = -f\n a = inv(a)\n end\n b = a^(div(f, 2))\n b *= b\n if isodd(f)\n b *= a\n end\n return b\nend\n\nfunction ^(a::RelOrdQuoRingElem, b::Int)\n if b == 0\n return one(parent(a))\n elseif b == 1\n return deepcopy(a)\n else\n if b < 0\n a = inv(a)\n b = -b\n end\n bit = ~((~UInt(0)) >> 1)\n while (UInt(bit) & b) == 0\n bit >>= 1\n end\n z = deepcopy(a)\n bit >>= 1\n while bit != 0\n z = mul!(z, z, z)\n if (UInt(bit) & b) != 0\n z = mul!(z, z, a)\n end\n bit >>= 1\n end\n return z\n end\nend\n\n################################################################################\n#\n# Special elements\n#\n################################################################################\n\niszero(x::RelOrdQuoRingElem) = iszero(x.elem)\n\nisone(x::RelOrdQuoRingElem) = isone(x.elem)\n\nfunction one(Q::RelOrdQuoRing)\n return Q(one(base_ring(Q)))\nend\n\nfunction zero(Q::RelOrdQuoRing)\n return Q(zero(base_ring(Q)))\nend\n\n################################################################################\n#\n# Equality\n#\n################################################################################\n\nfunction ==(x::RelOrdQuoRing, y::RelOrdQuoRing)\n return base_ring(x) === base_ring(y) && ideal(x) == ideal(y)\nend\n\n==(x::RelOrdQuoRingElem, y::RelOrdQuoRingElem) = x.elem == y.elem\n", "meta": {"hexsha": "f424d5c0181d8816fb9fa0f5618b7d68b73bdd76", "size": 5891, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NumField/NfRel/ResidueRing.jl", "max_stars_repo_name": "Pi-tree/Hecke.jl", "max_stars_repo_head_hexsha": "3efb13b1e582ab494fd6a88adcdc7b5a93535435", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NumField/NfRel/ResidueRing.jl", "max_issues_repo_name": "Pi-tree/Hecke.jl", "max_issues_repo_head_hexsha": "3efb13b1e582ab494fd6a88adcdc7b5a93535435", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NumField/NfRel/ResidueRing.jl", "max_forks_repo_name": "Pi-tree/Hecke.jl", "max_forks_repo_head_hexsha": "3efb13b1e582ab494fd6a88adcdc7b5a93535435", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1752136752, "max_line_length": 112, "alphanum_fraction": 0.470548294, "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24564154665647464}} {"text": "#= \nFinal parsing of preparsing structures\n\nNumbers and variables will finaly\n=#\ninclude(\"ofMeshDictPreParser.jl\")\n\nabstract type OfEntity end\nabstract type AbstractOfVar <: OfEntity end\nabstract type AbstractOfVal <: OfEntity end\n\nstruct OfDictionary <: OfEntity\n name::String\n entries::Vector{OfEntity}\nend\n\n# array list of same entities with length \nstruct OfArray <: OfEntity\n length::Int64\n entries::Vector{OfEntity}\nend\n\nstruct OfList<: OfEntity\n length::Int64\n entries::Vector{OfEntity}\nend\n\nstruct OfVariable{T} <: AbstractOfVar\n name::String\n value::T\nend\n\nstruct OfValue{T} <: AbstractOfVal\n value::T\nend\n\n\n\"\"\"\n dfs_parse(parse_entities::Vector{PreParsedEntity}, tokens::Vector{Token})\n\nparses pre parsed vector structure to finally parsed file structure\n\"\"\"\nfunction dfs_parse(parse_entities::Vector{PreParsedEntity}, tokens::Vector{Token})\n\n of_entities = Vector{OfEntity}(undef, 0)\n\n for parse_elem in parse_entities\n if typeof(parse_elem) == PreParsedVariable \n push!(of_entities, parse_of_variable(parse_elem, tokens))\n elseif typeof(parse_elem) == PreParsedFNum\n push!(of_entities, OfValue(parse(Float64,parse_elem.string)))\n elseif typeof(parse_elem) == PreParsedINum\n push!(of_entities, OfValue(parse(Int64,parse_elem.string)))\n elseif typeof(parse_elem) == PreParsedDictonary\n mypush!(of_entities, OfDictionary(parse_elem.name,\n dfs_parse(parse_elem.entries, tokens)))\n elseif typeof(parse_elem) == PreParsedArray\n mypush!(of_entities, OfArray(parse_elem.length, \n dfs_parse(parse_elem.entries, tokens)))\n elseif typeof(parse_elem) == PreParsedList\n parsed_list = dfs_parse(parse_elem.entries, tokens)\n mypush!(of_entities, OfList(length(parsed_list), parsed_list))\n end\n end\n\n return of_entities\nend\n\n\nfunction mypush!(of_entities::Vector{OfEntity}, OfEntity::T) where T <: OfEntity\n push!(of_entities, OfEntity)\nend\n\n\nfunction mypush!(of_entities::Vector{OfEntity},\n entities::Vector{T}) where T <: OfEntity\n for e in entities\n push!(of_entities, e)\n end\nend\n\n\n\"\"\"\n parse_of_variable(pe::PreParsedEntity, tokens::Vector{Token})\n\nParsing of a PreParsedEntity to final type OfVariable, which completes parsing.\n\"\"\"\n# TODO: only works for numbers and strings by now\nfunction parse_of_variable(pe::PreParsedEntity, tokens::Vector{Token})::OfVariable\n \n name = \"\"\n value = []\n\n if tokens[pe.id_token_from].type_id == TokenTypeID_Dict[:word]\n name = tokens[pe.id_token_from].string\n\n if ( (pe.id_token_to - pe.id_token_from) == 2 )\n if (tokens[pe.id_token_from+1].type_id == \n TokenTypeID_Dict[:int_number])\n\n value = parse(Int64, tokens[pe.id_token_from+1].string)\n\n elseif (tokens[pe.id_token_from+1].type_id == \n TokenTypeID_Dict[:float_number])\n\n value = parse(Float64, tokens[pe.id_token_from+1].string)\n\n elseif (tokens[pe.id_token_from+1].type_id \n == TokenTypeID_Dict[:word])\n\n value = tokens[pe.id_token_from+1].string\n\n elseif (tokens[pe.id_token_from+1].type_id \n == TokenTypeID_Dict[:string])\n \n value = tokens[pe.id_token_from+1].string\n\n else\n value = nothing\n end\n elseif ( ((pe.id_token_to - pe.id_token_from) == 3) &&\n (tokens[pe.id_token_from+1].type_id == \n TokenTypeID_Dict[:minus]) )\n\n if (tokens[pe.id_token_from+2].type_id == \n TokenTypeID_Dict[:int_number])\n\n value = parse(Int64, tokens[pe.id_token_from+1].string * \n tokens[pe.id_token_from+2].string)\n\n elseif (tokens[pe.id_token_from+2].type_id == \n TokenTypeID_Dict[:float_number])\n\n value = parse(Float64, tokens[pe.id_token_from+1].string * \n tokens[pe.id_token_from+2].string)\n else\n value = nothing\n end\n\n else\n value = 0\n end\n else\n error(\"First Token of Variable should be a word!\")\n end\n\n return OfVariable(name, value)\nend\n\n\n\"\"\"\n ofprint(ofvar::OfEntity, depth::Int64=0)\n\ndfs print in case for single OfEntity\n\"\"\"\nfunction ofprint(ofvar::OfEntity, depth::Int64=0)\n ofprint([ofvar], depth)\nend\n\n\n\"\"\"\n ofprint(ofvars::Vector{OfEntity}, depth::Int64=0) \n\ndfs print of Vector{OfEntity} to get a nicer view of finally parsed entities\n\"\"\"\nfunction ofprint(ofvars::Vector{OfEntity}, depth::Int64=0) \n for ofvar in ofvars\n if typeof(ofvar) <: AbstractOfVar \n println(\"\\t\"^depth,ofvar.name, \": \", ofvar.value)\n\n elseif typeof(ofvar) <: AbstractOfVal\n print(ofvar.value, \" \")\n\n elseif typeof(ofvar) == OfDictionary\n println()\n println(\"\\t\"^depth,ofvar.name, \" {\")\n depth += 1\n ofprint(ofvar.entries, depth)\n depth -= 1\n println(\"\\t\"^depth,\"}\")\n elseif typeof(ofvar) == OfArray\n print(\"\\t\"^depth,ofvar.length, \" (\")\n depth += 1\n ofprint(ofvar.entries,depth)\n print(\")\\n\")\n depth -= 1\n elseif typeof(ofvar) == OfList\n print(\"\\t\"^depth,\"(\")\n ofprint(ofvar.entries, depth)\n print(\")\\n\")\n end\n end\n\nend\n\n\"\"\"\n get_dictionary(ofvars::Vector{OfEntity}, dict_name::string)\n\nReturns Dictionary in first layer of ofvars with .name == dict_name\n\"\"\"\nfunction get_dictionary(ofvars::Vector{OfEntity}, dict_name::String)\n\n for f in ofvars\n if typeof(f) == OfDictionary && f.name == dict_name\n return f\n end\n end\n\n return nothing\nend\n\n\n\n\"\"\"\n get_variable(ofvars::Vector{OfEntity}, var_name::string)\n\nReturns Variable in first layer of ofvars with .name == var_name\n\"\"\"\nfunction get_variable(ofvars::Vector{OfEntity}, var_name::String)\n\n for f in ofvars\n if typeof(f) <: AbstractOfVar && f.name == var_name\n return f\n end\n end\n\n return nothing\nend\n\n\n\n\"\"\"\n get_variable_value(ofvars::Vector{OfEntity}, var_name::string)\n\nReturns Variable value in first layer of ofvars with .name == var_name\n\"\"\"\nfunction get_variable_value(ofvars::Vector{OfEntity}, var_name::String)\n\n var = get_variable(ofvars::Vector{OfEntity}, var_name::String)\n\n if !isnothing(var)\n return var.value\n else\n error(\"Variable \", var_name, \" cannot be found\")\n end\n\nend\n", "meta": {"hexsha": "4711cad2898ffc06a9b13c99a335dcd7d39b5bfb", "size": 6752, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/openfoam/ofMeshDictParser.jl", "max_stars_repo_name": "c-schubert/linearMeshIO", "max_stars_repo_head_hexsha": "8ad073961470b9bc75ab729c82480221c9c08a62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/openfoam/ofMeshDictParser.jl", "max_issues_repo_name": "c-schubert/linearMeshIO", "max_issues_repo_head_hexsha": "8ad073961470b9bc75ab729c82480221c9c08a62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openfoam/ofMeshDictParser.jl", "max_forks_repo_name": "c-schubert/linearMeshIO", "max_forks_repo_head_hexsha": "8ad073961470b9bc75ab729c82480221c9c08a62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2258064516, "max_line_length": 82, "alphanum_fraction": 0.6153732227, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2453745533667865}} {"text": "# This file is a part of BAT.jl, licensed under the MIT License (MIT).\n\n\nconst _default_float_WT = Float64 # Default type for float weights\nconst _default_int_WT = Int # Default type for int weights\nconst _default_LDT = Float64 # Default type for log-density values\n\n\n\"\"\"\n struct DensitySample\n\nA weighted sample drawn according to an statistical density,\ne.g. a [`BAT.AbstractDensity`](@ref).\n\nFields:\n * `v`: Multivariate parameter vector\n * `logd`: log of the value of the density at `v`\n * `weight`: Weight of the sample\n * `info`: Additional info on the provenance of the sample. Content depends\n on the sampling algorithm.\n * aux: Custom user-defined information attatched to the sample.\n\nConstructors:\n\n```julia\nDensitySample(\n v::AbstractVector{<:Real},\n logd::Real,\n weight::Real,\n info::Any,\n aux::Any\n)\n```\n\nUse [`DensitySampleVector`](@ref) to store vectors of multiple samples with\nan efficient column-based memory layout.\n\"\"\"\nstruct DensitySample{\n P,\n T<:Real,\n W<:Real,\n R,\n Q\n}\n v::P\n logd::T\n weight::W\n info::R\n aux::Q\nend\n\nexport DensitySample\n\n\n# DensitySample behaves as a scalar type under broadcasting:\n@inline Base.Broadcast.broadcastable(shape::DensitySample) = Ref(shape)\n\n\nimport Base.==\nfunction ==(A::DensitySample, B::DensitySample)\n A.v == B.v && A.logd == B.logd &&\n A.weight == B.weight && A.info == B.info && A.aux == B.aux\nend\n\n\nfunction Base.similar(s::DensitySample{P,T,W,R,Q}) where {P<:AbstractVector{<:Real},T,W,R,Q}\n v = fill!(similar(s.v), eltype(s.v)(NaN))\n logd = convert(T, NaN)\n weight = zero(W)\n info = R()\n aux = Q()\n P_new = typeof(v)\n DensitySample{P_new,T,W,R,Q}(v, logd, weight, info, aux)\nend\n\n\nfunction _apply_shape(shape::AbstractValueShape, s::DensitySample)\n DensitySample(\n stripscalar(shape(s.v)),\n s.logd,\n s.weight,\n s.info,\n s.aux,\n )\nend\n\n(shape::AbstractValueShape)(s::DensitySample) = _apply_shape(shape, s)\n\n\n\n\"\"\"\n DensitySampleVector\n\nType alias for `StructArrays.StructArray{<:DensitySample,...}`.\n\nConstructors:\n\n```julia\n DensitySampleVector(\n (\n v::AbstractVector{<:AbstractVector{<:Real}},\n logd::AbstractVector{<:Real},\n weight::AbstractVector{<:Real},\n info::AbstractVector{<:Any},\n aux::AbstractVector{<:Any}\n )\n )\n```\n\n```julia\n DensitySampleVector(\n v::AbstractVector,\n logval::AbstractVector{<:Real};\n weight::Union{AbstractVector{<:Real}, Symbol} = fill(1, length(eachindex(v))),\n info::AbstractVector = fill(nothing, length(eachindex(v))),\n aux::AbstractVector = fill(nothing, length(eachindex(v)))\n )\n```\n For `weight = :RepetitionWeight`, repeated samples will be dropped and the weight of the corresponding sample will be increased.\n\"\"\"\nconst DensitySampleVector{\n P,T<:AbstractFloat,W<:Real,R,Q,\n PV<:AbstractVector{P},TV<:AbstractVector{T},WV<:AbstractVector{W},RV<:AbstractVector{R},QV<:AbstractVector{Q}\n} = StructArray{\n DensitySample{P,T,W,R,Q},\n 1,\n NamedTuple{(:v, :logd, :weight, :info, :aux), Tuple{PV,TV,WV,RV,QV}}\n}\n\nexport DensitySampleVector\n\n\nfunction StructArray{DensitySample}(\n contents::Tuple{\n AbstractVector{P},\n AbstractVector{T},\n AbstractVector{W},\n AbstractVector{R},\n AbstractVector{Q},\n }\n) where {P,T<:AbstractFloat,W<:Real,R,Q}\n v, logd, weight, info, aux = contents\n StructArray{DensitySample{P,T,W,R,Q}}(contents)\nend\n\n\nDensitySampleVector(contents::NTuple{5,Any}) = StructArray{DensitySample}(contents)\n\n\n_create_undef_vector(::Type{T}, len::Integer) where T = Vector{T}(undef, len)\n\n\nfunction DensitySampleVector{P,T,W,R,Q}(::UndefInitializer, len::Integer, npar::Integer) where {\n PT<:Real, P<:AbstractVector{PT}, T<:AbstractFloat, W<:Real, R, Q\n}\n contents = (\n VectorOfSimilarVectors(ElasticArray{PT}(undef, npar, len)),\n Vector{T}(undef, len),\n Vector{W}(undef, len),\n _create_undef_vector(R, len),\n _create_undef_vector(Q, len)\n )\n\n DensitySampleVector(contents)\nend\n\nDensitySampleVector(::Type{S}, varlen::Integer) where {P<:AbstractVector{<:Real},T<:AbstractFloat,W<:Real,R,Q,S<:DensitySample{P,T,W,R,Q}} =\n DensitySampleVector{P,T,W,R,Q}(undef, 0, varlen)\n\n\nfunction DensitySampleVector(\n v::AbstractVector,\n logval::AbstractVector{<:Real};\n weight::Union{AbstractVector{<:Real}, Symbol} = fill(1, length(eachindex(v))),\n info::AbstractVector = fill(nothing, length(eachindex(v))),\n aux::AbstractVector = fill(nothing, length(eachindex(v)))\n)\n if weight == :RepetitionWeight\n idxs, weight = repetition_to_weights(v)\n return DensitySampleVector((ArrayOfSimilarArrays(v[idxs]), logval[idxs], weight, info[idxs], aux[idxs]))\n else\n return DensitySampleVector((ArrayOfSimilarArrays(v), logval, weight, info, aux))\n end\nend\n\n\n# Specialize getindex to properly support ArraysOfArrays and similar, preventing\n# conversion to exact element type:\n\n@inline Base.getindex(A::StructArray{<:DensitySample}, I::Int...) =\n DensitySample(A.v[I...], A.logd[I...], A.weight[I...], A.info[I...], A.aux[I...])\n\n@inline Base.getindex(A::StructArray{<:DensitySample}, I::Union{Int,AbstractArray,Colon}...) =\n DensitySampleVector((A.v[I...], A.logd[I...], A.weight[I...], A.info[I...], A.aux[I...]))\n\n# Specialize IndexStyle, current default for StructArray seems to be IndexCartesian()\nBase.IndexStyle(::StructArray{<:DensitySample, 1}) = IndexLinear()\n\n# Specialize comparison, currently StructArray seems fall back to `(==)(A::AbstractArray, B::AbstractArray)`\nimport Base.==\nfunction(==)(A::DensitySampleVector, B::DensitySampleVector)\n A.v == B.v &&\n A.logd == B.logd &&\n A.weight == B.weight &&\n A.info == B.info &&\n A.aux == B.aux\nend\n\n\nfunction Base.merge!(X::DensitySampleVector, Xs::DensitySampleVector...)\n for Y in Xs\n append!(X, Y)\n end\n X\nend\n\nBase.merge(X::DensitySampleVector, Xs::DensitySampleVector...) = merge!(deepcopy(X), Xs...)\n\n\nBase.@propagate_inbounds function _bcasted_apply_to_params(f, A::DensitySampleVector)\n DensitySampleVector((\n f.(A.v),\n A.logd,\n A.weight,\n A.info,\n A.aux\n ))\nend\n\nBase.copy(\n instance::Base.Broadcast.Broadcasted{\n <:Base.Broadcast.AbstractArrayStyle{1},\n <:Any,\n <:Union{AbstractValueShape,typeof(unshaped)},\n <:Tuple{DensitySampleVector}\n }\n) = _bcasted_apply_to_params(instance.f, instance.args[1])\n\n\nValueShapes.varshape(A::DensitySampleVector) = elshape(A.v)\n\n\nfunction _get_statw(f::Function, samples::DensitySampleVector, resultshape::AbstractValueShape)\n shape = varshape(samples)\n X = unshaped.(samples.v)\n w = FrequencyWeights(samples.weight)\n r_unshaped = f(X, w)\n resultshape(r_unshaped)\nend\n\nStatistics.mean(samples::DensitySampleVector) = _get_statw(mean, samples, varshape(samples))\nStatistics.var(samples::DensitySampleVector) = _get_statw(var, samples, replace_const_shapes(ValueShapes.const_zero_shape, varshape(samples)))\nStatistics.std(samples::DensitySampleVector) = _get_statw(std, samples, replace_const_shapes(ValueShapes.const_zero_shape, varshape(samples)))\n\nfunction Statistics.median(samples::DensitySampleVector)\n shape = varshape(samples)\n flat_samples = flatview(unshaped.(samples.v))\n n_params = size(flat_samples)[1]\n median_params = Vector{Float64}()\n\n for param in Base.OneTo(n_params)\n median_param = quantile(flat_samples[param,:], FrequencyWeights(samples.weight), 0.5)\n push!(median_params, median_param)\n end\n shape(median_params)\nend\n\nfunction _get_stat(f::Function, samples::DensitySampleVector)\n shape = varshape(samples)\n X = unshaped.(samples.v)\n r_unshaped = f(X)\n shape(r_unshaped)\nend\n\nBase.minimum(samples::DensitySampleVector) = _get_stat(minimum, samples)\nBase.maximum(samples::DensitySampleVector) = _get_stat(maximum, samples)\n\nStatistics.cov(samples::DensitySampleVector{<:AbstractVector{<:Real}}) = cov(samples.v, FrequencyWeights(samples.weight))\nStatistics.cor(samples::DensitySampleVector{<:AbstractVector{<:Real}}) = cor(samples.v, FrequencyWeights(samples.weight))\n\nfunction _get_mode(samples::DensitySampleVector)\n shape = varshape(samples)\n i = findmax(samples.logd)[2]\n v_unshaped = unshaped.(samples.v)[i]\n v = copy(shape(v_unshaped))\n (v, i)\nend\n\n\nStatsBase.mode(samples::DensitySampleVector) = _get_mode(samples)[1]\n\n\n\"\"\"\n drop_low_weight_samples(\n samples::DensitySampleVector,\n fraction::Real = 10^-4\n )\n\n*BAT-internal, not part of stable public API.*\n\nDrop `fraction` of the total probability mass from samples to filter out the\nsamples with the lowest weight.\n\"\"\"\nfunction drop_low_weight_samples(samples::DensitySampleVector, fraction::Real = 10^-5; threshold::Real=10^-2)\n W = float(samples.weight)\n if minimum(W) / maximum(W) > threshold\n samples\n else\n W_s = sort(W)\n Q = cumsum(W_s)\n Q ./= maximum(Q)\n @assert last(Q) ≈ 1\n ind = searchsortedlast(Q, fraction)\n if ind !== 0\n thresh = W_s[searchsortedlast(Q, fraction)]\n idxs = findall(x -> x >= thresh, samples.weight)\n samples[idxs]\n else\n samples\n end\n end\nend\n\n\n\"\"\"\n repetition_to_weights(v::AbstractVector)\n\n*BAT-internal, not part of stable public API.*\n\nDrop (subsequently) repeated samples by adding weights.\n\"\"\"\nfunction repetition_to_weights(v::AbstractVector)\n idxs = Vector{Int}()\n counts = Vector{Int}()\n push!(idxs, 1)\n push!(counts, 1)\n for i in 2:length(v)\n if v[i] == v[i-1]\n counts[end] += 1\n else\n push!(idxs, i)\n push!(counts, 1)\n end\n end\n return (idxs, counts)\nend\n", "meta": {"hexsha": "9d487c3535adb1fa24ae8fc32b4125ecdd0546ec", "size": 9914, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parameters/density_sample.jl", "max_stars_repo_name": "Cornelius-G/BAT.jl", "max_stars_repo_head_hexsha": "1bb577c8d976066c1f52070984d86020728f599c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parameters/density_sample.jl", "max_issues_repo_name": "Cornelius-G/BAT.jl", "max_issues_repo_head_hexsha": "1bb577c8d976066c1f52070984d86020728f599c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parameters/density_sample.jl", "max_forks_repo_name": "Cornelius-G/BAT.jl", "max_forks_repo_head_hexsha": "1bb577c8d976066c1f52070984d86020728f599c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5706051873, "max_line_length": 142, "alphanum_fraction": 0.665926972, "num_tokens": 2632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.24531184355627966}} {"text": "include(string(PROJECT_HOME,\"/simulation_code/updatefuns.jl\"))\ninclude(string(PROJECT_HOME,\"/simulation_code/create_hydraulics_layered.jl\"))\n\nfunction make_layers(_totaldepth)\n\tlinear_layers = collect(0:0.1:0.8);\n\ttoadd = [0,0,1,2,3,4,5,6,7];\n\tquad_layers = cumsum(toadd)/sum(toadd);\n\t\n\tif _totaldepth < 0.8\n\t\tlower_layer_thick = (_totaldepth-0.1)/Int(floor((_totaldepth-0.1) / 0.1));\n\t\tlayers = vcat(0, 0.1:lower_layer_thick:_totaldepth);\n\tend\n\t\n\tif _totaldepth >= 0.8\n\t\tlayers = linear_layers + quad_layers*(_totaldepth-0.8);\n\tend\n\treturn convert(Array{FT}, -1*layers)\nend\n\nfunction create_spac(\n sm::AbstractStomatalModel = OSMWang{FT}(),\n vcmax::FT = FT(30),\n kmax::FT = FT(0.3),\n\t\tz_soil::FT = FT(1000), \n chl::FT = FT(40),\n\t N_slice::Int = 1,\n\talpha::FT = FT(1.368),\n\tn::FT = FT(2.6257)\n) where {FT<:AbstractFloat} \n(\n\n\t#_soil_hs = create_soil_VC(VanGenuchten{FT}(), \"Silt Loam\");\n\t\n\t\n\t_soil_hs = VanGenuchten{FT}(stype = \"Ozark\",\n\t\t\t\t\t\t\t\t\tα = alpha,\n\t\t\t\t\t\t\t\t\tn = n,\n\t\t\t\t\t\t\t\t Θs = 0.45,\n\t\t\t\t\t\t\t\t Θr = 0.067);\n\t\n\t\t\t\t\t\t\t\t \n\t#_soil_hs = BrooksCorey{FT}(stype= \"Ozark\", Θs = FT(porosity), Θr = FT(0.05), ϕs = psi_sat, b = b_soil);\n\t\n\n\t_totaldepth = FT(z_soil/1000);\n\t_rootdepth = FT(z_soil/1000);\n\t#_soil_bounds = collect(FT,[0,-0.1,-0.25,-0.45,-0.7]);\n\t#_soil_bounds = collect(FT,[0,-0.1,-0.2,-0.3,-0.4]);\n\t#_soil_bounds = collect(FT,[0,-0.1,-0.2,-0.3,-0.4,-0.5,-0.6,-0.7]);\n\t\n\t#_soil_bounds = collect(FT,[0,-0.1,-0.15,-0.2,-0.25,-0.3,-0.35,-0.4]);\n\t#_soil_bounds[3:end] *= _totaldepth/FT(0.4);\n\t\n\t\n\t#_soil_bounds = collect(FT,[0,-0.1,-0.25,-0.5,-0.75,-1.0,-1.5,-2]);\n\t#_soil_bounds *= _totaldepth/FT(2);\n\n\t#_soil_bounds = collect(FT,[0,-0.1,-0.2, -0.3, -0.4, -0.5, -0.6, -0.7]);\n\t#_soil_bounds *= _totaldepth/FT(0.7);\n\t\t\n\t_soil_bounds = make_layers(_totaldepth);\n\t\n\t_totaldepth = -1*_soil_bounds[end];\n\t_rootdepth = -1*_soil_bounds[end];\n\n\t_air_bounds = convert(Array{FT},[0,5,9,12,16,18.5,20] );\n\t\n\t_tree_hs = create_tree2(FT(-1*_rootdepth), FT(9), FT(18.5), _soil_bounds,\n\t\t\t\t\t\t _air_bounds, N_slice);\n\tfor _root in _tree_hs.roots\n\t\t_root.sh = deepcopy(_soil_hs);\n\tend;\n\n\t_node = SPACMono{FT}(soil_bounds = _soil_bounds,\n\t\t\t\t\t\t air_bounds = _air_bounds,\n\t\t\t\t\t\t\t z_root = FT(-1*_rootdepth),\n\t\t\t\t\t\t\tz_canopy = 18.5,\n\t\t\t\t\t\t\tplant_hs = _tree_hs,\n\t\t\t\t\t\t\t\t ga = 413.223,\n\t\t\t\t\t\t\t\t la = 1735.537,\n\t\t\t\t\t\t\tlatitude = 38.74,\n\t\t\t\t\t\t longitude = -92.2,\n\t\t\t\t\t\t elevation = 219.4,\n\t\t\t\t\t stomata_model = sm);\n\t_node.swc = collect(FT,0.4*ones(length(_soil_bounds)-1));\n\t\n\tn_canopy = length(_node.plant_hs.canopy_index_in_air);\n\t\n\t#=\n\tincl_grid = collect(FT,[22.5,45+22.5]);\n\tazi_grid = collect(FT,[90,270]);\n\tincl_grid_bnd = [collect(FT,[0,45]) collect(FT,[45,90])];\n\t=#\n\t\n\tincl_grid = collect(FT,[45]);\n\tazi_grid = collect(FT,[180]);\n\tincl_grid_bnd = [collect(FT,[0]) collect(FT,[90])];\n\t\n\tnleaf = length(incl_grid)*length(azi_grid) + 1;\n\t\n\t_node.plant_ps = [CanopyLayer{FT}(n_leaf=nleaf) for\n\t\t\t\t\t\t\t\t\t\t i in 1:n_canopy];\n\t\n\t_node.canopy_rt = Canopy4RT{FT}(nLayer=n_canopy, LAI=_node.la/_node.ga, litab = incl_grid, litab_bnd = incl_grid_bnd, lazitab = azi_grid);\t\n\t\n\t\n\n\t#\"RT dimensions\"\n\t_node.rt_dim = create_rt_dims(_node.canopy_rt, _node.wl_set);\n\t#\"CanopyRads container\"\n\t_node.can_rad = create_canopy_rads(FT, _node.rt_dim);\n\t#\"CanopyOpticals container\"\n\t_node.can_opt = create_canopy_opticals(FT, _node.rt_dim);\n\t#\"Array of LeafBios container\"\n\t_node.leaves_rt = [create_leaf_bios(FT, _node.rt_dim) for\n\t\t\t\t\t\t\t\t\t\t i in 1:n_canopy];\n\n\t#\"RT container\"\n\t_node.rt_con = create_rt_cache(FT, _node.rt_dim);\n\t#\"Container for sunlit leaf area fraction in each layer\"\n\t_node.f_SL = repeat(_node.canopy_rt.lidf, outer=[ _node.canopy_rt.nAzi ]) /\n\t\t\t\t\t\t_node.canopy_rt.nAzi;\n\t\n\t\n\t\n\t#=\n\tfor _iPS in _node.plant_ps\n\t\t_iPS.g_min = 0.001;\n\t\t_iPS.g_min25 = 0.001;\n\t\t_iPS.g_max = 0.08; #0.50;\n\t\t_iPS.g_max25 = 0.08; #0.50;\n\tend;\n\t=#\n\t\n\tfor _iPS in _node.plant_ps\n\t\t_iPS.g_min = 0.001;\n\t\t_iPS.g_min25 = 0.001;\n\t\t_iPS.g_max = 0.12; #0.50;\n\t\t_iPS.g_max25 = 0.12; #0.50;\n\tend;\n\t\n\t\n\t_node.canopy_rt.Ω = 0.69;\n\t_node.canopy_rt.clump_a = 0.69;\n\tupdate_LAI!(_node, FT(4.2));\n\tupdate_Weibull!(_node, FT(5.703), FT(0.953));\n\n\t#update_Weibull!(_node, FT(4.0), FT(3.0));\n\t#for _leaf in _node.plant_hs.leaves\n #_leaf.vc.b = 1.0;\n #_leaf.vc.c = 3.0;\n #end;\n\t\n\t\n\t\n\t\n\t#for _leaf in _node.plant_hs.leaves\n # _leaf.vc.b = 2.0;\n #_leaf.vc.c = c;\n #end;\n\t\n\n\n # update fitted Vcmax, Kmax, and Chlrophyll content\n update_VJRWW!(_node, vcmax);\n update_Kmax!(_node, kmax);\n update_Cab!(_node, chl);\n initialize_spac_canopy!(_node);\n\t\n return _node\n)\nend\n", "meta": {"hexsha": "79d464545390696a8805039ed164a8c2ccfe8ea3", "size": 4640, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "simulation_code/create_spac_setsoil.jl", "max_stars_repo_name": "natan-holtzman/CliMa_Microwave", "max_stars_repo_head_hexsha": "1970015be901e4e724ecb4fa41e7cd3102dcf9d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-18T16:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T16:08:54.000Z", "max_issues_repo_path": "simulation_code/create_spac_setsoil.jl", "max_issues_repo_name": "natan-holtzman/CliMa_Microwave", "max_issues_repo_head_hexsha": "1970015be901e4e724ecb4fa41e7cd3102dcf9d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation_code/create_spac_setsoil.jl", "max_forks_repo_name": "natan-holtzman/CliMa_Microwave", "max_forks_repo_head_hexsha": "1970015be901e4e724ecb4fa41e7cd3102dcf9d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8208092486, "max_line_length": 141, "alphanum_fraction": 0.6269396552, "num_tokens": 1812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.24529252653354544}} {"text": "# Different ways to simulate molecules\n\nexport\n SteepestDescentMinimizer,\n simulate!,\n VelocityVerlet,\n Verlet,\n StormerVerlet,\n Langevin\n\n\"\"\"\n SteepestDescentMinimizer(; )\n\nSteepest descent energy minimization.\n\n# Arguments\n- `step_size::D=0.01u\"nm\"`: the initial maximum displacement.\n- `max_steps::Int=1000`: the maximum number of steps.\n- `tol::F=1000.0u\"kJ * mol^-1 * nm^-1\"`: the maximum force below which to\n finish minimization.\n- `run_loggers::Bool=false`: whether to run the loggers during minimization.\n- `log_stream::L=devnull`: stream to print minimization progress to.\n\"\"\"\nstruct SteepestDescentMinimizer{D, F, L}\n step_size::D\n max_steps::Int\n tol::F\n run_loggers::Bool\n log_stream::L\nend\n\nfunction SteepestDescentMinimizer(;\n step_size=0.01u\"nm\",\n max_steps=1_000,\n tol=1000.0u\"kJ * mol^-1 * nm^-1\",\n run_loggers=false,\n log_stream=devnull)\n return SteepestDescentMinimizer(step_size, max_steps, tol,\n run_loggers, log_stream)\nend\n\n\"\"\"\n simulate!(system, simulator, n_steps; parallel=true)\n simulate!(system, simulator; parallel=true)\n\nRun a simulation on a system according to the rules of the given simulator.\nCustom simulators should implement this function.\n\"\"\"\nfunction simulate!(sys,\n sim::SteepestDescentMinimizer;\n parallel::Bool=true)\n neighbors = find_neighbors(sys, sys.neighbor_finder; parallel=parallel)\n sim.run_loggers && run_loggers!(sys, neighbors, 0; parallel=parallel)\n E = potential_energy(sys, neighbors)\n println(sim.log_stream, \"Step 0 - potential energy \",\n E, \" - max force N/A - N/A\")\n hn = sim.step_size\n\n for step_n in 1:sim.max_steps\n F = forces(sys, neighbors; parallel=parallel)\n max_force = maximum(norm.(F))\n\n coords_copy = sys.coords\n sys.coords += hn * F ./ max_force\n sys.coords = wrap_coords_vec.(sys.coords, (sys.box_size,))\n\n neighbors_copy = neighbors\n neighbors = find_neighbors(sys, sys.neighbor_finder, neighbors, step_n;\n parallel=parallel)\n E_trial = potential_energy(sys, neighbors)\n if E_trial < E\n hn = 6 * hn / 5\n E = E_trial\n println(sim.log_stream, \"Step \", step_n, \" - potential energy \",\n E_trial, \" - max force \", max_force, \" - accepted\")\n else\n sys.coords = coords_copy\n neighbors = neighbors_copy\n hn = hn / 5\n println(sim.log_stream, \"Step \", step_n, \" - potential energy \",\n E_trial, \" - max force \", max_force, \" - rejected\")\n end\n\n sim.run_loggers && run_loggers!(sys, neighbors, step_n;\n parallel=parallel)\n\n if max_force < sim.tol\n break\n end\n end\n return sys\nend\n\n# Forces are often expressed per mol but this dimension needs removing for use in the integrator\nfunction remove_molar(x)\n fx = first(x)\n if dimension(fx) == u\"𝐋 * 𝐍^-1 * 𝐓^-2\"\n T = typeof(ustrip(fx))\n return x / T(Unitful.Na)\n else\n return x\n end\nend\n\n\"\"\"\n VelocityVerlet(; )\n\nThe velocity Verlet integrator.\n\n# Arguments\n- `dt::T`: the time step of the simulation.\n- `coupling::C=NoCoupling()`: the coupling which applies during the simulation.\n- `remove_CM_motion::Bool=true`: whether to remove the centre of mass motion\n every time step.\n\"\"\"\nstruct VelocityVerlet{T, C}\n dt::T\n coupling::C\n remove_CM_motion::Bool\nend\n\nfunction VelocityVerlet(; dt, coupling=NoCoupling(), remove_CM_motion=true)\n return VelocityVerlet(dt, coupling, remove_CM_motion)\nend\n\nfunction simulate!(sys,\n sim::VelocityVerlet,\n n_steps::Integer;\n parallel::Bool=true)\n neighbors = find_neighbors(sys, sys.neighbor_finder; parallel=parallel)\n run_loggers!(sys, neighbors, 0; parallel=parallel)\n accels_t = accelerations(sys, neighbors; parallel=parallel)\n accels_t_dt = zero(accels_t)\n sim.remove_CM_motion && remove_CM_motion!(sys)\n\n for step_n in 1:n_steps\n sys.coords += sys.velocities .* sim.dt .+ (remove_molar.(accels_t) .* sim.dt ^ 2) ./ 2\n sys.coords = wrap_coords_vec.(sys.coords, (sys.box_size,))\n\n accels_t_dt = accelerations(sys, neighbors; parallel=parallel)\n\n sys.velocities += remove_molar.(accels_t .+ accels_t_dt) .* sim.dt / 2\n\n sim.remove_CM_motion && remove_CM_motion!(sys)\n apply_coupling!(sys, sim, sim.coupling)\n\n run_loggers!(sys, neighbors, step_n; parallel=parallel)\n\n if step_n != n_steps\n neighbors = find_neighbors(sys, sys.neighbor_finder, neighbors, step_n;\n parallel=parallel)\n accels_t = accels_t_dt\n end\n end\n return sys\nend\n\n\"\"\"\n Verlet(; )\n\nThe leapfrog Verlet integrator.\nThis is a leapfrog integrator, so the velocities are offset by half a time step\nbehind the positions.\n\n# Arguments\n- `dt::T`: the time step of the simulation.\n- `coupling::C=NoCoupling()`: the coupling which applies during the simulation.\n- `remove_CM_motion::Bool=true`: whether to remove the centre of mass motion\n every time step.\n\"\"\"\nstruct Verlet{T, C}\n dt::T\n coupling::C\n remove_CM_motion::Bool\nend\n\nfunction Verlet(; dt, coupling=NoCoupling(), remove_CM_motion=true)\n return Verlet(dt, coupling, remove_CM_motion)\nend\n\nfunction simulate!(sys,\n sim::Verlet,\n n_steps::Integer;\n parallel::Bool=true)\n neighbors = find_neighbors(sys, sys.neighbor_finder; parallel=parallel)\n run_loggers!(sys, neighbors, 0; parallel=parallel)\n sim.remove_CM_motion && remove_CM_motion!(sys)\n\n for step_n in 1:n_steps\n accels_t = accelerations(sys, neighbors; parallel=parallel)\n\n sys.velocities += remove_molar.(accels_t) .* sim.dt\n\n sys.coords += sys.velocities .* sim.dt\n sys.coords = wrap_coords_vec.(sys.coords, (sys.box_size,))\n\n sim.remove_CM_motion && remove_CM_motion!(sys)\n apply_coupling!(sys, sim, sim.coupling)\n\n run_loggers!(sys, neighbors, step_n; parallel=parallel)\n\n if step_n != n_steps\n neighbors = find_neighbors(sys, sys.neighbor_finder, neighbors, step_n;\n parallel=parallel)\n end\n end\n return sys\nend\n\n\"\"\"\n StormerVerlet(; )\n\nThe Störmer-Verlet integrator.\nDoes not currently work with coupling methods that alter the velocity.\n\n# Arguments\n- `dt::T`: the time step of the simulation.\n- `coupling::C=NoCoupling()`: the coupling which applies during the simulation.\n\"\"\"\nstruct StormerVerlet{T, C}\n dt::T\n coupling::C\nend\n\nStormerVerlet(; dt, coupling=NoCoupling()) = StormerVerlet(dt, coupling)\n\nfunction simulate!(sys,\n sim::StormerVerlet,\n n_steps::Integer;\n parallel::Bool=true)\n neighbors = find_neighbors(sys, sys.neighbor_finder; parallel=parallel)\n run_loggers!(sys, neighbors, 0; parallel=parallel)\n coords_last = sys.coords\n\n for step_n in 1:n_steps\n accels_t = accelerations(sys, neighbors; parallel=parallel)\n\n coords_copy = sys.coords\n if step_n == 1\n # Use the velocities at the first step since there is only one set of coordinates\n sys.coords += sys.velocities .* sim.dt .+ (remove_molar.(accels_t) .* sim.dt ^ 2) ./ 2\n else\n sys.coords += vector.(coords_last, sys.coords, (sys.box_size,)) .+ remove_molar.(accels_t) .* sim.dt ^ 2\n end\n sys.coords = wrap_coords_vec.(sys.coords, (sys.box_size,))\n\n # This is accurate to O(dt)\n sys.velocities = vector.(coords_copy, sys.coords, (sys.box_size,)) ./ sim.dt\n\n apply_coupling!(sys, sim, sim.coupling)\n\n run_loggers!(sys, neighbors, step_n; parallel=parallel)\n\n if step_n != n_steps\n neighbors = find_neighbors(sys, sys.neighbor_finder, neighbors, step_n;\n parallel=parallel)\n coords_last = coords_copy\n end\n end\n return sys\nend\n\n\"\"\"\n Langevin(; )\n\nThe Langevin integrator, based on the Langevin Middle Integrator in OpenMM.\nThis is a leapfrog integrator, so the velocities are offset by half a time step\nbehind the positions.\n\n# Arguments\n- `dt::T`: the time step of the simulation.\n- `temperature::K`: the temperature of the simulation.\n- `friction::F`: the friction coefficient of the simulation.\n- `remove_CM_motion::Bool=true`: whether to remove the centre of mass motion\n every time step.\n\"\"\"\nstruct Langevin{S, K, F, T}\n dt::S\n temperature::K\n friction::F\n remove_CM_motion::Bool\n vel_scale::T\n noise_scale::T\nend\n\nfunction Langevin(; dt, temperature, friction, remove_CM_motion=true)\n vel_scale = exp(-dt * friction)\n noise_scale = sqrt(1 - vel_scale^2)\n return Langevin(dt, temperature, friction, remove_CM_motion, vel_scale, noise_scale)\nend\n\nfunction simulate!(sys,\n sim::Langevin,\n n_steps::Integer;\n parallel::Bool=true,\n rng=Random.GLOBAL_RNG)\n neighbors = find_neighbors(sys, sys.neighbor_finder; parallel=parallel)\n run_loggers!(sys, neighbors, 0; parallel=parallel)\n sim.remove_CM_motion && remove_CM_motion!(sys)\n\n for step_n in 1:n_steps\n accels_t = accelerations(sys, neighbors; parallel=parallel)\n\n sys.velocities += remove_molar.(accels_t) .* sim.dt\n\n sys.coords += sys.velocities .* sim.dt / 2\n noise = random_velocities(sys, sim.temperature; rng=rng)\n sys.velocities = sys.velocities .* sim.vel_scale .+ noise .* sim.noise_scale\n\n sys.coords += sys.velocities .* sim.dt / 2\n sys.coords = wrap_coords_vec.(sys.coords, (sys.box_size,))\n sim.remove_CM_motion && remove_CM_motion!(sys)\n\n run_loggers!(sys, neighbors, step_n; parallel=parallel)\n\n if step_n != n_steps\n neighbors = find_neighbors(sys, sys.neighbor_finder, neighbors, step_n;\n parallel=parallel)\n end\n end\n return sys\nend\n", "meta": {"hexsha": "9bc9e02b57f6570bdd42ce1628b0cf68bbd69321", "size": 10506, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simulators.jl", "max_stars_repo_name": "chemicalfiend/Molly.jl", "max_stars_repo_head_hexsha": "561b42f30b18699902da8ee0036184929d0436cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-05-17T00:35:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-21T09:36:02.000Z", "max_issues_repo_path": "src/simulators.jl", "max_issues_repo_name": "chemicalfiend/Molly.jl", "max_issues_repo_head_hexsha": "561b42f30b18699902da8ee0036184929d0436cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-10-29T19:18:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-16T16:43:25.000Z", "max_forks_repo_path": "src/simulators.jl", "max_forks_repo_name": "chemicalfiend/Molly.jl", "max_forks_repo_head_hexsha": "561b42f30b18699902da8ee0036184929d0436cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-10-29T19:03:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T20:34:58.000Z", "avg_line_length": 32.5263157895, "max_line_length": 116, "alphanum_fraction": 0.6302113078, "num_tokens": 2556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.2452001491997269}} {"text": "function converttopartitionedbernoullidbm(mdbm::MultimodalDBM)\n Vector{Union{BernoulliRBM, PartitionedRBM{BernoulliRBM}}}(mdbm)\nend\n\n\n\"\"\"\n addlayer!(dbm, x)\nAdds a pretrained layer to the BasicDBM `dbm`, given the dataset `x` as input\nfor the visible layer of the `dbm`.\n\n# Optional keyword arguments:\n* `isfirst`, `islast`: indicating that the new RBM should be trained as\n first (assumed if `dbm` is empty) or last layer of the DBM, respectively.\n If those flags are not set, the added layer is trained as intermediate layer.\n This information is needed to determine the factor for the weights during\n pretraining.\n* `epochs`, `nhidden`, `learningrate`/`learningrates`, `pcd`, `cdsteps`,\n `monitoring`: used for fitting the weights of the last layer, see `fitrbm(x)`\n\"\"\"\nfunction addlayer!(dbm::BasicDBM, x::Matrix{Float64};\n isfirst::Bool = isempty(dbm),\n islast::Bool = false,\n nhidden::Int = size(x,2),\n epochs::Int = 10,\n learningrate::Float64 = 0.005,\n learningrates::Vector{Float64} = learningrate * ones(epochs),\n pcd::Bool = true,\n cdsteps::Int = 1,\n monitoring::Function = nomonitoring)\n\n warn(\"`addlayer!`` is deprecated. Please use the options of `fitdbm` instead.\")\n # propagate input x up to last hidden layer\n hh = x\n for i = 1:length(dbm)\n hh = hiddenpotential(dbm[i], hh, 2.0) # intermediate layer, factor is 2.0\n end\n\n upfactor = downfactor = 2.0\n if isfirst\n downfactor = 1.0\n end\n if islast\n upfactor = 1.0\n end\n\n rbm = fitrbm(hh, nhidden = nhidden, epochs = epochs,\n rbmtype = BernoulliRBM,\n learningrate = learningrate,\n learningrates = learningrates,\n pcd = pcd, cdsteps = 1,\n upfactor = upfactor, downfactor = downfactor,\n monitoring = monitoring)\n\n push!(dbm, rbm)\n dbm\nend\n\n\nfunction defaultfinetuninglearningrates(learningrate, epochs)\n learningrate * 11.0 ./ (10.0 .+ (1:epochs))\nend\n\n\n\"\"\"\n fitdbm(x; ...)\nFits a (multimodal) DBM to the data set `x`.\nThe procedure consists of two parts:\nFirst a stack of RBMs is pretrained in a greedy layerwise manner\n(see `stackrbms(x)`). Then the weights of all layers are jointly\ntrained using the general Boltzmann Machine learning procedure\n(see `traindbm!(dbm,x)`).\n\n# Optional keyword arguments (ordered by importance):\n* `nhiddens`: vector that defines the number of nodes in the hidden layers of\n the DBM. The default value specifies two hidden layers with the same size\n as the visible layer.\n* `epochs`: number of training epochs for joint training\n* `epochspretraining`: number of training epochs for pretraining,\n defaults to `epochs`\n* `learningrate`/`learningrates`:\n learning rate(s) for joint training of layers (= fine tuning)\n using the learning algorithm for a general Boltzmann Machine.\n The learning rate for fine tuning is by default decaying with the number of epochs,\n starting with the given value for the `learningrate`.\n (For more details see `traindbm!`).\n* `learningratepretraining`: learning rate for pretraining,\n defaults to `learningrate`\n* `batchsizepretraining`: batchsize for pretraining, defaults to 1\n* `nparticles`: number of particles used for sampling during joint training of\n DBM, default 100\n* `pretraining`: The arguments for layerwise pretraining\n can be specified for each layer individually.\n This is done via a vector of `TrainLayer` objects.\n (For a detailed description of the possible parameters,\n see help for `TrainLayer`).\n If the number of training epochs and the learning rate are not specified\n explicitly for a layer, the values of `epochspretraining`,\n `learningratepretraining` and `batchsizepretraining` are used.\n* `monitoring`: Monitoring function accepting a `dbm` and the number of epochs\n retuning nothing. Used for the monitoring of fine-tuning.\n* `monitoringdatapretraining`: a `DataDict` that contains data used for\n monitoring the pretraining (see argument `monitoringdata` of `stackrbms`.)\n* `optimizer`/`optimizers`: an optimizer or a vector of optimizers for each epoch\n (see `AbstractOptimizer`) used for fine-tuning.\n* `optimizerpretraining`: an optimizer used for pre-training.\n Defaults to the `optimizer`.\n\"\"\"\nfunction fitdbm(x::Matrix{Float64};\n nhiddens::Vector{Int} = Vector{Int}(),\n epochs::Int = 10,\n nparticles::Int = 100,\n learningrate::Float64 = 0.005,\n learningrates::Vector{Float64} =\n defaultfinetuninglearningrates(learningrate, epochs),\n sdlearningrate::Float64 = 0.0,\n sdlearningrates::Vector{Float64} =\n defaultfinetuninglearningrates(sdlearningrate, epochs),\n learningratepretraining::Float64 = learningrate,\n epochspretraining::Int = epochs,\n batchsizepretraining::Int = 1,\n pretraining::AbstractTrainLayers = Vector{TrainLayer}(),\n monitoring::Function = nomonitoring,\n monitoringdatapretraining::DataDict = DataDict(),\n optimizer::AbstractOptimizer = NoOptimizer(),\n optimizers::Vector{<:AbstractOptimizer} = Vector{AbstractOptimizer}(),\n optimizerpretraining::AbstractOptimizer = optimizer)\n\n if isempty(pretraining) && isempty(nhiddens)\n # set default only if there is not any more detailed info\n nvariables = size(x,2)\n nhiddens = [nvariables; nvariables]\n end\n\n # Layerwise pre-training\n pretraineddbm = stackrbms(x, nhiddens = nhiddens,\n epochs = epochspretraining, predbm = true,\n batchsize = batchsizepretraining,\n learningrate = learningratepretraining,\n optimizer = optimizer,\n trainlayers = pretraining,\n monitoringdata = monitoringdatapretraining)\n # Fine-tuning using mean-field approximation in algorithm for\n # training a general Boltzmann machine\n traindbm!(pretraineddbm, x, epochs = epochs, nparticles = nparticles,\n learningrate = learningrate, learningrates = learningrates,\n sdlearningrate = sdlearningrate, sdlearningrates = sdlearningrates,\n optimizer = optimizer, optimizers = optimizers,\n monitoring = monitoring)\nend\n\n\n\"\"\"\n newparticleslike(particles)\nCreates new and uninitialized particles of the same dimensions as the given\n`particles`.\n\"\"\"\nfunction newparticleslike(particles::Particles)\n newparticles = Particles(undef, length(particles))\n for i in eachindex(particles)\n newparticles[i] = Matrix{Float64}(undef, size(particles[i]))\n end\n newparticles\nend\n\n\n\"\"\"\n meanfield(dbm, x)\n meanfield(dbm, x, eps)\nComputes the mean-field approximation for the data set `x` and\nreturns a matrix of particles for the DBM.\nThe number of particles is equal to the number of samples in `x`.\n`eps` is the convergence criterion for the fix-point iteration, default 0.001.\nIt is assumed that all nodes in in-between-layers are Bernoulli distributed.\n\"\"\"\nfunction meanfield(dbm::MultimodalDBM, x::Array{Float64,2}, eps::Float64 = 0.001)\n\n nlayers = length(dbm) + 1\n mu = Particles(undef, nlayers)\n\n # Initialization with single bottom-up pass using twice the weights for all\n # but the topmost layer (see [Salakhutdinov+Hinton, 2012], p. 1985)\n mu[1] = x\n for i=2:(nlayers-1)\n mu[i] = hiddenpotential(dbm[i-1], mu[i-1], 2.0)\n end\n mu[nlayers] = hiddenpotential(dbm[nlayers-1], mu[nlayers-1])\n\n newmu = newparticleslike(mu)\n newmu[1] = x\n input2 = newparticleslike(mu)\n\n # mean-field updates until convergence criterion is met\n delta = 1.0\n while delta > eps\n delta = 0.0\n\n for i = 2:(nlayers-1)\n # total input from layer below\n hiddeninput!(newmu[i], dbm[i-1], mu[i-1])\n # input from layer above\n visibleinput!(input2[i], dbm[i], mu[i+1])\n # combine input\n newmu[i] .+= input2[i]\n # By computing the potential,\n # the assumption is used that all nodes in in-between-layers\n # are Bernoulli-distributed:\n sigm!(newmu[i])\n\n delta = max(delta, maximum(abs.(mu[i] - newmu[i])))\n\n # swap new and old mu\n tmp = newmu[i]\n newmu[i] = mu[i]\n mu[i] = tmp\n end\n\n # last layer\n hiddenpotential!(newmu[end], dbm[end], mu[end-1])\n delta = max(delta, maximum(abs.(mu[end] - newmu[end])))\n\n # swap new and old mu\n tmp = newmu[end]\n newmu[end] = mu[end]\n mu[end] = tmp\n end\n\n mu\nend\n\n\n\"\"\"\n traindbm!(dbm, x; ...)\nTrains the `dbm` (a `BasicDBM` or a more general `MultimodalDBM`) using\nthe learning procedure for a general Boltzmann Machine with the\ntraining data set `x`.\nA learning step consists of mean-field inference (positive phase),\nstochastic approximation by Gibbs Sampling (negative phase) and the parameter\nupdates.\n\n# Optional keyword arguments (ordered by importance):\n* `epoch`: number of training epochs\n* `learningrate`/`learningrates`: a vector of learning rates for each epoch to\n update the weights and biases. The learning rates should decrease with the\n epochs, e. g. like `a / (b + epoch)`. If only one value is given as\n `learningrate`, `a` and `b` are 11.0 and 10.0, respectively.\n* `nparticles`: number of particles used for sampling, default 100\n* `monitoring`: A function that is executed after each training epoch.\n It has to accept the trained DBM and the current epoch as arguments.\n\"\"\"\nfunction traindbm!(dbm::MultimodalDBM, x::Array{Float64,2};\n epochs::Int = 10,\n nparticles::Int = 100,\n learningrate::Float64 = 0.005,\n learningrates::Vector{Float64} =\n defaultfinetuninglearningrates(learningrate, epochs),\n sdlearningrate::Float64 = 0.0,\n sdlearningrates::Vector{Float64} =\n defaultfinetuninglearningrates(sdlearningrate, epochs),\n monitoring::Function = nomonitoring,\n optimizer::AbstractOptimizer = NoOptimizer(),\n optimizers::Vector{<:AbstractOptimizer} = Vector{AbstractOptimizer}())\n\n assert_enoughvaluesforepochs(\"learningrates\", learningrates, epochs)\n\n optimizer = converttodbmoptimizer(optimizer, dbm)\n map!(opt -> converttodbmoptimizer(opt, dbm), optimizers, optimizers)\n optimizers = assertinitoptimizers(optimizer, optimizers, dbm,\n learningrates, sdlearningrates, epochs)\n\n particles = initparticles(dbm, nparticles)\n \n for epoch = 1:epochs\n traindbm!(dbm, x, particles, optimizers[epoch])\n\n # monitoring the learning process at the end of epoch\n monitoring(dbm, epoch)\n end\n\n dbm\nend\n\n\n\"\"\"\n traindbm!(dbm, x, particles, learningrate)\nTrains the given `dbm` for one epoch.\n\"\"\"\nfunction traindbm!(dbm::MultimodalDBM, x::Array{Float64,2}, particles::Particles,\n optimizer::AbstractOptimizer)\n\n gibbssample!(particles, dbm)\n mu = meanfield(dbm, x)\n\n computegradient!(optimizer, mu, particles, dbm)\n updateparameters!(dbm, optimizer)\n\n dbm\nend\n", "meta": {"hexsha": "b5c582f9a2a77f0ec346e34a4fcd075a81d8b8af", "size": 10817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dbmtraining.jl", "max_stars_repo_name": "MTreppner/scDBM.jl", "max_stars_repo_head_hexsha": "16a12562e6f3c151ab68dab6e39ed3094302ec43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-14T12:32:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-30T13:06:40.000Z", "max_issues_repo_path": "src/dbmtraining.jl", "max_issues_repo_name": "MTreppner/scDBM.jl", "max_issues_repo_head_hexsha": "16a12562e6f3c151ab68dab6e39ed3094302ec43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dbmtraining.jl", "max_forks_repo_name": "MTreppner/scDBM.jl", "max_forks_repo_head_hexsha": "16a12562e6f3c151ab68dab6e39ed3094302ec43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2986577181, "max_line_length": 86, "alphanum_fraction": 0.69668115, "num_tokens": 2858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24507923728798509}} {"text": "module GuillotineCallback\n\ninclude(\"./../../constraints/geometric/constants.jl\")\nusing JuMP\nusing .Constants\n\nexport guillotine_callback, get_involved_boxes_flbx, find_all_guillotine_cuts_exceeding_limit\n\n\n#Finds a guillotine cut that is larger than the allowed amount\nfunction guillotine_callback(cb_data, m)\n\n max_cut = guillotine_ds_var * callback_value(cb_data, m[:maxHeight])\n\n fixed_x = []\n fixed_y = []\n\n #Check if there exists a cut higher than the allowed cuts\n for i in 1:length(boxes) - 1\n\n if length(fixed_x) > 0 || length(fixed_y) > 0\n print(\"Fixed X \", fixed_x, \"\\n\")\n print(\"Fixed Y \", fixed_y, \"\\n\")\n end\n\n print(\"Round \", i, \"\\n\")\n \n #Find out where the cut is and pass information onwards\n if (callback_value(cb_data, m[:cut_flbx_left_i][i]) + 0.001 >= max_cut && check_if_fixed_x(cb_data, m, 1, i, fixed_x))\n print(\"Nr 1 \\n\")\n get_involved_boxes(cb_data, m, 1, i)\n x_value = callback_value(cb_data, m[:flbx_front_left_bot_x][i])\n push!(fixed_x, x_value)\n end\n if (callback_value(cb_data, m[:cut_flbx_j_plus_left_i][i]) + 0.001 >= max_cut && check_if_fixed_x(cb_data, m, 2, i, fixed_x))\n print(\"Nr 2 \\n\")\n get_involved_boxes(cb_data, m, 2, i)\n x_value = callback_value(cb_data, m[:flbx_front_left_bot_x][i])\n push!(fixed_x, x_value)\n end\n if (callback_value(cb_data, m[:cut_flbx_i_plus_right][i]) + 0.001 >= max_cut && check_if_fixed_x(cb_data, m, 3, i, fixed_x))\n print(\"Nr 3 \\n\")\n get_involved_boxes(cb_data, m, 3, i)\n x_value = callback_value(cb_data, m[:flbx_front_left_bot_x][i]) + callback_value(cb_data, m[:box_x_axis_cover][i])\n push!(fixed_x, x_value)\n end\n if (callback_value(cb_data, m[:cut_flbx_ij_plus_right][i]) + 0.001 >= max_cut && check_if_fixed_x(cb_data, m, 4, i, fixed_x))\n print(\"Nr 4 \\n\")\n get_involved_boxes(cb_data, m, 4, i)\n x_value = callback_value(cb_data, m[:flbx_front_left_bot_x][i]) + callback_value(cb_data, m[:box_x_axis_cover][i])\n push!(fixed_x, x_value)\n end\n if (callback_value(cb_data, m[:cut_flby_right][i]) + 0.001 >= max_cut && check_if_fixed_y(cb_data, m, 5, i, fixed_y))\n print(\"Nr 5 \\n\")\n get_involved_boxes(cb_data, m, 5, i)\n y_value = callback_value(cb_data, m[:flby_front_left_bot_y][i])\n push!(fixed_y, y_value)\n end\n if (callback_value(cb_data, m[:cut_flby_j_plus_right][i]) + 0.001 >= max_cut && check_if_fixed_y(cb_data, m, 6, i, fixed_y))\n print(\"Nr 6 \\n\")\n get_involved_boxes(cb_data, m, 6, i)\n y_value = callback_value(cb_data, m[:flby_front_left_bot_y][i])\n push!(fixed_y, y_value)\n end\n if (callback_value(cb_data, m[:cut_flby_i_plus_left][i]) + 0.001 >= max_cut && check_if_fixed_y(cb_data, m, 7, i, fixed_y))\n print(\"Nr 7 \\n\")\n get_involved_boxes(cb_data, m, 7, i)\n y_value = callback_value(cb_data, m[:flby_front_left_bot_y][i]) + callback_value(cb_data, m[:box_y_axis_cover][i])\n push!(fixed_y, y_value)\n end\n if (callback_value(cb_data, m[:cut_flby_ij_plus_left][i]) + 0.001 >= max_cut && check_if_fixed_y(cb_data, m, 8, i, fixed_y))\n print(\"Nr 8 \\n\")\n get_involved_boxes(cb_data, m, 8, i)\n y_value = callback_value(cb_data, m[:flby_front_left_bot_y][i]) + callback_value(cb_data, m[:box_y_axis_cover][i])\n push!(fixed_y, y_value)\n end\n end\n\n return \nend\n\nfunction check_if_fixed_x(cb_data, m, pos, i, fixed_x)\n fixed = false\n if pos == 1 || pos == 2\n for fixed_pos in 1:length(fixed_x)\n if (callback_value(cb_data, m[:flbx_front_left_bot_x][i]) - 0.0001 <= \n fixed_x[fixed_pos] <= \n callback_value(cb_data, m[:flbx_front_left_bot_x][i]) + 0.0001)\n fixed = true\n end\n end\n elseif pos == 3 || pos == 4\n for fixed_pos in 1:length(fixed_x)\n if (callback_value(cb_data, m[:flbx_front_left_bot_x][i]) + callback_value(cb_data, m[:box_x_axis_cover][i]) - 0.0001 <= \n fixed_x[fixed_pos] <= \n callback_value(cb_data, m[:flbx_front_left_bot_x][i]) + callback_value(cb_data, m[:box_x_axis_cover][i]) + 0.0001)\n fixed = true\n end\n end\n end\n return ~fixed\nend\n\nfunction check_if_fixed_y(cb_data, m, pos, i, fixed_y)\n fixed = false\n if pos == 5 || pos == 6\n for fixed_pos in 1:length(fixed_y)\n if (callback_value(cb_data, m[:flby_front_left_bot_y][i]) - 0.0001 <= \n fixed_y[fixed_pos] <= \n callback_value(cb_data, m[:flby_front_left_bot_y][i]) + 0.0001)\n fixed = true\n end\n end\n elseif pos == 7 || pos == 8\n for fixed_pos in 1:length(fixed_y)\n if (callback_value(cb_data, m[:flby_front_left_bot_y][i]) + callback_value(cb_data, m[:box_y_axis_cover][i]) - 0.0001 <= \n fixed_y[fixed_pos] <= \n callback_value(cb_data, m[:flby_front_left_bot_y][i]) + callback_value(cb_data, m[:box_y_axis_cover][i]) + 0.0001)\n fixed = true\n end\n end\n end\n return ~fixed\nend\n\n\n#Takes a box number to check what boxes are involved in guillotine\nfunction get_involved_boxes(cb_data, m, pos, i)\n involved = []\n push!(involved, i)\n # Check the position of the cut\n for j in 1:length(boxes) - 1\n if i!=j\n if (pos == 1)\n if (callback_value(cb_data, m[:guillotine_flbx][i, j]) == 1)\n push!(involved, j)\n end\n elseif (pos == 2)\n if (callback_value(cb_data, m[:guillotine_flbx_j_plus][i, j]) == 1)\n push!(involved, j)\n end\n elseif (pos == 3)\n if (callback_value(cb_data, m[:guillotine_flbx_i_plus][i, j]) == 1)\n push!(involved, j)\n end\n elseif (pos == 4)\n if (callback_value(cb_data, m[:guillotine_flbx_ij_plus][i, j]) == 1)\n push!(involved, j)\n end\n elseif (pos == 5)\n if (callback_value(cb_data, m[:guillotine_flby][i, j]) == 1)\n push!(involved, j)\n end\n elseif (pos == 6)\n if (callback_value(cb_data, m[:guillotine_flby_j_plus][i, j]) == 1)\n push!(involved, j)\n end\n elseif (pos == 7)\n if (callback_value(cb_data, m[:guillotine_flby_i_plus][i, j]) == 1)\n push!(involved, j)\n end\n elseif (pos == 8)\n if (callback_value(cb_data, m[:guillotine_flby_ij_plus][i, j]) == 1)\n push!(involved, j)\n end\n end\n break\n end\n end\n \n if (length(involved) >= 2)\n create_constraint(cb_data, m, involved, pos)\n end \nend\n\nfunction create_constraint(cb_data, m, involved, pos)\n print(involved)\n \n max_height = 0\n max_height_box = 0\n snd_max_height = 0\n snd_max_height_box = 0\n\n for i in 1:length(involved)\n height_of_i = callback_value(cb_data, m[:flbz_front_left_bot_z][involved[i]]) + callback_value(cb_data, m[:hob_height_of_box][involved[i]])\n if height_of_i >= max_height\n #update second highest\n snd_max_height = max_height\n snd_max_height_box = max_height_box\n\n #update highest\n max_height = height_of_i\n max_height_box = involved[i]\n elseif height_of_i >= snd_max_height\n #update second highest\n snd_max_height = height_of_i\n snd_max_height_box = involved[i]\n end\n end\n\n for i in 1:3\n print('\\n')\n print(i)\n print('\\n')\n @show callback_value(cb_data, m[:flbx_front_left_bot_x][i])\n @show callback_value(cb_data, m[:flby_front_left_bot_y][i]) \n @show callback_value(cb_data, m[:flbz_front_left_bot_z][i]) \n end\n\n print('\\n')\n print(\"First \", max_height, \" \", max_height_box, \"\\n\")\n print(\"Second \", snd_max_height, \" \", snd_max_height_box, \"\\n\")\n\n #If same size as sentinel, then the new constraints can't apply. \n if ~((callback_value(cb_data, m[:lob_length_of_box][max_height_box]) >= \n (1 - guillotine_fix_var) * callback_value(cb_data, m[:lob_length_of_box][length(boxes)])) &&\n (callback_value(cb_data, m[:wob_width_of_box][max_height_box]) >= \n (1 - guillotine_fix_var) * callback_value(cb_data, m[:wob_width_of_box][length(boxes)])))\n\n #check if lowest dimension still same as width of sentinel\n if ~((callback_value(cb_data, m[:lob_length_of_box][max_height_box]) >= \n (1 - guillotine_fix_var) * callback_value(cb_data, m[:lob_length_of_box][length(boxes)])) &&\n (callback_value(cb_data, m[:wob_width_of_box][max_height_box]) >= \n (1 - guillotine_fix_var) * callback_value(cb_data, m[:lob_length_of_box][length(boxes)])))\n if pos == 1\n con = @build_constraint(\n m[:flbx_front_left_bot_x][max_height_box] - \n m[:flbx_front_left_bot_x][snd_max_height_box] >= guillotine_fix_var\n )\n print(\"added constraint 1 \\n\")\n elseif pos == 2\n con = @build_constraint(\n (m[:flbx_front_left_bot_x][max_height_box] + m[:box_x_axis_cover][max_height_box]) -\n m[:flbx_front_left_bot_x][snd_max_height_box] >= guillotine_fix_var\n )\n print(\"added constraint 2 \\n\")\n elseif pos == 3\n con = @build_constraint(\n (m[:flbx_front_left_bot_x][snd_max_height_box] + m[:box_x_axis_cover][snd_max_height_box]) - \n m[:flbx_front_left_bot_x][max_height_box] >= guillotine_fix_var\n )\n print(\"added constraint 3 \\n\") \n elseif pos == 4\n con = @build_constraint(\n (m[:flbx_front_left_bot_x][snd_max_height_box] + m[:box_x_axis_cover][snd_max_height_box]) - \n (m[:flbx_front_left_bot_x][max_height_box] + m[:box_x_axis_cover][max_height_box]) >= guillotine_fix_var\n )\n print(\"added constraint 4 \\n\")\n end\n if pos == 1 || pos == 2 || pos == 3 || pos == 4\n MOI.submit(m, MOI.LazyConstraint(cb_data), con)\n end\n end\n if ~((callback_value(cb_data, m[:lob_length_of_box][max_height_box]) >= \n (1 - guillotine_fix_var) * callback_value(cb_data, m[:wob_width_of_box][length(boxes)])) &&\n (callback_value(cb_data, m[:wob_width_of_box][max_height_box]) >= \n (1 - guillotine_fix_var) * callback_value(cb_data, m[:wob_width_of_box][length(boxes)])))\n if pos == 5\n con = @build_constraint(\n m[:flby_front_left_bot_y][max_height_box] - \n m[:flby_front_left_bot_y][snd_max_height_box] >= guillotine_fix_var\n )\n print(\"added constraint 5 \\n\")\n elseif pos == 6\n con = @build_constraint(\n (m[:flby_front_left_bot_y][max_height_box] + m[:box_y_axis_cover][max_height_box]) -\n m[:flby_front_left_bot_y][snd_max_height_box] >= guillotine_fix_var\n )\n print(\"added constraint 6 \\n\")\n elseif pos == 7\n con = @build_constraint(\n (m[:flby_front_left_bot_y][snd_max_height_box] + m[:box_y_axis_cover][snd_max_height_box]) - \n m[:flby_front_left_bot_y][max_height_box] >= guillotine_fix_var\n )\n print(\"added constraint 7 \\n\") \n elseif pos == 8\n con = @build_constraint(\n (m[:flby_front_left_bot_y][snd_max_height_box] + m[:box_y_axis_cover][snd_max_height_box]) - \n (m[:flby_front_left_bot_y][max_height_box] + m[:box_y_axis_cover][max_height_box]) >= guillotine_fix_var\n )\n print(\"added constraint 8 \\n\")\n end\n if pos == 5 || pos == 6 || pos == 7 || pos == 8\n MOI.submit(m, MOI.LazyConstraint(cb_data), con)\n end \n end\n end\n\nend\n\n\nend\n\n\n", "meta": {"hexsha": "6baa74057288f4f9003988f359698aa93a10ba52", "size": 12678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/constraints/dynamic_stability/guillotine/callback.jl", "max_stars_repo_name": "ToralfFrich/Master_Thesis", "max_stars_repo_head_hexsha": "5d4a51598f1677c2f5c219a88ca9ab4c9b6a5c6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/constraints/dynamic_stability/guillotine/callback.jl", "max_issues_repo_name": "ToralfFrich/Master_Thesis", "max_issues_repo_head_hexsha": "5d4a51598f1677c2f5c219a88ca9ab4c9b6a5c6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/constraints/dynamic_stability/guillotine/callback.jl", "max_forks_repo_name": "ToralfFrich/Master_Thesis", "max_forks_repo_head_hexsha": "5d4a51598f1677c2f5c219a88ca9ab4c9b6a5c6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9762711864, "max_line_length": 147, "alphanum_fraction": 0.5694115791, "num_tokens": 3425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24507923171918283}} {"text": "# This file is a part of Julia. License is MIT: https://julialang.org/license\n\nmodule Random\n\nusing Base.dSFMT\nusing Base.GMP: GMP_VERSION, Limb\nimport Base: copymutable, copy, copy!, ==\n\nexport srand,\n rand, rand!,\n randn, randn!,\n randexp, randexp!,\n bitrand,\n randstring,\n randsubseq,randsubseq!,\n shuffle,shuffle!,\n randperm, randcycle,\n AbstractRNG, MersenneTwister, RandomDevice,\n GLOBAL_RNG, randjump\n\n\nabstract type AbstractRNG end\n\nabstract type FloatInterval end\nmutable struct CloseOpen <: FloatInterval end\nmutable struct Close1Open2 <: FloatInterval end\n\n\n## RandomDevice\n\nif is_windows()\n\n struct RandomDevice <: AbstractRNG\n buffer::Vector{UInt128}\n\n RandomDevice() = new(Vector{UInt128}(1))\n end\n\n function rand{T<:Union{Bool, Base.BitInteger}}(rd::RandomDevice, ::Type{T})\n win32_SystemFunction036!(rd.buffer)\n @inbounds return rd.buffer[1] % T\n end\n\n rand!(rd::RandomDevice, A::Array{<:Union{Bool, Base.BitInteger}}) = (win32_SystemFunction036!(A); A)\nelse # !windows\n struct RandomDevice <: AbstractRNG\n file::IOStream\n unlimited::Bool\n\n RandomDevice(unlimited::Bool=true) = new(open(unlimited ? \"/dev/urandom\" : \"/dev/random\"), unlimited)\n end\n\n rand{T<:Union{Bool, Base.BitInteger}}(rd::RandomDevice, ::Type{T}) = read( rd.file, T)\n rand!(rd::RandomDevice, A::Array{<:Union{Bool, Base.BitInteger}}) = read!(rd.file, A)\nend # os-test\n\n\n\"\"\"\n RandomDevice()\n\nCreate a `RandomDevice` RNG object. Two such objects will always generate different streams of random numbers.\n\"\"\"\nRandomDevice\n\n\nrand(rng::RandomDevice, ::Type{Close1Open2}) =\n reinterpret(Float64, 0x3ff0000000000000 | rand(rng, UInt64) & 0x000fffffffffffff)\n\nrand(rng::RandomDevice, ::Type{CloseOpen}) = rand(rng, Close1Open2) - 1.0\n\n\n## MersenneTwister\n\nconst MTCacheLength = dsfmt_get_min_array_size()\n\nmutable struct MersenneTwister <: AbstractRNG\n seed::Vector{UInt32}\n state::DSFMT_state\n vals::Vector{Float64}\n idx::Int\n\n function MersenneTwister(seed, state, vals, idx)\n length(vals) == MTCacheLength && 0 <= idx <= MTCacheLength || throw(DomainError())\n new(seed, state, vals, idx)\n end\nend\n\nMersenneTwister(seed::Vector{UInt32}, state::DSFMT_state) =\n MersenneTwister(seed, state, zeros(Float64, MTCacheLength), MTCacheLength)\n\n\"\"\"\n MersenneTwister(seed)\n\nCreate a `MersenneTwister` RNG object. Different RNG objects can have their own seeds, which\nmay be useful for generating different streams of random numbers.\n\"\"\"\nMersenneTwister(seed) = srand(MersenneTwister(Vector{UInt32}(), DSFMT_state()), seed)\n\nfunction copy!(dst::MersenneTwister, src::MersenneTwister)\n copy!(resize!(dst.seed, length(src.seed)), src.seed)\n copy!(dst.state, src.state)\n copy!(dst.vals, src.vals)\n dst.idx = src.idx\n dst\nend\n\ncopy(src::MersenneTwister) =\n MersenneTwister(copy(src.seed), copy(src.state), copy(src.vals), src.idx)\n\n==(r1::MersenneTwister, r2::MersenneTwister) =\n r1.seed == r2.seed && r1.state == r2.state && isequal(r1.vals, r2.vals) && r1.idx == r2.idx\n\n\n## Low level API for MersenneTwister\n\n@inline mt_avail(r::MersenneTwister) = MTCacheLength - r.idx\n@inline mt_empty(r::MersenneTwister) = r.idx == MTCacheLength\n@inline mt_setfull!(r::MersenneTwister) = r.idx = 0\n@inline mt_setempty!(r::MersenneTwister) = r.idx = MTCacheLength\n@inline mt_pop!(r::MersenneTwister) = @inbounds return r.vals[r.idx+=1]\n\nfunction gen_rand(r::MersenneTwister)\n dsfmt_fill_array_close1_open2!(r.state, pointer(r.vals), length(r.vals))\n mt_setfull!(r)\nend\n\n@inline reserve_1(r::MersenneTwister) = mt_empty(r) && gen_rand(r)\n# `reserve` allows one to call `rand_inbounds` n times\n# precondition: n <= MTCacheLength\n@inline reserve(r::MersenneTwister, n::Int) = mt_avail(r) < n && gen_rand(r)\n\n# precondition: !mt_empty(r)\n@inline rand_inbounds(r::MersenneTwister, ::Type{Close1Open2}) = mt_pop!(r)\n@inline rand_inbounds(r::MersenneTwister, ::Type{CloseOpen}) = rand_inbounds(r, Close1Open2) - 1.0\n@inline rand_inbounds(r::MersenneTwister) = rand_inbounds(r, CloseOpen)\n\n# produce Float64 values\n@inline rand{I<:FloatInterval}(r::MersenneTwister, ::Type{I}) = (reserve_1(r); rand_inbounds(r, I))\n\n@inline rand_ui52_raw_inbounds(r::MersenneTwister) = reinterpret(UInt64, rand_inbounds(r, Close1Open2))\n@inline rand_ui52_raw(r::MersenneTwister) = (reserve_1(r); rand_ui52_raw_inbounds(r))\n@inline rand_ui2x52_raw(r::MersenneTwister) = rand_ui52_raw(r) % UInt128 << 64 | rand_ui52_raw(r)\n\nfunction srand(r::MersenneTwister, seed::Vector{UInt32})\n copy!(resize!(r.seed, length(seed)), seed)\n dsfmt_init_by_array(r.state, r.seed)\n mt_setempty!(r)\n return r\nend\n\n# MersenneTwister jump\n\n\"\"\"\n randjump(r::MersenneTwister, jumps::Integer, [jumppoly::AbstractString=dSFMT.JPOLY1e21]) -> Vector{MersenneTwister}\n\nCreate an array of the size `jumps` of initialized `MersenneTwister` RNG objects. The\nfirst RNG object given as a parameter and following `MersenneTwister` RNGs in the array are\ninitialized such that a state of the RNG object in the array would be moved forward (without\ngenerating numbers) from a previous RNG object array element on a particular number of steps\nencoded by the jump polynomial `jumppoly`.\n\nDefault jump polynomial moves forward `MersenneTwister` RNG state by `10^20` steps.\n\"\"\"\nfunction randjump(mt::MersenneTwister, jumps::Integer, jumppoly::AbstractString)\n mts = MersenneTwister[]\n push!(mts, mt)\n for i in 1:jumps-1\n cmt = mts[end]\n push!(mts, MersenneTwister(cmt.seed, dSFMT.dsfmt_jump(cmt.state, jumppoly)))\n end\n return mts\nend\nrandjump(r::MersenneTwister, jumps::Integer) = randjump(r, jumps, dSFMT.JPOLY1e21)\n\n## initialization\n\nfunction __init__()\n try\n srand()\n catch ex\n Base.showerror_nostdio(ex,\n \"WARNING: Error during initialization of module Random\")\n end\nend\n\n\n## make_seed()\n# make_seed methods produce values of type Array{UInt32}, suitable for MersenneTwister seeding\n\nfunction make_seed()\n try\n return rand(RandomDevice(), UInt32, 4)\n catch\n println(STDERR, \"Entropy pool not available to seed RNG; using ad-hoc entropy sources.\")\n seed = reinterpret(UInt64, time())\n seed = hash(seed, UInt64(getpid()))\n try\n seed = hash(seed, parse(UInt64, readstring(pipeline(`ifconfig`, `sha1sum`))[1:40], 16))\n end\n return make_seed(seed)\n end\nend\n\nfunction make_seed(n::Integer)\n n < 0 && throw(DomainError())\n seed = UInt32[]\n while true\n push!(seed, n & 0xffffffff)\n n >>= 32\n if n == 0\n return seed\n end\n end\nend\n\nfunction make_seed(filename::AbstractString, n::Integer)\n read!(filename, Vector{UInt32}(Int(n)))\nend\n\n## srand()\n\n\"\"\"\n srand([rng=GLOBAL_RNG], [seed]) -> rng\n srand([rng=GLOBAL_RNG], filename, n=4) -> rng\n\nReseed the random number generator. If a `seed` is provided, the RNG will give a\nreproducible sequence of numbers, otherwise Julia will get entropy from the system. For\n`MersenneTwister`, the `seed` may be a non-negative integer, a vector of `UInt32` integers\nor a filename, in which case the seed is read from a file (`4n` bytes are read from the file,\nwhere `n` is an optional argument). `RandomDevice` does not support seeding.\n\"\"\"\nsrand(r::MersenneTwister) = srand(r, make_seed())\nsrand(r::MersenneTwister, n::Integer) = srand(r, make_seed(n))\nsrand(r::MersenneTwister, filename::AbstractString, n::Integer=4) = srand(r, make_seed(filename, n))\n\n\nfunction dsfmt_gv_srand()\n # Temporary fix for #8874 and #9124: update global RNG for Rmath\n dsfmt_gv_init_by_array(GLOBAL_RNG.seed+UInt32(1))\n return GLOBAL_RNG\nend\n\nfunction srand()\n srand(GLOBAL_RNG)\n dsfmt_gv_srand()\nend\n\nfunction srand(seed::Union{Integer, Vector{UInt32}})\n srand(GLOBAL_RNG, seed)\n dsfmt_gv_srand()\nend\n\nfunction srand(filename::AbstractString, n::Integer=4)\n srand(GLOBAL_RNG, filename, n)\n dsfmt_gv_srand()\nend\n\n## Global RNG\n\nconst GLOBAL_RNG = MersenneTwister(0)\nglobalRNG() = GLOBAL_RNG\n\n# rand: a non-specified RNG defaults to GLOBAL_RNG\n\n\"\"\"\n rand([rng=GLOBAL_RNG], [S], [dims...])\n\nPick a random element or array of random elements from the set of values specified by `S`; `S` can be\n\n* an indexable collection (for example `1:n` or `['x','y','z']`), or\n* a type: the set of values to pick from is then equivalent to `typemin(S):typemax(S)` for\n integers (this is not applicable to `BigInt`), and to ``[0, 1)`` for floating point numbers;\n\n`S` defaults to `Float64`.\n\"\"\"\n@inline rand() = rand(GLOBAL_RNG, CloseOpen)\n@inline rand(T::Type) = rand(GLOBAL_RNG, T)\nrand(dims::Dims) = rand(GLOBAL_RNG, dims)\nrand(dims::Integer...) = rand(convert(Tuple{Vararg{Int}}, dims))\nrand(T::Type, dims::Dims) = rand(GLOBAL_RNG, T, dims)\nrand(T::Type, d1::Integer, dims::Integer...) = rand(T, tuple(Int(d1), convert(Tuple{Vararg{Int}}, dims)...))\nrand!(A::AbstractArray) = rand!(GLOBAL_RNG, A)\n\nrand(r::AbstractArray) = rand(GLOBAL_RNG, r)\n\n\"\"\"\n rand!([rng=GLOBAL_RNG], A, [coll])\n\nPopulate the array `A` with random values. If the indexable collection `coll` is specified,\nthe values are picked randomly from `coll`. This is equivalent to `copy!(A, rand(rng, coll, size(A)))`\nor `copy!(A, rand(rng, eltype(A), size(A)))` but without allocating a new array.\n\"\"\"\nrand!(A::AbstractArray, r::AbstractArray) = rand!(GLOBAL_RNG, A, r)\n\nrand(r::AbstractArray, dims::Dims) = rand(GLOBAL_RNG, r, dims)\nrand(r::AbstractArray, dims::Integer...) = rand(GLOBAL_RNG, r, convert(Tuple{Vararg{Int}}, dims))\n\n## random floating point values\n\n@inline rand(r::AbstractRNG) = rand(r, CloseOpen)\n\n# MersenneTwister & RandomDevice\n@inline rand(r::Union{RandomDevice,MersenneTwister}, ::Type{Float64}) = rand(r, CloseOpen)\n\nrand_ui10_raw(r::MersenneTwister) = rand_ui52_raw(r)\nrand_ui23_raw(r::MersenneTwister) = rand_ui52_raw(r)\nrand_ui10_raw(r::AbstractRNG) = rand(r, UInt16)\nrand_ui23_raw(r::AbstractRNG) = rand(r, UInt32)\n\nrand(r::Union{RandomDevice,MersenneTwister}, ::Type{Float16}) =\n Float16(reinterpret(Float32, (rand_ui10_raw(r) % UInt32 << 13) & 0x007fe000 | 0x3f800000) - 1)\n\nrand(r::Union{RandomDevice,MersenneTwister}, ::Type{Float32}) =\n reinterpret(Float32, rand_ui23_raw(r) % UInt32 & 0x007fffff | 0x3f800000) - 1\n\n\n## random integers\n\n@inline rand_ui52_raw(r::AbstractRNG) = reinterpret(UInt64, rand(r, Close1Open2))\n@inline rand_ui52(r::AbstractRNG) = rand_ui52_raw(r) & 0x000fffffffffffff\n\n# MersenneTwister\n\n@inline rand{T<:Union{Bool, Int8, UInt8, Int16, UInt16, Int32, UInt32}}(r::MersenneTwister, ::Type{T}) = rand_ui52_raw(r) % T\n\nfunction rand(r::MersenneTwister, ::Type{UInt64})\n reserve(r, 2)\n rand_ui52_raw_inbounds(r) << 32 ⊻ rand_ui52_raw_inbounds(r)\nend\n\nfunction rand(r::MersenneTwister, ::Type{UInt128})\n reserve(r, 3)\n xor(rand_ui52_raw_inbounds(r) % UInt128 << 96,\n rand_ui52_raw_inbounds(r) % UInt128 << 48,\n rand_ui52_raw_inbounds(r))\nend\n\nrand(r::MersenneTwister, ::Type{Int64}) = reinterpret(Int64, rand(r, UInt64))\nrand(r::MersenneTwister, ::Type{Int128}) = reinterpret(Int128, rand(r, UInt128))\n\n## random Complex values\n\nrand{T<:Real}(r::AbstractRNG, ::Type{Complex{T}}) = complex(rand(r, T), rand(r, T))\n\n# random Char values\n# returns a random valid Unicode scalar value (i.e. 0 - 0xd7ff, 0xe000 - # 0x10ffff)\nfunction rand(r::AbstractRNG, ::Type{Char})\n c = rand(r, 0x00000000:0x0010f7ff)\n (c < 0xd800) ? Char(c) : Char(c+0x800)\nend\n\n# random values from Dict or Set (for efficiency)\nfunction rand(r::AbstractRNG, t::Dict)\n isempty(t) && throw(ArgumentError(\"dict must be non-empty\"))\n n = length(t.slots)\n while true\n i = rand(r, 1:n)\n Base.isslotfilled(t, i) && return (t.keys[i] => t.vals[i])\n end\nend\nrand(t::Dict) = rand(GLOBAL_RNG, t)\nrand(r::AbstractRNG, s::Set) = rand(r, s.dict).first\nrand(s::Set) = rand(GLOBAL_RNG, s)\n\n## Arrays of random numbers\n\nrand(r::AbstractRNG, dims::Dims) = rand(r, Float64, dims)\nrand(r::AbstractRNG, dims::Integer...) = rand(r, convert(Tuple{Vararg{Int}}, dims))\n\nrand(r::AbstractRNG, T::Type, dims::Dims) = rand!(r, Array{T}(dims))\nrand(r::AbstractRNG, T::Type, d1::Integer, dims::Integer...) = rand(r, T, tuple(Int(d1), convert(Tuple{Vararg{Int}}, dims)...))\n# note: the above method would trigger an ambiguity warning if d1 was not separated out:\n# rand(r, ()) would match both this method and rand(r, dims::Dims)\n# moreover, a call like rand(r, NotImplementedType()) would be an infinite loop\n\nfunction rand!{T}(r::AbstractRNG, A::AbstractArray{T})\n for i in eachindex(A)\n @inbounds A[i] = rand(r, T)\n end\n A\nend\n\n# MersenneTwister\n\nfunction rand_AbstractArray_Float64!{I<:FloatInterval}(r::MersenneTwister, A::AbstractArray{Float64}, n=length(A), ::Type{I}=CloseOpen)\n # what follows is equivalent to this simple loop but more efficient:\n # for i=1:n\n # @inbounds A[i] = rand(r, I)\n # end\n m = 0\n while m < n\n s = mt_avail(r)\n if s == 0\n gen_rand(r)\n s = mt_avail(r)\n end\n m2 = min(n, m+s)\n for i=m+1:m2\n @inbounds A[i] = rand_inbounds(r, I)\n end\n m = m2\n end\n A\nend\n\nrand!(r::MersenneTwister, A::AbstractArray{Float64}) = rand_AbstractArray_Float64!(r, A)\n\nfill_array!(s::DSFMT_state, A::Ptr{Float64}, n::Int, ::Type{CloseOpen}) = dsfmt_fill_array_close_open!(s, A, n)\nfill_array!(s::DSFMT_state, A::Ptr{Float64}, n::Int, ::Type{Close1Open2}) = dsfmt_fill_array_close1_open2!(s, A, n)\n\nfunction rand!{I<:FloatInterval}(r::MersenneTwister, A::Array{Float64}, n::Int=length(A), ::Type{I}=CloseOpen)\n # depending on the alignment of A, the data written by fill_array! may have\n # to be left-shifted by up to 15 bytes (cf. unsafe_copy! below) for\n # reproducibility purposes;\n # so, even for well aligned arrays, fill_array! is used to generate only\n # the n-2 first values (or n-3 if n is odd), and the remaining values are\n # generated by the scalar version of rand\n if n > length(A)\n throw(BoundsError(A,n))\n end\n n2 = (n-2) ÷ 2 * 2\n if n2 < dsfmt_get_min_array_size()\n rand_AbstractArray_Float64!(r, A, n, I)\n else\n pA = pointer(A)\n align = Csize_t(pA) % 16\n if align > 0\n pA2 = pA + 16 - align\n fill_array!(r.state, pA2, n2, I) # generate the data in-place, but shifted\n unsafe_copy!(pA, pA2, n2) # move the data to the beginning of the array\n else\n fill_array!(r.state, pA, n2, I)\n end\n for i=n2+1:n\n @inbounds A[i] = rand(r, I)\n end\n end\n A\nend\n\n@inline mask128(u::UInt128, ::Type{Float16}) = (u & 0x03ff03ff03ff03ff03ff03ff03ff03ff) | 0x3c003c003c003c003c003c003c003c00\n@inline mask128(u::UInt128, ::Type{Float32}) = (u & 0x007fffff007fffff007fffff007fffff) | 0x3f8000003f8000003f8000003f800000\n\nfunction rand!{T<:Union{Float16, Float32}}(r::MersenneTwister, A::Array{T}, ::Type{Close1Open2})\n n = length(A)\n n128 = n * sizeof(T) ÷ 16\n rand!(r, unsafe_wrap(Array, convert(Ptr{Float64}, pointer(A)), 2*n128), 2*n128, Close1Open2)\n A128 = unsafe_wrap(Array, convert(Ptr{UInt128}, pointer(A)), n128)\n @inbounds for i in 1:n128\n u = A128[i]\n u ⊻= u << 26\n # at this point, the 64 low bits of u, \"k\" being the k-th bit of A128[i] and \"+\" the bit xor, are:\n # [..., 58+32,..., 53+27, 52+26, ..., 33+7, 32+6, ..., 27+1, 26, ..., 1]\n # the bits needing to be random are\n # [1:10, 17:26, 33:42, 49:58] (for Float16)\n # [1:23, 33:55] (for Float32)\n # this is obviously satisfied on the 32 low bits side, and on the high side, the entropy comes\n # from bits 33:52 of A128[i] and then from bits 27:32 (which are discarded on the low side)\n # this is similar for the 64 high bits of u\n A128[i] = mask128(u, T)\n end\n for i in 16*n128÷sizeof(T)+1:n\n @inbounds A[i] = rand(r, T) + oneunit(T)\n end\n A\nend\n\nfunction rand!{T<:Union{Float16, Float32}}(r::MersenneTwister, A::Array{T}, ::Type{CloseOpen})\n rand!(r, A, Close1Open2)\n I32 = one(Float32)\n for i in eachindex(A)\n @inbounds A[i] = T(Float32(A[i])-I32) # faster than \"A[i] -= one(T)\" for T==Float16\n end\n A\nend\n\nrand!(r::MersenneTwister, A::Array{<:Union{Float16, Float32}}) = rand!(r, A, CloseOpen)\n\n\nfunction rand!(r::MersenneTwister, A::Array{UInt128}, n::Int=length(A))\n if n > length(A)\n throw(BoundsError(A,n))\n end\n Af = unsafe_wrap(Array, convert(Ptr{Float64}, pointer(A)), 2n)\n i = n\n while true\n rand!(r, Af, 2i, Close1Open2)\n n < 5 && break\n i = 0\n @inbounds while n-i >= 5\n u = A[i+=1]\n A[n] ⊻= u << 48\n A[n-=1] ⊻= u << 36\n A[n-=1] ⊻= u << 24\n A[n-=1] ⊻= u << 12\n n-=1\n end\n end\n if n > 0\n u = rand_ui2x52_raw(r)\n for i = 1:n\n @inbounds A[i] ⊻= u << 12*i\n end\n end\n A\nend\n\nfunction rand!{T<:Union{Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128}}(r::MersenneTwister, A::Array{T})\n n=length(A)\n n128 = n * sizeof(T) ÷ 16\n rand!(r, unsafe_wrap(Array, convert(Ptr{UInt128}, pointer(A)), n128))\n for i = 16*n128÷sizeof(T)+1:n\n @inbounds A[i] = rand(r, T)\n end\n A\nend\n\n## Generate random integer within a range\n\n# remainder function according to Knuth, where rem_knuth(a, 0) = a\nrem_knuth(a::UInt, b::UInt) = a % (b + (b == 0)) + a * (b == 0)\nrem_knuth(a::T, b::T) where {T<:Unsigned} = b != 0 ? a % b : a\n\n# maximum multiple of k <= 2^bits(T) decremented by one,\n# that is 0xFFFF...FFFF if k = typemax(T) - typemin(T) with intentional underflow\n# see http://stackoverflow.com/questions/29182036/integer-arithmetic-add-1-to-uint-max-and-divide-by-n-without-overflow\nmaxmultiple(k::T) where {T<:Unsigned} = (div(typemax(T) - k + oneunit(k), k + (k == 0))*k + k - oneunit(k))::T\n\n# maximum multiple of k within 1:2^32 or 1:2^64 decremented by one, depending on size\nmaxmultiplemix(k::UInt64) = if k >> 32 != 0; maxmultiple(k); else (div(0x0000000100000000, k + (k == 0))*k - oneunit(k))::UInt64; end\n\nabstract type RangeGenerator end\n\nstruct RangeGeneratorInt{T<:Integer,U<:Unsigned} <: RangeGenerator\n a::T # first element of the range\n k::U # range length or zero for full range\n u::U # rejection threshold\nend\n# generators with 32, 128 bits entropy\nRangeGeneratorInt(a::T, k::U) where {T,U<:Union{UInt32,UInt128}} = RangeGeneratorInt{T,U}(a, k, maxmultiple(k))\n# mixed 32/64 bits entropy generator\nRangeGeneratorInt(a::T, k::UInt64) where {T} = RangeGeneratorInt{T,UInt64}(a, k, maxmultiplemix(k))\n# generator for ranges\nfunction RangeGenerator(r::UnitRange{T}) where T<:Unsigned\n if isempty(r)\n throw(ArgumentError(\"range must be non-empty\"))\n end\n RangeGeneratorInt(first(r), last(r) - first(r) + oneunit(T))\nend\n\n# specialized versions\nfor (T, U) in [(UInt8, UInt32), (UInt16, UInt32),\n (Int8, UInt32), (Int16, UInt32), (Int32, UInt32), (Int64, UInt64), (Int128, UInt128),\n (Bool, UInt32)]\n\n @eval RangeGenerator(r::UnitRange{$T}) = begin\n if isempty(r)\n throw(ArgumentError(\"range must be non-empty\"))\n end\n RangeGeneratorInt(first(r), convert($U, unsigned(last(r) - first(r)) + one($U))) # overflow ok\n end\nend\n\nif GMP_VERSION.major >= 6\n struct RangeGeneratorBigInt <: RangeGenerator\n a::BigInt # first\n m::BigInt # range length - 1\n nlimbs::Int # number of limbs in generated BigInt's\n mask::Limb # applied to the highest limb\n end\n\nelse\n struct RangeGeneratorBigInt <: RangeGenerator\n a::BigInt # first\n m::BigInt # range length - 1\n limbs::Vector{Limb} # buffer to be copied into generated BigInt's\n mask::Limb # applied to the highest limb\n\n RangeGeneratorBigInt(a, m, nlimbs, mask) = new(a, m, Vector{Limb}(nlimbs), mask)\n end\nend\n\n\nfunction RangeGenerator(r::UnitRange{BigInt})\n m = last(r) - first(r)\n m < 0 && throw(ArgumentError(\"range must be non-empty\"))\n nd = ndigits(m, 2)\n nlimbs, highbits = divrem(nd, 8*sizeof(Limb))\n highbits > 0 && (nlimbs += 1)\n mask = highbits == 0 ? ~zero(Limb) : one(Limb)<> 32 == 0\n x = rand(rng, UInt32)\n while x > g.u\n x = rand(rng, UInt32)\n end\n else\n x = rand(rng, UInt64)\n while x > g.u\n x = rand(rng, UInt64)\n end\n end\n return reinterpret(T, reinterpret(UInt64, g.a) + rem_knuth(x, g.k))\nend\n\nfunction rand{T<:Integer, U<:Unsigned}(rng::AbstractRNG, g::RangeGeneratorInt{T,U})\n x = rand(rng, U)\n while x > g.u\n x = rand(rng, U)\n end\n (unsigned(g.a) + rem_knuth(x, g.k)) % T\nend\n\nif GMP_VERSION.major >= 6\n # mpz_limbs_write and mpz_limbs_finish are available only in GMP version 6\n function rand(rng::AbstractRNG, g::RangeGeneratorBigInt)\n x = BigInt()\n while true\n # note: on CRAY computers, the second argument may be of type Cint (48 bits) and not Clong\n xd = ccall((:__gmpz_limbs_write, :libgmp), Ptr{Limb}, (Ptr{BigInt}, Clong), &x, g.nlimbs)\n limbs = unsafe_wrap(Array, xd, g.nlimbs)\n rand!(rng, limbs)\n limbs[end] &= g.mask\n ccall((:__gmpz_limbs_finish, :libgmp), Void, (Ptr{BigInt}, Clong), &x, g.nlimbs)\n x <= g.m && break\n end\n ccall((:__gmpz_add, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &x, &x, &g.a)\n return x\n end\nelse\n function rand(rng::AbstractRNG, g::RangeGeneratorBigInt)\n x = BigInt()\n while true\n rand!(rng, g.limbs)\n g.limbs[end] &= g.mask\n ccall((:__gmpz_import, :libgmp), Void,\n (Ptr{BigInt}, Csize_t, Cint, Csize_t, Cint, Csize_t, Ptr{Limb}),\n &x, length(g.limbs), -1, sizeof(Limb), 0, 0, g.limbs)\n x <= g.m && break\n end\n ccall((:__gmpz_add, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &x, &x, &g.a)\n return x\n end\nend\n\nrand(rng::AbstractRNG, r::UnitRange{<:Union{Signed,Unsigned,BigInt,Bool}}) = rand(rng, RangeGenerator(r))\n\n\n# Randomly draw a sample from an AbstractArray r\n# (e.g. r is a range 0:2:8 or a vector [2, 3, 5, 7])\nrand(rng::AbstractRNG, r::AbstractArray) = @inbounds return r[rand(rng, 1:length(r))]\n\nfunction rand!(rng::AbstractRNG, A::AbstractArray, g::RangeGenerator)\n for i in eachindex(A)\n @inbounds A[i] = rand(rng, g)\n end\n return A\nend\n\nrand!(rng::AbstractRNG, A::AbstractArray, r::UnitRange{<:Union{Signed,Unsigned,BigInt,Bool,Char}}) = rand!(rng, A, RangeGenerator(r))\n\nfunction rand!(rng::AbstractRNG, A::AbstractArray, r::AbstractArray)\n g = RangeGenerator(1:(length(r)))\n for i in eachindex(A)\n @inbounds A[i] = r[rand(rng, g)]\n end\n return A\nend\n\nrand{T}(rng::AbstractRNG, r::AbstractArray{T}, dims::Dims) = rand!(rng, Array{T}(dims), r)\nrand(rng::AbstractRNG, r::AbstractArray, dims::Int...) = rand(rng, r, dims)\n\n## random BitArrays (AbstractRNG)\n\nfunction rand!(rng::AbstractRNG, B::BitArray)\n isempty(B) && return B\n Bc = B.chunks\n rand!(rng, Bc)\n Bc[end] &= Base._msk_end(B)\n return B\nend\n\n\"\"\"\n bitrand([rng=GLOBAL_RNG], [dims...])\n\nGenerate a `BitArray` of random boolean values.\n\"\"\"\nbitrand(r::AbstractRNG, dims::Dims) = rand!(r, BitArray(dims))\nbitrand(r::AbstractRNG, dims::Int...) = rand!(r, BitArray(dims))\n\nbitrand(dims::Dims) = rand!(BitArray(dims))\nbitrand(dims::Int...) = rand!(BitArray(dims))\n\n## randn() - Normally distributed random numbers using Ziggurat algorithm\n\n# The Ziggurat Method for generating random variables - Marsaglia and Tsang\n# Paper and reference code: http://www.jstatsoft.org/v05/i08/\n\n# randmtzig (covers also exponential variates)\n## Tables for normal variates\nconst ki =\n UInt64[0x0007799ec012f7b2,0x0000000000000000,0x0006045f4c7de363,0x0006d1aa7d5ec0a5,\n 0x000728fb3f60f777,0x0007592af4e9fbc0,0x000777a5c0bf655d,0x00078ca3857d2256,\n 0x00079bf6b0ffe58b,0x0007a7a34ab092ad,0x0007b0d2f20dd1cb,0x0007b83d3aa9cb52,\n 0x0007be597614224d,0x0007c3788631abe9,0x0007c7d32bc192ee,0x0007cb9263a6e86d,\n 0x0007ced483edfa84,0x0007d1b07ac0fd39,0x0007d437ef2da5fc,0x0007d678b069aa6e,\n 0x0007d87db38c5c87,0x0007da4fc6a9ba62,0x0007dbf611b37f3b,0x0007dd7674d0f286,\n 0x0007ded5ce8205f6,0x0007e018307fb62b,0x0007e141081bd124,0x0007e2533d712de8,\n 0x0007e3514bbd7718,0x0007e43d54944b52,0x0007e5192f25ef42,0x0007e5e67481118d,\n 0x0007e6a6897c1ce2,0x0007e75aa6c7f64c,0x0007e803df8ee498,0x0007e8a326eb6272,\n 0x0007e93954717a28,0x0007e9c727f8648f,0x0007ea4d4cc85a3c,0x0007eacc5c4907a9,\n 0x0007eb44e0474cf6,0x0007ebb754e47419,0x0007ec242a3d8474,0x0007ec8bc5d69645,\n 0x0007ecee83d3d6e9,0x0007ed4cb8082f45,0x0007eda6aee0170f,0x0007edfcae2dfe68,\n 0x0007ee4ef5dccd3e,0x0007ee9dc08c394e,0x0007eee9441a17c7,0x0007ef31b21b4fb1,\n 0x0007ef773846a8a7,0x0007efba00d35a17,0x0007effa32ccf69f,0x0007f037f25e1278,\n 0x0007f0736112d12c,0x0007f0ac9e145c25,0x0007f0e3c65e1fcc,0x0007f118f4ed8e54,\n 0x0007f14c42ed0dc8,0x0007f17dc7daa0c3,0x0007f1ad99aac6a5,0x0007f1dbcce80015,\n 0x0007f20874cf56bf,0x0007f233a36a3b9a,0x0007f25d69a604ad,0x0007f285d7694a92,\n 0x0007f2acfba75e3b,0x0007f2d2e4720909,0x0007f2f79f09c344,0x0007f31b37ec883b,\n 0x0007f33dbae36abc,0x0007f35f330f08d5,0x0007f37faaf2fa79,0x0007f39f2c805380,\n 0x0007f3bdc11f4f1c,0x0007f3db71b83850,0x0007f3f846bba121,0x0007f4144829f846,\n 0x0007f42f7d9a8b9d,0x0007f449ee420432,0x0007f463a0f8675e,0x0007f47c9c3ea77b,\n 0x0007f494e643cd8e,0x0007f4ac84e9c475,0x0007f4c37dc9cd50,0x0007f4d9d638a432,\n 0x0007f4ef934a5b6a,0x0007f504b9d5f33d,0x0007f5194e78b352,0x0007f52d55994a96,\n 0x0007f540d36aba0c,0x0007f553cbef0e77,0x0007f56642f9ec8f,0x0007f5783c32f31e,\n 0x0007f589bb17f609,0x0007f59ac2ff1525,0x0007f5ab5718b15a,0x0007f5bb7a71427c,\n 0x0007f5cb2ff31009,0x0007f5da7a67cebe,0x0007f5e95c7a24e7,0x0007f5f7d8b7171e,\n 0x0007f605f18f5ef4,0x0007f613a958ad0a,0x0007f621024ed7e9,0x0007f62dfe94f8cb,\n 0x0007f63aa036777a,0x0007f646e928065a,0x0007f652db488f88,0x0007f65e786213ff,\n 0x0007f669c22a7d8a,0x0007f674ba446459,0x0007f67f623fc8db,0x0007f689bb9ac294,\n 0x0007f693c7c22481,0x0007f69d881217a6,0x0007f6a6fdd6ac36,0x0007f6b02a4c61ee,\n 0x0007f6b90ea0a7f4,0x0007f6c1abf254c0,0x0007f6ca03521664,0x0007f6d215c2db82,\n 0x0007f6d9e43a3559,0x0007f6e16fa0b329,0x0007f6e8b8d23729,0x0007f6efc09e4569,\n 0x0007f6f687c84cbf,0x0007f6fd0f07ea09,0x0007f703570925e2,0x0007f709606cad03,\n 0x0007f70f2bc8036f,0x0007f714b9a5b292,0x0007f71a0a85725d,0x0007f71f1edc4d9e,\n 0x0007f723f714c179,0x0007f728938ed843,0x0007f72cf4a03fa0,0x0007f7311a945a16,\n 0x0007f73505ac4bf8,0x0007f738b61f03bd,0x0007f73c2c193dc0,0x0007f73f67bd835c,\n 0x0007f74269242559,0x0007f745305b31a1,0x0007f747bd666428,0x0007f74a103f12ed,\n 0x0007f74c28d414f5,0x0007f74e0709a42d,0x0007f74faab939f9,0x0007f75113b16657,\n 0x0007f75241b5a155,0x0007f753347e16b8,0x0007f753ebb76b7c,0x0007f75467027d05,\n 0x0007f754a5f4199d,0x0007f754a814b207,0x0007f7546ce003ae,0x0007f753f3c4bb29,\n 0x0007f7533c240e92,0x0007f75245514f41,0x0007f7510e91726c,0x0007f74f971a9012,\n 0x0007f74dde135797,0x0007f74be2927971,0x0007f749a39e051c,0x0007f747202aba8a,\n 0x0007f744571b4e3c,0x0007f741473f9efe,0x0007f73def53dc43,0x0007f73a4dff9bff,\n 0x0007f73661d4deaf,0x0007f732294f003f,0x0007f72da2d19444,0x0007f728cca72bda,\n 0x0007f723a5000367,0x0007f71e29f09627,0x0007f7185970156b,0x0007f7123156c102,\n 0x0007f70baf5c1e2c,0x0007f704d1150a23,0x0007f6fd93f1a4e5,0x0007f6f5f53b10b6,\n 0x0007f6edf211023e,0x0007f6e587671ce9,0x0007f6dcb2021679,0x0007f6d36e749c64,\n 0x0007f6c9b91bf4c6,0x0007f6bf8e1c541b,0x0007f6b4e95ce015,0x0007f6a9c68356ff,\n 0x0007f69e20ef5211,0x0007f691f3b517eb,0x0007f6853997f321,0x0007f677ed03ff19,\n 0x0007f66a08075bdc,0x0007f65b844ab75a,0x0007f64c5b091860,0x0007f63c8506d4bc,\n 0x0007f62bfa8798fe,0x0007f61ab34364b0,0x0007f608a65a599a,0x0007f5f5ca4737e8,\n 0x0007f5e214d05b48,0x0007f5cd7af7066e,0x0007f5b7f0e4c2a1,0x0007f5a169d68fcf,\n 0x0007f589d80596a5,0x0007f5712c8d0174,0x0007f557574c912b,0x0007f53c46c77193,\n 0x0007f51fe7feb9f2,0x0007f5022646ecfb,0x0007f4e2eb17ab1d,0x0007f4c21dd4a3d1,\n 0x0007f49fa38ea394,0x0007f47b5ebb62eb,0x0007f4552ee27473,0x0007f42cf03d58f5,\n 0x0007f4027b48549f,0x0007f3d5a44119df,0x0007f3a63a8fb552,0x0007f37408155100,\n 0x0007f33ed05b55ec,0x0007f3064f9c183e,0x0007f2ca399c7ba1,0x0007f28a384bb940,\n 0x0007f245ea1b7a2b,0x0007f1fcdffe8f1b,0x0007f1ae9af758cd,0x0007f15a8917f27e,\n 0x0007f10001ccaaab,0x0007f09e413c418a,0x0007f034627733d7,0x0007efc15815b8d5,\n 0x0007ef43e2bf7f55,0x0007eeba84e31dfe,0x0007ee237294df89,0x0007ed7c7c170141,\n 0x0007ecc2f0d95d3a,0x0007ebf377a46782,0x0007eb09d6deb285,0x0007ea00a4f17808,\n 0x0007e8d0d3da63d6,0x0007e771023b0fcf,0x0007e5d46c2f08d8,0x0007e3e937669691,\n 0x0007e195978f1176,0x0007deb2c0e05c1c,0x0007db0362002a19,0x0007d6202c151439,\n 0x0007cf4b8f00a2cb,0x0007c4fd24520efd,0x0007b362fbf81816,0x00078d2d25998e24]\nconst wi =\n [1.7367254121602630e-15,9.5586603514556339e-17,1.2708704834810623e-16,\n 1.4909740962495474e-16,1.6658733631586268e-16,1.8136120810119029e-16,\n 1.9429720153135588e-16,2.0589500628482093e-16,2.1646860576895422e-16,\n 2.2622940392218116e-16,2.3532718914045892e-16,2.4387234557428771e-16,\n 2.5194879829274225e-16,2.5962199772528103e-16,2.6694407473648285e-16,\n 2.7395729685142446e-16,2.8069646002484804e-16,2.8719058904113930e-16,\n 2.9346417484728883e-16,2.9953809336782113e-16,3.0543030007192440e-16,\n 3.1115636338921572e-16,3.1672988018581815e-16,3.2216280350549905e-16,\n 3.2746570407939751e-16,3.3264798116841710e-16,3.3771803417353232e-16,\n 3.4268340353119356e-16,3.4755088731729758e-16,3.5232663846002031e-16,\n 3.5701624633953494e-16,3.6162480571598339e-16,3.6615697529653540e-16,\n 3.7061702777236077e-16,3.7500889278747798e-16,3.7933619401549554e-16,\n 3.8360228129677279e-16,3.8781025861250247e-16,3.9196300853257678e-16,\n 3.9606321366256378e-16,4.0011337552546690e-16,4.0411583124143332e-16,\n 4.0807276830960448e-16,4.1198623774807442e-16,4.1585816580828064e-16,\n 4.1969036444740733e-16,4.2348454071520708e-16,4.2724230518899761e-16,\n 4.3096517957162941e-16,4.3465460355128760e-16,4.3831194100854571e-16,\n 4.4193848564470665e-16,4.4553546609579137e-16,4.4910405058828750e-16,\n 4.5264535118571397e-16,4.5616042766900381e-16,4.5965029108849407e-16,\n 4.6311590702081647e-16,4.6655819856008752e-16,4.6997804906941950e-16,\n 4.7337630471583237e-16,4.7675377680908526e-16,4.8011124396270155e-16,\n 4.8344945409350080e-16,4.8676912627422087e-16,4.9007095245229938e-16,\n 4.9335559904654139e-16,4.9662370843221783e-16,4.9987590032409088e-16,\n 5.0311277306593187e-16,5.0633490483427195e-16,5.0954285476338923e-16,\n 5.1273716399787966e-16,5.1591835667857364e-16,5.1908694086703434e-16,\n 5.2224340941340417e-16,5.2538824077194543e-16,5.2852189976823820e-16,\n 5.3164483832166176e-16,5.3475749612647295e-16,5.3786030129452348e-16,\n 5.4095367096239933e-16,5.4403801186554671e-16,5.4711372088173611e-16,\n 5.5018118554603362e-16,5.5324078453927836e-16,5.5629288815190902e-16,\n 5.5933785872484621e-16,5.6237605106900435e-16,5.6540781286489604e-16,\n 5.6843348504368141e-16,5.7145340215092040e-16,5.7446789269419609e-16,\n 5.7747727947569648e-16,5.8048187991076857e-16,5.8348200633338921e-16,\n 5.8647796628943653e-16,5.8947006281858718e-16,5.9245859472561339e-16,\n 5.9544385684180598e-16,5.9842614027720281e-16,6.0140573266426640e-16,\n 6.0438291839361250e-16,6.0735797884236057e-16,6.1033119259564394e-16,\n 6.1330283566179110e-16,6.1627318168165963e-16,6.1924250213258470e-16,\n 6.2221106652737879e-16,6.2517914260879998e-16,6.2814699653988953e-16,\n 6.3111489309056042e-16,6.3408309582080600e-16,6.3705186726088149e-16,\n 6.4002146908880247e-16,6.4299216230548961e-16,6.4596420740788321e-16,\n 6.4893786456033965e-16,6.5191339376461587e-16,6.5489105502874154e-16,\n 6.5787110853507413e-16,6.6085381480782587e-16,6.6383943488035057e-16,\n 6.6682823046247459e-16,6.6982046410815579e-16,6.7281639938375311e-16,\n 6.7581630103719006e-16,6.7882043516829803e-16,6.8182906940062540e-16,\n 6.8484247305500383e-16,6.8786091732516637e-16,6.9088467545571690e-16,\n 6.9391402292275690e-16,6.9694923761748294e-16,6.9999060003307640e-16,\n 7.0303839345521508e-16,7.0609290415654822e-16,7.0915442159548734e-16,\n 7.1222323861967788e-16,7.1529965167453030e-16,7.1838396101720629e-16,\n 7.2147647093647067e-16,7.2457748997883870e-16,7.2768733118146927e-16,\n 7.3080631231227429e-16,7.3393475611774048e-16,7.3707299057898310e-16,\n 7.4022134917657997e-16,7.4338017116476479e-16,7.4654980185558890e-16,\n 7.4973059291369793e-16,7.5292290266240584e-16,7.5612709640179217e-16,\n 7.5934354673958895e-16,7.6257263393567558e-16,7.6581474626104873e-16,\n 7.6907028037219191e-16,7.7233964170182985e-16,7.7562324486711744e-16,\n 7.7892151409638524e-16,7.8223488367564108e-16,7.8556379841610841e-16,\n 7.8890871414417552e-16,7.9227009821522709e-16,7.9564843005293662e-16,\n 7.9904420171571300e-16,8.0245791849212591e-16,8.0589009952726568e-16,\n 8.0934127848215009e-16,8.1281200422845008e-16,8.1630284158098775e-16,\n 8.1981437207065329e-16,8.2334719476060504e-16,8.2690192710884700e-16,\n 8.3047920588053737e-16,8.3407968811366288e-16,8.3770405214202216e-16,\n 8.4135299867980282e-16,8.4502725197240968e-16,8.4872756101861549e-16,\n 8.5245470086955962e-16,8.5620947401062333e-16,8.5999271183276646e-16,\n 8.6380527620052589e-16,8.6764806112455816e-16,8.7152199454736980e-16,\n 8.7542804025171749e-16,8.7936719990210427e-16,8.8334051523084080e-16,\n 8.8734907038131345e-16,8.9139399442240861e-16,8.9547646404950677e-16,\n 8.9959770648910994e-16,9.0375900262601175e-16,9.0796169037400680e-16,\n 9.1220716831348461e-16,9.1649689962191353e-16,9.2083241632623076e-16,\n 9.2521532390956933e-16,9.2964730630864167e-16,9.3413013134252651e-16,\n 9.3866565661866598e-16,9.4325583596767065e-16,9.4790272646517382e-16,\n 9.5260849610662787e-16,9.5737543220974496e-16,9.6220595062948384e-16,\n 9.6710260588230542e-16,9.7206810229016259e-16,9.7710530627072088e-16,\n 9.8221725991905411e-16,9.8740719604806711e-16,9.9267855488079765e-16,\n 9.9803500261836449e-16,1.0034804521436181e-15,1.0090190861637457e-15,\n 1.0146553831467086e-15,1.0203941464683124e-15,1.0262405372613567e-15,\n 1.0322001115486456e-15,1.0382788623515399e-15,1.0444832676000471e-15,\n 1.0508203448355195e-15,1.0572977139009890e-15,1.0639236690676801e-15,\n 1.0707072623632994e-15,1.0776584002668106e-15,1.0847879564403425e-15,\n 1.0921079038149563e-15,1.0996314701785628e-15,1.1073733224935752e-15,\n 1.1153497865853155e-15,1.1235791107110833e-15,1.1320817840164846e-15,\n 1.1408809242582780e-15,1.1500027537839792e-15,1.1594771891449189e-15,\n 1.1693385786910960e-15,1.1796266352955801e-15,1.1903876299282890e-15,\n 1.2016759392543819e-15,1.2135560818666897e-15,1.2261054417450561e-15,\n 1.2394179789163251e-15,1.2536093926602567e-15,1.2688244814255010e-15,\n 1.2852479319096109e-15,1.3031206634689985e-15,1.3227655770195326e-15,\n 1.3446300925011171e-15,1.3693606835128518e-15,1.3979436672775240e-15,\n 1.4319989869661328e-15,1.4744848603597596e-15,1.5317872741611144e-15,\n 1.6227698675312968e-15]\nconst fi =\n [1.0000000000000000e+00,9.7710170126767082e-01,9.5987909180010600e-01,\n 9.4519895344229909e-01,9.3206007595922991e-01,9.1999150503934646e-01,\n 9.0872644005213032e-01,8.9809592189834297e-01,8.8798466075583282e-01,\n 8.7830965580891684e-01,8.6900868803685649e-01,8.6003362119633109e-01,\n 8.5134625845867751e-01,8.4291565311220373e-01,8.3471629298688299e-01,\n 8.2672683394622093e-01,8.1892919160370192e-01,8.1130787431265572e-01,\n 8.0384948317096383e-01,7.9654233042295841e-01,7.8937614356602404e-01,\n 7.8234183265480195e-01,7.7543130498118662e-01,7.6863731579848571e-01,\n 7.6195334683679483e-01,7.5537350650709567e-01,7.4889244721915638e-01,\n 7.4250529634015061e-01,7.3620759812686210e-01,7.2999526456147568e-01,\n 7.2386453346862967e-01,7.1781193263072152e-01,7.1183424887824798e-01,\n 7.0592850133275376e-01,7.0009191813651117e-01,6.9432191612611627e-01,\n 6.8861608300467136e-01,6.8297216164499430e-01,6.7738803621877308e-01,\n 6.7186171989708166e-01,6.6639134390874977e-01,6.6097514777666277e-01,\n 6.5561147057969693e-01,6.5029874311081637e-01,6.4503548082082196e-01,\n 6.3982027745305614e-01,6.3465179928762327e-01,6.2952877992483625e-01,\n 6.2445001554702606e-01,6.1941436060583399e-01,6.1442072388891344e-01,\n 6.0946806492577310e-01,6.0455539069746733e-01,5.9968175261912482e-01,\n 5.9484624376798689e-01,5.9004799633282545e-01,5.8528617926337090e-01,\n 5.8055999610079034e-01,5.7586868297235316e-01,5.7121150673525267e-01,\n 5.6658776325616389e-01,5.6199677581452390e-01,5.5743789361876550e-01,\n 5.5291049042583185e-01,5.4841396325526537e-01,5.4394773119002582e-01,\n 5.3951123425695158e-01,5.3510393238045717e-01,5.3072530440366150e-01,\n 5.2637484717168403e-01,5.2205207467232140e-01,5.1775651722975591e-01,\n 5.1348772074732651e-01,5.0924524599574761e-01,5.0502866794346790e-01,\n 5.0083757512614835e-01,4.9667156905248933e-01,4.9253026364386815e-01,\n 4.8841328470545758e-01,4.8432026942668288e-01,4.8025086590904642e-01,\n 4.7620473271950547e-01,4.7218153846772976e-01,4.6818096140569321e-01,\n 4.6420268904817391e-01,4.6024641781284248e-01,4.5631185267871610e-01,\n 4.5239870686184824e-01,4.4850670150720273e-01,4.4463556539573912e-01,\n 4.4078503466580377e-01,4.3695485254798533e-01,4.3314476911265209e-01,\n 4.2935454102944126e-01,4.2558393133802180e-01,4.2183270922949573e-01,\n 4.1810064983784795e-01,4.1438753404089090e-01,4.1069314827018799e-01,\n 4.0701728432947315e-01,4.0335973922111429e-01,3.9972031498019700e-01,\n 3.9609881851583223e-01,3.9249506145931540e-01,3.8890886001878855e-01,\n 3.8534003484007706e-01,3.8178841087339344e-01,3.7825381724561896e-01,\n 3.7473608713789086e-01,3.7123505766823922e-01,3.6775056977903225e-01,\n 3.6428246812900372e-01,3.6083060098964775e-01,3.5739482014578022e-01,\n 3.5397498080007656e-01,3.5057094148140588e-01,3.4718256395679348e-01,\n 3.4380971314685055e-01,3.4045225704452164e-01,3.3711006663700588e-01,\n 3.3378301583071823e-01,3.3047098137916342e-01,3.2717384281360129e-01,\n 3.2389148237639104e-01,3.2062378495690530e-01,3.1737063802991350e-01,\n 3.1413193159633707e-01,3.1090755812628634e-01,3.0769741250429189e-01,\n 3.0450139197664983e-01,3.0131939610080288e-01,2.9815132669668531e-01,\n 2.9499708779996164e-01,2.9185658561709499e-01,2.8872972848218270e-01,\n 2.8561642681550159e-01,2.8251659308370741e-01,2.7943014176163772e-01,\n 2.7635698929566810e-01,2.7329705406857691e-01,2.7025025636587519e-01,\n 2.6721651834356114e-01,2.6419576399726080e-01,2.6118791913272082e-01,\n 2.5819291133761890e-01,2.5521066995466168e-01,2.5224112605594190e-01,\n 2.4928421241852824e-01,2.4633986350126363e-01,2.4340801542275012e-01,\n 2.4048860594050039e-01,2.3758157443123795e-01,2.3468686187232990e-01,\n 2.3180441082433859e-01,2.2893416541468023e-01,2.2607607132238020e-01,\n 2.2323007576391746e-01,2.2039612748015194e-01,2.1757417672433113e-01,\n 2.1476417525117358e-01,2.1196607630703015e-01,2.0917983462112499e-01,\n 2.0640540639788071e-01,2.0364274931033485e-01,2.0089182249465656e-01,\n 1.9815258654577511e-01,1.9542500351413428e-01,1.9270903690358912e-01,\n 1.9000465167046496e-01,1.8731181422380025e-01,1.8463049242679927e-01,\n 1.8196065559952254e-01,1.7930227452284767e-01,1.7665532144373500e-01,\n 1.7401977008183875e-01,1.7139559563750595e-01,1.6878277480121151e-01,\n 1.6618128576448205e-01,1.6359110823236570e-01,1.6101222343751107e-01,\n 1.5844461415592431e-01,1.5588826472447920e-01,1.5334316106026283e-01,\n 1.5080929068184568e-01,1.4828664273257453e-01,1.4577520800599403e-01,\n 1.4327497897351341e-01,1.4078594981444470e-01,1.3830811644855071e-01,\n 1.3584147657125373e-01,1.3338602969166913e-01,1.3094177717364430e-01,\n 1.2850872227999952e-01,1.2608687022018586e-01,1.2367622820159654e-01,\n 1.2127680548479021e-01,1.1888861344290998e-01,1.1651166562561080e-01,\n 1.1414597782783835e-01,1.1179156816383801e-01,1.0944845714681163e-01,\n 1.0711666777468364e-01,1.0479622562248690e-01,1.0248715894193508e-01,\n 1.0018949876880981e-01,9.7903279038862284e-02,9.5628536713008819e-02,\n 9.3365311912690860e-02,9.1113648066373634e-02,8.8873592068275789e-02,\n 8.6645194450557961e-02,8.4428509570353374e-02,8.2223595813202863e-02,\n 8.0030515814663056e-02,7.7849336702096039e-02,7.5680130358927067e-02,\n 7.3522973713981268e-02,7.1377949058890375e-02,6.9245144397006769e-02,\n 6.7124653827788497e-02,6.5016577971242842e-02,6.2921024437758113e-02,\n 6.0838108349539864e-02,5.8767952920933758e-02,5.6710690106202902e-02,\n 5.4666461324888914e-02,5.2635418276792176e-02,5.0617723860947761e-02,\n 4.8613553215868521e-02,4.6623094901930368e-02,4.4646552251294443e-02,\n 4.2684144916474431e-02,4.0736110655940933e-02,3.8802707404526113e-02,\n 3.6884215688567284e-02,3.4980941461716084e-02,3.3093219458578522e-02,\n 3.1221417191920245e-02,2.9365939758133314e-02,2.7527235669603082e-02,\n 2.5705804008548896e-02,2.3902203305795882e-02,2.2117062707308864e-02,\n 2.0351096230044517e-02,1.8605121275724643e-02,1.6880083152543166e-02,\n 1.5177088307935325e-02,1.3497450601739880e-02,1.1842757857907888e-02,\n 1.0214971439701471e-02,8.6165827693987316e-03,7.0508754713732268e-03,\n 5.5224032992509968e-03,4.0379725933630305e-03,2.6090727461021627e-03,\n 1.2602859304985975e-03]\n\n## Tables for exponential variates\nconst ke =\n UInt64[0x000e290a13924be3,0x0000000000000000,0x0009beadebce18bf,0x000c377ac71f9e08,\n 0x000d4ddb99075857,0x000de893fb8ca23e,0x000e4a8e87c4328d,0x000e8dff16ae1cb9,\n 0x000ebf2deab58c59,0x000ee49a6e8b9638,0x000f0204efd64ee4,0x000f19bdb8ea3c1b,\n 0x000f2d458bbe5bd1,0x000f3da104b78236,0x000f4b86d784571f,0x000f577ad8a7784f,\n 0x000f61de83da32ab,0x000f6afb7843cce7,0x000f730a57372b44,0x000f7a37651b0e68,\n 0x000f80a5bb6eea52,0x000f867189d3cb5b,0x000f8bb1b4f8fbbd,0x000f9079062292b8,\n 0x000f94d70ca8d43a,0x000f98d8c7dcaa99,0x000f9c8928abe083,0x000f9ff175b734a6,\n 0x000fa319996bc47d,0x000fa6085f8e9d07,0x000fa8c3a62e1991,0x000fab5084e1f660,\n 0x000fadb36c84cccb,0x000faff041086846,0x000fb20a6ea22bb9,0x000fb404fb42cb3c,\n 0x000fb5e295158173,0x000fb7a59e99727a,0x000fb95038c8789d,0x000fbae44ba684eb,\n 0x000fbc638d822e60,0x000fbdcf89209ffa,0x000fbf29a303cfc5,0x000fc0731df1089c,\n 0x000fc1ad1ed6c8b1,0x000fc2d8b02b5c89,0x000fc3f6c4d92131,0x000fc5083ac9ba7d,\n 0x000fc60ddd1e9cd6,0x000fc7086622e825,0x000fc7f881009f0b,0x000fc8decb41ac70,\n 0x000fc9bbd623d7ec,0x000fca9027c5b26d,0x000fcb5c3c319c49,0x000fcc20864b4449,\n 0x000fccdd70a35d40,0x000fcd935e34bf80,0x000fce42ab0db8bd,0x000fceebace7ec01,\n 0x000fcf8eb3b0d0e7,0x000fd02c0a049b60,0x000fd0c3f59d199c,0x000fd156b7b5e27e,\n 0x000fd1e48d670341,0x000fd26daff73551,0x000fd2f2552684be,0x000fd372af7233c1,\n 0x000fd3eeee528f62,0x000fd4673e73543a,0x000fd4dbc9e72ff7,0x000fd54cb856dc2c,\n 0x000fd5ba2f2c4119,0x000fd62451ba02c2,0x000fd68b415fcff4,0x000fd6ef1dabc160,\n 0x000fd75004790eb6,0x000fd7ae120c583f,0x000fd809612dbd09,0x000fd8620b40effa,\n 0x000fd8b8285b78fd,0x000fd90bcf594b1d,0x000fd95d15efd425,0x000fd9ac10bfa70c,\n 0x000fd9f8d364df06,0x000fda437086566b,0x000fda8bf9e3c9fe,0x000fdad28062fed5,\n 0x000fdb17141bff2c,0x000fdb59c4648085,0x000fdb9a9fda83cc,0x000fdbd9b46e3ed4,\n 0x000fdc170f6b5d04,0x000fdc52bd81a3fb,0x000fdc8ccacd07ba,0x000fdcc542dd3902,\n 0x000fdcfc30bcb793,0x000fdd319ef77143,0x000fdd6597a0f60b,0x000fdd98245a48a2,\n 0x000fddc94e575271,0x000fddf91e64014f,0x000fde279ce914ca,0x000fde54d1f0a06a,\n 0x000fde80c52a47cf,0x000fdeab7def394e,0x000fded50345eb35,0x000fdefd5be59fa0,\n 0x000fdf248e39b26f,0x000fdf4aa064b4af,0x000fdf6f98435894,0x000fdf937b6f30ba,\n 0x000fdfb64f414571,0x000fdfd818d48262,0x000fdff8dd07fed8,0x000fe018a08122c4,\n 0x000fe03767adaa59,0x000fe05536c58a13,0x000fe07211ccb4c5,0x000fe08dfc94c532,\n 0x000fe0a8fabe8ca1,0x000fe0c30fbb87a5,0x000fe0dc3ecf3a5a,0x000fe0f48b107521,\n 0x000fe10bf76a82ef,0x000fe122869e41ff,0x000fe1383b4327e1,0x000fe14d17c83187,\n 0x000fe1611e74c023,0x000fe1745169635a,0x000fe186b2a09176,0x000fe19843ef4e07,\n 0x000fe1a90705bf63,0x000fe1b8fd6fb37c,0x000fe1c828951443,0x000fe1d689ba4bfd,\n 0x000fe1e4220099a4,0x000fe1f0f26655a0,0x000fe1fcfbc726d4,0x000fe2083edc2830,\n 0x000fe212bc3bfeb4,0x000fe21c745adfe3,0x000fe225678a8895,0x000fe22d95fa23f4,\n 0x000fe234ffb62282,0x000fe23ba4a800d9,0x000fe2418495fddc,0x000fe2469f22bffb,\n 0x000fe24af3cce90d,0x000fe24e81ee9858,0x000fe25148bcda19,0x000fe253474703fe,\n 0x000fe2547c75fdc6,0x000fe254e70b754f,0x000fe25485a0fd1a,0x000fe25356a71450,\n 0x000fe2515864173a,0x000fe24e88f316f1,0x000fe24ae64296fa,0x000fe2466e132f60,\n 0x000fe2411df611bd,0x000fe23af34b6f73,0x000fe233eb40bf41,0x000fe22c02cee01b,\n 0x000fe22336b81710,0x000fe2198385e5cc,0x000fe20ee586b707,0x000fe20358cb5dfb,\n 0x000fe1f6d92465b1,0x000fe1e9621f2c9e,0x000fe1daef02c8da,0x000fe1cb7accb0a6,\n 0x000fe1bb002d22c9,0x000fe1a9798349b8,0x000fe196e0d9140c,0x000fe1832fdebc44,\n 0x000fe16e5fe5f931,0x000fe15869dccfcf,0x000fe1414647fe78,0x000fe128ed3cf8b2,\n 0x000fe10f565b69cf,0x000fe0f478c633ab,0x000fe0d84b1bdd9e,0x000fe0bac36e6688,\n 0x000fe09bd73a6b5b,0x000fe07b7b5d920a,0x000fe059a40c26d2,0x000fe03644c5d7f8,\n 0x000fe011504979b2,0x000fdfeab887b95c,0x000fdfc26e94a447,0x000fdf986297e305,\n 0x000fdf6c83bb8663,0x000fdf3ec0193eed,0x000fdf0f04a5d30a,0x000fdedd3d1aa204,\n 0x000fdea953dcfc13,0x000fde7331e3100d,0x000fde3abe9626f2,0x000fddffdfb1dbd5,\n 0x000fddc2791ff351,0x000fdd826cd068c6,0x000fdd3f9a8d3856,0x000fdcf9dfc95b0c,\n 0x000fdcb1176a55fe,0x000fdc65198ba50b,0x000fdc15bb3b2daa,0x000fdbc2ce2dc4ae,\n 0x000fdb6c206aaaca,0x000fdb117becb4a1,0x000fdab2a6379bf0,0x000fda4f5fdfb4e9,\n 0x000fd9e76401f3a3,0x000fd97a67a9ce1f,0x000fd90819221429,0x000fd8901f2d4b02,\n 0x000fd812182170e1,0x000fd78d98e23cd3,0x000fd7022bb3f082,0x000fd66f4edf96b9,\n 0x000fd5d473200305,0x000fd530f9ccff94,0x000fd48432b7b351,0x000fd3cd59a8469e,\n 0x000fd30b9368f90a,0x000fd23dea45f500,0x000fd16349e2e04a,0x000fd07a7a3ef98a,\n 0x000fcf8219b5df05,0x000fce7895bcfcde,0x000fcd5c220ad5e2,0x000fcc2aadbc17dc,\n 0x000fcae1d5e81fbc,0x000fc97ed4e778f9,0x000fc7fe6d4d720e,0x000fc65ccf39c2fc,\n 0x000fc4957623cb03,0x000fc2a2fc826dc7,0x000fc07ee19b01cd,0x000fbe213c1cf493,\n 0x000fbb8051ac1566,0x000fb890078d120e,0x000fb5411a5b9a95,0x000fb18000547133,\n 0x000fad334827f1e2,0x000fa839276708b9,0x000fa263b32e37ed,0x000f9b72d1c52cd1,\n 0x000f930a1a281a05,0x000f889f023d820a,0x000f7b577d2be5f3,0x000f69c650c40a8f,\n 0x000f51530f0916d8,0x000f2cb0e3c5933e,0x000eeefb15d605d8,0x000e6da6ecf27460]\n\nconst we =\n [1.9311480126418366e-15,1.4178028487910829e-17,2.3278824993382448e-17,\n 3.0487830247064320e-17,3.6665697714474878e-17,4.2179302189289733e-17,\n 4.7222561556862764e-17,5.1911915446217879e-17,5.6323471083955047e-17,\n 6.0510082606427647e-17,6.4510165096727506e-17,6.8352646803700541e-17,\n 7.2059939574689050e-17,7.5649815537392981e-17,7.9136643961951065e-17,\n 8.2532235563518929e-17,8.5846436168850513e-17,8.9087554865647428e-17,\n 9.2262679629663719e-17,9.5377914505292719e-17,9.8438560874559257e-17,\n 1.0144925809006294e-16,1.0441409405585343e-16,1.0733669323436384e-16,\n 1.1022028745670189e-16,1.1306777346479334e-16,1.1588176009705533e-16,\n 1.1866460730417886e-16,1.2141845865694359e-16,1.2414526862326387e-16,\n 1.2684682560606153e-16,1.2952477151912284e-16,1.3218061851538810e-16,\n 1.3481576335745444e-16,1.3743149982367625e-16,1.4002902946807859e-16,\n 1.4260947099321287e-16,1.4517386844829297e-16,1.4772319842763584e-16,\n 1.5025837641447456e-16,1.5278026239101652e-16,1.5528966581595696e-16,\n 1.5778735005459581e-16,1.6027403633350909e-16,1.6275040728083524e-16,\n 1.6521711010420076e-16,1.6767475945078279e-16,1.7012393998770646e-16,\n 1.7256520873568226e-16,1.7499909718432365e-16,1.7742611321380505e-16,\n 1.7984674284430714e-16,1.8226145183195818e-16,1.8467068712763576e-16,\n 1.8707487821298258e-16,1.8947443832625899e-16,1.9186976558915995e-16,\n 1.9426124404443042e-16,1.9664924461299023e-16,1.9903412597830144e-16,\n 2.0141623540485899e-16,2.0379590949693882e-16,2.0617347490308439e-16,\n 2.0854924897123771e-16,2.1092354035891528e-16,2.1329664960238294e-16,\n 2.1566886964838970e-16,2.1804048635167009e-16,2.2041177894111562e-16,\n 2.2278302045723950e-16,2.2515447816331350e-16,2.2752641393233694e-16,\n 2.2989908461180186e-16,2.3227274236804366e-16,2.3464763501180916e-16,\n 2.3702400630653389e-16,2.3940209626069303e-16,2.4178214140547710e-16,\n 2.4416437505894123e-16,2.4654902757768304e-16,2.4893632659702250e-16,\n 2.5132649726057970e-16,2.5371976244007951e-16,2.5611634294614988e-16,\n 2.5851645773082391e-16,2.6092032408240577e-16,2.6332815781331452e-16,\n 2.6574017344147618e-16,2.6815658436579989e-16,2.7057760303623509e-16,\n 2.7300344111887955e-16,2.7543430965657619e-16,2.7787041922541278e-16,\n 2.8031198008751431e-16,2.8275920234049704e-16,2.8521229606393309e-16,\n 2.8767147146315804e-16,2.9013693901073754e-16,2.9260890958589514e-16,\n 2.9508759461219033e-16,2.9757320619372521e-16,3.0006595725014739e-16,\n 3.0256606165070789e-16,3.0507373434762511e-16,3.0758919150899939e-16,\n 3.1011265065151543e-16,3.1264433077316750e-16,3.1518445248623523e-16,\n 3.1773323815073683e-16,3.2029091200858335e-16,3.2285770031865573e-16,\n 3.2543383149302610e-16,3.2801953623454359e-16,3.3061504767600738e-16,\n 3.3322060152114841e-16,3.3583643618764577e-16,3.3846279295240445e-16,\n 3.4109991609932597e-16,3.4374805306980633e-16,3.4640745461620167e-16,\n 3.4907837495850680e-16,3.5176107194449828e-16,3.5445580721360130e-16,\n 3.5716284636474652e-16,3.5988245912849274e-16,3.6261491954370031e-16,\n 3.6536050613905045e-16,3.6811950211971757e-16,3.7089219555951389e-16,\n 3.7367887959883854e-16,3.7647985264877841e-16,3.7929541860172334e-16,\n 3.8212588704887531e-16,3.8497157350504876e-16,3.8783279964117988e-16,\n 3.9070989352498183e-16,3.9360318987020748e-16,3.9651303029500381e-16,\n 3.9943976358986842e-16,4.0238374599574693e-16,4.0534534149283966e-16,\n 4.0832492210071775e-16,4.1132286819038357e-16,4.1433956880894741e-16,\n 4.1737542201763194e-16,4.2043083524385856e-16,4.2350622564821518e-16,\n 4.2660202050715582e-16,4.2971865761233266e-16,4.3285658568752094e-16,\n 4.3601626482415681e-16,4.3919816693657415e-16,4.4240277623809919e-16,\n 4.4563058973923611e-16,4.4888211776926172e-16,4.5215788452263475e-16,\n 4.5545842863172421e-16,4.5878430376746227e-16,4.6213607926964266e-16,\n 4.6551434080870692e-16,4.6891969108099157e-16,4.7235275053955480e-16,\n 4.7581415816285534e-16,4.7930457226372470e-16,4.8282467134125866e-16,\n 4.8637515497845119e-16,4.8995674478861404e-16,4.9357018541385775e-16,\n 4.9721624557917034e-16,5.0089571920591141e-16,5.0460942658884340e-16,\n 5.0835821564116245e-16,5.1214296321235415e-16,5.1596457648410618e-16,\n 5.1982399444994938e-16,5.2372218948478484e-16,5.2766016901098856e-16,\n 5.3163897726836902e-16,5.3565969719590503e-16,5.3972345243389779e-16,\n 5.4383140945596370e-16,5.4798477984116296e-16,5.5218482269752343e-16,\n 5.5643284724928722e-16,5.6073021560139669e-16,5.6507834569605064e-16,\n 5.6947871447763482e-16,5.7393286128396354e-16,5.7844239148359912e-16,\n 5.8300898038105864e-16,5.8763437741400573e-16,5.9232041066909314e-16,\n 5.9706899174600906e-16,6.0188212100252363e-16,6.0676189321700068e-16,\n 6.1171050370897217e-16,6.1673025496306200e-16,6.2182356380685327e-16,\n 6.2699296919933262e-16,6.3224114069342115e-16,6.3757088764394262e-16,\n 6.4298516924135947e-16,6.4848710546189033e-16,6.5407998903644809e-16,\n 6.5976729855445663e-16,6.6555271283433428e-16,6.7144012671064882e-16,\n 6.7743366840910103e-16,6.8353771870512740e-16,6.8975693209068478e-16,\n 6.9609626020748846e-16,7.0256097784459588e-16,7.0915671184495837e-16,\n 7.1588947332085531e-16,7.2276569364381212e-16,7.2979226475290851e-16,\n 7.3697658441912426e-16,7.4432660721604146e-16,7.5185090208325131e-16,\n 7.5955871753377488e-16,7.6746005575784274e-16,7.7556575712157906e-16,\n 7.8388759686228577e-16,7.9243839615735500e-16,8.0123215021130834e-16,\n 8.1028417659131464e-16,8.1961128778061250e-16,8.2923199285818092e-16,\n 8.3916673441467979e-16,8.4943816836487701e-16,8.6007149633349414e-16,\n 8.7109486293879040e-16,8.8253983380721398e-16,8.9444197485198646e-16,\n 9.0684155971316690e-16,9.1978444098118649e-16,9.3332313294229516e-16,\n 9.4751817065249841e-16,9.6243983456584759e-16,9.7817036547844198e-16,\n 9.9480684723838795e-16,1.0124650144288319e-15,1.0312843657756166e-15,\n 1.0514351604044550e-15,1.0731281954224043e-15,1.0966288068517408e-15,\n 1.1222774909350319e-15,1.1505212963006663e-15,1.1819635283304206e-15,\n 1.2174462832361815e-15,1.2581958069755114e-15,1.3060984107128082e-15,\n 1.3642786158057857e-15,1.4384889932178723e-15,1.5412190700064194e-15,\n 1.7091034077168055e-15]\nconst fe =\n [1.0000000000000000e+00,9.3814368086217470e-01,9.0046992992574648e-01,\n 8.7170433238120359e-01,8.4778550062398961e-01,8.2699329664305032e-01,\n 8.0842165152300838e-01,7.9152763697249562e-01,7.7595685204011555e-01,\n 7.6146338884989628e-01,7.4786862198519510e-01,7.3503809243142348e-01,\n 7.2286765959357202e-01,7.1127476080507601e-01,7.0019265508278816e-01,\n 6.8956649611707799e-01,6.7935057226476536e-01,6.6950631673192473e-01,\n 6.6000084107899970e-01,6.5080583341457110e-01,6.4189671642726609e-01,\n 6.3325199421436607e-01,6.2485273870366598e-01,6.1668218091520766e-01,\n 6.0872538207962201e-01,6.0096896636523223e-01,5.9340090169173343e-01,\n 5.8601031847726803e-01,5.7878735860284503e-01,5.7172304866482582e-01,\n 5.6480919291240017e-01,5.5803828226258745e-01,5.5140341654064129e-01,\n 5.4489823767243961e-01,5.3851687200286191e-01,5.3225388026304332e-01,\n 5.2610421398361973e-01,5.2006317736823360e-01,5.1412639381474856e-01,\n 5.0828977641064288e-01,5.0254950184134772e-01,4.9690198724154955e-01,\n 4.9134386959403253e-01,4.8587198734188491e-01,4.8048336393045421e-01,\n 4.7517519303737737e-01,4.6994482528395998e-01,4.6478975625042618e-01,\n 4.5970761564213769e-01,4.5469615747461550e-01,4.4975325116275500e-01,\n 4.4487687341454851e-01,4.4006510084235390e-01,4.3531610321563657e-01,\n 4.3062813728845883e-01,4.2599954114303434e-01,4.2142872899761658e-01,\n 4.1691418643300288e-01,4.1245446599716118e-01,4.0804818315203240e-01,\n 4.0369401253053028e-01,3.9939068447523107e-01,3.9513698183329016e-01,\n 3.9093173698479711e-01,3.8677382908413765e-01,3.8266218149600983e-01,\n 3.7859575940958079e-01,3.7457356761590216e-01,3.7059464843514600e-01,\n 3.6665807978151416e-01,3.6276297335481777e-01,3.5890847294874978e-01,\n 3.5509375286678746e-01,3.5131801643748334e-01,3.4758049462163698e-01,\n 3.4388044470450241e-01,3.4021714906678002e-01,3.3658991402867761e-01,\n 3.3299806876180899e-01,3.2944096426413633e-01,3.2591797239355619e-01,\n 3.2242848495608917e-01,3.1897191284495724e-01,3.1554768522712895e-01,\n 3.1215524877417955e-01,3.0879406693456019e-01,3.0546361924459026e-01,\n 3.0216340067569353e-01,2.9889292101558179e-01,2.9565170428126120e-01,\n 2.9243928816189257e-01,2.8925522348967775e-01,2.8609907373707683e-01,\n 2.8297041453878075e-01,2.7986883323697292e-01,2.7679392844851736e-01,\n 2.7374530965280297e-01,2.7072259679906002e-01,2.6772541993204479e-01,\n 2.6475341883506220e-01,2.6180624268936298e-01,2.5888354974901623e-01,\n 2.5598500703041538e-01,2.5311029001562946e-01,2.5025908236886230e-01,\n 2.4743107566532763e-01,2.4462596913189211e-01,2.4184346939887721e-01,\n 2.3908329026244918e-01,2.3634515245705964e-01,2.3362878343743335e-01,\n 2.3093391716962741e-01,2.2826029393071670e-01,2.2560766011668407e-01,\n 2.2297576805812019e-01,2.2036437584335949e-01,2.1777324714870053e-01,\n 2.1520215107537868e-01,2.1265086199297828e-01,2.1011915938898826e-01,\n 2.0760682772422204e-01,2.0511365629383771e-01,2.0263943909370902e-01,\n 2.0018397469191127e-01,1.9774706610509887e-01,1.9532852067956322e-01,\n 1.9292814997677135e-01,1.9054576966319539e-01,1.8818119940425432e-01,\n 1.8583426276219711e-01,1.8350478709776746e-01,1.8119260347549629e-01,\n 1.7889754657247831e-01,1.7661945459049488e-01,1.7435816917135349e-01,\n 1.7211353531532006e-01,1.6988540130252766e-01,1.6767361861725019e-01,\n 1.6547804187493600e-01,1.6329852875190182e-01,1.6113493991759203e-01,\n 1.5898713896931421e-01,1.5685499236936523e-01,1.5473836938446808e-01,\n 1.5263714202744286e-01,1.5055118500103989e-01,1.4848037564386679e-01,\n 1.4642459387834494e-01,1.4438372216063478e-01,1.4235764543247220e-01,\n 1.4034625107486245e-01,1.3834942886358020e-01,1.3636707092642886e-01,\n 1.3439907170221363e-01,1.3244532790138752e-01,1.3050573846833077e-01,\n 1.2858020454522817e-01,1.2666862943751067e-01,1.2477091858083096e-01,\n 1.2288697950954514e-01,1.2101672182667483e-01,1.1916005717532768e-01,\n 1.1731689921155557e-01,1.1548716357863353e-01,1.1367076788274431e-01,\n 1.1186763167005630e-01,1.1007767640518538e-01,1.0830082545103380e-01,\n 1.0653700405000166e-01,1.0478613930657017e-01,1.0304816017125772e-01,\n 1.0132299742595363e-01,9.9610583670637132e-02,9.7910853311492199e-02,\n 9.6223742550432798e-02,9.4549189376055859e-02,9.2887133556043541e-02,\n 9.1237516631040155e-02,8.9600281910032858e-02,8.7975374467270218e-02,\n 8.6362741140756913e-02,8.4762330532368119e-02,8.3174093009632383e-02,\n 8.1597980709237419e-02,8.0033947542319905e-02,7.8481949201606421e-02,\n 7.6941943170480503e-02,7.5413888734058410e-02,7.3897746992364746e-02,\n 7.2393480875708738e-02,7.0901055162371829e-02,6.9420436498728755e-02,\n 6.7951593421936601e-02,6.6494496385339774e-02,6.5049117786753749e-02,\n 6.3615431999807334e-02,6.2193415408540995e-02,6.0783046445479633e-02,\n 5.9384305633420266e-02,5.7997175631200659e-02,5.6621641283742877e-02,\n 5.5257689676697037e-02,5.3905310196046087e-02,5.2564494593071692e-02,\n 5.1235237055126281e-02,4.9917534282706372e-02,4.8611385573379497e-02,\n 4.7316792913181548e-02,4.6033761076175170e-02,4.4762297732943282e-02,\n 4.3502413568888183e-02,4.2254122413316234e-02,4.1017441380414819e-02,\n 3.9792391023374125e-02,3.8578995503074857e-02,3.7377282772959361e-02,\n 3.6187284781931423e-02,3.5009037697397410e-02,3.3842582150874330e-02,\n 3.2687963508959535e-02,3.1545232172893609e-02,3.0414443910466604e-02,\n 2.9295660224637393e-02,2.8188948763978636e-02,2.7094383780955800e-02,\n 2.6012046645134217e-02,2.4942026419731783e-02,2.3884420511558171e-02,\n 2.2839335406385240e-02,2.1806887504283581e-02,2.0787204072578117e-02,\n 1.9780424338009743e-02,1.8786700744696030e-02,1.7806200410911362e-02,\n 1.6839106826039948e-02,1.5885621839973163e-02,1.4945968011691148e-02,\n 1.4020391403181938e-02,1.3109164931254991e-02,1.2212592426255381e-02,\n 1.1331013597834597e-02,1.0464810181029979e-02,9.6144136425022099e-03,\n 8.7803149858089753e-03,7.9630774380170400e-03,7.1633531836349839e-03,\n 6.3819059373191791e-03,5.6196422072054830e-03,4.8776559835423923e-03,\n 4.1572951208337953e-03,3.4602647778369040e-03,2.7887987935740761e-03,\n 2.1459677437189063e-03,1.5362997803015724e-03,9.6726928232717454e-04,\n 4.5413435384149677e-04]\n\n\nconst ziggurat_nor_r = 3.6541528853610087963519472518\nconst ziggurat_nor_inv_r = inv(ziggurat_nor_r)\nconst ziggurat_exp_r = 7.6971174701310497140446280481\n\n\"\"\"\n randn([rng=GLOBAL_RNG], [T=Float64], [dims...])\n\nGenerate a normally-distributed random number of type `T` with mean 0 and standard deviation 1.\nOptionally generate an array of normally-distributed random numbers.\nThe `Base` module currently provides an implementation for the types\n`Float16`, `Float32`, and `Float64` (the default).\n\"\"\"\n@inline function randn(rng::AbstractRNG=GLOBAL_RNG)\n @inbounds begin\n r = rand_ui52(rng)\n rabs = Int64(r>>1) # One bit for the sign\n idx = rabs & 0xFF\n x = ifelse(r % Bool, -rabs, rabs)*wi[idx+1]\n rabs < ki[idx+1] && return x # 99.3% of the time we return here 1st try\n return randn_unlikely(rng, idx, rabs, x)\n end\nend\n\n# this unlikely branch is put in a separate function for better efficiency\nfunction randn_unlikely(rng, idx, rabs, x)\n @inbounds if idx == 0\n while true\n xx = -ziggurat_nor_inv_r*log(rand(rng))\n yy = -log(rand(rng))\n yy+yy > xx*xx && return (rabs >> 8) % Bool ? -ziggurat_nor_r-xx : ziggurat_nor_r+xx\n end\n elseif (fi[idx] - fi[idx+1])*rand(rng) + fi[idx+1] < exp(-0.5*x*x)\n return x # return from the triangular area\n else\n return randn(rng)\n end\nend\n\n\"\"\"\n randexp([rng=GLOBAL_RNG], [T=Float64], [dims...])\n\nGenerate a random number of type `T` according to the exponential distribution with scale 1.\nOptionally generate an array of such random numbers.\nThe `Base` module currently provides an implementation for the types\n`Float16`, `Float32`, and `Float64` (the default).\n\"\"\"\n@inline function randexp(rng::AbstractRNG=GLOBAL_RNG)\n @inbounds begin\n ri = rand_ui52(rng)\n idx = ri & 0xFF\n x = ri*we[idx+1]\n ri < ke[idx+1] && return x # 98.9% of the time we return here 1st try\n return randexp_unlikely(rng, idx, x)\n end\nend\n\nfunction randexp_unlikely(rng, idx, x)\n @inbounds if idx == 0\n return ziggurat_exp_r - log(rand(rng))\n elseif (fe[idx] - fe[idx+1])*rand(rng) + fe[idx+1] < exp(-x)\n return x # return from the triangular area\n else\n return randexp(rng)\n end\nend\n\n\"\"\"\n randn!([rng=GLOBAL_RNG], A::AbstractArray) -> A\n\nFill the array `A` with normally-distributed (mean 0, standard deviation 1) random numbers.\nAlso see the [`rand`](@ref) function.\n\"\"\"\nfunction randn! end\n\n\"\"\"\n randexp!([rng=GLOBAL_RNG], A::AbstractArray) -> A\n\nFill the array `A` with random numbers following the exponential distribution (with scale 1).\n\"\"\"\nfunction randexp! end\n\nlet Floats = Union{Float16,Float32,Float64}\n for randfun in [:randn, :randexp]\n randfun! = Symbol(randfun, :!)\n @eval begin\n # scalars\n $randfun(rng::AbstractRNG, ::Type{T}) where {T<:$Floats} = convert(T, $randfun(rng))\n $randfun(::Type{T}) where {T} = $randfun(GLOBAL_RNG, T)\n\n # filling arrays\n function $randfun!(rng::AbstractRNG, A::AbstractArray{T}) where T\n for i in eachindex(A)\n @inbounds A[i] = $randfun(rng, T)\n end\n A\n end\n\n $randfun!(A::AbstractArray) = $randfun!(GLOBAL_RNG, A)\n\n # generating arrays\n $randfun(rng::AbstractRNG, ::Type{T}, dims::Dims ) where {T} = $randfun!(rng, Array{T}(dims))\n # Note that this method explicitly does not define $randfun(rng, T), in order to prevent an infinite recursion.\n $randfun(rng::AbstractRNG, ::Type{T}, dim1::Integer, dims::Integer...) where {T} = $randfun!(rng, Array{T}(dim1, dims...))\n $randfun( ::Type{T}, dims::Dims ) where {T} = $randfun(GLOBAL_RNG, T, dims)\n $randfun( ::Type{T}, dims::Integer... ) where {T} = $randfun(GLOBAL_RNG, T, dims...)\n $randfun(rng::AbstractRNG, dims::Dims ) = $randfun(rng, Float64, dims)\n $randfun(rng::AbstractRNG, dims::Integer... ) = $randfun(rng, Float64, dims...)\n $randfun( dims::Dims ) = $randfun(GLOBAL_RNG, Float64, dims)\n $randfun( dims::Integer... ) = $randfun(GLOBAL_RNG, Float64, dims...)\n end\n end\nend\n\n## random UUID generation\n\nstruct UUID\n value::UInt128\n\n UUID(u::UInt128) = new(u)\nend\n\n\"\"\"\n uuid1([rng::AbstractRNG=GLOBAL_RNG]) -> UUID\n\nGenerates a version 1 (time-based) universally unique identifier (UUID), as specified\nby RFC 4122. Note that the Node ID is randomly generated (does not identify the host)\naccording to section 4.5 of the RFC.\n\"\"\"\nfunction uuid1(rng::AbstractRNG=GLOBAL_RNG)\n u = rand(rng, UInt128)\n\n # mask off clock sequence and node\n u &= 0x00000000000000003fffffffffffffff\n\n # set the unicast/multicast bit and version\n u |= 0x00000000000010000000010000000000\n\n # 0x01b21dd213814000 is the number of 100 nanosecond intervals\n # between the UUID epoch and Unix epoch\n timestamp = round(UInt64, time() * 1e7) + 0x01b21dd213814000\n ts_low = timestamp & typemax(UInt32)\n ts_mid = (timestamp >> 32) & typemax(UInt16)\n ts_hi = (timestamp >> 48) & 0x0fff\n\n u |= UInt128(ts_low) << 96\n u |= UInt128(ts_mid) << 80\n u |= UInt128(ts_hi) << 64\n\n UUID(u)\nend\n\n\"\"\"\n uuid4([rng::AbstractRNG=GLOBAL_RNG]) -> UUID\n\nGenerates a version 4 (random or pseudo-random) universally unique identifier (UUID),\nas specified by RFC 4122.\n\"\"\"\nfunction uuid4(rng::AbstractRNG=GLOBAL_RNG)\n u = rand(rng, UInt128)\n u &= 0xffffffffffff0fff3fffffffffffffff\n u |= 0x00000000000040008000000000000000\n UUID(u)\nend\n\n\"\"\"\n uuid_version(u::UUID) -> Integer\n\nInspects the given UUID and returns its version (see RFC 4122).\n\"\"\"\nfunction uuid_version(u::UUID)\n Int((u.value >> 76) & 0xf)\nend\n\nBase.convert(::Type{UInt128}, u::UUID) = u.value\n\nfunction Base.convert(::Type{UUID}, s::AbstractString)\n s = lowercase(s)\n\n if !ismatch(r\"^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$\", s)\n throw(ArgumentError(\"Malformed UUID string\"))\n end\n\n u = UInt128(0)\n for i in [1:8; 10:13; 15:18; 20:23; 25:36]\n u <<= 4\n d = s[i]-'0'\n u |= 0xf & (d-39*(d>9))\n end\n return UUID(u)\nend\n\nfunction Base.repr(u::UUID)\n u = u.value\n a = Vector{UInt8}(36)\n for i = [36:-1:25; 23:-1:20; 18:-1:15; 13:-1:10; 8:-1:1]\n d = u & 0xf\n a[i] = '0'+d+39*(d>9)\n u >>= 4\n end\n a[[24,19,14,9]] = '-'\n\n return String(a)\nend\n\nBase.show(io::IO, u::UUID) = write(io, Base.repr(u))\n\n# return a random string (often useful for temporary filenames/dirnames)\nlet b = UInt8['0':'9';'A':'Z';'a':'z']\n global randstring\n randstring(r::AbstractRNG, n::Int) = String(b[rand(r, 1:length(b), n)])\n randstring(r::AbstractRNG) = randstring(r,8)\n randstring(n::Int) = randstring(GLOBAL_RNG, n)\n randstring() = randstring(GLOBAL_RNG)\nend\n\n\n# Fill S (resized as needed) with a random subsequence of A, where\n# each element of A is included in S with independent probability p.\n# (Note that this is different from the problem of finding a random\n# size-m subset of A where m is fixed!)\nfunction randsubseq!(r::AbstractRNG, S::AbstractArray, A::AbstractArray, p::Real)\n 0 <= p <= 1 || throw(ArgumentError(\"probability $p not in [0,1]\"))\n n = length(A)\n p == 1 && return copy!(resize!(S, n), A)\n empty!(S)\n p == 0 && return S\n nexpected = p * length(A)\n sizehint!(S, round(Int,nexpected + 5*sqrt(nexpected)))\n if p > 0.15 # empirical threshold for trivial O(n) algorithm to be better\n for i = 1:n\n rand(r) <= p && push!(S, A[i])\n end\n else\n # Skip through A, in order, from each element i to the next element i+s\n # included in S. The probability that the next included element is\n # s==k (k > 0) is (1-p)^(k-1) * p, and hence the probability (CDF) that\n # s is in {1,...,k} is 1-(1-p)^k = F(k). Thus, we can draw the skip s\n # from this probability distribution via the discrete inverse-transform\n # method: s = ceil(F^{-1}(u)) where u = rand(), which is simply\n # s = ceil(log(rand()) / log1p(-p)).\n # -log(rand()) is an exponential variate, so can use randexp().\n L = -1 / log1p(-p) # L > 0\n i = 0\n while true\n s = randexp(r) * L\n s >= n - i && return S # compare before ceil to avoid overflow\n push!(S, A[i += ceil(Int,s)])\n end\n # [This algorithm is similar in spirit to, but much simpler than,\n # the one by Vitter for a related problem in \"Faster methods for\n # random sampling,\" Comm. ACM Magazine 7, 703-718 (1984).]\n end\n return S\nend\nrandsubseq!(S::AbstractArray, A::AbstractArray, p::Real) = randsubseq!(GLOBAL_RNG, S, A, p)\n\nrandsubseq(r::AbstractRNG, A::AbstractArray{T}, p::Real) where {T} = randsubseq!(r, T[], A, p)\n\n\"\"\"\n randsubseq(A, p) -> Vector\n\nReturn a vector consisting of a random subsequence of the given array `A`, where each\nelement of `A` is included (in order) with independent probability `p`. (Complexity is\nlinear in `p*length(A)`, so this function is efficient even if `p` is small and `A` is\nlarge.) Technically, this process is known as \"Bernoulli sampling\" of `A`.\n\"\"\"\nrandsubseq(A::AbstractArray, p::Real) = randsubseq(GLOBAL_RNG, A, p)\n\n\"Return a random `Int` (masked with `mask`) in ``[0, n)``, when `n <= 2^52`.\"\n@inline function rand_lt(r::AbstractRNG, n::Int, mask::Int=nextpow2(n)-1)\n # this duplicates the functionality of RangeGenerator objects,\n # to optimize this special case\n while true\n x = (rand_ui52_raw(r) % Int) & mask\n x < n && return x\n end\nend\n\n\"\"\"\n shuffle!([rng=GLOBAL_RNG,] v)\n\nIn-place version of [`shuffle`](@ref): randomly permute the array `v` in-place,\noptionally supplying the random-number generator `rng`.\n\"\"\"\nfunction shuffle!(r::AbstractRNG, a::AbstractVector)\n n = length(a)\n @assert n <= Int64(2)^52\n mask = nextpow2(n) - 1\n for i = n:-1:2\n (mask >> 1) == i && (mask >>= 1)\n j = 1 + rand_lt(r, i, mask)\n a[i], a[j] = a[j], a[i]\n end\n return a\nend\n\nshuffle!(a::AbstractVector) = shuffle!(GLOBAL_RNG, a)\n\n\"\"\"\n shuffle([rng=GLOBAL_RNG,] v)\n\nReturn a randomly permuted copy of `v`. The optional `rng` argument specifies a random\nnumber generator (see [Random Numbers](@ref)).\nTo permute `v` in-place, see [`shuffle!`](@ref). To obtain randomly permuted\nindices, see [`randperm`](@ref).\n\"\"\"\nshuffle(r::AbstractRNG, a::AbstractVector) = shuffle!(r, copymutable(a))\nshuffle(a::AbstractVector) = shuffle(GLOBAL_RNG, a)\n\n\"\"\"\n randperm([rng=GLOBAL_RNG,] n::Integer)\n\nConstruct a random permutation of length `n`. The optional `rng` argument specifies a random\nnumber generator (see [Random Numbers](@ref)).\nTo randomly permute a arbitrary vector, see [`shuffle`](@ref)\nor [`shuffle!`](@ref).\n\"\"\"\nfunction randperm(r::AbstractRNG, n::Integer)\n a = Vector{typeof(n)}(n)\n @assert n <= Int64(2)^52\n if n == 0\n return a\n end\n a[1] = 1\n mask = 3\n @inbounds for i = 2:Int(n)\n j = 1 + rand_lt(r, i, mask)\n if i != j # a[i] is uninitialized (and could be #undef)\n a[i] = a[j]\n end\n a[j] = i\n i == 1+mask && (mask = 2mask + 1)\n end\n return a\nend\nrandperm(n::Integer) = randperm(GLOBAL_RNG, n)\n\n\"\"\"\n randcycle([rng=GLOBAL_RNG,] n::Integer)\n\nConstruct a random cyclic permutation of length `n`. The optional `rng`\nargument specifies a random number generator, see [Random Numbers](@ref).\n\"\"\"\nfunction randcycle(r::AbstractRNG, n::Integer)\n a = Vector{typeof(n)}(n)\n n == 0 && return a\n @assert n <= Int64(2)^52\n a[1] = 1\n mask = 3\n @inbounds for i = 2:Int(n)\n j = 1 + rand_lt(r, i-1, mask)\n a[i] = a[j]\n a[j] = i\n i == 1+mask && (mask = 2mask + 1)\n end\n return a\nend\nrandcycle(n::Integer) = randcycle(GLOBAL_RNG, n)\n\nend # module\n", "meta": {"hexsha": "d1c99e953c8be829500c50a7bb76fe25469c89a8", "size": 73657, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "base/random.jl", "max_stars_repo_name": "odow/julia", "max_stars_repo_head_hexsha": "d394a934a5d66a933b47996e5b8b4cd572b16dc8", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "base/random.jl", "max_issues_repo_name": "odow/julia", "max_issues_repo_head_hexsha": "d394a934a5d66a933b47996e5b8b4cd572b16dc8", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base/random.jl", "max_forks_repo_name": "odow/julia", "max_forks_repo_head_hexsha": "d394a934a5d66a933b47996e5b8b4cd572b16dc8", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.4900064475, "max_line_length": 135, "alphanum_fraction": 0.7218594295, "num_tokens": 30759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24498004492533795}} {"text": "\nusing JuLIP: JVec\nconst BAI = BAInvariants\nimport Base: ==\nusing LinearAlgebra: dot, norm\nusing JuLIP: decode_dict\n\n# -------------- IO -------------------\n\n\nBondAngleDesc(transform::String, cutoff::Union{String, Tuple}) =\n BondAngleDesc(AnalyticTransform(transform), fcut_analyse(cutoff))\n\nDict(D::BondAngleDesc) = Dict( \"__id__\" => \"BondAngleDesc\",\n \"transform\" => Dict(D.transform),\n \"cutoff\" => Dict(D.cutoff) )\n\nBondAngleDesc(D::Dict) = BondAngleDesc( decode_dict(D[\"transform\"]),\n decode_dict(D[\"cutoff\"]) )\n\n==(D1::BondAngleDesc, D2::BondAngleDesc) =\n ( (D1.transform == D2.transform) && (D1.cutoff == D2.cutoff) )\n\nBase.convert(::Val{:BondAngleDesc}, D::Dict) = BondAngleDesc(D)\n\n# ------------- Interface Code ---------------\n\ntdegrees(::BondAngleDesc, vN::Val{N}) where {N} = BAI.tdegrees(vN)\n\n@inline ricoords(D::BondAngleDesc, Rs, J) = lengths_and_angles(Rs, J)\n\n@inline gradri2gradR!(desc::BondAngleDesc, dVsite, dV_drθ, Rs, J, rθ) =\n _grad_rθ2pos!(dVsite, dV_drθ, Rs, J, rθ...)\n\n# the cut-off for the bond-angle descriptor depends only on r but not on θ\n@inline fcut(D::BondAngleDesc, rθ) = fcut(D.cutoff, rθ[1])\n\n@inline function fcut_d(D::BondAngleDesc, rθ)\n fc, fc_d = fcut_d(D.cutoff, rθ[1])\n return fc, vcat(fc_d, zero(typeof(rθ[2])))\nend\n\n@inline skip_simplex(D::BondAngleDesc, rθ) = (maximum(rθ[1]) > cutoff(D.cutoff))\n\n@inline _rθ2x(D::BondAngleDesc, r, θ) = vcat(transform.(Ref(D), r), θ)\n@inline _rθ2x_d(D::BondAngleDesc, r, θ::SVector{K}) where {K} =\n vcat(transform_d.(Ref(D), r), @SVector ones(K))\n\n@inline invariants(D::BondAngleDesc, rθ::Tuple) =\n BAI.invariants(_rθ2x(D, rθ...))\n\n@inline invariants(D::BondAngleDesc, rθ::SVector{1}) =\n BAI.invariants(_rθ2x(D, rθ[1], (@SVector Float64[])))\n\n@inline invariants(D::BondAngleDesc, rθ::SVector{3}) =\n BAI.invariants(_rθ2x(D, SVector(rθ[1], rθ[2]), SVector(rθ[3])))\n\n@inline invariants(D::BondAngleDesc, rθ::SVector{6}) =\n BAI.invariants( _rθ2x(D, SVector(rθ[1], rθ[2], rθ[3]),\n SVector(rθ[4], rθ[5], rθ[6])) )\n\n@inline function invariants_ed(D::BondAngleDesc, rθ)\n x = _rθ2x(D, rθ...)\n I1, I2, DI1, DI2 = BAI.invariants_ed(x)\n x_d = _rθ2x_d(D, rθ...)\n return I1, I2, _sdot(x_d, DI1), _sdot(x_d, DI2)\nend\n\n\n# -------------- Kernel Functions --------------\n\n\"\"\"\n`_bondangles(Rs::AbstractVector)`\n\nTake collection `Rs::AbstractVector{JVec}` representing a simplex\nand convert into an ordered vector of bondlengths and bondangle\n```\n[ r1, r2, r3], [θ12, θ13, θ23 ]\n[ r1, r2, r3, r4], [θ12, θ13, θ14, θ23, θ24, θ34 ]\n```\n\"\"\"\n@generated function lengths_and_angles(Rs::AbstractVector{JVec{T}}, J::SVector{K}) where {T,K}\n # note K = N-1; eltype(Rs) == JVec{T}\n code = Expr[]\n idx = 0\n # bond lengths\n str_r = \"r = @SVector T[ \"\n for n = 1:K\n str_r *= \"norm(Rs[J[$n]]), \"\n end\n push_str!(code, str_r * \"]\")\n # bond angles\n str_θ = \"θ = @SVector T[ \"\n for n = 1:K-1, m = (n+1):K\n idx += 1\n str_θ *= \"dot(Rs[J[$n]], Rs[J[$m]]) / (r[$n] * r[$m]), \"\n end\n push_str!(code, str_θ * \"]\")\n # -----\n quote\n $(Expr(:meta, :inline))\n @inbounds $(Expr(:block, code...))\n return r, θ\n end\nend\n\n\"\"\"\nconvert ∇V (where ∇ is the gradient w.r.t. bond-lengths and bond-angle) into\nforces, i.e., into ∇Vsite (where ∇ is the gradient w.r.t. positions)\n\"\"\"\n@generated function _grad_rθ2pos!(dVsite, dV_drθ, Rs, J::SVector{K, Int}, r, θ) where {K}\n # K is the number of neighbours, i.e. N = K+1 counting also the center atom\n # ------\n code = Expr[]\n idx = 0\n # the first K entries of dV, are the derivatives w.r.t. |Ri|\n for k = 1:K\n idx += 1 # idx == k of course\n push!(code, :( dVsite[J[$k]] += (dV_drθ[$idx]/r[$k]) * Rs[J[$k]] ))\n end\n # the remaining ones are dot(R̂_i,R̂_j) = dot(R_i,R_j)/(r_i r_j)\n for n = 1:K-1, m = (n+1):K\n idx += 1\n push!(code, :( theta = dot(Rs[J[$n]], Rs[J[$m]]) / (r[$n]*r[$m]) ) )\n push!(code, :( dVsite[J[$n]] += (dV_drθ[$idx]/r[$n]) *\n (Rs[J[$m]]/r[$m] - theta * Rs[J[$n]]/r[$n]) ))\n push!(code, :( dVsite[J[$m]] += (dV_drθ[$idx]/r[$m]) *\n (Rs[J[$n]]/r[$n] - theta * Rs[J[$m]]/r[$m]) ))\n end\n quote\n $(Expr(:meta, :inline))\n @inbounds $(Expr(:block, code...))\n return dVsite\n end\nend\n", "meta": {"hexsha": "896238c824e07b9a618ef8d474c075acba865312", "size": 4446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/badescriptor.jl", "max_stars_repo_name": "cortner/ManyBodyIPs", "max_stars_repo_head_hexsha": "937fcf1dcdeb9db793023550fe922e44ecdd4c49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-30T01:35:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-30T01:35:01.000Z", "max_issues_repo_path": "src/badescriptor.jl", "max_issues_repo_name": "cortner/ManyBodyIPs", "max_issues_repo_head_hexsha": "937fcf1dcdeb9db793023550fe922e44ecdd4c49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-05-08T18:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-02T21:48:45.000Z", "max_forks_repo_path": "src/badescriptor.jl", "max_forks_repo_name": "cortner/ManyBodyIPs", "max_forks_repo_head_hexsha": "937fcf1dcdeb9db793023550fe922e44ecdd4c49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-20T21:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-20T21:06:40.000Z", "avg_line_length": 32.6911764706, "max_line_length": 94, "alphanum_fraction": 0.5650022492, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24498004492533793}} {"text": "# infdecomp.jl\nmodule InfDecomp\n\nusing InfDecomp_Base\nusing ExpCone\nusing GradDesc\n\nusing MathProgBase\n\nfeatures_list = [:Grad,:Jac,:JacVec,:Hess]::Vector{Symbol} # not doing :HessVec right now\n\n# ---------------------------------------------\n# M a t h P r o g B a s e I n t e r f a c e\n# ---------------------------------------------\n\nimport MathProgBase.initialize\nimport MathProgBase.features_available\nimport MathProgBase.eval_f\nimport MathProgBase.eval_g\nimport MathProgBase.eval_grad_f\nimport MathProgBase.jac_structure\nimport MathProgBase.hesslag_structure\nimport MathProgBase.eval_jac_g\nimport MathProgBase.eval_jac_prod\nimport MathProgBase.eval_jac_prod_t\nimport MathProgBase.eval_hesslag_prod\nimport MathProgBase.eval_hesslag\nimport MathProgBase.isobjlinear\nimport MathProgBase.isobjquadratic\nimport MathProgBase.isconstrlinear\n# import MathProgBase.obj_expr\n# import MathProgBase.constr_expr\nimport MathProgBase.getreducedcosts\nimport MathProgBase.getconstrduals\nimport MathProgBase.getsolution\nimport MathProgBase.status\nimport MathProgBase.getsolvetime\n\n# ------------\n# B a s i c s\n# ------------\n\n# initialize()\nfunction initialize(e::My_Eval, requested_features::Vector{Symbol})\n println(\"here!\")\n for feat in requested_features\n if feat ∉ features_list\n error(\"infdecomp.jl: initialize():\\n- JuliaOpt:MathProgBase is asking for a feature ($feat) that I don't have.- Maybe use another solver?\")\n end\n end\nend\n\n\n# features_available()\nfeatures_available(::My_Eval) = features_list\n\n# Properties:\nisobjlinear(::My_Eval) = false\nisobjquadratic(::My_Eval) = false\nisconstrlinear(::My_Eval, ::Integer) = true\n\n#global count_hesseval = 0\n# ------------------------------------------\n# E v a l u a t i o n : 0 t h o r d e r\n# ------------------------------------------\nfunction eval_f{TFloat_2,TFloat}(e::My_Eval, x::Vector{TFloat_2},dummy::TFloat=Float64(0)) :: TFloat\n local condent::Float64\n if e.TmpFloat==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n condent = condEntropy(e,x,BigFloat(0.))\n setprecision(BigFloat,prc)\n else\n condent = condEntropy(e,x,Float64(0))\n end\n e.count_eval_f += 1\n return -condent\n ;\nend #^ eval_f()\n\n# eval_g --- eval of constraint into g\nfunction eval_g(e::My_Eval, g::Vector{Float64}, x::Vector{Float64}) :: Void\n g .= reshape( reshape(x,1,e.n)*e.Gt , e.m, ) .- e.rhs\n e.count_eval_g += 1\n return nothing\n ;\nend # eval_g()\n\n\n# ------------------------------------------\n# E v a l u a t i o n : 1 s t o r d e r\n# ------------------------------------------\n\n####################################################################################################\n# G L O B A L V A R I A B L E\nglobal__ill_sol = \"What?!???\"\nill_sol__copy_sol = \"Oh, no!!!\"\nfunction ill_sol__do_copy_sol(x) :: Void\n if global__ill_sol == nothing\n global global__ill_sol = x[:]\n elseif typeof(global__ill_sol)==typeof(x)\n global global__ill_sol .= x\n else\n @show \"FUCK!!!!!\"\n end\n return nothing\nend\nfunction ill_sol__dont_copy_sol(x) :: Void\n return nothing\nend\n\nfunction set_copy_sol_behaviour(doit::Bool)\n if doit\n global global__ill_sol = nothing\n global ill_sol__copy_sol = ill_sol__do_copy_sol\n else\n global global__ill_sol = nothing\n global ill_sol__copy_sol = ill_sol__dont_copy_sol\n end\n ;\nend\n####################################################################################################\n\n\n# eval_grad_f --- eval gradient of objective function\nfunction eval_grad_f(e::My_Eval, g::Vector{Float64}, x::Vector{Float64}) :: Void\n if e.TmpFloat==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n ∇f(e,g,x,BigFloat(0.))\n setprecision(BigFloat,prc)\n else\n ∇f(e,g,x,Float64(0))\n end\n e.count_eval_grad_f += 1\n\n # Crap:\n ill_sol__copy_sol(x)\n\n return nothing\n ;\nend # eval_grad_f()\n\n\n# Constraint Jacobian\n# jac_structure() --- zero-nonzero pattern of constraint Jacobian\njac_structure(e::My_Eval) :: Tuple{Vector{Int64},Vector{Int64}} = ( e.Gt_L , e.Gt_K )\n# Note: Gt is transposed, so K and L are swapped [K: rows of G^T; L: columns of G^T]\n\n# eval_jac_g() --- constraint Jacobian -> J\nfunction eval_jac_g(e::My_Eval, J::Vector{Float64}, x::Vector{Float64}) :: Void\n J .= e.Gt.nzval\n e.count_eval_jac_g += 1\n return nothing\n ;\nend # eval_jac_g()\n\n\n# eval_jac_prod() --- constraint_Jacobian * w -> y\nfunction eval_jac_prod(e::My_Eval, y::Vector{Float64}, x::Vector{Float64}, w::Vector{Float64}) :: Void\n y .= reshape( reshape(w,1,e.n)*e.Gt , e.m, )\n return nothing\n ;\nend # eval_jac_prod()\n\n\n# eval_jac_prod_t() --- constraint_Jacobian^T * w -> y\nfunction eval_jac_prod_t{T<:AbstractFloat}(e::My_Eval, y::Vector{T}, x::Vector{T}, w::Vector{T}) :: Void\n y .= e.Gt*w\n return nothing\nend\n\n\n# ------------------------------------------\n# E v a l u a t i o n : 2 n d o r d e r\n# ------------------------------------------\n\n# Lagrangian:\n# L(x, (σ,μ) ) = σ f(x) + μ' G(x)\n# Since G(.) is linear, it's Hessian is 0 anyway, so it won't bother us.\n\n# hesslag_structure() --- zero-nonzero pattern of Hessian [wrt x] of the Lagrangian\nfunction hesslag_structure(e::My_Eval) :: Tuple{Vector{Int64},Vector{Int64}}\n K = Vector{Int64}()\n L = Vector{Int64}()\n counter = 0\n for y = 1:e.n_y\n for z = 1:e.n_z\n # Start with the diagonal\n for x = 1:e.n_x\n i = e.varidx[x,y,z]\n if i>0\n counter += 1\n push!(K,i)\n push!(L,i)\n end\n end\n # Now off-diagonal.\n # H is treated as a symmetric matrix, but:\n # if both (k,l) & (l,k) are present, their values will be added!\n for x = 1:e.n_x\n for u = 1:(x-1)\n i_x = e.varidx[x,y,z]\n i_u = e.varidx[u,y,z]\n if i_x>0 && i_u>0\n counter += 1\n push!(K,i_x)\n push!(L,i_u)\n end\n end\n end\n end# for z\n end #^ for y\n return (K,L)\n ;\nend # hesslag_structure()\n\n\nfunction Hess{TFloat}(e::My_Eval, H::Vector{Float64}, p::Vector{Float64}, σ::Float64, dummy::TFloat) :: Void\n counter = 0\n for y = 1:e.n_y\n for z = 1:e.n_z\n # make marginal P(*yz)\n P_yz ::TFloat = TFloat(0.)\n for x = 1:e.n_x\n i = e.varidx[x,y,z]\n if i>0\n P_yz += p[i]\n end\n end\n\n # now: for all pairs x,u we have:\n # if x ≠ u: -1/P_yz;\n # if x == u: ( P_yz - P(xyz) )/( P_yz * P(xyz) )\n\n # Start with the diagonal\n for x = 1:e.n_x\n i = e.varidx[x,y,z]\n if i>0\n counter += 1\n P_xyz = p[i]\n H[counter] = Float64( (P_xyz == 0 ) ? 1.e50 : TFloat(σ)*( P_yz - P_xyz )/( P_yz * P_xyz ) )\n end\n end\n # Now off-diagonal.\n # H is treated as a symmetric matrix, but:\n # if both (k,l) & (l,k) are present, their values will be added!\n for x = 1:e.n_x\n for u = 1:(x-1)\n i_x = e.varidx[x,y,z]\n i_u = e.varidx[u,y,z]\n if i_x>0 && i_u>0\n counter += 1\n H[counter] = -TFloat(σ)/P_yz\n end\n end\n end\n end#for z\n end# for y\n return nothing\n ;\nend # eval_hesslag()\n\n\n\n# eval_hesslag() --- Hessian [wrt x] of the Lagrangian\nfunction eval_hesslag(e::My_Eval, H::Vector{Float64}, x::Vector{Float64}, σ::Float64, μ::Vector{Float64}) :: Void\n if e.TmpFloat==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n Hess(e,H,x,σ,BigFloat(0.))\n setprecision(BigFloat,prc)\n e.count_hesseval += 1\n else\n Hess(e,H,x,σ,Float64(0))\n e.count_hesseval += 1\n end\n return nothing\n ;\nend # eval_hesslag()\n\n\n# eval_hesslag() --- ( Hessian [wrt x] of the Lagrangian ) * v\n# function eval_hesslag_prod{T<:AbstractFloat}(e::My_Eval, h::Vector{T}, x::Vector{T}, v::Vector{T}, σ::T, μ::Vector{T}) :: Void\n# h .= σ .* Hf(x)*v\n# return nothing\n# end\n\n\n#------------------\n# M A R G I N A L S\n#------------------\n\nfunction marginal_X{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: Array{TFloat_2,1}\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n end\n marg_x::Array{TFloat_2,1} = zeros(TFloat_2,e.n_x)\n if TFloat_2==BigFloat\n setprecision(BigFloat,prc)\n end\n for x in 1:e.n_x\n for y in 1:e.n_y\n for z in 1:e.n_z\n i = e.varidx[x,y,z]\n if i>0\n marg_x[x] += p[i]\n end\n end\n end\n end\n return marg_x\n ;\nend#^ marginal_X\n\nfunction marginal_Y{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: Array{TFloat_2,1}\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n end\n marg_y::Array{TFloat_2,1} = zeros(TFloat_2,e.n_y)\n if TFloat_2==BigFloat\n setprecision(BigFloat,prc)\n end\n for y in 1:e.n_y\n for x in 1:e.n_x\n for z in 1:e.n_z\n i = e.varidx[x,y,z]\n if i>0\n marg_y[y] += p[i]\n end\n end\n end\n end\n return marg_y\n ;\nend#^ marginal_Y\n\nfunction marginal_Z{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: Array{TFloat_2,1}\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n end\n marg_z::Array{TFloat_2,1} = zeros(TFloat_2,e.n_z)\n if TFloat_2==BigFloat\n setprecision(BigFloat,prc)\n end\n for z in 1:e.n_z\n for x in 1:e.n_x\n for y in 1:e.n_y\n i = e.varidx[x,y,z]\n if i>0\n marg_z[z] += p[i]\n end\n end\n end\n end\n return marg_z\n ;\nend#^ marginal_Z\n\nfunction marginal_XY{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: Array{TFloat_2,2}\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n setprecision(BigFloat,prc)\n end\n marg_xy::Array{TFloat_2,2} = zeros(TFloat_2,e.n_x,e.n_y)\n if TFloat_2==BigFloat\n setprecision(BigFloat,prc)\n end\n for x in 1:e.n_x\n for y in 1:e.n_y\n for z in 1:e.n_z\n i = e.varidx[x,y,z]\n if i>0\n marg_xy[x,y] += p[i]\n end\n end\n end\n end\n return marg_xy\n ;\nend#^ marginals_XY\n\nfunction marginal_XZ{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: Array{TFloat_2,2}\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n end\n marg_xz::Array{TFloat_2,2} = zeros(TFloat_2,e.n_x,e.n_z)\n if TFloat_2==BigFloat\n setprecision(BigFloat,prc)\n end\n for x in 1:e.n_x\n for z in 1:e.n_z\n for y in 1:e.n_y\n i = e.varidx[x,y,z]\n if i>0\n marg_xz[x,z] += p[i]\n end\n end\n end\n end\n return marg_xz\n ;\nend#^ marginal_XZ\n\nfunction marginal_YZ{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: Array{TFloat_2,2}\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n end\n marg_yz::Array{TFloat_2,2} = zeros(TFloat_2,e.n_y,e.n_z)\n if TFloat_2==BigFloat\n setprecision(BigFloat,prc)\n end\n for y in 1:e.n_y\n for z in 1:e.n_z\n for x in 1:e.n_x\n i = e.varidx[x,y,z]\n if i>0\n marg_yz[y,z] += p[i]\n end\n end\n end\n end\n return marg_yz\n ;\nend#^ marginal_YZ\n\n\n#------------------------------------------\n# I N F O R M A T I O N - F U N C T I O N S\n#------------------------------------------\n\n# entropy_X --- Shannon entropy of X --- H(X)\n\nfunction entropy_X{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: TFloat_2\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n s::BigFloat = BigFloat(0.)\n setprecision(BigFloat,prc)\n else\n s = Float64(0)\n end\n marg_x = marginal_X(e, p, TFloat)\n for x in 1:e.n_x\n s += ( ( marg_[x] ≤ 0 ) ? TFloat(0.) : marg_x[x]*log(marg_x[x]) )\n end\n return s\n ;\nend#^ entropy_X\n\n\n# I_X_Y --- Mutual information of X & Y --- I(X;Y)\n\nfunction I_X_Y{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: TFloat_2\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n s::BigFloat = BigFloat(0.)\n setprecision(BigFloat,prc)\n else\n s = Float64(0)\n end\n marg_x = marginal_X(e, p, TFloat)\n marg_y = marginal_Y(e, p, TFloat)\n marg_xy = marginal_XY(e, p, TFloat)\n for x in 1:e.n_x\n for y in 1:e.n_y\n s += ( (marg_xy[x,y] ≤ 0 || marg_x[x] ≤ 0 || marg_y[y] ≤ 0) ? TFloat_2(0.) : marg_xy[x,y]*log( marg_xy[x,y] / (marg_y[y] * marg_x[x]) ) )\n end\n end# ^y\n return s/log(2)\n ;\nend#^ I_X_Y\n\n\n# I_X_Y__Z --- Mutual information of X & Y|Z --- I(X;Y|Z)\n\nfunction I_X_Y__Z{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: TFloat_2\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n s::BigFloat = BigFloat(0.)\n setprecision(BigFloat,prc)\n else\n s = Float64(0)\n end\n marg_z = marginal_Z(e, p, TFloat)\n marg_xz = marginal_XZ(e, p, TFloat)\n marg_yz = marginal_YZ(e, p, TFloat)\n for x in 1:e.n_x\n for y in 1:e.n_y\n for z in 1:e.n_z\n i = e.varidx[x,y,z]\n if i>0\n s += ( (marg_yz[y,z] ≤ 0 || marg_z[z] ≤ 0 || marg_xz[x,z] ≤ 0 || p[i] ≤ 0 ) ? TFloat_2(0.) : p[i]*log( (p[i] * marg_z[z]) / (marg_xz[x,z] * marg_yz[y,z]) ) )\n end\n end\n end\n end\n return s/log(2)\n ;\nend#^ I_X_Y__Z\n\n\n# I_X_Z__Y --- Mutual information of X & Z|Y --- I(X;Z|Y)\n\nfunction I_X_Z__Y{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: TFloat_2\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n s::BigFloat = BigFloat(0.)\n setprecision(BigFloat,prc)\n else\n s = Float64(0)\n end\n marg_y = marginal_Y(e, p, TFloat)\n marg_xy = marginal_XY(e, p, TFloat)\n marg_yz = marginal_YZ(e, p, TFloat)\n for x in 1:e.n_x\n for y in 1:e.n_y\n for z in 1:e.n_z\n i = e.varidx[x,y,z]\n if i>0\n s += ( (marg_yz[y,z] ≤ 0 || marg_y[y] ≤ 0 || marg_xy[x,y] ≤ 0 || p[i] ≤ 0 ) ? TFloat_2(0.) : p[i]*log( (p[i] * marg_y[y]) / (marg_xy[x,y] * marg_yz[y,z]) ) )\n end\n end\n end\n end\n return s/log(2)\nend#^ I_X_Y__Z\n\n\n# SI --- Shared Information of Y & Z --- SI(Y;Z)\n\nfunction SI{TFloat_2,TFloat}(e::My_Eval, p::Vector{TFloat_2}, dummy::TFloat) :: TFloat_2\n if TFloat_2==BigFloat\n prc = precision(BigFloat)\n setprecision(BigFloat,e.bigfloat_nbits)\n s::BigFloat = BigFloat(0.)\n setprecision(BigFloat,prc)\n else\n s = Float64(0)\n end\n return I_X_Y(e, p, TFloat) - I_X_Y__Z(e, p, TFloat)\n ;\nend#^ SI\n\n\n# ----------------\n# U S I N G I T\n# ----------------\n\nnumo_vars(e::My_Eval) :: Int64 = e.n\nnumo_constraints(e::My_Eval) :: Int64 = e.m\nconstraints_lowerbounds_vec(e::My_Eval) :: Vector{Float64} = zeros(Float64,e.m)\nconstraints_upperbounds_vec(e::My_Eval) :: Vector{Float64} = zeros(Float64,e.m)\nvars_lowerbounds_vec(e::My_Eval) :: Vector{Float64} = zeros(Float64,e.n)\nvars_upperbounds_vec(e::My_Eval) :: Vector{Float64} = [Inf for j=1:e.n]\n\n\nusing Base.Test\n\n\nfunction do_it{T1,T2,T3}(pdf::Dict{Tuple{T1,T2,T3},Float64}, solver, tmpFloat::DataType=BigFloat ; warmstart::Bool=false, model_type=:IPM)\n print(\"Starting optimization now (\",now(),\")!\\n\")\n\n # global count_hesseval = 0\n const sd,myeval = create_stuff(pdf,tmpFloat)\n\n stats = nothing\n\n if model_type ∈ [:ECOS_L,:SCS_L]\n # Conic Programming, large model\n stats = ExpCone.model_L(myeval,solver)\n return sd,myeval,stats\n\n elseif model_type ∈ [:ECOS_S,:SCS_S]\n # Conic Programming, small model\n stats = ExpCone.model_S(myeval,solver)\n return sd,myeval,stats\n elseif model_type == :SCS_D\n # Conic Programming, Dual problem\n stats = ExpCone.model_D(myeval,solver)\n return sd,myeval,stats\n\n elseif model_type == :My_GradDesc\n stats = my_gradient_descent(myeval;\n max_iter = 1000,\n eps_grad = 1.e-20,\n eps_steplength = 1.e-20,\n stepfactor = .1)\n return sd,myeval,stats\n\n else # not Conic Program\n const lb = constraints_lowerbounds_vec(myeval)\n const ub = constraints_upperbounds_vec(myeval)\n const l = vars_lowerbounds_vec(myeval)\n const u = vars_upperbounds_vec(myeval)\n const model = MathProgBase.NonlinearModel(solver)\n MathProgBase.loadproblem!(model, myeval.n, myeval.m, l, u, lb, ub, :Min, myeval)\n\n if warmstart\n MathProgBase.setwarmstart!(model,ones(Float64,myeval.n))\n end\n\n MathProgBase.optimize!(model)\n # stat = MathProgBase.status(model)\n\n return sd,myeval,model;\n end\n\nend #^ do_it()\n\n\n#-----------------------------------------------\n# Solution & Statistics\n#-----------------------------------------------\ntype Solution_and_Stats\n instance_name :: String\n solver :: Symbol\n var_num :: Int64\n x_sz :: Int64\n y_sz :: Int64\n z_sz :: Int64\n status :: Symbol\n obj_val :: BigFloat\n q_nonneg_viol :: BigFloat\n q_min_entry :: BigFloat\n marginals_1 :: BigFloat\n marginals_2 :: BigFloat\n marginals_Inf :: BigFloat\n mu_nonneg_viol :: BigFloat\n complementarity_max :: BigFloat\n complementarity_sum :: BigFloat\n # MI_X_YZ :: BigFloat\n CI :: BigFloat\n SI :: BigFloat\n UI_Y :: BigFloat\n UI_Z :: BigFloat\n num_eval_f :: Int64\n num_eval_grad_f :: Int64\n num_eval_g :: Int64\n num_eval_jac_g :: Int64\n num_hessevals :: Int64\n opt_time :: BigFloat\n # entropy_X :: BigFloat\nend #^ type Solution_and_Stats\n\n\nfunction check_feasibility(name, model, myeval, solver) :: Solution_and_Stats\n if solver ∈ [:ECOS_L,:SCS_L,:ECOS_S,:SCS_S,:SCS_D]\n # Conic Program\n stats = model\n model = stats.model\n\n fstat = Solution_and_Stats(name,solver, 0,0,0,0, status(model) , big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),0,0,0,0,0,big(0.))\n fstat.x_sz = myeval.n_x\n fstat.y_sz = myeval.n_y\n fstat.z_sz = myeval.n_z\n\n fstat.var_num = MathProgBase.numvar(model)\n if status(model) ∈ [:Solve_Succeeded,:Optimal,:NearOptimal,:Suboptimal,:UserLimit,:FeasibleApproximate,:Error]\n # fstat.obj_val = stats.optimum\n fourtuple = information_quantities(myeval,fstat.obj_val,stats.q)\n (fstat.CI, fstat.SI, fstat.UI_Y, fstat.UI_Z) = fourtuple\n\n fstat.obj_val = eval_f(myeval,stats.q,Float64(0))\n\n fstat.q_nonneg_viol = max(-minimum(stats.q),0)\n fstat.q_min_entry = max(minimum(stats.q),0)\n\n equation = (stats.q'*myeval.Gt)' - myeval.rhs\n fstat.marginals_1 = norm(equation,1)\n fstat.marginals_2 = norm(equation,2)\n fstat.marginals_Inf = norm(equation,Inf)\n end\n fstat.opt_time = stats.time\n\n return fstat\n\n elseif solver == :My_GradDesc\n # First order method: Projected Gradient Descent \n stats = model\n\n fstat = Solution_and_Stats(name,solver, 0,0,0,0, stats.status , big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),0,0,0,0,0,big(0.))\n fstat.x_sz = myeval.n_x\n fstat.y_sz = myeval.n_y\n fstat.z_sz = myeval.n_z\n\n fstat.var_num = myeval.n\n if stats.status ∈ [:grad0 :step0 :iter]\n # fstat.obj_val = stats.optimum\n fourtuple = information_quantities(myeval,fstat.obj_val,stats.q)\n (fstat.CI, fstat.SI, fstat.UI_Y, fstat.UI_Z) = fourtuple\n\n fstat.obj_val = eval_f(myeval,stats.q,Float64(0))\n\n fstat.q_nonneg_viol = max(-minimum(stats.q),0)\n fstat.q_min_entry = max(minimum(stats.q),0)\n\n equation = (stats.q'*myeval.Gt)' - myeval.rhs\n fstat.marginals_1 = norm(equation,1)\n fstat.marginals_2 = norm(equation,2)\n fstat.marginals_Inf = norm(equation,Inf)\n end\n fstat.opt_time = stats.time\n\n return fstat\n\n else\n # Other solvers mainly Interior Point solvers \n fstat = Solution_and_Stats(name,solver, 0,0,0,0, status(model) , big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),big(0.),0,0,0,0,0,big(0.))\n fstat.x_sz = myeval.n_x\n fstat.y_sz = myeval.n_y\n fstat.z_sz = myeval.n_z\n\n fstat.var_num = myeval.n\n if status(model)==:Solve_Succeeded || status(model)==:Optimal || status(model)==:NearOptimal || status(model)==:Suboptimal || status(model)==:KnitroError || ( status(model)==:UserLimit && solver !=:Mosek ) || status(model)==:FeasibleApproximate \n q = Vector{Float64}( getsolution(model) )\n grad = zeros(Float64, myeval.n)\n InfDecomp.∇f(myeval, grad, q, Float64(.0))\n\n lambda = Vector{Float64}( getconstrduals(model) )\n\n mu = grad - myeval.Gt*lambda\n\n fstat.mu_nonneg_viol = max(-minimum(mu),0)\n\n fstat.complementarity_max = maximum( abs.(mu) .* abs.(q) )\n fstat.complementarity_sum = sum( abs.(mu) .* abs.(q) )\n else\n if global__ill_sol != nothing\n q = Vector{Float64}( global__ill_sol )\n end\n fstat.mu_nonneg_viol = -10\n fstat.complementarity_max = -10\n fstat.complementarity_sum = -10\n end# ^if status\n\n fstat.obj_val = eval_f(myeval,q,Float64(0))\n\n fstat.q_nonneg_viol = max(-minimum(q),0)\n fstat.q_min_entry = max(minimum(q),0)\n\n equation = (q'*myeval.Gt)' - myeval.rhs\n fstat.marginals_1 = norm(equation,1)\n fstat.marginals_2 = norm(equation,2)\n fstat.marginals_Inf = norm(equation,Inf)\n # fstat.entropy_X = entropy_X(myeval,q,Float64(0))\n # fstat.MI_X_YZ = fstat.entropy_X + fstat.obj_val\n\n fstat.CI, fstat.SI, fstat.UI_Y, fstat.UI_Z =\n information_quantities(myeval,fstat.obj_val,q)\n\n fstat.num_eval_f = myeval.count_eval_f\n fstat.num_eval_grad_f = myeval.count_eval_grad_f\n fstat.num_eval_g = myeval.count_eval_g\n fstat.num_eval_jac_g = myeval.count_eval_jac_g\n fstat.num_hessevals = myeval.count_hesseval\n if solver != :Ipopt\n fstat.opt_time = getsolvetime(model)\n end\n # end #^if status\n return fstat\n end\n ;\nend #^ check_feasibility()\n\nfunction information_quantities(myeval,optimum,q)\n p = Float64[]\n for x = 1:myeval.n_x\n for y = 1:myeval.n_y\n for z = 1:myeval.n_z\n if myeval.marg_xy[x,y] > 0 && myeval.marg_xz[x,z] > 0\n push!(p,myeval.prb_xyz[x,y,z])\n end\n end# z\n end# y\n end# x\n\n ci = -(eval_f(myeval,p,Float64(0)) + optimum)/log(2)\n si = SI(myeval,q,Float64(0))\n ui_Y = I_X_Y__Z(myeval,q,Float64(0))\n ui_Z = I_X_Z__Y(myeval,q,Float64(0))\n\n return ci,si, ui_Y, ui_Z\nend\n\nend #^ module\n\n; # EOF\n", "meta": {"hexsha": "b0367be27a7b031ab95b439ed4f0c5d81b1f713c", "size": 25039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/infdecomp.jl", "max_stars_repo_name": "dot-at/newpid", "max_stars_repo_head_hexsha": "fc27ffd2caa53ad6c3ed1b183f46e90a68c9e71a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-20T11:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-20T11:23:33.000Z", "max_issues_repo_path": "Julia/infdecomp.jl", "max_issues_repo_name": "dot-at/newpid", "max_issues_repo_head_hexsha": "fc27ffd2caa53ad6c3ed1b183f46e90a68c9e71a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/infdecomp.jl", "max_forks_repo_name": "dot-at/newpid", "max_forks_repo_head_hexsha": "fc27ffd2caa53ad6c3ed1b183f46e90a68c9e71a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-04-05T09:27:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-05T09:27:27.000Z", "avg_line_length": 31.3771929825, "max_line_length": 253, "alphanum_fraction": 0.5483046448, "num_tokens": 7678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.24489643445328263}} {"text": "# Define functions to find ∆ω, ∆a, ∆ψ by the implicit Newton step calculation algorithm.\n# Note that ω, a, ψ are fixed in this calculation.\n\n# We can save computations by implementing the assumption ∆D = 0, and also by updating ψ\n# directly without calculating ∆ψ.\n\nexport LasingSol, LasingVar\n\n# Below (and also in nonlasing.jl), many constructors take some arguments as templates, and\n# those template arguments are not directly set as fields: separate copies are created\n# (usually by `similar`) and set as fields.\n#\n# - An alternative would be to take parameters for creating those fields and create the\n# fields. E.g., we could take the length and the element type of a vector, create a vector,\n# and set it as a field. However, we are aiming to support many different types of vectors\n# (e.g., PETSc vector). We cannot predict all the parameters needed for creating these\n# vectors. By taking an actual instance of a vector in this case, we can support any types\n# of vectors.\n#\n# - Then, the next possibility would be to let the users to provide a copy, instead of\n# automatically generating a copy inside code. I avoid taking this route for consistency in\n# regard to automatic type conversion inside constructors. Suppose I create a custom type\n# named `MyType` containing `v::Vector{Float64}` as a field. If I instantiate `MyType` by\n# giving a `vi::Vector{Int64}` as an argument, `vi` is automatically type-converted into a\n# Vector{Float64} and set to `v`. Here, the resulting `v::Vector{Float64}` is a separate\n# copy from `vi::Vector{Int64}`. On the other hand, if I instantiate `MyType` by giving a\n# `vf::Vector{Float64}` as an argument, a copy is not created and the `vf` itself is set to\n# `v`. This inconsistency is confusing, because in one case changing the contents of the\n# outside vector `vi` does not affect the `MyType` instance, whereas in the other case it\n# does. In order to avoid this inconsistency, I decide to always create a copy of a\n# template argument. This way, no matter whether automatic type conversion occurs or not,\n# the stored field is a separate copy from the argument given to a constructor.\n\n\n# Solutions to the lasing equation.\nmutable struct LasingSol{VF<:AbsVecFloat,VC<:AbsVecComplexF} # VF and VC can be PETSc vectors with N entries\n ω::VecFloat # M real numbers: frequencies of modes (M = # of total modes, including both lasing and nonlasing)\n a²::VecFloat # M real numbers: squared \"amplitudes\" of modes inside hole-burning term; this includes γ(ω)² factor\n ψ::Vector{VC} # M complex vectors: normalized modes\n abs2ψ::Vector{VF} # M complex vectors: absolute squares of normalized modes; this is not abs2.(ψ) because of interpolation\n iₐ::VecInt # M integers: row indices where amplitudes are measured\n vtemp::VC # temporary storage for N complex numbers\n wtemp::VC # temporary storage for N complex numbers\n activated::VecBool # activated[m] == true if mode m is just activated; used in simulate!\n active::VecBool # active[m] == true if mode m is active (i.e., lasing)\n m_active::VecInt # vector of active (i.e., lasing) mode indices; collection of m such that active[m] == true\n function LasingSol{VF,VC}(ω::AbsVecReal,\n a²::AbsVecReal,\n ψ::AbsVec{<:AbsVecNumber},\n abs2ψ::AbsVec{<:AbsVecReal},\n iₐ::AbsVecInteger,\n vtemp::AbsVecComplexF) where {VF<:AbsVecFloat,VC<:AbsVecComplexF}\n M = length(ω)\n length(a²)==length(ψ)==length(abs2ψ)==length(iₐ)==M ||\n @error \"length.((ω,a²,ψ,abs2ψ)) = $(length.((ω,a²,ψ,abs2ψ))) should be all same.\"\n\n N = length(vtemp)\n for m = 1:M\n length(ψ[m])==length(abs2ψ[m])==N ||\n @error \"length.((ψ[$m],abs2ψ[$m],vtemp)) = $(length.((ψ[m],abs2ψ[m],vtemp))) should be all same.\"\n end\n\n return new(ω, a², ψ, abs2ψ, iₐ, vtemp, copy(vtemp), fill(false,M), fill(false,M), VecInt(undef,0)) # active[m]=false for all m: no mode is lasing\n end\nend\nLasingSol(ω::AbsVecReal, a²::AbsVecReal, ψ::AbsVec{VC}, abs2ψ::AbsVec{VF}, iₐ::AbsVecInteger, vtemp::VC) where {VF<:AbsVecFloat,VC<:AbsVecComplexF} =\n LasingSol{VF,VC}(ω, a², ψ, abs2ψ, iₐ, vtemp)\n\n# To do: check if the following works for vtemp of PETSc vector type.\nLasingSol(vtemp::AbsVec, M::Integer) = # vtemp has N entries\n LasingSol(zeros(M), zeros(M), [similar(vtemp,ComplexF).=0 for m = 1:M], [similar(vtemp,Float).=0 for m = 1:M], zeros(Int,M), similar(vtemp,ComplexF))\nLasingSol(N::Integer, M::Integer) = LasingSol(VecFloat(undef,N), M)\n\nBase.length(lsol::LasingSol) = length(lsol.ω) # number of total modes, including both lasing and nonlasing\nnum_active(lsol::LasingSol) = sum(lsol.active) # number of modes currently lasing\n\n\n# Note that this function changes iₐ. Therefore, this should not be called inside the\n# iteration for finding the solution for a given pump strength, because iₐ should be kept the\n# same for a given pump strength in order to solve the equations with the same normalization\n# conditions.\nfunction LinearAlgebra.normalize!(lsol::LasingSol)\n for m = lsol.m_active\n ψ = lsol.ψ[m]\n iₐ = argmax(abs2, ψ)\n lsol.iₐ[m] = iₐ\n\n lsol.a²[m] *= abs2(ψ[iₐ])\n ψ ./= ψ[iₐ] # make ψ[iₐ] = 1\n end\nend\n\n\n# Lasing equation variables that are reduced from all lasing modes\nmutable struct LasingReducedVar{VF<:AbsVecFloat} # VF can be PETSc vector with N entries\n D::Vector{VF} # length-K vector: each entry is N-vector storing population inversion, where K is number of atomic classes\n D′::Vector{VF} # length-K vector: each entry is N-vector storing derivative of population inversion with respect to hole-burning term\n function LasingReducedVar{VF}(D::AbsVec{<:AbsVecReal},\n D′::AbsVec{<:AbsVecReal}) where {VF<:AbsVecFloat}\n K = length(D) # number of atomic classes\n length(D′)==K || @error \"length(D) = $K and length(D′) = $(length(D′)) should be same\"\n\n if K ≥ 1\n N = length(D[1])\n for k = 1:K\n length(D[k])==length(D′[k])==N ||\n @error \"length(D[$k]) = $(length(D[k])) and length(D′[$k]) = $(length(D′[k])) should be $N.\"\n end\n end\n\n return new(D, D′)\n end\nend\nLasingReducedVar(D::AbsVec{<:AbsVecReal}, D′::AbsVec{<:AbsVecReal}) = LasingReducedVar{eltype(D)}(D, D′)\n\n# To do: check if the following works for vtemp of PETSc vector type.\nLasingReducedVar(vtemp::AbsVec, K::Integer) = LasingReducedVar([similar(vtemp,Float).=0 for k=1:K], [similar(vtemp,Float).=0 for k=1:K]) # vtemp has N entries\nLasingReducedVar(N::Integer, K::Integer) = LasingReducedVar(VecFloat(undef,N), K)\n\n\n# Initialize the variables that are NOT specific to a specific lasing mode. These variables\n# are constructed by summing up the contributions from all lasing modes.\nfunction init_reduced_var!(rvar::LasingReducedVar, lsol::LasingSol, gp::GainProfile)\n # abs2ψ should be updated before calling this function; see init_lvar!.\n\n hb = lsol.vtemp # temporary storage for hole-burning term\n for k = 1:length(gp) # atomic classes\n # Calculate the (1 + hole-burning term) for atomic class k.\n abs2γ = gp.abs2gain[k] # |γ²| function for atomic class k\n hole_burning!(hb, abs2γ, lsol.ω, lsol.a², lsol.abs2ψ)\n\n # Calculate the population inversion and the derivative of the population inversion\n # for the class-k atoms.\n #\n # hb is a complex vector storing real, and it is faster to take its real part first\n # and perform the further calculation on it.\n wt = gp.wt[k] # weight function for atomic class k\n rvar.D[k] .= wt.(gp.D₀) ./ real.(hb)\n rvar.D′[k] .= (-1.0) .* wt.(gp.D₀) ./ abs2.(real.(hb))\n end\n\n return nothing\nend\n\n\n# Lasing equation variables that are unique to each lasing mode\nmutable struct LasingModalVar{MXS<:AbstractMaxwellSolver,VC<:AbsVecComplexF} # VC can be PETSc vector\n # Consider adding εeff as a field, in case the user wants to solve the \"linear\" eigenvalue\n # equation for some reason.\n mxsolver::MXS\n ∂f∂ω::VC\nend\n\n# To do: check if the following works for vtemp of PETSc vector type.\nLasingModalVar(mxsolver_temp::AbstractMaxwellSolver, vtemp::AbsVec) = # for, e.g., PETSc vector vtemp; vtemp has N entries\n LasingModalVar(similar(mxsolver_temp), similar(vtemp,ComplexF))\n\nLasingModalVar(mxsolver_temp::AbstractMaxwellSolver, N::Integer) =\n LasingModalVar(similar(mxsolver_temp), VecComplexF(undef,N))\n\n\n# Initialize the variables that are specific to a specific lasing mode.\nfunction init_modal_var!(mvar::LasingModalVar,\n m::Integer, # index of lasing mode\n lsol::LasingSol,\n D::AbsVec{<:AbsVecFloat},\n gp::GainProfile,\n εc::AbsVecComplexF)\n init_modal_var_impl!(mvar.mxsolver, mvar.∂f∂ω, lsol.vtemp, lsol.ω[m], lsol.ψ[m], D, gp, εc)\nend\n\n# This is used in nonlasing.jl as well.\nfunction init_modal_var_impl!(mxsolver::AbstractMaxwellSolver,\n ∂f∂ω::AbsVecComplexF,\n vtemp::AbsVecComplexF,\n ω::Number,\n ψ::AbsVecComplexF,\n D::AbsVec{<:AbsVecFloat},\n gp::GainProfile,\n εc::AbsVecComplexF)\n K = length(gp) # number of atomic classes\n γ = gp.gain # K-vector whose kth entry is γ function of atomic class k\n γ′ = gp.gain′ # K-vector whose kth entry is γ′ function of atomic class k\n\n # Calculate the effective permittivity.\n εeff = vtemp # temporary storage for effective permitivity: εc + ∑ₖ(γₖ Dₖ)\n εeff .= εc\n for k = 1:K\n εeff .+= γ[k](ω) .* D[k]\n end\n\n init_mxsolver!(mxsolver, ω, εeff)\n\n # Calculate ∂f∂ω: derivative of SALT function w.r.t. ω, ignoring ω-dependence of D.\n ∂f∂ω .= 2ω .* εeff\n for k = 1:K\n σ = ω^2 * γ′[k](ω) # scalar\n ∂f∂ω .+= σ .* D[k]\n end\n ∂f∂ω .*= ψ\n\n return nothing\nend\n\n\nmutable struct LasingConstraint\n A::MatFloat # constraint matrix\n b::VecFloat # constraint vector\n ∆ωa²::VecFloat # vector of calculated ∆ω and ∆a²: ∆ω[m] = ∆ωa²[2m-1] and ∆a²[m] = ∆ωa²[2m]\n LasingConstraint(M::Integer) = new(MatFloat(undef,2M,2M), VecFloat(undef,2M), VecFloat(undef,2M))\nend\n\n\n# Components necessary for fixed-point iteration\nmutable struct LasingVar{MXS<:AbstractMaxwellSolver,VF<:AbsVecFloat,VC<:AbsVecComplexF}\n rvar::LasingReducedVar{VF}\n mvar_vec::Vector{LasingModalVar{MXS,VC}}\n cst::LasingConstraint\n inited::Bool\nend\nLasingVar(mxsolver_temp::AbstractMaxwellSolver, vtemp::AbsVec, K::Integer, M::Integer) = # K: number of atomic classes, M: number of modes\n LasingVar(LasingReducedVar(vtemp, K), [LasingModalVar(mxsolver_temp, vtemp) for m = 1:M], LasingConstraint(M), false)\nLasingVar(mxsolver_temp::AbstractMaxwellSolver, N::Integer, K::Integer, M::Integer) = LasingVar(mxsolver_temp, VecFloat(undef,N), K, M)\n\n\nfunction init_lvar!(lvar::LasingVar, lsol::LasingSol, gp::GainProfile, εc::AbsVecComplexF)\n rvar = lvar.rvar\n mvar_vec = lvar.mvar_vec\n\n # Update abs2ψ.\n for m = lsol.m_active\n abs2_interp!(lsol.abs2ψ[m], mvar_vec[m].mxsolver, lsol.ψ[m])\n # lsol.abs2ψ[m] .= abs2.(lsol.ψ[m])\n end\n\n init_reduced_var!(rvar, lsol, gp)\n\n for m = lsol.m_active\n init_modal_var!(mvar_vec[m], m, lsol, rvar.D, gp, εc)\n end\n\n lvar.inited = true\n\n return nothing\nend\n\n\nfunction norm_leq_impl(lsol::LasingSol, mvar_vec::AbsVec{<:LasingModalVar})\n leq = 0.0\n b = lsol.vtemp\n for m = lsol.m_active\n mxsolver = mvar_vec[m].mxsolver\n ψ = lsol.ψ[m]\n mxapply!(b, mxsolver, ψ) # b = A * ψ\n leq = max(leq, norm(b)) # 2-norm for each mode, ∞-norm between modes\n end\n\n return leq # return 0.0 if lsol.m_active is empty\nend\n\n\nfunction norm_leq(lsol::LasingSol, lvar::LasingVar, gp::GainProfile)\n lvar.inited || @error \"lvar is uninitialized: call init_lvar!(...) first.\"\n\n return norm_leq_impl(lsol, lvar.mvar_vec)\nend\n\n\n# Create the mth constraint equation for ∆ω and ∆a.\nfunction set_constraint!(cst::LasingConstraint,\n lsol::LasingSol,\n indₘ::Integer, # index of m in m_active\n mvar::LasingModalVar, # modal variables for mth lasing mode\n rvar::LasingReducedVar,\n gp::GainProfile)\n # Retrieve necessary variables for constructing the constraint.\n m = lsol.m_active[indₘ] # modal index of equation of interest\n L = num_active(lsol) # number of currently lasing modes\n K = length(gp) # number of atomic classes\n\n A = cst.A # left-hand-side matrix of constraint equation\n b = cst.b # right-hand-side vector of constraint equation\n\n ω = lsol.ω # M-vector whose mth entry is current approximate mth eigenfrequency\n a² = lsol.a² # M-vector whose mth entry is squared amplitude of current approximate mth eigenmode\n ψ = lsol.ψ # M-vector whose mth entry is current approximate mth eigenmode\n abs2ψ = lsol.abs2ψ # M-vector whose mth entry is absolute square of current approximate mth eigenmode\n\n ωₘ = ω[m]\n ωₘ² = ωₘ^2\n ψₘ = ψ[m]\n iₐₘ = lsol.iₐ[m] # where mth eigenmode is normalized\n\n vtemp = lsol.vtemp # scratch space 1\n wtemp = lsol.wtemp # scratch space 2\n\n γ = gp.gain # K-vector whose kth entry is γ function of atomic class k\n abs2γ = gp.abs2gain # K-vector whose kth entry is |γ|² function of atomic class k\n abs2γ′ = gp.abs2gain′ # K-vector whose kth entry is ∂|γ|²/∂ω function of atomic class k\n\n D′ = rvar.D′ # K-vector whose kth entry is derivative of population inversion of class-k atoms w.r.t. hole-burning term\n\n # Calculate the iₐth row of A⁻¹ and keep it as a column vector\n eᵢₐ = vtemp\n eᵢₐ .= 0\n eᵢₐ[iₐₘ] = 1\n r = wtemp # storage for row vector\n mxsolve_transpose!(r, mvar.mxsolver, eᵢₐ)\n\n # Construct A and b. Note that they are initialized to zero outside the present\n # function, by update_lsol_impl!.\n\n # Set the mth complex row of right-hand-side vector b of the constraint.\n @assert ψₘ[iₐₘ] ≈ 1\n b[2indₘ-1] = 1.0 # real(ψₘ[iₐₘ])\n b[2indₘ] = 0.0 # imag(ψₘ[iₐₘ])\n\n # Set the mth complex row of the left-hand-side matrix A of the constraint.\n for indⱼ = 1:L\n j = lsol.m_active[indⱼ] # jth complex column\n\n ωⱼ = ω[j]\n a²ⱼ = a²[j]\n abs2ψⱼ = abs2ψ[j]\n\n # Set the coefficient of ∆ωⱼ.\n vtemp .= 0\n ωₘ²a²ⱼ = ωₘ² * a²ⱼ # scalar\n for k = 1:K\n σ = (ωₘ²a²ⱼ * abs2γ′[k](ωⱼ)) * γ[k](ωₘ) # scalar: (real * real) * complex\n vtemp .+= σ .* D′[k]\n end\n vtemp .*= ψₘ .* abs2ψⱼ\n\n # The mth complex row has an additional contribution in the mth complex column from\n # the ωₘ-dependence outside the ω-dependent D.\n j==m && (vtemp .+= mvar.∂f∂ω)\n\n mω = BLAS.dotu(r, vtemp)\n A[2indₘ-1, 2indⱼ-1] = real(mω)\n A[2indₘ, 2indⱼ-1] = imag(mω)\n\n # Set the coefficient of ∆a²ⱼ.\n vtemp .= 0\n for k = 1:K\n σ = (ωₘ² * abs2γ[k](ωⱼ)) * γ[k](ωₘ) # scalar: (real * real) * complex\n vtemp .+= σ .* D′[k]\n end\n vtemp .*= ψₘ .* abs2ψⱼ\n\n ma² = BLAS.dotu(r, vtemp)\n A[2indₘ-1, 2indⱼ] = real(ma²)\n A[2indₘ, 2indⱼ] = imag(ma²)\n end\n\n return nothing\nend\n\n\n# Update ψ for the mth mode. This function does not update ω and a².\nfunction update_ψₘ!(lsol::LasingSol,\n ∆ωa²::VecFloat,\n indₘ::Integer, # index of m in m_active\n mvar::LasingModalVar,\n rvar::LasingReducedVar,\n gp::GainProfile)\n # Retrieve necessary variables for constructing the constraint.\n m = lsol.m_active[indₘ] # modal index of equation of interest\n L = num_active(lsol) # number of currently lasing modes\n K = length(gp) # number of atomic classes\n\n ω = lsol.ω # M-vector whose mth entry is current approximate mth eigenfrequency\n a² = lsol.a² # M-vector whose mth entry is squared amplitude of current approximate mth eigenmode\n ψ = lsol.ψ # M-vector whose mth entry is current approximate mth eigenmode\n abs2ψ = lsol.abs2ψ # M-vector whose mth entry is absolute square of current approximate mth eigenmode\n\n ωₘ = ω[m]\n ωₘ² = ωₘ^2\n ψₘ = ψ[m]\n iₐₘ = lsol.iₐ[m] # where mth eigenmode is normalized\n\n vtemp = lsol.vtemp # scratch space 1\n wtemp = lsol.wtemp # scratch space 1\n\n γ = gp.gain # K-vector whose kth entry is γ function of atomic class k\n abs2γ = gp.abs2gain # K-vector whose kth entry is |γ|² function of atomic class k\n abs2γ′ = gp.abs2gain′ # K-vector whose kth entry is ∂|γ|²/∂ω function of atomic class k\n\n D′ = rvar.D′ # K-vector whose kth entry is derivative of population inversion of class-k atoms w.r.t. hole-burning term\n\n wtemp .= 0 # initialize for mth row\n for indⱼ = 1:L\n j = lsol.m_active[indⱼ] # jth complex column\n\n ωⱼ = ω[j]\n a²ⱼ = a²[j]\n abs2ψⱼ = abs2ψ[j]\n\n ∆ωⱼ = ∆ωa²[2indⱼ-1]\n ∆a²ⱼ = ∆ωa²[2indⱼ]\n\n # Add the contribution of ∆ωⱼ.\n vtemp .= 0 # initialize for ∆ωⱼ\n ωₘ²a²ⱼ = ωₘ² * a²ⱼ # scalar\n for k = 1:K\n σ = (∆ωⱼ * ωₘ²a²ⱼ * abs2γ′[k](ωⱼ)) * γ[k](ωₘ) # scalar: (real * real * real) * complex\n vtemp .+= σ .* D′[k]\n end\n vtemp .*= abs2ψⱼ # ψₘ will be multiplied outside for loop, because it is common for both ∆ω and ∆a²\n wtemp .+= vtemp\n\n # Add the contribution of ∆a²ⱼ.\n vtemp .= 0 # initialize for ∆a²ⱼ\n for k = 1:K\n σ = (∆a²ⱼ * ωₘ² * abs2γ[k](ωⱼ)) * γ[k](ωₘ) # scalar: (real * real * real) * complex\n vtemp .+= σ .* D′[k]\n end\n vtemp .*= abs2ψⱼ # ψₘ will be multiplied outside for loop, because it is common for both ∆ω and ∆a²\n wtemp .+= vtemp\n end\n wtemp .*= ψₘ\n\n # The mth complex row has an additional contribution from the ωₘ-dependence outside the\n # ω-dependent D.\n ∆ωₘ = ∆ωa²[2indₘ-1]\n wtemp .+= ∆ωₘ .* mvar.∂f∂ω\n\n # @info \"‖A‖₁ = $(opnorm(mvar.A,1)), ‖vtemp‖ = $(norm(vtemp))\"\n mxsolve!(ψₘ, mvar.mxsolver, wtemp) # ψₘ .= mvar.mxsolver \\ wtemp\n\n # Normalize ψₘ just in case ψₘ[iₐₘ] ≠ 1.\n # ψₘ[iₐₘ]≈1 || @warn \"lasing mode m = $m is slightly nonnormal: |ψₘ[iₐₘ]-1| = $(abs(ψₘ[iₐₘ]-1)). The mode will be renormalized.\"\n # @info \"ψₘ[iₐₘ] = $(ψₘ[iₐₘ])\"\n ψₘ ./= ψₘ[iₐₘ]\n\n return nothing\nend\n\n\n# lvar should be already initialized by init_lvar! before starting the fixed-point iteration.\nfunction update_lsol!(lsol::LasingSol, lvar::LasingVar, gp::GainProfile)\n lvar.inited || @error \"lvar is uninitialized: call init_lvar!(...) first.\"\n update_lsol_impl!(lsol, lvar.mvar_vec, lvar.rvar, lvar.cst, gp)\n lvar.inited = false\n\n return nothing\nend\n\n\n# Fixed-point equation for lsol. Calculate ∆ω and ∆a, and then ∆ψ, and move lsol by them.\n#\n# This function is expensive to call, because it involves 2Mₗ linear solves, where Mₗ is the\n# number of lasing modes. Therefore, try not to call this function unnecessarily.\n#\n# init_lvar! should be called before using this function to make lvar prepared. However,\n# init_lvar! is not exported in order to force checking the norm by norm_leq to avoid\n# calling this function when the norm is small enough.\nfunction update_lsol_impl!(lsol::LasingSol,\n mvar_vec::AbsVec{<:LasingModalVar}, # should be already initialized\n rvar::LasingReducedVar, # should be already initialized\n cst::LasingConstraint,\n gp::GainProfile)\n # Construct the constraint equation on ∆ω and ∆a.\n L = num_active(lsol)\n\n A = cst.A\n b = cst.b\n ∆ωa² = cst.∆ωa²\n\n A .= 0\n b .= 0\n ∆ωa² .= 0\n\n # Below, we iterate over the contiguous indices indₘ to retrieve the currently lasing\n # mode index m from m_active, instead of directly iterating over m_active. This is\n # because we cannot use a submatrix @view(A[ind,ind]) in ldiv! when ind is not a\n # contiguous range of indices. See https://github.com/JuliaLang/julia/issues/30097.\n for indₘ = 1:L\n m = lsol.m_active[indₘ]\n set_constraint!(cst, lsol, indₘ, mvar_vec[m], rvar, gp)\n end\n\n # Calculate ∆ω and ∆a.\n # @info \"A = $(A[1:2L,1:2L]), b = $(b[1:2L]), ∆ωa² = $(∆ωa²[1:2L])\"\n LU = lu!(@view(A[1:2L,1:2L]))\n ldiv!(@view(∆ωa²[1:2L]), LU, @view(b[1:2L]))\n\n # Update ψ.\n # @info \"lsol.ω = $(lsol.ω), lsol.a² = $(lsol.a²), lsol.m_active = $(lsol.m_active)\"\n for indₘ = 1:L\n m = lsol.m_active[indₘ]\n # @info \"before apply: ‖lsol.ψ[$m]‖ = $(norm(lsol.ψ[m]))\"\n update_ψₘ!(lsol, ∆ωa², indₘ, mvar_vec[m], rvar, gp)\n # @info \"after apply: ‖lsol.ψ[$m]‖ = $(norm(lsol.ψ[m]))\"\n end\n\n # Update ω and a².\n #\n # abs2ψ is not updated here. In each iteration, the Anderson acceleration evaluates the\n # fixed-point function g once to get g(xₖ), but this g(xₖ) is not the new solution xₖ₊₁.\n # xₖ₊₁ is formed as an affine combinination of g(xₖ), ..., g(xₖ₋ₘ). Therefore,\n # abs2ψ evaluated at the end of the evaluation of the fixed point function g is abs2ψ of\n # g(xₖ), not the abs2ψ of xₖ₊₁. Therefore, in order to calculate abs2ψ for xₖ₊₁, which\n # is used inside g for evaluating g(xₖ₊₁), abs2ψ should be updated at the beginning of the\n # fixed-point function (where abs2ψ is used for the first time in that iteration step)\n # rather than at the end. This is inside init_lvar!, whose evaluation in checked at the\n # beginning of update_lsol!.\n #\n # The following loop should not be merged with the loop above, because update_ψₘ! uses\n # un-updated ω and a².\n for indₘ = 1:L\n m = lsol.m_active[indₘ]\n\n ∆ωₘ = ∆ωa²[2indₘ-1]\n ∆a²ₘ = ∆ωa²[2indₘ]\n\n lsol.ω[m] += ∆ωₘ\n lsol.a²[m] += ∆a²ₘ\n end\n\n return nothing\nend\n", "meta": {"hexsha": "369cef4e7de36b5f77b8fc4b6003a928ff5a1e41", "size": 22296, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lasing.jl", "max_stars_repo_name": "wsshin/SALTBase.jl", "max_stars_repo_head_hexsha": "7e649196ebe80045e17a3227280011fb3fab1cb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-19T08:27:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T18:37:29.000Z", "max_issues_repo_path": "src/lasing.jl", "max_issues_repo_name": "wsshin/SALTBase.jl", "max_issues_repo_head_hexsha": "7e649196ebe80045e17a3227280011fb3fab1cb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-06T14:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T16:10:27.000Z", "max_forks_repo_path": "src/lasing.jl", "max_forks_repo_name": "wsshin/SALTBase.jl", "max_forks_repo_head_hexsha": "7e649196ebe80045e17a3227280011fb3fab1cb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6309751434, "max_line_length": 159, "alphanum_fraction": 0.6364370291, "num_tokens": 7313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2448946368113344}} {"text": "using MathOptInterface\nconst MOI = MathOptInterface\nconst MOIU = MOI.Utilities\nconst AFFEQ = MOI.ConstraintIndex{MOI.ScalarAffineFunction{Cdouble}, MOI.EqualTo{Cdouble}}\n\nmutable struct Optimizer <: MOI.AbstractOptimizer\n objconstant::Cdouble\n objsign::Int\n blockdims::Vector{CSDP_INT}\n varmap::Vector{Tuple{Int, Int, Int}} # Variable Index vi -> blk, i, j\n num_entries::Dict{Tuple{Int, Int}, Int}\n b::Vector{Cdouble}\n C::blockmatrix\n problem::Union{Nothing, LoadingProblem}\n X::blockmatrix\n y::Union{Nothing, Vector{Cdouble}}\n Z::blockmatrix\n status::CSDP_INT\n pobj::Cdouble\n dobj::Cdouble\n solve_time::Float64\n silent::Bool\n options::Dict{Symbol, Any}\n function Optimizer(; kwargs...)\n optimizer = new(\n zero(Cdouble), 1, CSDP_INT[], Tuple{Int, Int, Int}[],\n Dict{Tuple{Int, Int}, Int}(), Cdouble[],\n blockmatrix(), nothing, blockmatrix(), nothing, blockmatrix(),\n -1, NaN, NaN, NaN, false, Dict{Symbol, Any}())\n for (key, value) in kwargs\n MOI.set(optimizer, MOI.RawParameter(String(key)), value)\n end\n # May need to call `free_loaded_prob` and `free_loading_prob`.\n finalizer(MOI.empty!, optimizer)\n return optimizer\n end\nend\n\nvarmap(optimizer::Optimizer, vi::MOI.VariableIndex) = optimizer.varmap[vi.value]\n\nfunction MOI.supports(optimizer::Optimizer, param::MOI.RawParameter)\n return Symbol(param.name) in ALLOWED_OPTIONS\nend\nfunction MOI.set(optimizer::Optimizer, param::MOI.RawParameter, value)\n if !(param.name isa String)\n Base.depwarn(\n \"passing `$(param.name)` to `MOI.RawParameter` as type \" *\n \"`$(typeof(param.name))` is deprecated. Use a string instead.\",\n Symbol(\"MOI.set\")\n )\n end\n if !MOI.supports(optimizer, param)\n throw(MOI.UnsupportedAttribute(param))\n end\n optimizer.options[Symbol(param.name)] = value\nend\nfunction MOI.get(optimizer::Optimizer, param::MOI.RawParameter)\n # TODO: This gives a poor error message if the name of the parameter is invalid.\n if !(param.name isa String)\n Base.depwarn(\n \"passing `$(param.name)` to `MOI.RawParameter` as type \" *\n \"`$(typeof(param.name))` is deprecated. Use a string instead.\",\n Symbol(\"MOI.set\")\n )\n end\n return optimizer.options[Symbol(param.name)]\nend\n\nMOI.supports(::Optimizer, ::MOI.Silent) = true\nfunction MOI.set(optimizer::Optimizer, ::MOI.Silent, value::Bool)\n optimizer.silent = value\nend\nMOI.get(optimizer::Optimizer, ::MOI.Silent) = optimizer.silent\n\nMOI.get(::Optimizer, ::MOI.SolverName) = \"CSDP\"\n# See table \"Return codes for easy_sdp() and CSDP\" in `doc/csdpuser.pdf`.\nconst RAW_STATUS = [\n \"Problem solved to optimality.\",\n \"Problem is primal infeasible.\",\n \"Problem is dual infeasible.\",\n \"Problem solved to near optimality.\",\n \"Maximum iterations reached.\",\n \"Stuck at edge of primal feasibility.\",\n \"Stuck at edge of dual feasibility.\",\n \"Lack of progress.\",\n \"X, Z, or O is singular.\",\n \"NaN or Inf values encountered.\",\n \"Program stopped by signal (SIXCPU, SIGTERM, etc.)\"]\n\nfunction MOI.get(optimizer::Optimizer, ::MOI.RawStatusString)\n return RAW_STATUS[optimizer.status + 1]\nend\nfunction MOI.get(optimizer::Optimizer, ::MOI.SolveTime)\n return optimizer.solve_time\nend\n\nfunction MOI.is_empty(optimizer::Optimizer)\n return iszero(optimizer.objconstant) &&\n isone(optimizer.objsign) &&\n isempty(optimizer.blockdims) &&\n isempty(optimizer.varmap) &&\n isempty(optimizer.num_entries) &&\n isempty(optimizer.b) &&\n iszero(optimizer.C.nblocks) &&\n optimizer.C.blocks == C_NULL &&\n optimizer.problem === nothing\nend\n\nfunction MOI.empty!(optimizer::Optimizer)\n optimizer.objconstant = zero(Cdouble)\n optimizer.objsign = 1\n empty!(optimizer.blockdims)\n empty!(optimizer.varmap)\n empty!(optimizer.num_entries)\n empty!(optimizer.b)\n if optimizer.problem !== nothing\n if optimizer.y !== nothing\n free_loaded_prob(optimizer.problem, optimizer.X, optimizer.y, optimizer.Z)\n end\n free_loading_prob(optimizer.problem)\n end\n optimizer.problem = nothing\n optimizer.C.nblocks = 0\n optimizer.C.blocks = C_NULL\n optimizer.X.nblocks = 0\n optimizer.X.blocks = C_NULL\n optimizer.y = nothing\n optimizer.Z.nblocks = 0\n optimizer.Z.blocks = C_NULL\n optimizer.status = -1\n optimizer.pobj = 0.0\n optimizer.dobj = 0.0\nend\n\nfunction MOI.supports(\n optimizer::Optimizer,\n ::Union{MOI.ObjectiveSense,\n MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Cdouble}}})\n return true\nend\n\nfunction MOI.supports_constraint(\n ::Optimizer, ::Type{MOI.VectorOfVariables}, ::Type{MOI.Reals})\n return false\nend\nconst SupportedSets = Union{MOI.Nonnegatives, MOI.PositiveSemidefiniteConeTriangle}\nfunction MOI.supports_constraint(\n ::Optimizer, ::Type{MOI.VectorOfVariables},\n ::Type{<:SupportedSets})\n return true\nend\nfunction MOI.supports_constraint(\n ::Optimizer, ::Type{MOI.ScalarAffineFunction{Cdouble}},\n ::Type{MOI.EqualTo{Cdouble}})\n return true\nend\n\nfunction MOI.copy_to(dest::Optimizer, src::MOI.ModelLike; kws...)\n return MOIU.automatic_copy_to(dest, src; kws...)\nend\nMOIU.supports_allocate_load(::Optimizer, copy_names::Bool) = !copy_names\n\nfunction MOIU.allocate(optimizer::Optimizer, ::MOI.ObjectiveSense, sense::MOI.OptimizationSense)\n # To be sure that it is done before load(optimizer, ::ObjectiveFunction, ...), we do it in allocate\n optimizer.objsign = sense == MOI.MIN_SENSE ? -1 : 1\nend\nfunction MOIU.allocate(::Optimizer, ::MOI.ObjectiveFunction, ::MOI.ScalarAffineFunction) end\n\nfunction MOIU.load(::Optimizer, ::MOI.ObjectiveSense, ::MOI.OptimizationSense) end\n# Loads objective coefficient α * vi\nfunction load_objective_term!(optimizer::Optimizer, α, vi::MOI.VariableIndex)\n blk, i, j = varmap(optimizer, vi)\n # in SDP format, it is max and in MPB Conic format it is min\n coef = optimizer.objsign * α\n if i != j\n coef /= 2\n end\n addentry(optimizer.problem, 0, blk, i, j, coef, true)\nend\nfunction MOIU.load(optimizer::Optimizer, ::MOI.ObjectiveFunction, f::MOI.ScalarAffineFunction)\n obj = MOIU.canonical(f)\n optimizer.objconstant = f.constant\n for t in obj.terms\n if !iszero(t.coefficient)\n load_objective_term!(optimizer, t.coefficient, t.variable_index)\n end\n end\nend\n\nfunction new_block(optimizer::Optimizer, set::MOI.Nonnegatives)\n push!(optimizer.blockdims, -MOI.dimension(set))\n blk = length(optimizer.blockdims)\n for i in 1:MOI.dimension(set)\n push!(optimizer.varmap, (blk, i, i))\n end\nend\n\nfunction new_block(optimizer::Optimizer, set::MOI.PositiveSemidefiniteConeTriangle)\n push!(optimizer.blockdims, set.side_dimension)\n blk = length(optimizer.blockdims)\n for i in 1:set.side_dimension\n for j in 1:i\n push!(optimizer.varmap, (blk, i, j))\n end\n end\nend\n\nfunction MOIU.allocate_constrained_variables(optimizer::Optimizer,\n set::SupportedSets)\n offset = length(optimizer.varmap)\n new_block(optimizer, set)\n ci = MOI.ConstraintIndex{MOI.VectorOfVariables, typeof(set)}(offset + 1)\n return [MOI.VariableIndex(i) for i in offset .+ (1:MOI.dimension(set))], ci\nend\n\nfunction MOIU.load_constrained_variables(\n optimizer::Optimizer, vis::Vector{MOI.VariableIndex},\n ci::MOI.ConstraintIndex{MOI.VectorOfVariables},\n set::SupportedSets)\nend\n\nfunction MOIU.load_variables(optimizer::Optimizer, nvars)\n @assert nvars == length(optimizer.varmap)\n dummy = isempty(optimizer.b)\n if dummy\n # See https://github.com/coin-or/Csdp/issues/2\n optimizer.b = [one(Cdouble)]\n optimizer.blockdims = [optimizer.blockdims; CSDP_INT(-1)]\n count_entry(optimizer, 1, length(optimizer.blockdims))\n end\n optimizer.C.nblocks = length(optimizer.blockdims)\n num_entries = zeros(CSDP_INT, length(optimizer.b), length(optimizer.blockdims))\n for (key, value) in optimizer.num_entries\n num_entries[key...] = value\n end\n optimizer.problem = allocate_loading_prob(Ref(optimizer.C), optimizer.blockdims, length(optimizer.b), num_entries, 3)\n if dummy\n # See https://github.com/coin-or/Csdp/issues/2\n duplicate = addentry(optimizer.problem, 1, length(optimizer.blockdims), 1, 1, 1.0, true)\n @assert !duplicate\n end\n\nend\n\nfunction count_entry(optimizer::Optimizer, con_idx::Integer, blk::Integer)\n key = (con_idx, blk)\n optimizer.num_entries[key] = get(optimizer.num_entries, key, 0) + 1\nend\n\nfunction MOIU.allocate_constraint(optimizer::Optimizer,\n func::MOI.ScalarAffineFunction{Cdouble},\n set::MOI.EqualTo{Cdouble})\n if !iszero(MOI.constant(func))\n throw(MOI.ScalarFunctionConstantNotZero{\n Cdouble, MOI.ScalarAffineFunction{Cdouble}, MOI.EqualTo{Cdouble}}(\n MOI.constant(func)))\n end\n push!(optimizer.b, MOI.constant(set))\n func = MOIU.canonical(func) # sum terms with same variables and same output_index\n for t in func.terms\n if !iszero(t.coefficient)\n blk, i, j = varmap(optimizer, t.variable_index)\n count_entry(optimizer, length(optimizer.b), blk)\n end\n end\n return AFFEQ(length(optimizer.b))\nend\n\nfunction MOIU.load_constraint(optimizer::Optimizer, ci::AFFEQ,\n f::MOI.ScalarAffineFunction, s::MOI.EqualTo)\n if !iszero(MOI.constant(f))\n throw(MOI.ScalarFunctionConstantNotZero{\n Cdouble, MOI.ScalarAffineFunction{Cdouble}, MOI.EqualTo{Cdouble}}(\n MOI.constant(f)))\n end\n setconstant(optimizer.problem, ci.value, MOI.constant(s))\n f = MOIU.canonical(f) # sum terms with same variables and same output_index\n if isempty(f.terms)\n throw(ArgumentError(\"Empty constraint $ci: $f-in-$s. Not supported by CSDP.\"))\n end\n for t in f.terms\n if !iszero(t.coefficient)\n blk, i, j = varmap(optimizer, t.variable_index)\n coef = t.coefficient\n if i != j\n coef /= 2\n end\n duplicate = addentry(optimizer.problem, ci.value, blk, i, j, coef, true)\n @assert !duplicate\n end\n end\nend\n\n\nfunction MOI.optimize!(optimizer::Optimizer)\n write_prob(optimizer)\n\n start_time = time()\n optimizer.y = loaded_initsoln(optimizer.problem, length(optimizer.b), Ref(optimizer.X), Ref(optimizer.Z))\n\n options = optimizer.options\n if optimizer.silent\n options = copy(options)\n options[:printlevel] = 0\n end\n\n optimizer.status, optimizer.pobj, optimizer.dobj = loaded_sdp(\n optimizer.problem, Ref(optimizer.X), optimizer.y,\n Ref(optimizer.Z), options)\n optimizer.solve_time = time() - start_time\nend\n\nfunction MOI.get(m::Optimizer, ::MOI.TerminationStatus)\n status = m.status\n if status == -1\n return MOI.OPTIMIZE_NOT_CALLED\n elseif status == 0\n return MOI.OPTIMAL\n elseif status == 1\n return MOI.INFEASIBLE\n elseif status == 2\n return MOI.DUAL_INFEASIBLE\n elseif status == 3\n return MOI.ALMOST_OPTIMAL\n elseif status == 4\n return MOI.ITERATION_LIMIT\n elseif 5 <= status <= 7\n return MOI.SLOW_PROGRESS\n elseif 8 <= status <= 9\n return MOI.NUMERICAL_ERROR\n else\n error(\"Internal library error: status=$status\")\n end\nend\n\nfunction MOI.get(m::Optimizer, attr::MOI.PrimalStatus)\n if attr.N > MOI.get(m, MOI.ResultCount())\n return MOI.NO_SOLUTION\n end\n status = m.status\n if status == 0\n return MOI.FEASIBLE_POINT\n elseif status == 1\n return MOI.INFEASIBLE_POINT\n elseif status == 2\n return MOI.INFEASIBILITY_CERTIFICATE\n elseif status == 3\n return MOI.NEARLY_FEASIBLE_POINT\n elseif 4 <= status <= 9\n return MOI.UNKNOWN_RESULT_STATUS\n else\n error(\"Internal library error: status=$status\")\n end\nend\n\nfunction MOI.get(m::Optimizer, attr::MOI.DualStatus)\n if attr.N > MOI.get(m, MOI.ResultCount())\n return MOI.NO_SOLUTION\n end\n status = m.status\n if status == 0\n return MOI.FEASIBLE_POINT\n elseif status == 1\n return MOI.INFEASIBILITY_CERTIFICATE\n elseif status == 2\n return MOI.INFEASIBLE_POINT\n elseif status == 3\n return MOI.NEARLY_FEASIBLE_POINT\n elseif 4 <= status <= 9\n return MOI.UNKNOWN_RESULT_STATUS\n else\n error(\"Internal library error: status=$status\")\n end\nend\n\nMOI.get(m::Optimizer, ::MOI.ResultCount) = 1\nfunction MOI.get(m::Optimizer, attr::MOI.ObjectiveValue)\n MOI.check_result_index_bounds(m, attr)\n return m.objsign * m.pobj + m.objconstant\nend\nfunction MOI.get(m::Optimizer, attr::MOI.DualObjectiveValue)\n MOI.check_result_index_bounds(m, attr)\n return m.objsign * m.dobj + m.objconstant\nend\nstruct PrimalSolutionMatrix <: MOI.AbstractModelAttribute end\nMOI.is_set_by_optimize(::PrimalSolutionMatrix) = true\nMOI.get(optimizer::Optimizer, ::PrimalSolutionMatrix) = optimizer.X\n\nstruct DualSolutionVector <: MOI.AbstractModelAttribute end\nMOI.is_set_by_optimize(::DualSolutionVector) = true\nMOI.get(optimizer::Optimizer, ::DualSolutionVector) = optimizer.y\n\nstruct DualSlackMatrix <: MOI.AbstractModelAttribute end\nMOI.is_set_by_optimize(::DualSlackMatrix) = true\nMOI.get(optimizer::Optimizer, ::DualSlackMatrix) = optimizer.Z\n\nfunction block(optimizer::Optimizer, ci::MOI.ConstraintIndex{MOI.VectorOfVariables})\n return optimizer.varmap[ci.value][1]\nend\nfunction dimension(optimizer::Optimizer, ci::MOI.ConstraintIndex{MOI.VectorOfVariables})\n blockdim = optimizer.blockdims[block(optimizer, ci)]\n if blockdim < 0\n return -blockdim\n else\n return MOI.dimension(MOI.PositiveSemidefiniteConeTriangle(blockdim))\n end\nend\nfunction vectorize_block(M, blk::Integer, s::Type{MOI.Nonnegatives})\n return diag(block(M, blk))\nend\nfunction vectorize_block(M::AbstractMatrix{Cdouble}, blk::Integer, s::Type{MOI.PositiveSemidefiniteConeTriangle}) where T\n B = block(M, blk)\n d = LinearAlgebra.checksquare(B)\n n = MOI.dimension(MOI.PositiveSemidefiniteConeTriangle(d))\n v = Vector{Cdouble}(undef, n)\n k = 0\n for j in 1:d\n for i in 1:j\n k += 1\n v[k] = B[i, j]\n end\n end\n @assert k == n\n return v\nend\n\nfunction MOI.get(optimizer::Optimizer, attr::MOI.VariablePrimal, vi::MOI.VariableIndex)\n MOI.check_result_index_bounds(optimizer, attr)\n blk, i, j = varmap(optimizer, vi)\n return block(MOI.get(optimizer, PrimalSolutionMatrix()), blk)[i, j]\nend\n\nfunction MOI.get(optimizer::Optimizer, attr::MOI.ConstraintPrimal,\n ci::MOI.ConstraintIndex{MOI.VectorOfVariables, S}) where S<:SupportedSets\n MOI.check_result_index_bounds(optimizer, attr)\n return vectorize_block(MOI.get(optimizer, PrimalSolutionMatrix()), block(optimizer, ci), S)\nend\nfunction MOI.get(optimizer::Optimizer, attr::MOI.ConstraintPrimal, ci::AFFEQ)\n MOI.check_result_index_bounds(optimizer, attr)\n return optimizer.b[ci.value]\nend\n\nfunction MOI.get(optimizer::Optimizer, attr::MOI.ConstraintDual,\n ci::MOI.ConstraintIndex{MOI.VectorOfVariables, S}) where S<:SupportedSets\n MOI.check_result_index_bounds(optimizer, attr)\n return vectorize_block(MOI.get(optimizer, DualSlackMatrix()), block(optimizer, ci), S)\nend\nfunction MOI.get(optimizer::Optimizer, attr::MOI.ConstraintDual, ci::AFFEQ)\n MOI.check_result_index_bounds(optimizer, attr)\n return -MOI.get(optimizer, DualSolutionVector())[ci.value]\nend\n", "meta": {"hexsha": "79fd3aa03c8494a976f796f86db759136966e195", "size": 15783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MOI_wrapper.jl", "max_stars_repo_name": "giordano/CSDP.jl", "max_stars_repo_head_hexsha": "958078c0744293be2a3179f20052ccb85e3a592b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MOI_wrapper.jl", "max_issues_repo_name": "giordano/CSDP.jl", "max_issues_repo_head_hexsha": "958078c0744293be2a3179f20052ccb85e3a592b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MOI_wrapper.jl", "max_forks_repo_name": "giordano/CSDP.jl", "max_forks_repo_head_hexsha": "958078c0744293be2a3179f20052ccb85e3a592b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9181415929, "max_line_length": 121, "alphanum_fraction": 0.6805423557, "num_tokens": 4095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.24474176519895383}} {"text": "#predevelopment and consenting\n\nfunction OMCost!(options::zefiroOptions,sizes::zefiroSizes,data::zefiroData,output::zefiroOutput)\n key = (options.postprocess ? \"postprocessing\" : \"evaluating\")\n println(key*\" operation cost\")\n operation!(options,sizes,data,output)\n println(key*\" maintenance cost\")\n maintenance!(options,sizes,data,output)\n nothing\n\nend\n\nfunction operation!(options::zefiroOptions,sizes::zefiroSizes,data::zefiroData,output::zefiroOutput)\n\n if options.operation == 0 \n if options.postprocess\n nothing\n else\n Crent = (data.l .* data.Pe) .* output.AEP * data.duration .* transpose(data.turbineQuantity)\n CinsO = zeros(sizes.winds,sizes.turbines)\n CtransO = zeros(sizes.winds,sizes.turbines)\n for i in 1:sizes.winds,j in 1:sizes.turbines\n CinsO[i,j] += data.ComIns[i] * data.IC[j]\n CtransO[i,j] += data.Ctransunit[i] * data.IC[j]\n end\n output.OPEX += Crent + CinsO + CtransO\n output.operation += Crent + CinsO + CtransO\n end\n else\n error(\"operation mode not found.\")\n end\n nothing\n\nend\n\nfunction maintenance!(options::zefiroOptions,sizes::zefiroSizes,data::zefiroData,output::zefiroOutput)\n\n if options.maintenance == 0 \n if options.postprocess\n nothing\n else\n Ccm = zeros(sizes.winds,sizes.turbines)\n Cmdir = zeros(sizes.winds,sizes.turbines)\n Cmind = zeros(sizes.winds,sizes.turbines)\n\n Ctrans = 2*(data.d .* data.tc) \n Clab = data.N1dOM .* data.LrOM \n Ccm .+= Ctrans .+ transpose(Clab) .+ data.consumCost\n\n for i in 1:sizes.winds,j in 1:sizes.turbines\n Cmdir[i,j] = (1-data.Pd[j])*data.lambda[j]*Ccm[i,j] + data.Pd[j]*data.Csm[j]\n end\n\n Cmind .+= (data.Cindport + data.Cindves + data.Cindlab).*transpose(data.turbineQuantity)\n\n output.OPEX += Cmdir + Cmind\n output.maintenance += Cmdir + Cmind\n end\n else\n error(\"maintenance mode not found.\")\n end\n nothing\n\nend", "meta": {"hexsha": "07c313a7300a24acb28a6a9ea6f0447757d353a2", "size": 2140, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/O&M.jl", "max_stars_repo_name": "Thiago-NovaesB/zefiro", "max_stars_repo_head_hexsha": "cc4ce0bf46cc2e2c8dea6e2d74798f9b1b15aaca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/O&M.jl", "max_issues_repo_name": "Thiago-NovaesB/zefiro", "max_issues_repo_head_hexsha": "cc4ce0bf46cc2e2c8dea6e2d74798f9b1b15aaca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/O&M.jl", "max_forks_repo_name": "Thiago-NovaesB/zefiro", "max_forks_repo_head_hexsha": "cc4ce0bf46cc2e2c8dea6e2d74798f9b1b15aaca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4375, "max_line_length": 104, "alphanum_fraction": 0.6065420561, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2445714984900063}} {"text": "function remove_tasks(gamma::Float64, LS::LoadingSequence, CTS::Constants)\n new_LS = deepcopy(LS)\n mod_gamma = Int(floor(CTS.P*gamma))\n if new_LS.order[mod_gamma+1].task.p == 0 && new_LS.order[mod_gamma+1].task.c == 0\n mod_gamma -= 1\n end\n for t = 1:mod_gamma\n if new_LS.order[end].task.p != 0 && new_LS.order[end].task.c != 0\n new_LS.len -= 1\n new_LS.tasks_left += 1\n end\n deleteat!(new_LS.filled_pos, findall(x->x==new_LS.order[length(new_LS.order)].task.p, new_LS.filled_pos))\n deleteat!(new_LS.loaded_cont, findall(x->x==new_LS.order[length(new_LS.order)].task.c, new_LS.loaded_cont))\n deleteat!(new_LS.order, length(new_LS.order))\n end\n return(new_LS)\nend\n\nfunction last_qc_moves(LS::LoadingSequence, CTS::Constants)\n QC_MOVES=Dict{Int, Array{NamedTuple{(:bay, :end_time, :start_time, :time),Tuple{Int64,Int64,Int64,Int64}}, 1}}()\n min_q = (q=0, end_time=CTS.H, start_time=CTS.H, time=CTS.H)\n\n flag = Array{Int,1}()\n while Set(collect(1:CTS.Q)) != Set(flag)\n for t in reverse(LS.order)\n for q = 1:CTS.Q\n if t.qc == q && !(q in flag)\n push!(flag, q)\n if t.start_time + 2*t.task.t < min_q.end_time\n min_q = (q=q, end_time=t.start_time + 2*t.task.t, start_time=t.start_time, time = t.task.t)\n break\n end\n end\n end\n end\n end\n\n flag = Array{Int,1}()\n while Set(collect(1:CTS.Q)) != Set(flag)\n for q = 1:CTS.Q\n l=Array{NamedTuple{(:bay, :end_time, :start_time, :time),Tuple{Int64,Int64,Int64,Int64}}, 1}()\n for t in reverse(LS.order)\n if t.qc == q\n if t.start_time > min_q.end_time\n push!(l, (bay=t.task.b, end_time=t.start_time + 2*t.task.t, start_time=t.start_time, time=t.task.t))\n else\n push!(l, (bay=t.task.b, end_time=t.start_time + 2*t.task.t, start_time=t.start_time, time=t.task.t))\n push!(flag, q)\n break\n end\n end\n end\n QC_MOVES[q]=reverse(l)\n end\n end\n return(min_q, QC_MOVES)\nend\n\n\nfunction get_current_state(LS::LoadingSequence, CTS::Constants)\n TIME = init_timer(CTS)\n TIME.available_cranes = Array{Int, 1}()\n QC = init_qc(CTS)\n min_q, QC_MOVES = last_qc_moves(LS, CTS)\n QC_TRAVEL = get_qc_travel(QC_MOVES, CTS)\n\n TIME.period = min_q.end_time\n TIME.available_cranes = Array{Int, 1}()\n\n for q = 1:CTS.Q\n QC[q].task_buffer = Array{LTask, 1}()\n #idle crane\n if QC_MOVES[q][end].end_time == TIME.period && length(QC_MOVES[q]) == 1\n QC[q].status = \"idle\"\n QC[q].time_left = 0\n QC[q].current_bay = QC_MOVES[q][end].bay\n QC[q].next_bay = QC_MOVES[q][end].bay\n push!(TIME.available_cranes, q)\n #loading crane\n elseif TIME.period >= QC_MOVES[q][end].start_time\n QC[q].status = \"loading\"\n QC[q].time_left = QC_MOVES[q][end].end_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][end].bay\n QC[q].next_bay = QC_MOVES[q][end].bay\n #moving or waiting to move/load crane\n elseif QC_MOVES[q][end-1].end_time <= TIME.period && TIME.period < QC_MOVES[q][end].start_time\n QC[q].next_bay = QC_MOVES[q][end].bay\n push!(QC[q].task_buffer, LTask(0, QC_MOVES[q][end].bay, 0, QC_MOVES[q][end].time))\n if QC_MOVES[q][end-1].bay == QC_MOVES[q][end].bay\n QC[q].status = \"waiting to load\"\n QC[q].time_left = QC_MOVES[q][end].start_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][end].bay\n elseif QC_TRAVEL[q][1].start_time <= TIME.period\n QC[q].status = \"moving\"\n QC[q].time_left = QC_TRAVEL[q][1].end_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][end].bay - QC[q].time_left/CTS.tt\n else\n QC[q].status = \"waiting to move\"\n QC[q].time_left = QC_TRAVEL[q][1].start_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][end-1].bay\n end\n #still loading the previous task\n elseif QC_MOVES[q][end-1].start_time <= TIME.period\n if length(QC_MOVES[q]) == 2\n QC[q].status = \"loading\"\n QC[q].time_left = QC_MOVES[q][end-1].end_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][end-1].bay\n QC[q].next_bay = QC_MOVES[q][end].bay\n push!(QC[q].task_buffer, LTask(0, QC_MOVES[q][end].bay, 0, QC_MOVES[q][end].time))\n end\n else\n for i = 1:length(QC_MOVES[q])-1\n #moving or waiting to move/load crane\n if QC_MOVES[q][i].end_time <= TIME.period && TIME.period < QC_MOVES[q][i+1].start_time\n QC[q].next_bay = QC_MOVES[q][i+1].bay\n for i = 1:length(QC_MOVES[q])-1\n push!(QC[q].task_buffer, LTask(0, QC_MOVES[q][i+1].bay, 0, QC_MOVES[q][i+1].time))\n end\n if QC_MOVES[q][i].bay == QC_MOVES[q][i+1].bay\n QC[q].status = \"waiting to load\"\n QC[q].time_left = QC_MOVES[q][i+1].start_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][i+1].bay\n elseif QC_TRAVEL[q][1].start_time <= TIME.period\n QC[q].status = \"moving\"\n QC[q].time_left = QC_TRAVEL[q][1].end_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][i+1].bay - QC[q].time_left/CTS.tt\n else\n QC[q].status = \"waiting to move\"\n QC[q].time_left = QC_TRAVEL[q][1].start_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][i].bay\n end\n #still loading the previous task\n elseif QC_MOVES[q][i].start_time <= TIME.period\n QC[q].status = \"loading\"\n QC[q].time_left = QC_MOVES[q][i].end_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][i].bay\n QC[q].next_bay = QC_MOVES[q][i].bay\n for i = 1:length(QC_MOVES[q])-1\n push!(QC[q].task_buffer, LTask(0, QC_MOVES[q][i+1].bay, 0, QC_MOVES[q][i+1].time))\n end\n end\n end\n end\n end\n return(true, TIME, QC)\nend\n\n\n\n\n\n\n\n\n\n\n\nfunction get_single_moves(QC_MOVES::Dict{Int, Array{NamedTuple{(:bay, :end_time, :start_time, :time),Tuple{Int64,Int64,Int64,Int64}}, 1}}, CTS::Constants)\n single_moves = Array{NamedTuple{(:qc, :bay, :start_time, :time),Tuple{Int64, Int64, Int64, Int64}},1}()\n check = false\n for q = 1:CTS.Q\n for t = 2:length(QC_MOVES[q])-1\n if QC_MOVES[q][t-1].bay < QC_MOVES[q][t].bay && QC_MOVES[q][t].bay > QC_MOVES[q][t+1].bay\n if QC_MOVES[q][t].time != 0\n push!(single_moves, (qc=q, bay=QC_MOVES[q][t].bay, start_time = QC_MOVES[q][t].start_time, time = QC_MOVES[q][t].time))\n check = true\n end\n elseif QC_MOVES[q][t-1].bay > QC_MOVES[q][t].bay && QC_MOVES[q][t].bay < QC_MOVES[q][t+1].bay\n if QC_MOVES[q][t].time != 0\n push!(single_moves, (qc=q, bay=QC_MOVES[q][t].bay, start_time = QC_MOVES[q][t].start_time, time = QC_MOVES[q][t].time))\n check = true\n end\n end\n end\n\n if QC_MOVES[q][end-1].bay != QC_MOVES[q][end-2].bay && QC_MOVES[q][end-1].time != 0\n push!(single_moves, (qc=q, bay=QC_MOVES[q][end-1].bay, start_time = QC_MOVES[q][end-1].start_time, time = QC_MOVES[q][end-1].time))\n check = true\n end\n if QC_MOVES[q][1].bay != init_bay(q,CTS) && QC_MOVES[q][1].bay != QC_MOVES[q][2].bay && QC_MOVES[q][2].time != 0\n push!(single_moves, (qc=q, bay=QC_MOVES[q][1].bay, start_time = QC_MOVES[q][1].start_time, time = QC_MOVES[q][1].time))\n check = true\n end\n end\n\n if check == false\n return(false)\n else\n return(single_moves)\n end\nend\n\nfunction get_single_task(single::NamedTuple{(:qc, :bay, :start_time, :time),Tuple{Int64,Int64,Int64,Int64}}, LS::LoadingSequence, CTS::Constants)\n single_task = (task=LTask(0,0,0,0), start_time=0, qc=0)\n left_flag = false\n right_flag = false\n l = Array{NamedTuple{(:task, :start_time, :qc),Tuple{LTask,Int64,Int64}},1}()\n r = Array{NamedTuple{(:task, :start_time, :qc),Tuple{LTask,Int64,Int64}},1}()\n for t in LS.order\n #single taks\n if t.start_time == single.start_time && t.qc == single.qc && t.task.b == single.bay && t.task.t == single.time\n single_task = t\n end\n if t.start_time < single.start_time && t.task.b == single.bay && t.qc == single.qc\n if left_flag == false\n left_flag = true\n elseif l[end].start_time + 2*l[end].task.t == t.start_time\n deleteat!(l, length(l))\n end\n push!(l, t)\n elseif single.start_time < t.start_time && t.task.b == single.bay && t.qc == single.qc\n if right_flag == false\n right_flag = true\n elseif r[end].start_time + 2*r[end].task.t == t.start_time\n deleteat!(r, length(r))\n end\n push!(r, t)\n end\n end\n\n return(single_task, left_flag, right_flag, l, r)\nend\n\nfunction trim_left(single::NamedTuple{(:task, :start_time, :qc),Tuple{LTask,Int64,Int64}}, left::NamedTuple{(:task, :start_time, :qc),Tuple{LTask,Int64,Int64}}, LS::LoadingSequence, CTS::Constants)\n LS1 = deepcopy(LS)\n LS2 = deepcopy(LS)\n LS3 = deepcopy(LS)\n\n #delete single_task\n deleteat!(LS1.filled_pos, findall(x->x==single.task.p, LS1.filled_pos))\n deleteat!(LS1.loaded_cont, findall(x->x==single.task.c, LS1.loaded_cont))\n deleteat!(LS1.order, findall(x->x==single, LS1.order))\n deleteat!(LS2.filled_pos, findall(x->x==single.task.p, LS2.filled_pos))\n deleteat!(LS2.loaded_cont, findall(x->x==single.task.c, LS2.loaded_cont))\n deleteat!(LS2.order, findall(x->x==single, LS2.order))\n deleteat!(LS3.filled_pos, findall(x->x==single.task.p, LS3.filled_pos))\n deleteat!(LS3.loaded_cont, findall(x->x==single.task.c, LS3.loaded_cont))\n deleteat!(LS3.order, findall(x->x==single, LS3.order))\n\n #trim LS\n for t in LS.order\n if left.start_time < t.start_time\n deleteat!(LS1.filled_pos, findall(x->x==t.task.p, LS1.filled_pos))\n deleteat!(LS1.loaded_cont, findall(x->x==t.task.c, LS1.loaded_cont))\n deleteat!(LS1.order, findall(x->x==t, LS1.order))\n if single.start_time <= t.start_time\n deleteat!(LS2.filled_pos, findall(x->x==t.task.p, LS2.filled_pos))\n deleteat!(LS2.loaded_cont, findall(x->x==t.task.c, LS2.loaded_cont))\n deleteat!(LS2.order, findall(x->x==t, LS2.order))\n elseif t.start_time <= single.start_time + 2*single.task.t\n deleteat!(LS3.filled_pos, findall(x->x==t.task.p, LS3.filled_pos))\n deleteat!(LS3.loaded_cont, findall(x->x==t.task.c, LS3.loaded_cont))\n deleteat!(LS3.order, findall(x->x==t, LS3.order))\n end\n elseif t.start_time <= left.start_time\n deleteat!(LS2.filled_pos, findall(x->x==t.task.p, LS2.filled_pos))\n deleteat!(LS2.loaded_cont, findall(x->x==t.task.c, LS2.loaded_cont))\n deleteat!(LS2.order, findall(x->x==t, LS2.order))\n deleteat!(LS3.filled_pos, findall(x->x==t.task.p, LS3.filled_pos))\n deleteat!(LS3.loaded_cont, findall(x->x==t.task.c, LS3.loaded_cont))\n deleteat!(LS3.order, findall(x->x==t, LS3.order))\n end\n end\n\n return(LS1, LS2, LS3)\nend\n\nfunction trim_right(single::NamedTuple{(:task, :start_time, :qc),Tuple{LTask,Int64,Int64}}, right::NamedTuple{(:task, :start_time, :qc),Tuple{LTask,Int64,Int64}}, LS::LoadingSequence, CTS::Constants)\n LS1 = deepcopy(LS)\n LS2 = deepcopy(LS)\n LS3 = deepcopy(LS)\n\n #delete single_task\n deleteat!(LS1.filled_pos, findall(x->x==single.task.p, LS1.filled_pos))\n deleteat!(LS1.loaded_cont, findall(x->x==single.task.c, LS1.loaded_cont))\n deleteat!(LS1.order, findall(x->x==single, LS1.order))\n deleteat!(LS2.filled_pos, findall(x->x==single.task.p, LS2.filled_pos))\n deleteat!(LS2.loaded_cont, findall(x->x==single.task.c, LS2.loaded_cont))\n deleteat!(LS2.order, findall(x->x==single, LS2.order))\n deleteat!(LS3.filled_pos, findall(x->x==single.task.p, LS3.filled_pos))\n deleteat!(LS3.loaded_cont, findall(x->x==single.task.c, LS3.loaded_cont))\n deleteat!(LS3.order, findall(x->x==single, LS3.order))\n\n #trim LS\n for t in LS.order\n if t.start_time >= single.start_time\n deleteat!(LS1.filled_pos, findall(x->x==t.task.p, LS1.filled_pos))\n deleteat!(LS1.loaded_cont, findall(x->x==t.task.c, LS1.loaded_cont))\n deleteat!(LS1.order, findall(x->x==t, LS1.order))\n if t.start_time >= right.start_time + 2*right.task.t\n deleteat!(LS2.filled_pos, findall(x->x==t.task.p, LS2.filled_pos))\n deleteat!(LS2.loaded_cont, findall(x->x==t.task.c, LS2.loaded_cont))\n deleteat!(LS2.order, findall(x->x==t, LS2.order))\n elseif t.start_time <= right.start_time\n deleteat!(LS3.filled_pos, findall(x->x==t.task.p, LS3.filled_pos))\n deleteat!(LS3.loaded_cont, findall(x->x==t.task.c, LS3.loaded_cont))\n deleteat!(LS3.order, findall(x->x==t, LS3.order))\n end\n elseif t.start_time < single.start_time\n deleteat!(LS2.filled_pos, findall(x->x==t.task.p, LS2.filled_pos))\n deleteat!(LS2.loaded_cont, findall(x->x==t.task.c, LS2.loaded_cont))\n deleteat!(LS2.order, findall(x->x==t, LS2.order))\n deleteat!(LS3.filled_pos, findall(x->x==t.task.p, LS3.filled_pos))\n deleteat!(LS3.loaded_cont, findall(x->x==t.task.c, LS3.loaded_cont))\n deleteat!(LS3.order, findall(x->x==t, LS3.order))\n end\n end\n return(LS1, LS2, LS3)\nend\n\nfunction merge_left(single::NamedTuple{(:task, :start_time, :qc),Tuple{LTask,Int64,Int64}}, LS1::LoadingSequence, LS2::LoadingSequence, LS3::LoadingSequence, CTS::Constants)\n #merge single task\n push!(LS1.order, (task=single.task, start_time = get_qc_last_time(single.qc, LS1) + travel_time(get_qc_last_bay(single.qc, LS1), single.task.b, CTS), qc=single.qc))\n push!(LS1.filled_pos, single.task.p)\n push!(LS1.loaded_cont, single.task.c)\n #update and merge LS2\n for t in LS2.order\n if t.qc == single.qc\n nt = (task=t.task, start_time = t.start_time + 2*single.task.t, qc=single.qc)\n push!(LS1.order, nt)\n else\n push!(LS1.order, t)\n end\n push!(LS1.filled_pos, t.task.p)\n push!(LS1.loaded_cont, t.task.c)\n end\n #update and merge LS3\n if length(LS3.order) > 0\n dif = 2*travel_time(get_qc_last_bay(single.qc, LS2), single.task.b, CTS)\n for t in LS3.order\n if t.qc == single.qc\n nt = (task=t.task, start_time = t.start_time - dif, qc=single.qc)\n push!(LS1.order, nt)\n else\n push!(LS1.order, t)\n end\n push!(LS1.filled_pos, t.task.p)\n push!(LS1.loaded_cont, t.task.c)\n end\n end\n return(LS1)\nend\n\nfunction merge_right(single::NamedTuple{(:task, :start_time, :qc),Tuple{LTask,Int64,Int64}}, LS1::LoadingSequence, LS2::LoadingSequence, LS3::LoadingSequence, CTS::Constants)\n #update and merge LS2\n if length(LS1.order) > 0\n dif = 2*travel_time(get_qc_last_bay(single.qc, LS1), single.task.b, CTS) + 2*single.task.t\n else\n dif = 2*travel_time(init_bay(single.qc, CTS), single.task.b, CTS) + 2*single.task.t\n end\n for t in LS2.order\n if t.qc == single.qc\n nt = (task=t.task, start_time = t.start_time - dif, qc=single.qc)\n push!(LS1.order, nt)\n else\n push!(LS1.order, t)\n end\n push!(LS1.filled_pos, t.task.p)\n push!(LS1.loaded_cont, t.task.c)\n end\n\n #merge single task\n push!(LS1.order, (task=single.task, start_time = get_qc_last_time(single.qc, LS1) + travel_time(get_qc_last_bay(single.qc, LS1), single.task.b, CTS), qc=single.qc))\n push!(LS1.filled_pos, single.task.p)\n push!(LS1.loaded_cont, single.task.c)\n\n #update and merge LS3\n dif = dif - 2*single.task.t\n for t in LS3.order\n if t.qc == single.qc\n nt = (task=t.task, start_time = t.start_time - dif, qc=single.qc)\n push!(LS1.order, nt)\n else\n push!(LS1.order, t)\n end\n push!(LS1.filled_pos, t.task.p)\n push!(LS1.loaded_cont, t.task.c)\n end\n return(LS1)\nend\n\nfunction remove_single_moves(prec::Dict{Int, Array}, makespan::Int, LS::LoadingSequence, CTS::Constants)\n QC_MOVES = get_qc_moves(LS, CTS)\n single_moves = get_single_moves(QC_MOVES, CTS)\n if single_moves == false\n return(LS)\n else\n for single in single_moves\n if single.qc == LS.order[end].qc\n single_task, left_flag, right_flag, l, r = get_single_task(single, LS, CTS)\n if left_flag == true\n for l_task in l\n LS1, LS2, LS3 = trim_left(single_task, l_task, LS, CTS)\n new_LS = merge_left(single_task, LS1, LS2, LS3, CTS)\n if check_solution(prec, new_LS, CTS) == true\n if total_makespan(new_LS, CTS) < makespan\n return(new_LS)\n end\n end\n end\n end\n if right_flag == true\n for r_task in r\n LS1, LS2, LS3 = trim_right(single_task, r_task, LS, CTS)\n new_LS = merge_right(single_task, LS1, LS2, LS3, CTS)\n if check_solution(prec, new_LS, CTS) == true\n if total_makespan(new_LS, CTS) < makespan\n return(new_LS)\n end\n end\n end\n end\n end\n end\n return(LS)\n end\nend\n\n\nfunction remove_useless_travel(LS::LoadingSequence)\n if LS.order[end].task.t == 0\n deleteat!(LS.order, length(LS.order))\n end\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction get_final_state(LS::LoadingSequence, CTS::Constants)\n TIME = init_timer(CTS)\n TIME.available_cranes = Array{Int, 1}()\n QC = init_qc(CTS)\n min_q, moves, QC_MOVES = ls_qc_moves(best_LS, CTS)\n QC_TRAVEL = get_qc_travel(QC_MOVES, CTS)\n\n TIME.period = min_q.end_time\n TIME.available_cranes = Array{Int, 1}()\n\n for q = 1:CTS.Q\n QC[q].task_buffer = Array{LTask, 1}()\n #idle crane\n if QC_MOVES[q][1].end_time == TIME.period\n QC[q].status = \"idle\"\n QC[q].time_left = 0\n QC[q].current_bay = QC_MOVES[q][1].bay\n QC[q].next_bay = QC_MOVES[q][1].bay\n push!(TIME.available_cranes, q)\n #loading crane\n elseif QC_MOVES[q][1].start_time <= TIME.period && TIME.period < QC_MOVES[q][1].end_time\n QC[q].status = \"loading\"\n QC[q].time_left = QC_MOVES[q][1].end_time - TIME.period\n QC[q].current_bay = QC_MOVES[q][1].bay\n QC[q].next_bay = QC_MOVES[q][1].bay\n else\n QC[q].status = \"idle\"\n QC[q].time_left = 0\n QC[q].current_bay = QC_MOVES[q][1].bay\n QC[q].next_bay = QC_MOVES[q][1].bay\n push!(TIME.available_cranes, q)\n end\n end\n return(min_q.q, moves, TIME, QC)\nend\n\nfunction remove_final_tasks(moves::Int, LS::LoadingSequence, CTS::Constants)\n new_LS = deepcopy(LS)\n\n if moves > 2\n while new_LS.len >= LS.len - (moves - 2)\n if new_LS.order[end].task.p != 0 && new_LS.order[end].task.c != 0\n new_LS.len -= 1\n new_LS.tasks_left += 1\n end\n deleteat!(new_LS.filled_pos, findall(x->x==new_LS.order[length(new_LS.order)].task.p, new_LS.filled_pos))\n deleteat!(new_LS.loaded_cont, findall(x->x==new_LS.order[length(new_LS.order)].task.c, new_LS.loaded_cont))\n deleteat!(new_LS.order, length(new_LS.order))\n end\n if new_LS.order[end].task.p == 0 && new_LS.order[end].task.c == 0\n deleteat!(new_LS.order, length(new_LS.order))\n end\n end\n return(new_LS)\nend\n\n\nfunction ls_qc_moves(LS::LoadingSequence, CTS::Constants)\n QC_MOVES=Dict{Int, Array{NamedTuple{(:bay, :end_time, :start_time, :time),Tuple{Int64,Int64,Int64,Int64}}, 1}}()\n min_q = (q=0, end_time=CTS.H, start_time=CTS.H, time=CTS.H)\n moves = 0\n flag = Array{Int,1}()\n while Set(collect(1:CTS.Q)) != Set(flag)\n for t in reverse(LS.order)\n for q = 1:CTS.Q\n if t.qc == q && !(q in flag) && t.task.t != 0\n push!(flag, q)\n if t.start_time + 2*t.task.t < min_q.end_time\n min_q = (q=q, end_time=t.start_time + 2*t.task.t, start_time=t.start_time, time = t.task.t)\n break\n end\n end\n end\n end\n end\n\n flag = Array{Int,1}()\n while Set(collect(1:CTS.Q)) != Set(flag)\n for q = 1:CTS.Q\n l=Array{NamedTuple{(:bay, :end_time, :start_time, :time),Tuple{Int64,Int64,Int64,Int64}}, 1}()\n for t in reverse(LS.order)\n if t.qc == q\n if t.start_time > min_q.end_time\n push!(l, (bay=t.task.b, end_time=t.start_time + 2*t.task.t, start_time=t.start_time, time=t.task.t))\n if t.task.t != 0\n moves += 1\n end\n elseif t.start_time < min_q.start_time && t.start_time + 2*t.task.t < min_q.start_time\n push!(l, (bay=t.task.b, end_time=t.start_time, start_time=t.start_time, time=0))\n push!(flag, q)\n break\n else\n push!(l, (bay=t.task.b, end_time=t.start_time + 2*t.task.t, start_time=t.start_time, time=t.task.t))\n push!(flag, q)\n if t.task.t != 0\n moves += 1\n end\n break\n end\n end\n end\n QC_MOVES[q]=reverse(l)\n end\n end\n return(min_q, moves, QC_MOVES)\nend\n", "meta": {"hexsha": "2951baf203e9910688af8d893c129c34913b86b5", "size": 23118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/heuristics/local_search.jl", "max_stars_repo_name": "marcmartinezruiz/MarcMartinez_thesis", "max_stars_repo_head_hexsha": "3a6079e8a1734bd709e0cdd4571c08124326e320", "max_stars_repo_licenses": ["Zlib", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/heuristics/local_search.jl", "max_issues_repo_name": "marcmartinezruiz/MarcMartinez_thesis", "max_issues_repo_head_hexsha": "3a6079e8a1734bd709e0cdd4571c08124326e320", "max_issues_repo_licenses": ["Zlib", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/heuristics/local_search.jl", "max_forks_repo_name": "marcmartinezruiz/MarcMartinez_thesis", "max_forks_repo_head_hexsha": "3a6079e8a1734bd709e0cdd4571c08124326e320", "max_forks_repo_licenses": ["Zlib", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7292418773, "max_line_length": 199, "alphanum_fraction": 0.5531187819, "num_tokens": 6728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.244571492275262}} {"text": "using Oceananigans\nusing Oceananigans.Architectures: arch_array\nusing Oceananigans: AbstractModel\nusing Oceananigans.Models.HydrostaticFreeSurfaceModels: HydrostaticFreeSurfaceModel\n\nfunction get_parameter(filename, group, parameter_name, default=nothing)\n parameter = default\n\n jldopen(filename) do file\n if parameter_name ∈ keys(file[\"$group\"])\n parameter = file[\"$group/$parameter_name\"]\n end\n end\n\n return parameter\nend\n\n\"\"\"\n OneDimensionalEnsembleModel(observations::OneDimensionalTimeSeriesBatch; architecture = CPU(), ensemble_size = 50, kwargs...)\n\nBuild an Oceananigans `HydrostaticFreeSurfaceModel` with many independent \ncolumns. The model grid is given by the data in `observations`, and the\ndynamics in each column is attached to its own `CATKEVerticalDiffusivity` closure stored in \nan `(Nx, Ny)` Matrix of closures. `ensemble_size = 50` is the \ndesired count of ensemble members for calibration with Ensemble Kalman Inversion (EKI), and the \nremaining keyword arguments `kwargs` define the default closure across all columns.\n\nIn the \"many columns\" configuration, we run the model on a 3D grid with `(Flat, Flat, Bounded)` boundary \nconditions so that many independent columns can be evolved at once with much of the computational overhead\nsplit among the columns. The `Nx` rows of vertical columns are each reserved for an \"ensemble\" member\nwhose attached parameter value (updated at each iteration of EKI) sets the diffusivity closure\nused to predict the model solution for the `Ny` physical scenarios described by the simulation-specific \n`OneDimensionalTimeSeries` objects in `observations`.\n\"\"\"\nfunction OneDimensionalEnsembleModel(observations::OneDimensionalTimeSeriesBatch; \n architecture = CPU(), \n ensemble_size = 50, \n closure = CATKEVerticalDiffusivity(Float64; warning=false, kwargs...)\n )\n\n #\n # Harvest observation file metadata\n #\n\n datapath = observations.file_path\n\n α = get_parameter(datapath, \"buoyancy\", \"equation_of_state/α\", 2e-4)\n g = get_parameter(datapath, \"buoyancy\", \"gravitational_acceleration\", 9.81)\n αg = α * g\n\n f = get_parameter(datapath, \"coriolis\", \"f\", 0.0)\n\n # Surface fluxes\n Qᵘ = get_parameter(datapath, \"parameters\", \"boundary_condition_u_top\", 0.0)\n Qᵛ = get_parameter(datapath, \"parameters\", \"boundary_conditions_v_top\", 0.0)\n Qᶿ = get_parameter(datapath, \"parameters\", \"boundary_condition_θ_top\", 0.0)\n Qᵇ = Qᶿ * αg\n\n # Bottom gradients\n dudz_bottom = get_parameter(datapath, \"parameters\", \"boundary_condition_u_bottom\", 0.0)\n dθdz_bottom = get_parameter(datapath, \"parameters\", \"boundary_condition_θ_bottom\", 0.0)\n dbdz_bottom = dθdz_bottom * αg\n\n #\n # Build model using metadata\n #\n\n grid = OneDimensionalEnsembleGrid(observations.grid; size=(ensemble_size, length(observations), data_grid.Nz))\n\n closure = [closure for i=1:ensemble_size, j=1:length(observations)]\n\n coriolis = [FPlane(f=td.constants[:f]) for i=1:ensemble_size, td in observations]\n coriolis = arch_array(architecture, coriolis)\n\n bc_matrix(x) = [x for i = 1:ensemble_size, d in observations]\n Qᵇ = bc_matrix(Qᵇ)\n Qᵘ = bc_matrix(Qᵘ)\n Qᵛ = bc_matrix(Qᵛ)\n dbdz_bottom = bc_matrix(dbdz_bottom)\n dudz_bottom = bc_matrix(dudz_bottom)\n\n # Convert to CuArray if necessary\n closure = arch_array(architecture, closure)\n Qᵇ = arch_array(architecture, Qᵇ)\n Qᵘ = arch_array(architecture, Qᵘ)\n Qᵛ = arch_array(architecture, Qᵛ)\n dbdz_bottom = arch_array(architecture, dbdz_bottom)\n dudz_bottom = arch_array(architecture, dudz_bottom)\n \n u_bcs = FieldBoundaryConditions(top = FluxBoundaryCondition(Qᵘ), \n bottom = GradientBoundaryCondition(dudz_bottom))\n v_bcs = FieldBoundaryConditions(top = FluxBoundaryCondition(Qᵛ))\n b_bcs = FieldBoundaryConditions(top = FluxBoundaryCondition(Qᵇ), \n bottom = GradientBoundaryCondition(dbdz_bottom))\n\n model = HydrostaticFreeSurfaceModel(architecture = architecture,\n grid = grid,\n tracers = (:b, :e),\n buoyancy = BuoyancyTracer(),\n coriolis = coriolis,\n boundary_conditions = (b=b_bcs, u=u_bcs, v=v_bcs),\n closure = closure)\n\n return model\nend", "meta": {"hexsha": "5a2633d2f78f3775c348a0082499a0812db79af4", "size": 4561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "projects/OceanBoundaryLayerParameterizations/src/one_dimensional_ensemble_model.jl", "max_stars_repo_name": "adelinehillier/OceanTurbulenceParameterEstimation.jl", "max_stars_repo_head_hexsha": "c0253976746d43c6667414be3801343818f6b2bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-03T04:11:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T04:11:22.000Z", "max_issues_repo_path": "projects/OceanBoundaryLayerParameterizations/src/one_dimensional_ensemble_model.jl", "max_issues_repo_name": "adelinehillier/OceanTurbulenceParameterEstimation.jl", "max_issues_repo_head_hexsha": "c0253976746d43c6667414be3801343818f6b2bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-09-15T20:32:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T22:17:15.000Z", "max_forks_repo_path": "projects/OceanBoundaryLayerParameterizations/src/one_dimensional_ensemble_model.jl", "max_forks_repo_name": "adelinehillier/OceanTurbulenceParameterEstimation.jl", "max_forks_repo_head_hexsha": "c0253976746d43c6667414be3801343818f6b2bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4380952381, "max_line_length": 129, "alphanum_fraction": 0.6812102609, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2444767650454476}} {"text": "# Заполняет словарь d индексами индивидуальных значений\n#=\nfunction indsdict!(d::Dict{T}, cdata::Tuple) where T\n @inbounds for (i, element) in enumerate(zip(cdata...))\n ind = ht_keyindex(d, element)\n if ind > 0\n push!(d.vals[ind], i)\n else\n v = Vector{Int}(undef, 1)\n v[1] = i\n d[element] = v\n end\n end\n d\nend\n=#\nnonunique(v) = [k for (k, v) in StatsBase.countmap(v) if v > 1]\n\nfunction floatparse(data)\n v = Vector{Float64}(undef, length(data))\n @inbounds for i = 1:length(data)\n if !isa(data[i], AbstractFloat) && !ismissing(data[i])\n if isa(data[i], AbstractString)\n try\n v[i] = parse(Float64, data[i])\n catch\n v[i] = NaN\n end\n else\n try\n v[i] = float(data[i])\n catch\n v[i] = NaN\n end\n end\n elseif ismissing(data[i])\n v[i] = NaN\n else\n v[i] = data[i]\n end\n end\n identity.(v)\nend\n\nfunction checkvalues(timevals_sp, concvals_sp)\n if !(eltype(timevals_sp) <: Number)\n timevals_sp = identity.(timevals_sp)\n eltype(timevals_sp) <: Number || error(\"Some time values not a number!\")\n end\n if !(eltype(concvals_sp) <: Union{Number, Missing})\n concvals_sp = identity.(concvals_sp)\n if !(eltype(concvals_sp) <: Union{Number, Missing})\n @warn \"Some concentration values not a number, try to fix.\"\n concvals_sp = floatparse(concvals_sp)\n end\n end\n timevals_sp, concvals_sp\nend\n\n\"\"\"\n pkimport(data, time, conc, sort; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime())\n\nImport PK data from table `data`.\n\n* `time` - time column;\n* `conc` - concentration column;\n* `sort` - subject sorting columns.\n\nkeywords:\n\n* `kelauto` - if `true` auto range settings, if `false` used `kelstart`/`kelend` from `elimrange`;\n* `elimrange` - set elimination range settings;\n* `dosetime` - set dose and dose time, by default dosetime = 0, dose is `NaN`.\n\n!!! note\n\n If time column have non-unique values - last pair time-concentration will be used.\n\n\"\"\"\nfunction pkimport(data, time, conc, sort; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime())\n if isa(sort, String) sort = [Symbol(sort)] end\n if isa(sort, Symbol) sort = [sort] end\n\n Tables.istable(data) || error(\"Data not a table!\")\n\n cols = Tables.columns(data)\n cdata = Tuple(Tables.getcolumn(cols, y) for y in sort)\n d = Dict{Tuple{eltype.(cdata)...}, Vector{Int}}()\n indsdict!(d, cdata)\n\n timec = Tables.getcolumn(data, time)\n concc = Tables.getcolumn(data, conc)\n\n any(isnanormissing, timec) && error(\"Some time values is NaN or Missing!\")\n\n sdata = Vector{PKSubject}(undef, length(d))\n i = one(Int)\n @inbounds for (k, v) in d\n timevals = timec[v]\n concvals = concc[v]\n if !allunique(timevals)\n @warn \"Not all time values is unique, last observation used! ($k)\"\n nuv = nonunique(timevals)\n nuvinds = findall(x -> x == first(nuv), timevals)[1:end-1]\n if length(nuv) > 1\n for cnt = 2:length(nuv)\n append!(nuvinds, findall(x -> x == nuv[cnt], timevals)[1:end-1])\n end\n end\n sort!(nuvinds)\n deleteat!(timevals, nuvinds)\n deleteat!(concvals, nuvinds)\n end\n sp = sortperm(timevals)\n timevals_sp = timevals[sp]\n concvals_sp = concvals[sp]\n timevals_sp, concvals_sp = checkvalues(timevals_sp, concvals_sp)\n sdata[i] = PKSubject(timevals_sp, concvals_sp, kelauto, elimrange, dosetime, Dict(sort .=> k))\n i += one(Int)\n end\n return DataSet(identity.(sdata))\nend\n\"\"\"\n pkimport(data, time, conc; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime())\n\nImport PK data from tabular data `data`, `time` - time column, `conc` - concentration column.\n\"\"\"\nfunction pkimport(data, time, conc; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime())\n timevals_sp, concvals_sp = checkvalues(copy(Tables.getcolumn(data, time)), copy(Tables.getcolumn(data, conc)))\n pkimport(timevals_sp, concvals_sp; kelauto = kelauto, elimrange = elimrange, dosetime = dosetime)\nend\n\"\"\"\n pkimport(time, conc; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime(), id = Dict{Symbol, Any}())\n\nImport PK data from time vector `time` and concentration vector `conc`.\n\"\"\"\nfunction pkimport(time, conc; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime(), id = Dict{Symbol, Any}())\n timevals_sp, concvals_sp = checkvalues(copy(time), copy(conc))\n PKSubject(timevals_sp, concvals_sp, kelauto, elimrange, dosetime, id)\nend\n\n\n\"\"\"\n upkimport(data, stime, etime, conc, vol, sort; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime())\n\nImport urine PK data from table `data`.\n\n* `stime` - start time column;\n* `etime` - end time column;\n* `conc` - concentration column;\n* `vol` - volume column;\n* `sort` - subject sorting columns.\n\"\"\"\nfunction upkimport(data, stime, etime, conc, vol, sort; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime())\n if isa(sort, String) sort = [Symbol(sort)] end\n if isa(sort, Symbol) sort = [sort] end\n\n cols = Tables.columns(data)\n cdata = Tuple(Tables.getcolumn(cols, y) for y in sort)\n d = Dict{Tuple{eltype.(cdata)...}, Vector{Int}}()\n indsdict!(d, cdata)\n\n tnames = Symbol.(names(data))\n isa(stime, Symbol) || stime in tnames || error(\"column Start Time ($stime) not found\")\n isa(etime, Symbol) || etime in tnames || error(\"column End Time ($etime) not found\")\n isa(conc, Symbol) || conc in tnames || error(\"column Concentration ($conc) not found\")\n isa(vol, Symbol) || vol in tnames || error(\"column Volume ($vol) not found\")\n\n stimec = Tables.getcolumn(data, stime)\n etimec = Tables.getcolumn(data, etime)\n concc = Tables.getcolumn(data, conc)\n volc = Tables.getcolumn(data, vol)\n\n any(isnanormissing, stimec) && error(\"Some Start Time values is NaN or Missing!\")\n any(isnanormissing, etimec) && error(\"Some End Time values is NaN or Missing!\")\n\n sdata = Vector{UPKSubject}(undef, length(d))\n i = one(Int)\n @inbounds for (k, v) in d\n stimevals = stimec[v]\n etimevals = etimec[v]\n concvals = concc[v]\n volvals = volc[v]\n #=\n timeranges = collect(zip(stimevals, etimevals))\n sp = sortperm(stimevals)\n\n timevals_sp = timeranges[sp]\n concvals_sp = concvals[sp]\n volvals_sp = volvals[sp]\n\n if length(timevals_sp) > 1\n for c = 2:length(timevals_sp)\n timevals_sp[c][1] == timevals_sp[c-1][2] || error(\"Start time ($(timevals_sp[c][1])) for observation $c not equal End time ($(timevals_sp[c-1][2])) for observation $(c-1)!\")\n end\n end\n sdata[i] = UPKSubject(timevals_sp, concvals_sp, volvals_sp, kelauto, elimrange, dosetime, Dict(sort .=> k))\n =#\n sdata[i] = upkimport(stimevals, etimevals, concvals, volvals; kelauto = kelauto, elimrange = elimrange, dosetime = dosetime, id = Dict(sort .=> k))\n i += one(Int)\n end\n return DataSet(identity.(sdata))\nend\n\"\"\"\n upkimport(data, stime, etime, conc, vol; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime())\n\nImport single urine PK data from table `data`.\n\n* `stime` - start time column;\n* `etime` - end time column;\n* `conc` - concentration column;\n* `vol` - volume column.\n\"\"\"\nfunction upkimport(data, stime, etime, conc, vol; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime())\n upkimport(Tables.getcolumn(data, stime), Tables.getcolumn(data, etime), Tables.getcolumn(data, conc), Tables.getcolumn(data, vol); kelauto = kelauto, elimrange = elimrange, dosetime = dosetime)\nend\n\"\"\"\n upkimport(stime, etime, conc, vol; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime())\n\nImport urine PK data from time vectors:\n* `stime` - start times;\n* `etime` - end times;\n* `conc` - concentrations;\n* `vol` - volumes.\n\"\"\"\nfunction upkimport(stime, etime, conc, vol; kelauto = true, elimrange = ElimRange(), dosetime = DoseTime(), id = Dict{Symbol, Any}())\n any(isnanormissing, stime) && error(\"Some Start Time values is NaN or Missing!\")\n any(isnanormissing, etime) && error(\"Some End Time values is NaN or Missing!\")\n timeranges = collect(zip(stime, etime))\n sp = sortperm(stime)\n timevals_sp = timeranges[sp]\n concvals_sp = conc[sp]\n volvals_sp = vol[sp]\n if length(timevals_sp) > 1\n for c = 2:length(timevals_sp)\n timevals_sp[c][1] == timevals_sp[c-1][2] || error(\"Start time ($(timevals_sp[c][1])) for observation $c not equal End time ($(timevals_sp[c-1][2])) for observation $(c-1)!\")\n end\n end\n UPKSubject(timevals_sp, concvals_sp, volvals_sp, kelauto, elimrange, dosetime, id)\nend\n\n\nfunction pdimport(data, time, obs, sort; bl = 0, th = NaN)\n if isa(sort, String) sort = [Symbol(sort)] end\n if isa(sort, Symbol) sort = [sort] end\n\n Tables.istable(data) || error(\"Data not a table!\")\n\n cols = Tables.columns(data)\n cdata = Tuple(Tables.getcolumn(cols, y) for y in sort)\n d = Dict{Tuple{eltype.(cdata)...}, Vector{Int}}()\n indsdict!(d, cdata)\n\n timec = Tables.getcolumn(data, time)\n obsc = Tables.getcolumn(data, obs)\n\n any(isnanormissing, timec) && error(\"Some time values is NaN or Missing!\")\n\n sdata = Vector{PDSubject}(undef, length(d))\n i = one(Int)\n @inbounds for (k, v) in d\n timevals = timec[v]\n obsvals = obsc[v]\n\n if !allunique(timevals)\n @warn \"Not all time values is unique, last observation used! ($k)\"\n nuv = nonunique(timevals)\n nuvinds = findall(x -> x == first(nuv), timevals)[1:end-1]\n if length(nuv) > 1\n for cnt = 2:length(nuv)\n append!(nuvinds, findall(x -> x == nuv[cnt], timevals)[1:end-1])\n end\n end\n sort!(nuvinds)\n deleteat!(timevals, nuvinds)\n deleteat!(obsvals, nuvinds)\n end\n sp = sortperm(timevals)\n timevals_sp = timevals[sp]\n obsvals_sp = obsvals[sp]\n timevals_sp, obsvals_sp = checkvalues(timevals_sp, obsvals_sp)\n sdata[i] = PDSubject(timevals_sp, obsvals_sp, bl, th, Dict(sort .=> k))\n i += one(Int)\n end\n return DataSet(identity.(sdata))\nend\n", "meta": {"hexsha": "5b0b53fad22640643b22c2ae0d40a5010a4e2ef8", "size": 10623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/import.jl", "max_stars_repo_name": "PharmCat/MetidaNCA.jl", "max_stars_repo_head_hexsha": "6401dbc74415a8689e53697975a23c573bb16ab2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-11T21:50:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T20:06:08.000Z", "max_issues_repo_path": "src/import.jl", "max_issues_repo_name": "PharmCat/MetidaNCA.jl", "max_issues_repo_head_hexsha": "6401dbc74415a8689e53697975a23c573bb16ab2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-10T20:05:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T15:14:33.000Z", "max_forks_repo_path": "src/import.jl", "max_forks_repo_name": "PharmCat/MetidaNCA.jl", "max_forks_repo_head_hexsha": "6401dbc74415a8689e53697975a23c573bb16ab2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0139372822, "max_line_length": 198, "alphanum_fraction": 0.6109385296, "num_tokens": 3021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24444868474512665}} {"text": "############################################################\n## joAbstractDAparallelLinearOperator(s) - overloaded Base functions\n\n# eltype(jo)\neltype(A::joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = promote_type(DDT,RDT)\n\n# deltype(jo)\ndeltype(A::joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = DDT\n\n# reltype(jo)\nreltype(A::joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = RDT\n\n# show(jo)\nfunction show(A::joAbstractDAparallelLinearOperator)\n println(\"Type: $(typeof(A).name)\")\n println(\"Name: $(A.name)\")\n println(\"Size: $(size(A))\")\n println(\" NVC: $(A.nvc)\")\n println(\" DDT: $(deltype(A))\")\n println(\" RDT: $(reltype(A))\")\n return nothing\nend\n\n# display(jo)\ndisplay(A::joAbstractDAparallelLinearOperator) = println((typeof(A),((A.m,A.n),A.nvc),A.name))\n\n# size(jo)\nsize(A::joAbstractDAparallelLinearOperator) = A.m,A.n\n\n# size(jo,1/2)\nfunction size(A::joAbstractDAparallelLinearOperator,ind::Integer)\n if ind==1\n\t\treturn A.m\n\telseif ind==2\n\t\treturn A.n\n\telseif ind==3\n\t\treturn A.nvc\n\telse\n\t\tthrow(joAbstractDAparallelLinearOperatorException(\"invalid index\"))\n\tend\nend\n\n# length(jo)\nlength(A::joAbstractDAparallelLinearOperator) = A.m*A.n\n\n# jo_full(jo)\n\n# norm(jo)\n\n# real(jo)\n\n# imag(jo)\n\n# conj(jo)\nconj(A::joDALinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDALinearOperator{DDT,RDT,N}(\"conj(\"*A.name*\")\",A.m,A.n,A.nvc,\n get(A.fop_C), A.fop_A, A.fop_T, A.fop,\n A.iop_C, A.iop_A, A.iop_T, A.iop,\n A.PAs_in, A.PAs_out, A.fclean, A.rclean\n )\nconj(A::joDAdistributedLinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDAdistributedLinearOperator{DDT,RDT,N}(\"conj(\"*A.name*\")\",A.m,A.n,A.nvc,\n get(A.fop_C), A.fop_A, A.fop_T, A.fop,\n A.iop_C, A.iop_A, A.iop_T, A.iop,\n A.PAs_in, A.PAs_out, A.fclean, A.rclean\n )\nconj(A::joDAdistributingLinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDAdistributingLinearOperator{DDT,RDT,N}(\"conj(\"*A.name*\")\",A.m,A.n,A.nvc,\n get(A.fop_C), A.fop_A, A.fop_T, A.fop,\n A.iop_C, A.iop_A, A.iop_T, A.iop,\n A.PAs_out, A.gclean\n )\nconj(A::joDAgatheringLinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDAgatheringLinearOperator{DDT,RDT,N}(\"conj(\"*A.name*\")\",A.m,A.n,A.nvc,\n get(A.fop_C), A.fop_A, A.fop_T, A.fop,\n A.iop_C, A.iop_A, A.iop_T, A.iop,\n A.PAs_in, A.gclean\n )\n\n# transpose(jo)\ntranspose(A::joDALinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDALinearOperator{RDT,DDT,N}(\"transpose(\"*A.name*\")\",A.n,A.m,A.nvc,\n get(A.fop_T), A.fop, A.fop_C, A.fop_A,\n A.iop_T, A.iop, A.iop_C, A.iop_A,\n A.PAs_out, A.PAs_in, A.rclean, A.fclean\n )\ntranspose(A::joDAdistributedLinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDAdistributedLinearOperator{RDT,DDT,N}(\"transpose(\"*A.name*\")\",A.n,A.m,A.nvc,\n get(A.fop_T), A.fop, A.fop_C, A.fop_A,\n A.iop_T, A.iop, A.iop_C, A.iop_A,\n A.PAs_out, A.PAs_in, A.rclean, A.fclean\n )\ntranspose(A::joDAdistributingLinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDAgatheringLinearOperator{RDT,DDT,N}(\"transpose(\"*A.name*\")\",A.n,A.m,A.nvc,\n get(A.fop_T), A.fop, A.fop_C, A.fop_A,\n A.iop_T, A.iop, A.iop_C, A.iop_A,\n A.PAs_out, A.gclean\n )\ntranspose(A::joDAgatheringLinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDAdistributingLinearOperator{RDT,DDT,N}(\"transpose(\"*A.name*\")\",A.n,A.m,A.nvc,\n get(A.fop_T), A.fop, A.fop_C, A.fop_A,\n A.iop_T, A.iop, A.iop_C, A.iop_A,\n A.PAs_in, A.gclean\n )\n\n# adjoint(jo)\nadjoint(A::joDALinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDALinearOperator{RDT,DDT,N}(\"adjoint(\"*A.name*\")\",A.n,A.m,A.nvc,\n get(A.fop_A), A.fop_C, A.fop, A.fop_T,\n A.iop_A, A.iop_C, A.iop, A.iop_T,\n A.PAs_out, A.PAs_in, A.rclean, A.fclean\n )\nadjoint(A::joDAdistributedLinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDAdistributedLinearOperator{RDT,DDT,N}(\"adjoint(\"*A.name*\")\",A.n,A.m,A.nvc,\n get(A.fop_A), A.fop_C, A.fop, A.fop_T,\n A.iop_A, A.iop_C, A.iop, A.iop_T,\n A.PAs_out, A.PAs_in, A.rclean, A.fclean\n )\nadjoint(A::joDAdistributingLinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDAgatheringLinearOperator{RDT,DDT,N}(\"adjoint(\"*A.name*\")\",A.n,A.m,A.nvc,\n get(A.fop_A), A.fop_C, A.fop, A.fop_T,\n A.iop_A, A.iop_C, A.iop, A.iop_T,\n A.PAs_out, A.gclean\n )\nadjoint(A::joDAgatheringLinearOperator{DDT,RDT,N}) where {DDT,RDT,N} =\n joDAdistributingLinearOperator{RDT,DDT,N}(\"adjoint(\"*A.name*\")\",A.n,A.m,A.nvc,\n get(A.fop_A), A.fop_C, A.fop, A.fop_T,\n A.iop_A, A.iop_C, A.iop, A.iop_T,\n A.PAs_in, A.gclean\n )\n\n# isreal(jo)\nisreal(A :: joAbstractDAparallelLinearOperator{DDT,RDT}) where {DDT,RDT} = (DDT<:Real && RDT<:Real)\n\n# issymmetric(jo)\n\n# ishermitian(jo)\n\n# getindex(jo,...)\n\n############################################################\n## overloaded Base *(...jo...)\n\n# *(jo,jo)\nfunction *(A::joDALinOpsUnion{CDT,ARDT,2},B::joDALinOpsUnion{BDDT,CDT,2}) where {ARDT,BDDT,CDT}\n size(A,2) == size(B,1) || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): shape mismatch\"))\n A.nvc==B.nvc || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): nvc mismatch\"))\n isapprox(A.PAs_in,B.PAs_out) || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): distributor mismatch\"))\n return joDALinearOperator{BDDT,ARDT,2}(\"($(A.name)*$(B.name))\",size(A,1),size(B,2),A.nvc,\n v1->A*(B*v1),\n v2->transpose(B)*(transpose(A)*v2),\n v3->adjoint(B)*(adjoint(A)*v3),\n v4->conj(A)*(conj(B)*v4),\n @joNF, @joNF, @joNF, @joNF,\n B.PAs_in,A.PAs_out,B.fclean,A.rclean)\nend\nfunction *(A::joDALinOpsUnion{CDT,ARDT,2},B::joDAdistributeLinOpsUnion{BDDT,CDT,2}) where {ARDT,BDDT,CDT}\n size(A,2) == size(B,1) || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): shape mismatch\"))\n A.nvc==B.nvc || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): nvc mismatch\"))\n isapprox(A.PAs_in,B.PAs_out) || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): distributor mismatch\"))\n return joDAdistributingLinearOperator{BDDT,ARDT,2}(\"($(A.name)*$(B.name))\",size(A,1),size(B,2),A.nvc,\n v1->A*(B*v1),\n v2->transpose(B)*(transpose(A)*v2),\n v3->adjoint(B)*(adjoint(A)*v3),\n v4->conj(A)*(conj(B)*v4),\n @joNF, @joNF, @joNF, @joNF,\n A.PAs_out,B.gclean)\nend\nfunction *(A::joDAgatherLinOpsUnion{CDT,ARDT,2},B::joDALinOpsUnion{BDDT,CDT,2}) where {ARDT,BDDT,CDT}\n size(A,2) == size(B,1) || throw(joDAgatheringLinearOperatorException(\"*($(A.name),$(B.name)): shape mismatch\"))\n A.nvc==B.nvc || throw(joDAgatheringLinearOperatorException(\"*($(A.name),$(B.name)): nvc mismatch\"))\n isapprox(A.PAs_in,B.PAs_out) || throw(joDAgatheringLinearOperatorException(\"*($(A.name),$(B.name)): distributor mismatch\"))\n return joDAgatheringLinearOperator{BDDT,ARDT,2}(\"($(A.name)*$(B.name))\",size(A,1),size(B,2),A.nvc,\n v1->A*(B*v1),\n v2->transpose(B)*(transpose(A)*v2),\n v3->adjoint(B)*(adjoint(A)*v3),\n v4->conj(A)*(conj(B)*v4),\n @joNF, @joNF, @joNF, @joNF,\n B.PAs_in,B.fclean)\nend\nfunction *(A::joDAdistributeLinOpsUnion{CDT,ARDT,2},B::joDAgatherLinOpsUnion{BDDT,CDT,2}) where {ARDT,BDDT,CDT}\n size(A,2) == size(B,1) || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): shape mismatch\"))\n A.nvc==B.nvc || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): nvc mismatch\"))\n return joDALinearOperator{BDDT,ARDT,2}(\"($(A.name)*$(B.name))\",size(A,1),size(B,2),A.nvc,\n v1->A*(B*v1),\n v2->transpose(B)*(transpose(A)*v2),\n v3->adjoint(B)*(adjoint(A)*v3),\n v4->conj(A)*(conj(B)*v4),\n @joNF, @joNF, @joNF, @joNF,\n B.PAs_in,A.PAs_out,B.gclean,A.gclean)\nend\nfunction *(A::joDAgatherLinOpsUnion{CDT,ARDT,2},B::joDAdistributeLinOpsUnion{BDDT,CDT,2}) where {ARDT,BDDT,CDT}\n size(A,2) == size(B,1) || throw(joLinearOperatorException(\"*($(A.name),$(B.name)): shape mismatch\"))\n A.nvc==B.nvc || throw(joLinearOperatorException(\"*($(A.name),$(B.name)): nvc mismatch\"))\n isapprox(A.PAs_in,B.PAs_out) || throw(joLinearOperatorException(\"*($(A.name),$(B.name)): distributor mismatch\"))\n return joLinearOperator{BDDT,ARDT}(\"($(A.name)*$(B.name))\",size(A,1),size(B,2),\n v1->A*(B*v1),\n v2->transpose(B)*(transpose(A)*v2),\n v3->adjoint(B)*(adjoint(A)*v3),\n v4->conj(A)*(conj(B)*v4),\n @joNF, @joNF, @joNF, @joNF)\nend\n# extras with warnings\nfunction *(A::joDAdistribute{CDT,ARDT,2},B::joDAgather{BDDT,CDT,2}) where {ARDT,BDDT,CDT}\n size(A,2) == size(B,1) || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): shape mismatch\"))\n A.PAs_out.dims[2]==B.PAs_in.dims[2] || throw(joDALinearOperatorException(\"*($(A.name),$(B.name)): nvc mismatch\"))\n @warn \"*($(typeof(A)),$(typeof(B))) is a senseless operation. Get rid of it!\"\n return joDALinearOperator{BDDT,ARDT,2}(\"($(A.name)*$(B.name))\",size(A,1),size(B,2),A.PAs_out.dims[2],\n v1->v1, v2->v2, v3->v3, v4->v4,\n @joNF, @joNF, @joNF, @joNF,\n B.PAs_in,A.PAs_out,B.gclean,A.gclean)\nend\nfunction *(A::joDAgather{CDT,ARDT,2},B::joDAdistribute{BDDT,CDT,2}) where {ARDT,BDDT,CDT}\n size(A,2) == size(B,1) || throw(joLinearOperatorException(\"*($(A.name),$(B.name)): shape mismatch\"))\n A.PAs_in.dims[2]==B.PAs_out.dims[2] || throw(joLinearOperatorException(\"*($(A.name),$(B.name)): nvc mismatch\"))\n isapprox(A.PAs_in,B.PAs_out) || throw(joLinearOperatorException(\"*($(A.name),$(B.name)): distributor mismatch\"))\n @warn \"*($(typeof(A)),$(typeof(B))) is a senseless operation. Get rid of it!\"\n return joLinearOperator{BDDT,ARDT}(\"($(A.name)*$(B.name))\",size(A,1),size(B,2),\n v1->v1, v2->v2, v3->v3, v4->v4,\n @joNF, @joNF, @joNF, @joNF)\nend\n# joDA with joAbstractLinearOperator\nfunction *(A::joDAdistributeLinOpsUnion{CDT,ARDT,2},B::joAbstractLinearOperator{BDDT,CDT}) where {ARDT,BDDT,CDT}\n size(A,2) == size(B,1) || throw(joAbstractLinearOperatorException(\"*($(A.name),$(B.name)): shape mismatch\"))\n return joDAdistributingLinearOperator{BDDT,ARDT,2}(\"($(A.name)*$(B.name))\",size(A,1),size(B,2),A.nvc,\n v1->A*(B*v1),\n v2->transpose(B)*(transpose(A)*v2),\n v3->adjoint(B)*(adjoint(A)*v3),\n v4->conj(A)*(conj(B)*v4),\n @joNF, @joNF, @joNF, @joNF,\n A.PAs_out,A.gclean)\nend\nfunction *(A::joAbstractLinearOperator{CDT,ARDT},B::joDAgatherLinOpsUnion{BDDT,CDT,2}) where {ARDT,BDDT,CDT}\n size(A,2) == size(B,1) || throw(joAbstractLinearOperatorException(\"*($(A.name),$(B.name)): shape mismatch\"))\n return joDAgatheringLinearOperator{BDDT,ARDT,2}(\"($(A.name)*$(B.name))\",size(A,1),size(B,2),B.nvc,\n v1->A*(B*v1),\n v2->transpose(B)*(transpose(A)*v2),\n v3->adjoint(B)*(adjoint(A)*v3),\n v4->conj(A)*(conj(B)*v4),\n @joNF, @joNF, @joNF, @joNF,\n B.PAs_in,B.gclean)\nend\n\n# *(jo,mvec)\nfunction *(A::joDALinearOperator{ADDT,ARDT,2},mv::DArray{mvDT,2}) where {ADDT,ARDT,mvDT<:Number}\n A.n == size(mv,1) || throw(joDALinearOperatorException(\"shape mismatch\"))\n A.nvc == size(mv,2) || throw(joDALinearOperatorException(\"shape mismatch\"))\n jo_check_type_match(ADDT,mvDT,join([\"DDT for *(jo,mvec):\",A.name,typeof(A),mvDT],\" / \"))\n isequiv(A.PAs_in,mv) || throw(joDALinearOperatorException(\"*($(A.name),mv::DArray): input distributor mismatch\"))\n MV=A.fop(mv)\n jo_check_type_match(ARDT,eltype(MV),join([\"RDT from *(jo,mvec):\",A.name,typeof(A),eltype(MV)],\" / \"))\n return MV\nend\nfunction *(A::joDAdistributedLinearOperator{ADDT,ARDT,2},mv::DArray{mvDT,2}) where {ADDT,ARDT,mvDT<:Number}\n A.n == size(mv,1) || throw(joDAdistributedLinearOperatorException(\"shape mismatch\"))\n A.nvc == size(mv,2) || throw(joDAdistributedLinearOperatorException(\"shape mismatch\"))\n jo_check_type_match(ADDT,mvDT,join([\"DDT for *(jo,mvec):\",A.name,typeof(A),mvDT],\" / \"))\n isequiv(A.PAs_in,mv) || throw(joDAdistributedLinearOperatorException(\"*($(A.name),mv::DArray): input distributor mismatch\"))\n MV=dalloc(A.PAs_out)\n spmd(joDAutils.jo_x_mv!,A.fop,mv,MV,pids=A.PAs_out.procs)\n jo_check_type_match(ARDT,eltype(MV),join([\"RDT from *(jo,mvec):\",A.name,typeof(A),eltype(MV)],\" / \"))\n return MV\nend\nfunction *(A::joDAdistributingLinearOperator{ADDT,ARDT,2},mv::LocalMatrix{mvDT}) where {ADDT,ARDT,mvDT<:Number}\n A.n == size(mv,1) || throw(joDAdistributingLinearOperatorException(\"shape mismatch in A$(size(A))*v$(size(mv))\"))\n A.nvc == size(mv,2) || throw(joDAdistributingLinearOperatorException(\"nvc size mismatch\"))\n jo_check_type_match(ADDT,mvDT,join([\"DDT for *(jo,mvec):\",A.name,typeof(A),mvDT],\" / \"))\n MV = A.fop(mv)\n jo_check_type_match(ARDT,eltype(MV),join([\"RDT from *(jo,mvec):\",A.name,typeof(A),eltype(MV)],\" / \"))\n return MV\nend\nfunction *(A::joDAgatheringLinearOperator{ADDT,ARDT,2},mv::DArray{mvDT,2}) where {ADDT,ARDT,mvDT<:Number}\n A.n == size(mv,1) || throw(joDAgatheringLinearOperatorException(\"shape mismatch in A$(size(A))*v$(size(mv))\"))\n A.nvc == size(mv,2) || throw(joDAgatheringLinearOperatorException(\"nvc size mismatch\"))\n jo_check_type_match(ADDT,mvDT,join([\"DDT for *(jo,mvec):\",A.name,typeof(A),mvDT],\" / \"))\n isequiv(A.PAs_in,mv) || throw(joDAgatheringLinearOperatorException(\"*($(A.name),mv::DArray): input distributor mismatch\"))\n MV = A.fop(mv)\n jo_check_type_match(ARDT,eltype(MV),join([\"RDT from *(jo,mvec):\",A.name,typeof(A),eltype(MV)],\" / \"))\n return MV\nend\n\n# *(mvec,jo)\n\n# *(jo,vec)\n\n# *(vec,jo)\n\n# *(num,jo)\n\n# *(jo,num)\n\n############################################################\n## overloaded Base \\(...jo...)\n\n# \\(jo,jo)\n\n# \\(jo,mvec)\n\n# \\(mvec,jo)\n\n# \\(jo,vec)\n\n# \\(vec,jo)\n\n# \\(num,jo)\n\n# \\(jo,num)\n#\\{ADDT,ARDT}(A::joAbstractDAparallelLinearOperator{ADDT,ARDT},a::Number) = inv(a)*A\n#\\{ADDT,ARDT}(A::joAbstractDAparallelLinearOperator{ADDT,ARDT},a::joNumber{ADDT,ARDT}) = inv(a)*A\n\n############################################################\n## overloaded Base +(...jo...)\n\n# +(jo)\n+(A::joAbstractDAparallelLinearOperator) = A\n\n# +(jo,jo)\n\n# +(jo,mvec)\n\n# +(mvec,jo)\n\n# +(jo,vec)\n\n# +(vec,jo)\n\n# +(jo,num)\n\n# +(num,jo)\n+(b::Number,A::joAbstractDAparallelLinearOperator{ADDT,ARDT}) where {ADDT,ARDT} = A+b\n+(b::joNumber{ADDT,ARDT},A::joAbstractDAparallelLinearOperator{ADDT,ARDT}) where {ADDT,ARDT} = A+b\n\n############################################################\n## overloaded Base -(...jo...)\n\n# -(jo)\n\n# -(jo,jo)\n-(A::joAbstractDAparallelLinearOperator,B::joAbstractDAparallelLinearOperator) = A+(-B)\n\n# -(jo,mvec)\n\n# -(mvec,jo)\n\n# -(jo,vec)\n\n# -(vec,jo)\n\n# -(jo,num)\n-(A::joAbstractDAparallelLinearOperator,b::Number) = A+(-b)\n-(A::joAbstractDAparallelLinearOperator,b::joNumber) = A+(-b)\n\n# -(num,jo)\n-(b::Number,A::joAbstractDAparallelLinearOperator) = -A+b\n-(b::joNumber,A::joAbstractDAparallelLinearOperator) = -A+b\n\n############################################################\n## overloaded Base .*(...jo...)\n\n# .*(num,jo)\nBase.Broadcast.broadcasted(::typeof(*),a::Number,A::joAbstractDAparallelLinearOperator) = a*A\nBase.Broadcast.broadcasted(::typeof(*),a::joNumber,A::joAbstractDAparallelLinearOperator) = a*A\n\n# .*(jo,num)\nBase.Broadcast.broadcasted(::typeof(*),A::joAbstractDAparallelLinearOperator,a::Number) = a*A\nBase.Broadcast.broadcasted(::typeof(*),A::joAbstractDAparallelLinearOperator,a::joNumber) = a*A\n\n############################################################\n## overloaded Base .\\(...jo...)\n\n############################################################\n## overloaded Base .+(...jo...)\n\n# .+(jo,num)\nBase.Broadcast.broadcasted(::typeof(+),A::joAbstractDAparallelLinearOperator,b::Number) = A+b\nBase.Broadcast.broadcasted(::typeof(+),A::joAbstractDAparallelLinearOperator,b::joNumber) = A+b\n\n# .+(num,jo)\nBase.Broadcast.broadcasted(::typeof(+),b::Number,A::joAbstractDAparallelLinearOperator) = A+b\nBase.Broadcast.broadcasted(::typeof(+),b::joNumber,A::joAbstractDAparallelLinearOperator) = A+b\n\n############################################################\n## overloaded Base .-(...jo...)\n\n# .-(jo,num)\nBase.Broadcast.broadcasted(::typeof(-),A::joAbstractDAparallelLinearOperator,b::Number) = A+(-b)\nBase.Broadcast.broadcasted(::typeof(-),A::joAbstractDAparallelLinearOperator,b::joNumber) = A+(-b)\n\n# .-(num,jo)\nBase.Broadcast.broadcasted(::typeof(-),b::Number,A::joAbstractDAparallelLinearOperator) = -A+b\nBase.Broadcast.broadcasted(::typeof(-),b::joNumber,A::joAbstractDAparallelLinearOperator) = -A+b\n\n############################################################\n## overloaded Base block methods\n\n# hcat(...jo...)\n\n# vcat(...jo...)\n\n# hvcat(...jo...)\n\n############################################################\n## overloaded LinearAlgebra functions\n\n# mul!(...,jo,...)\n\n# ldiv!(...,jo,...)\n\n", "meta": {"hexsha": "0afc90fdb563060743e5dc466654569f246b1ca2", "size": 17185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/joAbstractDAparallelLinearOperator/base_functions.jl", "max_stars_repo_name": "slimgroup/JOLI.jl", "max_stars_repo_head_hexsha": "c1f669e34353394fd9a4711dc0038cf697bc0ad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-02-28T21:50:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T16:03:45.000Z", "max_issues_repo_path": "src/joAbstractDAparallelLinearOperator/base_functions.jl", "max_issues_repo_name": "slimgroup/JOLI.jl", "max_issues_repo_head_hexsha": "c1f669e34353394fd9a4711dc0038cf697bc0ad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-08-03T21:02:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T20:17:27.000Z", "max_forks_repo_path": "src/joAbstractDAparallelLinearOperator/base_functions.jl", "max_forks_repo_name": "slimgroup/JOLI.jl", "max_forks_repo_head_hexsha": "c1f669e34353394fd9a4711dc0038cf697bc0ad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-11-11T02:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-05T16:06:20.000Z", "avg_line_length": 42.0171149144, "max_line_length": 128, "alphanum_fraction": 0.6082630201, "num_tokens": 5759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24444867830982878}} {"text": "export flow, flowdθ, flowdσ, flowdψ, STARTING_σ_ψ, STARTING_log_ogip, STARTING_t\n\nconst STARTING_σ_ψ = 0x1.baddbb87af68ap-2 # = 0.432\nconst STARTING_log_ogip = 0x1.670bf3d5b282dp-1 # = 0.701\nconst STARTING_t = 2*0.042/(2016-2003)\n\n# functions in case we have months to expiration\n@inline flow( FF::Type, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, d1::Integer, Dgt0::Bool, sgn_ext::Bool, τ::Real, geoid::Real, roy::T) where {N,T} = flow( FF, θ, σ, z, ψ, d, d1, Dgt0, sgn_ext, geoid, roy)\n@inline flowdθ(FF::Type, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, k::Integer, d::Integer, d1::Integer, Dgt0::Bool, sgn_ext::Bool, τ::Real, geoid::Real, roy::T) where {N,T} = flowdθ(FF, θ, σ, z, ψ, k, d, d1, Dgt0, sgn_ext, geoid, roy)\n@inline flowdσ(FF::Type, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, d1::Integer, Dgt0::Bool, sgn_ext::Bool, τ::Real, geoid::Real, roy::T) where {N,T} = flowdσ(FF, θ, σ, z, ψ, d, geoid, roy)\n@inline flowdψ(FF::Type, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, sgn_ext::Bool, τ::Real, geoid::Real, roy::T) where {N,T} = flowdψ(FF, θ, σ, z, ψ, d, sgn_ext, geoid, roy)\n@inline flowdψ(FF::Type, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, d1::Integer, Dgt0::Bool, sgn_ext::Bool, τ::Real, geoid::Real, roy::T) where {N,T} = flowdψ(FF, θ, σ, z, ψ, d, sgn_ext, geoid, roy)\n\n@inline flowdσ(FF::Type, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T) where {N,T} = flowdσ(FF, θ, σ, z, ψ, d, geoid, roy)\n\n\n# functions in case we have months to expiration\n@inline flow( FF::Type, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T) where {N,T} = flow( FF, θ, σ, z, ψ, d, _d1(wp,i), _Dgt0(wp,i), _sgnext(wp,i), geoid, roy)\n@inline flowdθ(FF::Type, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, k::Integer, d::Integer, geoid::Real, roy::T) where {N,T} = flowdθ(FF, θ, σ, z, ψ, k, d, _d1(wp,i), _Dgt0(wp,i), _sgnext(wp,i), geoid, roy)\n@inline flowdσ(FF::Type, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T) where {N,T} = flowdσ(FF, θ, σ, z, ψ, d, geoid, roy)\n@inline flowdψ(FF::Type, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T) where {N,T} = flowdψ(FF, θ, σ, z, ψ, d, _sgnext(wp,i), geoid, roy)\n\n# @inline function flowdθ(::Type, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, k::Integer, d::Integer, d1::Integer, Dgt0::Bool, sgn_ext::Bool, geoid::Real, roy::T)::T where {N,T}\n\n# --------------------------- common revenue functions & derivatives --------------------------------------\n\n@inline rev_exp_restricted(θ1::T, σ::T, logp::Real, ψ::Real, Dgt0::Bool, geoid::Real, roy::Real) where {T} = rev_exp( 1, θ1, 1, STARTING_log_ogip, STARTING_σ_ψ, σ, logp, ψ, Dgt0, geoid, roy)\n@inline drevdσ_exp_restricted(θ1::T, σ::T, logp::Real, ψ::Real, geoid::Real, roy::Real) where {T} = drevdσ_exp(1, θ1, 1, STARTING_log_ogip, STARTING_σ_ψ, σ, logp, ψ, geoid, roy)\n@inline drevdψ_exp_restricted(θ1::T, σ::T, logp::Real, ψ::Real, geoid::Real, roy::Real) where {T} = drevdψ_exp(1, θ1, 1, STARTING_log_ogip, STARTING_σ_ψ, σ, logp, ψ, geoid, roy)\n\n@inline rev_exp_restricted(θ1::T, σ::T, logp::Real, t::Real, ψ::Real, Dgt0::Bool, geoid::Real, roy::Real) where {T} = rev_exp( 1, θ1, 1, STARTING_log_ogip, STARTING_σ_ψ, STARTING_t, σ, logp, t, ψ, Dgt0, geoid, roy)\n@inline drevdσ_exp_restricted(θ1::T, σ::T, logp::Real, t::Real, ψ::Real, geoid::Real, roy::Real) where {T} = drevdσ_exp(1, θ1, 1, STARTING_log_ogip, STARTING_σ_ψ, STARTING_t, σ, logp, t, ψ, geoid, roy)\n@inline drevdψ_exp_restricted(θ1::T, σ::T, logp::Real, t::Real, ψ::Real, geoid::Real, roy::Real) where {T} = drevdψ_exp(1, θ1, 1, STARTING_log_ogip, STARTING_σ_ψ, STARTING_t, σ, logp, t, ψ, geoid, roy)\n\n# chebshev polynomials\n# See http://www.aip.de/groups/soe/local/numres/bookcpdf/c5-8.pdf\n@inline checkinterval(x::Real,min::Real,max::Real) = min <= x <= max || throw(DomainError(\"x = $x must be in [$min,$max]\"))\n@inline checkinterval(x::Real) = checkinterval(x,-1,1)\n@inline cheb0(x::Real) = (checkinterval(x); return one(Float64))\n@inline cheb1(x::Real) = (checkinterval(x); return x)\n@inline cheb2(x::Real) = (checkinterval(x); return 2*x^2 - 1)\n@inline cheb3(x::Real) = (checkinterval(x); return 4*x^3 - 3*x)\n@inline cheb4(x::Real) = (checkinterval(x); return 8*(x^4 - x^2) + 1)\n\n# -----------------------------------------\n# Flows\n# -----------------------------------------\n\ninclude(\"flow-payoffs-more.jl\")\n\n@inline function flow(::Type{Val{:cheb3_cost_tech}}, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T) where {N,T}\n# @inline function flow(::Type{Val{:cheb3_cost_tech}}, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, d1::Integer, Dgt0::Bool, sgn_ext::Bool, geoid::Real, roy::T) where {N,T}\n if d == 0\n _sgnext(wp,i) && return θ[11]\n return zero(T)\n end\n logp, logc, t = z\n u = rev_exp(1,θ[1],1,θ[2],θ[3],θ[4],σ, logp, t, ψ, _Dgt0(wp,i), geoid,roy) + (d==1 ? θ[5] : θ[6] )*cheb0(t) + θ[7]*cheb1(t) + θ[8]*cheb2(t) + θ[9]*cheb3(t) + θ[10]*exp(logc)\n d>1 && (u *= d)\n return u::T\nend\n\n@inline function flow(::Type{Val{:cheb3_cost_tech_restr}}, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, d1::Integer, Dgt0::Bool, sgn_ext::Bool, geoid::Real, roy::T) where {N,T}\n if d == 0\n sgn_ext && return θ[8]\n return zero(T)\n end\n logp, logc, t = z\n u = rev_exp_restricted(θ[1], σ, logp, t, ψ, Dgt0, geoid, roy) + (d==1 ? θ[2] : θ[3] )*cheb0(t) + θ[4]*cheb1(t) + θ[5]*cheb2(t) + θ[6]*cheb3(t) + θ[7]*exp(logc)\n d>1 && (u *= d)\n return u::T\nend\n\n\n# -----------------------------------------\n# number of parms\n# -----------------------------------------\n\nfunction number_of_model_parms(FF::Symbol)::Int\n FF ∈ (:one_restr,) && return 3\n FF ∈ (:dgt1_restr,:Dgt0_restr,) && return 4\n FF ∈ (:one,:dgt1_ext_restr, :dgt1_d1_restr,:dgt1_cost_restr,:cheb2_restr) && return 5\n FF ∈ (:dgt1,:Dgt0,:dgt1_cost_Dgt0_restr,:dgt1_pricecost_restr,:cheb3_restr) && return 6\n FF ∈ (:dgt1_ext,:dgt1_d1,:dgt1_cost,:dgt1_pricebreak_restr,:cheb2, :cheb3_dgt1_restr,) && return 7\n FF ∈ (:dgt1_cost_Dgt0,:dgt1_pricecost,:cheb3,:cheb3_cost_restr,:ttbuild_cost_restr,:cheb3_cost_tech_restr,) && return 8\n FF ∈ (:dgt1_pricebreak,:cheb3_dgt1,) && return 9\n FF ∈ (:cheb3_cost,:ttbuild_cost,) && return 10\n FF ∈ (:cheb3_cost_tech,) && return 11\n throw(error(\"FF = $(FF) not recognized\"))\nend\n\n# -----------------------------------------\n# dθ\n# -----------------------------------------\n\n@inline function flowdθ(::Type{Val{:cheb3_cost_tech}}, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, k::Integer, d::Integer, geoid::Real, roy::T) where {N,T}\n# @inline function flowdθ(::Type{Val{:cheb3_cost_tech}}, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, k::Integer,d::Integer, d1::Integer, Dgt0::Bool, sgn_ext::Bool, geoid::Real, roy::T)::T where {N,T}\n d == 0 && !_sgnext(wp,i) && return zero(T)\n Dgt0 = _Dgt0(wp,i)\n logp, logc, t = z\n\n # revenue\n k == 1 && return d * rev_exp(1,θ[1],1,θ[2],θ[3],θ[4],σ,logp,t,ψ,Dgt0,geoid,roy)\n k == 2 && return d * rev_exp(1,θ[1],1,θ[2],θ[3],θ[4],σ,logp,t,ψ,Dgt0,geoid,roy) * geoid\n k == 3 && return d * rev_exp(1,θ[1],1,θ[2],θ[3],θ[4],σ,logp,t,ψ,Dgt0,geoid,roy) * ( Dgt0 ? ψ : ψ*_ρ(σ) + θ[k]*(1-_ρ2(σ)))\n k == 4 && return d * rev_exp(1,θ[1],1,θ[2],θ[3],θ[4],σ,logp,t,ψ,Dgt0,geoid,roy) * t\n\n # drilling cost\n k == 5 && return d != 1 ? zero(T) : T( cheb0(t) )\n k == 6 && return d <= 1 ? zero(T) : T( d*cheb0(t) )\n k == 7 && return d == 0 ? zero(T) : T( d*cheb1(t) )\n k == 8 && return d == 0 ? zero(T) : T( d*cheb2(t) )\n k == 9 && return d == 0 ? zero(T) : T( d*cheb3(t) )\n k == 10 && return d == 0 ? zero(T) : T( d*exp(logc) )\n\n # extension cost\n k == 11 && return d == 0 && _sgnext(wp,i) ? one(T) : zero(T)\n\n throw(error(\"$k out of bounds\"))\nend\n\n\n\n@inline function flowdθ(::Type{Val{:cheb3_cost_tech_restr}}, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, k::Integer,d::Integer, d1::Integer, Dgt0::Bool, sgn_ext::Bool, geoid::Real, roy::T)::T where {N,T}\n d == 0 && !sgn_ext && return zero(T)\n\n logp, logc, t = z\n\n # revenue\n k == 1 && return d * rev_exp_restricted(θ[1], σ, logp, t, ψ, Dgt0, geoid, roy)\n\n # drilling cost\n k == 2 && return d != 1 ? zero(T) : T( cheb0(t) )\n k == 3 && return d <= 1 ? zero(T) : T( d*cheb0(t) )\n k == 4 && return d == 0 ? zero(T) : T( d*cheb1(t) )\n k == 5 && return d == 0 ? zero(T) : T( d*cheb2(t) )\n k == 6 && return d == 0 ? zero(T) : T( d*cheb3(t) )\n k == 7 && return d == 0 ? zero(T) : T( d*exp(logc) )\n # extension cost\n k == 8 && return d == 0 && sgn_ext ? one(T) : zero(T)\n\n throw(error(\"$k out of bounds\"))\nend\n\n# -----------------------------------------\n# dσ\n# -----------------------------------------\n\n\n@inline function flowdσ(::FF, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T)::T where {FF <: Union{ Type{Val{:one}}, Type{Val{:dgt1}}, Type{Val{:Dgt0}}, Type{Val{:dgt1_ext}}, Type{Val{:dgt1_d1}}, Type{Val{:dgt1_cost}}, Type{Val{:dgt1_cost_Dgt0}}, Type{Val{:cheb2}}, Type{Val{:cheb3}}, Type{Val{:cheb3_dgt1}}, Type{Val{:cheb3_cost}}, Type{Val{:ttbuild_cost}} }, N, T}\n d == 0 && return zero(T)\n return d * drevdσ_exp(1,θ[1],1,θ[2],θ[3],σ,z[1],ψ,geoid,roy)\nend\n\n\n@inline function flowdσ(::FF, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T)::T where {FF <: Union{ Type{Val{:one_restr}}, Type{Val{:dgt1_restr}}, Type{Val{:Dgt0_restr}}, Type{Val{:dgt1_ext_restr}}, Type{Val{:dgt1_d1_restr}}, Type{Val{:dgt1_cost_restr}}, Type{Val{:dgt1_cost_Dgt0_restr}}, Type{Val{:cheb2_restr}}, Type{Val{:cheb3_restr}}, Type{Val{:cheb3_dgt1_restr}}, Type{Val{:cheb3_cost_restr}}, Type{Val{:ttbuild_cost_restr}} },N, T}\n d == 0 && return zero(T)\n return d * drevdσ_exp_restricted(θ[1],σ,z[1],ψ,geoid,roy)\nend\n\n\n@inline function flowdσ(::FF, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T)::T where {FF <: Union{ Type{Val{:cheb3_cost_tech}} }, N, T}\n d == 0 && return zero(T)\n return d * drevdσ_exp(1,θ[1],1,θ[2],θ[3],θ[4],σ,first(z),last(z),ψ,geoid,roy)\nend\n\n\n@inline function flowdσ(::FF, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T)::T where {FF <: Union{ Type{Val{:cheb3_cost_tech_restr}} },N, T}\n d == 0 && return zero(T)\n return d * drevdσ_exp_restricted(θ[1],σ,first(z),last(z),ψ,geoid,roy)\nend\n\n\n# -----------------------------------------\n# dψ\n# -----------------------------------------\n\n@inline function flowdψ(::FF, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, sgn_ext::Bool, geoid::Real, roy::T) where {FF <: Union{ Type{Val{:one}}, Type{Val{:dgt1}}, Type{Val{:Dgt0}}, Type{Val{:dgt1_d1}}, Type{Val{:dgt1_cost}}, Type{Val{:dgt1_cost_Dgt0}}, Type{Val{:cheb2}}, Type{Val{:cheb3}}, Type{Val{:cheb3_dgt1}}, Type{Val{:cheb3_cost}}, Type{Val{:ttbuild_cost}} },N, T}\n d == 0 && return zero(T) # sgn_ext ? θ[10] : zero(T)\n return (d * drevdψ_exp(1,θ[1],1,θ[2],θ[3],σ,z[1],ψ,geoid,roy))::T\nend\n\n\n@inline function flowdψ(::FF, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, sgn_ext::Bool, geoid::Real, roy::T) where {FF <: Union{ Type{Val{:one_restr}}, Type{Val{:dgt1_restr}}, Type{Val{:Dgt0_restr}}, Type{Val{:dgt1_d1_restr}}, Type{Val{:dgt1_cost_restr}}, Type{Val{:dgt1_cost_Dgt0_restr}}, Type{Val{:cheb2_restr}}, Type{Val{:cheb3_restr}}, Type{Val{:cheb3_dgt1_restr}}, Type{Val{:cheb3_cost_restr}}, Type{Val{:ttbuild_cost_restr}} },N, T}\n d == 0 && return zero(T) # sgn_ext ? θ[10] : zero(T)\n return (d * drevdψ_exp_restricted(θ[1],σ,z[1],ψ,geoid,roy))::T\nend\n\n# @inline function flow( FF::Type, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T)\n# @inline function flowdθ(FF::Type, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, k::Integer, d::Integer, geoid::Real, roy::T)\n# @inline function flowdσ(FF::Type, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T)\n# @inline function flowdψ(FF::Type, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T)\n\n\n@inline function flowdψ(::FF, wp::AbstractUnitProblem, i::Integer, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, geoid::Real, roy::T) where {FF <: Union{ Type{Val{:cheb3_cost_tech}} }, N, T}\n d == 0 && return zero(T) # _sgnext(wp,i) ? θ[10] : zero(T)\n return (d * drevdψ_exp(1,θ[1],1,θ[2],θ[3],θ[4],σ,first(z),last(z),ψ,geoid,roy))::T\nend\n\n\n@inline function flowdψ(::FF, θ::AbstractVector{T}, σ::T, z::NTuple{N,T}, ψ::T, d::Integer, sgn_ext::Bool, geoid::Real, roy::T) where {FF <: Union{ Type{Val{:cheb3_cost_tech_restr}} }, N, T}\n d == 0 && return zero(T) # sgn_ext ? θ[10] : zero(T)\n return (d * drevdψ_exp_restricted(θ[1],σ,first(z),last(z),ψ,geoid,roy))::T\nend\n", "meta": {"hexsha": "9a7bba0aa29a0329b512b546ca78221b4a158e7e", "size": 14187, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/flow-payoffs.jl", "max_stars_repo_name": "magerton/ShaleDrillingModel.jl", "max_stars_repo_head_hexsha": "25c8845309603fafb19f406a7b065496078f01f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-07T05:10:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-07T05:10:00.000Z", "max_issues_repo_path": "src/flow-payoffs.jl", "max_issues_repo_name": "magerton/ShaleDrillingModel.jl", "max_issues_repo_head_hexsha": "25c8845309603fafb19f406a7b065496078f01f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/flow-payoffs.jl", "max_forks_repo_name": "magerton/ShaleDrillingModel.jl", "max_forks_repo_head_hexsha": "25c8845309603fafb19f406a7b065496078f01f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-09-23T23:33:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T15:20:16.000Z", "avg_line_length": 69.2048780488, "max_line_length": 474, "alphanum_fraction": 0.5655177275, "num_tokens": 5656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24432942065783597}} {"text": "#=\n\nESSE wrapper\n\nIgnacio Quintero Mächler\n\nt(-_-t)\n\nSeptember 26 2017\n\n=#\n\n\n\n\n\n\"\"\"\n esse(states_file ::String,\n tree_file ::String,\n envdata_file::String,\n cov_mod ::NTuple{M,String},\n out_file ::String,\n h ::Int64;\n constraints ::NTuple{N,String} = (\" \",),\n mvpars ::NTuple{O,String} = (\"lambda = beta\",),\n niter ::Int64 = 10_000,\n nthin ::Int64 = 10,\n nburn ::Int64 = 200,\n nchains ::Int64 = 1,\n ntakew ::Int64 = 100,\n winit ::Float64 = 2.0,\n scale_y ::NTuple{2,Bool} = (true, false),\n algorithm ::String = \"pruning\",\n λpriors ::Float64 = .1,\n μpriors ::Float64 = .1,\n gpriors ::Float64 = .1,\n lpriors ::Float64 = .1,\n qpriors ::Float64 = .1,\n βpriors ::NTuple{2,Float64} = (0.0, 10.0),\n hpriors ::Float64 = .1,\n optimal_w ::Float64 = 0.8,\n screen_print::Int64 = 5,\n Eδt ::Float64 = 1e-3,\n ti ::Float64 = 0.0,\n ρ ::Array{Float64,1} = [1.0]) where {M,N,O}\n\nWrapper for running a SSE model from file.\n\"\"\"\nfunction esse(states_file ::String,\n tree_file ::String,\n envdata_file::String,\n cov_mod ::NTuple{M,String},\n out_file ::String,\n h ::Int64;\n constraints ::NTuple{N,String} = (\" \",),\n mvpars ::NTuple{O,String} = (\"lambda = beta\",),\n niter ::Int64 = 10_000,\n nthin ::Int64 = 10,\n nburn ::Int64 = 200,\n nchains ::Int64 = 1,\n ntakew ::Int64 = 100,\n winit ::Float64 = 2.0,\n scale_y ::NTuple{2,Bool} = (true, false),\n algorithm ::String = \"pruning\",\n λpriors ::Float64 = .1,\n μpriors ::Float64 = .1,\n gpriors ::Float64 = .1,\n lpriors ::Float64 = .1,\n qpriors ::Float64 = .1,\n βpriors ::NTuple{2,Float64} = (0.0, 10.0),\n hpriors ::Float64 = .1,\n optimal_w ::Float64 = 0.8,\n screen_print::Int64 = 5,\n Eδt ::Float64 = 1e-3,\n ti ::Float64 = 0.0,\n ρ ::Array{Float64,1} = [1.0]) where {M,N,O}\n\n # read data \n tv, ed, el, bts, x, y = \n read_data_esse(states_file, tree_file, envdata_file)\n\n @info \"Data for $(length(tv)) species successfully read\"\n\n # scale y\n if scale_y[1]\n # if scale each function separately or together\n if scale_y[2]\n ymin = minimum(y)\n ymax = maximum(y)\n for j in axes(y,2), i in axes(y,1)\n y[i,j] = (y[i,j] - ymin)/(ymax - ymin)\n end\n else\n ymin = minimum(y, dims = 1)\n ymax = maximum(y, dims = 1)\n for j in axes(y,2), i in axes(y,1)\n y[i,j] = (y[i,j] - ymin[j])/(ymax[j] - ymin[j])\n end\n end\n end\n\n # prepare data\n X, p, fp, trios, ns, ned, pupd, phid, nnps, nps, mvps, nngps, mvhfs, \n dcp, dcfp, pardic, k, h, ny, model, af!, assign_hidfacs!, abts, bts, E0 = \n prepare_data(cov_mod, tv, x, y, ed, el, ρ, h, constraints, mvpars) \n\n @info \"Data successfully prepared\"\n\n ## make likelihood function\n # flow algorithm\n if occursin(r\"^[f|F][A-za-z]*\", algorithm) \n\n # prepare likelihood\n Gt, Et, lbts, nets, λevent!, rootll = \n prepare_ll(p, bts, E0, k, h, ny, ns, ned, model, Eδt, ti, abts, af!)\n\n # make likelihood function\n llf = make_loglik(Gt, Et, X, trios, lbts, bts, ns, ned, nets, \n λevent!, rootll)\n # prunning algorithm\n elseif occursin(r\"^[p|P][A-za-z]*\", algorithm)\n\n # prepare likelihood\n X, int, λevent!, rootll, abts1, abts2 = \n prepare_ll(X, p, E0, ns, k, h, ny, model, abts ,af!)\n\n # make likelihood function\n llf = make_loglik(X, abts1, abts2, trios, int, \n λevent!, rootll, k, h, ns, ned)\n\n else\n @error \"No matching likelihood for algorithm: $algorithm\"\n end\n\n # create prior function\n lpf = make_lpf(pupd, phid, \n λpriors, μpriors, gpriors, lpriors, qpriors, βpriors, hpriors, \n k, h, ny, model)\n\n # create posterior functions\n lhf = make_lhf(llf, lpf, assign_hidfacs!, dcp, dcfp)\n\n # number of parameters\n npars = length(pardic)\n\n # number of samples\n nlogs = fld(niter,nthin)\n\n # if parallel\n if nchains > 1\n # where to write in the Shared Array\n cits = [(1+j):(nlogs+j) for j in 0:nlogs:(nchains-1)*nlogs]\n\n # run slice-sampling in parallel\n R = SharedArray{Float64,2}(nlogs*nchains, npars+2)\n\n # run parallel loop\n @sync @distributed for ci in Base.OneTo(nchains)\n R[cits[ci],:] = \n slice_sampler(lhf, p, fp, nnps, nps, phid, mvps, nngps, mvhfs, npars, \n niter, nthin, nburn, ntakew, winit, optimal_w, screen_print)\n end\n\n # write output\n write_ssr(R, pardic, out_file, cits)\n else\n\n R = slice_sampler(lhf, p, fp, nnps, nps, phid, mvps, nngps, mvhfs, npars, \n niter, nthin, nburn, ntakew, winit, optimal_w, screen_print)\n\n # write output\n write_ssr(R, pardic, out_file)\n end\n\n return R\nend\n\n\n\n\n\n\"\"\"\n esse(tv ::Dict{Int64,Array{Float64,1}},\n ed ::Array{Int64,2}, \n el ::Array{Float64,1}, \n x ::Array{Float64,1},\n y ::Array{Float64,L}, \n cov_mod ::NTuple{M,String},\n out_file ::String,\n h ::Int64;\n constraints ::NTuple{N,String} = (\" \",),\n mvpars ::NTuple{O,String} = (\"lambda = beta\",),\n niter ::Int64 = 10_000,\n nthin ::Int64 = 10,\n nburn ::Int64 = 200,\n nchains ::Int64 = 1,\n ntakew ::Int64 = 100,\n winit ::Float64 = 2.0,\n scale_y ::NTuple{2,Bool} = (true, false),\n algorithm ::String = \"pruning\",\n λpriors ::Float64 = .1,\n μpriors ::Float64 = .1,\n gpriors ::Float64 = .1,\n lpriors ::Float64 = .1,\n qpriors ::Float64 = .1,\n βpriors ::NTuple{2,Float64} = (0.0, 10.0),\n hpriors ::Float64 = .1,\n optimal_w ::Float64 = 0.8,\n screen_print::Int64 = 5,\n Eδt ::Float64 = 1e-3,\n ti ::Float64 = 0.0,\n ρ ::Array{Float64,1} = [1.0]) where {L,M,N,O}\n\nWrapper for running a SSE model from simulations.\n\"\"\"\nfunction esse(tv ::Dict{Int64,Array{Float64,1}},\n ed ::Array{Int64,2}, \n el ::Array{Float64,1}, \n x ::Array{Float64,1},\n y ::Array{Float64,L}, \n cov_mod ::NTuple{M,String},\n out_file ::String,\n h ::Int64;\n constraints ::NTuple{N,String} = (\" \",),\n mvpars ::NTuple{O,String} = (\"lambda = beta\",),\n niter ::Int64 = 10_000,\n nthin ::Int64 = 10,\n nburn ::Int64 = 200,\n nchains ::Int64 = 1,\n ntakew ::Int64 = 100,\n winit ::Float64 = 2.0,\n scale_y ::NTuple{2,Bool} = (true, false),\n algorithm ::String = \"pruning\",\n λpriors ::Float64 = .1,\n μpriors ::Float64 = .1,\n gpriors ::Float64 = .1,\n lpriors ::Float64 = .1,\n qpriors ::Float64 = .1,\n βpriors ::NTuple{2,Float64} = (0.0, 10.0),\n hpriors ::Float64 = .1,\n optimal_w ::Float64 = 0.8,\n screen_print::Int64 = 5,\n Eδt ::Float64 = 1e-3,\n ti ::Float64 = 0.0,\n ρ ::Array{Float64,1} = [1.0]) where {L,M,N,O}\n\n # prepare data\n X, p, fp, trios, ns, ned, pupd, phid, nnps, nps, mvps, nngps, mvhfs, \n dcp, dcfp, pardic, k, h, ny, model, af!, assign_hidfacs!, abts, bts, E0 = \n prepare_data(cov_mod, tv, x, y, ed, el, ρ, h, constraints, mvpars) \n\n @info \"Data successfully prepared\"\n\n ## make likelihood function\n # flow algorithm\n if occursin(r\"^[f|F][A-za-z]*\", algorithm) \n\n # prepare likelihood\n Gt, Et, lbts, nets, λevent!, rootll = \n prepare_ll(p, bts, E0, k, h, ny, ns, ned, model, Eδt, ti, abts, af!)\n\n # make likelihood function\n llf = make_loglik(Gt, Et, X, trios, lbts, bts, ns, ned, nets, \n λevent!, rootll)\n # pruning algorithm\n elseif occursin(r\"^[p|P][A-za-z]*\", algorithm)\n\n # prepare likelihood\n X, int, λevent!, rootll, abts1, abts2 = \n prepare_ll(X, p, E0, ns, k, h, ny, model, abts ,af!)\n\n # make likelihood function\n llf = make_loglik(X, abts1, abts2, trios, int, \n λevent!, rootll, k, h, ns, ned)\n\n else\n @error \"No matching likelihood for algorithm: $algorithm\"\n end\n\n # create prior function\n lpf = make_lpf(pupd, phid, \n λpriors, μpriors, gpriors, lpriors, qpriors, βpriors, hpriors, \n k, h, ny, model)\n\n # create posterior functions\n lhf = make_lhf(llf, lpf, assign_hidfacs!, dcp, dcfp)\n\n # number of parameters\n npars = length(pardic)\n\n # number of samples\n nlogs = fld(niter,nthin)\n\n # if parallel\n if nchains > 1\n # where to write in the Shared Array\n cits = [(1+j):(nlogs+j) for j in 0:nlogs:(nchains-1)*nlogs]\n\n # run slice-sampling in parallel\n R = SharedArray{Float64,2}(nlogs*nchains, npars+2)\n\n # run parallel loop\n @sync @distributed for ci in Base.OneTo(nchains)\n R[cits[ci],:] = \n slice_sampler(lhf, p, fp, nnps, nps, phid, mvps, nngps, mvhfs, npars, \n niter, nthin, nburn, ntakew, winit, optimal_w, screen_print)\n end\n\n # write output\n write_ssr(R, pardic, out_file, cits)\n else\n\n R = slice_sampler(lhf, p, fp, nnps, nps, phid, mvps, nngps, mvhfs, npars, \n niter, nthin, nburn, ntakew, winit, optimal_w, screen_print)\n\n # write output\n write_ssr(R, pardic, out_file)\n end\n\n return R\nend\n\n\n\n\n\n\n\n\n\"\"\"\n read_data_esse(states_file ::String, \n tree_file ::String, \n envdata_file::String)\n\nProcess tree and state and environmental data file to run ESSE.\n\"\"\"\nfunction read_data_esse(states_file ::String, \n tree_file ::String, \n envdata_file::String)\n\n # read tree in postorder and assign to objects\n tree, bts = read_tree(tree_file, order = \"postorder\", branching_times = true)\n ntip = tree.nnod + 1\n ed = tree.ed\n el = tree.el\n tlab = tree.tlab\n\n # assign tip labels to edge numbers\n tip_labels = Dict{String,Integer}()\n ii = 0\n for i in Base.OneTo(size(ed,1))\n if ed[i,2] <= ntip\n ii += 1\n tip_labels[tlab[ii]] = ed[i,2]\n end\n end\n\n # read states text file\n data = readdlm(states_file)\n\n if size(data,1) != ntip\n data = readdlm(states_file, '\\t', '\\r')\n end\n\n if size(data,1) != ntip\n data = readdlm(states_file, '\\t', '\\n')\n end\n\n if size(data,1) != ntip \n error(\"Data file cannot be made of the right dimensions.\\n Make sure the data file has the same number of rows as tips in the tree\")\n end\n\n data_tlab = convert(Array{String,1}, data[:,1])\n data_states = convert(Array{Float64,2}, data[:,2:end])\n\n # create dictionary\n tip_states = Dict(tip_labels[val] => data_states[i,:] \n for (i,val) = enumerate(data_tlab))\n\n # process environmental data file\n envdata = readdlm(envdata_file)\n\n x = envdata[:,1]\n y = envdata[:,2:end]\n\n return tip_states, ed, el, bts, x, y\nend\n\n\n\n\n\n\"\"\"\n write_ssr(R ::Array{Float64,2}, \n pardic ::Dict{String,Int64},\n out_file::String)\n\nWrite the samples from an MC sampler data frame \ngiven a Dictionary of parameters.\n\"\"\"\nfunction write_ssr(R ::Array{Float64,2}, \n pardic ::Dict{String,Int64},\n out_file::String)\n\n # column names\n col_nam = [\"Iteration\", \"Posterior\"]\n\n for (k,v) in sort!(collect(pardic), by = x -> x[2])\n push!(col_nam, k)\n end\n\n R = vcat(reshape(col_nam, 1, lastindex(col_nam)), R)\n\n writedlm(out_file*\".log\", R)\nend\n\n\n\n\n\n\"\"\"\n write_ssr(R ::SharedArray{Float64,2}, \n pardic ::Dict{String,Int64},\n out_file::String,\n cits ::Array{UnitRange{Int64},1})\n\nWrite the samples from multiple chains of MC sampler data frame \ngiven a Dictionary of parameters.\n\"\"\"\nfunction write_ssr(R ::SharedArray{Float64,2}, \n pardic ::Dict{String,Int64},\n out_file::String,\n cits ::Array{UnitRange{Int64},1})\n\n # column names\n col_nam = [\"Iteration\", \"Posterior\"]\n\n for (k,v) in sort!(collect(pardic), by = x -> x[2])\n push!(col_nam, k)\n end\n\n for ci in Base.OneTo(length(cits))\n ri = vcat(reshape(col_nam, 1, lastindex(col_nam)), R[cits[ci],:])\n writedlm(out_file*\"_chain_$ci.log\", ri)\n end\n\nend\n\n\n\n\n\n\n\n", "meta": {"hexsha": "f6a8be562c2b9979f6fa2931b31e048e9808c696", "size": 13829, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/esse/sse_wrapper.jl", "max_stars_repo_name": "hmorlon/JPANDA", "max_stars_repo_head_hexsha": "cb91a2b516c56871a978cb4c13a89e6f6b47bb1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-11-05T08:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:22:43.000Z", "max_issues_repo_path": "src/esse/sse_wrapper.jl", "max_issues_repo_name": "hmorlon/JPANDA", "max_issues_repo_head_hexsha": "cb91a2b516c56871a978cb4c13a89e6f6b47bb1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-03T13:48:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T03:01:51.000Z", "max_forks_repo_path": "src/esse/sse_wrapper.jl", "max_forks_repo_name": "hmorlon/JPANDA", "max_forks_repo_head_hexsha": "cb91a2b516c56871a978cb4c13a89e6f6b47bb1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3934065934, "max_line_length": 136, "alphanum_fraction": 0.4982283607, "num_tokens": 4204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24432942065783597}} {"text": "\n\"\"\"\n\tALConstraintSet{T}\n\nAn [`AbstractConstraintSet`](@ref) that stores the constraint values as well as Lagrange\nmultiplier and penalty terms for each constraint.\n\nThe cost associated with constraint terms in the augmented Lagrangian can be evaluated for\n\n\tcost!(J::Vector, ::ALConstraintSet)\n\nwhich adds the cost at each time step to the vector `J` of length `N`.\n\nThe cost expansion for these terms is evaluated along the trajectory `Z` using\n\n\tcost_expansion!(E::Objective, conSet::ALConstraintSet, Z)\n\nwhich also adds the expansion terms to the terms in `E`.\n\nThe penalty and multiplier terms can be updated using\n\n\tpenalty_update!(::ALConstraintSet)\n\tdual_update!(::ALConstraintSet)\n\nThe current set of active constraint (with tolerance `tol`) can be re-calculated using\n\n\tupdate_active_set!(::ALConstraintSet, ::Val{tol})\n\nThe maximum penalty can be queried using `max_penalty(::ALConstraintSet)`, and the\npenalties and/or multipliers can be reset using\n\n\treset!(::ALConstraintSet)\n\treset_penalties!(::ALConstraintSet)\n\treset_duals!(::ALConstraintSet)\n\n# Constructor\n\tALConstraintSet(::ConstraintList, ::AbstractModel)\n\tALConstraintSet(::Problem)\n\"\"\"\nstruct ALConstraintSet{T} <: TO.AbstractConstraintSet\n convals::Vector{ALConVal}\n errvals::Vector{ALConVal} # TODO: is this needed?\n\t# ∇c_proj::Vector{<:Vector} # Jacobians of projected constraints\n # λ::Vector{<:Vector}\n # μ::Vector{<:Vector}\n\t# active::Vector{<:Vector}\n c_max::Vector{T}\n μ_max::Vector{T}\n μ_maxes::Vector{Vector{T}}\n\t# params::Vector{TO.ConstraintParams{T}}\n\tp::Vector{Int}\nend\n\nfunction ALConstraintSet(cons::TO.ConstraintList, model::RD.AbstractModel)\n n,m = cons.n, cons.m\n n̄ = RobotDynamics.state_diff_size(model)\n ncon = length(cons)\n useG = model isa RD.LieGroupModel\n\terrvals = map(1:ncon) do i\n C,c = TO.gen_convals(n̄, m, cons[i], cons.inds[i])\n ALConVal(n̄, m, cons[i], cons.inds[i], C, c, useG)\n end\n convals = map(errvals) do errval\n ALConVal(n, m, errval)\n end\n\terrvals = convert(Vector{ALConVal}, errvals)\n\tconvals = convert(Vector{ALConVal}, convals)\n\t# ∇c_proj = map(1:ncon) do i\n\t# \t[copy(errvals[i].jac[j,1]) for j in eachindex(cons.inds[i])]\n\t# end\n # λ = map(1:ncon) do i\n\t# \tp = length(cons[i])\n\t# \tconvals[i].λ\n # # [@SVector zeros(p) for j in cons.inds[i]]\n # end\n # μ = map(1:ncon) do i\n\t# \tp = length(cons[i])\n\t# \tconvals[i].μ\n # # [@SVector ones(p) for j in cons.inds[i]]\n # end\n # a = map(1:ncon) do i\n # p = length(cons[i])\n # [@SVector ones(Bool,p) for j in cons.inds[i]]\n\t# end\n\t# if ncon == 0\n\t# \t∇c_proj = Vector{Float64}[]\n\t# \tλ = Vector{Float64}[]\n\t# \tμ = Vector{Float64}[]\n\t# \ta = Vector{Float64}[]\n\t# end\n c_max = zeros(ncon)\n μ_max = zeros(ncon)\n μ_maxes = [zeros(length(ind)) for ind in cons.inds]\n\t# params = [TO.ConstraintParams() for con in cons.constraints]\n # ALConstraintSet(convals, errvals, ∇c_proj, λ, μ, a, c_max, μ_max, μ_maxes, params, copy(cons.p))\n ALConstraintSet(convals, errvals, c_max, μ_max, μ_maxes, copy(cons.p))\nend\n\n@inline ALConstraintSet(prob::Problem) = ALConstraintSet(prob.constraints, prob.model)\n\n@inline TO.get_convals(conSet::ALConstraintSet) = conSet.convals\n@inline TO.get_errvals(conSet::ALConstraintSet) = conSet.errvals\n\nget_duals(conSet::ALConstraintSet) = [cval.λ for cval in conSet.convals]\nfunction set_duals!(conSet::ALConstraintSet, λ)\n\tfor i = 1:length(conSet)\n\t\tset_duals!(conSet.convals[i], λ[i])\n\tend\nend\nfunction set_duals!(cval::ALConVal, λ)\n\tfor i = 1:length(cval.λ)\n\t\tcval.λ[i] .= λ[i]\n\tend\nend\n\nfor method in (:violation!, :∇violation!, :dual_update!, :penalty_update!, :reset_duals!, :reset_penalties!)\n\t@eval function $method(conSet::ALConstraintSet)\n\t\tfor i = 1:length(conSet)\n\t\t\t$method(conSet.convals[i])\n\t\tend\n\tend\nend\n\n############################################################################################\n# Augmented Lagrangian Updates\n############################################################################################\n\n# function dual_update!(conSet::ALConstraintSet)\n# for i in eachindex(conSet.λ)\n# dual_update!(conSet.convals[i])\n# \tend\n# end\n\nfunction dual_update!(conval::ALConVal)\n\tc = conval.vals\n\tλ = conval.λ\n\tμ = conval.μ\n\tλ_max = conval.params.λ_max\n\tcone = TO.sense(conval.con)\n\t# λ_min = TO.sense(conval.con) == Equality() ? -λ_max : zero(λ_max)\n\tfor i in eachindex(conval.inds)\n\t\tλ[i] .= dual_update(cone, SVector(λ[i]), SVector(c[i]), SVector(μ[i]), λ_max) \n\tend\nend\n\nfunction dual_update(::Equality, λ, c, μ, λmax)\n\tλbar = λ + μ .* c\n\treturn clamp.(λbar, -λmax, λmax)\nend\n\nfunction dual_update(::Inequality, λ, c, μ, λmax)\n \tλbar = λ + μ .* c\n\treturn clamp.(λbar, 0, λmax) # project onto the dual cone via max(0,x)\nend\n\nfunction dual_update(cone::SecondOrderCone, λ, c, μ, λmax)\n\t λbar = λ - μ .* c\n\t return TO.projection(cone, λbar) # project onto the dual cone\nend\n\n# function penalty_update!(conSet::ALConstraintSet)\n# \tfor i in eachindex(conSet.μ)\n# \t\tpenalty_update!(conSet.convals[i])\n# \tend\n# end\n\nfunction penalty_update!(cval::ALConVal)\n\tμ = cval.μ\n\tϕ = cval.params.ϕ\n\tμ_max = cval.params.μ_max\n\tfor i = 1:length(μ) \n\t\tμ[i] .*= ϕ\n\t\tclamp!(μ[i], 0, μ_max)\n\tend\nend\n\n# Active Set\nfunction update_active_set!(conSet::ALConstraintSet, val::Val{tol}=Val(0.0)) where tol\n\tfor i in 1:length(conSet) \n\t\t# update_active_set!(conSet.active[i], conSet.λ[i], conSet.convals[i], val)\n\t\tupdate_active_set!(conSet.convals[i], val)\n\tend\nend\n\nfunction update_active_set!(conval::ALConVal, ::Val{tol}) where tol\n\ta = conval.active\n\tλ = conval.λ\n\tif TO.sense(conval.con) == TO.Inequality()\n\t\tfor i in eachindex(a)\n\t\t\ta[i] = @. (conval.vals[i] >= -tol) | (λ[i] > zero(tol))\n\t\tend\n\tend\nend\n\n\"\"\"\n\tmax_penalty(conSet::ALConstraintSet)\n\nCalculate the maximum constrained penalty across all constraints.\n\"\"\"\nfunction max_penalty(conSet::ALConstraintSet)\n\tmax_penalty!(conSet)\n\tmaximum(conSet.μ_max)\nend\n\nfunction max_penalty!(conSet::ALConstraintSet{T}) where T\n conSet.c_max .*= 0\n\tfor i in 1:length(conSet) \n\t\tmaxes = conSet.μ_maxes[i]::Vector{T}\n max_penalty!(maxes, conSet.convals[i])\n conSet.μ_max[i] = maximum(maxes)\n end\nend\n\nfunction max_penalty!(μ_max::Vector{<:Real}, cval::ALConVal)\n for i in eachindex(cval.μ)\n μ_max[i] = maximum(cval.μ[i])\n end\n return nothing\nend\n\n############################################################################################\n# Constraint Penalties\n############################################################################################\n# function projection_jacobians!(conSet::ALConstraintSet)\n# \tfor i in eachindex(conSet.convals)\n# \t\tprojection_jacobians!(conSet.convals[i])\n# \tend\n# end\n\n\n# \"\"\"\n# \tconstraint_penalty!(conSet::ALConstraintSet)\n\n# Evaluate the penalty of the constraints. For equality constraints, this is the constraint \n# itself. For generalized inequalities, this is the projection of the constraint onto the\n# appropriate cone.\n# \"\"\"\n# function constraint_penalty!(conSet::ALConstraintSet)\n# \tfor i in eachindex(conSet.convals)\n# \t\tconstraint_penalty!(conSet.convals[i], conSet.λ[i])\n# \tend\n# end\n\n# function constraint_penalty!(conval::TO.ConVal, λ)\n# \tfor i in eachindex(conval.inds)\n# \t\tconval.vals2[i] = penalty(TO.sense(conval.con), conval.vals[i], λ[i])\n# \tend\n# end\n\n\n\n# \"\"\"\n# \tpenalty_jacobian!(conSet::ALConstraintSet)\n\n# Evaluate the Jacobian of the constraint penalty. For equality constraints, this is simply\n# the Jacobian of the constraint itself. For generalized inequalities, this is `∇proj*∇c`\n# where `∇proj` is the Jacobian of the projection of the constraint onto the corresponding \n# cone.\n# \"\"\"\n# function penalty_jacobian!(conSet::ALConstraintSet)\n# \tfor i in eachindex(conSet.errvals)\n# \t\tpenalty_jacobian!(conSet.∇c_proj[i], conSet.errvals[i], conSet.λ[i])\n# \tend\n# end\n\n# function penalty_jacobian!(∇c_proj::Vector, conval::TO.ConVal, λ::Vector)\n# \tif size(conval.jac, 2) > 1\n# \t\tthrow(ErrorException(\"Constraint projection not supported for CoupledConstraints\"))\n# \tend\n# \tfor i in eachindex(conval.inds)\n# \t\t∇penalty!(TO.sense(conval.con), ∇c_proj[i], conval.jac[i], conval.vals[i], λ[i])\n# \tend\n# end\n\n############################################################################################\n# Cost\n############################################################################################\n\n# function TO.cost!(J::Vector{<:Real}, conSet::ALConstraintSet)\n# \tfor i in eachindex(conSet.convals)\n# \t\tTO.cost!(J, conSet.convals[i], conSet.λ[i], conSet.μ[i], conSet.active[i])\n# \tend\n# end\n\n# function TO.cost!(J::Vector{<:Real}, conval::ALConVal, λ::Vector{<:StaticVector},\n# \t\tμ::Vector{<:StaticVector}, a::Vector{<:StaticVector})\n# \tfor (i,k) in enumerate(conval.inds)\n# \t\tc = SVector(conval.vals[i])\n# \t\tIμ = Diagonal(SVector(μ[i] .* a[i]))\n# \t\tJ[k] += λ[i]'c .+ 0.5*c'Iμ*c\n# \tend\n# end\n\n# function TO.cost_expansion!(E::Objective, conSet::ALConstraintSet, Z::AbstractTrajectory,\n# \t\tinit::Bool=false, rezero::Bool=false)\n# \tfor i in eachindex(conSet.errvals)\n# \t\tTO.cost_expansion!(E, conSet.convals[i], conSet.λ[i], conSet.μ[i], conSet.active[i])\n# \tend\n# end\n\n# @generated function TO.cost_expansion!(E::QuadraticObjective{n,m}, conval::ALConVal{C}, λ, μ, a) where {n,m,C}\n# \tif C <: TO.StateConstraint\n# \t\texpansion = quote\n# \t\t\tcx = ∇c\n# \t\t\tE[k].Q .+= cx'Iμ*cx\n# \t\t\tE[k].q .+= cx'g\n# \t\tend\n# \telseif C <: TO.ControlConstraint\n# \t\texpansion = quote\n# \t\t\tcu = ∇c\n# \t\t\tE[k].R .+= cu'Iμ*cu\n# \t\t\tE[k].r .+= cu'g\n# \t\tend\n# \telseif C<: TO.StageConstraint\n# \t\tix = SVector{n}(1:n)\n# \t\tiu = SVector{m}(n .+ (1:m))\n# \t\texpansion = quote\n# \t\t\tcx = ∇c[:,$ix]\n# \t\t\tcu = ∇c[:,$iu]\n# \t\t\tE[k].Q .+= cx'Iμ*cx\n# \t\t\tE[k].q .+= cx'g\n# \t\t\tE[k].H .+= cu'Iμ*cx\n# \t\t\tE[k].R .+= cu'Iμ*cu\n# \t\t\tE[k].r .+= cu'g\n# \t\tend\n# \telse\n# \t\tthrow(ArgumentError(\"cost expansion not supported for CoupledConstraints\"))\n# \tend\n# \tquote\n# \t\tfor (i,k) in enumerate(conval.inds)\n# \t\t\t∇c = SMatrix(conval.jac[i])\n# \t\t\tc = conval.vals[i]\n# \t\t\tIμ = Diagonal(a[i] .* μ[i])\n# \t\t\tg = Iμ*c .+ λ[i]\n\n# \t\t\t$expansion\n# \t\tend\n# \tend\n# end\n\n############################################################################################\n# RESET\n############################################################################################\n\nfunction reset!(conSet::ALConstraintSet)\n reset_duals!(conSet)\n reset_penalties!(conSet)\nend\n\n# function reset_duals!(conSet::ALConstraintSet)\n# \tfor i = 1:length(conSet)\n# \t\treset_duals!(conSet.convals[i])\n# \tend\n# end\n\n# function reset_penalties!(conSet::ALConstraintSet)\n# \tfor i = 1:length(conSet)\n# \t\treset_penalties!(conSet.convals[i])\n# \tend\n# end\n\n\n\"\"\"\n\tlink_constraints!(set1, set2)\n\nLink any common constraints between `set1` and `set2` by setting elements in `set1` to point\nto elements in `set2`\n\"\"\"\nfunction link_constraints!(set1::ALConstraintSet, set2::ALConstraintSet)\n\t# Find common constraints\n\tlinks = Tuple{Int,Int}[]\n\tfor (i,con1) in enumerate(set1)\n\t\tfor (j,con2) in enumerate(set2)\n\t\t\tif con1 === con2\n\t\t\t\tpush!(links, (i,j))\n\t\t\tend\n\t\tend\n\tend\n\n\t# Link values\n\tfor (i,j) in links\n\t\tset1.convals[i] = set2.convals[j]\n\t\tset1.errvals[i] = set2.errvals[j]\n\t\t# set1.active[i] = set2.active[j]\n\t\t# set1.λ[i] = set2.λ[j]\n\t\t# set1.μ[i] = set2.μ[j]\n\tend\n\treturn links\nend\n\nfunction shift_fill!(conSet::ALConstraintSet, n=1)\n\tfor i = 1:length(conSet)\n\t\tshift_fill!(conSet.convals[i], n)\n\tend\nend\n\n############################################################################################\n# Solver Options\n############################################################################################\nfunction reset!(conSet::ALConstraintSet{T}, opts::SolverOptions{T}) where T\n # if !isnan(opts.dual_max)\n # for params in conSet.params\n # params.λ_max = opts.dual_max\n # end\n # end\n # if !isnan(opts.penalty_max)\n # for params in conSet.params\n # params.μ_max = opts.penalty_max\n # end\n # end\n # if !isnan(opts.penalty_initial)\n # for params in conSet.params\n # params.μ0 = opts.penalty_initial\n # end\n # end\n # if !isnan(opts.penalty_scaling)\n # for params in conSet.params\n # params.ϕ = opts.penalty_scaling\n # end\n\t# end\n\tfor i = 1:length(conSet)\n\t\tset_params!(conSet.convals[i], opts)\n\tend\n if opts.reset_duals\n reset_duals!(conSet)\n end\n if opts.reset_penalties\n reset_penalties!(conSet)\n end\nend", "meta": {"hexsha": "88cbe8dd8bb2fdf3fd222f67c8b5c7497dcc804e", "size": 12605, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/augmented_lagrangian/ALconset.jl", "max_stars_repo_name": "tpr0p/Altro.jl", "max_stars_repo_head_hexsha": "cfe5f79fe64b454919d3edc26ad2ff2bb6cfe793", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2020-09-21T20:49:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:45:20.000Z", "max_issues_repo_path": "src/augmented_lagrangian/ALconset.jl", "max_issues_repo_name": "tpr0p/Altro.jl", "max_issues_repo_head_hexsha": "cfe5f79fe64b454919d3edc26ad2ff2bb6cfe793", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2020-07-11T00:04:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T16:36:08.000Z", "max_forks_repo_path": "src/augmented_lagrangian/ALconset.jl", "max_forks_repo_name": "tpr0p/Altro.jl", "max_forks_repo_head_hexsha": "cfe5f79fe64b454919d3edc26ad2ff2bb6cfe793", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-08-07T06:16:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T10:06:15.000Z", "avg_line_length": 29.3139534884, "max_line_length": 112, "alphanum_fraction": 0.6113447045, "num_tokens": 3813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.24432942065783594}} {"text": "#####################################################################\n# special.jl\n#\n# includes non-standard code I needed for papers and whatnot \n######################################################################\n\nfunction norm2(x::LocTuple, y::LocTuple)\n\td1 = x[1] - y[1]\n\td2 = x[2] - y[2]\n\treturn sqrt(d1*d1 + d2*d2)\nend\n\nfunction sim(j::LocTuple, actions::Vector{Pose}, observations::Vector{Float64}, b::Vector{Matrix{Float64}}, m::SearchDomain, x::Vehicle; show_mean=false, show_cov=false)\n\t# always start the vehicle in the center\n\t# NO, don't do that\n\t#x.x = m.length / 2.0\n\t#x.y = m.length / 2.0\n\ttheta!(m, j[1], j[2])\n\n\t# warn user if jammer is not where it should be\n\t#if abs(dx) > x.x || abs(dy) > x.y\n\t#\tprintln(\"WARNING: jammer outside search domain.\")\n\t#end\n\n\t# loop through all observations...\n\tfor (oi,o) in enumerate(observations)\n\t\t#update!(f, x, o)\n\t\t#plot(m, b[oi], x, show_mean=true, show_cov=true)\n\t\tplot(m, b[oi], x, show_mean=show_mean, show_cov=show_cov, obs=o)\n\t\tsavefig(\"temp_$(oi).png\", format=\"png\")\n\t\thold(false)\n\t\tact!(m, x, actions[oi])\n\tend\nend\n\nexport sim2\nfunction sim2(j::LocTuple, states::Vector{Pose}, observations::Vector{Float64}, b::Vector{Matrix{Float64}}, m::SearchDomain, x::Vehicle; show_mean=false, show_cov=false, show_path::Bool=true)\n\t# always start the vehicle in the center\n\t# NO, don't do that\n\t#x.x = m.length / 2.0\n\t#x.y = m.length / 2.0\n\ttheta!(m, j[1], j[2])\n\n\tpath_x = Float64[]\n\tpath_y = Float64[]\n\n\t# loop through all observations...\n\tfor (oi,o) in enumerate(observations)\n\t\tif show_path\n\t\t\t#plot path\n\t\t\tplot(path_x, path_y, \"k\")\n\t\tend\n\t\thold(true)\n\t\tplot(m, b[oi], x, show_mean=show_mean, show_cov=show_cov, obs=oi)\n\t\t#savefig(\"temp_$(oi).pdf\", format=\"pdf\", dpi=300)\n\t\tsavefig(\"temp_$(oi).png\", format=\"png\")\n\t\thold(false)\n\t\tpush!(path_x, x.x)\n\t\tpush!(path_y, x.y)\n\t\tx.x = states[oi][1]\n\t\tx.y = states[oi][2]\n\t\tx.heading = states[oi][3]\n\t\t#act!(m, x, actions[oi])\n\tend\nend\n\n# This was for AIAA GNC 2018 paper.\n# This probably shouldn't be here.\nexport eval2\nfunction eval2(j::LocTuple, states::Vector{Pose}, observations::Vector{Float64}, b::Vector{Matrix{Float64}}, m::SearchDomain, x::Vehicle; show_mean=false, show_cov=false, show_path::Bool=true)\n\t# always start the vehicle in the center\n\t# NO, don't do that\n\t#x.x = m.length / 2.0\n\t#x.y = m.length / 2.0\n\ttheta!(m, j[1], j[2])\n\n front_cone = Float64[]\n rear_cone = Float64[]\n sides = Float64[]\n\n\n\t# loop through all observations...\n\tfor (oi,o) in enumerate(observations)\n # get true bearing between x\n xt = (x.x,x.y,x.heading)\n rel_bearing = fit_180(xt[3] - true_bearing(xt, m.theta))\n if rel_bearing < 0.0\n rel_bearing = -1.0 * rel_bearing\n end\n\n\n cla()\n\t\tplot(m, b[oi], x, show_mean=show_mean, show_cov=show_cov, obs=oi)\n #title(\"o = $o\")\n #hold(false)\n if rel_bearing < 60.0\n # expect observation 1\n title(\"expect 1, got $o\")\n push!(front_cone, o)\n elseif rel_bearing < 120.0\n title(\"expect either, got $o\")\n push!(sides, o)\n else\n title(\"expect 0, got $o\")\n push!(rear_cone,o)\n end\n pause(0.15)\n\n # update vehicle position\n\t\tx.x = states[oi][1]\n\t\tx.y = states[oi][2]\n\t\tx.heading = states[oi][3]\n\tend\n return front_cone, sides, rear_cone\nend\n\nfunction simulate(m::SearchDomain, uav::SimUnit;\n video::Bool=true,\n pause_time=0.3\n )\n\n # reset the filter, vehicle, and policy\n # TODO: I think I assume the SimUnit comes in clean and ready to go\n #reset!(uav.f)\n #reset!(m, uav.x)\n #reset!(uav.p)\n\n # What was the cost to getting this first observation?\n temp_cost = get_cost(uav, m)\n\n # before doing anything else, we observe\n # and update filter once\n o = observe(m, uav.x)\n update!(uav, o)\n\n # This was our first step; steps count number of observations\n step_count = 1\n\n # plot if need be\n if video\n figure(\"Simulation\")\n plot(m, uav.f, uav.x)\n title(\"i = $(step_count)\")\n end\n\n\n while !is_complete(uav.f, uav.tc, step_count)\n # act\n a = action(m, uav, o)\n act!(m, uav.x, a)\n\n # get cost and update step count\n temp_cost += get_cost(uav, m, a)\n step_count += 1\n\n # observe and update\n o = observe(m, uav.x)\n update!(uav, o)\n\n # plot if need be\n if video\n pause(pause_time)\n figure(\"Simulation\")\n cla()\n plot(m, uav.f, uav.x)\n max_b = maximum(uav.f.b)\n title(\"i = $(step_count), max = $(round(max_b,3))\")\n end\n end\n\n return temp_cost\nend\n", "meta": {"hexsha": "850b6838434dec50494a3ae06d2ff984c9237b41", "size": 4738, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/special.jl", "max_stars_repo_name": "dressel/FEBOLPlots.jl", "max_stars_repo_head_hexsha": "74d020a10e6c40439e17cc06e2b16b97b30488fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/special.jl", "max_issues_repo_name": "dressel/FEBOLPlots.jl", "max_issues_repo_head_hexsha": "74d020a10e6c40439e17cc06e2b16b97b30488fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/special.jl", "max_forks_repo_name": "dressel/FEBOLPlots.jl", "max_forks_repo_head_hexsha": "74d020a10e6c40439e17cc06e2b16b97b30488fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.387283237, "max_line_length": 192, "alphanum_fraction": 0.57893626, "num_tokens": 1464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2443005306581844}} {"text": "\"\"\"\n VF2\n\nAn empty concrete type used to dispatch to [`vf2`](@ref) isomorphism functions.\n\"\"\"\nstruct VF2 <: IsomorphismAlgorithm end\n\n\"\"\"\n VF2State{G, T}\n\nStructure that is internally used by vf2\n\"\"\"\nstruct VF2State{G, T}\n g1::G\n g2::G\n core_1::Vector{T}\n core_2::Vector{T}\n in_1::Vector{T}\n in_2::Vector{T}\n out_1::Vector{T}\n out_2::Vector{T}\n\n function VF2State(g1::G, g2::G) where {G <: AbstractSimpleGraph{T}} where {T <: Integer}\n n1 = nv(g1)\n n2 = nv(g2)\n core_1 = zeros(T, n1)\n core_2 = zeros(T, n2)\n in_1 = zeros(T, n1)\n in_2 = zeros(T, n2)\n out_1 = zeros(T, n1)\n out_2 = zeros(T, n2)\n\n return new{G, T}(g1, g2, core_1, core_2, in_1, in_2, out_1, out_2)\n end\nend\n\n\"\"\"\n vf2(callback, g1, g2, problemtype; vertex_relation=nothing, edge_relation=nothing)\n\nIterate over all isomorphism between the graphs `g1` (or subgraphs thereof) and `g2`.\nThe problem that is solved depends on the value of `problemtype`:\n- IsomorphismProblem(): Only isomorphisms between the whole graph `g1` and `g2` are considered.\n- SubGraphIsomorphismProblem(): All isomorphism between subgraphs of `g1` and `g2` are considered.\n- InducedSubGraphIsomorphismProblem(): All isomorphism between vertex induced subgraphs of `g1` and `g2` are considered.\n\nUpon finding an isomorphism, the function `callback` is called with a vector `vmap` as an argument.\n`vmap` is a vector where `vmap[v] == u` means that vertex `v` in `g2` is mapped to vertex `u` in `g1`.\nIf the algorithm should look for another isomorphism, then this function should return `true`.\n\n### Optional Arguments\n- `vertex_relation`: A binary function that takes a vertex from `g1` and one from `g2`. An\n isomorphism only exists if this function returns `true` for all matched vertices.\n- `edge_relation`: A binary function that takes an edge from `g1` and one from `g2`. An\n isomorphism only exists if this function returns `true` for all matched edges.\n\n### References\nLuigi P. Cordella, Pasquale Foggia, Carlo Sansone, Mario Vento\n“A (Sub)Graph Isomorphism Algorithm for Matching Large Graphs”\n\"\"\"\nfunction vf2(callback::Function, g1::G, g2::G, problemtype::GraphMorphismProblem; \n vertex_relation::Union{Nothing, Function}=nothing, \n edge_relation::Union{Nothing, Function}=nothing) where {G <: AbstractSimpleGraph}\n if nv(g1) < nv(g2) || (problemtype == IsomorphismProblem() && nv(g1) != nv(g2))\n return \n end\n\n start_state = VF2State(g1, g2)\n start_depth = 1\n vf2match!(start_state, start_depth, callback, problemtype, vertex_relation, edge_relation)\n return\nend\n\n\"\"\"\n vf2check_feasibility(u, v, state, problemtype, vertex_relation, edge_relation)\n\nCheck whether two vertices of G₁ and G₂ can be matched. Used by [`vf2match!`](@ref).\n\"\"\"\nfunction vf2check_feasibility(u, v, state::VF2State, problemtype,\n vertex_relation::Union{Nothing, Function},\n edge_relation::Union{Nothing, Function})\n @inline function vf2rule_pred(u, v, state::VF2State, problemtype)\n if problemtype != SubGraphIsomorphismProblem()\n @inbounds for u2 in inneighbors(state.g1, u)\n if state.core_1[u2] != 0\n found = false\n # TODO can probably be replaced with has_edge for better performance\n for v2 in inneighbors(state.g2, v)\n if state.core_1[u2] == v2\n found = true\n break\n end\n end\n found || return false\n end\n end\n end\n @inbounds for v2 in inneighbors(state.g2, v)\n if state.core_2[v2] != 0\n found = false\n for u2 in inneighbors(state.g1, u)\n if state.core_2[v2] == u2\n found = true\n break\n end\n end\n found || return false\n end\n end\n return true\n end\n\n @inline function vf2rule_succ(u, v, state::VF2State, problemtype)\n if problemtype != SubGraphIsomorphismProblem()\n @inbounds for u2 in outneighbors(state.g1, u)\n if state.core_1[u2] != 0\n found = false\n for v2 in outneighbors(state.g2, v)\n if state.core_1[u2] == v2\n found = true\n break\n end\n end\n found || return false\n end\n end\n end\n found = false\n @inbounds for v2 in outneighbors(state.g2, v)\n if state.core_2[v2] != 0\n found = false\n for u2 in outneighbors(state.g1, u)\n if state.core_2[v2] == u2\n found = true\n break\n end\n end\n found || return false\n end\n end\n return true\n end\n \n\n @inline function vf2rule_in(u, v, state::VF2State, problemtype)\n count1 = 0\n count2 = 0\n @inbounds for u2 in outneighbors(state.g1, u)\n if state.in_1[u2] != 0 && state.core_1[u2] == 0\n count1 += 1\n end\n end\n @inbounds for v2 in outneighbors(state.g2, v)\n if state.in_2[v2] != 0 && state.core_2[v2] == 0\n count2 += 1\n end\n end\n if problemtype == IsomorphismProblem()\n count1 == count2 || return false\n else\n count1 >= count2 || return false\n end\n count1 = 0\n count2 = 0\n @inbounds for u2 in inneighbors(state.g1, u)\n if state.in_1[u2] != 0 && state.core_1[u2] == 0\n count1 += 1\n end\n end\n @inbounds for v2 in inneighbors(state.g2, v)\n if state.in_2[v2] != 0 && state.core_2[v2] == 0\n count2 += 1\n end\n end\n problemtype == IsomorphismProblem() && return count1 == count2 \n\n return count1 >= count2 \n end\n\n @inline function vf2rule_out(u, v, state::VF2State, problemtype)\n count1 = 0\n count2 = 0\n @inbounds for u2 in outneighbors(state.g1, u)\n if state.out_1[u2] != 0 && state.core_1[u2] == 0\n count1 += 1\n end\n end\n @inbounds for v2 in outneighbors(state.g2, v)\n if state.out_2[v2] != 0 && state.core_2[v2] == 0\n count2 += 1\n end\n end\n if problemtype == IsomorphismProblem()\n count1 == count2 || return false\n else\n count1 >= count2 || return false\n end\n\n count1 = 0\n count2 = 0\n @inbounds for u2 in inneighbors(state.g1, u)\n if state.out_1[u2] != 0 && state.core_1[u2] == 0\n count1 += 1\n end\n end\n @inbounds for v2 in inneighbors(state.g2, v)\n if state.out_2[v2] != 0 && state.core_2[v2] == 0\n count2 += 1\n end\n end\n problemtype == IsomorphismProblem() && return count1 == count2 \n\n return count1 >= count2 \n end\n\n @inline function vf2rule_new(u, v, state::VF2State, problemtype)\n problemtype == SubGraphIsomorphismProblem() && return true\n count1 = 0\n count2 = 0\n @inbounds for u2 in inneighbors(state.g1, u)\n if state.in_1[u2] == 0 && state.out_1[u2] == 0\n count1 += 1\n end\n end\n @inbounds for v2 in inneighbors(state.g2, v)\n if state.in_2[v2] == 0 && state.out_2[v2] == 0\n count2 += 1\n end\n end\n if problemtype == IsomorphismProblem()\n count1 == count2 || return false\n else\n count1 >= count2 || return false\n end\n count1 = 0\n count2 = 0\n @inbounds for u2 in outneighbors(state.g1, u)\n if state.in_1[u2] == 0 && state.out_1[u2] == 0\n count1 += 1\n end\n end\n @inbounds for v2 in outneighbors(state.g2, v)\n if state.in_2[v2] == 0 && state.out_2[v2] == 0\n count2 += 1\n end\n end\n problemtype == IsomorphismProblem() && return count1 == count2 \n \n return count1 >= count2\n end\n\n @inline function vf2rule_self_loops(u, v, state, problemtype)\n u_selflooped = has_edge(state.g1, u, u)\n v_selflooped = has_edge(state.g2, v, v)\n\n if problemtype == SubGraphIsomorphismProblem()\n return u_selflooped || !v_selflooped\n end\n return u_selflooped == v_selflooped\n end\n\n syntactic_feasability = vf2rule_pred(u, v, state, problemtype) && \n vf2rule_succ(u, v, state, problemtype) && \n vf2rule_in(u, v, state, problemtype) && \n vf2rule_out(u, v, state, problemtype) && \n vf2rule_new(u, v, state, problemtype) &&\n vf2rule_self_loops(u, v, state, problemtype)\n syntactic_feasability || return false\n\n\n if vertex_relation != nothing\n vertex_relation(u, v) || return false\n end\n if edge_relation != nothing\n E1 = edgetype(state.g1)\n E2 = edgetype(state.g2)\n for u2 in outneighbors(state.g1, u)\n state.core_1[u2] == 0 && continue\n v2 = state.core_1[u2]\n edge_relation(E1(u, u2), E2(v, v2)) || return false\n end\n for u2 in inneighbors(state.g1, u)\n state.core_1[u2] == 0 && continue\n v2 = state.core_1[u2]\n edge_relation(E1(u2, u), E2(v2, v)) || return false\n end\n end\n return true\nend\n\n\"\"\"\n vf2update_state!(state, u, v, depth)\n\nUpdate state before recursing. Helper function for [`vf2match!`](@ref).\n\"\"\"\nfunction vf2update_state!(state::VF2State, u, v, depth)\n@inbounds begin\n state.core_1[u] = v\n state.core_2[v] = u\n for w in outneighbors(state.g1, u)\n if state.out_1[w] == 0\n state.out_1[w] = depth\n end\n end\n for w in inneighbors(state.g1, u)\n if state.in_1[w] == 0\n state.in_1[w] = depth\n end\n end\n for w in outneighbors(state.g2, v)\n if state.out_2[w] == 0\n state.out_2[w] = depth\n end\n end\n for w in inneighbors(state.g2, v)\n if state.in_2[w] == 0\n state.in_2[w] = depth\n end\n end\nend\nend\n\n\"\"\"\n vf2reset_state!(state, u, v, depth)\n\nReset state after returning from recursion. Helper function for [`vf2match!`](@ref).\n\"\"\"\nfunction vf2reset_state!(state::VF2State, u, v, depth)\n@inbounds begin\n state.core_1[u] = 0\n state.core_2[v] = 0\n for w in outneighbors(state.g1, u)\n if state.out_1[w] == depth\n state.out_1[w] = 0\n end\n end\n for w in inneighbors(state.g1, u)\n if state.in_1[w] == depth\n state.in_1[w] = 0\n end\n end\n for w in outneighbors(state.g2, v)\n if state.out_2[w] == depth\n state.out_2[w] = 0\n end\n end\n for w in inneighbors(state.g2, v)\n if state.in_2[w] == depth\n state.in_2[w] = 0\n end\n end\nend\nend\n\n\"\"\"\n vf2match!(state, depth, callback, problemtype, vertex_relation, edge_relation)\n\nPerform isomorphic subgraph matching. Called by [`vf2`](@ref).\n\"\"\"\nfunction vf2match!(state, depth, callback::Function, problemtype::GraphMorphismProblem,\n vertex_relation, edge_relation)\n n1 = Int(nv(state.g1))\n n2 = Int(nv(state.g2))\n # if all vertices of G₂ are matched we call the callback function. If the\n # algorithm should look for another isomorphism then callback has to return true\n if depth > n2\n keepgoing = callback(state.core_2)\n return keepgoing\n end\n # First we try if there is a pair of unmatched vertices u∈G₁ v∈G₂ that are connected\n # by an edge going out of the set M(s) of already matched vertices\n found_pair = false\n v = 0\n @inbounds for j = 1:n2\n if state.out_2[j] != 0 && state.core_2[j] == 0\n v = j\n break\n end\n end\n if v != 0\n @inbounds for u = 1:n1\n if state.out_1[u] != 0 && state.core_1[u] == 0\n found_pair = true\n if vf2check_feasibility(u, v, state, problemtype, vertex_relation, edge_relation)\n vf2update_state!(state, u, v, depth)\n keepgoing = vf2match!(state, depth + 1, callback, problemtype, \n vertex_relation, edge_relation) \n keepgoing || return false\n vf2reset_state!(state, u, v, depth)\n end\n end\n end\n end\n found_pair && return true\n # If that is not the case we try if there is a pair of unmatched vertices u∈G₁ v∈G₂ that \n # are connected by an edge coming in from the set M(s) of already matched vertices\n v = 0\n @inbounds for j = 1:n2\n if state.in_2[j] != 0 && state.core_2[j] == 0\n v = j\n break\n end\n end\n if v != 0\n @inbounds for u = 1:n1\n if state.in_1[u] != 0 && state.core_1[u] == 0\n found_pair = true\n if vf2check_feasibility(u, v, state, problemtype, vertex_relation, edge_relation)\n vf2update_state!(state, u, v, depth)\n keepgoing = vf2match!(state, depth + 1, callback, problemtype,\n vertex_relation, edge_relation) \n keepgoing || return false\n vf2reset_state!(state, u, v, depth)\n end\n end\n end\n end\n found_pair && return true\n # If this is also not the case, we try all pairs of vertices u∈G₁ v∈G₂ that are not\n # yet matched\n v = 0\n @inbounds for j = 1:n2\n if state.core_2[j] == 0\n v = j\n break\n end\n end\n if v != 0\n @inbounds for u = 1:n1\n if state.core_1[u] == 0\n if vf2check_feasibility(u, v, state, problemtype, vertex_relation, edge_relation)\n vf2update_state!(state, u, v, depth)\n keepgoing = vf2match!(state, depth + 1, callback, problemtype,\n vertex_relation, edge_relation) \n keepgoing || return false\n vf2reset_state!(state, u, v, depth)\n end\n end\n end \n end\n return true\nend\n\n\nfunction has_induced_subgraphisomorph(g1::AbstractGraph, g2::AbstractGraph, alg::VF2;\n vertex_relation::Union{Nothing, Function}=nothing,\n edge_relation::Union{Nothing, Function}=nothing)::Bool\n result = false\n callback(vmap) = (result = true; return false)\n vf2(callback, g1, g2, InducedSubGraphIsomorphismProblem();\n vertex_relation=vertex_relation, edge_relation=edge_relation)\n return result\nend\n\nfunction has_subgraphisomorph(g1::AbstractGraph, g2::AbstractGraph, alg::VF2;\n vertex_relation::Union{Nothing, Function}=nothing,\n edge_relation::Union{Nothing, Function}=nothing,)::Bool\n result = false\n callback(vmap) = (result = true; return false)\n vf2(callback, g1, g2, SubGraphIsomorphismProblem();\n vertex_relation=vertex_relation, edge_relation=edge_relation)\n return result\nend\n\nfunction has_isomorph(g1::AbstractGraph, g2::AbstractGraph, alg::VF2;\n vertex_relation::Union{Nothing, Function}=nothing,\n edge_relation::Union{Nothing, Function}=nothing)::Bool\n\n !could_have_isomorph(g1, g2) && return false\n\n result = false\n callback(vmap) = (result = true; return false)\n vf2(callback, g1, g2, IsomorphismProblem(),\n vertex_relation=vertex_relation,\n edge_relation=edge_relation)\n return result\nend\n\nfunction count_induced_subgraphisomorph(g1::AbstractGraph, g2::AbstractGraph, alg::VF2;\n vertex_relation::Union{Nothing, Function}=nothing,\n edge_relation::Union{Nothing, Function}=nothing)::Int\n result = 0\n callback(vmap) = (result += 1; return true)\n vf2(callback, g1, g2, InducedSubGraphIsomorphismProblem(),\n vertex_relation=vertex_relation,\n edge_relation=edge_relation)\n return result\nend\n\nfunction count_subgraphisomorph(g1::AbstractGraph, g2::AbstractGraph, alg::VF2;\n vertex_relation::Union{Nothing, Function}=nothing,\n edge_relation::Union{Nothing, Function}=nothing)::Int\n result = 0\n callback(vmap) = (result += 1; return true)\n vf2(callback, g1, g2, SubGraphIsomorphismProblem(), vertex_relation=vertex_relation, edge_relation=edge_relation)\n return result\nend\n\nfunction count_isomorph(g1::AbstractGraph, g2::AbstractGraph, alg::VF2;\n vertex_relation::Union{Nothing, Function}=nothing,\n edge_relation::Union{Nothing, Function}=nothing)::Int\n !could_have_isomorph(g1, g2) && return 0\n result = 0\n callback(vmap) = (result += 1; return true)\n vf2(callback, g1, g2, IsomorphismProblem(), vertex_relation=vertex_relation, edge_relation=edge_relation)\n return result\nend\n\nfunction all_induced_subgraphisomorph(g1::AbstractGraph, g2::AbstractGraph, alg::VF2;\n vertex_relation::Union{Nothing, Function}=nothing,\n edge_relation::Union{Nothing, Function}=nothing)::Channel{Vector{Tuple{eltype(g1),eltype(g2)}}}\n make_callback(c) = vmap -> (put!(c, collect(zip(vmap,1:length(vmap)))), return true)\n T = Vector{Tuple{eltype(g1), eltype(g2)}}\n ch::Channel{T} = Channel(ctype=T) do c\n vf2(make_callback(c), g1, g2, InducedSubGraphIsomorphismProblem(), \n vertex_relation=vertex_relation,\n edge_relation=edge_relation)\n end\nend\n\nfunction all_subgraphisomorph(g1::AbstractGraph, g2::AbstractGraph, alg::VF2;\n vertex_relation::Union{Nothing, Function}=nothing,\n edge_relation::Union{Nothing, Function}=nothing)::Channel{Vector{Tuple{eltype(g1), eltype(g2)}}}\n\n make_callback(c) = vmap -> (put!(c, collect(zip(vmap,1:length(vmap)))), return true)\n T = Vector{Tuple{eltype(g1), eltype(g2)}}\n ch::Channel{T} = Channel(ctype=T) do c\n vf2(make_callback(c), g1, g2, SubGraphIsomorphismProblem(), \n vertex_relation=vertex_relation,\n edge_relation=edge_relation)\n end\n return ch\nend\n\nfunction all_isomorph(g1::AbstractGraph, g2::AbstractGraph, alg::VF2;\n vertex_relation::Union{Nothing, Function}=nothing,\n edge_relation::Union{Nothing, Function}=nothing)::Channel{Vector{Tuple{eltype(g1),eltype(g2)}}}\n T = Vector{Tuple{eltype(g1), eltype(g2)}}\n !could_have_isomorph(g1, g2) && return Channel(_ -> return, ctype=T)\n make_callback(c) = vmap -> (put!(c, collect(zip(vmap,1:length(vmap)))), return true)\n ch::Channel{T} = Channel(ctype=T) do c\n vf2(make_callback(c), g1, g2, IsomorphismProblem(), \n vertex_relation=vertex_relation,\n edge_relation=edge_relation)\n end\n return ch\nend\n", "meta": {"hexsha": "79f6c597fe3aafb8f9b0f40378a0184f5be173c0", "size": 19737, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Experimental/vf2.jl", "max_stars_repo_name": "blepabyte/LightGraphs.jl", "max_stars_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 745, "max_stars_repo_stars_event_min_datetime": "2015-03-19T03:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T00:59:06.000Z", "max_issues_repo_path": "src/Experimental/vf2.jl", "max_issues_repo_name": "blepabyte/LightGraphs.jl", "max_issues_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1491, "max_issues_repo_issues_event_min_datetime": "2015-03-19T17:04:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:47:57.000Z", "max_forks_repo_path": "src/Experimental/vf2.jl", "max_forks_repo_name": "blepabyte/LightGraphs.jl", "max_forks_repo_head_hexsha": "1fa2898a92bc551282f619d1818dd1dab4f85358", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 288, "max_forks_repo_forks_event_min_datetime": "2015-04-04T14:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T10:37:21.000Z", "avg_line_length": 36.0822669104, "max_line_length": 128, "alphanum_fraction": 0.5641181537, "num_tokens": 5268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24430053065818438}} {"text": "\n\"\"\"\n`module JAC.PhotoRecombination` \n ... a submodel of JAC that contains all methods for computing photo-recomnbination, i.e. radiative recombination \n and radiative electron capture properties between some initial and final-state multiplets.\n\"\"\"\nmodule PhotoRecombination\n\n using Printf, ..AngularMomentum, ..Basics, ..Continuum, ..ManyElectron, ..PhotoEmission, ..Radial, ..Nuclear, ..TableStrings\n ##x global JAC_counter = 0\n\n \"\"\"\n `struct Settings` ... defines a type for the details and parameters of computing photo recombination lines.\n\n + multipoles ::Array{EmMultipole} ... Specifies the multipoles of the radiation field that are to be included.\n + gauges ::Array{UseGauge} ... Specifies the gauges to be included into the computations.\n + electronEnergies ::Array{Float64,1} ... List of electron energies.\n + ionEnergies ::Array{Float64,1} ... List of ion energies.\n + useIonEnergies ::Bool ... Make use of ion energies in [MeV/u] to obtain the electron energies.\n + calcAnisotropy ::Bool ... True, if the overall anisotropy is to be calculated.\n + calcTensors ::Bool ... True, if the statistical tensors are to be calculated and false otherwise.\n + printBeforeComputation ::Bool ... True, if all energies and lines are printed before their evaluation.\n + selectLines ::Bool ... True, if lines are selected individually for the computations.\n + selectedLines ::Array{Tuple{Int64,Int64},1} ... List of lines, given by tupels (inital-level, final-level).\n \"\"\"\n struct Settings\n multipoles ::Array{EmMultipole}\n gauges ::Array{UseGauge}\n electronEnergies ::Array{Float64,1} \n ionEnergies ::Array{Float64,1}\n useIonEnergies ::Bool\n calcAnisotropy ::Bool\n calcTensors ::Bool \n printBeforeComputation ::Bool\n selectLines ::Bool\n selectedLines ::Array{Tuple{Int64,Int64},1} \n end \n\n\n \"\"\"\n `PhotoRecombination.Settings()` ... constructor for the default values of photo recombination line computations\n \"\"\"\n function Settings()\n Settings(EmMultipole[], UseGauge[], Float64[], Float64[], false, false, false, false, false, Tuple{Int64,Int64}[])\n end\n\n\n # `Base.show(io::IO, settings::PhotoRecombination.Settings)` \n #\t\t... prepares a proper printout of the variable settings::PhotoRecombination.Settings.\n function Base.show(io::IO, settings::PhotoRecombination.Settings) \n println(io, \"multipoles: $(settings.multipoles) \")\n println(io, \"gauges: $(settings.gauges) \")\n println(io, \"electronEnergies: $(settings.electronEnergies) \")\n println(io, \"ionEnergies: $(settings.ionEnergies) \")\n println(io, \"useIonEnergies: $(settings.useIonEnergies) \")\n println(io, \"calcAnisotropy: $(settings.calcAnisotropy) \")\n println(io, \"calcTensors: $(settings.calcTensors) \")\n println(io, \"printBeforeComputation: $(settings.printBeforeComputation) \")\n println(io, \"selectLines: $(settings.selectLines) \")\n println(io, \"selectedLines: $(settings.selectedLines) \")\n end\n\n\n \"\"\"\n `struct PhotoRecombination.Channel` \n ... defines a type for a photorecombination channel to help characterize a single multipole and scattering \n (continuum) state of many electron-states with a single free electron.\n\n + multipole ::EmMultipole ... Multipole of the photon emission/absorption.\n + gauge ::EmGauge ... Gauge for dealing with the (coupled) radiation field.\n + kappa ::Int64 ... partial-wave of the free electron\n + symmetry ::LevelSymmetry ... total angular momentum and parity of the scattering state\n + phase ::Float64 ... phase of the partial wave\n + amplitude ::Complex{Float64} ... Rec amplitude associated with the given channel.\n \"\"\"\n struct Channel\n multipole ::EmMultipole\n gauge ::EmGauge\n kappa ::Int64\n symmetry ::LevelSymmetry\n phase ::Float64\n amplitude ::Complex{Float64}\n end\n\n\n \"\"\"\n `struct PhotoRecombination.Line` \n ... defines a type for a Photorecombination line that may include the definition of channels.\n\n + initialLevel ::Level ... initial-(state) level\n + finalLevel ::Level ... final-(state) level\n + electronEnergy ::Float64 ... Energy of the (incoming free) electron.\n + photonEnergy ::Float64 ... Energy of the emitted photon.\n + crossSection ::EmProperty ... Cross section for this electron capture.\n + hasChannels ::Bool ... Determines whether the individual (sub-) channels are defined in terms of their \n free-electron energy, kappa, multipole, etc., or not.\n + channels ::Array{PhotoRecombination.Channel,1} ... List of photorecombination channels of this line.\n \"\"\"\n struct Line\n initialLevel ::Level\n finalLevel ::Level\n electronEnergy ::Float64\n photonEnergy ::Float64\n crossSection ::EmProperty\n hasChannels ::Bool\n channels ::Array{PhotoRecombination.Channel,1}\n end \n\n\n \"\"\"\n `PhotoRecombination.Line()` \n ... constructor for an `empty instance` of a photorecombination line between a specified initial \n and final level.\n \"\"\"\n function Line(initialLevel::Level, finalLevel::Level)\n Line(initialLevel::Level, finalLevel::Level, 0., 0., EmProperty(0., 0.), false, Channel[])\n end\n\n\n # `Base.show(io::IO, line::PhotoRecombination.Line)` ... prepares a proper printout of the variable line::PhotoRecombination.Line.\n function Base.show(io::IO, line::PhotoRecombination.Line) \n println(io, \"initialLevel: $(line.initialLevel) \")\n println(io, \"finalLevel: $(line.finalLevel) \")\n println(io, \"electronEnergy: $(line.electronEnergy) \")\n println(io, \"photonEnergy: $(line.photonEnergy) \")\n println(io, \"crossSection: $(line.crossSection) \")\n println(io, \"hasChannels: $(line.hasChannels) \")\n println(io, \"channels: $(line.channels) \")\n end\n\n\n \"\"\"\n `PhotoRecombination.amplitude(kind::String, channel::PhotoRecombination.Channel, energy::Float64, finalLevel::Level, \n continuumLevel::Level, grid::Radial.Grid)` \n ... to compute the kind = (photorecombination) amplitude \n < alpha_f J_f || O^(photorecombination) || (alpha_i J_i, epsilon kappa) J_t> due to the electron-photon \n interaction for the given final and continuum level, the partial wave of the outgoing electron as well as \n the given multipole and gauge. A value::ComplexF64 is returned.\n \"\"\"\n function amplitude(kind::String, channel::PhotoRecombination.Channel, energy::Float64, finalLevel::Level, \n continuumLevel::Level, grid::Radial.Grid)\n if kind in [ \"photorecombination\"]\n #-----------------------------------\n amplitude = PhotoEmission.amplitude(\"emission\", channel.multipole, channel.gauge, energy, finalLevel, continuumLevel, grid)\n amplitude = im^Basics.subshell_l(Subshell(101, channel.kappa)) * exp( im*channel.phase ) * amplitude\n else error(\"stop b\")\n end\n \n return( amplitude )\n end\n\n\n \"\"\"\n `PhotoRecombination.computeAmplitudesProperties(line::PhotoRecombination.Line, nm::Nuclear.Model, grid::Radial.Grid, nrContinuum::Int64, \n settings::PhotoRecombination.Settings)` \n ... to compute all amplitudes and properties of the given line; a line::PhotoRecombination.Line is returned for \n which the amplitudes and properties are now evaluated.\n \"\"\"\n function computeAmplitudesProperties(line::PhotoRecombination.Line, nm::Nuclear.Model, grid::Radial.Grid, nrContinuum::Int64,\n settings::PhotoRecombination.Settings)\n newChannels = PhotoRecombination.Channel[];; contSettings = Continuum.Settings(false, nrContinuum); csC = 0.; csB = 0.\n for channel in line.channels\n newfLevel = Basics.generateLevelWithSymmetryReducedBasis(line.finalLevel)\n newfLevel = Basics.generateLevelWithExtraSubshell(Subshell(101, channel.kappa), newfLevel)\n newiLevel = Basics.generateLevelWithSymmetryReducedBasis(line.initialLevel)\n cOrbital, phase = Continuum.generateOrbitalForLevel(line.electronEnergy, Subshell(101, channel.kappa), newiLevel, nm, grid, contSettings)\n newcLevel = Basics.generateLevelWithExtraElectron(cOrbital, channel.symmetry, newiLevel)\n newChannel = PhotoRecombination.Channel(channel.multipole, channel.gauge, channel.kappa, channel.symmetry, phase, 0.)\n amplitude = PhotoRecombination.amplitude(\"photorecombination\", channel, line.photonEnergy, newfLevel, newcLevel, grid)\n push!( newChannels, PhotoRecombination.Channel(newChannel.multipole, newChannel.gauge, newChannel.kappa, newChannel.symmetry, \n newChannel.phase, amplitude) )\n if channel.gauge == Basics.Coulomb csC = csC + abs(amplitude)^2\n elseif channel.gauge == Basics.Babushkin csB = csB + abs(amplitude)^2\n elseif channel.gauge == Basics.Magnetic csB = csB + abs(amplitude)^2; csC = csC + abs(amplitude)^2\n end\n end\n Ji2 = AngularMomentum.twoJ(line.initialLevel.J)\n csFactor = 8 * pi^3 * Defaults.getDefaults(\"alpha\")^3 * line.photonEnergy / (Ji2 + 1)\n crossSection = EmProperty(csFactor * csC, csFactor * csB)\n newLine = PhotoRecombination.Line( line.initialLevel, line.finalLevel, line.electronEnergy, line.photonEnergy, crossSection, true, newChannels)\n return( newLine )\n end\n\n\n\n \"\"\"\n `PhotoRecombination.computeAnisotropyParameter(nu::Int64, gauge::EmGauge, line::PhotoRecombination.Line)` \n ... to compute the anisotropy parameter of the emitted photons for the photorecombination of an initially unpolarized ion. \n A value::ComplexF64 is returned.\n \"\"\"\n function computeAnisotropyParameter(nu::Int64, gauge::EmGauge, line::PhotoRecombination.Line)\n if !line.hasChannels error(\"No channels are defined for the given PhotoRecombination.line.\") end\n wa = 0.0im; Ji = line.initialLevel.J; Jf = line.finalLevel.J \n wn = 0.; \n for ch in line.channels \n if gauge != ch.gauge && gauge != Basics.Magnetic continue end\n wn = wn + conj(ch.amplitude) * ch.amplitude \n end\n \n for cha in line.channels\n if gauge != cha.gauge && gauge != Basics.Magnetic continue end\n J = cha.symmetry.J; L = cha.multipole.L; if cha.multipole.electric p = 1 else p = 0 end\n j = AngularMomentum.kappa_j(cha.kappa); l = AngularMomentum.kappa_l(cha.kappa)\n #\n for chp in line.channels \n if gauge != chp.gauge && gauge != Basics.Magnetic continue end\n Jp = chp.symmetry.J; Lp = chp.multipole.L; if chp.multipole.electric pp = 1 else pp = 0 end\n jp = AngularMomentum.kappa_j(chp.kappa); lp = AngularMomentum.kappa_l(chp.kappa)\n #\n if 1 + (-1)^(L + p + Lp + pp - nu) == 0 continue end\n wa = wa + 1.0im^(L + p - Lp - pp) * AngularMomentum.phaseFactor([Ji, -1, AngularJ64(1//2), -1, Jf]) *\n sqrt( AngularMomentum.bracket([AngularJ64(L), AngularJ64(Lp), l, lp, j, jp, J, Jp]) ) * \n AngularMomentum.ClebschGordan( l, AngularM64(0), lp, AngularM64(0), AngularJ64(nu), AngularM64(0)) *\n AngularMomentum.ClebschGordan( AngularJ64(L), AngularM64(1), AngularJ64(Lp), AngularM64(-1), \n AngularJ64(nu), AngularM64(0)) *\n AngularMomentum.Wigner_6j(J, Jp, AngularJ64(nu), AngularJ64(Lp), AngularJ64(L), Jf) * \n AngularMomentum.Wigner_6j(J, Jp, AngularJ64(nu), jp, j, Ji) * \n AngularMomentum.Wigner_6j(j, jp, AngularJ64(nu), lp, l, AngularJ64(1//2)) * \n conj(cha.amplitude) * chp.amplitude\n end\n end\n \n value = - 0.5 * wa / wn\n return( value )\n end\n\n\n \"\"\"\n `PhotoRecombination.computeLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, nm::Nuclear.Model, grid::Radial.Grid, \n settings::PhotoRecombination.Settings; output::Bool=true)` \n ... to compute the photo recombination transition amplitudes and all properties as requested by the given settings. \n A list of lines::Array{PhotoRecombination.Lines} is returned.\n \"\"\"\n function computeLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, nm::Nuclear.Model, grid::Radial.Grid, \n settings::PhotoRecombination.Settings; output::Bool=true)\n println(\"\")\n printstyled(\"PhotoRecombination.computeLines(): The computation of photo-recombination properties starts now ... \\n\", color=:light_green)\n printstyled(\"--------------------------------------------------------------------------------------------------- \\n\", color=:light_green)\n println(\"\")\n lines = PhotoRecombination.determineLines(finalMultiplet, initialMultiplet, settings)\n # Display all selected lines before the computations start\n if settings.printBeforeComputation PhotoRecombination.displayLines(lines) end\n # Determine maximum energy and check for consistency of the grid\n maxEnergy = 0.; for line in lines maxEnergy = max(maxEnergy, line.electronEnergy) end\n nrContinuum = Continuum.gridConsistency(maxEnergy, grid)\n # Calculate all amplitudes and requested properties\n newLines = PhotoRecombination.Line[]\n for line in lines\n newLine = PhotoRecombination.computeAmplitudesProperties(line, nm, grid, nrContinuum, settings) \n push!( newLines, newLine)\n end\n # Print all results to screen\n PhotoRecombination.displayResults(stdout, newLines, settings)\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n if printSummary PhotoRecombination.displayResults(iostream, newLines, settings) end\n #\n if output return( lines )\n else return( nothing )\n end\n end\n\n \n\n \"\"\"\n `PhotoRecombination.determineChannels(finalLevel::Level, initialLevel::Level, settings::PhotoRecombination.Settings)` \n ... to determine a list of RecChannel for a transitions from the initial to final level and by taking into account \n the particular settings of for this computation; an Array{PhotoRecombination.Channel,1} is returned.\n \"\"\"\n function determineChannels(finalLevel::Level, initialLevel::Level, settings::PhotoRecombination.Settings)\n channels = PhotoRecombination.Channel[]; \n symi = LevelSymmetry(initialLevel.J, initialLevel.parity); symf = LevelSymmetry(finalLevel.J, finalLevel.parity) \n for mp in settings.multipoles\n for gauge in settings.gauges\n symList = AngularMomentum.allowedMultipoleSymmetries(symf, mp)\n for symt in symList\n kappaList = AngularMomentum.allowedKappaSymmetries(symi, symt)\n for kappa in kappaList\n # Include further restrictions if appropriate\n if string(mp)[1] == 'E' && gauge == Basics.UseCoulomb \n push!(channels, PhotoRecombination.Channel(mp, Basics.Coulomb, kappa, symt, 0., Complex(0.)) )\n elseif string(mp)[1] == 'E' && gauge == Basics.UseBabushkin \n push!(channels, PhotoRecombination.Channel(mp, Basics.Babushkin, kappa, symt, 0., Complex(0.)) ) \n elseif string(mp)[1] == 'M' \n push!(channels, PhotoRecombination.Channel(mp, Basics.Magnetic, kappa, symt, 0., Complex(0.)) ) \n end \n end\n end\n end\n end\n return( channels ) \n end\n\n\n \"\"\"\n `PhotoRecombination.determineLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, settings::PhotoRecombination.Settings)` \n ... to determine a list of PhotoRecombination.Line's for transitions between levels from the initial- and final-state \n multiplets, and by taking into account the particular selections and settings for this computation; \n an Array{PhotoRecombination.Line,1} is returned. Apart from the level specification, all physical properties are set \n to zero during the initialization process.\n \"\"\"\n function determineLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, settings::PhotoRecombination.Settings)\n if settings.selectLines selectLines = true; \n selectedLines = Basics.determineSelectedLines(settings.selectedLines, initialMultiplet, finalMultiplet)\n else selectLines = false\n end\n \n lines = PhotoRecombination.Line[]\n for i = 1:length(initialMultiplet.levels)\n for f = 1:length(finalMultiplet.levels)\n if selectLines && !((i,f) in selectedLines ) continue end\n ##x println(\"PhotoRecombination.determineLines-aa: i = $i, f = $f\")\n #\n if settings.useIonEnergies\n error(\"Not yet implemented: Given ion energies.\")\n else\n for en in settings.electronEnergies\n if en < 0 continue end \n # Electron energies are still in 'pre-defined' units; convert to Hartree\n en_au = Defaults.convertUnits(\"energy: to atomic\", en)\n omega = en_au + initialMultiplet.levels[i].energy - finalMultiplet.levels[f].energy\n\n channels = PhotoRecombination.determineChannels(finalMultiplet.levels[f], initialMultiplet.levels[i], settings) \n push!( lines, PhotoRecombination.Line(initialMultiplet.levels[i], finalMultiplet.levels[f], en_au, omega, \n EmProperty(0., 0.), true, channels) )\n end\n end\n end\n end\n return( lines )\n end\n\n\n \"\"\"\n `PhotoRecombination.displayLines(lines::Array{PhotoRecombination.Line,1})` \n ... to display a list of lines and channels that have been selected due to the prior settings. A neat table of all selected \n transitions and energies is printed but nothing is returned otherwise.\n \"\"\"\n function displayLines(lines::Array{PhotoRecombination.Line,1})\n println(\" \")\n println(\" Selected photorecombination lines:\")\n println(\" \")\n println(\" \", TableStrings.hLine(175))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(18, \"i-level-f\"; na=2); sb = sb * TableStrings.hBlank(20)\n sa = sa * TableStrings.center(18, \"i--J^P--f\"; na=4); sb = sb * TableStrings.hBlank(22)\n sa = sa * TableStrings.center(10, \"Energy_if\"; na=2); \n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=2)\n sa = sa * TableStrings.center(12, \"Energy e_r\"; na=1); \n sb = sb * TableStrings.center(12, TableStrings.inUnits(\"energy\"); na=2)\n sa = sa * TableStrings.center(10, \"omega\"; na=5); \n sb = sb * TableStrings.center(10, TableStrings.inUnits(\"energy\"); na=4)\n sa = sa * TableStrings.flushleft(57, \"List of multipoles, gauges, kappas and total symmetries\"; na=4) \n sb = sb * TableStrings.flushleft(57, \"partial (multipole, gauge, total J^P) \"; na=4)\n println(sa); println(sb); println(\" \", TableStrings.hLine(175)) \n # \n for line in lines\n sa = \" \"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4)\n energy = line.initialLevel.energy - line.finalLevel.energy\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", energy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.electronEnergy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", line.photonEnergy)) * \" \"\n kappaMultipoleSymmetryList = Tuple{Int64,EmMultipole,EmGauge,LevelSymmetry}[]\n for i in 1:length(line.channels)\n push!( kappaMultipoleSymmetryList, (line.channels[i].kappa, line.channels[i].multipole, line.channels[i].gauge, \n line.channels[i].symmetry) )\n end\n wa = TableStrings.kappaMultipoleSymmetryTupels(85, kappaMultipoleSymmetryList)\n sb = sa * wa[1]; println( sb ) \n for i = 2:length(wa)\n sb = TableStrings.hBlank( length(sa) ) * wa[i]; println( sb )\n end\n end\n println(\" \", TableStrings.hLine(175), \"\\n\")\n #\n return( nothing )\n end\n\n\n \"\"\"\n `PhotoRecombination.displayResults(stream::IO, lines::Array{PhotoRecombination.Line,1}, settings::PhotoRecombination.Settings)` \n ... to list all results, energies, cross sections, etc. of the selected lines. A neat table is printed but nothing is \n returned otherwise.\n \"\"\"\n function displayResults(stream::IO, lines::Array{PhotoRecombination.Line,1}, settings::PhotoRecombination.Settings)\n println(stream, \" \")\n println(stream, \" Photorecombination cross sections for beta^2 * gamma^2 = 1:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(133))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(18, \"i-level-f\" ; na=0); sb = sb * TableStrings.hBlank(20)\n sa = sa * TableStrings.center(16, \"i--J^P--f\" ; na=3); sb = sb * TableStrings.hBlank(19)\n sa = sa * TableStrings.center(12, \"i--Energy--f\"; na=4) \n sb = sb * TableStrings.center(12,TableStrings.inUnits(\"energy\"); na=4)\n sa = sa * TableStrings.center(12, \"omega\" ; na=4) \n sb = sb * TableStrings.center(12, TableStrings.inUnits(\"energy\"); na=4)\n sa = sa * TableStrings.center(12, \"Energy e_p\"; na=3) \n sb = sb * TableStrings.center(12, TableStrings.inUnits(\"energy\"); na=3)\n sa = sa * TableStrings.center(10, \"Multipoles\"; na=1); sb = sb * TableStrings.hBlank(13)\n sa = sa * TableStrings.center(30, \"Cou -- Cross section -- Bab\"; na=3) \n sb = sb * TableStrings.center(30, TableStrings.inUnits(\"cross section\") * \" \" * \n TableStrings.inUnits(\"cross section\"); na=3)\n println(stream, sa); println(stream, sb); println(stream, \" \", TableStrings.hLine(133)) \n # \n for line in lines\n sa = \" \"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(17, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(17, TableStrings.symmetries_if(isym, fsym); na=3)\n en = line.initialLevel.energy - line.finalLevel.energy\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", en)) * \" \"\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", line.photonEnergy)) * \" \"\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", line.electronEnergy)) * \" \"\n multipoles = EmMultipole[]\n for ch in line.channels\n multipoles = push!( multipoles, ch.multipole)\n end\n multipoles = unique(multipoles); mpString = TableStrings.multipoleList(multipoles) * \" \"\n sa = sa * TableStrings.flushleft(11, mpString[1:10]; na=2)\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"cross section: from atomic\", line.crossSection.Coulomb)) * \" \"\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"cross section: from atomic\", line.crossSection.Babushkin)) * \" \"\n println(stream, sa)\n end\n println(stream, \" \", TableStrings.hLine(133))\n #\n #\n if settings.calcAnisotropy \n println(stream, \" \")\n println(stream, \" Anisotropy angular parameters beta_nu of the emitted photons for initially unpolarized ions:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(133))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(18, \"i-level-f\" ; na=0); sb = sb * TableStrings.hBlank(20)\n sa = sa * TableStrings.center(16, \"i--J^P--f\" ; na=3); sb = sb * TableStrings.hBlank(19)\n sa = sa * TableStrings.center(12, \"i--Energy--f\"; na=4) \n sb = sb * TableStrings.center(12,TableStrings.inUnits(\"energy\"); na=4)\n sa = sa * TableStrings.center(12, \"omega\" ; na=4) \n sb = sb * TableStrings.center(12, TableStrings.inUnits(\"energy\"); na=4)\n sa = sa * TableStrings.center(12, \"Energy e_p\"; na=3) \n sb = sb * TableStrings.center(12, TableStrings.inUnits(\"energy\"); na=3)\n sa = sa * TableStrings.center(10, \"Multipoles\"; na=5); sb = sb * TableStrings.hBlank(15)\n sa = sa * TableStrings.flushleft(57, \"beta's\"; na=4) \n println(stream, sa); println(stream, sb); println(stream, \" \", TableStrings.hLine(133)) \n # \n for line in lines\n sa = \" \"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(17, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(17, TableStrings.symmetries_if(isym, fsym); na=3)\n en = line.initialLevel.energy - line.finalLevel.energy\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", en)) * \" \"\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", line.photonEnergy)) * \" \"\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", line.electronEnergy)) * \" \"\n multipoles = EmMultipole[]\n for ch in line.channels\n multipoles = push!( multipoles, ch.multipole)\n end\n multipoles = unique(multipoles); mpString = TableStrings.multipoleList(multipoles) * \" \"\n sa = sa * TableStrings.flushleft(11, mpString[1:10]; na=3)\n be = PhotoRecombination.computeAnisotropyParameter(1, Basics.Coulomb, line); sa = sa * @sprintf(\"%.4e\", be.re) * \" (1, C); \"\n be = PhotoRecombination.computeAnisotropyParameter(1, Basics.Babushkin, line); sa = sa * @sprintf(\"%.4e\", be.re) * \" (1, B); \"\n println(stream, sa); sa = TableStrings.hBlank(102)\n be = PhotoRecombination.computeAnisotropyParameter(2, Basics.Coulomb, line); sa = sa * @sprintf(\"%.4e\", be.re) * \" (2, C); \"\n be = PhotoRecombination.computeAnisotropyParameter(2, Basics.Babushkin, line); sa = sa * @sprintf(\"%.4e\", be.re) * \" (2, B); \"\n println(stream, sa); sa = TableStrings.hBlank(102)\n be = PhotoRecombination.computeAnisotropyParameter(3, Basics.Coulomb, line); sa = sa * @sprintf(\"%.4e\", be.re) * \" (3, C); \"\n be = PhotoRecombination.computeAnisotropyParameter(3, Basics.Babushkin, line); sa = sa * @sprintf(\"%.4e\", be.re) * \" (3, B); \"\n println(stream, sa); sa = TableStrings.hBlank(102)\n be = PhotoRecombination.computeAnisotropyParameter(4, Basics.Coulomb, line); sa = sa * @sprintf(\"%.4e\", be.re) * \" (4, C); \"\n be = PhotoRecombination.computeAnisotropyParameter(4, Basics.Babushkin, line); sa = sa * @sprintf(\"%.4e\", be.re) * \" (4, B); \"\n println(stream, sa); sa = TableStrings.hBlank(102)\n end\n println(stream, \" \", TableStrings.hLine(133))\n end\n #\n #\n if settings.calcTensors \n println(stream, \" \")\n println(stream, \" Reduced statistical tensors of the recombined ion ... not yet implemented !!\")\n println(stream, \" \")\n end\n #\n return( nothing )\n end\n\nend # module\n", "meta": {"hexsha": "abfcc8820a212d456c15d82a54880734920c163d", "size": 30902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-PhotoRecombination.jl", "max_stars_repo_name": "Zstar95/JAC.jl", "max_stars_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-15T11:27:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T11:27:51.000Z", "max_issues_repo_path": "src/module-PhotoRecombination.jl", "max_issues_repo_name": "Zstar95/JAC.jl", "max_issues_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-PhotoRecombination.jl", "max_forks_repo_name": "Zstar95/JAC.jl", "max_forks_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.1942740286, "max_line_length": 151, "alphanum_fraction": 0.5797035791, "num_tokens": 7309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.24422291747900432}} {"text": "###############################################################################\n#\n# NfRelOrd\n#\n###############################################################################\n\n# I don't like that we have to drag S around\n# Still hoping for julia/#18466\n\nmutable struct NfRelOrdSet{T}\n nf::RelativeExtension{T}\n\n function NfRelOrdSet{T}(K::RelativeExtension{T}) where {T}\n a = new(K)\n return a\n end\nend\n\nmutable struct NfRelOrd{T, S} <: Ring\n nf::RelativeExtension{T}\n basis_nf::Vector{RelativeElement{T}}\n basis_mat::Generic.Mat{T}\n basis_mat_inv::Generic.Mat{T}\n basis_pmat::PMat{T, S}\n pseudo_basis::Vector{Tuple{RelativeElement{T}, S}}\n\n disc_abs::NfOrdIdl # used if T == nf_elem\n disc_rel#::NfRelOrdIdl{T} # used otherwise; is a forward declaration\n parent::NfRelOrdSet{T}\n\n isequation_order::Bool\n\n ismaximal::Int # 0 Not known\n # 1 Known to be maximal\n # 2 Known to not be maximal\n\n trace_mat::Generic.Mat{T}\n\n inv_coeff_ideals::Vector{S}\n\n function NfRelOrd{T, S}(K::RelativeExtension{T}) where {T, S}\n z = new{T, S}()\n z.nf = K\n z.parent = NfRelOrdSet{T}(K)\n z.isequation_order = false\n z.ismaximal = 0\n return z\n end\n\n function NfRelOrd{T, S}(K::RelativeExtension{T}, M::PMat{T, S}) where {T, S}\n z = NfRelOrd{T, S}(K)\n z.nf = K\n z.parent = NfRelOrdSet{T}(K)\n z.basis_pmat = M\n z.basis_mat = M.matrix\n return z\n end\n\n function NfRelOrd{T, S}(K::RelativeExtension{T}, M::Generic.Mat{T}) where {T, S}\n z = NfRelOrd{T, S}(K)\n z.nf = K\n z.parent = NfRelOrdSet{T}(K)\n z.basis_mat = M\n z.basis_pmat = pseudo_matrix(M)\n return z\n end\nend\n\n###############################################################################\n#\n# NfRelOrdElem\n#\n###############################################################################\n\nmutable struct NfRelOrdElem{T} <: RingElem\n parent#::NfRelOrd{T, S} # I don't want to drag the S around\n elem_in_nf::RelativeElement{T}\n elem_in_basis::Vector{T}\n has_coord::Bool\n\n function NfRelOrdElem{T}(O::NfRelOrd{T}) where {T}\n z = new{T}()\n z.parent = O\n z.elem_in_nf = zero(nf(O))\n z.elem_in_basis = Vector{T}(degree(O))\n z.has_coord = false\n return z\n end\n\n function NfRelOrdElem{T}(O::NfRelOrd{T}, a::RelativeElement{T}) where {T}\n z = new{T}()\n z.parent = O\n z.elem_in_nf = a\n z.elem_in_basis = Vector{T}(degree(O))\n z.has_coord = false\n return z\n end\n\n function NfRelOrdElem{T}(O::NfRelOrd{T}, a::RelativeElement{T}, arr::Vector{T}) where {T}\n z = new{T}()\n z.parent = O\n z.elem_in_nf = a\n z.elem_in_basis = arr\n z.has_coord = true\n return z\n end\nend\n\n###############################################################################\n#\n# NfRelOrdFracIdl\n#\n###############################################################################\n\nmutable struct NfRelOrdFracIdlSet{T, S}\n order::NfRelOrd{T, S}\n\n function NfRelOrdFracIdlSet{T, S}(O::NfRelOrd{T, S}) where {T, S}\n a = new(O)\n return a\n end\nend\n\nmutable struct NfRelOrdFracIdl{T, S}\n order::NfRelOrd{T, S}\n parent::NfRelOrdFracIdlSet{T, S}\n basis_pmat::PMat{T, S}\n pseudo_basis::Vector{Tuple{RelativeElement{T}, S}}\n basis_mat::Generic.Mat{T}\n basis_mat_inv::Generic.Mat{T}\n den::fmpz\n\n norm\n has_norm::Bool\n\n function NfRelOrdFracIdl{T, S}(O::NfRelOrd{T, S}) where {T, S}\n z = new{T, S}()\n z.order = O\n z.parent = NfRelOrdFracIdlSet{T, S}(O)\n z.has_norm = false\n return z\n end\n\n function NfRelOrdFracIdl{T, S}(O::NfRelOrd{T, S}, M::PMat{T, S}) where {T, S}\n z = NfRelOrdFracIdl{T, S}(O)\n z.basis_pmat = M\n z.basis_mat = M.matrix\n return z\n end\n\n function NfRelOrdFracIdl{T, S}(O::NfRelOrd{T, S}, a::Array{Tuple{T1, S}}) where {T1 <: RelativeElement{T}, S} where T\n z = NfRelOrdFracIdl{T, S}(O)\n z.pseudo_basis = a\n return z\n end\nend\n\n###############################################################################\n#\n# NfRelOrdIdl\n#\n###############################################################################\n\nmutable struct NfRelOrdIdlSet{T, S}\n order::NfRelOrd{T, S}\n\n function NfRelOrdIdlSet{T, S}(O::NfRelOrd{T, S}) where {T, S}\n a = new(O)\n return a\n end\nend\n\nmutable struct NfRelOrdIdl{T, S}\n order::NfRelOrd{T, S}\n parent::NfRelOrdIdlSet{T, S}\n basis_pmat::PMat{T, S}\n pseudo_basis::Vector{Tuple{RelativeElement{T}, S}}\n basis_mat::Generic.Mat{T}\n basis_mat_inv::Generic.Mat{T}\n\n norm\n has_norm::Bool\n is_prime::Int # 0: don't know\n # 1 known to be prime\n # 2 known to be not prime\n splitting_type::Tuple{Int, Int}\n\n minimum\n non_index_div_poly::fq_poly # only used if the ideal is a prime ideal not dividing the index\n p_uniformizer::NfRelOrdElem{T}\n anti_uniformizer::RelativeElement{T}\n\n function NfRelOrdIdl{T, S}(O::NfRelOrd{T, S}) where {T, S}\n z = new{T, S}()\n z.order = O\n z.parent = NfRelOrdIdlSet{T, S}(O)\n z.has_norm = false\n z.is_prime = 0\n z.splitting_type = (0,0)\n return z\n end\n\n function NfRelOrdIdl{T, S}(O::NfRelOrd{T, S}, M::PMat{T, S}) where {T, S}\n z = NfRelOrdIdl{T, S}(O)\n z.basis_pmat = M\n z.basis_mat = M.matrix\n return z\n end\n\n function NfRelOrdIdl{T, S}(O::NfRelOrd{T, S}, a::Array{Tuple{T1, S}}) where {T1 <: RelativeElement{T}, S} where T\n z = NfRelOrdIdl{T, S}(O)\n z.pseudo_basis = a\n return z\n end\nend\n", "meta": {"hexsha": "8ab41d2f547184195c5ef45fea4b9fd5981ca0f1", "size": 5458, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NfRel/NfRelTypes.jl", "max_stars_repo_name": "alexjbest/Hecke.jl", "max_stars_repo_head_hexsha": "ea59d93e7a29e73e1a1ffe103db8ce37c456e405", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NfRel/NfRelTypes.jl", "max_issues_repo_name": "alexjbest/Hecke.jl", "max_issues_repo_head_hexsha": "ea59d93e7a29e73e1a1ffe103db8ce37c456e405", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NfRel/NfRelTypes.jl", "max_forks_repo_name": "alexjbest/Hecke.jl", "max_forks_repo_head_hexsha": "ea59d93e7a29e73e1a1ffe103db8ce37c456e405", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2685185185, "max_line_length": 119, "alphanum_fraction": 0.5511176255, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2442137209116739}} {"text": "\nabstract type Tri end\nabstract type Tet end\n\n\"\"\"\n$(TYPEDEF)\n\nData structure for holding geometry data.\n\"\"\"\nstruct eMesh{T1<:Union{Nothing,Tri},T2<:Union{Nothing,Tet}}\n point::Vector{SVector{3,Float64}}\n tri::Union{Nothing,Vector{SVector{3,Int64}}}\n tet::Union{Nothing,Vector{SVector{4,Int64}}}\n ϵ::Union{Nothing,Vector{Float64}}\n function eMesh( point::Vector{SVector{3,Float64}},\n tri::Union{Nothing,Vector{SVector{3,Int64}}},\n tet::Union{Nothing,Vector{SVector{4,Int64}}}=nothing,\n ϵ::Union{Nothing,Vector{Float64}}=nothing)\n\n T1_ = ifelse(tri == nothing, Nothing, Tri)\n T2_ = ifelse(tet == nothing, Nothing, Tet)\n if T2_ == Tet\n @assert(isa(ϵ, Vector{Float64}))\n @assert(length(ϵ) == length(point), \"length(ϵ) = $(length(ϵ)) but length(point) = $(length(point))\")\n (length(ϵ) != 0) && @assert(0.0 < maximum(ϵ), \"normalized penetration extent must be non-negative\")\n (length(ϵ) != 0) && @assert(minimum(ϵ) == 0.0, \"normalized penetration extent must be zero on the surface of the volume mesh\")\n for k = 1:length(tet)\n (0.0 < volume(point[tet[k]])) || error(\"inverted tetrahedron\")\n end\n else\n @assert(ϵ == nothing)\n end\n (T1_ == T2_ == Nothing) && error(\"a whole lot of nothing\")\n return new{T1_,T2_}(deepcopy(point), deepcopy(tri), deepcopy(tet), deepcopy(ϵ))\n end\n function eMesh(hm::HomogenousMesh, tet::Union{Nothing,Vector{SVector{4,Int64}}}=nothing,\n ϵ::Union{Nothing,Vector{Float64}}=nothing)\n\n point = [SVector{3,Float64}(k) for k = hm.vertices]\n tri = [SVector{3,Int64}(k) for k = hm.faces]\n return eMesh(point, tri, tet, ϵ)\n end\n eMesh{Tri,Nothing}() = eMesh(Vector{SVector{3,Float64}}(), Vector{SVector{3,Int64}}(), nothing, nothing)\n eMesh{Nothing,Tet}() = eMesh(Vector{SVector{3,Float64}}(), nothing, Vector{SVector{4,Int64}}(), Vector{Float64}())\n eMesh{Tri,Tet}() = eMesh(Vector{SVector{3,Float64}}(), Vector{SVector{3,Int64}}(), Vector{SVector{4,Int64}}(), Vector{Float64}())\nend\n\n\"\"\"\n$(SIGNATURES)\n\nConverts an `eMesh` to a mesh that contains only tetrahedrons.\nYou need to do this before adding an `eMesh` as contact geometry.\n\"\"\"\nas_tet_eMesh(e_mesh::eMesh{Tri,Tet}) = eMesh(e_mesh.point, nothing, e_mesh.tet, e_mesh.ϵ)\nas_tet_eMesh(e_mesh::eMesh{Nothing,Tet}) = deepcopy(e_mesh)\n\n\"\"\"\n$(SIGNATURES)\n\nConverts an `eMesh` to a mesh that contains only triangles.\nYou need to do this before adding an `eMesh` as contact geometry.\n\"\"\"\nas_tri_eMesh(e_mesh::eMesh{Tri,Tet}, is_repair::Bool=true) = eMesh(e_mesh.point, e_mesh.tri, nothing, nothing)\nas_tri_eMesh(e_mesh::eMesh{Tri,Nothing}, is_repair::Bool=true) = deepcopy(e_mesh)\nfunction as_tri_eMesh(eM::eMesh{Nothing,Tet}, is_repair::Bool=true)\n\ti3 = Vector{SVector{3,Int64}}()\n\tfor k = 1:n_tet(eM)\n\t\ti_tet = eM.tet[k]\n\t\tϵ_tet = eM.ϵ[i_tet]\n\t\ti_tet_new = sort_so_big_ϵ_last(ϵ_tet, i_tet)\n\t\tpush!(i3, i_tet_new[1:3])\n\tend\n\teM_tri = eMesh(eM.point, i3)\n\tif is_repair\n\t\tmesh_repair!(eM_tri)\n\tend\n\treturn eM_tri\nend\n\nvertex_pos_for_tri_ind(eM::eMesh{Tri,T2}, k::Int64) where {T2} = eM.point[eM.tri[k]]\nvertex_pos_for_tet_ind(eM::eMesh{T1,Tet}, k::Int64) where {T1} = eM.point[eM.tet[k]]\n\nn_point(eM::eMesh) = length(eM.point)\nn_tri(eM::eMesh) = length(eM.tri)\nn_tet(eM::eMesh) = length(eM.tet)\nget_tri(eM::eMesh) = eM.tri\nget_tet(eM::eMesh) = eM.tet\nget_point(eM::eMesh) = eM.point\n\nfunction Base.empty!(e_mesh::eMesh{T1,T2}) where {T1,T2}\n empty!(e_mesh.point)\n (T1 == Nothing) || empty!(e_mesh.tri)\n (T2 == Nothing) || empty!(e_mesh.tet)\n (T2 == Nothing) || empty!(e_mesh.ϵ)\n return nothing\nend\n\nfunction Base.isempty(e_mesh::eMesh{T1,T2}) where {T1,T2}\n is_emp = isempty(e_mesh.point)\n if T1 == Tri\n is_emp = is_emp || isempty(e_mesh.tri)\n end\n if T2 == Tet\n is_emp = is_emp || isempty(e_mesh.tet)\n is_emp = is_emp || isempty(e_mesh.ϵ)\n end\n return is_emp\nend\n\nfunction Base.append!(eM_1::eMesh{T1,T2}, eM_2::eMesh{T1,T2}) where {T1,T2}\n n_1 = n_point(eM_1)\n if T1 != Nothing\n for k = eM_2.tri\n push!(eM_1.tri, k .+ n_1)\n end\n end\n if T2 != Nothing\n for k = eM_2.tet\n push!(eM_1.tet, k .+ n_1)\n end\n append!(eM_1.ϵ, eM_2.ϵ)\n end\n append!(eM_1.point, eM_2.point)\n return nothing\nend\n\n### VERIFICATION\nverify_mesh(eM::eMesh{Tri,Nothing}) = verify_mesh_tri(eM)\nverify_mesh(eM::eMesh{Nothing,Tet}) = verify_mesh_tet(eM)\nfunction verify_mesh(eM::eMesh{Tri,Tet})\n\teM_tri = as_tri_eMesh(eM)\n eM_tet = as_tet_eMesh(eM)\n\tverify_mesh_tri(eM_tri)\n\tverify_mesh_tet(eM_tet)\n eM_tri_2 = as_tri_eMesh(eM_tet)\n (area(eM_tri) ≈ area(eM_tri_2)) || error(\"surfaces where penetration extent is 0.0 is not the same as the tri surface\")\n\treturn nothing\nend\n\nfunction verify_mesh_tet(eM::eMesh{Nothing,Tet})\n length_tet = n_tet(eM)\n length_point = n_point(eM)\n length_ϵ = length(eM.ϵ)\n for k = 1:length_tet\n iΔ = eM.tet[k]\n point_Δ = eM.point[iΔ]\n (0.0 < volume(point_Δ)) || error(\"tet with negative volume\")\n end\n (length_ϵ == length_point) || error(\"number of points not equal to number or ϵ\")\n if !isempty(eM.ϵ)\n (minimum(eM.ϵ) < 0.0) && error(\"normalized penetration extent must be non-negative\")\n (minimum(eM.ϵ) == 0.0) || error(\"normalized penetration extent must be 0.0 somewhere\")\n end\n return nothing\nend\n\nfunction verify_mesh_tri(eM::eMesh{Tri,Nothing})\n for k = 1:n_tri(eM)\n iΔ = eM.tri[k]\n point_Δ = eM.point[iΔ]\n end\n return nothing\nend\n\n### MESH MANIPULATION\n\"\"\"\n$(SIGNATURES)\n\nCreates a transformation matrix by creating a `basic_dh` from `extra_arguments` and then transforms the `eMesh`.\nSee [`basic_dh`](@ref) for how to create common transformation types.\nReflections are not allowed.\n\"\"\"\nfunction transform!(e_mesh::eMesh{T1,T2}, extra_args...) where {T1,T2}\n dh = basic_dh(extra_args...)\n point = e_mesh.point\n for k = 1:n_point(e_mesh)\n point[k] = dh_vector_mul(dh, point[k])\n end\nend\n\nstruct PointObj\n p::SVector{3,Float64}\n w::Float64\n b::Bool\n k::Int64\nend\n\nfunction crop_mesh(eM::eMesh{Tri,Nothing}, plane::SMatrix{1,4,Float64,4})\n function add_cropped_triangle!(eM_new::eMesh{Tri,Nothing}, iΔ::SVector{3,Int64})\n function plane_dot_2(eM_new::eMesh{Tri,Nothing}, plane::SMatrix{1,4,Float64,4}, k::Int64)\n p = get_point(eM_new)[k]\n w = dot(plane[:], onePad(p))\n b = -1.0e-12 < w\n return PointObj(p, w, b, k)\n end\n\n o1 = plane_dot_2(eM_new, plane, iΔ[1])\n o2 = plane_dot_2(eM_new, plane, iΔ[2])\n o3 = plane_dot_2(eM_new, plane, iΔ[3])\n s_bool = o1.b + o2.b + o3.b\n (s_bool == 3) && (push!(eM_new.tri, iΔ)) # all entire triangle\n ((s_bool == 0) || (s_bool == 3)) && (return nothing) # exit function\n (o1.b == o2.b) && ((o1, o2, o3) = (o2, o3, o1)) # put 1 and 2 on opposite sides\n (o2.b == o3.b) && ((o1, o2, o3) = (o3, o1, o2)) # put 2 and 3 on opposite sides\n (o1.b == o2.b) || (o2.b == o3.b) && error(\"something is wrong\") # sanity check\n push!(eM_new.point, weightPoly(o1.p, o2.p, o1.w, o2.w))\n i12 = length(get_point(eM_new))\n push!(eM_new.point, weightPoly(o2.p, o3.p, o2.w, o3.w))\n i23 = length(get_point(eM_new))\n if o2.b # add top of triangle\n push!(eM_new.tri, SVector{3,Int64}(i12, o2.k, i23))\n else # add bottom quadralateral\n push!(eM_new.tri, SVector{3,Int64}(o1.k, i12, i23))\n push!(eM_new.tri, SVector{3,Int64}(o1.k, i23, o3.k))\n end\n end\n\n eM_new = eMesh{Tri,Nothing}()\n append!(eM_new.point, eM.point)\n for iΔ = eM.tri\n add_cropped_triangle!(eM_new, iΔ)\n end\n mesh_repair!(eM_new)\n return eM_new\nend\n\nfunction invert!(eM::eMesh{Tri,Nothing})\n for k = 1:n_tri(eM)\n tri_k = eM.tri[k]\n eM.tri[k] = SVector{3,Float64}(tri_k[3], tri_k[2], tri_k[1])\n end\nend\n\n### MESH REPAIR\nfunction mesh_repair!(e_mesh::eMesh{T1,T2}) where {T1,T2}\n mesh_remove_unused_points!(e_mesh)\n mesh_inplace_rekey!(e_mesh)\n mesh_remove_unused_points!(e_mesh)\n return delete_triangles!(e_mesh)\nend\n\nfunction remove_degenerate!(eM::eMesh)\n\tarea_or_vol(v::SVector{3,SVector{3,Float64}}) = area(v)\n\tarea_or_vol(v::SVector{4,SVector{3,Float64}}) = volume(v)\n\n\ttol = 1.0e-6\n\tfor vec_ind = (eM.tet, eM.tri)\n\t\tif vec_ind != nothing\n\t\t\tv = [area_or_vol(eM.point[vec_ind[k]]) for k = 1:length(vec_ind)]\n\t\t\tmax_v = maximum(v)\n\t\t\ti_bad = findall(v .< max_v * tol)\n\t\t\tdeleteat!(vec_ind, i_bad)\n\t\tend\n\tend\nend\n\nrekey!(v::Nothing, i::Vector{Int64}) = nothing\nrekey!(v::Vector{SVector{N,Int64}}, i::Vector{Int64}) where {N} = replace!(x -> i[x], v)\n\nfunction mesh_inplace_rekey(e_mesh::eMesh{T1,T2}) where {T1,T2}\n e_mesh_copy = deepcopy(e_mesh)\n mesh_inplace_rekey!(e_mesh_copy)\n return e_mesh_copy\nend\n\nfunction mesh_inplace_rekey!(e_mesh::eMesh{T1,T2}) where {T1,T2}\n # Expresses the mesh using the minumum number of points\n\n function shortest_side(e_mesh::eMesh)\n shortest_side(v::Nothing) = Inf\n shortest_side(ind::Vector{SVector{N,Int64}}) where {N} = minimum([shortest_side(e_mesh.point[k]) for k = ind])\n function shortest_side(v::SVector{N,SVector{3,Float64}}) where {N}\n d_min = Inf\n for k = 1:N\n for kk = 1:(k-1)\n d_min = min(d_min, norm(v[k] - v[kk]))\n end\n end\n return d_min\n end\n\n return min(shortest_side(e_mesh.tri), shortest_side(e_mesh.tet))\n end\n\n function inplace_rekey(point::Vector{SVector{3,Float64}}, min_side_length::Float64)\n balltree = BallTree(point; reorder = false)\n idxs = inrange(balltree, point, min_side_length * 0.499) # Assume that all points closer to each other than hald a side length are duplicates\n return first.(sort!.(idxs))\n end\n\n if !isempty(e_mesh) # reducing over an empty collection is not allowed\n min_side_length = shortest_side(e_mesh)\n new_key = inplace_rekey(e_mesh.point, min_side_length)\n rekey!(e_mesh.tri, new_key)\n rekey!(e_mesh.tet, new_key)\n mesh_remove_unused_points!(e_mesh)\n return new_key\n end\n return nothing\nend\n\nfunction mesh_remove_unused_points!(e_mesh::eMesh{T1,T2}) where {T1,T2}\n truth_vector = falses(n_point(e_mesh))\n (T1 != Nothing) && (for k = e_mesh.tri; truth_vector[k] = true; end)\n (T2 != Nothing) && (for k = e_mesh.tet; truth_vector[k] = true; end)\n new_key = cumsum(truth_vector)\n rekey!(e_mesh.tri, new_key)\n rekey!(e_mesh.tet, new_key)\n ind_truth = findall(truth_vector)\n point_new = e_mesh.point[ind_truth]\n empty!(e_mesh.point)\n append!(e_mesh.point, point_new)\n if T2 != Nothing\n ϵ_new = e_mesh.ϵ[ind_truth]\n empty!(e_mesh.ϵ)\n append!(e_mesh.ϵ, ϵ_new)\n end\n return nothing\nend\n\ndelete_triangles!(e_mesh::eMesh{Nothing,T2}) where {T2} = -9999\nfunction delete_triangles!(e_mesh::eMesh{Tri,T2}) where {T2}\n\t# TODO: fix this to only delete triangles for connected meshes\n\n ### make the first index lowest\n for k = 1:n_tri(e_mesh)\n iΔ = e_mesh.tri[k]\n min_index = minimum(iΔ)\n (min_index == iΔ[1]) || (iΔ = SVector(iΔ[3], iΔ[1], iΔ[2]))\n (min_index == iΔ[1]) || (iΔ = SVector(iΔ[3], iΔ[1], iΔ[2]))\n end\n\n ### create a dictionary of key repition counts\n key_type = Vector{Tuple{Int64,SVector{3,Int64}}}\n dict_ind = Dict{SVector{3,Int64},key_type}()\n for k = 1:n_tri(e_mesh)\n iΔ = e_mesh.tri[k]\n sort_iΔ = sort(iΔ)\n !haskey(dict_ind, sort_iΔ) && (dict_ind[sort_iΔ] = key_type() )\n push!(dict_ind[sort_iΔ], (k, iΔ))\n end\n\n ### check for issues is triangle pairs\n i_delete = Vector{Int64}()\n for (key_k, val_k) = dict_ind\n length_val_k = length(val_k)\n if length_val_k == 2\n val_k1 = val_k[1]\n val_k2 = val_k[2]\n (val_k1[2] == val_k2[2]) && error(\"non-opposing triangles\")\n push!(i_delete, val_k1[1], val_k2[1])\n elseif 3 <= length_val_k\n error(\"something is wrong\")\n end\n end\n\n ### Actually delete the opposing triangles\n i_delete = sort(i_delete)\n deleteat!(e_mesh.tri, i_delete)\n\treturn length(i_delete)\nend\n\nfunction sub_div_mesh(eM_ico::eMesh{Tri,T2}, n_div::Int64) where {T2}\n n_end(n::Int64) = div((n + 1) * n, 2)\n n_start(n::Int64) = 1 + n_end(n - 1)\n\n function sub_div_triangle(p::SVector{3,SVector{3,Float64}}, n_div::Int64)\n function sub_div_triangle_vert_index(n_div::Int64)\n i_tri = Vector{SVector{3,Int64}}()\n for k = 1:n_div\n for kk = 0:(k - 1)\n i1 = n_start(k) + kk\n i2 = i1 + k\n i3 = i2 + 1\n push!(i_tri, SVector{3,Int64}(i1, i2, i3))\n end\n for kk = 0:(k - 2)\n i1 = n_start(k) + kk\n i2 = i1 + k + 1\n i3 = i2 - k\n push!(i_tri, SVector{3,Int64}(i1, i2, i3))\n end\n end\n return i_tri\n end\n\n function get_new_point(n_vert::Int64, n_div::Int64, p::SVector{3,SVector{3,Float64}})\n function find_layer_1(i_point::Int64)\n i_end_layer = 1\n i_layer = 1\n while i_end_layer < i_point\n i_layer += 1\n i_end_layer += i_layer\n end\n norm_extent_1 = ifelse(i_point == 1, 0.0, (i_end_layer - i_point) / (i_layer - 1) )\n return i_layer, norm_extent_1\n end\n\n i_layer, norm_extent_1 = find_layer_1(n_vert)\n ϕ_1 = (n_div - i_layer + 1) / n_div\n ϕ_2 = (1 - ϕ_1) * norm_extent_1\n ϕ_3 = 1 - ϕ_1 - ϕ_2\n ϕ = SVector{3,Float64}(ϕ_1, ϕ_2, ϕ_3)\n return sum(p .* ϕ)\n end\n\n point = Vector{SVector{3,Float64}}()\n i_tri_div = sub_div_triangle_vert_index(n_div)\n for k = 1:n_end(n_div + 1)\n push!(point, get_new_point(k, n_div, p))\n end\n return eMesh(point, i_tri_div, nothing, nothing)\n end\n\n eM_ico_div = eMesh{Tri,Nothing}()\n for k = 1:n_tri(eM_ico)\n p = vertex_pos_for_tri_ind(eM_ico, k)\n append!(eM_ico_div, sub_div_triangle(p, n_div))\n end\n mesh_repair!(eM_ico_div)\n return eM_ico_div\nend\n\n### BASIC SHAPES\n\"\"\"\n$(SIGNATURES)\n\nOutputs an `eMesh` for a half-plane.\n\"\"\"\nfunction eMesh_half_plane(plane_w::Float64=1.0, is_include_vis_sides::Bool=false)\n v1, v2, v3 = [SVector{3,Float64}(cos(theta), sin(theta), 0.0) for theta = (0.0, 2*pi/3, 4*pi/3)]\n v4 = SVector{3,Float64}(0.0, 0.0, -1.0) * plane_w\n point = [v1, v2, v3, v4]\n if is_include_vis_sides\n tri = [SVector{3,Int64}(1,2,3), SVector{3,Int64}(1,3,4), SVector{3,Int64}(1,4,2), SVector{3,Int64}(2,4,3)]\n else\n tri = [SVector{3,Int64}(1,2,3)]\n end\n tet = [SVector{4,Int64}(4,1,2,3)]\n ϵ = [0.0, 0.0, 0.0, plane_w]\n return eMesh(point, tri, tet, ϵ)\nend\n\n\"\"\"\n$(SIGNATURES)\n\nOutputs an `eMesh` for a sphere. Larger values of `n_div` create finer discretizations.\n\"\"\"\nfunction eMesh_sphere(rad::Union{Float64,SVector{3,Float64}}=1.0, n_div::Int64=4)\n function make_icosahedron()\n φ = Base.MathConstants.golden\n\n v = Vector{SVector{3,Float64}}()\n for s_1 = (-1.0, +1.0)\n for s_2 = (-1.0, +1.0)\n push!(v, SVector{3,Float64}( 0.0, s_1, φ * s_2) )\n push!(v, SVector{3,Float64}( s_1, φ * s_2, 0.0) )\n push!(v, SVector{3,Float64}(φ * s_2, 0.0, s_1) )\n end\n end\n\n n_ico_vert = 12\n d = zeros(n_ico_vert, n_ico_vert)\n for k = 1:n_ico_vert\n for kk = 1:n_ico_vert\n d[k, kk] = norm(v[k] - v[kk])\n end\n end\n\n v_face_vert = Vector{SVector{3,Int64}}()\n b = d .== 2.0\n for i1 = 1:n_ico_vert\n for i2 = 1:n_ico_vert\n for i3 = 1:n_ico_vert\n if (i1 < i2 < i3) && b[i1, i2] && b[i2, i3] && b[i1, i3]\n p1 = v[i1]\n p2 = v[i2]\n p3 = v[i3]\n n = triangleNormal(p1, p2, p3)\n c = normalize(centroid(p1, p2, p3))\n i_face = ifelse(n ≈ c, SVector{3,Int64}(i1, i2, i3), SVector{3,Int64}(i1, i3, i2))\n push!(v_face_vert, i_face)\n end\n end\n end\n end\n\n push!(v, SVector{3,Float64}(0,0,0))\n v_tet = Vector{SVector{4,Int64}}()\n for k = 1:length(v_face_vert)\n push!(v_tet, SVector{4,Int64}(13, v_face_vert[k]...))\n end\n ϵ = vcat(zeros(n_ico_vert), 1.0)\n return eMesh(v, v_face_vert, v_tet, ϵ)\n end\n\n function volumize_about(eM::eMesh{Tri,Nothing})\n i_tet = Vector{SVector{4,Int64}}()\n n_vert = n_point(eM)\n n_center = n_vert + 1\n for k = 1:n_tri(eM)\n push!(i_tet, SVector{4,Int64}(n_center, eM.tri[k]...))\n end\n ϵ = vcat(zeros(n_vert), 1.0)\n point = deepcopy(eM.point)\n push!(point, zeros(SVector{3,Float64}))\n return eMesh(point, eM.tri, i_tet, ϵ)\n end\n\n function project_to_sphere!(eM::eMesh)\n for k = 1:n_point(eM)\n eM.point[k] = normalize(eM.point[k])\n end\n return nothing\n end\n\n eM_ico = make_icosahedron()\n eM_ico_div = sub_div_mesh(eM_ico, n_div)\n project_to_sphere!(eM_ico_div)\n\n rad = ones(SVector{3,Float64}) .* rad\n transform!(eM_ico_div, Diagonal(rad))\n\n return volumize_about(eM_ico_div)\nend\n\nfunction output_box_ind()\n oriented_box_faces = (\n SVector{4, Int64}(1,3,5,7), # -x\n SVector{4, Int64}(2,6,4,8), # +x\n SVector{4, Int64}(1,5,2,6), # -y\n SVector{4, Int64}(3,4,7,8), # +y\n SVector{4, Int64}(1,2,3,4), # -z\n SVector{4, Int64}(5,7,6,8), # +z\n )\n ϵ = zeros(Float64,8)\n push!(ϵ, 1.0)\n tri = Vector{SVector{3,Int64}}()\n tet = Vector{SVector{4,Int64}}()\n for k = 1:6\n bf_k = oriented_box_faces[k]\n push!(tri, bf_k[SVector{3,Int64}(1,3,4)])\n push!(tri, bf_k[SVector{3,Int64}(1,4,2)])\n end\n for k = 1:length(tri)\n tri_k = tri[k]\n push!(tet, SVector{4,Int64}(9, tri_k[1], tri_k[2], tri_k[3]))\n end\n return tri, tet, ϵ\nend\n\n\"\"\"\n$(SIGNATURES)\n\nOutputs an `eMesh` for a box.\n\"\"\"\nfunction eMesh_box(r::Union{Float64,SVector{3,Float64}}=1.0, c::SVector{3,Float64}=zeros(SVector{3,Float64}))\n point = [\n SVector{3,Float64}(-1,-1,-1),\n SVector{3,Float64}(+1,-1,-1),\n SVector{3,Float64}(-1,+1,-1),\n SVector{3,Float64}(+1,+1,-1),\n SVector{3,Float64}(-1,-1,+1),\n SVector{3,Float64}(+1,-1,+1),\n SVector{3,Float64}(-1,+1,+1),\n SVector{3,Float64}(+1,+1,+1),\n SVector{3,Float64}( 0, 0, 0),\n ]\n tri, tet, ϵ = output_box_ind()\n e_mesh = eMesh(point, tri, tet, ϵ)\n r = r .* ones(SVector{3,Float64})\n transform!(e_mesh, SMatrix{3,3,Float64,9}(r[1], 0, 0, 0, r[2], 0, 0, 0, r[3]))\n transform!(e_mesh, c)\n return e_mesh\nend\n\nconst SF3 = SVector{3,Float64}\nconst SI3 = SVector{3,Int64}\nconst SI4 = SVector{4,Int64}\n\nfunction create_2D_circle(rad::Float64=1.0; n::Int64=12)\n points_2D = Vector{SF3}()\n tri_2D = Vector{SI3}()\n i_center = n + 1\n θ_range = LinRange(0.0, 2 * π, n + 1)[2:end]\n for (k, θ) = enumerate(θ_range)\n s, c = sincos(θ)\n push!(points_2D, rad * SF3(c, s, 0.0))\n push!(tri_2D, SI3(k, mod1(k + 1, n), i_center))\n end\n push!(points_2D, SF3(0, 0, 0))\n return eMesh(points_2D, tri_2D)\nend\n\nfunction smallest_first(v::SI4)\n\t_, i = findmin(v)\n\treturn SI4(v[i], v[mod1(i + 1, 4)], v[mod1(i + 2, 4)], v[mod1(i + 3, 4)])\nend\n\nfunction add_stuff_for_extrude!(tri::Vector{SI3}, tet::Vector{SI4}, k::Int64, i_tri_k::SI3, n_✴_2D::Int64)\n\tb1, b2, b3 = i_tri_k\n\tt4, t5, t6 = i_tri_k .+ n_✴_2D\n\ti_center = k + n_✴_2D * 2\n\toriented_slice_faces = (\n SI4(b1,b2,t5,t4),\n SI4(b2,b3,t6,t5),\n SI4(b1,t4,t6,b3)\n )\n tri_add = Vector{SI3}()\n push!(tri_add, SI3(b1,b3,b2))\n push!(tri_add, SI3(t4,t5,t6))\n for bf_k = oriented_slice_faces\n\t\tbf_k = smallest_first(bf_k)\n\t\tpush!(tri_add, bf_k[SI3(1,2,3)])\n push!(tri_add, bf_k[SI3(1,3,4)])\n end\n for tri_k = tri_add\n push!(tri, tri_k)\n push!(tet, SI4(i_center, tri_k[1], tri_k[2], tri_k[3]))\n end\nend\n\nfunction verify_trianges_have_same_normal(surf::eMesh{Tri,Nothing})\n\tn̂ = [triangleNormal(vertex_pos_for_tri_ind(surf, k)) for k = 1:n_tri(surf)]\n\tn̂_mean = n̂[1]\n\tfor n̂_k = n̂\n\t\t(n̂_k ≈ n̂_mean) || error(\"All triangles must have the same normal.\")\n\tend\n\treturn n̂_mean\nend\n\n\"\"\"\n$(SIGNATURES)\n\nExtrudes a planar `eMesh` of type `eMesh{Tri,Nothing}` into a type `eMesh{Tri,Tet}` in the direction of the plane\nnormal. This direction is detected automatically.\nThe function errors if the points do not lie on a plane.\n\"\"\"\nfunction extrude_mesh(surf::eMesh{Tri,Nothing}, thick::Float64)\n\tn̂ = verify_trianges_have_same_normal(surf)\n\n tri_2D = surf.tri\n points_2D = surf.point\n\tn_▲_2D = length(tri_2D )\n\tn_✴_2D = length(points_2D)\n point_lo = points_2D .- [n̂ * thick / 2]\n point_hi = points_2D .+ [n̂ * thick / 2]\n point_centroid = [centroid(points_2D[k]) for k = tri_2D]\n point = vcat(point_lo, point_hi, point_centroid)\n ϵ = vcat(zeros(2 * n_✴_2D), ones(n_▲_2D))\n tri = Vector{SI3}()\n tet = Vector{SI4}()\n for (k, i_tri_k) = enumerate(tri_2D)\n\t\tadd_stuff_for_extrude!(tri, tet, k, i_tri_k, n_✴_2D)\n end\n eM_thick = eMesh(point, tri, tet, ϵ)\n\tmesh_repair!(eM_thick)\n return eM_thick\nend\n\n\"\"\"\n$(SIGNATURES)\n\nOutputs an `eMesh` for a cylinder.\n\"\"\"\nfunction eMesh_cylinder(rad::Float64=1.0, height::Float64=1.0; n::Int64=6)\n\teM_circle = create_2D_circle(rad, n=n)\n\treturn extrude_mesh(eM_circle, height)\nend\n", "meta": {"hexsha": "552d3eebd995211309bd177143d3649e5e57db1c", "size": 22254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometry/mesh.jl", "max_stars_repo_name": "ryanelandt/PressureFieldContact.jl", "max_stars_repo_head_hexsha": "a8247c895666bf0475d65a239f4a6166e3cfebe1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-06-24T23:58:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:36.000Z", "max_issues_repo_path": "src/geometry/mesh.jl", "max_issues_repo_name": "ryanelandt/PressureFieldContact.jl", "max_issues_repo_head_hexsha": "a8247c895666bf0475d65a239f4a6166e3cfebe1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-05-05T02:48:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T16:22:45.000Z", "max_forks_repo_path": "src/geometry/mesh.jl", "max_forks_repo_name": "ryanelandt/SoftContact.jl", "max_forks_repo_head_hexsha": "a8247c895666bf0475d65a239f4a6166e3cfebe1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:29:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T07:51:13.000Z", "avg_line_length": 33.2149253731, "max_line_length": 150, "alphanum_fraction": 0.5936910218, "num_tokens": 7801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24397418133274887}} {"text": "#InspectDR: Base functionnality and types\n#-------------------------------------------------------------------------------\n\n#AnnotationArea\n#TODO: Themes: Define StyleInfo/style?\n#TODO: Themes: Vector/Dict of StyleInfo/Layout?\n\n\n#==Abstracts\n===============================================================================#\nabstract Plot\nabstract PlotCanvas\n\n\n#==Constants\n===============================================================================#\nconst DInf = convert(DReal, Inf)\nconst DNaN = convert(DReal, NaN)\n\nconst COLOR_TRANSPARENT = ARGB32(0, 0, 0, 0)\n\nconst COLOR_BLACK = RGB24(0, 0, 0)\nconst COLOR_WHITE = RGB24(1, 1, 1)\n\nconst COLOR_RED = RGB24(1, 0, 0)\nconst COLOR_GREEN = RGB24(0, 1, 0)\nconst COLOR_BLUE = RGB24(0, 0, 1)\n\n\n#==Plot-level structures\n===============================================================================#\n#=Input structures are high-level constructs describing the plot. They will\nbe broken down to lower-level structures later on.\n=#\n\ntype LineAttributes <: AttributeList\n\tstyle\n\twidth #[0, 10]\n\tcolor\nend\nline(;style=:solid, width=1, color=COLOR_BLACK) =\n\tLineAttributes(style, width, color)\n\n#\"line\" constructor:\n#TODO: Inadequate\n#eval(genexpr_attriblistbuilder(:line, LineAttributes, reqfieldcnt=0))\n\ntype GlyphAttributes <: AttributeList #Don't use \"Symbol\" - name used by Julia\n#==IMPORTANT:\nEdge width & color taken from LineAttributes\n==#\n\tshape #because \"type\" is reserved\n\tsize #of glyph. edge width taken from LineAttributes\n\tcolor #glyph linecolor. = nothing to match line.color\n\tfillcolor\nend\nglyph(;shape=:none, size=3, color=nothing, fillcolor=nothing) =\n\tGlyphAttributes(shape, size, color, fillcolor)\n\n#\"glyph\" constructor:\n#TODO: Inadequate\n#eval(genexpr_attriblistbuilder(:glyph, GlyphAttributes, reqfieldcnt=0))\n\ntype GridAttributes <: AttributeList\n\t#Bool values\n\tvmajor\n\tvminor\n\thmajor\n\thminor\nend\ngrid(;vmajor=false, vminor=false, hmajor=false, hminor=false) =\n\tGridAttributes(vmajor, vminor, hmajor, hminor)\n\n#Dispatchable scale:\nimmutable AxisScale{T}\n\tcall{T}(t::Type{AxisScale{T}}) = error(\"$t not supported\")\n\tcall(::Type{AxisScale{:lin}}) = new{:lin}()\n\tcall(::Type{AxisScale{:log2}}) = new{:log2}()\n\tcall(::Type{AxisScale{:log10}}) = new{:log10}()\n\tcall(::Type{AxisScale{:dB10}}) = new{:dB10}()\n\tcall(::Type{AxisScale{:dB20}}) = new{:dB20}()\n\n\t#Aliases:\n\tcall(::Type{AxisScale{:log}}) = new{:log10}()\nend\nAxisScale(t::Symbol) = AxisScale{t}()\n\n#Specifies configuration of axes:\nabstract Axes\n\n#Rectilinear axis (ex: normal cartesian +logarithmic, ...):\nimmutable AxesRect <: Axes\n\txscale::AxisScale\n\tyscale::AxisScale\nend\nAxesRect(xscale::Symbol, yscale::Symbol) = AxesRect(AxisScale{xscale}(), AxisScale{yscale}())\nAxesRect() = AxesRect(:lin, :lin)\n\n#Curvilinear axes (ex: polar plots):\nimmutable AxesCurv <: Axes\n\trscale::AxisScale #Radial scale could be \nend\nAxesCurv(rscale::Symbol=:lin) = AxesCurv(AxisScale{rscale}())\n\nimmutable AxesSmith{T} <: Axes\n\tref::Float64 #Y/Zref\n\tcall{T}(t::Type{AxesSmith{T}}, ref::Real) = error(\"$t not supported\")\n\tcall(::Type{AxesSmith{:Z}}, ref::Real) = new{:Z}(ref)\n\tcall(::Type{AxesSmith{:Y}}, ref::Real) = new{:Y}(ref)\nend\nAxesSmith(t::Symbol, ref::Real=1) = AxesSmith{t}(ref)\nAxesSmith(t::Symbol, ref::Void) = AxesSmith(t)\n\ntype Waveform{T}\n\tid::DisplayString\n\tds::T\n\tline::LineAttributes\n\tglyph::GlyphAttributes\n\text::PExtents2D\nend\n\n#Input waveform:\ntypealias IWaveform Waveform{IDataset}\n\n#Display waveform (concrete (x, y) pair):\ntypealias DWaveform Waveform{Vector{Point2D}}\n\n#=TODO:\ntypealias DWaveformCplx Waveform{PointComplex}\nto track x-values of complex data??\n=#\n\ntype Annotation\n\ttitle::DisplayString\n\txlabel::DisplayString\n\tylabel::DisplayString\n\ttimestamp::DisplayString\nend\nAnnotation(;title=\"\") = Annotation(title, \"\", \"\", Libc.strftime(time()))\n\ntype Font\n\tname::AbstractString\n\t_size::Float64\n\tbold::Bool\nend\nFont(name::AbstractString, _size::Real; bold::Bool=false) = Font(name, _size, bold)\nFont(_size::Real; bold::Bool=false) = Font(defaults.fontname, _size, bold)\n\n#Legend layout/style\ntype LegendLStyle\n\tenabled::Bool\n\t#autosize::Bool Auto-compute width from text.\n\tfont::Font\n\t#position: left/right/...\n\twidth::Float64\n\t#border::Bool\n\t#wborder\n\tvgap::Float64 #Vertical spacing between (% of text height).\n\tlinegap::Float64 #Spacing between line and label (% of M character).\n\tlinelength::Float64 #length of line segment to display.\nend\n\n#Plot layout\n#TODO: Split Layout into \"StyleInfo\" - which includes Layout??\ntype Layout\n\thtitle::Float64 #Title allocation\n\twaxlabel::Float64 #Vertical axis label allocation (width)\n\thaxlabel::Float64 #Horizontal axis label allocation (height)\n\twnolabels::Float64 #Width to use where no labels are displayed\n\n\twticklabel::Float64 #y-axis values allocation (width)\n\thticklabel::Float64 #x-axis values allocation (height)\n\thlabeloffset::Float64\n\tvlabeloffset::Float64\n\n\ttframe::Float64 #Frame thickness\n\n\twdata::Float64 #Suggested width of data (graph) area\n\thdata::Float64 #Suggested height of data (graph) area\n\n\tfnttitle::Font\n\tfntaxlabel::Font\n\tfntticklabel::Font\n\tfnttime::Font\n\n\tgrid::GridAttributes\n\tlegend::LegendLStyle\n\txlabelformat::TickLabelStyle\n\tylabelformat::TickLabelStyle\n\tshowtimestamp::Bool\nend\nLayout(;fontname::AbstractString=defaults.fontname, fontscale=defaults.fontscale) =\n\tLayout(\n\t20*fontscale, 20*fontscale, 20*fontscale, 45, #Title/main labels\n\t60*fontscale, 15*fontscale, 3, 7, 2, #Ticks/frame\n\tdefaults.wdata, defaults.hdata,\n\tFont(fontname, fontscale*14, bold=true), #Title\n\tFont(fontname, fontscale*14), Font(fontname, fontscale*12), #Axis/Tick labels\n\tFont(fontname, fontscale*8), #Time stamp\n\tGridAttributes(true, false, true, false),\n\tLegendLStyle(false, Font(fontname, fontscale*12), 100.0, .25, 0.5, 20),\n\tTickLabelStyle(), TickLabelStyle(), defaults.showtimestamp\n)\n\n#Tag data as being part of a given coordinate system:\nimmutable CoordSystem{ID}; end\ntypealias DeviceCoord CoordSystem{:dev}\ntypealias NormCoord CoordSystem{:norm}\ntypealias DataCoord CoordSystem{:data}\n\nimmutable TypedCoord{CT<:CoordSystem}\n\tv::DReal\nend\n#Annotation coordinates can match data or be normalized to plot bounds (0 -> 1):\ntypealias AnnotationCoord Union{TypedCoord{NormCoord}, TypedCoord{DataCoord}}\ncoord(s::Symbol, v::DReal) = TypedCoord{CoordSystem{s}}(v)\n\ntype TextAnnotation\n\ttext::DisplayString\n\tpt::Point2D #Data coordinates - set NaN to use offsets only\n\txoffset::DReal #Normalized to [0,1] plot bounds\n\tyoffset::DReal #Normalized to [0,1] plot bounds\n\tfont::Font\n\tcolor::Colorant\n\tangle::DReal #Degrees\n\talign::Symbol #tl, tc, tr, cl, cc, cr, bl, bc, br\nend\n#Don't use \"text\"... high probability of collisions when exported...\natext(text::AbstractString; x::Real=DNaN, y::Real=DNaN, xoffset=0, yoffset=0,\n\tfont=Font(10), color=COLOR_BLACK, angle=0, align=:bl) =\n\tTextAnnotation(text, Point2D(x,y), xoffset, yoffset, font, color, angle, align)\n\ntype HVMarker\n\tvmarker::Bool #false: hmarker\n\tpos::DReal\n\tline::LineAttributes\nend\nvmarker(pos, line=InspectDR.line()) = HVMarker(true, pos, line)\nhmarker(pos, line=InspectDR.line()) = HVMarker(false, pos, line)\n\n#2D plot.\ntype Plot2D <: Plot\n\tlayout::Layout\n\taxes::Axes\n\tannotation::Annotation\n\n\t#Plot extents (access using getextents):\n\text_data::PExtents2D #Maximum extents of data\n\text_full::PExtents2D #Defines \"full\" zoom when combined with ext_data\n\text::PExtents2D #Current/active extents\n\n\tdata::Vector{IWaveform}\n\tmarkers::Vector{HVMarker}\n\tatext::Vector{TextAnnotation}\n\n\t#Display data cache:\n\tinvalid_ddata::Bool #Is cache of display data invalid?\n\tdisplay_data::Vector{DWaveform} #Clipped to current extents\n\n\t#Maximum # of x-pts in display:\n\t#TODO: move to layout?\n\txres::Int\nend\n\nPlot2D(;title=\"\") = Plot2D(Layout(), AxesRect(), Annotation(title=title),\n\tPExtents2D(), PExtents2D(), PExtents2D(), [], [], [], true, [], 1000\n)\n\ntype Multiplot\n\ttitle::DisplayString\n\n\tsubplots::Vector{Plot}\n\tncolumns::Int\n\n\t#Default width/height of plots\n\twplot::Float64\n\thplot::Float64\n\n\thtitle::Float64 #Title height allocation\n\tfnttitle::Font\nend\nMultiplot(;title=\"\", ncolumns=1, titlefont=Font(defaults.fontname, 20),\n\t\twplot=defaults.wplot, hplot=defaults.hplot) =\n\tMultiplot(title, [], ncolumns, wplot, hplot, 30, titlefont)\n\n\n#==Constructor-like functions\n===============================================================================#\n\n#axes function:\n#Interface is a bit irregular, but should be easy to use...\n#-------------------------------------------------------------------------------\nfunction axes(a1::Symbol)\n\tif :smith == a1\n\t\treturn AxesSmith(:Z)\n\telseif :polar == a1\n\t\treturn AxesCurv()\n\telse\n\t\tthrow(MethodError(axes, (a1,)))\n\tend\nend\n\nfunction axes(a1::Symbol, a2::Symbol; ref = nothing)\n\tif :smith == a1\n\t\treturn AxesSmith(a2, ref)\n\telseif ref != nothing\n\t\terror(\"cannot set ref for axes(:$a1, :$a2)\")\n\tend\n\n\tif :polar == a1\n\t\treturn AxesCurv(a2)\n\telse\n\t\treturn AxesRect(a1, a2)\n\tend\nend\n\nfunction axes(a1::Symbol, a2::Symbol, a3::Symbol)\n\tif :polar == a1\n\t\treturn AxesCurv(a2, a3)\n\telse\n\t\tthrow(MethodError(axes, (a1,a2,a3)))\n\tend\nend\n\n\n#==Accessors\n===============================================================================#\n_width(style::LegendLStyle) = style.width\n\ngetextents(d::IWaveform) = getextents(d.ds)\nfunction getextents(dlist::Vector{IWaveform})\n\tresult = PExtents2D(DNaN, DNaN, DNaN, DNaN)\n\tfor d in dlist\n\t\tresult = union(result, d.ext)\n\tend\n\treturn result\nend\n\n\n#==Mutators\n===============================================================================#\nsettitle(mplot::Plot2D, title::DisplayStringArg) =\n\t(mplot.annotation.title = DisplayString(title))\n\nsettitle(mplot::Multiplot, title::DisplayStringArg) =\n\t(mplot.title = DisplayString(title))\n\n\n#==\"add\" interface\n===============================================================================#\n\nfunction _add(mp::Multiplot, plot::Plot2D)\n\tpush!(mp.subplots, plot)\n\treturn plot\nend\n_add{T<:Plot}(mp::Multiplot, ::Type{T}) = _add(mp, T())\n\n\n#Set dataf1=false to overwrite optimizations for functions of 1 argument.\nfunction _add(plot::Plot2D, x::Vector, y::Vector; id::AbstractString=\"\", dataf1=true)\n\tif dataf1\n\t\tdataf1 = isincreasing(x) #Can we use optimizations?\n\tend\n\text = PExtents2D() #Don't care at the moment\n\tds = IWaveform(id, IDataset{dataf1}(x, y), line(), glyph(), ext)\n\tpush!(plot.data, ds)\n\treturn ds\nend\n\nfunction _add(plot::Plot2D, marker::HVMarker)\n\tpush!(plot.markers, marker)\n\treturn marker\nend\n\nfunction _add(plot::Plot2D, a::TextAnnotation)\n\tpush!(plot.atext, a)\n\treturn a\nend\n\n\n#==Mapping/interpolation functions\n===============================================================================#\n\n#Mapping functions, depending on axis type:\n#-------------------------------------------------------------------------------\ndatamap{T<:Number}(::Type{T}, ::AxisScale) = (x::T)->DReal(x)\ndatamap{T<:Number}(::Type{T}, ::AxisScale{:dB10}) = (x::T)->(5*log10(DReal(abs2(x))))\ndatamap{T<:Number}(::Type{T}, ::AxisScale{:dB20}) = (x::T)->(10*log10(DReal(abs2(x))))\ndatamap{T<:Number}(::Type{T}, ::AxisScale{:log2}) =\n\t(x::T)->(x<0? DNaN: log2(DReal(x)))\ndatamap{T<:Number}(::Type{T}, ::AxisScale{:log10}) =\n\t(x::T)->(x<0? DNaN: log10(DReal(x)))\n#TODO: find a way to show negative values for log10?\n\ndatamap_rev{T<:Number}(::Type{T}, ::AxisScale) = (x::T)->DReal(x)\n#NOTE: Values dBs remain in dBs for readability\ndatamap_rev{T<:Number}(::Type{T}, ::AxisScale{:log2}) = (x::T)->(2.0^x)\ndatamap_rev{T<:Number}(::Type{T}, ::AxisScale{:log10}) = (x::T)->(10.0^x)\n\ndatamap_rev{T<:Number}(v::T, s::AxisScale) = datamap_rev(T,s)(v) #One-off conversion\n\n\n#Extents mapping functions, depending on axis type:\n#-------------------------------------------------------------------------------\nextentsmap(::AxisScale) = (x::DReal)->x #Most axis types don't need to re-map extents.\n#NOTE: Extents in dBs remain extents in dBs\nextentsmap(t::AxisScale{:log2}) = datamap(DReal, t)\nextentsmap(t::AxisScale{:log10}) = datamap(DReal, t)\n\nextentsmap_rev(::AxisScale) = (x::DReal)->x #Most axis types don't need to re-map extents.\n#NOTE: Extents in dBs remain extents in dBs\nextentsmap_rev(t::AxisScale{:log2}) = datamap_rev(DReal, t)\nextentsmap_rev(t::AxisScale{:log10}) = datamap_rev(DReal, t)\n\n\n#==Plot extents\n===============================================================================#\n\nfunction invalidate_extents(plot::Plot2D)\n\t#If extents are no longer valid, neither is display cache:\n\tplot.invalid_ddata = true\nend\n\nfunction invalidate_datalist(plot::Plot2D)\n\tplot.invalid_ddata = true\nend\n\nrescale(ext::PExtents2D, axes::Axes) = ext #Default\nfunction rescale(ext::PExtents2D, axes::AxesRect)\n\txmap = extentsmap(axes.xscale)\n\tymap = extentsmap(axes.yscale)\n\treturn PExtents2D(\n\t\txmap(ext.xmin), xmap(ext.xmax),\n\t\tymap(ext.ymin), ymap(ext.ymax)\n\t)\nend\nrescale_rev(ext::PExtents2D, axes::Axes) = ext #Default\nfunction rescale_rev(ext::PExtents2D, axes::AxesRect)\n\txmap = extentsmap_rev(axes.xscale)\n\tymap = extentsmap_rev(axes.yscale)\n\treturn PExtents2D(\n\t\txmap(ext.xmin), xmap(ext.xmax),\n\t\tymap(ext.ymin), ymap(ext.ymax)\n\t)\nend\n\n#Accessor:\ngetextents(plot::Plot2D) = plot.ext\ngetextents_xfrm(plot::Plot2D) = rescale(plot.ext, plot.axes)\n\n#Full extents are always merged (ext_full expected to be incomplete):\ngetextents_full(plot::Plot2D) = merge(plot.ext_data, plot.ext_full)\n\n#Set active plot extents using data coordinates:\nfunction setextents(plot::Plot2D, ext::PExtents2D, hallowed::Bool=true, vallowed::Bool=true)\n\txmin = ext.xmin; xmax = ext.xmax; ymin = ext.ymin; ymax = ext.ymax\n\tif !hallowed\n\t\txmin = plot.ext.xmin\n\t\txmax = plot.ext.xmax\n\tend\n\tif !vallowed\n\t\tymin = plot.ext.ymin\n\t\tymax = plot.ext.ymax\n\tend\n\t#Automatically fill-in any NaN fields, if possible:\n\tplot.ext = merge(getextents_full(plot), PExtents2D(xmin, xmax, ymin, ymax))\n\tinvalidate_extents(plot)\nend\n\n#Set active plot extents using xfrm display coordinates:\nsetextents_xfrm(plot::Plot2D, ext::PExtents2D, hallowed::Bool=true, vallowed::Bool=true) =\n\tsetextents(plot, rescale_rev(ext, plot.axes), hallowed, vallowed)\n\nfunction setextents_full(plot::Plot2D, ext::PExtents2D)\n\tplot.ext_full = ext\nend\n\n\n#==Plot/graph bounding boxes\n===============================================================================#\n\naspect_square(::Axes) = false\naspect_square(::AxesSmith) = true\n\n#Returns a centered bounding box with square aspect ratio.\nfunction squarebounds(bb::BoundingBox)\n\tw = width(bb); h = height(bb)\n\txmin = bb.xmin; xmax = bb.xmax\n\tymin = bb.ymin; ymax = bb.ymax\n\tif w < h\n\t\thdim = w / 2\n\t\tc = (ymin + ymax) / 2\n\t\tymin = c - hdim; ymax = c + hdim\n\telse\n\t\thdim = h / 2\n\t\tc = (xmin + xmax) / 2\n\t\txmin = c - hdim; xmax = c + hdim\n\tend\n\treturn BoundingBox(xmin, xmax, ymin, ymax)\nend\n\n#Get bounding box of graph (plot data area):\nfunction graphbounds(plotb::BoundingBox, lyt::Layout)\n\txmin = plotb.xmin + lyt.waxlabel + lyt.wticklabel\n\txmax = plotb.xmax\n\txmax -= lyt.legend.enabled? _width(lyt.legend): lyt.wnolabels\n\tymin = plotb.ymin + lyt.htitle\n\tymax = plotb.ymax - lyt.haxlabel - lyt.hticklabel\n\n\t#Avoid division by zero, inversions, ...\n\tif xmin >= xmax\n\t\tc = (xmin + xmax)/2\n\t\txmin = c - 0.5\n\t\txmax = c + 0.5\n\tend\n\tif ymin >= ymax\n\t\tc = (ymin + ymax)/2\n\t\tymin = c - 0.5\n\t\tymax = c + 0.5\n\tend\n\n\treturn BoundingBox(xmin, xmax, ymin, ymax)\nend\n\nfunction graphbounds(plotb::BoundingBox, lyt::Layout, axes::Axes)\n\tgraphbb = graphbounds(plotb, lyt)\n\tif aspect_square(axes)\n\t\tgraphbb = squarebounds(graphbb)\n\tend\n\treturn graphbb\nend\n\n#Get bounding box of entire plot:\nfunction plotbounds(lyt::Layout, graphw::Float64, graphh::Float64)\n\txmax = graphw + lyt.waxlabel + lyt.wticklabel\n\txmax += lyt.legend.enabled? _width(lyt.legend): lyt.wnolabels\n\tymax = graphh + lyt.htitle + lyt.haxlabel + lyt.hticklabel\n\treturn BoundingBox(0, xmax, 0, ymax)\nend\n\n#Get suggested plot bounds:\nfunction plotbounds(lyt::Layout, axes::Axes)\n\twdata = lyt.wdata; hdata = lyt.hdata\n\tif aspect_square(axes)\n\t\twdata = hdata = min(wdata, hdata)\n\tend\n\treturn plotbounds(lyt, wdata, hdata)\nend\n\n\n#==Pre-processing display data\n===============================================================================#\n\nfunction _reduce(input::IWaveform, ext::PExtents2D, xres_max::Integer)\n\treturn DWaveform(input.id, _reduce(input.ds, ext, xres_max), input.line, input.glyph, input.ext)\nend\n\n_reduce(inputlist::Vector{IWaveform}, ext::PExtents2D, xres_max::Integer) =\n\tmap((input)->_reduce(input, ext, xres_max::Integer), inputlist)\n\n#Rescale input dataset:\n#-------------------------------------------------------------------------------\nfunction _rescale{T<:Number}(d::Vector{T}, scale::AxisScale)\n\t#Apparently, passing functions as arguments is not efficient in Julia.\n\t#-->Specializing on AxisScale, hoping to improve efficiency on dmap:\n\tdmap = datamap(T, scale)\n\n\tresult = Array(DReal, length(d))\n\tfor i in 1:length(d)\n\t\tresult[i] = dmap(d[i])\n\tend\n\treturn result\nend\n_rescale{T<:Number}(d::Vector{T}, scale::AxisScale{:lin}) = d #Optimization: Linear scale does not need re-scaling\n_rescale{T<:IDataset}(input::T, xscale::AxisScale, yscale::AxisScale) =\n\tT(_rescale(input.x, xscale), _rescale(input.y, yscale))\n\nfunction _rescale(input::IWaveform, xscale::AxisScale, yscale::AxisScale)\n\tds = _rescale(input.ds, xscale, yscale)\n\treturn IWaveform(input.id, ds, input.line, input.glyph, getextents(ds))\nend\n\n#Specialized on xscale/yscale for efficiency:\n_rescale(inputlist::Vector{IWaveform}, xscale::AxisScale, yscale::AxisScale) =\n\tmap((input)->_rescale(input, xscale, yscale), inputlist)\n\n_rescale(inputlist::Vector{IWaveform}, axes::AxesRect) = _rescale(inputlist, axes.xscale, axes.yscale)\n\n_rescale(pt::Point2D, xscale::AxisScale, yscale::AxisScale) =\n\tPoint2D(datamap(DReal, xscale)(pt.x), datamap(DReal, yscale)(pt.y))\n_rescale(pt::Point2D, axes::AxesRect) = _rescale(pt, axes.xscale, axes.yscale)\n\n\n#Preprocess input dataset (rescale/reduce quantity of data/...):\n#-------------------------------------------------------------------------------\n# (Updates display_data)\nfunction preprocess_data(plot::Plot2D)\n\t#TODO: Find a way to preprocess x-vectors referencing same data only once?\n\n\t#Rescale data\n\twfrmlist = _rescale(plot.data, plot.axes)\n\n\t#Update extents:\n\tplot.ext_data = rescale_rev(getextents(wfrmlist), plot.axes) #Update max extents\n\tsetextents(plot, plot.ext) #Update extents, resolving any NaN fields.\n\text = getextents_xfrm(plot) #Read back extents, in transformed coordinates\n\n\t#Reduce data:\n\tplot.display_data = _reduce(wfrmlist, ext, plot.xres)\n\tplot.invalid_ddata = false\n\n\t#NOTE: Rescaling before data reduction is somewhat inefficient, but makes\n\t# it easier to interpolate data in _reduce step.\n\t#TODO: Find a way to efficiently reduce before re-scaling???\nend\n\n\n#==High-level display functions\n===============================================================================#\nfunction update_ddata(plot::Plot2D)\n\tinvalidate_extents(plot) #Always compute below:\n\t#TODO: Conditionnaly compute (only when data changed/added)?\n\n\tif plot.invalid_ddata\n\t\tpreprocess_data(plot)\n\tend\nend\n\n#Last line\n", "meta": {"hexsha": "2bc3e90878b4316a1e9ce514b39f2282f3f11613", "size": 18926, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/base.jl", "max_stars_repo_name": "JuliaPackageMirrors/InspectDR.jl", "max_stars_repo_head_hexsha": "a9e6aa05c053c3eb5a65d8a32199934560afb80d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/base.jl", "max_issues_repo_name": "JuliaPackageMirrors/InspectDR.jl", "max_issues_repo_head_hexsha": "a9e6aa05c053c3eb5a65d8a32199934560afb80d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base.jl", "max_forks_repo_name": "JuliaPackageMirrors/InspectDR.jl", "max_forks_repo_head_hexsha": "a9e6aa05c053c3eb5a65d8a32199934560afb80d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0412698413, "max_line_length": 114, "alphanum_fraction": 0.6736235866, "num_tokens": 5453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24387372091340012}} {"text": "\"\"\"\nWrapper for minimization function\n\"\"\"\n\n\n## Minimization function\n\"\"\"\nMethod to resize bounds if float is passed\n\"\"\"\nfunction _resize_bounds(lx, nx::Int)\n if length(lx) == 1 && nx > 1\n lx = lx*ones(nx)\n end\n return lx\nend\n\n\n\"\"\"\n minimize(func!::Function, x0::Vector, ng::Int; kwargs...)\n\nMinimize function, common interface to IPOPT and SNOPT\n\nObjective function structure:\n\n```julia\nfunction func!(g, x)\n \n return \nend\n```\n\n# Arguments\n - `func!::Function`: fitness function with signature `rosenbrock!(g, x)` and returning objective\n - `x0::Vector: initial guess\n - `ng::Int: number of constraints\n - `lx::Vector: lower bound on x\n - `ux::Vector: upper bound on x\n - `lg::Vector: lower bound on constraints\n - `ug::Vector: upper bound on constraints\n - `solver::String`: solver, \"ipopt\" or \"snopt\"\n - `options::Dict`: options used by solver\n - `sparsity::AbstractSparsityPattern`: sparsity pattern, defualt is DensePattern()\n - `derivatives::AbstractDiffMethod`: derivative method, ForwardFD() or CentralFD() or ForwardAD() or ReverseAD()\n - `outputfile::Boolean`: whether to create output file\n - `verbosity::Int`: verbosirty level, >= 0\n\n# Returns\n - `Tuple`: xstar, fstar, info\n\"\"\"\nfunction minimize(func!::Function, x0::Vector, ng::Int; kwargs...)\n # unpack values\n lx = _assign_from_kwargs(Dict(kwargs), :lx, -Inf)\n ux = _assign_from_kwargs(Dict(kwargs), :ux, Inf)\n lg = _assign_from_kwargs(Dict(kwargs), :lg, -Inf)\n ug = _assign_from_kwargs(Dict(kwargs), :ug, 0.0)\n solver = _assign_from_kwargs(Dict(kwargs), :solver, \"ipopt\")\n options = _assign_from_kwargs(Dict(kwargs), :options, Dict())\n sparsity = _assign_from_kwargs(Dict(kwargs), :sparsity, DensePattern())\n derivatives = _assign_from_kwargs(Dict(kwargs), :derivatives, ForwardFD())\n outputfile = _assign_from_kwargs(Dict(kwargs), :outputfile, false)\n verbosity = _assign_from_kwargs(Dict(kwargs), :verbosity, 0)\n\n # snopt-specific settings\n lencw = _assign_from_kwargs(Dict(kwargs), :lencw, 500)\n iSumm = _assign_from_kwargs(Dict(kwargs), :iSumm, 6) # print to screen if 6\n\n # initialize number of decision variables\n nx = length(x0)\n\n # resize bounds if input length is 1\n lx = _resize_bounds(lx, nx)\n ux = _resize_bounds(ux, nx)\n lg = _resize_bounds(lg, ng)\n ug = _resize_bounds(ug, ng)\n\n # create cache\n # if verbosity>0\n # println(\"derivatives: $derivatives\")\n # end\n cache = _create_cache(sparsity, derivatives, func!, nx, ng)\n\n # determine sparsity pattern\n rows, cols = _get_sparsity(sparsity, nx, ng)\n\n if cmp(solver, \"ipopt\") == 0\n xstar, fstar, info = minimize_ipopt(options, cache, x0, lx, ux, lg, ug, rows, cols, outputfile)\n elseif cmp(solver, \"snopt\") == 0\n xstar, fstar, info = minimize_snopt(options, cache, x0, lx, ux, lg, ug, rows, cols, outputfile, lencw, iSumm)\n end\n #print(\"typeof-cache: \")\n #println(typeof(cache))\n return xstar, fstar, info\nend\n\n\n\"\"\"\n _assign_from_kwargs(keyargs::Dict, keyname, default)\n\nUtility to unpack kwargs\n\"\"\"\nfunction _assign_from_kwargs(keyargs::Dict, keyname, default)\n if haskey(keyargs, keyname)==true\n var = keyargs[keyname]\n else\n var = default\n end\n return var\nend\n", "meta": {"hexsha": "5fa81ddaa194c1973e61cbe188caa885505908ac", "size": 3379, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/minimize.jl", "max_stars_repo_name": "Yuricst/joptimise", "max_stars_repo_head_hexsha": "5a8e28d63358db87941dba0435864d8bcfe2c3fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-29T02:29:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T15:16:26.000Z", "max_issues_repo_path": "src/minimize.jl", "max_issues_repo_name": "Yuricst/joptimise", "max_issues_repo_head_hexsha": "5a8e28d63358db87941dba0435864d8bcfe2c3fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-17T03:02:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T03:02:24.000Z", "max_forks_repo_path": "src/minimize.jl", "max_forks_repo_name": "Yuricst/joptimise", "max_forks_repo_head_hexsha": "5a8e28d63358db87941dba0435864d8bcfe2c3fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0, "max_line_length": 117, "alphanum_fraction": 0.6632139686, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24387372091340012}} {"text": "import Geometry\n\n\"\"\"\n struct JacobianMatrix{T} <: AbstractMatrix{T}\nJacobian matrix. Block-diagonal local matrix represents intraelement operations,\noff-diagonal represents connectivity between elements.\n\n`diag[:,iS1,:,iS2,iK]` is a square matrix d(f(u[:,iS1,iK))/d(u[:,iS2,iK])\nfor states iS1, iS2, element iK. Designed so that `diag[:,:,:,:,iK]` can be\nin-place reshaped for matrix multiplication.\n\n`offdiag[iFN2,iS2,iN1,iS1,iF,iK1]` is a rectangular matrix\nd(f(u[iN1,iS1,iK1])/d(u[iFN2,iS2,mesh.e2e[iF,iK1]]), or effect of neighbor iF on\nelement iK1. Again, can in-place reshape for matrix multiplication. Note that\nfor upper triangular portion of global matrix (`mesh.e2e[iF,iK1]x==je,A.mesh.e2e[:,ie])\n if je < ie\n # Lower triangular part stored directly\n iFN2 = findfirst(x->x==jn,A.mesh.ef2n[:,iF])\n iFN = 0\n if !isnothing(iFN2)\n # We need the original face node\n iFN = mesh.nfn2fn[iFN2]\n else\n # Node is not on the face => no Jacobian dependence\n return zero(T)\n end\n return A.offdiag[iFN,is,jn,js,iF,ie]\n else\n # Upper triangular part stored transposed\n iFN = findfirst(x->x==im,A.mesh.ef2n[:,iF])\n iFN2 = 0\n if !isnothing(iFN)\n # We need the neighbor's face node\n iFN2 = mesh.nfn2fn[iFN]\n else\n # Node is not on the face => no Jacobian dependence\n return zero(T)\n end\n return A.offdiag[iFN2,js,im,is,iF,ie]\n end\n else\n # Non-neighboring elements => no Jacobian dependence\n return zero(T)\n end\nend\n\"\"\"\n setindex!(A::JacobianMatrix, v, i::Integer)\nLinear scalar indexed assignment of `JacobianMatrix`\n\"\"\"\n@inline function Base.setindex!(A::JacobianMatrix, v, i::Integer)\n (sz1,sz2) = size(A)\n j = rem1(i, sz1); i = div(i, sz2, RoundUp)\n setindex!(A, v, i, j)\nend\n\"\"\"\n setindex!(A::JacobianMatrix{T}, v, i::Integer, j::Integer)\n2-dimensional scalar assignment of `JacobianMatrix`. Not efficient.\n\"\"\"\n@inline function Base.setindex!(A::JacobianMatrix{T}, v, i::Integer, j::Integer) where {T}\n @boundscheck checkbounds(Bool, A,i,j)\n (m,ns,n,ns2,ne) = size(A.diag)\n im = rem1(i ,m ); i2 = div(i ,m , RoundUp)\n is = rem1(i2,ns); i3 = div(i2,ns, RoundUp)\n ie = rem1(i3,ne)\n jn = rem1(j ,n ); j2 = div(j ,n , RoundUp)\n js = rem1(j2,ns); j3 = div(j2,ns, RoundUp)\n je = rem1(j3,ne)\n if ie==je\n # On diagonal\n if checkbounds(Bool,A.diag, im,is,jn,js,ie)\n @inbounds setindex!(A.diag, v, im,is,jn,js,ie)\n end\n elseif je ∈ A.mesh.e2e[:,ie]\n iF = findfirst(x->x==je,A.mesh.e2e[:,ie])\n if je < ie\n # Lower triangular part stored directly\n iFN2 = findfirst(x->x==jn,A.mesh.ef2n[:,iF])\n iFN = 0\n if !isnothing(iFN2)\n # We need the original face node\n iFN = mesh.nfn2fn[iFN2]\n else\n if !iszero(v)\n # Node is not on the face => no Jacobian dependence\n throw(ArgumentError(\"Cannot set off-diagonal entry ($i,$j) to non-zero value $v\"))\n else\n return v\n end\n end\n return setindex!(A.offdiag, v, iFN,is,jn,js,iF,ie)\n else\n # Upper triangular part stored transposed\n iFN = findfirst(x->x==im,A.mesh.ef2n[:,iF])\n iFN2 = 0\n if !isnothing(iFN)\n # We need the neighbor's face node\n iFN2 = mesh.nfn2fn[iFN]\n else\n if !iszero(v)\n # Node is not on the face => no Jacobian dependence\n throw(ArgumentError(\"Cannot set off-diagonal entry ($i,$j) to non-zero value $v\"))\n else\n return v\n end\n end\n return setindex!(A.offdiag, v, iFN2,js,im,is,iF,ie)\n end\n else\n # Non-neighboring elements => no Jacobian dependence\n if !iszero(v)\n throw(ArgumentError(\"Cannot set off-diagonal entry ($i,$j) to non-zero value $v\"))\n else\n return v\n end\n end\nend\n\n(==)(A::JacobianMatrix, B::JacobianMatrix) = (A.diag == B.diag && A.offdiag == B.offdiag)\n(-)(A::JacobianMatrix) = JacobianMatrix(-A.diag, -A.offdiag, A.mesh)\nfunction (+)(A::JacobianMatrix, B::JacobianMatrix)\n @assert A.mesh === B.mesh\n JacobianMatrix(A.diag+B.diag, A.offdiag+B.offdiag, A.mesh)\nend\nfunction (-)(A::JacobianMatrix, B::JacobianMatrix)\n @assert A.mesh === B.mesh\n JacobianMatrix(A.diag-B.diag,A.offdiag-B.offdiag,mesh)\nend\n# TODO: Matrix addition with LocalMatrix as well?\n(*)(c::Number, A::JacobianMatrix) = JacobianMatrix(c*A.diag, c*A.offdiag, A.mesh)\n(*)(A::JacobianMatrix, c::Number) = JacobianMatrix(c*A.diag, c*A.offdiag, A.mesh)\n(/)(A::JacobianMatrix, c::Number) = JacobianMatrix(A.diag / c, A.offdiag / c, A.mesh)\n(*)(A::JacobianMatrix, B::JacobianMatrix) = error(\"Too expensive an operation!\")\n\n\" Store `faces` on `volume` array according to given mask: vol[mask] += face \"\nfunction distribute_face_to_nodes!(volume, faces, mask)\n volume_shaped = reshape(volume, size(volume,1), prod(size(volume)[2:end])))\n faces_shaped = reshape(faces, size(faces,1), prod(size(faces)[2:end]))\n for j = 1:size(volume_shaped,2)\n for i = 1:size(mask,1)\n volume_shaped[mask[i],j] += faces_shaped[i,j]\n end\n end\nend\n\" Collect `volume` into `faces` array according to given mask: face = vol[mask] \"\nfunction collect_face_from_nodes!(faces, volume, mask)\n volume_shaped = reshape(volume, size(volume,1), prod(size(volume)[2:end])))\n faces_shaped = reshape(faces, size(faces,1), prod(size(faces)[2:end]))\n for j = 1:size(volume_shaped,2)\n for i = 1:size(mask,1)\n faces_shaped[i,j] = volume_shaped[mask[i],j]\n end\n end\nend\n\nfunction (*)(A::JacobianMatrix{T1}, x::AbstractVector{T2}) where {T1, T2}\n (m,ns,n,ns2,ne) = size(A.diag)\n b = zeros(typeof(zero(T1)*zero(T2)), m*ns*ne)\n b_shaped = reshape(b, m,ns,ne)\n b_mult = reshape(b, m*ns,ne)\n x_shaped = reshape(x, n,ns2,ne)\n x_mult = reshape(x, n*ns2,ne)\n faces_mult = zeros(typeof(zero(T1)*zero(T2)), A.mesh.n_face_nodes*ns)\n faces_shaped = reshape(faces, A.mesh.n_face_nodes, ns)\n for iK = 1:ne\n # Diagonal of A\n @views Adiag = reshape(A.diag[:,:,:,:,iK], m*ns, n*ns2)\n @views b_mult[:,iK] .+= Adiag*x_mult[:,iK]\n # Off-diagonal of A\n for iF = 1:Geometry.N_FACES\n nK = A.mesh.e2e[iF,iK]\n if nK > 0\n Aoff = reshape(@view A.offdiag[:,:,:,:,iF,iK], A.mesh.n_faces_nodes*ns,m*ns)\n nF = A.mesh.e2f[iF,iK]\n if nK < iK\n # Lower triangular part stored directly\n @views faces_mult .= Aoff*x_mult[:,iK]\n @views distribute_face_to_nodes!(b_shaped[:,:,iK], faces_shaped, A.mesh.ef2n[:,iF])\n else\n # Upper triangular part stored transposed\n @views collect_face_from_nodes!(faces_shaped, x_shaped[:,:,nK], A.mesh.ef2n[:,nF])\n @views b_mult[:,iK] .+= Aoff'*faces_mult\n end\n end\n end\n end\n return b\nend\nfunction (*)(A::JacobianMatrix{T1}, x::SolutionVector{T2}) where {T1, T2}\n (m,ns,n,ns2,ne) = size(A.diag)\n b_shaped = zeros(typeof(zero(T1)*zero(T2)), m,ns,ne)\n b_mult = reshape(b, m*ns,ne)\n x_mult = reshape(x.data, n*ns2,ne)\n faces_mult = zeros(typeof(zero(T1)*zero(T2)), A.mesh.n_face_nodes*ns)\n faces_shaped = reshape(faces, A.mesh.n_face_nodes, ns)\n @views for iK = 1:ne\n # Diagonal of A\n Adiag = reshape(A.diag[:,:,:,:,iK], m*ns, n*ns2)\n b_mult[:,iK] .+= Adiag*x_mult[:,iK]\n # Off-diagonal of A\n for iF = 1:Geometry.N_FACES\n nK = A.mesh.e2e[iF,iK]\n if nK > 0\n Aoff = reshape(A.offdiag[:,:,:,:,iF,iK], A.mesh.n_faces_nodes*ns,m*ns)\n nF = A.mesh.e2f[iF,iK]\n if nK < iK\n # Lower triangular part stored directly\n faces_mult .= Aoff*x_mult[:,iK]\n distribute_face_to_nodes!(b_shaped[:,:,iK], faces_shaped, A.mesh.ef2n[:,iF])\n else\n # Upper triangular part stored transposed\n collect_face_from_nodes!(faces_shaped, x.data[:,:,nK], A.mesh.ef2n[:,nF])\n b_mult[:,iK] .+= Aoff'*faces_mult\n end\n end\n end\n end\n return SolutionVector(b_shaped)\nend\n\"\"\"\n mul!(y::SolutionVector, A::JacobianMatrix, x::SolutionVector, α::Number, β::Number)\nReturn A x α + y β by overwriting y\n\"\"\"\nfunction LinearAlgebra.mul!(y::SolutionVector{T1}, A::JacobianMatrix, x::SolutionVector, α::Number, β::Number) where {T1}\n (m,ns,n,ns2,ne) = size(A.diag)\n (nx,ns2x,nex) = true_size(x)\n (my,nsy,ney) = true_size(y)\n @assert m == my && ns == nsy && ne == ney \"JacobianMatrix $(size(A.diag)), SolutionVector $(true_size(y)) mismatched size\"\n @assert n == nx && ns2 == ns2x && ne == nex \"JacobianMatrix $(size(A.diag)), SolutionVector $(true_size(x)) mismatched size\"\n y_shaped = reshape(y.data, m*ns*ne)\n y_mult = reshape(y.data, m*ns,ne)\n x_shaped = reshape(x.data, n,ns2,ne)\n x_mult = reshape(x.data, n*ns2,ne)\n faces_mult = zeros(T1, A.mesh.n_face_nodes*ns)\n faces_shaped = reshape(faces, A.mesh.n_face_nodes, ns)\n @views for iK = 1:ne\n # Diagonal of A\n Adiag = reshape(A.diag[:,:,:,:,iK], m*ns, n*ns2)\n # y[iK] = Adiag*x[iK]*α + y[iK]*β\n mul!(y_mult[:,iK], Adiag, x_mult[:,iK], α, β)\n # Off-diagonal of A\n for iF = 1:Geometry.N_FACES\n nK = A.mesh.e2e[iF,iK]\n if nK > 0\n Aoff = reshape(A.offdiag[:,:,:,:,iF,iK], A.mesh.n_faces_nodes*ns,m*ns)\n nF = A.mesh.e2f[iF,iK]\n if nK < iK\n # Lower triangular part stored directly\n faces_mult .= Aoff*x_mult[:,iK]\n # y[iK] += Aoff*faces[iK]*α\n distribute_face_to_nodes!(y_shaped[:,:,iK], faces_shaped, A.mesh.ef2n[:,iF])\n else\n # Upper triangular part stored transposed\n collect_face_from_nodes!(faces_shaped, x_shaped[:,:,nK], A.mesh.ef2n[:,nF])\n # y[iK] += Aoff'*faces[nK]*α\n mul!(y_mult[:,iK], Aoff', faces_mult, α, 1.0)\n end\n end\n end\n end\nend\n\n\"\"\"\n ldiv!(A::JacobianMatrix, x::SolutionVector)\nIn-place linear solve A\\\\x using numerical iterative solver based on\npreconditioned GMRES.\nTODO: Decide actual algorithm and create production-level version of code.\n\"\"\"\nfunction LinearAlgebra.ldiv!(A::JacobianMatrix, x::SolutionVector)\n println(\"my ldiv!\")\n (m,ns,n,ns2,ne) = size(A.diag)\n (nx,ns2x,nex) = true_size(x)\n @assert nx == m == n && ns2x == ns2 == ns && ne == nex \"JacobianMatrix A $(size(A.diag)) cannot \\\\ x $(true_size(x))\"\n # TODO: program the solver here\n error(\"Not yet programmed!\")\nend\nfunction \\(A::LocalMatrix, x::SolutionVector)\n println(\"my \\\\\")\n (m,ns,n,ns2,ne) = size(A.diag)\n (nx,ns2x,nex) = true_size(x)\n @assert nx == m == n && ns2x == ns2 == ns && ne == nex \"JacobianMatrix A $(size(A.diag)) cannot \\\\ x $(true_size(x))\"\n b = deepcopy(x)\n LinearAlgebra.ldiv!(A, b)\nend\n\nfunction L2_error!(u::SolutionVector, u_true::SolutionVector, M::JacobianMatrix)\n u_true -= u\n return L2_norm(u_true, M)\nend\nfunction L2_norm(u::SolutionVector, M::JacobianMatrix)\n Mu = M*u\n (n,ns,ne) = true_size(Mu)\n l2_norms = zeros(ns)\n for iK = 1:ne\n for iS = 1:ns\n @views l2_norms[iS] += u.data[:,iS,iK]'*Mu.data[:,iS,iK]\n end\n end\n return l2_norms\nend\n", "meta": {"hexsha": "0a1e07bc9d594bb8c51c704ff652febc77b08f3b", "size": 14155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/JacobianMatrix.jl", "max_stars_repo_name": "NoseKnowsAll/DGToolkit", "max_stars_repo_head_hexsha": "e029ed96f337b187876a52a3f63b7636336374c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-22T03:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T03:23:48.000Z", "max_issues_repo_path": "src/JacobianMatrix.jl", "max_issues_repo_name": "NoseKnowsAll/DGToolkit", "max_issues_repo_head_hexsha": "e029ed96f337b187876a52a3f63b7636336374c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/JacobianMatrix.jl", "max_forks_repo_name": "NoseKnowsAll/DGToolkit", "max_forks_repo_head_hexsha": "e029ed96f337b187876a52a3f63b7636336374c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-22T03:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-22T03:23:50.000Z", "avg_line_length": 39.7612359551, "max_line_length": 128, "alphanum_fraction": 0.5815612858, "num_tokens": 4289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.24379165663305924}} {"text": "## Functions to compute the reduced shape\n\n# for reductions that expand 0 dims to 1\nreduced_dims(a::AbstractArray, region) = reduced_dims(size(a), region)\n\n# for reductions that keep 0 dims as 0\nreduced_dims0(a::AbstractArray, region) = reduced_dims0(size(a), region)\nreduced_dims{N}(siz::NTuple{N,Int}, d::Int, rd::Int) = (d == 1 ? tuple(rd, siz[d+1:N]...) :\n d == N ? tuple(siz[1:N-1]..., rd) :\n 1 < d < N ? tuple(siz[1:d-1]..., rd, siz[d+1:N]...) : \n siz)::typeof(siz)\nreduced_dims{N}(siz::NTuple{N,Int}, d::Int) = reduced_dims(siz, d, 1)\nreduced_dims0{N}(siz::NTuple{N,Int}, d::Int) = 1 <= d <= N ? reduced_dims(siz, d, (siz[d] == 0 ? 0 : 1)) : siz\n\nfunction reduced_dims{N}(siz::NTuple{N,Int}, region)\n rsiz = [siz...]\n for i in region\n if 1 <= i <= N\n rsiz[i] = 1\n end\n end\n tuple(rsiz...)::typeof(siz)\nend\n\nfunction reduced_dims0{N}(siz::NTuple{N,Int}, region)\n rsiz = [siz...]\n for i in region\n if i <= i <= N\n rsiz[i] = (rsiz[i] == 0 ? 0 : 1)\n end\n end\n tuple(rsiz...)::typeof(siz)\nend\n\nfunction regionsize(a, region)\n s = 1\n for d in region\n s *= size(a,d)\n end\n s\nend\n\n\n###### Generic reduction functions #####\n\n## initialization\n\nfor (Op, initfun) in ((:AddFun, :zero), (:MulFun, :one), (:MaxFun, :typemin), (:MinFun, :typemax))\n @eval initarray!{T}(a::AbstractArray{T}, ::$(Op), init::Bool) = (init && fill!(a, $(initfun)(T)); a)\nend\n\nfor (Op, initval) in ((:AndFun, true), (:OrFun, false))\n @eval initarray!(a::AbstractArray, ::$(Op), init::Bool) = (init && fill!(a, $initval); a)\nend\n\nreducedim_initarray{R}(A::AbstractArray, region, v0, ::Type{R}) = fill!(similar(A,R,reduced_dims(A,region)), v0)\nreducedim_initarray{T}(A::AbstractArray, region, v0::T) = reducedim_initarray(A, region, v0, T)\n\nreducedim_initarray0{R}(A::AbstractArray, region, v0, ::Type{R}) = fill!(similar(A,R,reduced_dims0(A,region)), v0)\nreducedim_initarray0{T}(A::AbstractArray, region, v0::T) = reducedim_initarray0(A, region, v0, T)\n\n# TODO: better way to handle reducedim initialization\n#\n# The current scheme is basically following Steven G. Johnson's original implementation\n#\nfunction reducedim_init{T}(f, op::AddFun, A::AbstractArray{T}, region)\n if method_exists(zero, (Type{T},))\n x = evaluate(f, zero(T))\n z = zero(x) + zero(x)\n Tr = typeof(z) == typeof(x) && !isbits(T) ? T : typeof(z)\n else\n z = zero(sum(f, A))\n Tr = typeof(z)\n end\n return reducedim_initarray(A, region, z, Tr)\nend\n\nfunction reducedim_init{T}(f, op::MulFun, A::AbstractArray{T}, region)\n if method_exists(zero, (Type{T},))\n x = evaluate(f, zero(T))\n z = one(x) * one(x)\n Tr = typeof(z) == typeof(x) && !isbits(T) ? T : typeof(z)\n else\n z = one(prod(f, A))\n Tr = typeof(z)\n end\n return reducedim_initarray(A, region, z, Tr)\nend\n\nreducedim_init{T}(f, op::MaxFun, A::AbstractArray{T}, region) = reducedim_initarray0(A, region, typemin(evaluate(f, zero(T))))\nreducedim_init{T}(f, op::MinFun, A::AbstractArray{T}, region) = reducedim_initarray0(A, region, typemax(evaluate(f, zero(T))))\nreducedim_init{T}(f::Union(AbsFun,Abs2Fun), op::MaxFun, A::AbstractArray{T}, region) = \n reducedim_initarray(A, region, zero(evaluate(f, zero(T))))\n\nreducedim_init(f, op::AndFun, A::AbstractArray, region) = reducedim_initarray(A, region, true)\nreducedim_init(f, op::OrFun, A::AbstractArray, region) = reducedim_initarray(A, region, false)\n\n# specialize to make initialization more efficient for common cases\n\ntypealias CommonReduceResult Union(Uint64,Uint128,Int64,Int128,Float32,Float64,Complex64,Complex128)\n\nfor (IT, RT) in ((:CommonReduceResult, :T), (:SmallSigned, :Int), (:SmallUnsigned, :Uint))\n @eval begin\n reducedim_init{T<:$IT}(f::Union(IdFun,AbsFun,Abs2Fun), op::AddFun, A::AbstractArray{T}, region) = \n reducedim_initarray(A, region, zero($RT))\n reducedim_init{T<:$IT}(f::Union(IdFun,AbsFun,Abs2Fun), op::MulFun, A::AbstractArray{T}, region) = \n reducedim_initarray(A, region, one($RT))\n end \nend\nreducedim_init(f::Union(IdFun,AbsFun,Abs2Fun), op::AddFun, A::AbstractArray{Bool}, region) = \n reducedim_initarray(A, region, 0)\n\n\n## generic (map)reduction\n\nhas_fast_linear_indexing(a::AbstractArray) = false\nhas_fast_linear_indexing(a::Array) = true\n\nfunction check_reducdims(R, A)\n # Check whether R has compatible dimensions w.r.t. A for reduction\n #\n # It returns an integer value value (useful for choosing implementation)\n # - If it reduces only along leading dimensions, e.g. sum(A, 1) or sum(A, (1, 2)),\n # it returns the length of the leading slice. For the two examples above, \n # it will be size(A, 1) or size(A, 1) * size(A, 2).\n # - Otherwise, e.g. sum(A, 2) or sum(A, (1, 3)), it returns 0.\n #\n lsiz = 1\n had_nonreduc = false\n for i = 1:ndims(A)\n sRi = size(R, i)\n sAi = size(A, i)\n if sRi == 1\n if sAi > 1 \n if had_nonreduc\n lsiz = 0 # to reduce along i, but some previous dimensions were non-reducing\n else\n lsiz *= sAi # if lsiz was set to zero, it will stay to be zero\n end\n end\n else\n sRi == sAi || \n throw(DimensionMismatch(\"Reduction on array of size $(size(A)) with output of size $(size(R))\"))\n had_nonreduc = true\n end\n end\n return lsiz\nend\n\n@ngenerate N typeof(R) function _mapreducedim!{T,N}(f, op, R::AbstractArray, A::AbstractArray{T,N})\n lsiz = check_reducdims(R, A)\n isempty(A) && return R\n @nextract N sizeR d->size(R,d)\n sizA1 = size(A, 1)\n\n if has_fast_linear_indexing(A) && lsiz > 16\n # use mapreduce_impl, which is probably better tuned to achieve higher performance\n nslices = div(length(A), lsiz)\n ibase = 0\n for i = 1:nslices\n @inbounds R[i] = mapreduce_impl(f, op, A, ibase+1, ibase+lsiz)\n ibase += lsiz\n end\n elseif size(R, 1) == 1 && sizA1 > 1\n # keep the accumulator as a local variable when reducing along the first dimension\n @nloops N i d->(d>1? (1:size(A,d)) : (1:1)) d->(j_d = sizeR_d==1 ? 1 : i_d) begin\n @inbounds r = (@nref N R j)\n for i_1 = 1:sizA1\n @inbounds v = evaluate(f, (@nref N A i))\n r = evaluate(op, r, v)\n end\n @inbounds (@nref N R j) = r\n end \n else\n # general implementation\n @nloops N i A d->(j_d = sizeR_d==1 ? 1 : i_d) begin\n @inbounds v = evaluate(f, (@nref N A i))\n @inbounds (@nref N R j) = evaluate(op, (@nref N R j), v)\n end\n end\n return R \nend\n\nmapreducedim!(f, op, R::AbstractArray, A::AbstractArray) = _mapreducedim!(f, op, R, A)\n\nfunction mapreducedim!(f::Function, op, R::AbstractArray, A::AbstractArray)\n is(op, +) ? _mapreducedim!(f, AddFun(), R, A) :\n is(op, *) ? _mapreducedim!(f, MulFun(), R, A) :\n is(op, &) ? _mapreducedim!(f, AndFun(), R, A) :\n is(op, |) ? _mapreducedim!(f, OrFun(), R, A) :\n _mapreducedim!(f, op, R, A)\nend\n\nreducedim!{RT}(op, R::AbstractArray{RT}, A::AbstractArray) = mapreducedim!(IdFun(), op, R, A, zero(RT))\n\nmapreducedim(f, op, A::AbstractArray, region, v0) = mapreducedim!(f, op, reducedim_initarray(A, region, v0), A)\nmapreducedim{T}(f, op, A::AbstractArray{T}, region) = mapreducedim!(f, op, reducedim_init(f, op, A, region), A)\n\nreducedim(op, A::AbstractArray, region, v0) = mapreducedim(IdFun(), op, A, region, v0)\nreducedim(op, A::AbstractArray, region) = mapreducedim(IdFun(), op, A, region)\n\n\n##### Specific reduction functions #####\n\nfor (fname, Op) in [(:sum, :AddFun), (:prod, :MulFun), \n (:maximum, :MaxFun), (:minimum, :MinFun), \n (:all, :AndFun), (:any, :OrFun)]\n\n fname! = symbol(string(fname, '!'))\n @eval begin \n $(fname!)(f::Union(Function,Func{1}), r::AbstractArray, A::AbstractArray; init::Bool=true) = \n mapreducedim!(f, $(Op)(), initarray!(r, $(Op)(), init), A)\n $(fname!)(r::AbstractArray, A::AbstractArray; init::Bool=true) = $(fname!)(IdFun(), r, A; init=init)\n\n $(fname)(f::Union(Function,Func{1}), A::AbstractArray, region) = \n mapreducedim(f, $(Op)(), A, region)\n $(fname)(A::AbstractArray, region) = $(fname)(IdFun(), A, region)\n end\nend\n\nfor (fname, fbase, Fun) in [(:sumabs, :sum, :AbsFun), \n (:sumabs2, :sum, :Abs2Fun), \n (:maxabs, :maximum, :AbsFun), \n (:minabs, :minimum, :AbsFun)]\n fname! = symbol(string(fname, '!'))\n fbase! = symbol(string(fbase, '!'))\n @eval begin \n $(fname!)(r::AbstractArray, A::AbstractArray; init::Bool=true) = \n $(fbase!)($(Fun)(), r, A; init=init)\n $(fname)(A::AbstractArray, region) = $(fbase)($(Fun)(), A, region)\n end\nend\n\n\n##### findmin & findmax #####\n\n# Generate the body for a reduction function reduce!(f, Rval, Rind, A), using a comparison operator f\n# Rind contains the index of A from which Rval was taken\nfunction gen_findreduction_body(N, f::Function)\n F = Expr(:quote, f)\n quote\n (isempty(Rval) || isempty(A)) && return Rval, Rind\n for i = 1:$N\n (size(Rval, i) == size(A, i) || size(Rval, i) == 1) || throw(DimensionMismatch(\"Find-reduction on array of size $(size(A)) with output of size $(size(Rval))\"))\n size(Rval, i) == size(Rind, i) || throw(DimensionMismatch(\"Find-reduction: outputs must be of the same size\"))\n end\n @nexprs $N d->(sizeR_d = size(Rval,d))\n # If we're reducing along dimension 1, for efficiency we can make use of a temporary.\n # Otherwise, keep the result in Rval/Rind so that we traverse A in storage order.\n k = 0\n @inbounds if size(Rval, 1) < size(A, 1)\n @nloops $N i d->(d>1? (1:size(A,d)) : (1:1)) d->(j_d = sizeR_d==1 ? 1 : i_d) begin\n tmpRv = (@nref $N Rval j)\n tmpRi = (@nref $N Rind j)\n for i_1 = 1:size(A,1)\n k += 1\n tmpAv = (@nref $N A i)\n if ($F)(tmpAv, tmpRv)\n tmpRv = tmpAv\n tmpRi = k\n end\n end\n (@nref $N Rval j) = tmpRv\n (@nref $N Rind j) = tmpRi\n end\n else\n @nloops $N i A d->(j_d = sizeR_d==1 ? 1 : i_d) begin\n k += 1\n tmpAv = (@nref $N A i)\n if ($F)(tmpAv, (@nref $N Rval j))\n (@nref $N Rval j) = tmpAv\n (@nref $N Rind j) = k\n end\n end\n end\n Rval, Rind\n end\nend\n\neval(ngenerate(:N, :(typeof((Rval,Rind))), :(_findmin!{T,N}(Rval::AbstractArray, Rind::AbstractArray, A::AbstractArray{T,N})), N->gen_findreduction_body(N, <)))\nfindmin!{R}(rval::AbstractArray{R}, rind::AbstractArray, A::AbstractArray; init::Bool=true) = _findmin!(initarray!(rval, typemax(R), init), rind, A)\nfindmin{T}(A::AbstractArray{T}, region) = \n isempty(A) ? (similar(A,reduced_dims0(A,region)), zeros(Int,reduced_dims0(A,region))) :\n _findmin!(reducedim_initarray0(A, region, typemax(T)), zeros(Int,reduced_dims0(A,region)), A)\n\neval(ngenerate(:N, :(typeof((Rval,Rind))), :(_findmax!{T,N}(Rval::AbstractArray, Rind::AbstractArray, A::AbstractArray{T,N})), N->gen_findreduction_body(N, >)))\nfindmax!{R}(rval::AbstractArray{R}, rind::AbstractArray, A::AbstractArray; init::Bool=true) = _findmax!(initarray!(rval, typemin(R), init), rind, A)\nfindmax{T}(A::AbstractArray{T}, region) = \n isempty(A) ? (similar(A,reduced_dims0(A,region)), zeros(Int,reduced_dims0(A,region))) :\n _findmax!(reducedim_initarray0(A, region, typemin(T)), zeros(Int,reduced_dims0(A,region)), A)\n\n\n", "meta": {"hexsha": "bc9450fc5d56075e08bf07bb86b2eab0146621dc", "size": 12113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "base/reducedim.jl", "max_stars_repo_name": "jakebolewski/julia", "max_stars_repo_head_hexsha": "15deb558b63934c1e24b8bbb27308cb6f5829693", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-18T01:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T16:09:02.000Z", "max_issues_repo_path": "base/reducedim.jl", "max_issues_repo_name": "jakebolewski/julia", "max_issues_repo_head_hexsha": "15deb558b63934c1e24b8bbb27308cb6f5829693", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base/reducedim.jl", "max_forks_repo_name": "jakebolewski/julia", "max_forks_repo_head_hexsha": "15deb558b63934c1e24b8bbb27308cb6f5829693", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3412969283, "max_line_length": 171, "alphanum_fraction": 0.5756625114, "num_tokens": 3821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2437250143786896}} {"text": "function _readgml(io::IO, line, ::Type{G}) where G\n mapping = Dict{Int,Int}()\n i = 0\n while startswith(line, \"node\")\n i += 1\n line = readline(io) |> strip\n line == \"[\" && (line = readline(io) |> strip)\n while !startswith(line, \"]\")\n name, valstr = splitgml(line)\n if name == \"id\"\n mapping[parse(Int, valstr)] = i\n end\n line = readline(io) |> strip\n end\n line = readline(io) |> strip #skip ]\n end\n g = G(i)\n while startswith(line, \"edge\")\n line = readline(io) |> strip\n line == \"[\" && (line = readline(io) |> strip)\n u = -1\n v = -1\n while !startswith(line, \"]\")\n name, valstr = splitgml(line)\n if name == \"source\"\n id = parse(Int, valstr)\n u = mapping[id]\n elseif name == \"target\"\n id = parse(Int, valstr)\n v = mapping[id]\n end\n line = readline(io) |> strip\n end\n @assert u > 0 && v > 0\n add_edge!(g, u, v)\n line = readline(io) |> strip #skip ]\n end\n return g\nend\n\nfunction readgml(io::IO, ::Type{G}) where G\n H = G\n line = readline(io) |> strip\n @assert startswith(line, \"graph\")\n line = readline(io) |> strip\n line == \"[\" && (line = readline(io) |> strip)\n while !startswith(line, \"node\") && !isempty(line)\n if startswith(line, \"directed\")\n H = parse(Int, line[10:end]) == 1 ? digraphtype(G) : graphtype(G)\n end\n line = readline(io) |> strip\n end\n return _readgml(io, line, H)\nend\n\nfunction gmltypeof(valstr)\n str = strip(valstr, '\\\"')\n if length(str) < length(valstr)\n return String\n else\n return Float64\n end\nend\n\ngmlval(::Type{T}, x) where {T} = parse(T, x)\ngmlval(::Type{String}, x) = strip(x, '\\\"')\nfunction splitgml(s::AbstractString)\n i = findfirst(isequal(' '), s)\n return SubString(s, 1, i-1), SubString(s, i+1, length(s))\nend\n\ngmlprintval(x) = x\ngmlprintval(x::String) = \"\\\"\" * x * \"\\\"\"\n\n\nfunction _readnetgml(io::IO, line, g)\n mapping = Dict{Int,Int}()\n i = 0\n while startswith(line, \"node\")\n i += 1\n line = readline(io) |> strip\n line == \"[\" && (line = readline(io) |> strip)\n @assert startswith(line, \"id\")\n name, valstr = splitgml(line)\n mapping[parse(Int, valstr)] = i\n add_vertex!(g)\n line = readline(io) |> strip\n while !startswith(line, \"]\")\n name, valstr = splitgml(line)\n !has_vprop(g, name) && vprop!(g, name, String)\n T = valtype(vprop(g, name))\n vprop(g, name)[i] = gmlval(T, valstr)\n line = readline(io) |> strip\n end\n\n line = readline(io) |> strip #skip ]\n end\n\n while startswith(line, \"edge\")\n line = readline(io) |> strip\n line == \"[\" && (line = readline(io) |> strip)\n startswith(line, \"id\") && (line = readline(io) |> strip)\n\n @assert startswith(line, \"source\")\n name, valstr = splitgml(line)\n u = mapping[parse(Int, valstr)]\n line = readline(io) |> strip\n @assert startswith(line, \"target\")\n name, valstr = splitgml(line)\n v = mapping[parse(Int, valstr)]\n line = readline(io) |> strip\n ok, e = add_edge!(g, u, v)\n\n while !startswith(line, \"]\")\n name, valstr = splitgml(line)\n !has_eprop(g, name) && eprop!(g, name, gmltypeof(valstr))\n T = valtype(eprop(g, name))\n eprop(g, name)[e] = gmlval(T, valstr)\n line = readline(io) |> strip\n end\n\n line = readline(io) |> strip #skip ]\n end\n return g\nend\n\n\nfunction readnetgml(io::IO, ::Type{G}) where G<:ANetOrDiNet\n H = G\n line = readline(io) |> strip\n @assert startswith(line, \"graph\")\n line = readline(io) |> strip\n line == \"[\" && (line = readline(io) |> strip)\n gdict = Dict{String, String}()\n while !startswith(line, \"node\") && !isempty(line)\n if startswith(line, \"directed\")\n H = parse(Int, line[10:end]) == 1 ? digraphtype(G) : graphtype(G)\n else\n name, valstr = splitgml(line)\n gdict[name] = gmlval(String, valstr)\n end\n line = readline(io) |> strip\n end\n g = H()\n for (name, val) in gdict\n gprop!(g, name, val)\n end\n return _readnetgml(io, line, g)\nend\n\n\"\"\"\n writegml(f, g)\n\nWrites a graph `g` to a file `f` in the\n[GML](https://en.wikipedia.org/wiki/Graph_Modelling_Language) format.\n\"\"\"\nfunction writegml(io::IO, g::AGraphOrDiGraph)\n println(io, \"graph [\")\n # length(gname) > 0 && println(io, \"label \\\"$gname\\\"\")\n is_directed(g) && println(io, \"\\tdirected 1\")\n for i=1:nv(g)\n println(io,\"\\tnode [\")\n println(io,\"\\t\\tid $i\")\n println(io,\"\\t]\")\n end\n for (s,t) in edges(g)\n println(io,\"\\tedge [\")\n println(io,\"\\t\\tsource $s\")\n println(io,\"\\t\\ttarget $t\")\n println(io,\"\\t]\")\n end\n println(io, \"]\")\n return 1\nend\n\nfunction writenetgml(io::IO, g::ANetOrDiNet)\n println(io, \"graph [\")\n is_directed(g) && println(io, \"\\tdirected 1\")\n for (pname, p) in gprop(g)\n println(io,\"\\t$pname $(gmlprintval(p))\")\n end\n for i=1:nv(g)\n println(io,\"\\tnode [\")\n println(io,\"\\t\\tid $i\")\n for (name, val) in vprop(g, i)\n println(io,\"\\t\\t$name $(gmlprintval(val))\")\n end\n println(io,\"\\t]\")\n end\n for e in edges(g)\n println(io,\"\\tedge [\")\n println(io,\"\\t\\tsource $(src(e))\")\n println(io,\"\\t\\ttarget $(dst(e))\")\n for (name, val) in eprop(g, e)\n println(io,\"\\t\\t$name $(gmlprintval(val))\")\n end\n println(io,\"\\t]\")\n end\n println(io, \"]\")\n return 1\nend\n\nfilemap[:gml] = (readgml, writegml, readnetgml, writenetgml)\n", "meta": {"hexsha": "598837841ceef58155b2f351ad1c0cb4d0fb3b51", "size": 5892, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/persistence/gml.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_stars_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2017-02-24T15:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:59:23.000Z", "max_issues_repo_path": "src/persistence/gml.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_issues_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2017-02-23T09:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T09:10:31.000Z", "max_forks_repo_path": "src/persistence/gml.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Erdos.jl-90d7349d-81aa-5495-813a-883243abfe31", "max_forks_repo_head_hexsha": "2eb248772a05eac35823a07373dd5644913c6dbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-03-04T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:54:44.000Z", "avg_line_length": 28.8823529412, "max_line_length": 77, "alphanum_fraction": 0.5186693822, "num_tokens": 1735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2437250143786896}} {"text": "#=\nTime steps for the MixedSolver module.\nSince the FE and FV portions may use different steppers, this must work for both,\nbut they can be done separately by only passing one set of variables.\nFor all of them:\ninput\n- fe_var\n- fv_var\n- vol_lhs\n- vol_rhs\n- surf_lhs\n- surf_rhs\n- step_info = (t, dt, dofs_per_node_fe, dofs_per_loop_fe, assemble_func_fe, dofs_per_node_fv, dofs_per_loop_fv, assemble_func_fv)\n- fe_storage = (A, b, fe_sol, allocated_vecs, b_order, b_sizes)\n- fv_storage = (fv_sol, allocated_vecs_fv)\n=#\n\nfunction mixed_euler_explicit_step(fe_var, fv_var, vol_lhs, vol_rhs, surf_lhs, surf_rhs, t, step_info, fe_storage, fv_storage)\n fe_stepper = step_info[1];\n fv_stepper = step_info[2];\n dofs_per_node_fe = step_info[3];\n dofs_per_loop_fe = step_info[4];\n fe_assemble_func = step_info[5];\n dofs_per_node_fv = step_info[6];\n dofs_per_loop_fv = step_info[7];\n fv_assemble_func = step_info[8];\n dt = fe_stepper.dt;\n assemble_t = 0;\n linsolve_t = 0;\n \n if !(fv_var === nothing) && config.num_partitions > 1 exchange_ghosts(fv_var, fv_grid, i); end\n pre_step_function();\n \n ### First step the FE part #######################################################################################\n if !(fe_var === nothing)\n # Unpack things\n A = fe_storage[1];\n b = fe_storage[2];\n fe_sol = fe_storage[3];\n allocated_vecs = fe_storage[4];\n b_order = fe_storage[5];\n b_sizes = fe_storage[6];\n \n N1 = size(grid_data.allnodes,2);\n \n assemble_t += @elapsed begin\n b = assemble(fe_var, nothing, vol_rhs[1], allocated_vecs, dofs_per_node_fe, dofs_per_loop_fe, t, dt; rhs_only = true, assemble_loops=fe_assemble_func);\n b = gather_system(nothing, b, N1, dofs_per_node_fe, b_order, b_sizes);\n end\n \n linsolve_t += @elapsed(tmpvec = distribute_solution( linear_system_solve(A,b) , N1, dofs_per_node_fe, b_order, b_sizes));\n \n # At this point tmpvec holds the boundary values\n # directly write them to the variable values and zero sol.\n copy_bdry_vals_to_variables(fe_var, tmpvec, grid_data, dofs_per_node_fe, zero_vals=true);\n \n for i=1:length(fe_sol)\n fe_sol[i] = fe_sol[i] + dt * tmpvec[i];\n end\n \n copy_bdry_vals_to_vector(fe_var, fe_sol, grid_data, dofs_per_node_fe);\n place_sol_in_vars(fe_var, fe_sol);\n \n end\n \n ### Then step the FV part ######################################################################################\n if !(fv_var === nothing)\n fv_sol = fv_storage[1];\n fv_allocated_vecs = fv_storage[2];\n \n assemble_t += @elapsed(tmpvec = fv_assemble(fv_var, vol_lhs[2], vol_rhs[2], surf_lhs[2], surf_rhs[2], fv_allocated_vecs, dofs_per_node_fv, dofs_per_loop_fv, t, dt, assemble_loops=fv_assemble_func));\n \n for i=1:length(fv_sol)\n fv_sol[i] = fv_sol[i] + dt * tmpvec[i];\n end\n \n FV_copy_bdry_vals_to_vector(fv_var, fv_sol, fv_grid, dofs_per_node_fv);\n place_sol_in_vars(fv_var, fv_sol);\n end\n \n post_step_function();\n \n return (assemble_t, linsolve_t);\nend\n\nfunction mixed_euler_implicit_step(fe_var, fv_var, vol_lhs, vol_rhs, surf_lhs, surf_rhs, t, step_info, fe_storage, fv_storage)\n fe_stepper = step_info[1];\n fv_stepper = step_info[2];\n dofs_per_node_fe = step_info[3];\n dofs_per_loop_fe = step_info[4];\n fe_assemble_func = step_info[5];\n dofs_per_node_fv = step_info[6];\n dofs_per_loop_fv = step_info[7];\n fv_assemble_func = step_info[8];\n dt = fe_stepper.dt;\n assemble_t = 0;\n linsolve_t = 0;\n \n if !(fv_var === nothing) && config.num_partitions > 1 exchange_ghosts(fv_var, fv_grid, i); end\n pre_step_function();\n \n ### First step the FE part #######################################################################################\n if !(fe_var === nothing)\n # Unpack things\n A = fe_storage[1];\n b = fe_storage[2];\n fe_sol = fe_storage[3];\n allocated_vecs = fe_storage[4];\n b_order = fe_storage[5];\n b_sizes = fe_storage[6];\n \n N1 = size(grid_data.allnodes,2);\n \n assemble_t += @elapsed begin\n b = assemble(fe_var, nothing, vol_rhs[1], allocated_vecs, dofs_per_node_fe, dofs_per_loop_fe, t, dt; rhs_only = true, assemble_loops=fe_assemble_func);\n b = gather_system(nothing, b, N1, dofs_per_node_fe, b_order, b_sizes);\n end\n \n linsolve_t += @elapsed(tmpvec = distribute_solution( linear_system_solve(A,b) , N1, dofs_per_node_fe, b_order, b_sizes));\n \n # At this point tmpvec holds the boundary values\n # directly write them to the variable values and zero sol.\n copy_bdry_vals_to_variables(fe_var, tmpvec, grid_data, dofs_per_node_fe, zero_vals=true);\n \n for i=1:length(fe_sol)\n fe_sol[i] = tmpvec[i];\n end\n \n copy_bdry_vals_to_vector(fe_var, fe_sol, grid_data, dofs_per_node_fe);\n place_sol_in_vars(fe_var, fe_sol);\n end\n \n ### Then step the FV part ######################################################################################\n if !(fv_var === nothing)\n fv_sol = fv_storage[1];\n fv_allocated_vecs = fv_storage[2];\n \n ## TODO\n \n FV_copy_bdry_vals_to_vector(fv_var, fv_sol, fv_grid, dofs_per_node_fv);\n place_sol_in_vars(fv_var, fv_sol);\n end\n \n post_step_function();\n \n return (assemble_t, linsolve_t);\nend\n\nfunction mixed_crank_nicholson_step(fe_var, fv_var, vol_lhs, vol_rhs, surf_lhs, surf_rhs, t, step_info, fe_storage, fv_storage)\n fe_stepper = step_info[1];\n fv_stepper = step_info[2];\n dofs_per_node_fe = step_info[3];\n dofs_per_loop_fe = step_info[4];\n fe_assemble_func = step_info[5];\n dofs_per_node_fv = step_info[6];\n dofs_per_loop_fv = step_info[7];\n fv_assemble_func = step_info[8];\n dt = fe_stepper.dt;\n assemble_t = 0;\n linsolve_t = 0;\n \n if !(fv_var === nothing) && config.num_partitions > 1 exchange_ghosts(fv_var, fv_grid, i); end\n pre_step_function();\n \n ### First step the FE part #######################################################################################\n if !(fe_var === nothing)\n # Unpack things\n A = fe_storage[1];\n b = fe_storage[2];\n fe_sol = fe_storage[3];\n allocated_vecs = fe_storage[4];\n b_order = fe_storage[5];\n b_sizes = fe_storage[6];\n \n N1 = size(grid_data.allnodes,2);\n \n assemble_t += @elapsed begin\n b = assemble(fe_var, nothing, vol_rhs[1], allocated_vecs, dofs_per_node_fe, dofs_per_loop_fe, t, dt; rhs_only = true, assemble_loops=fe_assemble_func);\n b = gather_system(nothing, b, N1, dofs_per_node_fe, b_order, b_sizes);\n end\n\n linsolve_t += @elapsed(tmpvec = distribute_solution( linear_system_solve(A,b) , N1, dofs_per_node_fe, b_order, b_sizes));\n\n # At this point tmpvec holds the boundary values\n # directly write them to the variable values and zero sol.\n copy_bdry_vals_to_variables(fe_var, tmpvec, grid_data, dofs_per_node_fe, zero_vals=true);\n\n for i=1:length(fe_sol)\n fe_sol[i] = tmpvec[i];\n end\n \n copy_bdry_vals_to_vector(fe_var, fe_sol, grid_data, dofs_per_node_fe);\n place_sol_in_vars(fe_var, fe_sol);\n end\n \n ### Then step the FV part ######################################################################################\n if !(fv_var === nothing)\n fv_sol = fv_storage[1];\n fv_allocated_vecs = fv_storage[2];\n \n ## TODO\n \n FV_copy_bdry_vals_to_vector(fv_var, fv_sol, fv_grid, dofs_per_node_fv);\n place_sol_in_vars(fv_var, fv_sol);\n end\n \n post_step_function();\n \n return (assemble_t, linsolve_t);\nend\n\nfunction mixed_lsrk4_step(fe_var, fv_var, vol_lhs, vol_rhs, surf_lhs, surf_rhs, t, step_info, fe_storage, fv_storage)\n fe_stepper = step_info[1];\n fv_stepper = step_info[2];\n dofs_per_node_fe = step_info[3];\n dofs_per_loop_fe = step_info[4];\n fe_assemble_func = step_info[5];\n dofs_per_node_fv = step_info[6];\n dofs_per_loop_fv = step_info[7];\n fv_assemble_func = step_info[8];\n dt = fe_stepper.dt;\n assemble_t = 0;\n linsolve_t = 0;\n \n ### First step the FE part #######################################################################################\n if !(fe_var === nothing)\n # Unpack things\n A = fe_storage[1];\n b = fe_storage[2];\n fe_sol = fe_storage[3];\n allocated_vecs = fe_storage[4];\n b_order = fe_storage[5];\n b_sizes = fe_storage[6];\n tmppi = fe_storage[7];\n tmpki = fe_storage[8];\n \n N1 = size(grid_data.allnodes,2);\n \n # Low storage RK4: \n # p0 = u\n # ki = ai*k(i-1) + dt*f(p(i-1), t+ci*dt)\n # pi = p(i-1) + bi*ki\n # u = p5\n \n tmppi = get_var_vals(fe_var, tmppi);\n for rki=1:fe_stepper.stages\n rktime = t + fe_stepper.c[rki]*fe_stepper.dt;\n # p(i-1) is currently in u\n pre_step_function();\n \n ### First step the FE part #######################################################################################\n assemble_t += @elapsed begin\n b = assemble(fe_var, nothing, vol_rhs[1], allocated_vecs, dofs_per_node_fe, dofs_per_loop_fe, rktime, fe_stepper.dt; rhs_only = true, assemble_loops=fe_assemble_func);\n b = gather_system(nothing, b, N1, dofs_per_node_fe, b_order, b_sizes);\n end\n \n linsolve_t += @elapsed(fe_sol = distribute_solution( linear_system_solve(A,b) , N1, dofs_per_node_fe, b_order, b_sizes));\n \n # At this point sol holds the boundary values\n # directly write them to the variable values and zero sol.\n copy_bdry_vals_to_variables(fe_var, fe_sol, grid_data, dofs_per_node_fe, zero_vals=true);\n \n if rki == 1 # because a1 == 0\n tmpki = fe_stepper.dt .* fe_sol;\n else\n tmpki = fe_stepper.a[rki].*tmpki + fe_stepper.dt.*fe_sol;\n end\n tmppi = tmppi + fe_stepper.b[rki].*tmpki\n \n copy_bdry_vals_to_vector(fe_var, tmppi, grid_data, dofs_per_node_fe);\n place_sol_in_vars(fe_var, tmppi);\n \n post_step_function();\n end\n \n end\n \n ### Then step the FV part ######################################################################################\n if !(fv_var === nothing)\n fv_sol = fv_storage[1];\n fv_allocated_vecs = fv_storage[2];\n fv_tmppi = fv_storage[3];\n fv_tmpki = fv_storage[4];\n \n fv_tmppi = get_var_vals(fv_var, fv_tmppi);\n for rki=1:fv_stepper.stages\n rktime = t + fv_stepper.c[rki]*fv_stepper.dt;\n # p(i-1) is currently in u\n if config.num_partitions > 1 exchange_ghosts(fv_var, fv_grid, i); end\n pre_step_function();\n \n assemble_t += @elapsed(fv_sol = fv_assemble(fv_var, vol_lhs[2], vol_rhs[2], surf_lhs[2], surf_rhs[2], fv_allocated_vecs, dofs_per_node_fv, dofs_per_loop_fv, rktime, dt, assemble_loops=fv_assemble_func));\n \n if rki == 1 # because a1 == 0\n fv_tmpki = fv_stepper.dt .* fv_sol;\n else\n fv_tmpki = fv_stepper.a[rki].*fv_tmpki + fv_stepper.dt.*fv_sol;\n end\n fv_tmppi = fv_tmppi + fv_stepper.b[rki].*fv_tmpki\n \n FV_copy_bdry_vals_to_vector(fv_var, fv_tmppi, fv_grid, dofs_per_node_fv);\n place_sol_in_vars(fv_var, fv_tmppi);\n \n post_step_function();\n end\n end\n \n return (assemble_t, linsolve_t);\nend\n\n# This may be removed.\nfunction mixed_rk4_step(fe_var, fv_var, vol_lhs, vol_rhs, surf_lhs, surf_rhs, t, step_info, fe_storage, fv_storage)\n return mixed_multistage_step(fe_var, fv_var, vol_lhs, vol_rhs, surf_lhs, surf_rhs, t, step_info, fe_storage, fv_storage);\nend\n\nfunction mixed_multistage_step(fe_var, fv_var, vol_lhs, vol_rhs, surf_lhs, surf_rhs, t, step_info, fe_storage, fv_storage)\n fe_stepper = step_info[1];\n fv_stepper = step_info[2];\n dofs_per_node_fe = step_info[3];\n dofs_per_loop_fe = step_info[4];\n fe_assemble_func = step_info[5];\n dofs_per_node_fv = step_info[6];\n dofs_per_loop_fv = step_info[7];\n fv_assemble_func = step_info[8];\n dt = fe_stepper.dt;\n assemble_t = 0;\n linsolve_t = 0;\n \n ### First step the FE part #######################################################################################\n if !(fe_var === nothing)\n # Unpack things\n A = fe_storage[1];\n b = fe_storage[2];\n fe_sol = fe_storage[3];\n allocated_vecs = fe_storage[4];\n b_order = fe_storage[5];\n b_sizes = fe_storage[6];\n tmpresult = fe_storage[7];\n tmpki = fe_storage[8];\n \n N1 = size(grid_data.allnodes,2);\n \n # solution will be placed in var.values for each stage\n for stage=1:fe_stepper.stages\n stime = t + fe_stepper.c[stage]*fe_stepper.dt;\n \n # Update the values in vars to be used in this stage\n if stage > 1\n initialized_tmpresult = false;\n for j=1:stage\n if fe_stepper.a[stage, j] > 0\n if !initialized_tmpresult\n initialized_tmpresult = true;\n for k=1:length(fe_sol)\n tmpresult[k] = fe_sol[k] + fe_stepper.dt * fe_stepper.a[stage, j] * tmpki[k,j];\n end\n else\n for k=1:length(fe_sol)\n tmpresult[k] += fe_stepper.dt * fe_stepper.a[stage, j] * tmpki[k,j];\n end\n end\n end\n end\n \n if initialized_tmpresult\n copy_bdry_vals_to_vector(fe_var, tmpresult, grid_data, dofs_per_node_fe);\n place_sol_in_vars(fe_var, tmpresult);\n end\n post_step_function(); # seems weird, but imagine this is happening after stage-1\n end\n \n pre_step_function();\n \n ### First step the FE part #######################################################################################\n assemble_t += @elapsed begin\n b = assemble(fe_var, nothing, vol_rhs[1], allocated_vecs, dofs_per_node_fe, dofs_per_loop_fe, stime, fe_stepper.dt; rhs_only = true, assemble_loops=fe_assemble_func);\n b = gather_system(nothing, b, N1, dofs_per_node_fe, b_order, b_sizes);\n end\n \n linsolve_t += @elapsed(tmpki[:,stage] = distribute_solution( linear_system_solve(A,b) , N1, dofs_per_node_fe, b_order, b_sizes));\n \n # At this point tmpki[:,stage] holds the boundary values\n # directly write them to the variable values and zero sol.\n copy_bdry_vals_to_variables(fe_var, tmpki[:,stage], grid_data, dofs_per_node_fe, zero_vals=true);\n \n end\n for i=1:length(fe_sol)\n for stage=1:fe_stepper.stages\n fe_sol[i] += fe_stepper.dt * fe_stepper.b[stage] * tmpki[i, stage];\n end\n end\n \n copy_bdry_vals_to_vector(fe_var, fe_sol, grid_data, dofs_per_node_fe);\n place_sol_in_vars(fe_var, fe_sol);\n \n post_step_function();\n end\n \n ### Then step the FV part ######################################################################################\n if !(fv_var === nothing)\n fv_sol = fv_storage[1];\n fv_allocated_vecs = fv_storage[2];\n fv_tmpresult = fv_storage[3];\n fv_tmpki = fv_storage[4];\n \n # solution will be placed in var.values for each stage\n for stage=1:fv_stepper.stages\n stime = t + fv_stepper.c[stage]*fv_stepper.dt;\n \n # Update the values in vars to be used in this stage\n if stage > 1\n initialized_tmpresult = false;\n for j=1:stage\n if fv_stepper.a[stage, j] > 0\n if !initialized_tmpresult\n initialized_tmpresult = true;\n for k=1:length(fv_sol)\n fv_tmpresult[k] = fv_sol[k] + fv_stepper.dt * fv_stepper.a[stage, j] * fv_tmpki[k,j];\n end\n else\n for k=1:length(fv_sol)\n fv_tmpresult[k] += fv_stepper.dt * fv_stepper.a[stage, j] * fv_tmpki[k,j];\n end\n end\n end\n end\n \n if initialized_tmpresult\n FV_copy_bdry_vals_to_vector(fv_var, fv_tmpresult, fv_grid, dofs_per_node_fv);\n place_sol_in_vars(fv_var, fv_tmpresult);\n end\n post_step_function(); # seems weird, but imagine this is happening after stage-1\n end\n \n if config.num_partitions > 1 exchange_ghosts(fv_var, fv_grid, i); end\n pre_step_function();\n \n tmpki[:,stage] = fv_assemble(fv_var, vol_lhs[2], vol_rhs[2], surf_lhs[2], surf_rhs[2], fv_allocated_vecs, dofs_per_node_fv, dofs_per_loop_fv, stime, fv_stepper.dt, assemble_loops=fv_assemble_func);\n end\n for i=1:length(fv_sol)\n for stage=1:fv_stepper.stages\n fv_sol[i] += fv_stepper.dt * fv_stepper.b[stage] * fv_tmpki[i, stage];\n end\n end\n FV_copy_bdry_vals_to_vector(fv_var, fv_sol, fv_grid, dofs_per_node_fv);\n place_sol_in_vars(fv_var, fv_sol);\n \n post_step_function();\n end\n \n return (assemble_t, linsolve_t);\nend", "meta": {"hexsha": "7d10f7dea0453473c59c9f101174ec850d7a2580", "size": 18559, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mixed_time_step.jl", "max_stars_repo_name": "paralab/Finch", "max_stars_repo_head_hexsha": "77fb81c55a8b063f1d8dd7b91a01ab4d7371a9a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-10-06T16:09:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T20:56:15.000Z", "max_issues_repo_path": "src/mixed_time_step.jl", "max_issues_repo_name": "paralab/Finch", "max_issues_repo_head_hexsha": "77fb81c55a8b063f1d8dd7b91a01ab4d7371a9a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mixed_time_step.jl", "max_forks_repo_name": "paralab/Finch", "max_forks_repo_head_hexsha": "77fb81c55a8b063f1d8dd7b91a01ab4d7371a9a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0597345133, "max_line_length": 215, "alphanum_fraction": 0.5509995151, "num_tokens": 4624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.24365167515638106}} {"text": "# Replace Flux's LSTMCell with BasicLSTMCell from TensorFlow 1.\n# It's implementation is slightly different.\n# https://github.com/tensorflow/tensorflow/blob/v2.4.1/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py#L786-L787\n# https://github.com/FluxML/Flux.jl/blob/master/src/layers/recurrent.jl#L141-L142\n# The replacement is required because the pre-trained models use BasicLSTMCell.\nstruct BasicLSTMCell{A,V,S}\n Wi::A\n Wh::A\n b::V\n state0::S\nend\n\nfunction BasicLSTMCell(in::Integer, out::Integer;\n init = Flux.glorot_uniform,\n initb = zeros,\n init_state = zeros)\n cell = BasicLSTMCell(init(out * 4, in), init(out * 4, out), initb(out * 4), (init_state(out,1), init_state(out,1)))\n cell.b[gate(out, 2)] .= 1\n return cell\nend\n\nfunction (m::BasicLSTMCell)((h, c), x) where {A,V,T}\n b, o = m.b, size(h, 1)\n g = m.Wi*x .+ m.Wh*h .+ b\n input = σ.(gate(g, o, 1))\n cell = tanh.(gate(g, o, 2))\n forget = σ.(gate(g, o, 3))\n output = σ.(gate(g, o, 4))\n c = forget .* c .+ input .* cell\n h′ = output .* tanh.(c)\n sz = size(x)\n return (h′, c), reshape(h′, :, sz[2:end]...)\nend\n\nFlux.@functor BasicLSTMCell\n\nBase.show(io::IO, l::BasicLSTMCell) =\n print(io, \"BasicLSTMCell(\", size(l.Wi, 2), \", \", size(l.Wi, 1)÷4, \")\")\n\n\"\"\"\n BasicLSTM(in::Integer, out::Integer)\nImplements the BasicLSTMCell from TensorFlow 1\nhttps://github.com/tensorflow/tensorflow/blob/v2.4.1/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py#L648-L814\n\"\"\"\nBasicLSTM(a...; ka...) = Flux.Recur(BasicLSTMCell(a...; ka...))\nFlux.Recur(m::BasicLSTMCell) = Flux.Recur(m, m.state0)\n", "meta": {"hexsha": "992c46951977e46a08808774f2eefa927c61a09e", "size": 1674, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PerformanceRNN/layers.jl", "max_stars_repo_name": "VasanthManiVasi/MusicModels.jl", "max_stars_repo_head_hexsha": "4724241286ea9047866c9216ac9d88fe15021446", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PerformanceRNN/layers.jl", "max_issues_repo_name": "VasanthManiVasi/MusicModels.jl", "max_issues_repo_head_hexsha": "4724241286ea9047866c9216ac9d88fe15021446", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PerformanceRNN/layers.jl", "max_forks_repo_name": "VasanthManiVasi/MusicModels.jl", "max_forks_repo_head_hexsha": "4724241286ea9047866c9216ac9d88fe15021446", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6170212766, "max_line_length": 123, "alphanum_fraction": 0.6296296296, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.24361671903168117}} {"text": "#------- SET UP DESIGN PARAMETERS --------#\n\nstruct plyproperties\n names#::Array{String,1}\n plies::Array{Composites.material,1}\nend\n\nstruct geometry\n t::Array{Float64,1}\n s::Array{Float64,1}\n x::Array{Float64,1} #x-location of airfoil section (positive x = downstream)\n y::Array{Float64,1} #y-location of airfoil section (positive y = spanwise)\n z::Array{Float64,1} #z-location of airfoil section (positive z = up)\n chord::Array{Float64,1}\n normalchord::Array{Float64,1} #normal chord length\n twist::Array{Float64,1} #airfoil twist in degrees\n sweep::Array{Float64,1}\n dihedral::Array{Float64,1}\n airfoilthickness::Array{Float64,1}\n xaf::Array{Float64,2}\n yaf::Array{Float64,2}\nend\n\nstruct compstructure\n material::Array{Array{Composites.material,1},1}\n laminate::Array{Composites.laminate,1}\n A::Array{Array{Float64,2},1}\n B::Array{Array{Float64,2},1}\n D::Array{Array{Float64,2},1}\n bucklingstrain::Array{Float64,2}\n precompinput::Array{PreComp.input,1}\n precompoutput::Array{PreComp.output,1}\nend\n\nstruct designparameters\n # configuration assumptions\n p_n_akima::Int64\n p_radii::Array{Float64,1}\n p_webloc::Array{Float64,1}\n\n # operating point assumptions\n altitude::Float64 #m\n\n # material properties\n plyprops::plyproperties\n p_usedmaterials\n p_orientation::Array{Float64,1}\n\n # Propeller Design\n p_lam_t::Array{Float64,1}\n\n p_chord::Array{Float64,1}\n p_sweep_d::Array{Float64,1}\n p_twist_d::Array{Float64,1}\n p_pitch_d::Float64\n p_dihedral_d::Array{Float64,1}\n p_airfoilthickness::Array{Float64,1}\n p_aerocenter::Array{Float64,1}\n p_x_offset::Array{Float64,1}\n velocity::Float64\n p_Rtip::Float64\n blades::Float64\n numprops::Int64\n machtip::Float64\n p_rpm::Float64\n kv::Float64\n i0::Float64\n batt_mass::Float64\n\n # Wing Design\n w_n_linear::Int64\n w_webloc::Array{Float64,1}\n w_lam_t::Array{Float64,1}\n w_chord::Array{Float64,1}\n w_aoa_d::Float64\n w_twist_d::Array{Float64,1}\n w_halfspan::Float64\n w_nondim_halfspany::Array{Float64,1}\n w_sweep_d::Array{Float64,1}\n w_dihedral_d::Array{Float64,1}\n w_usedmaterials #array of strings???\n w_orientation::Array{Float64,1}\n w_x_offset::Array{Float64,1}\n w_aerocenter::Array{Float64,1}\n\n n_CP::Float64\n payload::Float64\n max_mass::Float64\n gravity::Float64\n h_set::Float64\n specif_energy::Float64\n required_range::Float64\n required_takeoff_dist::Float64\n altitude_accel::Float64\n altitude_climb::Float64\n altitude_cruise::Float64\n required_noise::Float64\n required_cruise::Float64\n\nend\n\nfunction designparameters(;\n p_n_akima = 20,\n p_radii::Array{Float64,1}=Float64[0.0,0.2,.4,.6,.8,1.0],\n p_webloc::Array{Float64,1}=[1.0],\n altitude::Float64=18288.0,\n plyprops::plyproperties=plyproperties(),\n p_usedmaterials = [\"highmodulus_uni\",\"highmodulus_weave\",\"taylor_foam\"],\n p_orientation=[0.0,-45],\n # structural design variables\n p_lam_t = ones(length(p_radii)*length(p_usedmaterials)),\n # geometric design variables\n p_chord = Float64[0.1, 0.1, 0.1, 0.1, 0.1],\n p_sweep_d = Float64[0.0,0.0,0.0,0.0,0.0],\n p_twist_d = Float64[30.0, 30.0, 30.0, 30.0],\n p_pitch_d = 0.0,\n p_dihedral_d = fill(0.0,5),\n p_airfoilthickness = Float64[0.147538, 0.132307, 0.127404, 0.130604, 0.245836, 0.0629818],\n p_aerocenter = ones(p_radii)*0.25,\n p_x_offset = zeros(p_radii),\n # operating point design variables\n velocity = 15.40662113981876,\n # propulsion design variables\n p_Rtip = 2.25,\n blades = 2,\n numprops = 4,\n machtip = 0.8,\n p_rpm = 1020.45,\n kv = 4.271513933940295,\n i0 = 0.1,\n batt_mass = 1E8,\n\n w_n_linear = 20,\n w_halfspan = 10.0,\n w_webloc::Array{Float64,1}=[0.40],\n w_usedmaterials = [\"highmodulus_uni\",\"highmodulus_weave\",\"taylor_foam\"],\n w_nondim_halfspany = linspace(0,w_halfspan,length(w_chord)),\n w_lam_t = ones(length(w_nondim_halfspany)*length(w_usedmaterials)),\n w_chord = [0.5,0.5],\n w_aoa_d = 0.0,\n w_twist_d = [0.0,0.0],\n w_sweep_d = [0.0,0.0],\n w_dihedral_d = [0.0,0.0],\n w_orientation = [0.0,45.0,45.0], #uni, weave, webweave\n w_x_offset = ones(w_nondim_halfspany)*0.25,\n w_aerocenter = ones(w_nondim_halfspany)*0.275,\n\n n_CP = 60.0,\n payload = 684.0,\n max_mass = 1500.0,\n gravity = 9.81,\n h_set = 20.0, #meters\n specif_energy = 300.0, #wh/kg\n required_range = 150000.0, #km\n required_takeoff_dist = 395.0, #meters\n altitude_accel = 0.0,\n altitude_climb = 0.0,\n altitude_cruise = 3000.0,\n required_noise = 68.0,\n required_cruise = 28.0,\n\n )\n\n parameters = designparameters(p_n_akima,p_radii,p_webloc,altitude,plyprops,p_usedmaterials,p_orientation,p_lam_t,\n p_chord,p_sweep_d,p_twist_d,p_pitch_d,p_dihedral_d,p_airfoilthickness,p_aerocenter,p_x_offset,velocity,p_Rtip,\n blades,numprops,machtip,p_rpm,kv,i0,batt_mass,w_n_linear,w_webloc,w_lam_t,w_chord,w_aoa_d,w_twist_d,w_halfspan,w_nondim_halfspany,w_sweep_d,w_dihedral_d,w_usedmaterials,\n w_orientation,w_x_offset,w_aerocenter,n_CP,payload,max_mass,gravity,h_set,\n specif_energy,required_range,required_takeoff_dist,altitude_accel,altitude_climb,\n altitude_cruise,required_noise,required_cruise)\n return parameters\nend\n\n\nstruct propwingdesign\n #Design Variables at this scope\n batt_mass::Float64\n w_aoa::Float64\n p_rpm::Float64\n p_pitch::Float64\n velocity::Float64\n\n #Design Parameters at this scope\n constraints\n af\n p_xaf\n p_yaf\n p_xafstrain\n p_yafstrain\n w_xaf\n w_yaf\n w_xafstrain\n w_yafstrain\n spline_3D_freestream\n spline_3D_blown\n\n # Design variables unique to the system function\n p_lam_tin\n p_orientation::Array{Float64,1}\n p_chord_pts::Array{Float64,1}\n p_twist_pts::Array{Float64,1}\n p_Rtip::Float64\n kv::Float64\n i0::Float64\n w_chord_pts::Array{Float64,1}\n w_twist_pts::Array{Float64,1}\n w_halfspan::Float64\n w_sweep_pts::Array{Float64,1}\n w_dihedral_pts::Array{Float64,1}\n w_lam_tin\n w_orientation::Array{Float64,1}\n w_airfoilthickness::Array{Float64,1}\n\n #Design variables unique to the system function\n etaprop_center::Array{Float64,1}\n p_n_akima::Int64\n p_radii::Array{Float64,1}\n altitude::Float64\n numprops::Int64\n p_x_offset::Array{Float64,1}\n p_aerocenter::Array{Float64,1}\n p_usedmaterials\n p_webloc::Array{Float64,1}\n plyprops\n blades::Float64\n w_n_linear::Int64\n w_x_offset::Array{Float64,1}\n w_aerocenter::Array{Float64,1}\n w_nondim_halfspany::Array{Float64,1}\n w_usedmaterials\n w_webloc::Array{Float64,1}\n prop_tilt::Float64\n\n #Control parameters\n detailed::Bool\n VTKfilename\n savefinalvtk::Bool\n verification::Bool\n plots::Bool\n n_CP::Int64\n\nend\n\nfunction propwingdesign(;\n #Design Variables at this scope\n batt_mass = 0.0,\n w_aoa = 0.0,\n p_rpm = 0.0,\n p_pitch = 0.0,\n velocity = 0.0,\n\n #Design Parameters at this scope\n constraints = [],\n af = [],\n p_xaf = [],\n p_yaf = [],\n p_xafstrain = [],\n p_yafstrain = [],\n w_xaf = [],\n w_yaf = [],\n w_xafstrain = [],\n w_yafstrain = [],\n spline_3D_freestream = [],\n spline_3D_blown = [],\n\n # Design variables unique to the system function\n p_lam_tin= [],\n p_orientation = zeros(2),\n p_chord_pts = zeros(2),\n p_twist_pts = zeros(2),\n p_Rtip =0.0,\n kv =0.0,\n i0 =0.0,\n w_chord_pts = zeros(2),\n w_twist_pts = zeros(2),\n w_halfspan =0.0,\n w_sweep_pts = zeros(2),\n w_dihedral_pts = zeros(2),\n w_lam_tin= [],\n w_orientation = zeros(2),\n w_airfoilthickness = zeros(2),\n\n #Design variables unique to the system function\n etaprop_center = zeros(2),\n p_n_akima = 10 ,\n p_radii = zeros(2),\n altitude =0.0,\n numprops = 10 ,\n p_x_offset = zeros(2),\n p_aerocenter = zeros(2),\n p_usedmaterials = [],\n p_webloc = zeros(2),\n plyprops = [],\n blades = 10 ,\n w_n_linear = 10 ,\n w_x_offset = zeros(2),\n w_aerocenter = zeros(2),\n w_nondim_halfspany = zeros(2),\n w_usedmaterials = [],\n w_webloc = zeros(2),\n prop_tilt = 0.0,\n\n #Control parameters\n detailed = false,\n VTKfilename = \"notdefined.vtk\",\n savefinalvtk = false,\n verification = false,\n plots = false,\n n_CP = 60,\n )\n\n return propwingdesign(batt_mass, w_aoa, p_rpm, p_pitch, velocity,\n constraints, af, p_xaf, p_yaf, p_xafstrain, p_yafstrain, w_xaf, w_yaf,\n w_xafstrain, w_yafstrain, spline_3D_freestream, spline_3D_blown,\n p_lam_tin, p_orientation, p_chord_pts, p_twist_pts, p_Rtip, kv, i0,\n w_chord_pts, w_twist_pts, w_halfspan, w_sweep_pts, w_dihedral_pts,\n w_lam_tin, w_orientation, w_airfoilthickness, etaprop_center,\n p_n_akima, p_radii, altitude, numprops, p_x_offset, p_aerocenter,\n p_usedmaterials, p_webloc, plyprops, blades, w_n_linear, w_x_offset,\n w_aerocenter, w_nondim_halfspany, w_usedmaterials, w_webloc, prop_tilt,\n detailed, VTKfilename, savefinalvtk, verification, plots, n_CP)\nend\n\nstruct propwing_out\n #Propulsion\n ETA_total::Float64\n ETA_m::Float64\n ETA_p::Float64\n # Propeller\n CT::Float64\n CQ::Float64\n Np::Array{Float64,1}\n Tp::Array{Float64,1}\n p_alphas::Array{Float64,1}\n uprop::Array{Float64,1}\n vprop::Array{Float64,1}\n total_thrust::Float64\n advance_ratio::Float64\n torque::Float64\n db_test::Array{Float64,1}\n\n # Motor\n V_m::Float64\n I_m::Float64\n # Masses\n propwing_mass::Float64\n mass_prop::Float64\n mass_ESC::Float64\n mass_motor::Float64\n mass_wing::Float64\n\n # Wing\n panels#::Array{Float64,1}\n Lift::Float64\n Drag::Float64\n viscousDrag::Float64\n a::Float64\n Fp#::Array{Float64,1}\n cllocal::Array{Float64,1}\n cl::Array{Float64,1}\n Vinfeff::Array{Float64,1}\n alphaeff::Array{Float64,1}\n\n #Structures\n p_c_stress #::Array{Float64,2}\n w_c_stress #::Array{Float64,2}\n p_c_buckling #::Array{Float64,2}\n w_c_buckling #::Array{Float64,2}\n\n fail::Bool\nend\n\nfunction propwing_out(;\n #Propulsion\n ETA_total = 0.0,\n ETA_m = 0.0,\n ETA_p = 0.0,\n # Propeller\n CT = 0.0,\n CQ = 0.0,\n Np = zeros(2),\n Tp = zeros(2),\n p_alphas = zeros(2),\n uprop = zeros(2),\n vprop = zeros(2),\n total_thrust = 0.0,\n advance_ratio = 0.0,\n torque = 0.0,\n db_test = zeros(2),\n\n # Motor\n V_m = 0.0,\n I_m = 0.0,\n # Masses\n propwing_mass = 0.0,\n mass_prop = 0.0,\n mass_ESC = 0.0,\n mass_motor = 0.0,\n mass_wing = 0.0,\n\n # Wing\n panels = zeros(2),\n Lift = 0.0,\n Drag = 0.0,\n viscousDrag = 0.0,\n a = 0.0,\n Fp = [],# = zeros(2)\n cllocal = zeros(2),\n cl = zeros(2),\n Vinfeff = zeros(2),\n alphaeff = zeros(2),\n\n #Structures\n p_c_stress = zeros(2),\n w_c_stress = zeros(2),\n p_c_buckling = zeros(2),\n w_c_buckling = zeros(2),\n fail = false,\n)\n\n return propwing_out(ETA_total,ETA_m,ETA_p,CT,CQ,Np,Tp,p_alphas,uprop,vprop,total_thrust,\n advance_ratio,torque,db_test,V_m,I_m,propwing_mass,mass_prop,mass_ESC,\n mass_motor,mass_wing,panels,Lift,Drag,viscousDrag,a,Fp,cllocal,cl,Vinfeff,alphaeff,\n p_c_stress,w_c_stress,p_c_buckling,w_c_buckling, fail)\n\n\nend\n\nstruct system_output\n range_true::Float64\n dist_accel::Float64\n dist_climb::Float64\n\n energy_accel::Float64\n energy_climb::Float64\n energy_cruise::Float64\n\n t_accel::Float64\n t_transition::Float64\n t_climb::Float64\n t_cruise::Float64\n\n total_mass::Float64\n total_weight::Float64\n\n gama::Float64\n radius::Float64\n xtr::Float64\n ytr::Float64\n H_left::Float64\n x_left::Float64\n\n optconvals::Dict{Symbol,Array{Float64,1}}\n\n payload::Float64\n max_mass::Float64\n gravity::Float64\n h_set::Float64\n specif_energy::Float64\n required_takeoff_dist::Float64\n altitude_accel::Float64\n altitude_climb::Float64\n altitude_cruise::Float64\n required_noise::Float64\n etaprop_center::Array{Float64,1}\n batt_mass_accel::Float64\n batt_mass_climb::Float64\n batt_mass_cruise::Float64\n Fl::Float64\nend\n\nfunction system_output(;\n range_true = 0.0,\n dist_accel = 0.0,\n dist_climb = 0.0,\n\n energy_accel = 0.0,\n energy_climb = 0.0,\n energy_cruise = 0.0,\n\n t_accel = 0.0,\n t_transition = 0.0,\n t_climb = 0.0,\n t_cruise = 0.0,\n\n total_mass = 0.0,\n total_weight = 0.0,\n\n gama = 0.0,\n radius = 0.0,\n xtr = 0.0,\n ytr = 0.0,\n H_left = 0.0,\n x_left = 0.0,\n\n optconvals = Dict{Symbol,Array{Float64,1}}(),\n\n payload = 0.0,\n max_mass = 0.0,\n gravity = 0.0,\n h_set = 0.0,\n specif_energy = 0.0,\n required_takeoff_dist = 0.0,\n altitude_accel = 0.0,\n altitude_climb = 0.0,\n altitude_cruise = 0.0,\n required_noise = 0.0,\n etaprop_center = [0.0,0.0],\n batt_mass_accel = 0.0,\n batt_mass_climb = 0.0,\n batt_mass_cruise = 0.0,\n Fl = 0.0,\n )\n\n return system_output(range_true,dist_accel,dist_climb, energy_accel,\n energy_climb,energy_climb, t_accel,t_transition,t_climb,t_cruise,\n total_mass,total_weight, gama,radius,xtr,ytr,H_left,x_left, optconvals,\n payload,max_mass,gravity,h_set,specif_energy,required_takeoff_dist,\n altitude_accel,altitude_climb,altitude_cruise,required_noise,\n etaprop_center,batt_mass_accel,batt_mass_climb,batt_mass_cruise,Fl)\n\nend\n\n# This file sets up default values and bounds for design variables\nfunction getoptxbounds!(paramdict,designparams)\n\n ##############################################################################\n #----------------------- Prop Design Variables ------------------------#\n ##############################################################################\n\n lb_scale = 1.0 #1E-6\n ub_scale = 1E3\n # Skin Fabric Ply Thickness Design Variables\n p_nstations = length(designparams.p_radii)\n matnames = designparams.plyprops.names\n p_nplies = length(designparams.p_usedmaterials)\n\n name = :p_lam_t\n default = zeros(designparams.p_lam_t)\n lowerbound = zeros(designparams.p_lam_t)\n upperbound = zeros(designparams.p_lam_t)\n scaling = zeros(designparams.p_lam_t)\n for i = 1:p_nplies\n idx = find(matnames -> matnames == designparams.p_usedmaterials[i],matnames)\n material = designparams.plyprops.plies[idx[1]]\n\n default1 = designparams.p_lam_t[(i-1)*p_nstations+1:(i)*p_nstations]\n lowerbound1 = fill(designparams.plyprops.plies[idx[1]].t*lb_scale,p_nstations)\n upperbound1 = fill(designparams.plyprops.plies[idx[1]].t*ub_scale,p_nstations)\n scaling1 = fill(0.01/designparams.plyprops.plies[idx[1]].t,p_nstations)\n\n default[(i-1)*p_nstations+1:(i)*p_nstations] = default1\n lowerbound[(i-1)*p_nstations+1:(i)*p_nstations] = lowerbound1\n upperbound[(i-1)*p_nstations+1:(i)*p_nstations] = upperbound1\n scaling[(i-1)*p_nstations+1:(i)*p_nstations] = scaling1\n\n end\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n\n name = :p_orientation\n default = designparams.p_orientation\n lowerbound = fill(-90.0,length(default))\n upperbound = fill(90.0,length(default))\n scaling = fill(1.0./90.0,length(default))\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :p_chord\n default = designparams.p_chord\n lowerbound = fill(0.01,p_nstations)\n lowerbound[end] = 0.001 #tip, works well for splines\n upperbound = fill(0.8,p_nstations)\n scaling = fill(1E2,p_nstations)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :p_sweep_d\n default = designparams.p_sweep_d\n lowerbound = fill(0.0,p_nstations-1)\n upperbound = fill(45.0,p_nstations-1)\n scaling = fill(pi/180.0,p_nstations-1)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n OptParams.addparam!(paramdict,:p_pitch_d_accel, designparams.p_pitch_d*10.0, -25.0, 45.0, 1E1)\n OptParams.addparam!(paramdict,:p_pitch_d_climb, designparams.p_pitch_d*10.0, -25.0, 45.0, 1E0)\n OptParams.addparam!(paramdict,:p_pitch_d_cruise, designparams.p_pitch_d*-2, -5.0, 80.0, 1E2)\n\n name = :p_twist_d\n default = designparams.p_twist_d\n lowerbound = fill(-0.0,p_nstations)\n upperbound = fill(45.0,p_nstations)\n scaling = fill(0.1,p_nstations)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :p_dihedral_d\n default = designparams.p_dihedral_d\n lowerbound = fill(0.0,p_nstations-1)\n upperbound = fill(10.0,p_nstations-1)\n scaling = fill(pi/180.0,p_nstations-1)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :p_airfoilthickness\n default = designparams.p_airfoilthickness\n lowerbound = fill(0.050,p_nstations)\n upperbound = fill(0.250,p_nstations)\n scaling = fill(10.0,p_nstations)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n\n OptParams.addparam!(paramdict,:p_Rtip,designparams.p_Rtip,0.1,5.0,1E-1)\n\n ##############################################################################\n #----------------------- Wing Design Variables ------------------------#\n ##############################################################################\n\n # Skin Fabric Ply Thickness Design Variables\n w_nstations = length(designparams.w_chord)\n\n name = :w_lam_t\n default = zeros(designparams.w_lam_t)\n lowerbound = zeros(designparams.w_lam_t)\n upperbound = zeros(designparams.w_lam_t)\n scaling = zeros(designparams.w_lam_t)\n for i = 1:length(designparams.w_usedmaterials)\n idx = find(matnames -> matnames == designparams.w_usedmaterials[i],matnames)\n material = designparams.plyprops.plies[idx[1]]\n\n default1 = designparams.w_lam_t[(i-1)*w_nstations+1:(i)*w_nstations]\n lowerbound1 = fill(designparams.plyprops.plies[idx[1]].t*lb_scale,w_nstations)\n upperbound1 = fill(designparams.plyprops.plies[idx[1]].t*ub_scale,w_nstations)\n scaling1 = fill(0.01/designparams.plyprops.plies[idx[1]].t,w_nstations)\n\n default[(i-1)*w_nstations+1:(i)*w_nstations] = default1\n lowerbound[(i-1)*w_nstations+1:(i)*w_nstations] = lowerbound1\n upperbound[(i-1)*w_nstations+1:(i)*w_nstations] = upperbound1\n scaling[(i-1)*w_nstations+1:(i)*w_nstations] = scaling1\n\n end\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :w_orientation\n default = designparams.w_orientation\n lowerbound = fill(-90.0,length(default))\n upperbound = fill(90.0,length(default))\n scaling = fill(1.0./90.0,length(default))\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :w_chord\n default = designparams.w_chord\n lowerbound = fill(0.1,w_nstations)\n upperbound = fill(5.0,w_nstations)\n scaling = fill(100.0/designparams.w_halfspan,w_nstations)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n OptParams.addparam!(paramdict,:w_aoa_d_accel,designparams.w_aoa_d*1.1,2.0,40.0,1E-2)\n OptParams.addparam!(paramdict,:w_aoa_d_climb,designparams.w_aoa_d*0.5,5.0,40.0,1E0)\n OptParams.addparam!(paramdict,:w_aoa_d_cruise,designparams.w_aoa_d*0.5,0.20,20.0,1E0)\n\n name = :w_twist_d\n default = designparams.w_twist_d\n lowerbound = fill(-10.0,w_nstations)\n upperbound = fill(20.0,w_nstations)\n scaling = fill(10.0,w_nstations)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :w_halfspan\n default = designparams.w_halfspan\n lowerbound = 5.699\n upperbound = 12.0\n scaling = 1.0/designparams.w_halfspan\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :w_sweep_d\n default = designparams.w_sweep_d\n lowerbound = fill(0.0,w_nstations)\n upperbound = fill(20.0,w_nstations)\n scaling = fill(10.0,w_nstations)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :w_dihedral_d\n default = designparams.w_dihedral_d\n lowerbound = fill(0.0,w_nstations)\n upperbound = fill(20.0,w_nstations)\n scaling = fill(10.0,w_nstations)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n name = :w_airfoilthickness\n default = designparams.p_airfoilthickness\n lowerbound = fill(0.050,p_nstations)\n upperbound = fill(0.250,p_nstations)\n scaling = fill(10.0,p_nstations)\n OptParams.addparam!(paramdict,name,default,lowerbound,upperbound,scaling)\n\n\n\n\n ##############################################################################\n #----------------- Operating Point Design Variables ------------------------#\n ##############################################################################\n\n OptParams.addparam!(paramdict,:velocity_accel,designparams.velocity/1.4,5.0,28.0,1E1)\n OptParams.addparam!(paramdict,:velocity_climb,designparams.velocity*1.0,5.0,60.0,1E-2)\n OptParams.addparam!(paramdict,:velocity_cruise,designparams.velocity*1.0,20.0,100.0,1E1)\n\n ##############################################################################\n #------------------------- Propulsion Design Variables ---------------------#\n ##############################################################################\n\n OptParams.addparam!(paramdict,:p_rpm_accel,designparams.p_rpm*4.5,200.0,40000.0,1E-1)\n OptParams.addparam!(paramdict,:p_rpm_climb,designparams.p_rpm*4.6,200.0,40000.0,1E-2)\n OptParams.addparam!(paramdict,:p_rpm_cruise,designparams.p_rpm*2.5,100.0,10000.0,1E0)\n OptParams.addparam!(paramdict,:kv,designparams.kv,5.0,5000.0,1E-0)\n OptParams.addparam!(paramdict,:i0,designparams.i0,0.1,6.0,1E0)\n OptParams.addparam!(paramdict,:batt_mass_accel,designparams.batt_mass,0.001,100.0,1E0)\n OptParams.addparam!(paramdict,:batt_mass_climb,designparams.batt_mass,0.01,100.0,1E-1)\n OptParams.addparam!(paramdict,:batt_mass_cruise,designparams.batt_mass,5.0,1000.0,1E-1)\n OptParams.addparam!(paramdict,:number_blades,2.0,2.0,5.0,1E-0)\n OptParams.addparam!(paramdict,:radius,100.0,2.0,2000.0,1E-1)\n OptParams.addparam!(paramdict,:gama_d,30.0,0.1,89.9,1E-1)\nend\n\n#------ SET UP OPTIMIZATION PARAMETERS -------#\n\nmutable struct controlparams\n objective::Symbol\n printfreq::Int\n savevtk::Int\n printobjective::Bool\n printdetailedoutput::Bool\n printconstraintviolations::Bool\nend\n\nfunction controlparams(;\n objective::Symbol = :mass,\n printfreq::Int = 1,\n savevtk::Int = 3,\n printobjective::Bool = true,\n printdetailedoutput::Bool = true,\n printconstraintviolations::Bool = true,\n )\n controlparams(objective,printfreq,savevtk,printobjective,printdetailedoutput,\n printconstraintviolations)\nend\n\n# Define design variables\nfunction getoptparams()\n designvar = [\n :p_lam_t, #1-12\n # :p_orientation,\n :p_chord, #13-18\n :p_twist_d, #19-24\n :p_pitch_d_accel, #25\n :p_pitch_d_climb, #25\n :p_pitch_d_cruise, #25\n\n :velocity_accel,\n :velocity_climb,\n :velocity_cruise,\n :p_Rtip,\n :p_rpm_accel,\n :p_rpm_climb,\n :p_rpm_cruise,\n # :kv, #28\n # :i0, #29\n\n\n # :w_orientation,\n :w_chord, #30-32\n :w_aoa_d_accel, #multi\n :w_aoa_d_climb, #multi\n :w_aoa_d_cruise, #multi\n # :w_twist_d, #33-35\n # :w_halfspan,\n # :w_sweep_d,\n # :w_dihedral_d,\n # :w_lam_t, #36-end\n :batt_mass_accel,\n :batt_mass_climb,\n :batt_mass_cruise,\n ]\n\n # Define general constraints\n constraints = [\n :p_materialfailure,\n :p_localbuckling,\n # :w_materialfailure,\n # :w_localbuckling,\n\n :totalmass,\n :machtip,\n :Lift,\n :Drag,\n :noise,\n # :p_chordlamthick,\n # :range,\n :takeoff_dist,\n :stall,\n :capacity,\n :p_alphas,\n ]\n\n # define run controls\n ctlparams = controlparams(\n objective= :range, #:mass,#:range #:ETA_total_cruise,\n printfreq = 50,\n savevtk = 500,\n printobjective=true,\n printdetailedoutput=true,\n printconstraintviolations=true,\n )\n\n return designvar, constraints, ctlparams\nend\n\n\n#------- MATERIAL PROPERTIES -------#\nfunction plyproperties()\n names = [\"highmodulus_uni\",\n \"standard_uni\",\n \"MR60H\",\n \"T3900_uni\",\n \"T700_uni\",\n \"ELT5500\",\n \"UDCarbon\",\n \"highmodulus_weave\",\n \"standard_weave\",\n \"T3900_weave\",\n \"T700_weave\",\n \"Gelcoat\",\n \"Triax\",\n \"Saertex\",\n \"taylor_foam\",\n \"SNL_foam\"]\n\n e1 =zeros(16)\n e2 =zeros(16)\n g12 =zeros(16)\n anu =zeros(16)\n rho =zeros(16)\n xt =zeros(16)\n xc =zeros(16)\n yt =zeros(16)\n yc =zeros(16)\n s =zeros(16)\n plythickness =zeros(16)\n\n # \"highmodulus_uni\"\n e1[1] = 175.0e9\n e2[1] = 8.0e9\n g12[1] = 5.0e9\n anu[1] = 0.30\n rho[1] = 1600.0\n xt[1] = min(1.0,1355.656/1682.011)*1000e6 #mean -> A-basis\n xc[1] = min(1.0,1103.943/1396.504)*850e6 #mean -> A-basis\n yt[1] = min(1.0,39.226/52.975)*40e6 #mean -> A-basis\n yc[1] = min(1.0,235.434/282.439)*200e6 #mean -> A-basis\n s[1] = min(1.0,142.411/159.516)*60e6 #mean -> A-basis\n plythickness[1] = 0.152e-3\n # \"standard_uni\"\n e1[2] = 135.0e9\n e2[2] = 10.0e9\n g12[2] = 5.0e9\n anu[2] = 0.30\n rho[2] = 1600.0\n xt[2] = min(1.0,1355.656/1682.011)*1500e6 #mean -> A-basis\n xc[2] = min(1.0,1103.943/1396.504)*1200e6 #mean -> A-basis\n yt[2] = min(1.0,39.226/52.975)*50e6 #mean -> A-basis\n yc[2] = min(1.0,235.434/282.439)*250e6 #mean -> A-basis\n s[2] = min(1.0,142.411/159.516)*70e6 #mean -> A-basis\n plythickness[2] = 0.152e-3\n # \"MR60H\"\n e1[3] = (165e9+150e9)/2.0\n e2[3] = 8.56e9\n g12[3] = 4.39e9\n anu[3] = 0.326\n rho[3] = 1810.0\n xt[3] = min(1.0,1355.656/1682.011)*3190e6 #mean -> A-basis\n xc[3] = min(1.0,1103.943/1396.504)*1440e6 #mean -> A-basis\n yt[3] = min(1.0,39.226/52.975)*82.0e6 #mean -> A-basis\n yc[3] = min(1.0,235.434/282.439)*200.0e6 #mean -> A-basis\n s[3] = min(1.0,142.411/159.516)*141e6 #mean -> A-basis\n plythickness[3] = 0.152e-3\n # \"T3900_uni\"\n e1[4] = (148e9+131e9)/2.0\n e2[4] = (9.7e9+9.7e9)/2.0\n g12[4] = 4.83e9\n anu[4] = 0.33\n rho[4] = 1573.0\n xt[4] = min(1.0,1355.656/1682.011)*2830e6 #CTD mean -> A-basis\n xc[4] = min(1.0,1103.943/1396.504)*1772e6 #CTD mean -> A-basis\n yt[4] = min(1.0,39.226/52.975)*56.9e6 #CTD mean -> A-basis\n yc[4] = min(1.0,235.434/282.439)*303e6 #CTD mean -> A-basis\n s[4] = min(1.0,142.411/159.516)*89.6e6 #CTD mean -> A-basis\n plythickness[4] = 0.191e-3\n # \"T700_uni\"\n e1[5]=120.8e9\n e2[5]=11.57e9\n g12[5]=5.219e9\n anu[5]=0.350\n rho[5]=1525.0\n xt[5]=1356e6\n xc[5]=1104e6\n yt[5]=39.23e6\n yc[5]=235.4e6\n s[5]=142.4e6\n plythickness[5] = 0.152e-3\n # \"ELT5500\"\n e1[6]=41.8e9\n e2[6]=14.00e9\n g12[6]=2.630e9\n anu[6]=0.280\n rho[6]=1920.0\n xt[6]=972.0e6\n xc[6]=702.0e6\n yt[6]=100.0e6 #made up\n yc[6]=100.0e6 #made up\n s[6]=100.0e6 #made up\n plythickness[6] = 0.47e-3\n # \"UDCarbon\"\n e1[7]=114.5e9\n e2[7]=8.39e9\n g12[7]=5.990e9\n anu[7]=0.270\n rho[7]=1220.0\n xt[7]=1546.0e6\n xc[7]=1047.0e6\n yt[7]=100.0e6 #made up\n yc[7]=100.0e6 #made up\n s[7]=100.0e6 #made up\n plythickness[7] = 0.47e-3\n\n # FABRICS\n # \"highmodulus_weave\"\n e1[8] = 85.0e9\n e2[8] = 85.0e9\n g12[8] = 5.0e9\n anu[8] = 0.10\n rho[8] = 1600.0\n xt[8] = min(1.0,1355.656/1682.011)*350e6 #mean -> A-basis\n xc[8] = min(1.0,1103.943/1396.504)*150e6 #mean -> A-basis\n yt[8] = min(1.0,39.226/52.975)*350e6 #mean -> A-basis\n yc[8] = min(1.0,235.434/282.439)*150e6 #mean -> A-basis\n s[8] = min(1.0,142.411/159.516)*35e6 #mean -> A-basis\n plythickness[8] = 0.218e-3\n # \"standard_weave\"\n e1[9] = 70.0e9\n e2[9] = 70.0e9\n g12[9] = 5.0e9\n anu[9] = 0.10\n rho[9] = 1600.0\n xt[9] = min(1.0,1355.656/1682.011)*600e6 #mean -> A-basis\n xc[9] = min(1.0,1103.943/1396.504)*570e6 #mean -> A-basis\n yt[9] = min(1.0,39.226/52.975)*600e6 #mean -> A-basis\n yc[9] = min(1.0,235.434/282.439)*570e6 #mean -> A-basis\n s[9] = min(1.0,142.411/159.516)*90e6 #mean -> A-basis\n plythickness[9] = 0.218e-3\n # \"T3900_weave\"\n e1[10] = (70.3e9+71.0e9)/2.0\n e2[10] = (68.9e9+67.6e9)/2.0\n g12[10] = 4.6e9\n anu[10] = 0.032\n rho[10] = 1551.0\n xt[10] = min(1.0,701.302/803.236)*1055e6 #CTD mean -> A-basis\n xc[10] = min(1.0,549.748/749.955)*676e6 #CTD mean -> A-basis\n yt[10] = min(1.0,557.575/722.602)*945e6 #CTD mean -> A-basis\n yc[10] = min(1.0,604.067/741.866)*614e6 #CTD mean -> A-basis\n s[10] = min(1.0,138.440/154.888)*79.3e6 #CTD mean -> A-basis\n plythickness[10] = 0.218e-3\n # \"T700_weave\"\n e1[11]=55.82e9\n e2[11]=52.10e9\n g12[11]=4.295e9\n anu[11]=0.085\n rho[11]=1501.0\n xt[11]=701.32e6\n yt[11]=557.59e6\n xc[11]=549.77e6\n yc[11]=604.08e6\n s[11]=138.44e6\n plythickness[11] = 0.218e-3\n # \"Gelcoat\"\n e1[12]=3.44e9\n e2[12]=3.44e9\n g12[12]=1.38e9\n anu[12]=0.3\n rho[12]=1235.0\n xt[12]=100.0e6 #made up\n xc[12]=100.0e6 #made up\n yt[12]=100.0e6 #made up\n yc[12]=100.0e6 #made up\n s[12]=100.0e6 #made up\n plythickness[12] = 0.05e-3\n # \"Triax\"\n e1[13]=27.7e9\n e2[13]=13.65e9\n g12[13]=7.2e9\n anu[13]=0.39\n rho[13]=1850.0\n xt[13]=700.0e6\n xc[13]=100.0e6 #made up\n yt[13]=700.0e6\n yc[13]=100.0e6 #made up\n s[13]=100.0e6 #made up\n plythickness[13] = 0.94e-3\n # \"Saertex\"\n e1[14]=13.6e9\n e2[14]=13.3e9\n g12[14]=11.8e9\n anu[14]=0.49\n rho[14]=1780.0\n xt[14]=144.0e6\n xc[14]=213.0e6\n yt[14]=144.0e6\n yc[14]=213.0e6\n s[14]=100.0e6 #made up\n plythickness[14] = 1.0e-3\n\n #FOAMS\n # \"taylor_foam\"\n e1[15]=48.0e6\n e2[15]=48.0e6\n g12[15]=28.0e6\n anu[15]=0.3\n rho[15]=75.0\n xt[15]=100.0e6 #made up\n yt[15]=100.0e6 #made up\n xc[15]=100.0e6 #made up\n yc[15]=100.0e6 #made up\n s[15]=100.0e6 #made up\n plythickness[15]=1.0E-3\n # \"SNL_foam\"\n e1[16]=256.0e6\n e2[16]=256.0e6\n g12[16]=22.0e6\n anu[16]=0.3\n rho[16]=200.0\n xt[16]=100.0e6 #made up\n yt[16]=100.0e6 #made up\n xc[16]=100.0e6 #made up\n yc[16]=100.0e6 #made up\n s[16]=100.0e6 #made up\n plythickness[16]=1.0E-3\n\n return plyproperties(names,Composites.material(e1,e2,g12,anu,rho,xt,xc,yt,yc,s,plythickness))\nend\n", "meta": {"hexsha": "dbd15acd52b53e32033c19527fa7ddaa65e39255", "size": 30569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/setup.jl", "max_stars_repo_name": "byuflowlab/moore2019multipropopt", "max_stars_repo_head_hexsha": "116e2ec2ec7885285b8865ef571864874dfa4574", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-17T14:22:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T14:30:49.000Z", "max_issues_repo_path": "src/setup.jl", "max_issues_repo_name": "byuflowlab/moore2019multipropopt", "max_issues_repo_head_hexsha": "116e2ec2ec7885285b8865ef571864874dfa4574", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/setup.jl", "max_forks_repo_name": "byuflowlab/moore2019multipropopt", "max_forks_repo_head_hexsha": "116e2ec2ec7885285b8865ef571864874dfa4574", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.280651341, "max_line_length": 173, "alphanum_fraction": 0.6371487455, "num_tokens": 11252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24361671903168114}} {"text": "## Expressions ##\n\n\n### Expression templates ###\n\n\"Defines branch indicator as a function of corresponding ne_branch indicator variables.\"\nfunction expression_branch_indicator(pm::_PM.AbstractPowerModel, br_idx::Int; nw::Int=_PM.nw_id_default)\n if !haskey(_PM.var(pm, nw), :z_branch)\n _PM.var(pm, nw)[:z_branch] = Dict{Int,Any}()\n end\n\n branch = _PM.ref(pm, nw, :branch, br_idx)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n\n expression_branch_indicator(pm, nw, br_idx, f_bus, t_bus)\nend\n\n\n### Actual expressions ###\n\nfunction expression_branch_indicator(pm::_PM.AbstractPowerModel, n::Int, br_idx, f_bus, t_bus)\n branch_ne_sum = sum(_PM.var(pm, n, :branch_ne, l) for l in _PM.ref(pm, n, :ne_buspairs, (f_bus,t_bus), \"branches\")) \n\n _PM.var(pm, n, :z_branch)[br_idx] = 1 - branch_ne_sum\nend\n\n\n\n## Constraints ##\n\n\n### Constraint templates ###\n\n\"\"\nfunction constraint_ohms_yt_from_repl(pm::_PM.AbstractPowerModel, i::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, i)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (i, f_bus, t_bus)\n t_idx = (i, t_bus, f_bus)\n\n g, b = _PM.calc_branch_y(branch)\n tr, ti = _PM.calc_branch_t(branch)\n g_fr = branch[\"g_fr\"]\n b_fr = branch[\"b_fr\"]\n tm = branch[\"tap\"]\n\n vad_min = _PM.ref(pm, nw, :off_angmin)\n vad_max = _PM.ref(pm, nw, :off_angmax)\n\n\n # track if a certain candidate branch is replacing a line \n replace, ne_br_idx = replace_branch(pm, nw, f_bus, t_bus)\n # If lines is to be repalced use formulations below, else use PowerModels constraint for existing branches\n if replace == 0\n _PM.constraint_ohms_yt_from(pm, nw, f_bus, t_bus, f_idx, t_idx, g, b, g_fr, b_fr, tr, ti, tm)\n else\n constraint_ohms_yt_from_repl(pm, nw, ne_br_idx, f_bus, t_bus, f_idx, b, vad_min, vad_max)\n end\nend\n\n\"\"\nfunction constraint_ohms_yt_to_repl(pm::_PM.AbstractPowerModel, i::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, i)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (i, f_bus, t_bus)\n t_idx = (i, t_bus, f_bus)\n\n g, b = _PM.calc_branch_y(branch)\n tr, ti = _PM.calc_branch_t(branch)\n g_to = branch[\"g_to\"]\n b_to = branch[\"b_to\"]\n tm = branch[\"tap\"]\n\n vad_min = _PM.ref(pm, nw, :off_angmin)\n vad_max = _PM.ref(pm, nw, :off_angmax)\n\n # track if a certain candidate branch is replacing a line \n replace, ne_br_idx = replace_branch(pm, nw, f_bus, t_bus)\n # If lines is to be repalced use formulations below, else use PowerModels constraint for existing branches\n if replace == 0\n _PM.constraint_ohms_yt_to(pm, nw, f_bus, t_bus, f_idx, t_idx, g, b, g_to, b_to, tr, ti, tm)\n else\n constraint_ohms_yt_to_repl(pm, nw, ne_br_idx, f_bus, t_bus, t_idx, b, vad_min, vad_max)\n end\nend\n\nfunction constraint_voltage_angle_difference_repl(pm::_PM.AbstractPowerModel, i::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, i)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (i, branch[\"f_bus\"], branch[\"t_bus\"])\n\n vad_min = _PM.ref(pm, nw, :off_angmin)\n vad_max = _PM.ref(pm, nw, :off_angmax)\n\n # track if a certain candidate branch is replacing a line \n replace, ne_br_idx = replace_branch(pm, nw, f_bus, t_bus)\n # If lines is to be repalced use formulations below, else use PowerModels constraint for existing branches\n if replace == 0\n _PM.constraint_voltage_angle_difference(pm, nw, f_idx, branch[\"angmin\"], branch[\"angmax\"])\n else\n constraint_voltage_angle_difference_repl(pm, nw, ne_br_idx, f_idx, branch[\"angmin\"], branch[\"angmax\"], vad_min, vad_max)\n end\nend\n\nfunction constraint_thermal_limit_from_repl(pm::_PM.AbstractPowerModel, i::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, i)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (i, f_bus, t_bus)\n\n if !haskey(branch, \"rate_a\")\n Memento.error(_LOGGER, \"constraint_thermal_limit_from_ne requires a rate_a value on all branches, calc_thermal_limits! can be used to generate reasonable values\")\n end\n\n # track if a certain candidate branch is replacing a line \n replace, ne_br_idx = replace_branch(pm, nw, f_bus, t_bus)\n # If lines is to be repalced use formulations below, else use PowerModels constraint for existing branches\n if replace == 0\n _PM.constraint_thermal_limit_from(pm, nw, f_idx, branch[\"rate_a\"])\n else\n constraint_thermal_limit_from_repl(pm, nw, ne_br_idx, f_idx, branch[\"rate_a\"])\n end\nend\n\n\"\"\nfunction constraint_thermal_limit_to_repl(pm::_PM.AbstractPowerModel, i::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, i)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n t_idx = (i, t_bus, f_bus)\n\n if !haskey(branch, \"rate_a\")\n Memento.error(_LOGGER, \"constraint_thermal_limit_to_ne requires a rate_a value on all branches, calc_thermal_limits! can be used to generate reasonable values\")\n end\n # track if a certain candidate branch is replacing a line \n replace, ne_br_idx = replace_branch(pm, nw, f_bus, t_bus)\n # If lines is to be repalced use formulations below, else use PowerModels constraint for existing branches\n if replace == 0\n _PM.constraint_thermal_limit_to(pm, nw, t_idx, branch[\"rate_a\"])\n else\n constraint_thermal_limit_to_repl(pm, nw, ne_br_idx, t_idx, branch[\"rate_a\"])\n end\nend\n\n\n#### Constraint templates used in radial networks ####\n\n\"States that at most one of the ne_branches sharing the same bus pair must be built.\"\nfunction constraint_branch_complementarity(pm::_PM.AbstractPowerModel, br_idx::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n\n constraint_branch_complementarity(pm, nw, br_idx, f_bus, t_bus)\nend\n\n\"\"\nfunction constraint_power_losses_on_off(pm::_PM.AbstractPowerModel, br_idx::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (br_idx, f_bus, t_bus)\n t_idx = (br_idx, t_bus, f_bus)\n\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n tm = branch[\"tap\"]\n g_sh_fr = branch[\"g_fr\"]\n g_sh_to = branch[\"g_to\"]\n b_sh_fr = branch[\"b_fr\"]\n b_sh_to = branch[\"b_to\"]\n\n vad_min = _PM.ref(pm, nw, :off_angmin)\n vad_max = _PM.ref(pm, nw, :off_angmax)\n\n constraint_power_losses_on_off(pm, nw, br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, g_sh_to, b_sh_fr, b_sh_to, tm, vad_min, vad_max)\nend\n\n\"\"\nfunction constraint_power_losses_frb_on_off(pm::_PM.AbstractPowerModel, br_idx::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (br_idx, f_bus, t_bus)\n t_idx = (br_idx, t_bus, f_bus)\n\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n tm = branch[\"tap\"]\n g_sh_fr = branch[\"g_fr\"]\n g_sh_to = branch[\"g_to\"]\n b_sh_fr = branch[\"b_fr\"]\n b_sh_to = branch[\"b_to\"]\n\n vad_min = _PM.ref(pm, nw, :off_angmin)\n vad_max = _PM.ref(pm, nw, :off_angmax)\n\n constraint_power_losses_frb_on_off(pm, nw, br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, g_sh_to, b_sh_fr, b_sh_to, tm, vad_min, vad_max)\nend\n\n\"\"\nfunction constraint_power_losses_oltc_on_off(pm::_PM.AbstractBFModel, br_idx::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (br_idx, f_bus, t_bus)\n t_idx = (br_idx, t_bus, f_bus)\n\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n g_sh_fr = branch[\"g_fr\"]\n g_sh_to = branch[\"g_to\"]\n b_sh_fr = branch[\"b_fr\"]\n b_sh_to = branch[\"b_to\"]\n\n vad_min = _PM.ref(pm, nw, :off_angmin)\n vad_max = _PM.ref(pm, nw, :off_angmax)\n\n constraint_power_losses_oltc_on_off(pm, nw, br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, g_sh_to, b_sh_fr, b_sh_to, vad_min, vad_max)\nend\n\n\"\"\nfunction constraint_ne_power_losses_parallel(pm::_PM.AbstractPowerModel, ne_br_idx::Int; nw::Int=_PM.nw_id_default)\n ne_branch = _PM.ref(pm, nw, :ne_branch, ne_br_idx)\n f_bus = ne_branch[\"f_bus\"]\n t_bus = ne_branch[\"t_bus\"]\n f_idx = (ne_br_idx, f_bus, t_bus)\n t_idx = (ne_br_idx, t_bus, f_bus)\n vad_min = _PM.ref(pm, nw, :off_angmin)\n vad_max = _PM.ref(pm, nw, :off_angmax)\n\n ne_r = ne_branch[\"br_r\"]\n ne_x = ne_branch[\"br_x\"]\n ne_tm = ne_branch[\"tap\"]\n ne_g_sh_fr = ne_branch[\"g_fr\"]\n ne_g_sh_to = ne_branch[\"g_to\"]\n ne_b_sh_fr = ne_branch[\"b_fr\"]\n ne_b_sh_to = ne_branch[\"b_to\"]\n\n br_idx = branch_idx(pm, nw, f_bus, t_bus)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n tm = branch[\"tap\"]\n g_sh_fr = branch[\"g_fr\"]\n g_sh_to = branch[\"g_to\"]\n b_sh_fr = branch[\"b_fr\"]\n b_sh_to = branch[\"b_to\"]\n\n if ne_tm != tm\n Memento.error(_LOGGER, \"ne_branch $(ne_br_idx) cannot be built in parallel to branch $(br_idx) because has a different tap ratio\")\n end\n\n constraint_ne_power_losses_parallel(pm, nw, br_idx, ne_br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, g_sh_to, b_sh_fr, b_sh_to, ne_r, ne_x, ne_g_sh_fr, ne_g_sh_to, ne_b_sh_fr, ne_b_sh_to, tm, vad_min, vad_max)\nend\n\n\"\"\nfunction constraint_ne_power_losses_frb_parallel(pm::_PM.AbstractPowerModel, ne_br_idx::Int; nw::Int=_PM.nw_id_default)\n ne_branch = _PM.ref(pm, nw, :ne_branch, ne_br_idx)\n f_bus = ne_branch[\"f_bus\"]\n t_bus = ne_branch[\"t_bus\"]\n f_idx = (ne_br_idx, f_bus, t_bus)\n t_idx = (ne_br_idx, t_bus, f_bus)\n vad_min = _PM.ref(pm, nw, :off_angmin)\n vad_max = _PM.ref(pm, nw, :off_angmax)\n\n ne_r = ne_branch[\"br_r\"]\n ne_x = ne_branch[\"br_x\"]\n ne_tm = ne_branch[\"tap\"]\n ne_g_sh_fr = ne_branch[\"g_fr\"]\n ne_g_sh_to = ne_branch[\"g_to\"]\n ne_b_sh_fr = ne_branch[\"b_fr\"]\n ne_b_sh_to = ne_branch[\"b_to\"]\n\n br_idx = branch_idx(pm, nw, f_bus, t_bus)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n tm = branch[\"tap\"]\n g_sh_fr = branch[\"g_fr\"]\n g_sh_to = branch[\"g_to\"]\n b_sh_fr = branch[\"b_fr\"]\n b_sh_to = branch[\"b_to\"]\n\n if ne_tm != tm\n Memento.error(_LOGGER, \"ne_branch $(ne_br_idx) cannot be built in parallel to branch $(br_idx) because has a different tap ratio\")\n end\n\n constraint_ne_power_losses_frb_parallel(pm, nw, br_idx, ne_br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, g_sh_to, b_sh_fr, b_sh_to, ne_r, ne_x, ne_g_sh_fr, ne_g_sh_to, ne_b_sh_fr, ne_b_sh_to, tm, vad_min, vad_max)\nend\n\n\"\"\nfunction constraint_voltage_magnitude_difference_on_off(pm::_PM.AbstractPowerModel, br_idx::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (br_idx, f_bus, t_bus)\n t_idx = (br_idx, t_bus, f_bus)\n\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n g_sh_fr = branch[\"g_fr\"]\n b_sh_fr = branch[\"b_fr\"]\n tm = branch[\"tap\"]\n\n constraint_voltage_magnitude_difference_on_off(pm, nw, br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, b_sh_fr, tm)\nend\n\n\"\"\nfunction constraint_voltage_magnitude_difference_frb_on_off(pm::_PM.AbstractPowerModel, br_idx::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (br_idx, f_bus, t_bus)\n t_idx = (br_idx, t_bus, f_bus)\n\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n g_sh_fr = branch[\"g_fr\"]\n b_sh_fr = branch[\"b_fr\"]\n tm = branch[\"tap\"]\n\n constraint_voltage_magnitude_difference_frb_on_off(pm, nw, br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, b_sh_fr, tm)\nend\n\n\"\"\nfunction constraint_voltage_magnitude_difference_oltc_on_off(pm::_PM.AbstractBFModel, br_idx::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n f_idx = (br_idx, f_bus, t_bus)\n t_idx = (br_idx, t_bus, f_bus)\n\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n g_sh_fr = branch[\"g_fr\"]\n b_sh_fr = branch[\"b_fr\"]\n tm_min = branch[\"tm_min\"]\n tm_max = branch[\"tm_max\"]\n\n constraint_voltage_magnitude_difference_oltc_on_off(pm, nw, br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, b_sh_fr, tm_min, tm_max)\nend\n\n\"\"\nfunction constraint_ne_voltage_magnitude_difference_parallel(pm::_PM.AbstractPowerModel, ne_br_idx::Int; nw::Int =_PM.nw_id_default)\n ne_branch = _PM.ref(pm, nw, :ne_branch, ne_br_idx)\n f_bus = ne_branch[\"f_bus\"]\n t_bus = ne_branch[\"t_bus\"]\n f_idx = (ne_br_idx, f_bus, t_bus)\n t_idx = (ne_br_idx, t_bus, f_bus)\n\n ne_r = ne_branch[\"br_r\"]\n ne_x = ne_branch[\"br_x\"]\n ne_g_sh_fr = ne_branch[\"g_fr\"]\n ne_b_sh_fr = ne_branch[\"b_fr\"]\n ne_tm = ne_branch[\"tap\"]\n\n br_idx = branch_idx(pm, nw, f_bus, t_bus)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n g_sh_fr = branch[\"g_fr\"]\n b_sh_fr = branch[\"b_fr\"]\n tm = branch[\"tap\"]\n if is_oltc_branch(pm, br_idx, nw = nw)\n Memento.error(_LOGGER, \"ne_branch $ne_br_idx cannot be built in parallel to an OLTC (branch $br_idx)\")\n end\n if ne_tm != tm\n Memento.error(_LOGGER, \"ne_branch $ne_br_idx cannot be built in parallel to branch $br_idx because has a different tap ratio\")\n end\n\n constraint_ne_voltage_magnitude_difference_parallel(pm, nw, br_idx, ne_br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, b_sh_fr, ne_r, ne_x, ne_g_sh_fr, ne_b_sh_fr, tm)\nend\n\n\"\"\nfunction constraint_ne_voltage_magnitude_difference_frb_parallel(pm::_PM.AbstractPowerModel, ne_br_idx::Int; nw::Int =_PM.nw_id_default)\n ne_branch = _PM.ref(pm, nw, :ne_branch, ne_br_idx)\n f_bus = ne_branch[\"f_bus\"]\n t_bus = ne_branch[\"t_bus\"]\n f_idx = (ne_br_idx, f_bus, t_bus)\n t_idx = (ne_br_idx, t_bus, f_bus)\n\n ne_r = ne_branch[\"br_r\"]\n ne_x = ne_branch[\"br_x\"]\n ne_g_sh_fr = ne_branch[\"g_fr\"]\n ne_b_sh_fr = ne_branch[\"b_fr\"]\n ne_tm = ne_branch[\"tap\"]\n\n br_idx = branch_idx(pm, nw, f_bus, t_bus)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n r = branch[\"br_r\"]\n x = branch[\"br_x\"]\n g_sh_fr = branch[\"g_fr\"]\n b_sh_fr = branch[\"b_fr\"]\n tm = branch[\"tap\"]\n\n if is_oltc_branch(pm, br_idx, nw = nw)\n Memento.error(_LOGGER, \"ne_branch $ne_br_idx cannot be built in parallel to an OLTC (branch $br_idx)\")\n end\n if ne_tm != tm\n Memento.error(_LOGGER, \"ne_branch $ne_br_idx cannot be built in parallel to branch $br_idx because has a different tap ratio\")\n end\n\n constraint_ne_voltage_magnitude_difference_frb_parallel(pm, nw, br_idx, ne_br_idx, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, b_sh_fr, ne_r, ne_x, ne_g_sh_fr, ne_b_sh_fr, tm)\nend\n\n\"\"\nfunction constraint_ne_thermal_limit_from_parallel(pm::_PM.AbstractPowerModel, ne_br_idx::Int; nw::Int=_PM.nw_id_default)\n ne_branch = _PM.ref(pm, nw, :ne_branch, ne_br_idx)\n f_bus = ne_branch[\"f_bus\"]\n t_bus = ne_branch[\"t_bus\"]\n f_idx = (ne_br_idx, f_bus, t_bus)\n if !haskey(ne_branch, \"rate_a\")\n Memento.error(_LOGGER, \"constraint_ne_thermal_limit_from_parallel requires a rate_a value on all ne_branches, calc_thermal_limits! can be used to generate reasonable values\")\n end\n ne_rate_a = ne_branch[\"rate_a\"]\n\n br_idx = branch_idx(pm, nw, f_bus, t_bus)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n rate_a = branch[\"rate_a\"]\n\n constraint_ne_thermal_limit_from_parallel(pm, nw, br_idx, ne_br_idx, f_idx, rate_a, ne_rate_a)\nend\n\n\"\"\nfunction constraint_ne_thermal_limit_to_parallel(pm::_PM.AbstractPowerModel, ne_br_idx::Int; nw::Int=_PM.nw_id_default)\n ne_branch = _PM.ref(pm, nw, :ne_branch, ne_br_idx)\n f_bus = ne_branch[\"f_bus\"]\n t_bus = ne_branch[\"t_bus\"]\n t_idx = (ne_br_idx, t_bus, f_bus)\n if !haskey(ne_branch, \"rate_a\")\n Memento.error(_LOGGER, \"constraint_ne_thermal_limit_to_parallel requires a rate_a value on all ne_branches, calc_thermal_limits! can be used to generate reasonable values\")\n end\n ne_rate_a = ne_branch[\"rate_a\"]\n\n br_idx = branch_idx(pm, nw, f_bus, t_bus)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n rate_a = branch[\"rate_a\"]\n\n constraint_ne_thermal_limit_to_parallel(pm, nw, br_idx, ne_br_idx, t_idx, rate_a, ne_rate_a)\nend\n\n\n\n### Actual constraints ###\n\nfunction constraint_ohms_yt_from_repl(pm::_PM.AbstractDCPModel, n::Int, ne_br_idx, f_bus, t_bus, f_idx, b, vad_min, vad_max)\n p_fr = _PM.var(pm, n, :p, f_idx)\n va_fr = _PM.var(pm, n, :va, f_bus)\n va_to = _PM.var(pm, n, :va, t_bus)\n z = _PM.var(pm, n, :branch_ne, ne_br_idx)\n\n JuMP.@constraint(pm.model, p_fr <= -b*(va_fr - va_to + vad_max*z))\n JuMP.@constraint(pm.model, p_fr >= -b*(va_fr - va_to + vad_min*z))\nend\n\n\"nothing to do, this model is symetric\"\nfunction constraint_ohms_yt_to_repl(pm::_PM.AbstractAPLossLessModels, n::Int, ne_br_idx, f_bus, t_bus, t_idx, b, vad_min, vad_max)\nend\n\nfunction constraint_voltage_angle_difference_repl(pm::_PM.AbstractDCPModel, n::Int, ne_br_idx, f_idx, angmin, angmax, vad_min, vad_max)\n i, f_bus, t_bus = f_idx\n\n va_fr = _PM.var(pm, n, :va, f_bus)\n va_to = _PM.var(pm, n, :va, t_bus)\n z = _PM.var(pm, n, :branch_ne, ne_br_idx)\n\n JuMP.@constraint(pm.model, va_fr - va_to <= angmax*(1-z) + vad_max*z)\n JuMP.@constraint(pm.model, va_fr - va_to >= angmin*(1-z) + vad_min*z)\nend\n\n\"\"\nfunction constraint_thermal_limit_from_repl(pm::_PM.AbstractActivePowerModel, n::Int, ne_br_idx, f_idx, rate_a)\n p_fr = _PM.var(pm, n, :p, f_idx)\n z = _PM.var(pm, n, :branch_ne, ne_br_idx)\n\n JuMP.@constraint(pm.model, p_fr <= rate_a*(1-z))\n JuMP.@constraint(pm.model, p_fr >= -rate_a*(1-z))\nend\n\n\"\"\nfunction constraint_thermal_limit_to_repl(pm::_PM.AbstractActivePowerModel, n::Int, ne_br_idx, t_idx, rate_a)\n p_to = _PM.var(pm, n, :p, t_idx)\n z = _PM.var(pm, n, :branch_ne, ne_br_idx)\n\n JuMP.@constraint(pm.model, p_to <= rate_a*(1-z))\n JuMP.@constraint(pm.model, p_to >= -rate_a*(1-z))\nend\n\n\n#### Actual constraints used in radial networks ####\n\n\"States that at most one of the ne_branches sharing the same bus pair must be built.\"\nfunction constraint_branch_complementarity(pm::_PM.AbstractPowerModel, n::Int, i, f_bus, t_bus)\n JuMP.@constraint(pm.model, sum(_PM.var(pm, n, :branch_ne, l) for l in ne_branch_ids(pm, n, f_bus, t_bus)) <= 1)\nend\n\n\"\"\nfunction constraint_voltage_magnitude_difference_on_off(pm::_PM.AbstractBFAModel, n::Int, i, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, b_sh_fr, tm)\n branch = _PM.ref(pm, n, :branch, i)\n fr_bus = _PM.ref(pm, n, :bus, f_bus)\n to_bus = _PM.ref(pm, n, :bus, t_bus)\n M_hi = fr_bus[\"vmax\"]^2/tm^2 - to_bus[\"vmin\"]^2\n M_lo = -fr_bus[\"vmin\"]^2/tm^2 + to_bus[\"vmax\"]^2\n \n p_fr = _PM.var(pm, n, :p, f_idx)\n q_fr = _PM.var(pm, n, :q, f_idx)\n w_fr = _PM.var(pm, n, :w, f_bus)\n w_to = _PM.var(pm, n, :w, t_bus)\n z = _PM.var(pm, n, :z_branch, i)\n\n JuMP.@constraint(pm.model, (w_fr/tm^2) - w_to <= 2*(r*p_fr + x*q_fr) + M_hi*(1-z) )\n JuMP.@constraint(pm.model, (w_fr/tm^2) - w_to >= 2*(r*p_fr + x*q_fr) - M_lo*(1-z) )\nend\n\n\"\"\nfunction constraint_voltage_magnitude_difference_frb_on_off(pm::_PM.AbstractBFAModel, n::Int, i, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, b_sh_fr, tm)\n branch = _PM.ref(pm, n, :branch, i)\n fr_bus = _PM.ref(pm, n, :bus, f_bus)\n to_bus = _PM.ref(pm, n, :bus, t_bus)\n M_hi = 1.0^2/tm^2 - to_bus[\"vmin\"]^2\n M_lo = -1.0^2/tm^2 + to_bus[\"vmax\"]^2\n \n p_fr = _PM.var(pm, n, :p, f_idx)\n q_fr = _PM.var(pm, n, :q, f_idx)\n w_to = _PM.var(pm, n, :w, t_bus)\n z = _PM.var(pm, n, :z_branch, i)\n # w_fr is assumed equal to 1.0\n\n JuMP.@constraint(pm.model, (1.0/tm^2) - w_to <= 2*(r*p_fr + x*q_fr) + M_hi*(1-z) )\n JuMP.@constraint(pm.model, (1.0/tm^2) - w_to >= 2*(r*p_fr + x*q_fr) - M_lo*(1-z) )\nend\n\n\"\"\nfunction constraint_voltage_magnitude_difference_oltc_on_off(pm::_PM.AbstractBFAModel, n::Int, i, f_bus, t_bus, f_idx, t_idx, r, x, g_sh_fr, b_sh_fr, tm_min, tm_max)\n branch = _PM.ref(pm, n, :branch, i)\n fr_bus = _PM.ref(pm, n, :bus, f_bus)\n to_bus = _PM.ref(pm, n, :bus, t_bus)\n M_hi = 1.0^2/tm_min^2 - to_bus[\"vmin\"]^2\n M_lo = -1.0^2/tm_max^2 + to_bus[\"vmax\"]^2\n \n p_fr = _PM.var(pm, n, :p, f_idx)\n q_fr = _PM.var(pm, n, :q, f_idx)\n ttmi = _PM.var(pm, n, :ttmi, i)\n w_to = _PM.var(pm, n, :w, t_bus)\n z = _PM.var(pm, n, :z_branch, i)\n # w_fr is assumed equal to 1.0 to preserve the linearity of the model\n\n JuMP.@constraint(pm.model, 1.0*ttmi - w_to <= 2*(r*p_fr + x*q_fr) + M_hi*(1-z) )\n JuMP.@constraint(pm.model, 1.0*ttmi - w_to >= 2*(r*p_fr + x*q_fr) - M_lo*(1-z) )\nend\n\n\"\"\nfunction constraint_ne_voltage_magnitude_difference_parallel(pm::_PM.AbstractBFAModel, n::Int, br_idx_e, br_idx_c, f_bus, t_bus, f_idx_c, t_idx_c, r_e, x_e, g_sh_fr_e, b_sh_fr_e, r_c, x_c, g_sh_fr_c, b_sh_fr_c, tm)\n # Suffixes: _e: existing branch; _c: candidate branch; _p: parallel equivalent\n r_p = (r_e*(r_c^2+x_c^2)+r_c*(r_e^2+x_e^2)) / ((r_e+r_c)^2+(x_e+x_c)^2)\n x_p = (x_e*(r_c^2+x_c^2)+x_c*(r_e^2+x_e^2)) / ((r_e+r_c)^2+(x_e+x_c)^2)\n\n constraint_ne_voltage_magnitude_difference(pm::_PM.AbstractBFAModel, n::Int, br_idx_c, f_bus, t_bus, f_idx_c, t_idx_c, r_p, x_p, 0, 0, tm)\nend\n\n\"\"\nfunction constraint_ne_voltage_magnitude_difference_frb_parallel(pm::_PM.AbstractBFAModel, n::Int, br_idx_e, br_idx_c, f_bus, t_bus, f_idx_c, t_idx_c, r_e, x_e, g_sh_fr_e, b_sh_fr_e, r_c, x_c, g_sh_fr_c, b_sh_fr_c, tm)\n # Suffixes: _e: existing branch; _c: candidate branch; _p: parallel equivalent\n r_p = (r_e*(r_c^2+x_c^2)+r_c*(r_e^2+x_e^2)) / ((r_e+r_c)^2+(x_e+x_c)^2)\n x_p = (x_e*(r_c^2+x_c^2)+x_c*(r_e^2+x_e^2)) / ((r_e+r_c)^2+(x_e+x_c)^2)\n\n constraint_ne_voltage_magnitude_difference_frb(pm::_PM.AbstractBFAModel, n::Int, br_idx_c, f_bus, t_bus, f_idx_c, t_idx_c, r_p, x_p, 0, 0, tm)\nend\n\n\n\n## Auxiliary functions ##\n\nfunction replace_branch(pm, nw, f_bus, t_bus)\n replace = 0\n ne_br_idx = 0\n for (br, ne_branch) in _PM.ref(pm, nw, :ne_branch)\n if ((ne_branch[\"f_bus\"] == f_bus && ne_branch[\"t_bus\"] == t_bus) || (ne_branch[\"f_bus\"] == t_bus && ne_branch[\"t_bus\"] == f_bus)) && ne_branch[\"replace\"] == true\n replace = 1\n ne_br_idx = br\n end\n end\n return replace, ne_br_idx\nend\n\n\"Returns the index of `branch` connecting `f_bus` to `t_bus`, if such a `branch` exists; 0 otherwise\"\nfunction branch_idx(pm::_PM.AbstractPowerModel, nw::Int, f_bus, t_bus)\n buspairs = _PM.ref(pm, nw, :buspairs)\n buspair = get(buspairs, (f_bus,t_bus), Dict(\"branch\"=>0))\n return buspair[\"branch\"]\nend\n\n\"Returns a list of indices of `ne_branch`es relative to `branch` `br_idx`\"\nfunction ne_branch_ids(pm::_PM.AbstractPowerModel, br_idx::Int; nw::Int=_PM.nw_id_default)\n branch = _PM.ref(pm, nw, :branch, br_idx)\n f_bus = branch[\"f_bus\"]\n t_bus = branch[\"t_bus\"]\n ne_branch_ids(pm, nw, f_bus, t_bus)\nend\n\n\"Returns a list of indices of `ne_branch`es connecting `f_bus` to `t_bus`\"\nfunction ne_branch_ids(pm::_PM.AbstractPowerModel, nw::Int, f_bus, t_bus)\n ne_buspairs = _PM.ref(pm, nw, :ne_buspairs)\n ne_buspair = get(ne_buspairs, (f_bus,t_bus), Dict(\"branches\"=>Int[]))\n return ne_buspair[\"branches\"]\nend\n\n\"Returns whether a `ne_branch` is intended to replace the existing branch or to be added in parallel\"\nfunction ne_branch_replace(pm::_PM.AbstractPowerModel, ne_br_idx::Int; nw::Int=_PM.nw_id_default)\n ne_branch = _PM.ref(pm, nw, :ne_branch, ne_br_idx)\n if !haskey(ne_branch, \"replace\")\n Memento.error(_LOGGER, \"a `replace` value is required on all `ne_branch`es\")\n end\n return ne_branch[\"replace\"] == 1\nend\n", "meta": {"hexsha": "de60e69790ff59cc8c3c39c24da880916595e4e3", "size": 23875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core/line_replacement.jl", "max_stars_repo_name": "Electa-Git/FlexPlan.jl", "max_stars_repo_head_hexsha": "bedaa248f3abdfeb72882f3ae4015ca0e742550c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-11-18T20:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T16:45:02.000Z", "max_issues_repo_path": "src/core/line_replacement.jl", "max_issues_repo_name": "Electa-Git/FlexPlan.jl", "max_issues_repo_head_hexsha": "bedaa248f3abdfeb72882f3ae4015ca0e742550c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2021-11-18T16:15:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:06:13.000Z", "max_forks_repo_path": "src/core/line_replacement.jl", "max_forks_repo_name": "Electa-Git/FlexPlan.jl", "max_forks_repo_head_hexsha": "bedaa248f3abdfeb72882f3ae4015ca0e742550c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4460547504, "max_line_length": 222, "alphanum_fraction": 0.6697382199, "num_tokens": 7822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24361671903168114}} {"text": "# This file is a part of Julia. License is MIT: https://julialang.org/license\n\n## general machinery for irrational mathematical constants\n\n\"\"\"\n AbstractIrrational <: Real\n\nNumber type representing an exact irrational value.\n\"\"\"\nabstract type AbstractIrrational <: Real end\n\n\"\"\"\n Irrational{sym} <: AbstractIrrational\n\nNumber type representing an exact irrational value denoted by the\nsymbol `sym`.\n\"\"\"\nstruct Irrational{sym} <: AbstractIrrational end\n\nshow(io::IO, x::Irrational{sym}) where {sym} = print(io, sym)\n\nfunction show(io::IO, ::MIME\"text/plain\", x::Irrational{sym}) where {sym}\n if get(io, :compact, false)\n print(io, sym)\n else\n print(io, sym, \" = \", string(float(x))[1:15], \"...\")\n end\nend\n\npromote_rule(::Type{<:AbstractIrrational}, ::Type{Float16}) = Float16\npromote_rule(::Type{<:AbstractIrrational}, ::Type{Float32}) = Float32\npromote_rule(::Type{<:AbstractIrrational}, ::Type{<:AbstractIrrational}) = Float64\npromote_rule(::Type{<:AbstractIrrational}, ::Type{T}) where {T<:Real} = promote_type(Float64, T)\npromote_rule(::Type{S}, ::Type{T}) where {S<:AbstractIrrational,T<:Number} = promote_type(promote_type(S, real(T)), T)\n\nAbstractFloat(x::AbstractIrrational) = Float64(x)\nFloat16(x::AbstractIrrational) = Float16(Float32(x))\nComplex{T}(x::AbstractIrrational) where {T<:Real} = Complex{T}(T(x))\n\n@pure function Rational{T}(x::AbstractIrrational) where T<:Integer\n o = precision(BigFloat)\n p = 256\n while true\n setprecision(BigFloat, p)\n bx = BigFloat(x)\n r = rationalize(T, bx, tol=0)\n if abs(BigFloat(r) - bx) > eps(bx)\n setprecision(BigFloat, o)\n return r\n end\n p += 32\n end\nend\n(::Type{Rational{BigInt}})(x::AbstractIrrational) = throw(ArgumentError(\"Cannot convert an AbstractIrrational to a Rational{BigInt}: use rationalize(Rational{BigInt}, x) instead\"))\n\n@pure function (t::Type{T})(x::AbstractIrrational, r::RoundingMode) where T<:Union{Float32,Float64}\n setprecision(BigFloat, 256) do\n T(BigFloat(x), r)\n end\nend\n\nfloat(::Type{<:AbstractIrrational}) = Float64\n\n==(::Irrational{s}, ::Irrational{s}) where {s} = true\n==(::AbstractIrrational, ::AbstractIrrational) = false\n\n<(::Irrational{s}, ::Irrational{s}) where {s} = false\nfunction <(x::AbstractIrrational, y::AbstractIrrational)\n Float64(x) != Float64(y) || throw(MethodError(<, (x, y)))\n return Float64(x) < Float64(y)\nend\n\n<=(::Irrational{s}, ::Irrational{s}) where {s} = true\n<=(x::AbstractIrrational, y::AbstractIrrational) = x==y || x -Inf &&\n !isempty(constraint_info.range.additional_terms_lb)\n con_lb[ci_name, :].data .= JuMP.AffExpr(0.0)\n continue\n end\n for t in time_steps\n expression_lb = JuMP.AffExpr(0.0, variable[ci_name, t] => 1.0)\n for val in constraint_info.range.additional_terms_lb\n JuMP.add_to_expression!(\n expression_lb,\n get_variable(psi_container, val)[ci_name, t],\n -1.0,\n )\n end\n lb_val = max(0.0, constraint_info.range.limits.min)\n con_lb[ci_name, t] =\n JuMP.@constraint(psi_container.JuMPmodel, expression_lb >= lb_val)\n end\n end\n return\nend\n\n@doc raw\"\"\"\nConstructs upper bound for given variable and time series data and a multiplier.\n\n# Constraint\n\n```variable[name, t] <= constraint_infos[name].multiplier * ts_data[name].timeseries[t] ```\n\n# LaTeX\n\n`` x_t \\leq r^{val} r_t, \\forall t ``\n\"\"\"\nfunction device_timeseries_ub!(\n psi_container::PSIContainer,\n inputs::TimeSeriesConstraintSpecInternal,\n)\n time_steps = model_time_steps(psi_container)\n names = [get_component_name(x) for x in inputs.constraint_infos]\n variable = get_variable(psi_container, inputs.variable_name)\n ub_name = middle_rename(inputs.constraint_name, PSI_NAME_DELIMITER, \"ub\")\n con_ub = add_cons_container!(psi_container, ub_name, names, time_steps)\n lazy_add_lb = false\n\n for constraint_info in inputs.constraint_infos\n ci_name = get_component_name(constraint_info)\n for t in time_steps\n expression_ub = JuMP.AffExpr(0.0, variable[ci_name, t] => 1.0)\n for val in constraint_info.range.additional_terms_ub\n JuMP.add_to_expression!(\n expression_ub,\n get_variable(psi_container, val)[ci_name, t],\n )\n end\n con_ub[ci_name, t] = JuMP.@constraint(\n psi_container.JuMPmodel,\n expression_ub <= constraint_info.multiplier * constraint_info.timeseries[t]\n )\n end\n if constraint_info.range.limits.min > -Inf ||\n !isempty(constraint_info.range.additional_terms_lb)\n lazy_add_lb = true\n end\n end\n\n @debug lazy_add_lb\n lazy_add_lb && lazy_lb!(psi_container, inputs)\n\n return\nend\n\n@doc raw\"\"\"\nConstructs lower bound for given variable subject to time series data and a multiplier.\n\n# Constraint\n\n``` constraint_infos[name].multiplier * ts_data[name].timeseries[t] <= variable[name, t] ```\n\n# LaTeX\n\n`` r^{val} r_t \\leq x_t, \\forall t ``\n\nwhere (name, data) in range_data.\n\"\"\"\nfunction device_timeseries_lb!(\n psi_container::PSIContainer,\n inputs::TimeSeriesConstraintSpecInternal,\n)\n time_steps = model_time_steps(psi_container)\n variable = get_variable(psi_container, inputs.variable_name)\n lb_name = middle_rename(inputs.constraint_name, PSI_NAME_DELIMITER, \"lb\")\n names = [get_component_name(x) for x in inputs.constraint_infos]\n constraint = add_cons_container!(psi_container, lb_name, names, time_steps)\n\n for constraint_info in inputs.constraint_infos\n ci_name = get_component_name(constraint_info)\n for t in time_steps\n expression_lb = JuMP.AffExpr(0.0, variable[ci_name, t] => 1.0)\n for val in constraint_info.range.additional_terms_lb\n JuMP.add_to_expression!(\n expression_lb,\n get_variable(psi_container, val)[ci_name, t],\n -1.0,\n )\n end\n constraint[ci_name, t] = JuMP.@constraint(\n psi_container.JuMPmodel,\n expression_lb >= constraint_info.multiplier * constraint_info.timeseries[t]\n )\n end\n end\n return\nend\n\n@doc raw\"\"\"\nConstructs upper bound for given variable using a parameter. The constraint is\n built with a time series data vector and a multiplier\n\n# Constraint\n\n``` variable[name, t] <= constraint_infos[name].multiplier * param[name, t] ```\n\n# LaTeX\n\n`` x^{var}_t \\leq r^{val} x^{param}_t, \\forall t ``\n\"\"\"\nfunction device_timeseries_param_ub!(\n psi_container::PSIContainer,\n inputs::TimeSeriesConstraintSpecInternal,\n)\n time_steps = model_time_steps(psi_container)\n names = [get_component_name(x) for x in inputs.constraint_infos]\n variable = get_variable(psi_container, inputs.variable_name)\n ub_name = middle_rename(inputs.constraint_name, PSI_NAME_DELIMITER, \"ub\")\n con_ub = add_cons_container!(psi_container, ub_name, names, time_steps)\n container =\n add_param_container!(psi_container, inputs.param_reference, names, time_steps)\n multiplier = get_multiplier_array(container)\n param = get_parameter_array(container)\n lazy_add_lb = false\n\n for constraint_info in inputs.constraint_infos\n ci_name = get_component_name(constraint_info)\n for t in time_steps\n expression_ub = JuMP.AffExpr(0.0, variable[ci_name, t] => 1.0)\n for val in constraint_info.range.additional_terms_ub\n JuMP.add_to_expression!(\n expression_ub,\n get_variable(psi_container, val)[ci_name, t],\n )\n end\n param[ci_name, t] =\n PJ.add_parameter(psi_container.JuMPmodel, constraint_info.timeseries[t])\n con_ub[ci_name, t] = JuMP.@constraint(\n psi_container.JuMPmodel,\n expression_ub <= constraint_info.multiplier * param[ci_name, t]\n )\n multiplier[ci_name, t] = constraint_info.multiplier\n end\n if constraint_info.range.limits.min > -Inf ||\n !isempty(constraint_info.range.additional_terms_lb)\n lazy_add_lb = true\n end\n end\n\n @debug lazy_add_lb\n lazy_add_lb && lazy_lb!(psi_container, inputs)\n return\nend\n\n@doc raw\"\"\"\nConstructs lower bound for given variable using a parameter. The constraint is\n built with a time series data vector and a multiplier\n\n# Constraint\n\n``` constraint_infos[name].multiplier * param[name, t] <= variable[name, t] ```\n\n# LaTeX\n\n`` r^{val} x^{param}_t \\leq x^{var}_t, \\forall t ``\n\"\"\"\nfunction device_timeseries_param_lb!(\n psi_container::PSIContainer,\n inputs::TimeSeriesConstraintSpecInternal,\n)\n time_steps = model_time_steps(psi_container)\n variable = get_variable(psi_container, inputs.variable_name)\n lb_name = middle_rename(inputs.constraint_name, PSI_NAME_DELIMITER, \"lb\")\n names = [get_component_name(x) for x in inputs.constraint_infos]\n constraint = add_cons_container!(psi_container, lb_name, names, time_steps)\n container =\n add_param_container!(psi_container, inputs.param_reference, names, time_steps)\n multiplier = get_multiplier_array(container)\n param = get_parameter_array(container)\n\n for constraint_info in inputs.constraint_infos\n ci_name = get_component_name(constraint_info)\n for t in time_steps\n expression_lb = JuMP.AffExpr(0.0, variable[ci_name, t] => 1.0)\n for val in constraint_info.range.additional_terms_lb\n JuMP.add_to_expression!(\n expression_lb,\n get_variable(psi_container, val)[ci_name, t],\n -1.0,\n )\n end\n param[ci_name, t] =\n PJ.add_parameter(psi_container.JuMPmodel, constraint_info.timeseries[t])\n constraint_info[ci_name, t] = JuMP.@constraint(\n psi_container.JuMPmodel,\n expression_lb >= constraint_info.multiplier * param[ci_name, t]\n )\n multiplier[ci_name, t] = constraint_info.multiplier\n end\n end\n\n return\nend\n\n@doc raw\"\"\"\nConstructs upper bound for variable and time series or confines to 0 depending on binary variable.\n The upper bound is defined by a time series and a multiplier.\n\n# constraint_infos\n\n``` varcts[name, t] <= varbin[name, t]* constraint_infos[name].multiplier * ts_data[name].timeseries[t] ```\n\nwhere (name, data) in range_data.\n\n# LaTeX\n\n`` x^{cts}_t \\leq r^{val} r_t x^{bin}_t, \\forall t ``\n\"\"\"\nfunction device_timeseries_ub_bin!(\n psi_container::PSIContainer,\n inputs::TimeSeriesConstraintSpecInternal,\n)\n time_steps = model_time_steps(psi_container)\n ub_name = middle_rename(inputs.constraint_name, PSI_NAME_DELIMITER, \"ub\")\n varcts = get_variable(psi_container, inputs.variable_name)\n varbin = get_variable(psi_container, inputs.bin_variable_name)\n names = [get_component_name(x) for x in inputs.constraint_infos]\n con_ub = add_cons_container!(psi_container, ub_name, names, time_steps)\n for constraint_info in inputs.constraint_infos\n ci_name = get_component_name(constraint_info)\n for t in time_steps\n forecast = constraint_info.timeseries[t]\n multiplier = constraint_info.multiplier\n expression_ub = JuMP.AffExpr(0.0, varcts[ci_name, t] => 1.0)\n for val in constraint_info.range.additional_terms_ub\n JuMP.add_to_expression!(\n expression_ub,\n get_variable(psi_container, val)[ci_name, t],\n )\n end\n con_ub[ci_name, t] = JuMP.@constraint(\n psi_container.JuMPmodel,\n expression_ub <= varbin[ci_name, t] * multiplier * forecast\n )\n end\n end\n return\nend\n\n@doc raw\"\"\"\nConstructs upper bound for variable and time series and a multiplier or confines to 0 depending on binary variable.\n Uses BigM constraint type to allow for parameter since ParameterJuMP doesn't support var*parameter\n\n# constraint_infos\n\n``` varcts[name, t] - constraint_infos[name].multipliers * param[name, t] <= (1 - varbin[name, t]) * M_value ```\n\n``` varcts[name, t] <= varbin[name, t]*M_value ```\n\n# LaTeX\n\n`` x^{cts}_t - r^{val} x^{param}_t \\leq M(1 - x^{bin}_t ), forall t ``\n\n`` x^{cts}_t \\leq M x^{bin}_t, \\forall t ``\n\"\"\"\nfunction device_timeseries_ub_bigM!(\n psi_container::PSIContainer,\n inputs::TimeSeriesConstraintSpecInternal,\n)\n time_steps = model_time_steps(psi_container)\n ub_name = middle_rename(inputs.constraint_name, PSI_NAME_DELIMITER, \"ub\")\n key_status = middle_rename(inputs.constraint_name, PSI_NAME_DELIMITER, \"status\")\n\n varcts = get_variable(psi_container, inputs.variable_name)\n varbin = get_variable(psi_container, inputs.bin_variable_name)\n names = [get_component_name(x) for x in inputs.constraint_infos]\n con_ub = add_cons_container!(psi_container, ub_name, names, time_steps)\n con_status = add_cons_container!(psi_container, key_status, names, time_steps)\n container =\n add_param_container!(psi_container, inputs.param_reference, names, time_steps)\n multiplier = get_multiplier_array(container)\n param = get_parameter_array(container)\n\n for constraint_info in inputs.constraint_infos\n ci_name = get_component_name(constraint_info)\n for t in time_steps\n expression_ub = JuMP.AffExpr(0.0, varcts[ci_name, t] => 1.0)\n for val in constraint_info.range.additional_terms_ub\n JuMP.add_to_expression!(\n expression_ub,\n get_variable(psi_container, val)[ci_name, t],\n )\n end\n param[ci_name, t] =\n PJ.add_parameter(psi_container.JuMPmodel, constraint_info.timeseries[t])\n con_ub[ci_name, t] = JuMP.@constraint(\n psi_container.JuMPmodel,\n expression_ub - param[ci_name, t] * constraint_info.multiplier <=\n (1 - varbin[ci_name, t]) * M_VALUE\n )\n con_status[ci_name, t] = JuMP.@constraint(\n psi_container.JuMPmodel,\n expression_ub <= varbin[ci_name, t] * M_VALUE\n )\n multiplier[ci_name, t] = constraint_info.multiplier\n end\n end\n return\nend\n", "meta": {"hexsha": "0066c6d4a93f2497540b3e1f27747b8ab78e8f8a", "size": 12831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/devices_models/devices/common/timeseries_constraint.jl", "max_stars_repo_name": "andrewrosemberg/PowerSimulations.jl", "max_stars_repo_head_hexsha": "edcbd0494b84ac1a8c21d986bd10a17ad6c189ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-12T06:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T06:17:19.000Z", "max_issues_repo_path": "src/devices_models/devices/common/timeseries_constraint.jl", "max_issues_repo_name": "superdakun/PowerSimulations.jl", "max_issues_repo_head_hexsha": "9f9cc278455e8db83433b2d3f26ce7f7830561be", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/devices_models/devices/common/timeseries_constraint.jl", "max_forks_repo_name": "superdakun/PowerSimulations.jl", "max_forks_repo_head_hexsha": "9f9cc278455e8db83433b2d3f26ce7f7830561be", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2994186047, "max_line_length": 115, "alphanum_fraction": 0.6637050892, "num_tokens": 2946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.24352583594336813}} {"text": "const MANTISSA_MASK = Base.significand_mask(Float64)\nconst EXP_MASK = Base.exponent_mask(Float64) >> Base.significand_bits(Float64)\n\nmemcpy(d, doff, s, soff, n) = ccall(:memcpy, Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Int), d + doff - 1, s + soff - 1, n)\nmemmove(d, doff, s, soff, n) = ccall(:memmove, Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}, Int), d + doff - 1, s + soff - 1, n)\n\npow5_bitcount(::Type{Float16}) = 30\npow5_bitcount(::Type{Float32}) = 61\npow5_bitcount(::Type{Float64}) = 121\n\npow5_inv_bitcount(::Type{Float16}) = 30\npow5_inv_bitcount(::Type{Float32}) = 59\npow5_inv_bitcount(::Type{Float64}) = 122\n\nqinvbound(::Type{Float16}) = 4\nqinvbound(::Type{Float32}) = 9\nqinvbound(::Type{Float64}) = 21\n\nqbound(::Type{Float16}) = 15\nqbound(::Type{Float32}) = 31\nqbound(::Type{Float64}) = 63\n\n\"\"\"\n Ryu.log10pow2(e::Integer)\n\nComputes `floor(log10(2^e))`. This is valid for all `e < 1651`.\n\"\"\"\nlog10pow2(e) = (e * 78913) >> 18\n\n\n\"\"\"\n Ryu.log10pow5(e::Integer)\n\nComputes `floor(log10(5^e))`. This is valid for all `e < 2621`.\n\"\"\"\nlog10pow5(e) = (e * 732923) >> 20\n\n\"\"\"\n Ryu.pow5bits(e)\n\nComputes `e == 0 ? 1 : ceil(log2(5^e))`. This is valid for `e < 3529` (if performend in `Int32` arithmetic).\n\"\"\"\npow5bits(e) = ((e * 1217359) >> 19) + 1\n\n\"\"\"\"\n Ryu.mulshift(m::U, mula, j) where {U<:Unsigned}\n\nCompute `(m * mul) >> j`, where `j >= 8*sizeof(U)`. The type of the results is the larger of `U` or `UInt32`.\n\"\"\"\n@inline function mulshift(m::U, mul, j) where {U<:Unsigned}\n W = widen(U)\n nbits = 8*sizeof(U)\n return ((((W(m) * (mul % U)) >> nbits) + W(m) * (mul >> nbits)) >> (j - nbits)) % promote_type(U,UInt32)\nend\n\nindexforexp(e) = div(e + 15, 16)\npow10bitsforindex(idx) = 16 * idx + 120\nlengthforindex(idx) = div(((Int64(16 * idx) * 1292913986) >> 32) + 1 + 16 + 8, 9)\n\n\"\"\"\n Ryu.pow5(x, p)\n\nReturn `true` if `5^p` is a divisor of `x`.\n\"\"\"\n@inline function pow5(x, p)\n count = 0\n while true\n q = div(x, 5)\n r = x - 5 * q\n r != 0 && return count >= p\n x = q\n count += 1\n end\nend\n\n\"\"\"\n Ryu.pow2(x, p)\n\nReturn `true` if `2^p` is a divisor of `x`. In other words, if the trailing `p` bits of `x` are zero.\n\"\"\"\npow2(x, p) = (x & ((Int64(1) << p) - 1)) == 0\n\n\"\"\"\n Ryu.decimallength(v)\n\nThe number of decimal digits of the integer `v`.\n\"\"\"\n@inline function decimallength(v)\n v >= 10000000000000000 && return 17\n v >= 1000000000000000 && return 16\n v >= 100000000000000 && return 15\n v >= 10000000000000 && return 14\n v >= 1000000000000 && return 13\n v >= 100000000000 && return 12\n v >= 10000000000 && return 11\n v >= 1000000000 && return 10\n v >= 100000000 && return 9\n v >= 10000000 && return 8\n v >= 1000000 && return 7\n v >= 100000 && return 6\n v >= 10000 && return 5\n v >= 1000 && return 4\n v >= 100 && return 3\n v >= 10 && return 2\n return 1\nend\n@inline function decimallength(v::UInt32)\n v >= 100000000 && return 9\n v >= 10000000 && return 8\n v >= 1000000 && return 7\n v >= 100000 && return 6\n v >= 10000 && return 5\n v >= 1000 && return 4\n v >= 100 && return 3\n v >= 10 && return 2\n return 1\nend\n@inline function decimallength(v::UInt16)\n v >= 10000 && return 5\n v >= 1000 && return 4\n v >= 100 && return 3\n v >= 10 && return 2\n return 1\nend\n\n@inline function mulshiftinvsplit(::Type{Float64}, mv, mp, mm, i, j)\n @inbounds mul = DOUBLE_POW5_INV_SPLIT[i + 1]\n vr = mulshift(mv, mul, j)\n vp = mulshift(mp, mul, j)\n vm = mulshift(mm, mul, j)\n return vr, vp, vm\nend\n\n@inline function mulshiftinvsplit(::Type{Float32}, mv, mp, mm, i, j)\n @inbounds mul = FLOAT_POW5_INV_SPLIT[i + 1]\n vr = mulshift(mv, mul, j)\n vp = mulshift(mp, mul, j)\n vm = mulshift(mm, mul, j)\n return vr, vp, vm\nend\n\n@inline function mulshiftinvsplit(::Type{Float16}, mv, mp, mm, i, j)\n @inbounds mul = HALF_POW5_INV_SPLIT[i + 1]\n vr = mulshift(mv, mul, j)\n vp = mulshift(mp, mul, j)\n vm = mulshift(mm, mul, j)\n return vr, vp, vm\nend\n\n@inline function mulshiftsplit(::Type{Float64}, mv, mp, mm, i, j)\n @inbounds mul = DOUBLE_POW5_SPLIT[i + 1]\n vr = mulshift(mv, mul, j)\n vp = mulshift(mp, mul, j)\n vm = mulshift(mm, mul, j)\n return vr, vp, vm\nend\n\n@inline function mulshiftsplit(::Type{Float32}, mv, mp, mm, i, j)\n @inbounds mul = FLOAT_POW5_SPLIT[i + 1]\n vr = mulshift(mv, mul, j)\n vp = mulshift(mp, mul, j)\n vm = mulshift(mm, mul, j)\n return vr, vp, vm\nend\n\n@inline function mulshiftsplit(::Type{Float16}, mv, mp, mm, i, j)\n @inbounds mul = HALF_POW5_SPLIT[i + 1]\n vr = mulshift(mv, mul, j)\n vp = mulshift(mp, mul, j)\n vm = mulshift(mm, mul, j)\n return vr, vp, vm\nend\n\n\"\"\"\n Ryu.umul256(a::UInt128, bHi::UInt64, bLo::UInt64)::Tuple{UInt128, UInt128}\n\nCompute `p = a*b` where `b = bLo + bHi<<64`, returning the result as `pLo, pHi` where `p = pLo + pHi<<128`.\n\"\"\"\n@inline function umul256(a, bHi, bLo)\n aLo = a % UInt64\n aHi = (a >> 64) % UInt64\n\n b00 = UInt128(aLo) * bLo\n b01 = UInt128(aLo) * bHi\n b10 = UInt128(aHi) * bLo\n b11 = UInt128(aHi) * bHi\n\n b00Lo = b00 % UInt64\n b00Hi = (b00 >> 64) % UInt64\n\n mid1 = b10 + b00Hi\n mid1Lo = mid1 % UInt64\n mid1Hi = (mid1 >> 64) % UInt64\n\n mid2 = b01 + mid1Lo\n mid2Lo = mid2 % UInt64\n mid2Hi = (mid2 >> 64) % UInt64\n\n pHi = b11 + mid1Hi + mid2Hi\n pLo = (UInt128(mid2Lo) << 64) | b00Lo\n return pLo, pHi\nend\n\n\"\"\"\n Ryu.umul256_hi(a::UInt128, bHi::UInt64, bLo::UInt64)::UInt128\n\nCompute `pHi = (a*b)>>128` where `b = bLo + bHi<<64`.\n\"\"\"\n@inline umul256_hi(a, bHi, bLo) = umul256(a, bHi, bLo)[2]\n\n\"\"\"\n Ryu.mulshiftmod1e9(m, mula, mulb, mulc, j)::UInt32\n\nCompute `(m * mul) >> j % 10^9` where `mul = mula + mulb<<64 + mulc<<128`, and `j >= 128`.\n\"\"\"\n@inline function mulshiftmod1e9(m, mula, mulb, mulc, j)\n b0 = UInt128(m) * mula\n b1 = UInt128(m) * mulb\n b2 = UInt128(m) * mulc\n mid = b1 + ((b0 >> 64) % UInt64)\n s1 = b2 + ((mid >> 64) % UInt64)\n v = s1 >> (j - 128)\n multiplied = umul256_hi(v, 0x89705F4136B4A597, 0x31680A88F8953031)\n shifted = (multiplied >> 29) % UInt32\n return (v % UInt32) - UInt32(1000000000) * shifted\nend\n\n@inline function append_n_digits(olength, digits, buf, pos)\n i = 0\n while digits >= 10000\n c = digits % 10000\n digits = div(digits, 10000)\n c0 = (c % 100) << 1\n c1 = div(c, 100) << 1\n unsafe_copyto!(buf, pos + olength - i - 2, DIGIT_TABLE, c0 + 1, 2)\n unsafe_copyto!(buf, pos + olength - i - 4, DIGIT_TABLE, c1 + 1, 2)\n i += 4\n end\n if digits >= 100\n c = (digits % 100) << 1\n digits = div(digits, 100)\n unsafe_copyto!(buf, pos + olength - i - 2, DIGIT_TABLE, c + 1, 2)\n i += 2\n end\n if digits >= 10\n c = digits << 1\n unsafe_copyto!(buf, pos + olength - i - 2, DIGIT_TABLE, c + 1, 2)\n i += 2\n else\n buf[pos] = UInt8('0') + digits\n i += 1\n end\n return pos + i\nend\n\n@inline function append_d_digits(olength, digits, buf, pos, decchar)\n i = 0\n while digits >= 10000\n c = digits % 10000\n digits = div(digits, 10000)\n c0 = (c % 100) << 1\n c1 = div(c, 100) << 1\n unsafe_copyto!(buf, pos + olength + 1 - i - 2, DIGIT_TABLE, c0 + 1, 2)\n unsafe_copyto!(buf, pos + olength + 1 - i - 4, DIGIT_TABLE, c1 + 1, 2)\n i += 4\n end\n if digits >= 100\n c = (digits % 100) << 1\n digits = div(digits, 100)\n unsafe_copyto!(buf, pos + olength + 1 - i - 2, DIGIT_TABLE, c + 1, 2)\n i += 2\n end\n if digits >= 10\n c = digits << 1\n buf[pos] = DIGIT_TABLE[c + 1]\n buf[pos + 1] = decchar\n buf[pos + 2] = DIGIT_TABLE[c + 2]\n i += 3\n else\n buf[pos] = UInt8('0') + digits\n buf[pos + 1] = decchar\n i += 2\n end\n return pos + i\nend\n\n@inline function append_c_digits(count, digits, buf, pos)\n i = 0\n while i < count - 1\n c = (digits % 100) << 1\n digits = div(digits, 100)\n unsafe_copyto!(buf, pos + count - i - 2, DIGIT_TABLE, c + 1, 2)\n i += 2\n end\n if i < count\n buf[pos + count - i - 1] = UInt8('0') + (digits % 10)\n i += 1\n end\n return pos + i\nend\n\n@inline function append_nine_digits(digits, buf, pos)\n if digits == 0\n for _ = 1:9\n buf[pos] = UInt8('0')\n pos += 1\n end\n return pos\n end\n i = 0\n while i < 5\n c = digits % 10000\n digits = div(digits, 10000)\n c0 = (c % 100) << 1\n c1 = div(c, 100) << 1\n unsafe_copyto!(buf, pos + 7 - i, DIGIT_TABLE, c0 + 1, 2)\n unsafe_copyto!(buf, pos + 5 - i, DIGIT_TABLE, c1 + 1, 2)\n i += 4\n end\n buf[pos] = UInt8('0') + digits\n i += 1\n return pos + i\nend\n\nconst BIG_MASK = (big(1) << 64) - 1\n\nconst POW10_SPLIT = collect(Iterators.flatten(map(0:63) do idx\n pow10bits = pow10bitsforindex(idx)\n map(0:lengthforindex(idx)-1) do i\n v = (div(big(1) << pow10bits, big(10)^(9 * i)) + 1) % ((big(10)^9) << 136)\n return (UInt64(v & BIG_MASK), UInt64((v >> 64) & BIG_MASK), UInt64((v >> 128) & BIG_MASK))\n end\nend))\n\nfunction generateinversetables()\n POW10_OFFSET_2 = Vector{UInt16}(undef, 68 + 1)\n MIN_BLOCK_2 = fill(0xff, 68 + 1)\n POW10_SPLIT_2 = Tuple{UInt64, UInt64, UInt64}[]\n lowerCutoff = big(1) << (54 + 8)\n for idx = 0:67\n POW10_OFFSET_2[idx + 1] = length(POW10_SPLIT_2)\n i = 0\n while true\n v = ((big(10)^(9 * (i + 1)) >> (-(120 - 16 * idx))) % (big(10)^9) << (120 + 16))\n if MIN_BLOCK_2[idx + 1] == 0xff && ((v * lowerCutoff) >> 128) == 0\n i += 1\n continue\n end\n if MIN_BLOCK_2[idx + 1] == 0xff\n MIN_BLOCK_2[idx + 1] = i\n end\n v == 0 && break\n push!(POW10_SPLIT_2, ((v & BIG_MASK) % UInt64, ((v >> 64) & BIG_MASK) % UInt64, ((v >> 128) & BIG_MASK) % UInt64))\n i += 1\n end\n end\n POW10_OFFSET_2[end] = length(POW10_SPLIT_2)\n MIN_BLOCK_2[end] = 0x00\n\n return POW10_OFFSET_2, MIN_BLOCK_2, POW10_SPLIT_2\nend\n\nconst POW10_OFFSET_2, MIN_BLOCK_2, POW10_SPLIT_2 = generateinversetables()\n\n\"\"\"\n Ryu.pow5invsplit(T, i)\n\nCompute `floor(2^k/5^i)+1`, where `k = pow5bits(i) - 1 + pow5_inv_bitcount(T)`. The result\nis an unsigned integer twice as wide as `T` (i.e. a `UInt128` if `T == Float64`), with\n`pow5_inv_bitcount(T)` significant bits.\n\"\"\"\nfunction pow5invsplit(::Type{T}, i) where {T<:AbstractFloat}\n W = widen(uinttype(T))\n pow = big(5)^i\n inv = div(big(1) << (ndigits(pow, base=2) - 1 + pow5_inv_bitcount(T)), pow) + 1\n return W(inv)\nend\n\n\"\"\"\n Ryu.pow5split(T, i)\n\nCompute `floor(5^i/2^k)`, where `k = pow5bits(i) - pow5_bitcount(T)`. The result is an\nunsigned integer twice as wide as `T` (i.e. a `UInt128` if `T == Float64`), with\n`pow5_bitcount(T)` significant bits.\n\"\"\"\nfunction pow5split(::Type{T}, i) where {T<:AbstractFloat}\n W = widen(uinttype(T))\n pow = big(5)^i\n return W(pow >> (ndigits(pow, base=2) - pow5_bitcount(T)))\nend\n\nconst DOUBLE_POW5_INV_SPLIT = map(i->pow5invsplit(Float64, i), 0:291)\nconst FLOAT_POW5_INV_SPLIT = map(i->pow5invsplit(Float32, i), 0:30)\nconst HALF_POW5_INV_SPLIT = map(i->pow5invsplit(Float16, i), 0:17)\n\nconst DOUBLE_POW5_SPLIT = map(i->pow5split(Float64, i), 0:325)\nconst FLOAT_POW5_SPLIT = map(i->pow5split(Float32, i), 0:46)\nconst HALF_POW5_SPLIT = map(i->pow5split(Float16, i), 0:23)\n\nconst DIGIT_TABLE = UInt8[\n '0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9',\n '1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9',\n '2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9',\n '3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9',\n '4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9',\n '5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9',\n '6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9',\n '7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9',\n '8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9',\n '9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9'\n]\n\nconst POW10_OFFSET = UInt16[\n 0, 2, 5, 8, 12, 16, 21, 26, 32, 39,\n 46, 54, 62, 71, 80, 90, 100, 111, 122, 134,\n 146, 159, 173, 187, 202, 217, 233, 249, 266, 283,\n 301, 319, 338, 357, 377, 397, 418, 440, 462, 485,\n 508, 532, 556, 581, 606, 632, 658, 685, 712, 740,\n 769, 798, 828, 858, 889, 920, 952, 984, 1017, 1050,\n 1084, 1118, 1153, 1188\n]\n", "meta": {"hexsha": "c0bab2cb57f657c09a0b0d2c29c1f18da81f9767", "size": 12707, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "base/ryu/utils.jl", "max_stars_repo_name": "taqtiqa-mark/julia", "max_stars_repo_head_hexsha": "eebf56327306f4e34e4482d9b083b9504ecbcd02", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-24T03:31:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-24T03:31:36.000Z", "max_issues_repo_path": "base/ryu/utils.jl", "max_issues_repo_name": "taqtiqa-mark/julia", "max_issues_repo_head_hexsha": "eebf56327306f4e34e4482d9b083b9504ecbcd02", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base/ryu/utils.jl", "max_forks_repo_name": "taqtiqa-mark/julia", "max_forks_repo_head_hexsha": "eebf56327306f4e34e4482d9b083b9504ecbcd02", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1113744076, "max_line_length": 126, "alphanum_fraction": 0.5471000236, "num_tokens": 4974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2434713721650456}} {"text": "## Functions to handle input files.\n\nusing Chemfiles\n\ninclude(\"clustering.jl\")\n\n\n\"\"\"\n parse_cif(file_path)\n\nParse a CIF file and return a dictionary where each identifier (without the\nstarting '_' character) is linked to its value.\nValues are either a string or a vector of string (if defined in a loop).\n\"\"\"\nfunction parse_cif(file)\n all_data = Dict{String, Union{String, Vector{String}}}()\n inloop = false\n loopisspecified = false\n loopspec = String[]\n loop_n = 0\n\n l = read(file, String)\n i, j, x = nextword(l, 0)\n while i != 0\n\n if inloop\n if !loopisspecified\n if l[i] != '_' # This indicates the start of the values\n loop_n = length(loopspec)\n loopisspecified = true\n else # The identifier is part of the loop specification\n push!(loopspec, l[i+1:j])\n all_data[l[i+1:j]] = String[]\n i, j, x = nextword(l, x); continue\n end\n end\n\n # From this point, the loop has been specified\n @assert loopisspecified\n if l[i] != '_' && l[i:j] != \"loop_\"\n for k in 1:loop_n\n push!(all_data[loopspec[k]], l[i:j])\n i, j, x = nextword(l, x)\n end\n continue\n end\n if l[i:j] == \"loop_\"\n loopisspecified = false\n loopspec = String[]\n i, j, x = nextword(l, x); continue\n end\n\n # This point can only be reached if we just quitted a loop\n inloop = false\n end\n\n @assert !inloop\n if l[i] == '_' # Simple identifier definition\n next_i, next_j, next_x = nextword(l, x)\n @assert next_i != 0\n all_data[l[i+1:j]] = l[next_i:next_j]\n x = next_x\n else\n if l[i:j] == \"loop_\"\n inloop = true\n loopisspecified = false\n loopspec = String[]\n elseif j-i > 4 && l[i:i+4] == \"data_\"\n @assert !haskey(all_data, \"data\")\n all_data[\"data\"] = l[i+5:j]\n else\n k::Int = findprev(isequal('\\n'), l, i)\n n::Int = count(\"\\n\", l[1:k])\n error(\"Unkown word \\\"$(l[i:j])\\\" at line $(n+1), position $(i-k):$(j-k)\")\n end\n end\n\n i, j, x = nextword(l, x)\n end\n\n return all_data\nend\n\nfunction parsestrip(s)\n s = s[end] == ')' ? s[1:prevind(s, findlast('(', s))] : s\n return parse(BigFloat, s)\nend\n\n\n\"\"\"\n CIF(file_path::AbstractString)\n\nMake a CIF object out of the parsed file.\n\"\"\"\nCIF(file::AbstractString) = CIF(parse_cif(file))\nfunction CIF(parsed::Dict{String, Union{Vector{String},String}})\n natoms = length(parsed[\"atom_site_label\"])\n equivalentpositions = pop!(parsed,\n haskey(parsed, \"symmetry_equiv_pos_as_xyz\") ?\n \"symmetry_equiv_pos_as_xyz\" : \"space_group_symop_operation_xyz\")\n refid = find_refid(equivalentpositions)\n cell = Cell(Symbol(haskey(parsed, \"symmetry_cell_setting\") ?\n pop!(parsed, \"symmetry_cell_setting\") : \"\"),\n pop!(parsed, \"symmetry_space_group_name_H-M\"),\n haskey(parsed, \"symmetry_Int_Tables_number\") ?\n parse(Int, pop!(parsed, \"symmetry_Int_Tables_number\")) : 0,\n parsestrip(pop!(parsed, \"cell_length_a\")),\n parsestrip(pop!(parsed, \"cell_length_b\")),\n parsestrip(pop!(parsed, \"cell_length_c\")),\n parsestrip(pop!(parsed, \"cell_angle_alpha\")),\n parsestrip(pop!(parsed, \"cell_angle_beta\")),\n parsestrip(pop!(parsed, \"cell_angle_gamma\")),\n parse.(EquivalentPosition, equivalentpositions, Ref(refid)))\n\n haskey(parsed, \"symmetry_equiv_pos_site_id\") && pop!(parsed, \"symmetry_equiv_pos_site_id\")\n removed_identity = false\n for i in eachindex(cell.equivalents)\n eq = cell.equivalents[i]\n if isone(eq.mat) && iszero(eq.ofs)\n deleteat!(cell.equivalents, i)\n removed_identity = true\n break\n end\n end\n @assert removed_identity\n\n labels = pop!(parsed, \"atom_site_label\")\n _symbols = haskey(parsed, \"atom_site_type_symbol\") ?\n pop!(parsed, \"atom_site_type_symbol\") : copy(labels)\n symbols = String[]\n @inbounds for x in _symbols\n i = findfirst(!isletter, x)\n push!(symbols, isnothing(i) ? x : x[1:i-1])\n end\n pos_x = pop!(parsed, \"atom_site_fract_x\")\n pos_y = pop!(parsed, \"atom_site_fract_y\")\n pos_z = pop!(parsed, \"atom_site_fract_z\")\n\n\n types = Symbol[]\n pos = Matrix{Float64}(undef, 3, natoms)\n correspondence = Dict{String, Int}()\n for i in 1:natoms\n @assert !haskey(correspondence, labels[i])\n correspondence[labels[i]] = i\n push!(types, Symbol(symbols[i]))\n pos[:,i] = parsestrip.([pos_x[i], pos_y[i], pos_z[i]])\n pos[:,i] .-= floor.(Int, pos[:,i])\n end\n\n invids = sortperm(types)\n types = types[invids]\n ids = invperm(invids)\n bonds = falses(natoms, natoms)\n if haskey(parsed, \"geom_bond_atom_site_label_1\") &&\n haskey(parsed, \"geom_bond_atom_site_label_2\")\n bond_a = pop!(parsed, \"geom_bond_atom_site_label_1\")\n bond_b = pop!(parsed, \"geom_bond_atom_site_label_2\")\n for i in 1:length(bond_a)\n x = correspondence[bond_a[i]]\n y = correspondence[bond_b[i]]\n bonds[x,y] = bonds[y,x] = 1\n end\n end\n\n return CIF(parsed, cell, ids, types, pos, bonds)\nend\n\n\n\n\"\"\"\n parse_arc(file)\n\nParse a .arc Systre archive such as the one used by the RCSR.\nReturn a pair `(flag, pairs)`.\n\n`flag` is set if the archive corresponds to one generated by a compatible release\nof CrystalNets. If unset, the genomes of the archive may not be the same as those\ncomputed by CrystalNets for the same nets.\n`pairs` is a `Dict{String,String}` whose entries have the form `genome => id` where `id`\nis the name of the net and `genome` is the topological genome corresponding to this net\n(given as a string of whitespace-separated values parseable by `PeriodicGraph`).\n\"\"\"\nfunction parse_arc(file)\n pairs = Dict{String,String}()\n curr_key = \"\"\n counter = 1\n firstline = readline(file)\n flag = startswith(firstline, \"Made by CrystalNets.jl v\")\n if flag\n flag = CRYSTAL_NETS_VERSION == VersionNumber(firstline[25:end])\n end\n for l in eachline(file)\n if length(l) > 3 && l[1:3] == \"key\"\n @assert isempty(curr_key)\n i = 4\n while isspace(l[i])\n i += 1\n end\n curr_key = l[i:end]\n @assert !haskey(pairs, curr_key)\n elseif length(l) > 2 && l[1:2] == \"id\"\n @assert !isempty(curr_key)\n i = 3\n while isspace(l[i])\n i += 1\n end\n pairs[curr_key] = l[i:end]\n curr_key = \"\"\n end\n end\n return flag, pairs\nend\n\n\"\"\"\n parse_arcs(file)\n\nParse a folder containing .arc Systre archives such as the one used by the RCSR.\nReturn a pair `(flag, pairs)` with the same convention than `parse_arc`\n\"\"\"\nfunction parse_arcs(path)\n combine(x, y) = x * \", \" * y\n dict = Dict{String,String}()\n flag = true\n for f in readdir(path; sort=true)\n _flag, _dict = parse_arc(path*f)\n flag &= _flag\n mergewith!(combine, dict, _dict)\n end\n return flag, dict\nend\n\nfunction parse_atom_name(name::AbstractString)\n firstsep = findfirst(x -> ispunct(x) || isspace(x) || isnumeric(x), name)\n if firstsep isa Nothing\n return String(name)\n else\n firstsep::Int\n if firstsep != 1 && !any(isuppercase, @view name[nextind(name, firstsep):end])\n return String(name[1:prevind(firstsep)])\n else\n return String(name)\n end\n end\nend\n\nfunction parse_atom(name)\n atom = Chemfiles.Atom(name)\n set_type!(atom, parse_atom_name(name))\n return atom\nend\n\n\nfunction set_unique_bond_type!(frame::Frame, types, bond_length, bonded_atoms::Tuple{Symbol, Symbol}, onlykeep, tol)\n @ifwarn @info \"To avoid guessing bonds, use a file format that contains the bonds.\"\n n = Int(size(frame))\n pos = Chemfiles.positions(frame)\n mat = Chemfiles.matrix(UnitCell(frame))'\n indices = [i for i in 1:n if types[i] ∈ onlykeep]\n #=@inbounds=# for _i in 1:length(indices)\n i = indices[_i]\n for _j in _i+1:length(indices)\n j = indices[_j]\n if minmax(types[i], types[j]) == bonded_atoms\n bonded = abs2(periodic_distance(pos[:,i], pos[:,j], mat) - bond_length) <= tol\n if bonded\n Chemfiles.add_bond!(frame, i-1, j-1)\n end\n end\n end\n end\n nothing\nend\n\nfunction try_guess_bonds!(frame::Frame)\n # n = Int(size(frame))\n # types = Vector{Symbol}(undef, n)\n # for i in 1:n\n # types[i] = Symbol(parse_atom_name(Chemfiles.type(Chemfiles.Atom(frame, i-1))))\n # end\n # unique_types = unique!(sort(types))\n # if unique_types == [:C] || unique_types == [:C, :H]\n # if !(NOWARN::Bool)\n # @warn \"Guessing bonds. The structure seems to be made of only carbons (and possibly hydrogens): using an interatomic distance of 1.54±0.3 Å to assign edges between C atoms.\"\n # end\n # set_unique_bond_type!(frame, types, 1.54, (:C, :C), (:C,), 0.3)\n # elseif unique_types == [:O, :Si] || unique_types == [:Si]\n # if !(NOWARN::Bool)\n # @warn \"Guessing bonds. The structure seems to be a zeolite: using an interatomic distance of 3.1±0.2 Å to assign edges between Si atoms.\"\n # end\n # set_unique_bond_type!(frame, types, 1.63, (:O, :Si), (:O, :Si), 0.1)\n # else\n @ifwarn begin\n @warn \"Guessing bonds through Chemfiles. This may take a while for big structures and may be inexact.\"\n @info \"To avoid guessing bonds, use a file format that contains the bonds.\"\n end\n guess_bonds!(frame)\n # end\nend\n\n\nfunction attribute_residues(topology, assert_use_existing_residues)\n m = Int(count_residues(topology))\n n = Int(size(topology))\n atoms_in_residues = m == 0 ? 0 : sum(length(atoms(Residue(topology, i))) for i in 0:(m-1))\n @assert atoms_in_residues <= n\n\n if atoms_in_residues < n\n if assert_use_existing_residues\n throw(ArgumentError(\"\"\"\n Cannot use existing residues as vertices because not all atoms have an associated residue.\n To fix this, either assign a residue to each atom or provide another way to detect the vertices.\n \"\"\"))\n end\n @ifwarn begin\n if atoms_in_residues > 0\n @warn \"Some but not all atoms have an associated residue, so we cannot rely on existing residues\"\n end\n end\n attributions = Int[]\n else\n attributions = zeros(Int, n)\n for i_residue in 1:m\n for atom in atoms(Residue(topology, i_residue-1))\n attributions[atom+1] = i_residue\n end\n end\n end\n return attributions\nend\n\n@static if !isdefined(Chemfiles, :atoms) # up to 0.9.3 included\n function atoms(residue::Residue)\n count = size(residue)\n result = Array{UInt64}(undef, count)\n Chemfiles.__check(Chemfiles.lib.chfl_residue_atoms(Chemfiles.__const_ptr(residue), pointer(result), count))\n return result\n end\nend\n\n\nfunction check_collision(pos, mat)\n _n, n = size(pos)\n @assert _n == 3\n invmat = inv(mat)\n toremove = Int[]\n for i in 1:n, j in (i+1):n\n if periodic_distance(invmat*pos[:,i], invmat*pos[:,j], mat) < 0.55\n push!(toremove, i)\n push!(toremove, j)\n end\n end\n tokeep = collect(1:n)\n if !isempty(toremove)\n @ifwarn @warn \"This file contains multiple colliding atoms. All colliding atoms will be removed.\"\n unique!(sort!(toremove))\n end\n return toremove\nend\n\n\nhasHneighbor(types, graph, i) = any(x -> types[x.v] === :H, neighbors(graph,i))\nfunction check_valence(types, graph)\n n = length(types)\n\n ## Small atoms valence check\n invalidatoms = Set{Symbol}()\n for i in 1:n\n d = degree(graph, i)\n t = types[i]\n if t === :O && d > 2 && (d > 3 || !hasHneighbor(types, graph, i))\n push!(invalidatoms, :O)\n elseif t === :C && d > 4\n push!(invalidatoms, :C)\n elseif t === :N && d > 3 && (d > 4 || !hasHneighbor(types, graph, i))\n push!(invalidatoms, :N)\n end\n end\n if !isempty(invalidatoms)\n s = String.(collect(invalidatoms))\n @ifwarn @warn \"Found $(join(s, ',', \" and \")) with too many bonds.\"\n return true\n end\n return false\nend\n\n\n\"\"\"\n @enum BondingMode\n\nSelection mode for the detection of bonds. The choices are:\n- `InputBonds`: use the input bonds. Fail if those are not specified.\n- `ChemfilesBonds`: use chemfiles built-in bond detection mechanism.\n- `AutoBonds`: if the input specifies bonds, use them unless they look suspicious (too or too\n large according to a heuristic). Otherwise, fall back to `ChemfilesBonds`.\n\"\"\"\n@enum BondingMode begin\n InputBonds\n ChemfilesBonds\n AutoBonds\nend\n\n\nfunction sanity_checks!(pos, types, graph, mat, bondingmode)\n ## Bond length check\n removeedges = PeriodicEdge3D[]\n for e in edges(graph)\n s, d = e.src, e.dst.v\n bondlength = norm(pos[:,d] .+ (mat * e.dst.ofs) .- pos[:,s])\n if bondlength > 3\n @ifwarn @warn \"Suspiciously large bond found.\"\n return true\n elseif bondlength < 0.85 && types[s] !== :H && types[d] !== :H\n push!(removeedges, e)\n end\n end\n if bondingmode == AutoBonds\n @ifwarn begin\n if !isempty(removeedges)\n @warn \"Suspiciously small bond found. Such bonds are probably spurious and will be deleted.\"\n @info \"To force retaining these bonds, use --bond-detect=input or --bond-detect=chemfiles\"\n end\n end\n for e in removeedges\n rem_edge!(graph, e)\n end\n end\n return false\nend\n\n\n\"\"\"\n parse_chemfiles(path)\n\nParse a file given in any reckognised chemical format and extract the topological\ninformation.\nSuch format can be .cif or any file format reckognised by Chemfiles.jl that\ncontains all the necessary topological information.\n\"\"\"\nfunction parse_chemfile(_path, exportto=tempdir(), bondingmode::BondingMode=AutoBonds, assert_use_existing_residues=false ; ignore_atoms=[])\n # Separate the cases unhandled by Chemfiles from the others\n path = expanduser(_path)\n cell = Cell()\n frame::Frame = if lowercase(last(splitext(path))) == \".cif\"\n framecif = Frame()\n cif = expand_symmetry(CIF(path))\n a, b, c, α, β, γ = cell_parameters(cif.cell)\n set_cell!(framecif, UnitCell(a, b, c, α, β, γ))\n n = length(cif.ids)\n ignored = 0\n for i in 1:n\n typ = cif.types[cif.ids[i]]\n if typ ∈ ignore_atoms\n ignored += 1\n continue\n end\n pos = cif.cell.mat * cif.pos[:,i]\n atom = parse_atom(string(typ))\n add_atom!(framecif, atom, Vector{Float64}(pos))\n end\n n -= ignored\n if iszero(cif.bonds)\n try_guess_bonds!(framecif)\n else\n for i in 1:n, j in (i+1):n\n if cif.bonds[i,j]\n add_bond!(framecif, i-1, j-1)\n end\n end\n end\n attributions = Int[]\n\n framecif\n else # The rest is handled by Chemfiles\n\n frameelse = read(Trajectory(path))\n for i in Int(size(frameelse))-1:-1:0\n if Symbol(type(Chemfiles.Atom(frameelse, i))) ∈ ignore_atoms\n Chemfiles.remove_atom!(frameelse, i)\n end\n end\n\n toremove = reverse(check_collision(positions(frameelse), matrix(UnitCell(frame))))\n for j in toremove\n Chemfiles.remove_atom!(frameelse, j-1)\n end\n\n topology = Topology(frameelse)\n n = Int(size(topology))\n\n if bonds_count(topology) == 0\n try_guess_bonds!(frameelse)\n topology = Topology(frameelse) # safer but useless since the underlying pointer is the same\n end\n\n attributions = attribute_residues(topology, assert_use_existing_residues)\n\n frameelse\n end\n\n cell = Cell(Cell(), SMatrix{3,3,BigFloat}(matrix(UnitCell(frame)))')\n if !all(isfinite, cell.mat) || iszero(det(cell.mat))\n @ifwarn @warn \"Suspicious unit cell of matrix $(Float64.(cell.mat)). Is the input really periodic? Using a cubic unit cell instead\"\n cell = Cell()\n end\n\n types = [Symbol(type(Chemfiles.Atom(frame, i))) for i in 0:(n-1)]\n poss = copy(positions(frame))\n\n adjacency = zeros(Bool, n, n)\n for (a,b) in eachcol(bonds(Topology(frame)))\n adjacency[a+1,b+1] = true\n adjacency[b+1,a+1] = true\n end\n mat = Float64.(cell.mat)\n graph = PeriodicGraph3D(n, edges_from_bonds(adjacency, mat, poss))\n\n if bondingmode != InputBonds\n bad_valence = check_valence(types, graph)\n recompute_bonds = bad_valence || sanity_checks!(poss, types, graph, mat, bondingmode)\n if recompute_bonds\n @ifwarn begin\n @warn \"Disregarding all bonds from the input file.\"\n @info \"To force retaining the initial bonds, use --bond-detect=input\"\n end\n try_guess_bonds!(frame)\n topology = Topology(frame)\n adjacency = zeros(Bool, n, n)\n for (a,b) in eachcol(bonds(topology))\n adjacency[a+1,b+1] = true\n adjacency[b+1,a+1] = true\n end\n graph = PeriodicGraph3D(n, edges_from_bonds(adjacency, cell.mat, poss))\n @ifwarn if check_valence(types, graph)\n @warn \"Remaining atoms with invalid valence. Proceeding anyway.\"\n end\n recompute_bonds = sanity_checks!(poss, types, graph, cell.mat, bondingmode)\n @ifwarn if recompute_bonds\n @warn \"Remaining bonds of suspicious lengths. Proceeding anyway.\"\n end\n attributions = attribute_residues(topology, assert_use_existing_residues)\n end\n end\n\n if isempty(attributions)\n crystalnothing = Crystal{Nothing}(cell, types, nothing, poss, graph)\n ifexport(crystalnothing, splitext(splitdir(path)[2])[1], exportto)\n return crystalnothing\n else\n crystalclusters = Crystal{Clusters}(cell, types, regroup_sbus(graph, attributions), poss, graph)\n ifexport(crystalclusters, splitext(splitdir(path)[2])[1], exportto)\n return crystalclusters\n end\nend\n", "meta": {"hexsha": "3356b4305644e68b9f5a09c500ba4612bcbf2267", "size": 18967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/input.jl", "max_stars_repo_name": "kjappelbaum/CrystalNets.jl", "max_stars_repo_head_hexsha": "a3ea0c02ad2125503b155dce1ec1499d842070ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-10-13T16:03:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:10:36.000Z", "max_issues_repo_path": "src/input.jl", "max_issues_repo_name": "kjappelbaum/CrystalNets.jl", "max_issues_repo_head_hexsha": "a3ea0c02ad2125503b155dce1ec1499d842070ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-10-13T21:55:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T07:53:03.000Z", "max_forks_repo_path": "src/input.jl", "max_forks_repo_name": "kjappelbaum/CrystalNets.jl", "max_forks_repo_head_hexsha": "a3ea0c02ad2125503b155dce1ec1499d842070ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-13T19:04:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-11T07:08:51.000Z", "avg_line_length": 34.1747747748, "max_line_length": 187, "alphanum_fraction": 0.5881794696, "num_tokens": 4972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24338981352578684}} {"text": "export datachunk\nexport split_into_n, split_tod_mpi, get_chunk_properties\n\nimport Healpix\nimport CorrNoise\nusing Random\nusing FITSIO\n\n\ntry\n import MPI\ncatch\nend \n\n\n\"\"\"\nThis structure holds a number of parameters relative to a certain chunk of data.\n\nField | Type | Meaning\n:----------------- |:-------------- |:------------------------------------------------------------\n`pol_number` | Int | ID number of the polarimeter\n`first_idx` | Int | Index of the first element of the chunk\n`last_idx` | Int | Index of the last element of the chunk\n`num_of_elements` | Int | Total number of elements of the chunk\n\n# Example\ngiven the following array of data: [1, 10, 20, 3, 4, 5, 7]\nmeasured by the polarimeter number 2\n\nthe chunk: [20, 3, 4]\nwill correspond to the following structure:\ndatachunk(2, 3, 5, 3)\n\"\"\"\nstruct datachunk\n pol_number ::Int\n first_idx::Int\n last_idx::Int\n num_of_elements::Int\nend \n\n\n\"\"\"\n function split_into_n(length, num_of_segments)\n Given the `length` of the array, it convenientely \n splits it into `num_of_segments` sections of as similar length as possible.\n It returns an array containing the number of elements of each section.\n\n # Example\n julia> split_into_n(20, 3)\n 3-element Array{Int64,1}:\n 6\n 7\n 7\n\"\"\"\nfunction split_into_n(length, num_of_segments)\n @assert num_of_segments >0\n @assert length >= num_of_segments\n start_pos = zeros(Int, num_of_segments+1)\n \n for i in 1:num_of_segments+1\n start_pos[i] = floor(((i-1)*length/num_of_segments))\n end\n \n return start_pos[2:end]-start_pos[1:end-1] \nend\n\n\n\"\"\"\n function split_tod_mpi(total_time, baseline_length_s, baselines_per_process, num_of_MPI_proc)\n \n This function can be used to split the TOD production of many polarimeters among MPI processes.\n\n It requires in input:\n\n -the total time (in seconds) of the simulated observation \n -the length (in seconds) of each 1/f noise baseline\n -the array containing the number of 1/f baselines to simulate for each process.\n It can be obtained by using the function `plit_into_n` in the following way:\n\n split_into_n(num_of_polarimeters*baselines_per_pol, num_of_MPI_proc)\n \n where baselines_per_pol = Int64(total_time/baseline_length_s) is the number of baselines of each polarimeter\n\n -the number of MPI processes used\n\n It returns an array of arrays of `datachunk` instances, of length == num_of_MPI_proc\n where each element tells the chunk of data that each process should simulate (see Example) \n\n # Example\n ```julia-repl\n julia> num_of_polarimeters = 4\n julia> num_of_MPI_proc = 3\n julia> total_time = 50\n julia> baseline_length_s = 10\n julia> baselines_per_pol = Int64(total_time/baseline_length_s)\n 5\n\n julia> baselines_per_process = split_into_n(20, 3)\n 3-element Array{Int64,1}:\n 6\n 7\n 7\n\n julia> chunks = split_tod_mpi(total_time, baseline_length_s, baselines_per_process, num_of_MPI_proc)\n 3-element Array{Any,1}:\n Any[datachunk(1, 1, 5, 5), datachunk(2, 1, 1, 1)]\n Any[datachunk(2, 2, 5, 4), datachunk(3, 1, 3, 3)]\n Any[datachunk(3, 4, 5, 2), datachunk(4, 1, 5, 5)]\n ```\n\n which means:\n\n - process number 0 should simulate: \n polarimeter number 1 from baseline 1 to baseline 5, total number of baselines = 5\n polarimeter number 2 from baseline 1 to baseline 1 , total number of baselines = 1\n\n - process number 1 should simulate: \n polarimeter number 2 from baseline 2 to baseline 5, total number of baselines = 4\n polarimeter number 3 from baseline 1 to baseline 3 , total number of baselines = 3\n\n - process number 2 should simulate: \n polarimeter number 3 from baseline 4 to baseline 5, total number of baselines = 2\n polarimeter number 4 from baseline 1 to baseline 5, total number of baselines = 5\n\n\"\"\"\nfunction split_tod_mpi(total_time, baseline_length_s, baselines_per_process, num_of_MPI_proc)\n\n duration = Int64(total_time/baseline_length_s)\n\n #initialization\n detector_num = 1\n sample_idx = 0\n samples_in_det = duration\n result = []\n \n for rank_num in 0:(num_of_MPI_proc-1) #loop on MPI processes\n \n samples_for_this_process = baselines_per_process[rank_num+1]\n samples_left = samples_for_this_process\n data_this_rank = []\n \n while samples_left > 0 #loop on detectors\n \n #if the current detector has more samples than needed to fill the current MPI process\n if samples_in_det > samples_left\n \n first_idx = sample_idx+1\n last_idx = sample_idx+samples_left\n data = datachunk(detector_num, first_idx, last_idx, samples_left)\n data_this_rank = append!(data_this_rank, [data])\n \n sample_idx = sample_idx + samples_left\n samples_in_det = samples_in_det - samples_left\n samples_left = 0 \n \n #if the current detector has not enough samples to provide the current MPI process \n #with the required number of samples. In this case we need to increase \"detector_num\" before the next iteration\n else \n \n first_idx = sample_idx+1\n last_idx = sample_idx+samples_in_det\n data = datachunk(detector_num, first_idx, last_idx, samples_in_det)\n data_this_rank = append!(data_this_rank, [data])\n \n samples_left = samples_left - samples_in_det\n samples_in_det = 0\n end\n \n if samples_in_det == 0\n detector_num +=1\n sample_idx = 0\n samples_in_det = duration \n end\n \n end \n \n result = append!(result, [data_this_rank])\n \n end \n \n return result\n \nend\n\n\"\"\"\n function get_chunk_properties(chunks, baseline_length_s, fsamp_hz, rank)\n \n Given:\n - the data chunks (which can be obtained by using the function `split_tod_mpi`)\n - the length (in seconds) of each 1/f noise baseline\n - the sampling frequency (in Hz)\n - the number of current MPI rank\n\n this function extracts useful information to perform the TOD simulation in the current rank.\n\n\n It returns a tuple containing 5 arrays:\n - the ID number of the polarimeters that the current rank will simulate\n - the start time of the acquisition portion for each polarimeter\n - the stop time of the acquisition portion for each polarimeter\n - the number of 1/f baselines for each polarimeter\n - the total number of samples for each polarimeter\n\n # Example\n ```julia-repl\n julia> baseline_length_s = 10\n julia> fsamp_hz = 10\n julia> rank = 1\n\n julia> chunks = [[datachunk(1, 1, 5, 5), datachunk(2, 1, 1, 1)], [datachunk(2, 2, 5, 4), datachunk(3, 1, 3, 3)], [datachunk(3, 4, 5, 2), datachunk(4, 1, 5, 5)]]\n\n get_chunk_properties(chunks, baseline_length_s, fsamp_hz, rank)\n ([2, 3], [10.0, 0.0], [50.0, 30.0], [4, 3], [400, 300])\n\n which means that rank 1 will simulate:\n - polarimeter number 2 from 10 s (from the starting of the acquisition) to 50 s, \n with a total of 4 1/f baselines and 400 samples.\n - polarimeter number 3 from 0 s (from the starting of the acquisition) to 30 s, \n with a total of 3 1/f baselines and 300 samples.\n\n \"\"\"\n function get_chunk_properties(chunks, baseline_length_s, fsamp_hz, rank)\n\n this_rank_chunk = chunks[rank+1]\n first_time, last_time = [Array{Float64}(undef, length(this_rank_chunk)) for i in (1:2)]\n detector_number, num_of_baselines, baseline_len, num_of_samples = [Array{Int64}(undef, length(this_rank_chunk)) for i in (1:4)]\n \n for i in 1:length(this_rank_chunk)\n detector_number[i] = this_rank_chunk[i].pol_number\n first_time[i] = (this_rank_chunk[i].first_idx-1)*baseline_length_s\n last_time[i] = this_rank_chunk[i].last_idx*baseline_length_s -0.99*(1/fsamp_hz)\n num_of_baselines[i] = this_rank_chunk[i].num_of_elements\n num_of_samples[i] = num_of_baselines[i]*baseline_length_s*fsamp_hz \n end\n return (detector_number, first_time, last_time, num_of_baselines, num_of_samples)\n end\n \n\n", "meta": {"hexsha": "6f19bb17289d8744c097720b5271d6da7f1046d8", "size": 8756, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tod_splitter.jl", "max_stars_repo_name": "fincardona/Stripeline.jl", "max_stars_repo_head_hexsha": "e4dd169f9952e26b16292dccd44ce64cf69db67e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tod_splitter.jl", "max_issues_repo_name": "fincardona/Stripeline.jl", "max_issues_repo_head_hexsha": "e4dd169f9952e26b16292dccd44ce64cf69db67e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tod_splitter.jl", "max_forks_repo_name": "fincardona/Stripeline.jl", "max_forks_repo_head_hexsha": "e4dd169f9952e26b16292dccd44ce64cf69db67e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6359832636, "max_line_length": 168, "alphanum_fraction": 0.6298538145, "num_tokens": 2220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2433898074516826}} {"text": "function polar_kernel(n::Int, nlines::Int, line_start::Int, scale::Float64,\n u_curr::CuDeviceArray{Float64,1}, v_curr::CuDeviceArray{Float64,1},\n l_curr::CuDeviceArray{Float64,1}, rho::CuDeviceArray{Float64,1},\n shift_lines::Int, param::CuDeviceArray{Float64,2},\n _YffR::CuDeviceArray{Float64,1}, _YffI::CuDeviceArray{Float64,1},\n _YftR::CuDeviceArray{Float64,1}, _YftI::CuDeviceArray{Float64,1},\n _YttR::CuDeviceArray{Float64,1}, _YttI::CuDeviceArray{Float64,1},\n _YtfR::CuDeviceArray{Float64,1}, _YtfI::CuDeviceArray{Float64,1},\n frBound::CuDeviceArray{Float64,1}, toBound::CuDeviceArray{Float64,1})\n\n tx = threadIdx().x\n ty = threadIdx().y\n I = blockIdx().x\n id_line = I + shift_lines\n\n x = @cuDynamicSharedMem(Float64, n)\n xl = @cuDynamicSharedMem(Float64, n, n*sizeof(Float64))\n xu = @cuDynamicSharedMem(Float64, n, (2*n)*sizeof(Float64))\n\n @inbounds begin\n YffR = _YffR[id_line]; YffI = _YffI[id_line]\n YftR = _YftR[id_line]; YftI = _YftI[id_line]\n YttR = _YttR[id_line]; YttI = _YttI[id_line]\n YtfR = _YtfR[id_line]; YtfI = _YtfI[id_line]\n\n pij_idx = line_start + 8*(I-1)\n\n xl[1] = sqrt(frBound[2*(id_line-1)+1])\n xu[1] = sqrt(frBound[2*id_line])\n xl[2] = sqrt(toBound[2*(id_line-1)+1])\n xu[2] = sqrt(toBound[2*id_line])\n xl[3] = -2*pi\n xu[3] = 2*pi\n xl[4] = -2*pi\n xu[4] = 2*pi\n\n x[1] = min(xu[1], max(xl[1], sqrt(u_curr[pij_idx+4])))\n x[2] = min(xu[2], max(xl[2], sqrt(u_curr[pij_idx+5])))\n x[3] = min(xu[3], max(xl[3], u_curr[pij_idx+6]))\n x[4] = min(xu[4], max(xl[4], u_curr[pij_idx+7]))\n\n param[1,id_line] = l_curr[pij_idx]\n param[2,id_line] = l_curr[pij_idx+1]\n param[3,id_line] = l_curr[pij_idx+2]\n param[4,id_line] = l_curr[pij_idx+3]\n param[5,id_line] = l_curr[pij_idx+4]\n param[6,id_line] = l_curr[pij_idx+5]\n param[7,id_line] = l_curr[pij_idx+6]\n param[8,id_line] = l_curr[pij_idx+7]\n param[9,id_line] = rho[pij_idx]\n param[10,id_line] = rho[pij_idx+1]\n param[11,id_line] = rho[pij_idx+2]\n param[12,id_line] = rho[pij_idx+3]\n param[13,id_line] = rho[pij_idx+4]\n param[14,id_line] = rho[pij_idx+5]\n param[15,id_line] = rho[pij_idx+6]\n param[16,id_line] = rho[pij_idx+7]\n param[17,id_line] = v_curr[pij_idx]\n param[18,id_line] = v_curr[pij_idx+1]\n param[19,id_line] = v_curr[pij_idx+2]\n param[20,id_line] = v_curr[pij_idx+3]\n param[21,id_line] = v_curr[pij_idx+4]\n param[22,id_line] = v_curr[pij_idx+5]\n param[23,id_line] = v_curr[pij_idx+6]\n param[24,id_line] = v_curr[pij_idx+7]\n\n CUDA.sync_threads()\n\n status, minor_iter = tron_kernel(n, shift_lines, 500, 200, 1e-6, scale, true, x, xl, xu,\n param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n\n vi_vj_cos = x[1]*x[2]*cos(x[3] - x[4])\n vi_vj_sin = x[1]*x[2]*sin(x[3] - x[4])\n\n u_curr[pij_idx] = YffR*x[1]^2 + YftR*vi_vj_cos + YftI*vi_vj_sin\n u_curr[pij_idx+1] = -YffI*x[1]^2 - YftI*vi_vj_cos + YftR*vi_vj_sin\n u_curr[pij_idx+2] = YttR*x[2]^2 + YtfR*vi_vj_cos - YtfI*vi_vj_sin\n u_curr[pij_idx+3] = -YttI*x[2]^2 - YtfI*vi_vj_cos - YtfR*vi_vj_sin\n u_curr[pij_idx+4] = x[1]^2\n u_curr[pij_idx+5] = x[2]^2\n u_curr[pij_idx+6] = x[3]\n u_curr[pij_idx+7] = x[4]\n end\n\n return\nend\n\nfunction polar_kernel_cpu(n::Int, nline::Int, line_start::Int, scale::Float64,\n u_curr::AbstractVector{Float64}, v_curr::AbstractVector{Float64},\n l_curr::AbstractVector{Float64}, rho::AbstractVector{Float64},\n shift::Int,\n param::Array{Float64},\n YffR::Array{Float64}, YffI::Array{Float64},\n YftR::Array{Float64}, YftI::Array{Float64},\n YttR::Array{Float64}, YttI::Array{Float64},\n YtfR::Array{Float64}, YtfI::Array{Float64},\n frBound::Array{Float64}, toBound::Array{Float64})\n avg_minor_it = 0\n\n x = zeros(n)\n xl = zeros(n)\n xu = zeros(n)\n\n xl[3] = -2*pi\n xu[3] = 2*pi\n xl[4] = -2*pi\n xu[4] = 2*pi\n\n @inbounds for I=1:nline\n pij_idx = line_start + 8*(I-1)\n id_line = shift + I\n\n xl[1] = sqrt(frBound[2*(id_line-1)+1])\n xu[1] = sqrt(frBound[2*id_line])\n xl[2] = sqrt(toBound[2*(id_line-1)+1])\n xu[2] = sqrt(toBound[2*id_line])\n\n x[1] = min(xu[1], max(xl[1], sqrt(u_curr[pij_idx+4])))\n x[2] = min(xu[2], max(xl[2], sqrt(u_curr[pij_idx+5])))\n x[3] = min(xu[3], max(xl[3], u_curr[pij_idx+6]))\n x[4] = min(xu[4], max(xl[4], u_curr[pij_idx+7]))\n\n param[1,id_line] = l_curr[pij_idx]\n param[2,id_line] = l_curr[pij_idx+1]\n param[3,id_line] = l_curr[pij_idx+2]\n param[4,id_line] = l_curr[pij_idx+3]\n param[5,id_line] = l_curr[pij_idx+4]\n param[6,id_line] = l_curr[pij_idx+5]\n param[7,id_line] = l_curr[pij_idx+6]\n param[8,id_line] = l_curr[pij_idx+7]\n param[9,id_line] = rho[pij_idx]\n param[10,id_line] = rho[pij_idx+1]\n param[11,id_line] = rho[pij_idx+2]\n param[12,id_line] = rho[pij_idx+3]\n param[13,id_line] = rho[pij_idx+4]\n param[14,id_line] = rho[pij_idx+5]\n param[15,id_line] = rho[pij_idx+6]\n param[16,id_line] = rho[pij_idx+7]\n param[17,id_line] = v_curr[pij_idx]\n param[18,id_line] = v_curr[pij_idx+1]\n param[19,id_line] = v_curr[pij_idx+2]\n param[20,id_line] = v_curr[pij_idx+3]\n param[21,id_line] = v_curr[pij_idx+4]\n param[22,id_line] = v_curr[pij_idx+5]\n param[23,id_line] = v_curr[pij_idx+6]\n param[24,id_line] = v_curr[pij_idx+7]\n\n function eval_f_cb(x)\n f = eval_f_polar_kernel_cpu(id_line, scale, x, param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n return f\n end\n\n function eval_g_cb(x, g)\n eval_grad_f_polar_kernel_cpu(id_line, scale, x, g, param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n return\n end\n\n function eval_h_cb(x, mode, rows, cols, _scale, lambda, values)\n eval_h_polar_kernel_cpu(id_line, x, mode, scale, rows, cols, lambda, values,\n param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n return\n end\n\n nele_hess = 10\n tron = ExaTron.createProblem(4, xl, xu, nele_hess, eval_f_cb, eval_g_cb, eval_h_cb;\n :tol => 1e-6, :matrix_type => :Dense, :max_minor => 200,\n :frtol => 1e-12)\n\n tron.x .= x\n status = ExaTron.solveProblem(tron)\n x .= tron.x\n avg_minor_it += tron.minor_iter\n\n cos_ij = cos(x[3] - x[4])\n sin_ij = sin(x[3] - x[4])\n vi_vj_cos = x[1]*x[2]*cos_ij\n vi_vj_sin = x[1]*x[2]*sin_ij\n\n u_curr[pij_idx] = YffR[id_line]*x[1]^2 + YftR[id_line]*vi_vj_cos + YftI[id_line]*vi_vj_sin\n u_curr[pij_idx+1] = -YffI[id_line]*x[1]^2 - YftI[id_line]*vi_vj_cos + YftR[id_line]*vi_vj_sin\n u_curr[pij_idx+2] = YttR[id_line]*x[2]^2 + YtfR[id_line]*vi_vj_cos - YtfI[id_line]*vi_vj_sin\n u_curr[pij_idx+3] = -YttI[id_line]*x[2]^2 - YtfI[id_line]*vi_vj_cos - YtfR[id_line]*vi_vj_sin\n u_curr[pij_idx+4] = x[1]^2\n u_curr[pij_idx+5] = x[2]^2\n u_curr[pij_idx+6] = x[3]\n u_curr[pij_idx+7] = x[4]\n end\n\n return 0, avg_minor_it / nline\nend\n\nfunction polar_kernel_two_level(\n n::Int, nline::Int, line_start::Int, bus_start::Int, scale::Float64,\n u::CuDeviceArray{Float64}, xbar::CuDeviceArray{Float64},\n z::CuDeviceArray{Float64}, l::CuDeviceArray{Float64}, rho::CuDeviceArray{Float64},\n shift_lines::Int, param::CuDeviceArray{Float64},\n _YffR::CuDeviceArray{Float64}, _YffI::CuDeviceArray{Float64},\n _YftR::CuDeviceArray{Float64}, _YftI::CuDeviceArray{Float64},\n _YttR::CuDeviceArray{Float64}, _YttI::CuDeviceArray{Float64},\n _YtfR::CuDeviceArray{Float64}, _YtfI::CuDeviceArray{Float64},\n frBound::CuDeviceArray{Float64}, toBound::CuDeviceArray{Float64},\n brBusIdx::CuDeviceArray{Int}\n)\n I = blockIdx().x\n id_line = I + shift_lines\n\n x = @cuDynamicSharedMem(Float64, n)\n xl = @cuDynamicSharedMem(Float64, n, n*sizeof(Float64))\n xu = @cuDynamicSharedMem(Float64, n, (2*n)*sizeof(Float64))\n\n @inbounds begin\n YffR = _YffR[id_line]; YffI = _YffI[id_line]\n YftR = _YftR[id_line]; YftI = _YftI[id_line]\n YttR = _YttR[id_line]; YttI = _YttI[id_line]\n YtfR = _YtfR[id_line]; YtfI = _YtfI[id_line]\n\n pij_idx = line_start + 8*(I-1)\n xbar_pij_idx = line_start + 4*(I-1)\n\n xl[1] = sqrt(frBound[2*(id_line-1)+1])\n xu[1] = sqrt(frBound[2*id_line])\n xl[2] = sqrt(toBound[2*(id_line-1)+1])\n xu[2] = sqrt(toBound[2*id_line])\n xl[3] = -2*pi\n xu[3] = 2*pi\n xl[4] = -2*pi\n xu[4] = 2*pi\n\n x[1] = min(xu[1], max(xl[1], sqrt(u[pij_idx+4])))\n x[2] = min(xu[2], max(xl[2], sqrt(u[pij_idx+5])))\n x[3] = min(xu[3], max(xl[3], u[pij_idx+6]))\n x[4] = min(xu[4], max(xl[4], u[pij_idx+7]))\n\n fr_idx = bus_start + 2*(brBusIdx[2*(id_line-1)+1] - 1)\n to_idx = bus_start + 2*(brBusIdx[2*id_line] - 1)\n\n param[1,id_line] = l[pij_idx]\n param[2,id_line] = l[pij_idx+1]\n param[3,id_line] = l[pij_idx+2]\n param[4,id_line] = l[pij_idx+3]\n param[5,id_line] = l[pij_idx+4]\n param[6,id_line] = l[pij_idx+5]\n param[7,id_line] = l[pij_idx+6]\n param[8,id_line] = l[pij_idx+7]\n param[9,id_line] = rho[pij_idx]\n param[10,id_line] = rho[pij_idx+1]\n param[11,id_line] = rho[pij_idx+2]\n param[12,id_line] = rho[pij_idx+3]\n param[13,id_line] = rho[pij_idx+4]\n param[14,id_line] = rho[pij_idx+5]\n param[15,id_line] = rho[pij_idx+6]\n param[16,id_line] = rho[pij_idx+7]\n param[17,id_line] = xbar[xbar_pij_idx] - z[pij_idx]\n param[18,id_line] = xbar[xbar_pij_idx+1] - z[pij_idx+1]\n param[19,id_line] = xbar[xbar_pij_idx+2] - z[pij_idx+2]\n param[20,id_line] = xbar[xbar_pij_idx+3] - z[pij_idx+3]\n param[21,id_line] = xbar[fr_idx] - z[pij_idx+4]\n param[22,id_line] = xbar[to_idx] - z[pij_idx+5]\n param[23,id_line] = xbar[fr_idx+1] - z[pij_idx+6]\n param[24,id_line] = xbar[to_idx+1] - z[pij_idx+7]\n\n CUDA.sync_threads()\n\n status, minor_iter = tron_kernel(n, shift_lines, 500, 200, 1e-6, scale, true, x, xl, xu,\n param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n\n vi_vj_cos = x[1]*x[2]*cos(x[3] - x[4])\n vi_vj_sin = x[1]*x[2]*sin(x[3] - x[4])\n\n u[pij_idx] = YffR*x[1]^2 + YftR*vi_vj_cos + YftI*vi_vj_sin\n u[pij_idx+1] = -YffI*x[1]^2 - YftI*vi_vj_cos + YftR*vi_vj_sin\n u[pij_idx+2] = YttR*x[2]^2 + YtfR*vi_vj_cos - YtfI*vi_vj_sin\n u[pij_idx+3] = -YttI*x[2]^2 - YtfI*vi_vj_cos - YtfR*vi_vj_sin\n u[pij_idx+4] = x[1]^2\n u[pij_idx+5] = x[2]^2\n u[pij_idx+6] = x[3]\n u[pij_idx+7] = x[4]\n end\n\n return\nend\n\nfunction polar_kernel_two_level_cpu(\n n::Int, nline::Int, line_start::Int, bus_start::Int, scale::Float64,\n u::AbstractVector{Float64}, xbar::AbstractVector{Float64},\n z::AbstractVector{Float64}, l::AbstractVector{Float64}, rho::AbstractVector{Float64},\n shift::Int,\n param::Array{Float64},\n YffR::Array{Float64}, YffI::Array{Float64},\n YftR::Array{Float64}, YftI::Array{Float64},\n YttR::Array{Float64}, YttI::Array{Float64},\n YtfR::Array{Float64}, YtfI::Array{Float64},\n frBound::Array{Float64}, toBound::Array{Float64},\n brBusIdx::Array{Int}\n)\n avg_minor_it = 0\n\n x = zeros(n)\n xl = zeros(n)\n xu = zeros(n)\n\n xl[3] = -2*pi\n xu[3] = 2*pi\n xl[4] = -2*pi\n xu[4] = 2*pi\n\n @inbounds for I=1:nline\n pij_idx = line_start + 8*(I-1)\n xbar_pij_idx = line_start + 4*(I-1)\n id_line = shift + I\n\n xl[1] = sqrt(frBound[2*(id_line-1)+1])\n xu[1] = sqrt(frBound[2*id_line])\n xl[2] = sqrt(toBound[2*(id_line-1)+1])\n xu[2] = sqrt(toBound[2*id_line])\n\n x[1] = min(xu[1], max(xl[1], sqrt(u[pij_idx+4])))\n x[2] = min(xu[2], max(xl[2], sqrt(u[pij_idx+5])))\n x[3] = min(xu[3], max(xl[3], u[pij_idx+6]))\n x[4] = min(xu[4], max(xl[4], u[pij_idx+7]))\n\n fr_idx = bus_start + 2*(brBusIdx[2*(id_line-1)+1] - 1)\n to_idx = bus_start + 2*(brBusIdx[2*id_line] - 1)\n\n param[1,id_line] = l[pij_idx]\n param[2,id_line] = l[pij_idx+1]\n param[3,id_line] = l[pij_idx+2]\n param[4,id_line] = l[pij_idx+3]\n param[5,id_line] = l[pij_idx+4]\n param[6,id_line] = l[pij_idx+5]\n param[7,id_line] = l[pij_idx+6]\n param[8,id_line] = l[pij_idx+7]\n param[9,id_line] = rho[pij_idx]\n param[10,id_line] = rho[pij_idx+1]\n param[11,id_line] = rho[pij_idx+2]\n param[12,id_line] = rho[pij_idx+3]\n param[13,id_line] = rho[pij_idx+4]\n param[14,id_line] = rho[pij_idx+5]\n param[15,id_line] = rho[pij_idx+6]\n param[16,id_line] = rho[pij_idx+7]\n param[17,id_line] = xbar[xbar_pij_idx] - z[pij_idx]\n param[18,id_line] = xbar[xbar_pij_idx+1] - z[pij_idx+1]\n param[19,id_line] = xbar[xbar_pij_idx+2] - z[pij_idx+2]\n param[20,id_line] = xbar[xbar_pij_idx+3] - z[pij_idx+3]\n param[21,id_line] = xbar[fr_idx] - z[pij_idx+4]\n param[22,id_line] = xbar[to_idx] - z[pij_idx+5]\n param[23,id_line] = xbar[fr_idx+1] - z[pij_idx+6]\n param[24,id_line] = xbar[to_idx+1] - z[pij_idx+7]\n\n function eval_f_cb(x)\n f = eval_f_polar_kernel_cpu(id_line, scale, x, param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n return f\n end\n\n function eval_g_cb(x, g)\n eval_grad_f_polar_kernel_cpu(id_line, scale, x, g, param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n return\n end\n\n function eval_h_cb(x, mode, rows, cols, _scale, lambda, values)\n eval_h_polar_kernel_cpu(id_line, x, mode, scale, rows, cols, lambda, values,\n param, YffR, YffI, YftR, YftI, YttR, YttI, YtfR, YtfI)\n return\n end\n\n nele_hess = 10\n tron = ExaTron.createProblem(4, xl, xu, nele_hess, eval_f_cb, eval_g_cb, eval_h_cb;\n :tol => 1e-6, :matrix_type => :Dense, :max_minor => 200,\n :frtol => 1e-12)\n\n tron.x .= x\n status = ExaTron.solveProblem(tron)\n x .= tron.x\n avg_minor_it += tron.minor_iter\n\n vi_vj_cos = x[1]*x[2]*cos(x[3] - x[4])\n vi_vj_sin = x[1]*x[2]*sin(x[3] - x[4])\n\n u[pij_idx] = YffR[id_line]*x[1]^2 + YftR[id_line]*vi_vj_cos + YftI[id_line]*vi_vj_sin\n u[pij_idx+1] = -YffI[id_line]*x[1]^2 - YftI[id_line]*vi_vj_cos + YftR[id_line]*vi_vj_sin\n u[pij_idx+2] = YttR[id_line]*x[2]^2 + YtfR[id_line]*vi_vj_cos - YtfI[id_line]*vi_vj_sin\n u[pij_idx+3] = -YttI[id_line]*x[2]^2 - YtfI[id_line]*vi_vj_cos - YtfR[id_line]*vi_vj_sin\n u[pij_idx+4] = x[1]^2\n u[pij_idx+5] = x[2]^2\n u[pij_idx+6] = x[3]\n u[pij_idx+7] = x[4]\n end\n\n return 0, avg_minor_it / nline\nend\n", "meta": {"hexsha": "ff39a782f1d82acd6b45d2fbd21e3e24bab5fb09", "size": 15732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/admm/polar_kernel.jl", "max_stars_repo_name": "wzhangw/ExaTron.jl", "max_stars_repo_head_hexsha": "c5844f356876904c410b68bf2b20ba3a03597674", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-07T19:27:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:38:20.000Z", "max_issues_repo_path": "src/admm/polar_kernel.jl", "max_issues_repo_name": "wzhangw/ExaTron.jl", "max_issues_repo_head_hexsha": "c5844f356876904c410b68bf2b20ba3a03597674", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-05-07T16:17:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T22:22:53.000Z", "max_forks_repo_path": "src/admm/polar_kernel.jl", "max_forks_repo_name": "wzhangw/ExaTron.jl", "max_forks_repo_head_hexsha": "c5844f356876904c410b68bf2b20ba3a03597674", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-22T14:34:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T16:21:49.000Z", "avg_line_length": 40.2352941176, "max_line_length": 117, "alphanum_fraction": 0.5673150267, "num_tokens": 5965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24338980137757818}} {"text": "module OBJFileIO\n\nexport Shapeobject, loadOBJFile, createCylinderVertices\n\n############### Begin Type declaration for Shape Object ################\ntype Shapeobject\n #A new type declaration. This is a shape object that is composed of\n #An array of vertices and an array of faces\n vertices::Array{Float64, 2}\n faces::Array{Int64, 2}\n\n #Constructor that creates an object from an obj file\n function Shapeobject(filename::String)\n #Create instance of the object\n shapeOBJ = new()\n #Populate the object fields using the loadOBJFile method\n shapeOBJ.vertices, shapeOBJ.faces = loadOBJFile(filename)\n #Return object\n return shapeOBJ\n end #end constructor\n\n #Constructor that creates an object from an obj file\n function Shapeobject(cylDiamter::Float64, cylLength::Float64,\n numVertices::Int64, filename::String)\n #Create instance of the object\n shapeOBJ = new()\n #Populate the object.faces field using the loadOBJFile method\n x, shapeOBJ.faces = loadOBJFile(filename)\n #Populate the object.vertices field using the createCylinderVertices method\n shapeOBJ.vertices = createCylinderVertices(cylDiamter, cylLength, numVertices)\n #Return object\n return shapeOBJ\n end #end constructor\n\nend # end of type declaration\n\n############### Begin Functions ###############\n\n#FUNCTION\n#SUMMARY:\n#This function loads an obj file and returns an array of vertices and an array of faces\n#\n#INPUTS:\n# objFile::String -\n# Path to the obj file containing the object that you want\n#\n#OUTPUTS:\n# Tuple of arrays\n#\n# objectVertices::Array{Float64,2} -\n# array containing the vertices of the object\n#\n# objectFaces::Array{Float64,2} -\n# array containing the faces of the object\nfunction loadOBJFile(objFile::String)\n #Initiate variables for the object vertices and faces\n objectVertices = zeros(Float64,1,3)\n objectFaces = zeros(Int64,1,3)\n\n #Initialise variables to temporarily store the data for each line.\n lineVertex = zeros(Float64,1,3)\n lineFace = zeros(Int64,1,3)\n\n #Initialise counter for the vertex and face line number\n vertexLineCounter = 1\n faceLineCounter = 1\n\n #Open OBJ file for reading\n objFileContent = open(objFile)\n\n #Loop through each line of the file and look for vertex lines and face lines\n #Those lines begin with a 'v' or and 'f' respectively.\n #Foor those lines store the values in the repsective objectvertices or object faces\n #array.\n for line in eachline(objFileContent)\n if line[1] == 'v'\n vertexLine = split(line)\n #Initialise counter for the vertex line number\n for i = 1:length(vertexLine)\n if i != 1\n if vertexLineCounter == 1\n objectVertices[vertexLineCounter,i-1] = parsefloat(vertexLine[i])\n else\n lineVertex[i-1] = parsefloat(vertexLine[i])\n end\n end\n end\n if vertexLineCounter != 1\n #Concatenate the vertex from the parsed line to the object vertices array\n objectVertices = vcat(objectVertices,lineVertex)\n end\n #Increment counter\n vertexLineCounter += 1\n\n elseif line[1] == 'f'\n faceLine = split(line)\n for i = 1:length(faceLine)\n if i != 1\n if faceLineCounter == 1\n objectFaces[faceLineCounter,i-1] = parseint(faceLine[i])\n else\n lineFace[i-1] = parsefloat(faceLine[i])\n end\n end\n end\n if faceLineCounter != 1\n #Concatenate the face from the parsed line to the object vertices array\n objectFaces = vcat(objectFaces,lineFace)\n end\n #Increment counter\n faceLineCounter += 1\n end\n end\n\n #Close the file now we are done with it\n close(objFileContent)\n\n #return Object vertices and faces\n return objectVertices, objectFaces\nend #end loadOBJFile function\n\n#FUNCTION\n#SUMMARY:\n#Takes in parameters and returns a cylinder object from those parameters\n#\n#INPUTS:\n# cylDiameter::Float64 -\n# Diameter of cylinder\n#\n# cylLength::Float64 -\n# Axial length of the cylinder\n#\n# numVertices::Int64 -\n# number of vertices around each end of cylinder i.e. this is half of the total number\n# of vertices in the cylinder object\n#\n#OUTPUTS:\n# vertices::Array{Float64,2}\n# An 2*numVertices x 3 array containing the coordinates of each vertex of the cylinder\nfunction createCylinderVertices(cylDiamter::Float64, cylLength::Float64, numVertices::Int64)\n #Calculate radius\n cylRadius = cylDiamter/2\n\n #Create xCoordinates\n cylBase = cylLength/2\n xCoordBase = -cylBase\n xCoordTop = cylBase\n\n #Calculate angular step around circle\n angleToVertex = -2π/numVertices\n\n #Preallocate vertices array\n vertices = zeros(Float64, 2 * numVertices, 3)\n\n #Loop through each vertex\n for vertex = 1:numVertices\n #Calculate points around the circle\n yCoord = cylRadius * cos((vertex - 1) * angleToVertex)\n ZCoord = cylRadius * sin((vertex - 1) * angleToVertex)\n\n #Add points to the vertices array for the Base\n vertices[2 * vertex - 1, 1] = xCoordBase\n vertices[2 * vertex - 1, 2] = yCoord\n vertices[2 * vertex - 1, 3] = ZCoord\n\n #Add points to the vertices array for the Top\n vertices[2 * vertex, 1] = xCoordTop\n vertices[2 * vertex, 2] = yCoord\n vertices[2 * vertex, 3] = ZCoord\n end\n\n #return vertices\n return vertices\nend #end createCylinderVertices method\n\nend #end module\n", "meta": {"hexsha": "8e76084600c36488c748cbb13a6bd59fe2214255", "size": 5844, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ObjectFiles_jl/OBJFileIO.jl", "max_stars_repo_name": "el-uhu/LearnigResources-Julia_Python", "max_stars_repo_head_hexsha": "a9d70c7d9b2b8a36f7f31a9ca13f226ecfb9e691", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ObjectFiles_jl/OBJFileIO.jl", "max_issues_repo_name": "el-uhu/LearnigResources-Julia_Python", "max_issues_repo_head_hexsha": "a9d70c7d9b2b8a36f7f31a9ca13f226ecfb9e691", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObjectFiles_jl/OBJFileIO.jl", "max_forks_repo_name": "el-uhu/LearnigResources-Julia_Python", "max_forks_repo_head_hexsha": "a9d70c7d9b2b8a36f7f31a9ca13f226ecfb9e691", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0169491525, "max_line_length": 92, "alphanum_fraction": 0.6362080767, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24333894270930437}} {"text": "\"\"\"implementation of Simultaneous Sampling-and-Search Planning (SSSP)\"\"\"\nmodule LibSSSP\nexport SSSP\n\nimport Printf: @sprintf, @printf\nimport Base: @kwdef\nimport ...MRMP: AbsState, Node, now, elapsed_sec, gen_uniform_sampling, get_mid_status, dist\nimport DataStructures: PriorityQueue, enqueue!, dequeue!\nimport ..Solvers: gen_g_func, get_distance_tables, get_distance_table\n\n@kwdef mutable struct SuperNode{State<:AbsState}\n Q::Vector{Node{State}} # set of search nodes\n next::Int64 # next agent, 0 -> fixed agents\n id::String = get_Q_id(Q, next)\n parent_id::Union{Nothing,String} = nothing # parent node\n g::Float64 = 0.0 # g-value\n h::Float64 = 0.0 # h-value\n f::Float64 = g + h # f-value\n depth::Int64 = 1 # depth\nend\n\n\"\"\"\n SSSP(\n config_init::Vector{State},\n config_goal::Vector{State},\n connect::Function,\n collide::Function,\n check_goal::Function;\n g_func::Function = gen_g_func(greedy = true),\n steering_depth::Int64 = 2,\n num_vertex_expansion::Int64 = 10,\n init_min_dist_thread::Float64 = 0.1,\n decreasing_rate_min_dist_thread::Float64 = 0.99,\n epsilon::Union{Float64,Nothing} = nothing,\n TIME_LIMIT::Union{Nothing,Real} = 30,\n VERBOSE::Int64 = 0,\n\n use_random_h_func::Bool = false, # for ablation study\n no_roadmap_at_beginning::Bool = false, # for ablation study\n\n no_fast_collision_check::Bool = false, # use 'slow' collision checker\n )::Tuple{\n Union{Nothing,Vector{Vector{Node{State}}}}, # solution\n Vector{Vector{Node{State}}}, # roadmap\n } where {State<:AbsState}\n\nimplementation of SSSP\n\"\"\"\nfunction SSSP(\n config_init::Vector{State},\n config_goal::Vector{State},\n connect::Function,\n collide::Function,\n check_goal::Function;\n g_func::Function = gen_g_func(greedy = true),\n steering_depth::Int64 = 2,\n num_vertex_expansion::Int64 = 10,\n init_min_dist_thread::Float64 = 0.1,\n decreasing_rate_min_dist_thread::Float64 = 0.99,\n epsilon::Union{Float64,Nothing} = nothing,\n TIME_LIMIT::Union{Nothing,Real} = 30,\n VERBOSE::Int64 = 0,\n\n # for ablation study\n use_random_h_func::Bool = false,\n no_roadmap_at_beginning::Bool = false,\n\n # just for fairness of experiments\n no_fast_collision_check::Bool = false,\n)::Tuple{\n Union{Nothing,Vector{Vector{Node{State}}}}, # solution\n Vector{Vector{Node{State}}}, # roadmap\n} where {State<:AbsState}\n \"\"\"get initial solution / refinement\"\"\"\n\n t_s = now()\n elapsed() = elapsed_sec(t_s)\n timeover() = TIME_LIMIT != nothing && elapsed() > TIME_LIMIT\n\n # number of agents\n N = length(config_init)\n\n # define sampler\n sampler = gen_uniform_sampling(config_init[1])\n\n # used in steering\n conn(q_from::State, q_to::State, i::Int64) = begin\n (isnothing(epsilon) || dist(q_from, q_to) <= epsilon) && connect(q_from, q_to, i)\n end\n\n # get initial roadmap by RRT-connect\n roadmaps = (\n no_roadmap_at_beginning ?\n map(\n i -> begin\n v_init = Node{State}(config_init[i], 1, [])\n v_goal = Node{State}(config_goal[i], 2, [])\n conn(v_init.q, v_goal.q, i) && push!(v_init.neighbors, v_goal.id)\n conn(v_goal.q, v_init.q, i) && push!(v_goal.neighbors, v_init.id)\n [v_init, v_goal]\n end,\n 1:N,\n ) :\n gen_RRT_connect_roadmaps(\n config_init,\n config_goal,\n connect;\n steering_depth = steering_depth,\n epsilon = epsilon,\n TIME_LIMIT = (isnothing(TIME_LIMIT) ? nothing : TIME_LIMIT - elapsed()),\n )\n )\n if isnothing(roadmaps)\n VERBOSE > 0 &&\n @info @sprintf(\"\\t%6.4f sec: failed to construct initial roadmaps\\n\", elapsed())\n return (nothing, map(i -> Vector{Node{State}}(), 1:N))\n end\n\n VERBOSE > 0 && !no_roadmap_at_beginning && @info (\"\\tdone, setup initial roadmaps\")\n\n # setup distance tables\n distance_tables = get_distance_tables(roadmaps)\n\n # verbose\n print_progress! =\n (S::SuperNode{State}, loop_cnt::Int64; force::Bool = false) -> begin\n (VERBOSE < 1 || (!force && (loop_cnt % 100 != 0))) && return\n @printf(\n \"\\r\\t\\t%6.4f sec, explored node: %08d, f: %.4f, depth: %04d\",\n elapsed(),\n loop_cnt,\n S.f,\n S.depth\n )\n end\n\n # setup heuristic function\n h_func(Q::Vector{Node{State}}) =\n (use_random_h_func ? rand() : sum(map(i -> distance_tables[i][Q[i].id], 1:N)) / N)\n\n # initial configuration\n Q_init = [roadmaps[i][1] for i = 1:N]\n\n # initial search node\n S_init = SuperNode(Q = Q_init, next = 1, id = get_Q_id(Q_init, 0), h = h_func(Q_init))\n\n k = 0\n while !timeover()\n k += 1\n\n # open list\n OPEN = PriorityQueue{SuperNode{State},Float64}()\n\n # discovered list to avoid duplication\n VISITED = Dict{String,SuperNode{State}}()\n\n # threshold of space-filling metric\n min_dist_thread = init_min_dist_thread * (decreasing_rate_min_dist_thread^(k - 1))\n\n # setup initail node\n enqueue!(OPEN, S_init, S_init.f)\n VISITED[S_init.id] = S_init\n\n loop_cnt = 0\n while !isempty(OPEN) && !timeover()\n loop_cnt += 1\n\n # pop\n S = dequeue!(OPEN)\n\n # check goal\n if check_goal(S.Q)\n print_progress!(S, loop_cnt, force = true)\n VERBOSE > 0 && @info @sprintf(\"\\n\\t%6.4f sec: found solution\\n\", elapsed())\n return (backtrack(S, VISITED), roadmaps)\n end\n\n # initial search or update for refine agents\n i = S.next\n j = mod1(S.next + 1, N)\n\n v = S.Q[i]\n\n # explore new states\n expand!(\n (q_from::State, q_to::State) -> conn(q_from, q_to, i),\n sampler,\n v,\n roadmaps[i],\n min_dist_thread,\n num_vertex_expansion,\n steering_depth,\n ) && (distance_tables[i] = get_distance_table(roadmaps[i]))\n\n # expand search node\n for p_id in vcat(v.neighbors, v.id)\n\n # create new configuration\n p = roadmaps[i][p_id]\n Q = copy(S.Q)\n Q[i] = p\n\n # check duplication and collision\n Q_id = get_Q_id(Q, j)\n haskey(VISITED, Q_id) && continue\n !no_fast_collision_check && collide(S.Q, p.q, i) && continue\n no_fast_collision_check && collide(S.Q, Q) && continue\n\n # create new search node\n S_new = SuperNode(\n Q = Q,\n next = j,\n id = Q_id,\n parent_id = S.id,\n h = h_func(Q),\n g = S.g + g_func(S.Q, Q),\n depth = S.depth + 1,\n )\n\n # insert\n enqueue!(OPEN, S_new, S_new.f)\n VISITED[S_new.id] = S_new\n end\n print_progress!(S, loop_cnt, force = isempty(OPEN))\n end\n\n VERBOSE > 1 && println()\n end\n\n VERBOSE > 0 && @info @sprintf(\"\\t%6.4f sec: failed to find solution\\n\", elapsed())\n return (nothing, roadmaps)\nend\n\n\"\"\"implementation of vertex expansion\"\"\"\nfunction expand!(\n connect::Function,\n sampler::Function,\n v_from::Node{State},\n roadmap::Vector{Node{State}},\n min_dist_thread::Float64,\n num_vertex_expansion::Int64,\n steering_depth::Int64,\n)::Bool where {State<:AbsState}\n\n updated = false\n for _ = 1:num_vertex_expansion\n # steering\n q_new = steering(connect, sampler(), v_from.q, steering_depth)\n # check space-filling metric\n if minimum(v -> dist(v.q, q_new), roadmap) > min_dist_thread\n # add vertex and edges\n u = Node(\n q_new,\n length(roadmap) + 1,\n map(v -> v.id, filter(v -> connect(q_new, v.q), roadmap)),\n )\n push!(roadmap, u)\n # update neighbors\n foreach(\n v -> push!(v.neighbors, u.id),\n filter(v -> connect(v.q, q_new), roadmap),\n )\n updated = true\n end\n end\n return updated\nend\n\nfunction steering(\n connect::Function,\n q_rand::State,\n q_near::State,\n steering_depth::Int64,\n)::State where {State<:AbsState}\n\n q_h = q_rand # probably unsafe -> eventually safe\n if !connect(q_near, q_h)\n # binary search\n q_l = q_near # safe\n for _ = 1:steering_depth\n q = get_mid_status(q_l, q_h)\n if connect(q_near, q)\n q_l = q\n else\n q_h = q\n end\n end\n q_h = q_l\n end\n return q_h\nend\n\n\"\"\"generate initial roadmaps via RRT-Connect\"\"\"\nfunction gen_RRT_connect_roadmaps(\n config_init::Vector{State},\n config_goal::Vector{State},\n connect::Function;\n steering_depth::Int64 = 2,\n epsilon::Union{Float64,Nothing} = 0.2,\n TIME_LIMIT::Union{Nothing,Real} = 30,\n)::Union{Nothing,Vector{Vector{Node{State}}}} where {State<:AbsState}\n\n # utilities for timeout\n t_s = now()\n elapsed() = elapsed_sec(t_s)\n timeover() = TIME_LIMIT != nothing && elapsed() > TIME_LIMIT\n\n N = length(config_init)\n roadmaps = Vector{Vector{Node{State}}}()\n for i = 1:N\n rmp = gen_RRT_connect_roadmap(\n i,\n config_init[i],\n config_goal[i],\n connect;\n steering_depth = steering_depth,\n epsilon = epsilon,\n TIME_LIMIT = (isnothing(TIME_LIMIT) ? nothing : TIME_LIMIT - elapsed()),\n )\n isnothing(rmp) && return nothing\n push!(roadmaps, rmp)\n end\n return roadmaps\nend\n\nfunction gen_RRT_connect_roadmap(\n i::Int64,\n q_init::State,\n q_goal::State,\n connect::Function;\n steering_depth::Int64 = 2,\n epsilon::Union{Float64,Nothing} = 0.2,\n TIME_LIMIT::Union{Nothing,Real} = 30,\n)::Union{Nothing,Vector{Node{State}}} where {State<:AbsState}\n\n # utilities for timeout\n t_s = now()\n elapsed() = elapsed_sec(t_s)\n timeover() = TIME_LIMIT != nothing && elapsed() > TIME_LIMIT\n\n # define sampler\n sampler = gen_uniform_sampling(q_init)\n\n # re-define connect function\n conn(q_from::State, q_to::State)::Bool = begin\n # check distance\n !(isnothing(epsilon) || dist(q_from, q_to) <= epsilon) && return false\n\n !connect(q_from, q_to, i) && return false\n\n return true\n end\n\n conn(q::State)::Bool = connect(q, i)\n\n # special case\n if conn(q_init, q_goal)\n v_init = Node(q_init, 1, [2])\n v_goal = Node(q_goal, 2, Vector{Int64}())\n conn(q_goal, q_init) && push!(v_goal.neighbors, v_init.id)\n return [v_init, v_goal]\n end\n\n # store all samples\n V1 = [q_init]\n V2 = [q_goal]\n\n V = V1\n\n # main loop\n iter = 0\n while !timeover()\n iter += 1\n from_start = (iter % 2 == 1)\n\n (flg, q_new) = extend!(conn, sampler(), V1, from_start, steering_depth)\n if flg != :trapped &&\n extend!(conn, q_new, V2, !from_start, steering_depth)[1] == :reached\n # fix tree\n if from_start\n V1, V2 = V2, V1\n end\n # create roadmap, insert vertices\n roadmap = [Node{State}(q_init, 1, []), Node{State}(q_goal, 2, [])]\n foreach(q -> push!(roadmap, Node{State}(q, length(roadmap) + 1, [])), V1[2:end])\n foreach(q -> push!(roadmap, Node{State}(q, length(roadmap) + 1, [])), V2[2:end])\n # create roadmap, insert edges\n for (k, v_from) in enumerate(roadmap)\n for (l, v_to) in enumerate(roadmap)\n if k != l && conn(v_from.q, v_to.q)\n push!(v_from.neighbors, v_to.id)\n end\n end\n timeover() && return nothing\n end\n return roadmap\n end\n\n # swap tree\n V1, V2 = V2, V1\n end\n\n return nothing\nend\n\n\"\"\"used in RRT-Connect\"\"\"\nfunction extend!(\n connect::Function,\n q_rand::State, # sampled point\n V::Vector{State}, # vertices\n from_start::Bool, # true -> tree rooted C_init, false -> tree rooted C_goal\n steering_depth::Int64,\n)::Tuple{Symbol,State} where {State<:AbsState}\n\n # find nearest existing vertex\n q_near =\n (from_start ? argmin(q -> dist(q, q_rand), V) : argmin(q -> dist(q_rand, q), V))\n flg = :reached\n\n q_l = q_near # safe sample\n q_h = q_rand # probably unsafe sample -> eventually safe\n\n # steering, binary search\n if from_start ? !connect(q_near, q_h) : !(connect(q_h) && connect(q_h, q_near))\n flg = :trapped\n for _ = 1:steering_depth\n q = from_start ? get_mid_status(q_l, q_h) : get_mid_status(q_h, q_l)\n if from_start ? connect(q_near, q) : (connect(q) && connect(q, q_near))\n flg = :advanced\n q_l = q\n else\n q_h = q\n end\n end\n q_h = q_l\n end\n\n flg != :trapped && push!(V, q_h)\n return (flg, q_h)\nend\n\n\"\"\"generate id of search nodes\"\"\"\nfunction get_Q_id(Q::Vector{Node{State}}, next::Int64)::String where {State<:AbsState}\n return @sprintf(\"%s_%d\", join([v.id for v in Q], \"-\"), next)\nend\n\n\"\"\"obtain solution from search nodes by backtracking\"\"\"\nfunction backtrack(\n S_fin::SuperNode{State},\n VISITED::Dict{String,SuperNode{State}},\n)::Vector{Vector{Node{State}}} where {State<:AbsState}\n\n S = S_fin\n solution = Vector{Vector{Node{State}}}()\n while S.parent_id != nothing\n pushfirst!(solution, S.Q)\n S = VISITED[S.parent_id]\n end\n pushfirst!(solution, S.Q)\n return solution\nend\n\nend\n", "meta": {"hexsha": "a0f344f9efe7e3f1b7b10897d63f3374e0abb4ca", "size": 14060, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solvers/sssp.jl", "max_stars_repo_name": "Kei18/sssp", "max_stars_repo_head_hexsha": "f9959c5751c9efd1a25a1d01df4bf7b304883b76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-02T11:23:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:30:07.000Z", "max_issues_repo_path": "src/solvers/sssp.jl", "max_issues_repo_name": "Kei18/sssp", "max_issues_repo_head_hexsha": "f9959c5751c9efd1a25a1d01df4bf7b304883b76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/sssp.jl", "max_forks_repo_name": "Kei18/sssp", "max_forks_repo_head_hexsha": "f9959c5751c9efd1a25a1d01df4bf7b304883b76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3017241379, "max_line_length": 92, "alphanum_fraction": 0.5600284495, "num_tokens": 3758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24333894270930437}} {"text": "###################################################\n## selection.jl\n## Build graph for scenario-based network flow method to solve full problem\n## Authors: Arthur Delarue, Sébastien Martin, 2018\n###################################################\n\n\"\"\"\n Represents a node in scenario graph\n Required attributes:\n - id::Int : unique reference of node\n\"\"\"\nabstract type ScenarioNode end\n\n\"\"\"\n Node in scenario graph, represents buses arriving at the beginning of a route for a school\n\"\"\"\nstruct ArrivalNode <: ScenarioNode\n id::Int\n\n \"School associated with this node\"\n school::Int\n \"Route corresponding to the node\"\n route::Route\n \"Total service time of route\"\n serviceTime::Float64\n \"Scenario number\"\n scenario::Int\nend\n\n\"\"\"\n Node in scenario graph, represents buses departing from a school\n\"\"\"\nstruct DepartureNode <: ScenarioNode\n id::Int\n\n \"School associated with this node\"\n school::Int\n \"Capacity, i.e. number of buses that can leave\"\n capacity::Int\n \"Scenario number\"\n scenario::Int\nend\n\n\"\"\"\n Node in scenario graph, represents a bus yard\n\"\"\"\nstruct YardNode <: ScenarioNode\n id::Int\n\n \"Yard associated with this node\"\n yard::Int\nend\n\n\"\"\"\n represents graph of scenarios for schools (master problem)\n\"\"\"\nmutable struct ScenarioGraph\n \"graph object\"\n graph::DiGraph\n \"list of nodes\"\n nodes::Vector{ScenarioNode}\n \"dictionary mapping node type to node ids\"\n nodeTypes::Dict{Symbol,Vector{Int}}\n \"dictionary mapping pairs of nodes to costs\"\n costs::Dict{Tuple{Int,Int}, Float64}\n \"number of scenarios per school\"\n numScenarios::Vector{Int}\nend\n\n\"\"\"\n Assumes the scenarios have already been computed in the data\n Builds ScenarioGraph using this input\n\"\"\"\nfunction buildScenarioGraph(data::SchoolBusData)\n if !data.withRoutingScenarios\n error(\"Cannot compute scenario graph without scenarios\")\n end\n nodes = ScenarioNode[]\n nodeTypes = Dict(elt => Int[] for elt in [:YardNode, :ArrivalNode, :DepartureNode])\n # get the yard nodes\n yardNodes, currentNodeId = getYardNodes!(data, nodeTypes)\n append!(nodes, yardNodes)\n numScenarios = [length(data.scenarios[sID]) for sID=eachindex(data.schools)]\n for schoolID = eachindex(data.schools)\n for scenarioNum = 1:numScenarios[schoolID]\n schoolNodes, currentNodeId = getSchoolScenarioNodes!(data, schoolID,\n currentNodeId, scenarioNum,\n nodeTypes)\n append!(nodes, schoolNodes)\n end\n end\n graph = DiGraph(length(nodes))\n costs = Dict{Tuple{Int,Int}, Float64}()\n possibleEdgeTypes = [(:DepartureNode, :ArrivalNode), (:DepartureNode, :YardNode),\n (:ArrivalNode, :DepartureNode), (:YardNode, :ArrivalNode)]\n for (type1, type2) in possibleEdgeTypes\n for idx1 in nodeTypes[type1], idx2 in nodeTypes[type2]\n node1 = nodes[idx1]\n node2 = nodes[idx2]\n edgeWasAdded, cost = createEdge!(data, graph, node1, node2)\n if edgeWasAdded\n costs[node1.id, node2.id] = cost\n end\n end\n end\n return ScenarioGraph(graph, nodes, nodeTypes, costs, numScenarios)\nend\n\n\"\"\"\n Get nodes for one scenario for a given school\n Args:\n data::SchoolBusData : the data\n schoolId::Int : the id of the school\n currentNodeId : id of node, incremented for each new node\n scenarioNum : id of scenario\n nodeTypes : the attributes of the ScenarioGraph that we are updating\n Returns:\n the nodes for that scenario\n the id of the current node (to be passed along to the next call)\n\"\"\"\nfunction getSchoolScenarioNodes!(data::SchoolBusData, schoolID::Int,\n currentNodeId::Int, scenarioNum::Int,\n nodeTypes::Dict{Symbol, Vector{Int}})\n schoolNodes = ScenarioNode[]\n scenario = data.scenarios[schoolID][scenarioNum]\n for routeID in scenario.routeIDs\n route = data.routes[schoolID][routeID]\n # create arrival nodes\n push!(schoolNodes, ArrivalNode(currentNodeId, schoolID, route,\n serviceTime(data, schoolID, route),\n scenario.id))\n push!(nodeTypes[:ArrivalNode], currentNodeId)\n currentNodeId += 1\n end\n push!(schoolNodes, DepartureNode(currentNodeId,schoolID,length(scenario.routeIDs),scenarioNum))\n push!(nodeTypes[:DepartureNode], currentNodeId)\n currentNodeId += 1\n return schoolNodes, currentNodeId\nend\n\n\"\"\"\n Get nodes for yards\n\"\"\"\nfunction getYardNodes!(data::SchoolBusData, nodeTypes::Dict{Symbol,Vector{Int}})\n yardNodes = ScenarioNode[]\n nodeId = 1\n for yard in data.yards\n push!(yardNodes, YardNode(nodeId, yard.id))\n push!(nodeTypes[:YardNode], nodeId)\n nodeId += 1\n end\n return yardNodes, nodeId\nend\n\n\"\"\"\n Decide whether a bus from one school can serve another school (time feasible)\n By convention, school 1 is the school from which the bus would depart in the morning, and\n the route belings to school 2\n\"\"\"\nfunction isFeasibleInTime(data::SchoolBusData, school1::Int, school2::Int,\n route::Route, routeTime::Float64)\n return (data.schools[school1].starttime +\n traveltime(data, data.schools[school1], data.stops[school2][route.stops[1]]) +\n routeTime + data.schools[school2].dwelltime <= data.schools[school2].starttime)\nend\n\n\"\"\"\n Add edge between two nodes and compute cost of the edge\n\"\"\"\nfunction createEdge!(data::SchoolBusData, graph::DiGraph,\n node1::ScenarioNode, node2::ScenarioNode)\n edgeWasAdded = false\n cost = nothing\n return edgeWasAdded, cost\nend\nfunction createEdge!(data::SchoolBusData, graph::DiGraph,\n node1::DepartureNode, node2::ArrivalNode)\n edgeWasAdded = false\n if node1.school != node2.school\n # can only go to another school and route must be feasible\n if isFeasibleInTime(data, node1.school, node2.school,\n node2.route, node2.serviceTime)\n edgeWasAdded = add_edge!(graph, node1.id, node2.id)\n end\n end\n return edgeWasAdded, 0.\nend\nfunction createEdge!(data::SchoolBusData, graph::DiGraph,\n node1::DepartureNode, node2::YardNode)\n return add_edge!(graph, node1.id, node2.id), 0.\nend\nfunction createEdge!(data::SchoolBusData, graph::DiGraph,\n node1::ArrivalNode, node2::DepartureNode)\n edgeWasAdded = false\n if node1.school == node2.school && node1.scenario == node2.scenario\n edgeWasAdded = add_edge!(graph, node1.id, node2.id)\n end\n return edgeWasAdded, 0.\nend\nfunction createEdge!(data::SchoolBusData, graph::DiGraph,\n node1::YardNode, node2::ArrivalNode)\n return add_edge!(graph, node1.id, node2.id), 1.\nend\n\n\n\"\"\"\n Wrapper function replacing LightGraphs.out_edges since it was deprecated\n Returns a generator with the desired edges\n\"\"\"\nfunction edges_out(graph::DiGraph, node::Int)\n return (Edge(node, j) for j in outneighbors(graph, node))\nend\n\n\"\"\"\n Wrapper function replacing LightGraphs.in_edges since it was deprecated\n Returns a generator with the desired edges\n\"\"\"\nfunction edges_in(graph::DiGraph, node::Int)\n return (Edge(j, node) for j in inneighbors(graph, node))\nend\n\n\"\"\"\n Flow method for scenario selection\n Args:\n - the data\n - the scenario graph we've constructed\n Returns:\n - a vector of length the number of schools, containing the index of\n the scenario that is used for each school\n\"\"\"\nfunction selectScenario(data::SchoolBusData, sg::ScenarioGraph; args...)\n edgeCost(edge::Edge) = sg.costs[src(edge), dst(edge)]\n\n model = Model(solver = GurobiSolver(Threads=getthreads(), MIPGap=0.01; args...))\n\n @variable(model, useScenario[i=eachindex(data.schools), j=1:sg.numScenarios[i]], Bin)\n @variable(model, busFlow[edge=edges(sg.graph)] >= 0, Int)\n\n @constraint(model, capacityDeparture[i=sg.nodeTypes[:DepartureNode]],\n sum(busFlow[edge] for edge=edges_out(sg.graph, i)) <= sg.nodes[i].capacity)\n @constraint(model, capacityArrival[i=sg.nodeTypes[:ArrivalNode]],\n sum(busFlow[edge] for edge=edges_out(sg.graph, i)) ==\n useScenario[sg.nodes[i].school, sg.nodes[i].scenario])\n\n @constraint(model, oneScenario[i=eachindex(data.schools)],\n sum(useScenario[i,j] for j=1:sg.numScenarios[i]) == 1)\n\n @constraint(model, flowConservation[i=vertices(sg.graph)],\n sum(busFlow[edge] for edge=edges_in(sg.graph, i)) ==\n sum(busFlow[edge] for edge=edges_out(sg.graph, i)))\n\n @objective(model, Min, sum(busFlow[edge] * edgeCost(edge) for edge=edges(sg.graph)))\n\n status = solve(model)\n scenarioUsed = [indmax(getvalue(useScenario[i,j])\n for j=1:sg.numScenarios[i]) for i=eachindex(sg.numScenarios)]\n return scenarioUsed\nend\n\n\"\"\"\n Represents node in FullRoutingGraph\n Mandatory attributes:\n - id::Int : unique identifier\n - yardId::Int : yard number\n\"\"\"\nabstract type FullRoutingNode end\n\n\"\"\"\n In full routing flow graph, represents a bus with a certain capacity\n\"\"\"\nstruct BusNode <: FullRoutingNode\n id::Int\n yardId::Int\n \"Route associated with node\"\n route::Route\n \"School associated with node\"\n school::Int\n \"Service time of route\"\n serviceTime::Float64\nend\n\n\"\"\"\n In full routing flow graph, represents a yard\n\"\"\"\nstruct FullYardNode <: FullRoutingNode\n id::Int\n yardId::Int\nend\n\n\"\"\"\n Represents the situation after the scenario has been picked: one bus per route per school\n Similar to ScenarioGraph\n\"\"\"\nmutable struct FullRoutingGraph\n \"The graph itself\"\n graph::DiGraph\n \"list of node objects\"\n nodes::Vector{FullRoutingNode}\n \"dictionary mapping pairs of nodes to costs\"\n costs::Dict{Tuple{Int,Int},Float64}\nend\n\n\"\"\"\n Given routes object (such as that output by flow master problem), set up full routing graph\n\"\"\"\nfunction buildFullRoutingGraph(data::SchoolBusData, usedScenario::Vector{Int})\n nodes = FullRoutingNode[]\n costs = Dict{Tuple{Int,Int},Float64}()\n\n currentId = 1\n # yard nodes\n for yard in data.yards\n push!(nodes, FullYardNode(currentId, yard.id))\n currentId += 1\n end\n # school bus nodes\n for schoolID in eachindex(data.schools)\n scenario = data.scenarios[schoolID][usedScenario[schoolID]]\n for routeID in scenario.routeIDs\n route = data.routes[schoolID][routeID]\n for yard in data.yards\n push!(nodes, BusNode(currentId, yard.id, route, schoolID,\n serviceTime(data, schoolID, route)))\n currentId += 1\n end\n end\n end\n graph = DiGraph(length(nodes))\n # edges\n for node1 in nodes, node2 in nodes\n edgeWasAdded, cost = createEdge!(data, graph, node1, node2)\n if edgeWasAdded\n costs[node1.id, node2.id] = cost\n end\n end\n return FullRoutingGraph(graph, nodes, costs)\nend\n\n\"\"\"\n Method creates an edge between two nodes, with one function per type of node pair\n\"\"\"\nfunction createEdge!(data::SchoolBusData, graph::DiGraph,\n node1::FullRoutingNode, node2::FullRoutingNode)\n return false, 0.\nend\nfunction createEdge!(data::SchoolBusData, graph::DiGraph,\n node1::FullYardNode, node2::BusNode)\n edgeWasAdded, cost = false, 0.\n if node1.yardId == node2.yardId\n edgeWasAdded = add_edge!(graph, node1.id, node2.id)\n cost = traveltime(data, data.yards[node1.yardId],\n data.stops[node2.school][node2.route.stops[1]])\n end\n return edgeWasAdded, cost\nend\nfunction createEdge!(data::SchoolBusData, graph::DiGraph,\n node1::BusNode, node2::FullYardNode)\n edgeWasAdded, cost = false, 0.\n if node1.yardId == node2.yardId\n edgeWasAdded = add_edge!(graph, node1.id, node2.id)\n cost = traveltime(data, data.schools[node1.school], data.yards[node2.yardId])\n end\n return edgeWasAdded, cost\nend\nfunction createEdge!(data::SchoolBusData, graph::DiGraph,\n node1::BusNode, node2::BusNode)\n edgeWasAdded, cost = false, 0.\n if node1.yardId == node2.yardId && node1.school != node2.school\n if isFeasibleInTime(data, node1.school,\n node2.school, node2.route, node2.serviceTime)\n edgeWasAdded = add_edge!(graph, node1.id, node2.id)\n cost = traveltime(data, data.schools[node1.school],\n data.stops[node2.school][node2.route.stops[1]])\n end\n end\n return edgeWasAdded, cost\nend\n\n\"\"\"\n Given a full routing graph, constructs a YardId => node dictionary\n\"\"\"\nfunction yardToNodeDict(frg::FullRoutingGraph)\n d = Dict{Int,Int}()\n for node in frg.nodes\n if typeof(node) == FullYardNode\n d[node.yardId] = node.id\n end\n end\n return d\nend\n\n\"\"\"\n Bus scheduling problem\n\"\"\"\nfunction solveFullRouting(data::SchoolBusData, frg::FullRoutingGraph; args...)\n model = Model(solver = GurobiSolver(Threads=getthreads(), MIPGap=0.01; args...))\n # variables - morning\n @variable(model, busFlow[edge=edges(frg.graph)], Bin)\n length([node for node in frg.nodes if typeof(node) == FullYardNode]) > 1 &&\n error(\"Too many yards\")\n # variables - yard capacity\n @variable(model, yardCapacity[y=eachindex(frg.nodes);\n typeof(frg.nodes[y]) == FullYardNode] >= 0, Int)\n # a route can be served by at most one bus from a given yard - morning\n @constraint(model, oneBusPerRoute[nodeId=eachindex(frg.nodes);\n typeof(frg.nodes[nodeId]) == BusNode],\n sum(busFlow[edge] for edge = edges_in(frg.graph, nodeId)) == 1)\n # flow conservation constraints - morning\n @constraint(model, flowConservation[nodeId=vertices(frg.graph)],\n sum(busFlow[edge] for edge=edges_in(frg.graph, nodeId)) ==\n sum(busFlow[edge] for edge=edges_out(frg.graph, nodeId)))\n @constraint(model, flowBound[y=eachindex(frg.nodes);\n typeof(frg.nodes[y]) == FullYardNode],\n sum(busFlow[edge] for edge=edges_out(frg.graph, y)) <= yardCapacity[y])\n # minimize the total cost of buses (First Order = total number of bus)\n @objective(model, Min, sum(yardCapacity[y]\n for (y,node)=enumerate(frg.nodes) if typeof(node) == FullYardNode))\n status = solve(model)\n flows = Dict(edge => getvalue(busFlow[edge]) for edge=edges(frg.graph))\n return interpretFlows!(data, frg, flows)\nend\n\n\"\"\"\n Given flows, get final buses\n\"\"\"\nfunction interpretFlows!(data::SchoolBusData, frg::FullRoutingGraph, flows::Dict)\n finalBuses = Bus[]\n currentBusId = 1\n dict = yardToNodeDict(frg)\n for yard in data.yards\n yardNode = dict[yard.id]\n yardIsEmpty = false\n # keep following bus routes until yard is empty\n while !yardIsEmpty\n schools, routes = followBusAlongRoute!(frg, flows, yardNode)\n if isempty(schools)\n yardIsEmpty = true\n else\n push!(finalBuses, Bus(currentBusId, yard.id, schools, routes))\n currentBusId += 1\n end\n end\n end\n return finalBuses\nend\n\n\"\"\"\n Extract a bus route from a flows object, removing flows as they are found\n\"\"\"\nfunction followBusAlongRoute!(frg::FullRoutingGraph, flows::Dict, yardNode::Int)\n schools, routes = Int[], Int[]\n if yardNode == -1 && length(flows) == 0\n return schools, routes\n end\n currentNode = yardNode\n backToYard = false\n while !backToYard\n for edge in edges_out(frg.graph, currentNode)\n if flows[edge] > 0.5\n if typeof(frg.nodes[dst(edge)]) == BusNode\n push!(schools, frg.nodes[dst(edge)].school)\n push!(routes, frg.nodes[dst(edge)].route.id)\n currentNode = dst(edge)\n else\n backToYard = true\n end\n flows[edge] = 0.\n break\n end\n end\n if isempty(schools) # couldn't find anything leading out of the yard\n backToYard = true\n end\n end\n return schools, routes\nend\n\nfunction routeBuses!(data::SchoolBusData; args...)\n sg = buildScenarioGraph(data)\n data.usedScenario = selectScenario(data, sg; args...)\n frg = buildFullRoutingGraph(data, data.usedScenario)\n data.buses = solveFullRouting(data, frg; args...)\n data.withFinalBuses = true\n return data\nend\n", "meta": {"hexsha": "fa53c0bd7864a75731b1cea76a8ac112118f00c7", "size": 17055, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/selection.jl", "max_stars_repo_name": "jihoyeo/SchoolBusRouting", "max_stars_repo_head_hexsha": "7d49b5968d34466b4c606d6bf2e1b28e5c6abfe2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-28T10:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T17:53:41.000Z", "max_issues_repo_path": "src/selection.jl", "max_issues_repo_name": "jihoyeo/SchoolBusRouting", "max_issues_repo_head_hexsha": "7d49b5968d34466b4c606d6bf2e1b28e5c6abfe2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-18T15:26:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T01:00:56.000Z", "max_forks_repo_path": "src/selection.jl", "max_forks_repo_name": "jihoyeo/SchoolBusRouting", "max_forks_repo_head_hexsha": "7d49b5968d34466b4c606d6bf2e1b28e5c6abfe2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-09-03T13:52:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-14T02:44:58.000Z", "avg_line_length": 35.0925925926, "max_line_length": 99, "alphanum_fraction": 0.631017297, "num_tokens": 4191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24318841659104834}} {"text": "using Pkg;Pkg.activate(@__DIR__)\nusing Comrade\nusing PyCall\nusing Plots\n\nusing GalacticOptim, Optim\nusing Zygote\nusing Parameters\nusing Distributions\nusing SpeedMapping\nusing AdvancedHMC\nusing Dynesty\n\nload_ehtim()\n@pyimport eht_dmc as ed\n\n# To download the data visit https://doi.org/10.25739/g85n-f134\nobs = ehtim.obsdata.load_uvfits(joinpath(@__DIR__, \"SR1_M87_2017_096_hi_hops_netcal_StokesI.uvfits\"))\nobs.add_scans()\n\nobsavg = obs.avg_coherent(0.0, scan_avg=true)\n\nimg = ehtim.image.make_empty(512, μas2rad(250.0), obs.ra, obs.dec, obs.rf, obs.source)\nimg = img.add_gauss(1.0, [μas2rad(40.0), μas2rad(30.0), π/3, 0.0, 0.0])\n\nobslist = obsavg.split_obs()\n\ngainoff = 0.0\ngainp = Dict(\"AA\"=> 0.01,\n \"AP\" => 0.1,\n \"AZ\" => 0.1,\n \"JC\" => 0.1,\n \"LM\" => 0.2,\n \"PV\" => 0.1,\n \"SM\" => 0.1,\n \"SR\" => 0.1)\nobsim = img.observe_same(ehtim.obsdata.merge_obs(obslist[10:15]), ttype=\"fast\", gainp=gainp, gain_offset=gainoff, ampcal=false, phasecal=false, stabilize_scan_phase=true, stabilize_scan_amp=true)\n# now get cal table\nctable = ehtim.calibrating.self_cal.self_cal(obsim, img, caltable=true)\nehtim.caltable.save_caltable(ctable, obsim, datadir=joinpath(@__DIR__ ,\"CaltableTest\"))\n\n\ndvis = extract_vis(obsim)\ndlcamp = extract_lcamp(obsim; count=\"min\")\ndcphase = extract_cphase(obsim, count=\"min-cut0bl\")\ndamp = extract_amp(obsim)\nst = scantable(dvis)\n\ngcache = Comrade.GainCache(st)\n\nstruct Model{G}\n gcache::G\nend\n\nfunction Model(st::Comrade.ScanTable)\n gcache = Comrade.GainCache(st)\n return Model{typeof(gcache)}(gcache)\nend\n\nfunction (mod::Model)(θ)\n @unpack f, σ, τ, ξ, gamp, gphase = θ\n g = gamp.*cis.(gphase)\n m = f*rotated(stretched(Gaussian(), σ*τ, σ), ξ)\n Comrade.GainModel(mod.gcache, g, m)\nend\n\n# define the priors\ndistamp = (AA = LogNormal(0.0, 0.1),\n AP = LogNormal(0.0, 0.1),\n LM = LogNormal(0.0, 0.2),\n AZ = LogNormal(0.0, 0.1),\n JC = LogNormal(0.0, 0.1),\n PV = LogNormal(0.0, 0.1),\n #SM = LogNormal(0.0, 0.1)\n )\ndistphase = (AA = Normal(0.0, 1e-4),\n AP = Normal(0.0, π),\n LM = Normal(0.0, π),\n AZ = Normal(0.0, 1.0*π),\n JC = Normal(0.0, 1.0*π),\n PV = Normal(0.0, π),\n #SM = Normal(0.0, 1.0*π),\n )\nprior = (\n f = Uniform(0.9, 1.1),\n σ = Uniform(μas2rad(10.0), μas2rad(30.0)),\n τ = Uniform(0.1, 1.0),\n ξ = Uniform(-π/2, π/2),\n gamp = Comrade.GainPrior(distamp, st),\n gphase = Comrade.GainPrior(distphase, st)\n )\n# Now form the posterior\n\nmms = Model(st)\n\ncllklhd = RadioLikelihood(dlcamp, dcphase)\nclpost = Posterior(cllklhd, prior, mms)\n\nlklhd = RadioLikelihood(dvis)#damp, dcphase)\npost = Posterior(lklhd, prior, mms)\ntpost = asflat(post)\n# We will use HMC to sample the posterior.\n# First to reduce burn in we use pathfinder\nndim = dimension(tpost)\nf, tr = GalacticOptim.OptimizationFunction(post, GalacticOptim.AutoForwardDiff{15}())\n#x0 = inverse(tr, rand(post.prior))\n\nx0 = rand(post.prior, 50)\nq, ϕ, inds = multipathfinder(clpost, 100; init_params=x0, ndraws_per_run=50)\n\nres = map(1:150) do i\n #x0 = xx\n #x0.gphase .= randn(length(xx.gphase))\n #x0.gamp .= 1 .+ 0.2*randn(length(xx.gamp))\n prob = GalacticOptim.OptimizationProblem(f, randn(ndim), nothing)\n #sol, xopt = solve(prob, BBO_adaptive_de_rand_1_bin_radiuslimited(), tr; maxiters=200_000)\n\n #xopt = rand(post.prior)\n #prob = GalacticOptim.OptimizationProblem(f, sol.u, nothing)\n sol, xopt = solve(prob, LBFGS(), tr; iterations=2_000)\n @info \"$i/50 $(sol.minimum)\"\n xopt, sol.minimum\nend\n\n\n\nmetric = DenseEuclideanMetric(ndim)\nchain, stats = sample(post, HMC(;metric), 14_000; nadapts=10_000, init_params=res[ind[1]][1])\n", "meta": {"hexsha": "2df9cc1eaea48e0dfb6e887eb80d024a7091b36f", "size": 3845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/gaintest.jl", "max_stars_repo_name": "ptiede/Comrade.jl", "max_stars_repo_head_hexsha": "1037ac3d638112606cffcf7943770f0d7028f6ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-02T16:20:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T16:20:38.000Z", "max_issues_repo_path": "examples/gaintest.jl", "max_issues_repo_name": "ptiede/Comrade.jl", "max_issues_repo_head_hexsha": "1037ac3d638112606cffcf7943770f0d7028f6ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-01-14T02:04:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T17:02:02.000Z", "max_forks_repo_path": "examples/gaintest.jl", "max_forks_repo_name": "ptiede/Comrade.jl", "max_forks_repo_head_hexsha": "1037ac3d638112606cffcf7943770f0d7028f6ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-27T17:41:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T17:41:25.000Z", "avg_line_length": 29.8062015504, "max_line_length": 196, "alphanum_fraction": 0.6343302991, "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24318841007703076}} {"text": "# User-level methods to compute lightcurves\n\nstruct Lightcurve{T<:Real}\n dt::T # Exposure time\n tobs::Vector{T} # Observed times\n fobs::Vector{T} # Observed flux\n eobs::Vector{T} # Measurement errors\n nobs::Int64 # number of flux measurements\n flux::Vector{T} # Computed model flux\n dfdu::Matrix{T} # Derivative of flux wrt limbdark coefficients\n dfdk::Matrix{T} # Derivatives wrt the radius ratios\n dfdq0::Matrix{T} # Derivatives wrt initial Nbody Cartesian coordinates and masses\n dfdr::Vector{T} # Derivatives wrt stellar radius\n\n # Transit parameters\n u_n::Vector{T} # Limbdark coefficients\n k::Vector{T} # radius ratios\n rstar::Vector{T} # Stellar radius\n\n # Interal arrays/values\n dtinv::T # Inverse of the exposure time\n dbdq0::Vector{T} # derivative of the impact parameter wrt the Nbody initial conditions\n n_params::Int64 # Number of nbody model parameters\n do_grad::Bool # Compute gradients or not\n\n function Lightcurve(dt::T, tobs::Vector{T}, fobs::Vector{T}, eobs::Vector{T}, u_n::Vector{T}, k::Vector{T}, rstar::T, n_params::Int64=0) where T<:Real\n @assert (length(tobs) == length(fobs)) && (length(tobs) == length(eobs)) \"Data arrays are different sizes\"\n @assert n_params >= 0 \"Number of model parameters must be a positive integer\"\n n_params > 0 ? do_grad = true : do_grad = false\n nobs = length(tobs)\n flux = zeros(T,nobs)\n dtinv = dt == 0.0 ? 0.0 : inv(dt)\n dfdu = zeros(T, nobs, length(u_n))\n dfdk = zeros(T, nobs, length(k))\n dfdq0 = zeros(T, nobs, n_params)\n dbdq0 = zeros(T, n_params)\n dfdr = zeros(T, nobs)\n return new{T}(dt,tobs,fobs,eobs,nobs,flux,dfdu,dfdk,dfdq0,dfdr,u_n,k,[rstar],dtinv,dbdq0,n_params,do_grad)\n end\nend\n\n\"\"\"Zero out the model arrays\"\"\"\nfunction zero_out!(lc::Lightcurve{T}) where T<:Real\n lc.dfdu .= 0.0\n lc.dfdk .= 0.0\n lc.dfdq0 .= 0.0\n lc.dfdr .= 0.0\n lc.flux .= 0.0\nend\n\n# Normalize the exposure integration by the exposure time.\nfunction normalize!(lc::Lightcurve{T}, ia::IntegralArrays{T}) where T<:Real\n lc.flux .*= lc.dtinv # Divide by exposure time to get average flux\n if lc.do_grad\n # Do the same for derivatives\n lc.dfdk .*= lc.dtinv\n lc.dfdu .*= lc.dtinv\n lc.dfdq0 .*= lc.dtinv\n lc.dfdr .*= lc.dtinv\n end\nend\n\n# If non-integrated exposure, do nothing\n@inline normalize!(lc::Lightcurve{T}, ia::T) where T<:Real = nothing\n\nfunction find_transit_time(t0::T, h::T, points::AbstractMatrix{T}) where T<:Real\n tt = find_zero(t->compute_impact_parameter(t, t0, h, points), t0)\n return tt\nend\n\nfunction points_of_contact_4(tt::T,t0::T,h::T,points::AbstractMatrix{T},k::T) where T<:Real\n t1 = find_zero(t -> (1.0+k-compute_impact_parameter(t,t0,h,points)), tt-h)\n t2 = find_zero(t -> (1.0-k-compute_impact_parameter(t,t0,h,points)), tt-h)\n t3 = find_zero(t -> (1.0-k-compute_impact_parameter(t,t0,h,points)), tt+h)\n t4 = find_zero(t -> (1.0+k-compute_impact_parameter(t,t0,h,points)), tt+h)\n return SVector(t1,t2,t3,t4)\nend\n\nfunction points_of_contact_2(t0::T,tt::T,h::T,points::AbstractMatrix{T},k::T) where T<:Real\n t1 = find_zero(t -> (1.0+k-compute_impact_parameter(t,t0,h,points)), tt-h)\n t4 = find_zero(t -> (1.0+k-compute_impact_parameter(t,t0,h,points)), tt+h)\n return SVector(t1,t4)\nend\n\nfunction compute_lightcurve!(lc::Lightcurve{T}, ts::TransitSeries{T, ProvidedTimes}; tol::T=1e-6, maxdepth::Int64=6) where T<:Real\n\n zero_out!(lc) # Zero out model arrays\n\n # Check if we're doing an integrated lightcurve\n ia = lc.dt == 0.0 ? 0.0 : IntegralArrays(lc.do_grad ? (lc.n_params + length(lc.u_n) + length(lc.k) + 2) : 1, maxdepth, tol) # Plus 2 for flux and rstar\n\n # Make transit structure (will be updated with proper r and b later)\n trans = transit_init(lc.k[1], 0.0, lc.u_n, lc.do_grad)\n\n # Iterate over each transit time and sum Lightcurve\n rstar = lc.rstar[1]\n for it in eachindex(ts.times)\n # check for transit\n t0 = ts.times[it] # Get \"data\" transit time (expansion point)\n ib = ts.bodies[it] # Get transiting body\n\n tt = try\n # Compute the transit time by finding where the x component of\n # the impact parameter is equal to zero\n # This assumes the body crosses the mid plane during the transit\n find_transit_time(t0, ts.h, @views(ts.points[ib,it,:,:]./rstar))\n catch e\n # If no convergence, just use the supplied transit time\n t0\n end\n\n # Get the impact parameter at the transit midpoint (computed above)\n b0 = compute_impact_parameter(t0, tt, ts.h, @views(ts.points[ib,it,:,:]./rstar))\n if b0 > 1.0+lc.k[ib-1]; continue; end\n\n # Compute points of contact\n # If grazing transit, only two points\n if (b0 + lc.k[ib-1]) >= 1.0\n tc = points_of_contact_2(t0, tt, ts.h, @views(ts.points[ib,it,:,:]./rstar), lc.k[ib-1])\n else\n tc = points_of_contact_4(t0, tt, ts.h, @views(ts.points[ib,it,:,:]./rstar), lc.k[ib-1])\n end\n\n # Integrate lightcurve\n trans.r = lc.k[ib-1]\n integrate_transit!(ib,it,t0,tc,trans,lc,ts,ia)\n end\n\n # Normalize by exposure time, if needed.\n normalize!(lc, ia)\n return\nend\n\nfunction integrate_transit!(ib::Int64,it::Int64,t0::T,tc::SVector{N,T},trans::Transit_Struct{T},lc::Lightcurve{T},ts::TransitSeries{T},ia::IntegralArrays{T}) where {N, T<:Real}\n nc = length(tc) # Number of points of contact\n dt = lc.dt\n inv_rstar = inv(lc.rstar[1])\n\n # Integrate over each Exposure\n for i in 1:lc.nobs\n tstart = lc.tobs[i] - 0.5*dt\n tend = lc.tobs[i] + 0.5*dt\n\n # Check if remaining exposures are inside transit\n if tstart > tc[end]; break; end # Don't need to continue loop if passed transit\n if tend < tc[1]; continue; end\n\n # Check if points of contact are within exposure\n tlim = [tstart]\n for j in 1:nc\n if tstart < tc[j] && tc[j] < tend\n push!(tlim, tc[j])\n end\n end\n push!(tlim, tend)\n\n # Get series expansion components\n xc = components(@views(ts.points[ib,it,:,1].*inv_rstar), ts.h)\n yc = components(@views(ts.points[ib,it,:,2].*inv_rstar), ts.h)\n\n if lc.do_grad\n n_bodies = length(ts.count)\n dxc = [components(ts.dpoints[ib,it,:,1,k,i].*inv_rstar, ts.h) for i in 1:7, k in 1:n_bodies][:]\n dyc = [components(ts.dpoints[ib,it,:,2,k,i].*inv_rstar, ts.h) for i in 1:7, k in 1:n_bodies][:]\n\n # integrate over exposure\n for j in 1:length(tlim)-1\n integrate_timestep!(t0, tlim[j], tlim[j+1], xc, yc, dxc, dyc, trans, ia, lc.dbdq0, ib-1)\n lc.flux[i] += ia.I_of_f[1]\n lc.dfdq0[i,:] .+= ia.I_of_f[2:1+n_bodies*7]\n lc.dfdk[i,:] .+= ia.I_of_f[2+n_bodies*7:n_bodies*8]\n lc.dfdu[i,:] .+= trans.dgdu' * ia.I_of_f[end-trans.n-1:end-1]\n lc.dfdr[i] += ia.I_of_f[end] * inv_rstar\n end\n else\n # Integrate over exposure\n for j in 1:length(tlim)-1\n integrate_timestep!(t0, tlim[j], tlim[j+1], xc, yc, trans, ia)\n lc.flux[i] += ia.I_of_f[1]\n end\n end\n end\n return\nend\n\nfunction integrate_transit!(ib::Int64,it::Int64,t0::T,tc::SVector{N,T},trans::Transit_Struct{T},lc::Lightcurve{T},ts::TransitSeries{T},ia::T) where {N, T<:Real}\n inv_rstar = inv(lc.rstar[1])\n\n # Compute the flux at each point\n for i in 1:lc.nobs\n # Check if observation is outside of a transit\n if lc.tobs[i] > tc[end]; break; end\n if lc.tobs[i] < tc[1]; continue; end\n\n # Get series expansion components\n xc = components(@views(ts.points[ib,it,:,1].*inv_rstar), ts.h)\n yc = components(@views(ts.points[ib,it,:,2].*inv_rstar), ts.h)\n\n if lc.do_grad\n n_bodies = length(ts.count)\n dxc = [components(ts.dpoints[ib,it,:,1,k,i].*inv_rstar, ts.h) for i in 1:7, k in 1:n_bodies][:]\n dyc = [components(ts.dpoints[ib,it,:,2,k,i].*inv_rstar, ts.h) for i in 1:7, k in 1:n_bodies][:]\n\n compute_flux!(lc.tobs[i], t0, xc, yc, dxc, dyc, lc, trans, i, ki, inv_rstar)\n else\n lc.flux[i] += compute_flux(lc.tobs[i], t0, xc, yc, trans)\n end\n end\n return\nend\n\nfunction integrate_timestep!(t0::T, a::T, b::T, xc::SVector{N,T}, yc::SVector{N,T}, trans::Transit_Struct{T}, ia::IntegralArrays{T}) where {N, T<:Real}\n # Computes the flux as function of time.\n # Closure to be passed to integrator function\n transit_flux! = let trans=trans, t0=t0, xc=xc, yc=yc\n (time::T, flux::Vector{T}) -> begin\n trans.b = compute_impact_parameter(time, t0, xc, yc)\n flux[1] = transit_poly_g(trans)-1\n end\n end\n\n # Integrate transit_flux! over interval [a,b]\n integrate_simpson!(a,b,transit_flux!,ia)\nend\n\nfunction compute_flux(tc::T, t0::T, xc::SVector{N,T}, yc::SVector{N,T}, trans::Transit_Struct{T}) where {N, T<:Real}\n # Compute flux at a particular time\n trans.b = compute_impact_parameter(tc, t0, xc, yc)\n flux = transit_poly_g(trans) - 1\n return flux\nend\n\nfunction integrate_timestep!(t0::T, a::T, b::T, xc::SVector{N,T}, yc::SVector{N,T}, dxc, dyc, trans::Transit_Struct{T}, ia, dbdq0, ki) where {N,T<:Real}\n n_coords = length(dbdq0)\n\n # Map radius ratio index to the gradient array index.\n k_ind = ki + 1 + n_coords\n\n # Compute the flux and derivatives\n transit_flux_grad! = let trans=trans, t0=t0, xc=xc, yc=yc, dbdq0=dbdq0, n_coords = n_coords, k_ind=k_ind\n (time::T, dflux::Vector{T}) -> begin\n trans.b = compute_impact_parameter!(time, t0, xc, yc, dxc, dyc, dbdq0)\n dflux .= 0.0\n dflux[1] = transit_poly_g!(trans)-1 # Flux at time\n dflux[2:1+n_coords] .= trans.dfdrb[2] .* dbdq0 # Gradient wrt the initial conditions\n dflux[k_ind] = trans.dfdrb[1] # radius ratio (derivative of others are zero)\n dflux[end-trans.n-1:end-1] .= trans.dfdg # dfdg (greens basis)\n dflux[end] = -trans.dfdrb[2]*trans.b # dfdrstar * rstar (divide by rstar outside)\n end\n end\n\n # Integrate flux and derivatives over exposure interval [a,b]\n integrate_simpson!(a,b,transit_flux_grad!,ia)\nend\n\nfunction compute_flux!(tc::T, t0::T, xc, yc, dxc, dyc, lc, trans, i, ki, inv_rstar) where T<:Real\n # Compute flux and derivatives\n trans.b = compute_impact_parameter!(tc, t0, xc, yc, dxc, dyc, lc.dbdq0)\n lc.flux[i] += transit_poly_g!(trans) - 1 # Flux\n lc.dfdq0[i,:] .+= trans.dfdrb[2] .* lc.dbdq0 # Derivative wrt initial conditions\n lc.dfdk[i,ki] += trans.dfdrb[1] # Radius ratio\n lc.dfdu[i,:] .+= trans.dgdu' * trans.dfdg # Limbdarkening params\n lc.dfdr[i] += -trans.dfdrb[2]*trans.b*inv_rstar # Stellar radius\n return\nend", "meta": {"hexsha": "28908fa43b904a5df618e4603222544f28d03eae", "size": 11153, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Lightcurve.jl", "max_stars_repo_name": "langfzac/Photodynamics.jl", "max_stars_repo_head_hexsha": "50e4cb5b69b3d420eb7c3d3938726152340511d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T08:40:19.000Z", "max_issues_repo_path": "src/Lightcurve.jl", "max_issues_repo_name": "langfzac/Photodynamics.jl", "max_issues_repo_head_hexsha": "50e4cb5b69b3d420eb7c3d3938726152340511d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-12T17:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-12T17:36:04.000Z", "max_forks_repo_path": "src/Lightcurve.jl", "max_forks_repo_name": "langfzac/Photodynamics.jl", "max_forks_repo_head_hexsha": "50e4cb5b69b3d420eb7c3d3938726152340511d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0867924528, "max_line_length": 176, "alphanum_fraction": 0.608356496, "num_tokens": 3517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24318841007703076}} {"text": "\"Values for units for strings found in option line.\"\nconst units = Dict{ String, Float64 }(\n \"HZ\" => 1e0,\n \"KHZ\" => 1e3,\n \"MHZ\" => 1e6,\n \"GHZ\" => 1e9\n)\n\"The default unit, if not found in option line.\"\nconst default_units = \"GHZ\"\n\n\"Symbols for different parameter formats for strings found in option line\"\nconst parameters = Dict{ String, Symbol }(\n \"S\" => :ScatteringParameters,\n \"Y\" => :AdmittanceParameters,\n \"Z\" => :ImpedanceParameters,\n \"H\" => :HybridHParameters,\n \"G\" => :HybridGParameters,\n)\n\"The default parameter format, if not found in option line.\"\nconst default_parameter = \"S\"\n\n\"Symbols for data format for strings found in option line.\"\nconst formats = Dict{ String, Symbol }(\n \"DB\" => :DecibelAngle,\n \"MA\" => :MagnitudeAngle,\n \"RI\" => :RealImaginary\n)\n\"The default data format, if not found in option line.\"\nconst default_format = \"MA\"\n\"The default characteristic impedance, if not found in option line.\"\nconst default_resistance = 50\n\n\"\"\"\n is_commentline( line )\n\nChecks, if a line is a comment line.\n\"\"\"\nis_comment_line( line ) = length( line ) > 0 && line[ 1 ] == '!'\n\"\"\"\n parse_comment_line( line )\n\nReturns the comment of a comment line.\n\"\"\"\nparse_comment_line( line ) = line[ 2:end ]\n\n\"\"\"\n is_option_line( line )\n\nChecks, if a line is a option line.\n\"\"\"\nis_option_line( line ) = length( line ) > 0 && line[ 1 ] == '#'\n\n\"\"\"\n is_frequency_unit_option( option )\n\nChecks, if a string is a valid unit in an option line.\n\"\"\"\nis_frequency_unit_option( option ) = haskey( units, uppercase( option ) )\n\n\"\"\"\n parse_frequency_unit_option( option )\n\nReturns the multiplier for a unit string in an option line.\n\"\"\"\nparse_frequency_unit_option( option ) = units[ uppercase( option ) ]\n\n\"\"\"\n is_parameter_option( option )\n\nChecks, if a string is a valid parameter format in an option line.\n\"\"\"\nis_parameter_option( option ) = haskey( parameters, uppercase( option ) )\n\n\"\"\"\n parse_parameter_option( option )\n\nReturns the symbol for a valid parameter format string in an option line.\n\"\"\"\nparse_parameter_option( option ) = parameters[ uppercase( option ) ]\n\n\"\"\"\n is_format_option( option )\n\nChecks, if a string is a valid data format in an option line.\n\"\"\"\nis_format_option( option ) = haskey( formats, uppercase( option ) )\n\n\"\"\"\n parse_format_option( option )\n\nReturns the symbol for a valid data format string in an option line.\n\"\"\"\nparse_format_option( option ) = formats[ uppercase( option ) ]\n\n\"\"\"\n is_resistance_option( option )\n\nChecks, if a string is a valid resistance in an option line.\n\"\"\"\nis_resistance_option( option ) = uppercase( option ) == \"R\"\n\n\"\"\"\n parse_resistance_option( option )\n\nReturns the value of the characteristic impedance for a valid resistance string in an option line.\n\"\"\"\nparse_resistance_option( option ) = parse( Float64, option )\n\n\"\"\"\n is_empy_line( line )\n\nChecks, if a line is empty.\n\"\"\"\nis_empy_line( line ) = length( line ) == 0\n\n\"\"\"\n parse_option_line( line )\n\nReturns the option structure for a valid option line.\n\"\"\"\nfunction parse_option_line( line )\n line = uppercase( line )\n\n default = Options()\n unit = default.unit\n parameter = default.parameter\n format = default.format\n resistance = default.resistance\n\n entries = split( line[ 2:end ] )\n\n next_is_resistance = false\n for entry in entries\n if next_is_resistance\n resistance = parse_resistance_option( entry )\n next_is_resistance = false\n else\n if is_frequency_unit_option( entry )\n unit = parse_frequency_unit_option( entry )\n elseif is_parameter_option( entry )\n parameter = parse_parameter_option( entry )\n elseif is_format_option( entry )\n format = parse_format_option( entry )\n else\n next_is_resistance = is_resistance_option( entry )\n end\n end\n end\n Options( unit, parameter, format, resistance )\nend\n\n\"\"\"\n ma2comp( m, a )\n\nConverts a pair of values in magnitude / angle format to a complex number.\n\"\"\"\nma2comp( m, a ) = m * cis( deg2rad( a ) )\n\n\ndB2Mag( dB ) = 10 ^ ( dB / 20 )\n\n\"\"\"\n da2comp( m, a )\n\nConverts a pair of values in dB / angle format to a complex number.\n\"\"\"\nda2comp( d, a ) = ma2comp( dB2Mag( d ), a )\n\n\"Holds conversion functions for parameter format symbols when parsing.\"\nconst ParseConversions = Dict{ Symbol, Function }(\n :RealImaginary => complex,\n :MagnitudeAngle => ma2comp,\n :DecibelAngle => da2comp,\n)\n\n\"\"\"\n parse_data( line, N, [ options ] )\n\nReturns a data point structure for a valid line of a one-port Touchstone file.\n\nFor 3 or more ports, the line should be the concatenation of 3 or more lines from the Touchstone file.\n\"\"\"\nfunction parse_data( line::String, N, options = Options(), version = 1 )\n vals = map( s -> parse( Float64, s ), split( line ) )\n parse_data( vals, N, options, version )\nend\n\n\"\"\"\n parse_data( vals, N, [ options ] )\n\nReturns a data point structure for a vector of numbers from a one-port Touchstone file.\n\nFor 3 or more ports, the array should contain exactly 2N² + 1 values.\n\"\"\"\nfunction parse_data( vals::Array{Float64}, N, options = Options(), version = 1, twoPortDataFlipped = true )\n if length( vals ) != 2N * N + 1\n error( \"Wrong number of values!\" )\n end\n freq = vals[ 1 ] * options.unit\n pairs = zip( vals[ 2:2:end - 1 ], vals[ 3:2:end ] )\n converted = map( pair -> ParseConversions[ options.format ]( pair... ), pairs )\n # renormalize Z, Y, G and H parameters for version 1.0\n if version == 1\n if options.parameter == :ImpedanceParameters\n converted = map( x -> x * options.resistance, converted )\n end\n if options.parameter == :AdmittanceParameters\n converted = map( x -> x / options.resistance, converted )\n end\n if N == 2\n if options.parameter == :HybridGParameters\n converted[ 1 ] /= options.resistance\n converted[ 4 ] *= options.resistance\n end\n if options.parameter == :HybridHParameters\n converted[ 1 ] *= options.resistance\n converted[ 4 ] /= options.resistance\n end\n end\n end\n res = reshape( converted, N, N )\n if N > 2 || ( N == 2 && !twoPortDataFlipped )\n res = permutedims( res, [ 2, 1 ] )\n end\n return DataPoint( freq, res )\nend\n\nfunction parseNoiseData( vals::Array{Float64}, options = Options(), version = 1 )\n if length( vals ) != 5\n error( \"Wrong number of noise data values!\" )\n end\n frequency = vals[ 1 ] * options.unit\n minNoiseFigure = dB2Mag( vals[ 2 ] )\n reflCoeff = ma2comp( vals[ 3 ], vals[ 4 ] )\n effNoiseRes = vals[ 5 ]\n if version == 1\n effNoiseRes *= options.resistance\n end\n return NoiseDataPoint( frequency, minNoiseFigure, reflCoeff, effNoiseRes )\nend\n\nfunction stripCommentFromLine( line )\n comment = \"\"\n strings = split( line, \"!\" )\n if length( strings ) > 1\n comment = join( strings[ 2:end ], \"!\" )\n line = strings[ 1 ]\n end\n return( line, comment)\nend\n\nfunction getValsAndPushComments!( comments, line )\n line, comment = stripCommentFromLine( line )\n if comment != \"\"\n push!( comments, comment )\n end\n vals = map( s -> parse( Float64, s ), split( line ) )\n return vals\nend\n\n\"\"\"\n parse_touchstone_stream( stream, [ ports ] )\n\nReturns a TouchstoneData structure for a valid Touchstone data stream.\n\"\"\"\nfunction parse_touchstone_stream( stream::IO, ports::Integer = 1 )\n version = 1\n options = Options()\n option_line_found = false\n comments = Vector{ String }()\n data = Vector{ DataPoint }()\n noiseData = Vector{ NoiseDataPoint }()\n neededValues = 1 + 2ports * ports\n vals = Vector{ Float64 }()\n keywordparams = Dict{ Symbol, Any }()\n networkdata = false\n noiseDataExpected = false\n twoPortDataFlipped = true\n referenceNextLine = false\n endfound = false\n lastParamFrequency = -1\n for line in eachline( stream )\n if referenceNextLine\n keywordparams[ :Reference ] = parse_reference( split( line ) )\n referenceNextLine = false\n elseif is_empy_line( line )\n ;# nothing\n elseif is_keyword_line( line )\n version = 2\n keyword, params = parse_keyword_line( line )\n keywordparams[ keyword ] = params\n if option_line_found && keyword == :Version\n error( \"V2.0: [Version] 2.0 before option line expected.\" )\n end\n if keyword in unOrderedKeywordSymbols\n keywordString = keywordSymbolStrings[ keyword ]\n if !haskey( keywordparams, :Version ) || keywordparams[ :Version ] != 2\n error( \"V2.0: [Version] keyword before [$( keywordString )] keyword expected.\" )\n end\n if !option_line_found\n error( \"V2.0: Option line before [$( keywordString )] keyword expected.\" )\n end\n if !haskey( keywordparams, :NumberOfPorts )\n error( \"V2.0: [Number of Ports] keyword before [$( keywordString )] keyword expected.\" )\n end\n if haskey( keywordparams, :NetworkData )\n error( \"V2.0: [Network Data] keyword after [$( keywordString )] keyword expected.\" )\n end\n end\n if keyword == :Reference\n if length( keywordparams[ :Reference ] ) == 0\n referenceNextLine = true\n end\n elseif keyword == :NetworkData\n networkdata = true\n if haskey( keywordparams, :NoiseData )\n error( \"V2.0: [Noise Data] keyword after [Network Data] keyword expected.\" )\n end\n if !haskey( keywordparams, :NumberOfFrequencies )\n error( \"V2.0: [Number of Frequencies] keyword before [Network Data] keyword expected.\" )\n end\n elseif keyword == :NumberOfPorts\n ports = keywordparams[ :NumberOfPorts ]\n neededValues = 1 + 2ports * ports\n elseif keyword == :TwoPortDataOrder\n dataOrder = keywordparams[ :TwoPortDataOrder ]\n if dataOrder == \"12_21\"\n twoPortDataFlipped = true\n elseif dataOrder == \"21_12\"\n twoPortDataFlipped = false\n end\n elseif keyword == :NoiseData\n noiseDataExpected = true\n networkdata = false\n elseif keyword == :End\n networkdata = false\n noiseDataExpected = false\n endfound = true\n end\n elseif is_comment_line( line )\n push!( comments, parse_comment_line( line ) )\n elseif !option_line_found && is_option_line( line )\n if haskey( keywordparams, :Version ) && keywordparams[ :Version ] == 2 && haskey( keywordparams, :NumberOfPorts )\n error( \"V2.0: Option line before [Number of Ports] keyword expected.\" )\n end\n options = parse_option_line( line )\n option_line_found = true\n elseif noiseDataExpected\n vals = getValsAndPushComments!( comments, line )\n push!( noiseData, parseNoiseData( vals, options, version ) )\n elseif !haskey( keywordparams, :Version ) || ( keywordparams[ :Version ] == 2 && networkdata )\n newVals = getValsAndPushComments!( comments, line )\n if version == 1\n # V1.0 Noise Data starts, when frequency decreases.\n if length( vals ) == 0\n if newVals[ 1 ] <= lastParamFrequency\n push!( noiseData, parseNoiseData( newVals, options, 1 ) )\n vals = Vector{Float64}()\n noiseDataExpected = true\n end\n lastParamFrequency = newVals[ 1 ]\n end\n # V1.0: not more then 4 value pairs per line. (#7)\n # The first line contains the frequency.\n maxVals = length( vals ) == 0 ? 9 : 8\n if length( newVals ) > maxVals\n error( \"V1.0: more than four complex values in one parameter line.\" )\n end\n end\n vals = [ vals; newVals ]\n if length( vals ) >= neededValues\n push!( data, parse_data( vals, ports, options, version, twoPortDataFlipped ) )\n vals = Vector{Float64}()\n end\n elseif endfound\n error( \"V2.0: Non empty or comment line found after [End] keyword.\" )\n end\n end\n ret = TouchstoneData( data, noiseData, options, comments, keywordparams )\n return ret\nend\n\n\"\"\"\n parse_touchstone_string( in, [ ports ] )\n\nReturns a TouchstoneData structure for a valid Touchstone data string.\n\"\"\"\nparse_touchstone_string( in::String, ports::Integer = 1 ) = parse_touchstone_stream( IOBuffer( in ), ports )\n\n\"\"\"\n parse_touchstone_file( filename, [ ports ] )\n\nReturns a TouchstoneData structure for a valid Touchstone data file.\n\nWhen called without ports, tries to interpret the file extension, such as \".s2p\", or \".S4P\".\n\"\"\"\nfunction parse_touchstone_file( filename::String, ports::Integer = 0 )\n if ports == 0\n extorig = splitext( filename )[ 2 ][ 2: end ]\n ext = uppercase( extorig )\n if ext[ 1 ] == 'S' && ext[ end ] == 'P'\n ports = parse( Int64, ext[ 2:end - 1 ] )\n else\n error( \"File extension ( $( extorig ) ) not recognized, unknown number of ports.\" )\n end\n end\n open( filename ) do io\n parse_touchstone_stream( open( filename ), ports )\n end\nend\n\n# V2.0\n\"Symbols for different keywords\"\nconst keywordStringSymbols = Dict{ String, Symbol }(\n \"VERSION\" => :Version,\n \"NUMBER OF PORTS\" => :NumberOfPorts,\n \"TWO-PORT DATA ORDER\" => :TwoPortDataOrder,\n \"NUMBER OF FREQUENCIES\" => :NumberOfFrequencies,\n \"NUMBER OF NOISE FREQUENCIES\" => :NumberOfNoiseFrequencies,\n \"REFERENCE\" => :Reference,\n \"MATRIX FORMAT\" => :MatrixFormat,\n \"MIXED-MODE ORDER\" => :MixedModeOrder,\n \"BEGIN INFORMATION\" => :BeginInformation,\n \"END INFORMATION\" => :EndInformation,\n \"NETWORK DATA\" => :NetworkData,\n \"NOISE DATA\" => :NoiseData,\n \"END\" => :End,\n)\n\nconst keywordSymbolStrings = Dict{ Symbol, String }(\n :Version => \"Version\",\n :NumberOfPorts => \"Number of Ports\",\n :TwoPortDataOrder => \"Two-Port Data Order\",\n :NumberOfFrequencies => \"Number of Frequencies\",\n :NumberOfNoiseFrequencies => \"Number of Noise Frequencies\",\n :Reference => \"Reference\",\n :MatrixFormat => \"Matrix Format\",\n :MixedModeOrder => \"Mixed-Mode Order\",\n :BeginInformation => \"Begin Information\",\n :EndInformation => \"End Information\",\n :NetworkData => \"Network Data\",\n :NoiseData => \"NoiseData\",\n :End => \"End\",\n)\n\nconst unOrderedKeywordSymbols = [\n :TwoPortDataOrder,\n :NumberOfFrequencies,\n :NumberOfNoiseFrequencies,\n :Reference,\n :MatrixFormat,\n :MixedModeOrder,\n :BeginInformation,\n :EndInformation,\n]\n\n\"\"\"\n is_keyword_line( line )\n\nChecks, if a line is a valid keyword line.\n\"\"\"\nis_keyword_line( line::String ) = length( line ) > 0 && line[ 1 ] == '['\n\nfunction parse_N_params( params, N::Integer, tp::DataType = String )\n if length( params ) != N\n error( \"Exactly $( N ) parameter expected.\" )\n else\n if tp != String\n params = map( x -> parse( tp, x ), params )\n end\n if N == 1\n params = params[ 1 ]\n end\n return params\n end\nend\n\nfunction parse_N_params( params, tp::DataType )\n N = length( params )\n if tp != String\n params = map( x -> parse( tp, x ), params )\n end\nend\n\nfunction parse_version_params( params )\n versionstring = parse_N_params( params, 1 )\n if versionstring == \"2.0\"\n return 2\n else\n error( \"Unknown version $( versionstring )\" )\n end\nend\n\nparse_number_of_ports( params ) = parse_N_params( params, 1, Int64 )\nparse_two_port_data_order( params ) = parse_N_params( params, 1 )\nparse_number_of_frequencies( params ) = parse_N_params( params, 1, Int64 )\nparse_number_of_noise_frequencies( params ) = parse_N_params( params, 1, Int64 )\nparse_reference( params ) = parse_N_params( params, Float64 )\nparse_matrix_format( params ) = []\nparse_mixed_mode_order( params ) = []\nparse_begin_information( params ) = []\nparse_end_information( params ) = []\nparse_network_data( params ) = []\nparse_noise_data( params ) = []\nparse_end( params ) = []\n\nconst version_param_parsers = Dict{ Symbol, Function }(\n :Version => parse_version_params,\n :NumberOfPorts => parse_number_of_ports,\n :TwoPortDataOrder => parse_two_port_data_order,\n :NumberOfFrequencies => parse_number_of_frequencies,\n :NumberOfNoiseFrequencies => parse_number_of_noise_frequencies,\n :Reference => parse_reference,\n :MatrixFormat => parse_matrix_format,\n :MixedModeOrder => parse_mixed_mode_order,\n :BeginInformation => parse_begin_information,\n :EndInformation => parse_end_information,\n :NetworkData => parse_network_data,\n :NoiseData => parse_noise_data,\n :End => parse_end,\n)\n\n\"\"\"\n parse_keyword_line( line )\n\nReturns the keyword parameters for a keyword line.\n\"\"\"\nfunction parse_keyword_line( line )\n keyword, paramstring = split( line[ 2:end ], \"]\" )\n keyword = uppercase( keyword )\n params = split( paramstring )\n if haskey( keywordStringSymbols, keyword )\n kwSymbol = keywordStringSymbols[ keyword ]\n params = version_param_parsers[ kwSymbol ]( params )\n else\n error( \"Not a valid keyword.\" )\n end\n return kwSymbol, params\nend\n", "meta": {"hexsha": "d000bf03d821f69dca39f452d07010684a9c05e2", "size": 16794, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ParseTouchstone.jl", "max_stars_repo_name": "mpichl87/Touchstone.jl", "max_stars_repo_head_hexsha": "b31c8b1ea0df6b32f4d0f8da18a8ee2b226f562b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-30T00:25:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T19:10:32.000Z", "max_issues_repo_path": "src/ParseTouchstone.jl", "max_issues_repo_name": "mpichl87/Touchstone.jl", "max_issues_repo_head_hexsha": "b31c8b1ea0df6b32f4d0f8da18a8ee2b226f562b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ParseTouchstone.jl", "max_forks_repo_name": "mpichl87/Touchstone.jl", "max_forks_repo_head_hexsha": "b31c8b1ea0df6b32f4d0f8da18a8ee2b226f562b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-19T18:14:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:14:28.000Z", "avg_line_length": 31.1, "max_line_length": 119, "alphanum_fraction": 0.6570203644, "num_tokens": 4435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2431017652866156}} {"text": "module Optimisers\n\nusing Functors: functor, fmap, isleaf\nusing LinearAlgebra\n\ninclude(\"interface.jl\")\n\ninclude(\"destructure.jl\")\nexport destructure, total, total2\n\ninclude(\"rules.jl\")\nexport Descent, ADAM, Momentum, Nesterov, RMSProp,\n ADAGrad, AdaMax, ADADelta, AMSGrad, NADAM, ADAMW, RADAM, OADAM, AdaBelief,\n WeightDecay, ClipGrad, ClipNorm, OptimiserChain\n\n\"\"\"\n Optimisers.apply!(rule::RuleType, state, parameters, gradient) -> (state, gradient)\n\nThis defines the action of any optimisation rule. It should return the modified gradient\nwhich will be subtracted from the parameters, and the updated state (if any) for use at\nthe next iteration, as a tuple `(state, gradient)`.\n\nFor efficiency it is free to mutate the old state, but only what is returned will be used.\nIdeally this should check `iswriteable(x)`, which the built-in rules do via [`@..`](@ref).\n\nThe initial state is `init(rule::RuleType, parameters)`.\n\n# Example\n```jldoctest\njulia> Optimisers.init(Descent(0.1), Float32[1,2,3]) === nothing\ntrue\n\njulia> Optimisers.apply!(Descent(0.1), nothing, Float32[1,2,3], [4,5,6])\n(nothing, Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}}(*, ([4, 5, 6], 0.1f0)))\n```\n\"\"\"\napply!\n\n\"\"\"\n Optimisers.init(rule::RuleType, parameters) -> state\n\nSets up the initial state for a given optimisation rule, and an array of parameters.\nThis and [`apply!`](@ref) are the two functions which any new optimisation rule must define.\n\n# Examples\n```jldoctest\njulia> Optimisers.init(Descent(), Float32[1,2,3]) # is `nothing`\n\njulia> Optimisers.init(Momentum(), [1.0, 2.0])\n2-element Vector{Float64}:\n 0.0\n 0.0\n```\n\"\"\"\ninit\n\n\"\"\"\n Optimisers.setup(rule, model) -> tree\n\nInitialises the given optimiser for every trainable parameter within the model.\nReturns a tree of the relevant states, which must be passed to [`update`](@ref)\nor [`update!`](@ref).\n\n# Example\n```jldoctest\njulia> Optimisers.setup(Descent(0.1f0), (x = rand(3), y = (true, false), z = tanh))\n(x = Leaf(Descent{Float32}(0.1), nothing), y = (nothing, nothing), z = nothing)\n```\n\"\"\"\nsetup\n\n\"\"\"\n Optimisers.update(tree, model, gradient) -> (tree, model)\n\nUses the optimiser and the gradient to change the trainable parameters in the model.\nReturns the improved model, and the optimiser states needed for the next update.\nThe initial tree of states comes from [`setup`](@ref).\n\nSee also [`update!`](@ref), which will be faster for models of ordinary `Array`s or `CuArray`s.\n\n# Example\n```jldoctest\njulia> m = (x = Float32[1,2,3], y = tanh);\n\njulia> t = Optimisers.setup(Descent(0.1f0), m)\n(x = Leaf(Descent{Float32}(0.1), nothing), y = nothing)\n\njulia> g = (x = [1,1,1], y = nothing); # fake gradient\n\njulia> Optimisers.update(t, m, g)\n((x = Leaf(Descent{Float32}(0.1), nothing), y = nothing), (x = Float32[0.9, 1.9, 2.9], y = tanh))\n```\n\"\"\"\nupdate\n\n\"\"\"\n Optimisers.update!(tree, model, gradient) -> (tree, model)\n\nUses the optimiser and the gradient to change the trainable parameters in the model.\nReturns the improved model, and the optimiser states needed for the next update.\nThe initial tree of states comes from [`setup`](@ref).\n\nThis is used in exactly the same manner as [`update`](@ref), but because it may mutate\narrays within the old model (and the old state), it will be faster for models of ordinary\n`Array`s or `CuArray`s. However, you should not rely on the old model being fully updated.\n\"\"\"\nupdate!\n\nend # module\n", "meta": {"hexsha": "417b90d4a65c81d84342bfb7e230d517b7d28324", "size": 3426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Optimisers.jl", "max_stars_repo_name": "mcabbott/Optimisers.jl", "max_stars_repo_head_hexsha": "2bf0efaf11d49482a02366a207bfff0e9ad40759", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Optimisers.jl", "max_issues_repo_name": "mcabbott/Optimisers.jl", "max_issues_repo_head_hexsha": "2bf0efaf11d49482a02366a207bfff0e9ad40759", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Optimisers.jl", "max_forks_repo_name": "mcabbott/Optimisers.jl", "max_forks_repo_head_hexsha": "2bf0efaf11d49482a02366a207bfff0e9ad40759", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1454545455, "max_line_length": 97, "alphanum_fraction": 0.7069468768, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.24295081462946136}} {"text": "\"\"\"\n minimalsetup1d(N)\n\nCreates a minimal setup of all important variables.\n\nSuch it generates the moments `height`, `velocity` as well as a dummy distribution with its speeds `f0`, `f1` and `f2`.\nFurther a set of forcing is supplied, they can be used with `foces.slip`, `.h∇p`, `.bathymetry` and `.thermal`.\n\n# Example\n```jldoctest\njulia> using JuSwalbe\n\njulia> constants, mom, f, distribution = minimalsetup1d(10)\n(JuSwalbe.Inputconstants\n lx: Int64 10\n ly: Int64 512\n maxruntime: Int64 100000\n dumping: Int64 1000\n τ: Float64 1.0\n gravity: Float64 0.0\n γ: Float64 0.01\n δ: Float64 1.0\n μ: Float64 0.16666666666666666\n kbt: Float64 0.0\n, JuSwalbe.Macroquant{Array{Float64,1},Array{Float64,1}}\n height: Array{Float64}((10,)) [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]\n velocity: Array{Float64}((10,)) [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]\n pressure: Array{Float64}((10,)) [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n energy: Array{Float64}((10,)) [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n, JuSwalbe.Forces{Array{Float64,1}}\n slip: Array{Float64}((10,)) [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]\n h∇p: Array{Float64}((10,)) [-0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1]\n bathymetry: Array{Float64}((10,)) [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n thermal: Array{Float64}((10,)) [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n, JuSwalbe.DistributionD1Q3{Array{Float64,1}}\n f0: Array{Float64}((10,)) [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]\n f1: Array{Float64}((10,)) [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n f2: Array{Float64}((10,)) [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n)\n\njulia> mom.height\n10-element Array{Float64,1}:\n 1.0\n 1.0\n 1.0\n 1.0\n 1.0\n 1.0\n 1.0\n 1.0\n 1.0\n 1.0\n```\nSee also: [`minimalsetup2d`](@ref)\n\"\"\"\nfunction minimalsetup1d(N::Int)\n input = Inputconstants(lx=N)\n mom = Macroquant(height = ones(N), velocity=fill(0.1, N), pressure=zeros(N), energy=zeros(N))\n forces = Forces(slip=fill(0.1, N), thermal=zeros(N), h∇p=fill(-0.1, N), bathymetry=zeros(N))\n dist = DistributionD1Q3(f0 = ones(N), f1 = zeros(N), f2 = zeros(N))\n return input, mom, forces, dist\nend\n\n\"\"\"\n minimalsetup2d(N,M)\n\nCreates a minimal working example set of macroscopic moments, forces and a distribution.\n\n# Example\n```jldoctest\njulia> using JuSwalbe\n\njulia> input, mom, f, dist = minimalsetup2d(5,5)\n(JuSwalbe.Inputconstants\n lx: Int64 5\n ly: Int64 5\n maxruntime: Int64 100000\n dumping: Int64 1000\n τ: Float64 1.0\n gravity: Float64 0.0\n γ: Float64 0.01\n δ: Float64 1.0\n μ: Float64 0.16666666666666666\n kbt: Float64 0.0\n, JuSwalbe.Macroquant{Array{Float64,2},JuSwalbe.Twovector{Array{Float64,2}}}\n height: Array{Float64}((5, 5)) [1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0; … ; 1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0]\n velocity: JuSwalbe.Twovector{Array{Float64,2}}\n pressure: Array{Float64}((5, 5)) [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]\n energy: Array{Float64}((5, 5)) [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]\n, JuSwalbe.Forces{JuSwalbe.Twovector{Array{Float64,2}}}\n slip: JuSwalbe.Twovector{Array{Float64,2}}\n h∇p: JuSwalbe.Twovector{Array{Float64,2}}\n bathymetry: JuSwalbe.Twovector{Array{Float64,2}}\n thermal: JuSwalbe.Twovector{Array{Float64,2}}\n, JuSwalbe.DistributionD2Q9{Array{Float64,2}}\n f0: Array{Float64}((5, 5)) [1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0; … ; 1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0]\n f1: Array{Float64}((5, 5)) [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]\n f2: Array{Float64}((5, 5)) [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]\n f3: Array{Float64}((5, 5)) [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]\n f4: Array{Float64}((5, 5)) [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]\n f5: Array{Float64}((5, 5)) [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]\n f6: Array{Float64}((5, 5)) [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]\n f7: Array{Float64}((5, 5)) [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]\n f8: Array{Float64}((5, 5)) [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]\n)\n\n```\n\nSee also: [`minimalsetup1d`](@ref)\n\"\"\"\nfunction minimalsetup2d(N::Int, M::Int)\n input = Inputconstants(lx=N, ly=M)\n vel = Twovector(x=fill(0.02, (N,M)), y=fill(-0.02, (N,M)))\n zerovec = Twovector(x=zeros(N,M), y=zeros(N,M))\n mom = Macroquant(height = ones(N,M), velocity=vel, pressure=zeros(N,M), energy=zeros(N,M))\n forces = Forces(slip=vel, thermal=zerovec, h∇p=vel, bathymetry=zerovec)\n dist = DistributionD2Q9(f0 = ones(N,M), f1 = zeros(N,M), f2 = zeros(N,M), \n f3 = zeros(N,M), f4 = zeros(N,M), f5 = zeros(N,M), \n f6 = zeros(N,M), f7 = zeros(N,M), f8 = zeros(N,M))\n return input, mom, forces, dist\nend\n\n\"\"\"\n simplemoment2d(n,m,type)\n\nCreates moments of type JuSwalbe.Macroquant with dimensions (n,m).\n\n# Example\n```jldoctest\njulia> using JuSwalbe\n\njulia> mom = simplemoment2d(5,5)\nJuSwalbe.Macroquant{Array{Float64,2},JuSwalbe.Twovector{Array{Float64,2}}}\n height: Array{Float64}((5, 5)) [1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0; … ; 1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0]\n velocity: JuSwalbe.Twovector{Array{Float64,2}}\n pressure: Array{Float64}((5, 5)) [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]\n energy: Array{Float64}((5, 5)) [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]\n\njulia> mom.height\n5×5 Array{Float64,2}:\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n\n```\n\"\"\"\nfunction simplemoment2d(n::Int, m::Int; T=Float64)\n mom = JuSwalbe.Macroquant(height=ones(T, (n,m)), \n velocity=JuSwalbe.Twovector(x=fill(T(0.1),(n,m)), y=fill(T(-0.1),(n,m))), \n pressure=zeros(T, (n,m)), \n energy=zeros(T,(n,m)))\n return mom\nend\n\n\"\"\"\n simplemoment1d(n,type)\n\nCreates moments of type JuSwalbe.Macroquant with length n.\n\n# Example\n```jldoctest\njulia> using JuSwalbe\n\njulia> mom = simplemoment1d(5)\nJuSwalbe.Macroquant{Array{Float64,1},Array{Float64,1}}\n height: Array{Float64}((5,)) [1.0, 1.0, 1.0, 1.0, 1.0]\n velocity: Array{Float64}((5,)) [0.1, 0.1, 0.1, 0.1, 0.1]\n pressure: Array{Float64}((5,)) [0.0, 0.0, 0.0, 0.0, 0.0]\n energy: Array{Float64}((5,)) [0.0, 0.0, 0.0, 0.0, 0.0]\n\njulia> mom.height\n5-element Array{Float64,1}:\n 1.0\n 1.0\n 1.0\n 1.0\n 1.0\n\n```\n\"\"\"\nfunction simplemoment1d(n::Int; T=Float64)\n mom = JuSwalbe.Macroquant(height=ones(T, n), velocity=fill(T(0.1),n), pressure=zeros(T, n), energy=zeros(T, n))\n return mom\nend\n\n\"\"\"\n simpleTwovector(n,m,T)\n\nGenerates a JuSwalbe.Twovector of type T and dimension (n,m).\n\n# Example\n```jldoctest\njulia> using JuSwalbe\n\njulia> twovec = simpleTwovector(5,5)\nJuSwalbe.Twovector{Array{Float64,2}}\n x: Array{Float64}((5, 5)) [0.1 0.1 … 0.1 0.1; 0.1 0.1 … 0.1 0.1; … ; 0.1 0.1 … 0.1 0.1; 0.1 0.1 … 0.1 0.1]\n y: Array{Float64}((5, 5)) [-0.1 -0.1 … -0.1 -0.1; -0.1 -0.1 … -0.1 -0.1; … ; -0.1 -0.1 … -0.1 -0.1; -0.1 -0.1 … -0.1 -0.1]\n\njulia> twovec.x\n5×5 Array{Float64,2}:\n 0.1 0.1 0.1 0.1 0.1\n 0.1 0.1 0.1 0.1 0.1\n 0.1 0.1 0.1 0.1 0.1\n 0.1 0.1 0.1 0.1 0.1\n 0.1 0.1 0.1 0.1 0.1\n```\n\"\"\"\nfunction simpleTwovector(n::Int,m::Int; T=Float64)\n xy = JuSwalbe.Twovector(x=fill(T(0.1),(n,m)), y=fill(T(-0.1),(n,m)))\n return xy\nend\n\nfunction zeroTwovector(n::Int,m::Int; T=Float64)\n xy = JuSwalbe.Twovector(x=zeros(T ,(n,m)), y=zeros(T, (n,m)))\n return xy\nend\n\nfunction zeroTwovectorCU(n::Int,m::Int; T=Float32)\n jaja = zeros(n,m)\n xy = JuSwalbe.Twovector(x=CuArray(jaja), y=CuArray(jaja))\n return xy\nend\n\n\"\"\"\n simpledistD2Q9(n, m, T)\n\nGenerates a `D2Q9` distribution function of dimension `n`,`m` with defined fill statements.\n\n# Example\n```jldoctest\njulia> using JuSwalbe\n\njulia> dist = simpledistD2Q9(5,5)\nJuSwalbe.DistributionD2Q9{Array{Float64,2}}\n f0: Array{Float64}((5, 5)) [1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0; … ; 1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0]\n f1: Array{Float64}((5, 5)) [0.1 0.1 … 0.1 0.1; 0.1 0.1 … 0.1 0.1; … ; 0.1 0.1 … 0.1 0.1; 0.1 0.1 … 0.1 0.1]\n f2: Array{Float64}((5, 5)) [-0.1 -0.1 … -0.1 -0.1; -0.1 -0.1 … -0.1 -0.1; … ; -0.1 -0.1 … -0.1 -0.1; -0.1 -0.1 … -0.1 -0.1]\n f3: Array{Float64}((5, 5)) [0.01 0.01 … 0.01 0.01; 0.01 0.01 … 0.01 0.01; … ; 0.01 0.01 … 0.01 0.01; 0.01 0.01 … 0.01 0.01]\n f4: Array{Float64}((5, 5)) [-0.01 -0.01 … -0.01 -0.01; -0.01 -0.01 … -0.01 -0.01; … ; -0.01 -0.01 … -0.01 -0.01; -0.01 -0.01 … -0.01 -0.01]\n f5: Array{Float64}((5, 5)) [0.2 0.2 … 0.2 0.2; 0.2 0.2 … 0.2 0.2; … ; 0.2 0.2 … 0.2 0.2; 0.2 0.2 … 0.2 0.2]\n f6: Array{Float64}((5, 5)) [0.02 0.02 … 0.02 0.02; 0.02 0.02 … 0.02 0.02; … ; 0.02 0.02 … 0.02 0.02; 0.02 0.02 … 0.02 0.02]\n f7: Array{Float64}((5, 5)) [0.02 0.02 … 0.02 0.02; 0.02 0.02 … 0.02 0.02; … ; 0.02 0.02 … 0.02 0.02; 0.02 0.02 … 0.02 0.02]\n f8: Array{Float64}((5, 5)) [0.5 0.5 … 0.5 0.5; 0.5 0.5 … 0.5 0.5; … ; 0.5 0.5 … 0.5 0.5; 0.5 0.5 … 0.5 0.5]\n\njulia> dist.f0\n5×5 Array{Float64,2}:\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n\njulia> typeof(dist)\nJuSwalbe.DistributionD2Q9{Array{Float64,2}}\n```\n\nSee also: [`simpleTwovector`](@ref), [`simplemoment2d`](@ref)\n\n\"\"\"\nfunction simpledistD2Q9(n::Int, m::Int; T=Float64)\n dist = JuSwalbe.DistributionD2Q9(f0 = ones(T, (n,m)), f1 = fill(T(0.1), (n,m)), f2 = fill(T(-0.1), (n,m)),\n f3 = fill(T(0.01), (n,m)), f4 = fill(T(-0.01), (n,m)), f5 = fill(T(0.2), (n,m)), \n f6 = fill(T(0.02), (n,m)), f7 = fill(T(0.02), (n,m)), f8 = fill(T(0.5), (n,m)))\n\n return dist\nend", "meta": {"hexsha": "a00cf076c5e469ea0c6ff75f7ca284b9340efbdc", "size": 10047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/minimalsetup.jl", "max_stars_repo_name": "Zitzeronion/JuSwalbe", "max_stars_repo_head_hexsha": "eb0aca0eabe327d4f9ca5756b4fc5b0e4fb2876b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-24T13:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-24T13:28:56.000Z", "max_issues_repo_path": "src/minimalsetup.jl", "max_issues_repo_name": "Zitzeronion/JuSwalbe", "max_issues_repo_head_hexsha": "eb0aca0eabe327d4f9ca5756b4fc5b0e4fb2876b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-05-08T00:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-09T01:31:47.000Z", "max_forks_repo_path": "src/minimalsetup.jl", "max_forks_repo_name": "Zitzeronion/JuSwalbe.jl", "max_forks_repo_head_hexsha": "eb0aca0eabe327d4f9ca5756b4fc5b0e4fb2876b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3494423792, "max_line_length": 141, "alphanum_fraction": 0.5644470986, "num_tokens": 5583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24294048363959556}} {"text": "\"\"\"\nGeneric Fermion module\n\"\"\"\nmodule AbstractFermion\n #export FermionFields,Wx!,Wdagx!,clear!,substitute_fermion!,Dx!\n\n #export FermionFields,\n # Wx!,Wdagx!,clear!,substitute_fermion!,Dx!,fermion_shift!,\n # fermion_shiftB!,add!,set_wing_fermi!,WdagWx!,apply_periodicity\n\n import ..Actions:FermiActionParam,FermiActionParam_Wilson,\n FermiActionParam_WilsonClover,FermiActionParam_Staggered\n import ..Gaugefields:GaugeFields,GaugeFields_1d,SU3GaugeFields,SU2GaugeFields,SU3GaugeFields_1d,SU2GaugeFields_1d,\n staggered_phase,SUn,SU2,SU3,SUNGaugeFields,SUNGaugeFields_1d,SU\n using Random\n abstract type FermionFields end\n\n\n\n \n function clear!(a::FermionFields)\n n1,n2,n3,n4,n5,n6 = size(a.f)\n for i6=1:n6\n for i5=1:n5\n for i4=1:n4\n for i3=1:n3\n for i2=1:n2\n @simd for i1=1:n1\n a.f[i1,i2,i3,i4,i5,i6]= 0\n end\n end\n end\n end\n end\n end\n end\n\n \n function add!(c::FermionFields,alpha::Number,a::FermionFields,beta::Number,b::FermionFields) #c = c + alpha*a + beta*b\n n1,n2,n3,n4,n5,n6 = size(a.f)\n\n for i6=1:n6\n for i5=1:n5\n for i4=1:n4\n for i3=1:n3\n for i2=1:n2\n @simd for i1=1:n1\n #println(a.f[i1,i2,i3,i4,i5,i6],\"\\t\",b.f[i1,i2,i3,i4,i5,i6] )\n c.f[i1,i2,i3,i4,i5,i6] += alpha*a.f[i1,i2,i3,i4,i5,i6] +beta*b.f[i1,i2,i3,i4,i5,i6] \n end\n end\n end\n end\n end\n end\n return\n end\n\n function add!(c::FermionFields,alpha::Number,a::FermionFields) #c = c + alpha*a \n n1,n2,n3,n4,n5,n6 = size(a.f)\n\n for i6=1:n6\n for i5=1:n5\n for i4=1:n4\n for i3=1:n3\n for i2=1:n2\n @simd for i1=1:n1\n #println(a.f[i1,i2,i3,i4,i5,i6],\"\\t\",b.f[i1,i2,i3,i4,i5,i6] )\n c.f[i1,i2,i3,i4,i5,i6] += alpha*a.f[i1,i2,i3,i4,i5,i6] \n end\n end\n end\n end\n end\n end\n return\n end\n\n function add!(coeff::Number,c::FermionFields,alpha::Number,a::FermionFields) #c = coeff*c + alpha*a \n n1,n2,n3,n4,n5,n6 = size(a.f)\n\n for i6=1:n6\n for i5=1:n5\n for i4=1:n4\n for i3=1:n3\n for i2=1:n2\n @simd for i1=1:n1\n #println(a.f[i1,i2,i3,i4,i5,i6],\"\\t\",b.f[i1,i2,i3,i4,i5,i6] )\n c.f[i1,i2,i3,i4,i5,i6] = coeff*c.f[i1,i2,i3,i4,i5,i6] + alpha*a.f[i1,i2,i3,i4,i5,i6] \n end\n end\n end\n end\n end\n end\n return\n end\n\n\n\n function Wx!(xout::FermionFields,U::Array{GaugeFields,1},\n x::FermionFields,temps::Array{FermionFields,1},fparam::T) where T <: FermiActionParam\n error(\"This FermionFields type is not supported yet in function Wx!. The type is $(typeof(x))\")\n end\n\n function Dx!(xout::T,U::Array{G,1},\n x::T,temps::Array{T,1}) where {T <: FermionFields,G <: GaugeFields}\n error(\"This FermionFields type is not supported yet in function Dx!. The type is $(typeof(x))\")\n\n return\n end\n\n function Ddagx!(xout::T,U::Array{G,1},\n x::T,temps::Array{T,1}) where {T <: FermionFields,G <: GaugeFields}\n error(\"This FermionFields type is not supported yet in function Ddagx!. The type is $(typeof(x))\")\n\n return\n end\n\n function Dxplus!(xout::T,ν::Int64,U::Array{G,1},\n x::T,temps::Array{T,1}) where {T <: FermionFields,G <: GaugeFields}\n #temp = temps[4]\n error(\"This FermionFields type is not supported yet in function Dx!. The type is $(typeof(x))\")\n\n return\n end\n\n\n function fermion_shiftB!(b::T,evensite,u::Array{GaugeFields{SU{NC}},1},μ,a::T) where {NC,T <: FermionFields}\n error(\"This FermionFields type is not supported yet in function fermion_shiftB!. The type is $(typeof(x))\")\n end\n\n\n function Wdagx!(xout::FermionFields,U::Array{GaugeFields,1},\n x::FermionFields,temps::Array{FermionFields,1},fparam::T) where T <: FermiActionParam\n error(\"This FermionFields type is not supported yet in function Wdagx!. The type is $(typeof(x))\")\n end\n\n function WdagWx!(xout::T,U::Array{G,1},x::T,temps::Array{T,1},fparam) where {T <: FermionFields,G <: GaugeFields}\n temp = temps[5]\n Wx!(temp,U,x,temps,fparam) \n \n Wdagx!(xout,U,temp,temps,fparam) \n \n return\n end\n\n\n\n function WdagWx!(xout::T,U::Array{G,1},x::T,temps::Array{T,1},fparam,indices) where {T <: FermionFields,G <: GaugeFields}\n WdagWx!(xout,U,x,temps,fparam)\n return\n end\n\n\n\n function substitute_fermion!(H,j,x::FermionFields)\n error(\"substitute_fermion! is not implemented for $(typeof(x))\")\n end\n\n function set_wing_fermi!(a::FermionFields)\n NT = a.NT\n NZ = a.NZ\n NY = a.NY\n NX = a.NX\n NC = a.NC\n\n #! X-direction\n for ialpha=1:4\n for it=1:NT\n for iz = 1:NZ\n for iy=1:NY\n for k=1:NC\n a[k,0,iy,iz,it,ialpha] = a.BoundaryCondition[1]*a[k,NX,iy,iz,it,ialpha]\n end\n end\n end\n end\n end\n\n for ialpha=1:4\n for it=1:NT\n for iz=1:NZ\n for iy=1:NY\n for k=1:NC\n a[k,NX+1,iy,iz,it,ialpha] = a.BoundaryCondition[1]*a[k,1,iy,iz,it,ialpha]\n end\n end\n end\n end\n end\n\n #Y-direction\n for ialpha = 1:4\n for it=1:NT\n for iz=1:NZ\n for ix=1:NX\n for k=1:NC\n a[k,ix,0,iz,it,ialpha] = a.BoundaryCondition[2]*a[k,ix,NY,iz,it,ialpha]\n end\n end\n end\n end\n end\n\n for ialpha=1:4\n for it=1:NT\n for iz=1:NZ\n for ix=1:NX\n for k=1:NC\n a[k,ix,NY+1,iz,it,ialpha] = a.BoundaryCondition[2]*a[k,ix,1,iz,it,ialpha]\n end\n end\n end\n end\n end\n\n \n for ialpha=1:4\n # Z-direction\n for it=1:NT\n for iy=1:NY\n for ix=1:NX\n for k=1:NC\n a[k,ix,iy,0,it,ialpha] = a.BoundaryCondition[3]*a[k,ix,iy,NZ,it,ialpha]\n a[k,ix,iy,NZ+1,it,ialpha] = a.BoundaryCondition[3]*a[k,ix,iy,1,it,ialpha]\n\n end\n end\n end\n end\n\n #T-direction\n for iz=1:NZ\n for iy=1:NY\n for ix=1:NX\n for k=1:NC\n a[k,ix,iy,iz,0,ialpha] = a.BoundaryCondition[4]*a[k,ix,iy,iz,NT,ialpha]\n a[k,ix,iy,iz,NT+1,ialpha] = a.BoundaryCondition[4]*a[k,ix,iy,iz,1,ialpha]\n end\n end\n end\n end\n\n end\n\n \n\n \n\n end\n\n \n function fermion_shift!(b::F,u::Array{GaugeFields{SU{NC}},1},μ,a::F) where {NC,F <: FermionFields}\n if μ == 0\n substitute!(b,a)\n return\n end\n\n NX = a.NX\n NY = a.NY\n NZ = a.NZ\n NT = a.NT\n #NC = a.NC\n\n if μ > 0\n idel = zeros(Int64,4)\n idel[μ] = 1\n\n n6 = size(a.f)[6]\n for ialpha=1:n6\n for it=1:NT\n it1 = it + idel[4]\n for iz=1:NZ\n iz1 = iz + idel[3]\n for iy=1:NY\n iy1 = iy + idel[2]\n for ix=1:NX\n ix1 = ix + idel[1]\n for k1=1:NC\n b[k1,ix,iy,iz,it,ialpha] = 0\n @simd for k2=1:NC\n b[k1,ix,iy,iz,it,ialpha] += u[μ][k1,k2,ix,iy,iz,it]*a[k2,ix1,iy1,iz1,it1,ialpha]\n end\n end\n end\n end\n end\n end\n end\n \n elseif μ < 0\n idel = zeros(Int64,4)\n idel[-μ] = 1\n n6 = size(b.f)[6]\n for ialpha =1:n6\n for it=1:NT\n it1 = it - idel[4]\n for iz=1:NZ\n iz1 = iz -idel[3]\n for iy=1:NY\n iy1 = iy -idel[2]\n for ix=1:NX\n ix1 = ix -idel[1]\n \n for k1=1:NC\n b[k1,ix,iy,iz,it,ialpha] = 0\n @simd for k2=1:NC\n b[k1,ix,iy,iz,it,ialpha] += conj(u[-μ][k2,k1,ix1,iy1,iz1,it1])*a[k2,ix1,iy1,iz1,it1,ialpha]\n end\n end\n end\n end\n end\n end\n end\n end\n\n end\n\n \n function fermion_shift!(b::F,evensite::Bool,u::Array{GaugeFields{SU{NC}},1},μ,a::F) where {NC,F <: FermionFields}\n if μ == 0\n substitute!(b,a)\n return\n end\n ibush = ifelse(evensite,0,1)\n\n NX = a.NX\n NY = a.NY\n NZ = a.NZ\n NT = a.NT\n #NC = a.NC\n\n if μ > 0\n idel = zeros(Int64,4)\n idel[μ] = 1\n\n n6 = size(a.f)[6]\n for ialpha=1:n6\n for it=1:NT\n it1 = it + idel[4]\n for iz=1:NZ\n iz1 = iz + idel[3]\n for iy=1:NY\n iy1 = iy + idel[2]\n xran =1+(1+ibush+iy+iz+it)%2:2:NX\n for ix in xran\n ix1 = ix + idel[1]\n for k1=1:NC\n b[k1,ix,iy,iz,it,ialpha] = 0\n @simd for k2=1:NC\n b[k1,ix,iy,iz,it,ialpha] += u[μ][k1,k2,ix,iy,iz,it]*a[k2,ix1,iy1,iz1,it1,ialpha]\n end\n end\n end\n end\n end\n end\n end\n \n elseif μ < 0\n idel = zeros(Int64,4)\n idel[-μ] = 1\n n6 = size(b.f)[6]\n for ialpha =1:n6\n for it=1:NT\n it1 = it - idel[4]\n for iz=1:NZ\n iz1 = iz -idel[3]\n for iy=1:NY\n iy1 = iy -idel[2]\n xran =1+(1+ibush+iy+iz+it)%2:2:NX\n for ix in xran\n ix1 = ix -idel[1]\n \n for k1=1:NC\n b[k1,ix,iy,iz,it,ialpha] = 0\n @simd for k2=1:NC\n b[k1,ix,iy,iz,it,ialpha] += conj(u[-μ][k2,k1,ix1,iy1,iz1,it1])*a[k2,ix1,iy1,iz1,it1,ialpha]\n end\n end\n end\n end\n end\n end\n end\n end\n\n end\n\n\n function apply_periodicity(ix,iy,iz,it,NX,NY,NZ,NT,BC)\n \n ixflag1 = (ix < 1)\n ixflag2 = (ix > NX)\n ix += ifelse(ixflag1,NX,0)\n ix += ifelse(ixflag2,-NX,0)\n\n sign = ifelse(ixflag1 || ixflag2,BC[1],1)\n #sign = ifelse(ixflag2,BC[1],1)\n\n\n\n iyflag1 = (iy < 1)\n iyflag2 = (iy > NY)\n \n iy += ifelse(iyflag1,NY,0)\n iy += ifelse(iyflag2,-NY,0)\n\n sign = ifelse(iyflag1 || iyflag2,BC[2],1)\n #sign = ifelse(iyflag2,BC[2],1)\n\n izflag1 = (iz < 1)\n izflag2 = (iz > NZ)\n\n iz += ifelse(izflag1,NZ,0)\n iz += ifelse(izflag2,-NZ,0)\n\n sign = ifelse(izflag1 || izflag2,BC[3],1)\n #sign = ifelse(izflag2,BC[3],1)\n\n itflag1 = (it < 1)\n itflag2 = (it > NT)\n\n it += ifelse(itflag1,NT,0)\n it += ifelse(itflag2,-NT,0)\n\n sign = ifelse(itflag1 || itflag2,BC[4],1)\n #sign = ifelse(itflag2,BC[4],1)\n\n return ix,iy,iz,it,sign\n end\n\n\n\n \n\n\n \"\"\"\nc-------------------------------------------------c\nc Random number function for Gaussian Noise\n with σ^2 = 1/2\nc-------------------------------------------------c\n \"\"\"\n function gauss_distribution_fermi!(x::FermionFields)\n NC = x.NC\n NX = x.NX\n NY = x.NY\n NZ = x.NZ\n NT = x.NT\n n6 = size(x.f)[6]\n σ = sqrt(1/2)\n\n for ialpha = 1:n6\n for it=1:NT\n for iz=1:NZ\n for iy=1:NY\n for ix=1:NX\n for ic=1:NC\n \n x[ic,ix,iy,iz,it,ialpha] = σ*randn()+im*σ*randn()\n end\n end\n end\n end\n end\n end\n\n set_wing_fermi!(x)\n\n return\n end\n\n \"\"\"\nc-------------------------------------------------c\nc Random number function for Gaussian Noise\n with σ^2 = 1/2\nc-------------------------------------------------c\n \"\"\"\n function gauss_distribution_fermi!(x::FermionFields,randomfunc,σ)\n NC = x.NC\n NX = x.NX\n NY = x.NY\n NZ = x.NZ\n NT = x.NT\n n6 = size(x.f)[6]\n #σ = sqrt(1/2)\n\n for mu = 1:n6\n for ic=1:NC\n for it=1:NT\n for iz=1:NZ\n for iy=1:NY\n for ix=1:NX\n v1 = sqrt(-log(randomfunc()+1e-10))\n v2 = 2pi*randomfunc()\n\n xr = v1*cos(v2)\n xi = v1 * sin(v2)\n\n x[ic,ix,iy,iz,it,mu] = σ*xr + σ*im*xi\n end\n end\n end\n end\n end\n end\n\n set_wing_fermi!(x)\n\n return\n end\n\n function gauss_distribution_fermi!(x::FermionFields,randomfunc)\n σ = 1\n gauss_distribution_fermi!(x,randomfunc,σ)\n end\n\n function gauss_distribution_fermi_Z2!(x::FermionFields) \n NC = x.NC\n NX = x.NX\n NY = x.NY\n NZ = x.NZ\n NT = x.NT\n n6 = size(x.f)[6]\n #σ = sqrt(1/2)\n\n for mu = 1:n6\n for it=1:NT\n for iz=1:NZ\n for iy=1:NY\n for ix=1:NX\n for ic=1:NC\n x[ic,ix,iy,iz,it,mu] = rand([-1,1])\n end\n end\n end\n end\n end\n end\n\n set_wing_fermi!(x)\n\n return\n end\n\n \"\"\"\nc-------------------------------------------------c\nc Random number function Z4 Noise\nc https://arxiv.org/pdf/1611.01193.pdf\nc-------------------------------------------------c\n \"\"\"\n function Z4_distribution_fermi!(x::FermionFields)\n NC = x.NC\n NX = x.NX\n NY = x.NY\n NZ = x.NZ\n NT = x.NT\n n6 = size(x.f)[6]\n θ = 0.0\n N::Int32 = 4\n Ninv = Float64(1/N)\n for ialpha = 1:n6\n for it=1:NT\n for iz=1:NZ\n for iy=1:NY\n for ix=1:NX\n for ic=1:NC\n θ = Float64(rand(0:N-1))*π*Ninv # r \\in [0,π/4,2π/4,3π/4]\n x[ic,ix,iy,iz,it,ialpha] = cos(θ)+im*sin(θ) \n end\n end\n end\n end\n end\n end\n\n set_wing_fermi!(x)\n\n return\n end\n\n\n\n\n\nend", "meta": {"hexsha": "ec8e79382e77b1d33f1c31496eb9aa46a12f80ed", "size": 17183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fermions/AbstractFermion.jl", "max_stars_repo_name": "RJaBi/LatticeQCD.jl", "max_stars_repo_head_hexsha": "a900545295a981a50a33c8aea8f5994b5bf1650a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fermions/AbstractFermion.jl", "max_issues_repo_name": "RJaBi/LatticeQCD.jl", "max_issues_repo_head_hexsha": "a900545295a981a50a33c8aea8f5994b5bf1650a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fermions/AbstractFermion.jl", "max_forks_repo_name": "RJaBi/LatticeQCD.jl", "max_forks_repo_head_hexsha": "a900545295a981a50a33c8aea8f5994b5bf1650a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2227891156, "max_line_length": 131, "alphanum_fraction": 0.3812489088, "num_tokens": 4901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24277034842815162}} {"text": "\r\n\"\"\"\r\n`module JAC.StrongField\r\n ... a submodel of JAC that contains all methods to set-up and perform strong-field computations. \r\n\"\"\"\r\nmodule StrongField\r\n\r\n using GSL, ## HypergeometricFunctions, Plots, \r\n Printf, SpecialFunctions, ..AngularMomentum, ..Basics, ..Defaults, ..InteractionStrength, ..Radial, ..ManyElectron, \r\n ..Nuclear, ..Pulse, ..TableStrings\r\n\r\n export aaaa\r\n\r\n \r\n \"\"\"\r\n `abstract type StrongField.AbstractSFAObservable` \r\n ... defines an abstract and a number of types for the observables that can be computed with SFA amplitudes.\r\n\r\n + struct SfaNoObservable ... an empty instance of an observable that does not help compute anything.\r\n + struct SfaEnergyDistribution ... to compute the energy distribution of the photoelectrons.\r\n + struct SfaMomentumDistribution ... to compute the momentum distribution of the photoelectrons.\r\n \"\"\"\r\n abstract type AbstractSFAObservable end\r\n struct SfaNoObservable <: StrongField.AbstractSFAObservable end\r\n\r\n\r\n \"\"\"\r\n `struct StrongField.SfaEnergyDistribution <: StrongField.AbstractSFAObservable` \r\n ... to compute in SFA the energy distribution of photoelectrons at given energies and angles.\r\n\r\n + theta ::Float64 ... polar angle of the energy distribution\r\n + phi ::Float64 ... azimuthal angle of the energy distribution\r\n + energies ::Array{Float64,1} ... specifies the photoelectron energy in the current units. \r\n \"\"\"\r\n struct SfaEnergyDistribution <: StrongField.AbstractSFAObservable\r\n theta ::Float64\r\n phi ::Float64\r\n energies ::Array{Float64,1}\r\n end\r\n\r\n \"\"\"\r\n `StrongField.SfaEnergyDistribution(theta::Float64, phi::Float64, NoEnergies::Int64, maxEnergy::Float64)` \r\n ... defines an energy distribution for given (theta,phi) and for NoEnergies between 0 < energy <= maxEnergy;\r\n a dist::SfaEnergyDistribution is returned.\r\n \"\"\"\r\n function SfaEnergyDistribution(theta::Float64, phi::Float64, NoEnergies::Int64, maxEnergy::Float64)\r\n energies = Float64[]; for i=1:NoEnergies push!(energies, i*maxEnergy / NoEnergies) end\r\n SfaEnergyDistribution(theta, phi, energies)\r\n end\r\n\r\n function Base.string(obs::SfaEnergyDistribution)\r\n sa = \"Compute photo-electron energy distribution at angles (theta,phi) = ($(obs.theta), $(obs.phi)) for the energies [a.u.]:\" \r\n return( sa )\r\n end\r\n\r\n function Base.show(io::IO, obs::SfaEnergyDistribution)\r\n sa = string(obs); print(io, sa, \"\\n\"); print(io, \" \", obs.energies)\r\n end\r\n \r\n \"\"\"\r\n `struct StrongField.SfaMomentumDistribution <: StrongField.AbstractSFAObservable` \r\n ... to compute in SFA the momentum distribution of photoelectrons for given polar angle theta and at given energies and azimuthal angles.\r\n\r\n + theta ::Float64 ... polar angle of the energy distribution\r\n + phi ::Array{Float64,1} ... specifies the azimuthal angles\r\n + energies ::Array{Float64,1} ... specifies the photoelectron energy in the current units. \r\n \"\"\"\r\n struct SfaMomentumDistribution <: StrongField.AbstractSFAObservable\r\n theta ::Float64\r\n phis ::Array{Float64,1}\r\n energies ::Array{Float64,1}\r\n end\r\n \r\n \"\"\"\r\n `StrongField.SfaMomentumDistribution(theta::Float64, NoPhi::Int64, NoEnergies::Int64, maxEnergy::Float64)` \r\n ... defines a momentum distribution for given theta and for NoEnergies between 0 < energy <= maxEnergy and NoPhi between 0 <= phi < 2pi;\r\n a dist::SfaMomentumDistribution is returned.\r\n \"\"\"\r\n function SfaMomentumDistribution(theta::Float64, NoPhi::Int64, NoEnergies::Int64, maxEnergy::Float64)\r\n energies = Float64[]; for i=1:NoEnergies push!(energies, i*maxEnergy / NoEnergies) end\r\n phis = Float64[]; for i=1:NoPhi push!(phis, i*2pi / NoPhi) end\r\n SfaMomentumDistribution(theta, phis, energies)\r\n end\r\n\r\n function Base.string(obs::SfaMomentumDistribution)\r\n sa = \"Compute photo-electron momentum distribution at polar angle theta = $(obs.theta) for (energy [a.u.], phi):\" \r\n return( sa )\r\n end\r\n\r\n function Base.show(io::IO, obs::SfaMomentumDistribution)\r\n sa = string(obs); print(io, sa, \"\\n\"); print(io, \" \", obs.energies); print(io, \" \", obs.phi)\r\n end\r\n \r\n \r\n \"\"\"\r\n `abstract type StrongField.AbstractVolkovState` \r\n ... defines an abstract and a number of types for dealing with the Volkov states in the computation of the SFA amplitudes.\r\n\r\n + struct FreeVolkov ... to apply the free-Volkov states.\r\n + struct CoulombVolkov ... apply the Coulomb-Volkov states.\r\n + struct DistortedVolkov ... apply the Distorted-Volkov states.\r\n \"\"\"\r\n abstract type AbstractVolkovState end\r\n struct FreeVolkov <: AbstractVolkovState end\r\n \r\n \r\n \"\"\"\r\n `struct StrongField.CoulombVolkov <: StrongField.AbstractVolkovState`\r\n \r\n + Z ::Float64 ... Charge that generates the Coulomb potential\r\n \"\"\"\r\n struct CoulombVolkov <: StrongField.AbstractVolkovState\r\n Z ::Float64\r\n end\r\n \r\n struct DistortedVolkov <: AbstractVolkovState end\r\n \r\n \r\n \r\n function Base.string(volkov::FreeVolkov) return( \"free-Volkov states\" ) end\r\n function Base.string(volkov::CoulombVolkov) return( \"Coulomb-Volkov states in potential of charge Z = $(volkov.Z)\" ) end\r\n function Base.string(volkov::DistortedVolkov) return( \"distorted-Volkov states\" ) end\r\n \r\n \r\n \"\"\"\r\n `struct StrongField.Settings` \r\n ... defines a type for the details and parameters of computing SFA amplitudes.\r\n\r\n + multipoles ::Array{EmMultipoles} ... Multipoles of the radiation field that are to be included.\r\n + gauges ::Array{UseGauge} ... Specifies the gauges to be included into the computations.\r\n + printBefore ::Bool ... True, if all the requested amplitudes are printed before the computation start.\r\n + printAmplitudes ::Bool ... True, if the amplitudes are to be printed.\r\n \"\"\"\r\n struct Settings \r\n multipoles ::Array{EmMultipole,1}\r\n gauges ::Array{UseGauge}\r\n printBefore ::Bool\r\n printAmplitudes ::Bool\r\n end \r\n\r\n\r\n \"\"\"\r\n `StrongField.Settings()` \r\n ... constructor for the default values of SFA computations.\r\n \"\"\"\r\n function Settings()\r\n Settings([E1], [UseCoulomb], false, false)\r\n end\r\n\r\n\r\n # `Base.show(io::IO, settings::StrongField.Settings)` ... prepares a proper printout of the variable settings::StrongField.Settings.\r\n function Base.show(io::IO, settings::StrongField.Settings) \r\n println(io, \"multipoles: $(settings.multipoles) \")\r\n println(io, \"use-gauges: $(settings.gauges) \")\r\n println(io, \"printBefore: $(settings.printBefore) \")\r\n println(io, \"printAmplitudes: $(settings.printAmplitudes) \")\r\n end\r\n\r\n\r\n \"\"\"\r\n `struct StrongField.Computation` \r\n ... defines a type for the computation of strong-field amplitudes and observables (properties).\r\n \r\n + observable ::AbstractSFAObservable ... The obserable to be calculated in SFA.\r\n + nuclearModel ::Nuclear.Model ... Model, charge and parameters of the nucleus.\r\n + grid ::Radial.Grid ... The radial grid to be used for the computation.\r\n + initialLevel ::Level ... Initial level of the atom\r\n + finalLevel ::Level ... Final level of the atom\r\n + beam ::Pulse.AbstractBeam ... Beam character and properties of the incident light pulse.\r\n + envelope ::Pulse.AbstractEnvelope ... Envelope of the incident light pulse. \r\n + polarization ::Basics.AbstractPolarization ... Envelope of the incident light pulse. \r\n + volkov ::AbstractVolkovState ... Specify the treatment/approach of the Volkov states.\r\n + settings ::StrongField.Settings ... Settings for the controlling the SFA amplitudes.\r\n \"\"\"\r\n struct Computation\r\n observable ::AbstractSFAObservable\r\n nuclearModel ::Nuclear.Model\r\n grid ::Radial.Grid \r\n initialLevel ::Level \r\n finalLevel ::Level\r\n beam ::Pulse.AbstractBeam \r\n envelope ::Pulse.AbstractEnvelope\r\n polarization ::Basics.AbstractPolarization \r\n volkov ::AbstractVolkovState\r\n settings ::StrongField.Settings\r\n end \r\n\r\n \r\n \"\"\"\r\n `StrongField.Computation()` ... constructor for an `empty` instance of StrongField.Computation().\r\n \"\"\"\r\n function Computation()\r\n Computation( SfaNoObservable(), Nuclear.Model(1.0), Radial.Grid(true), Level(), Level(), \r\n Pulse.PlaneWaveBeam(), Pulse.InfiniteEnvelope(), Basics.RightCircular(), FreeVolkov(), Settings() )\r\n end\r\n\r\n\r\n # `Base.string(comp::StrongField.Computation)` ... provides a String notation for the variable comp::StrongField.Computation.\r\n function Base.string(comp::StrongField.Computation)\r\n sa = \"Strong-field computation: \" * string(comp.observable) * \" for Z = $(comp.nuclearModel.Z) with \" * string(comp.volkov) * \"\\n\"\r\n sa = sa * \" initial level with (J, P, energy) = ($(comp.initialLevel.J), $(comp.initialLevel.parity), $(comp.initialLevel.energy)) \\n\" \r\n sa = sa * \" final level with (J, P, energy) = ($(comp.finalLevel.J), $(comp.finalLevel.parity), $(comp.finalLevel.energy)) \\n\\n\" \r\n sa = sa * \"The incident laser pulse is described by the: \\n \"\r\n sa = sa * string(comp.beam) * \"\\n \" * string(comp.polarization) * \"\\n \" * string(comp.envelope)\r\n return( sa )\r\n end\r\n\r\n\r\n # `Base.show(io::IO, comp::StrongField.Computation)` ... prepares a proper printout of the variable comp::StrongField.Computation.\r\n function Base.show(io::IO, comp::StrongField.Computation) \r\n sa = Base.string(comp); print(io, sa, \"\\n\\n\")\r\n println(io, \"Settings: \\n$(comp.settings) \") \r\n println(io, \"nuclearModel: $(comp.nuclearModel) \")\r\n println(io, \"grid: $(comp.grid) \")\r\n end\r\n\r\n\r\n \"\"\"\r\n `struct StrongField.SphericalAmplitude` \r\n ... to keep the amplitude at a given energy-angular point (energy, theta, phi) in momentum space.\r\n\r\n + energy ::Float64 ... Kinetic energy of the (outgoing) photoelectron.\r\n + theta ::Float64 ... Polar angle of the (outgoing) photoelectron.\r\n + phi ::Float64 ... Azimuthal angle of the (outgoing) photoelectron.\r\n + value ::ComplexF64 ... (Total) Amplitude.\r\n \"\"\"\r\n struct SphericalAmplitude\r\n energy ::Float64\r\n theta ::Float64\r\n phi ::Float64 \r\n value ::ComplexF64\r\n end\r\n\r\n\r\n function Base.string(amp::StrongField.SphericalAmplitude)\r\n sa = \"Total SFA amplitude at (energy, theta, phi) = ($(amp.energy),$(amp.theta),$(amp.phi)) is $(amp.value).\" \r\n return( sa )\r\n end\r\n\r\n function Base.show(io::IO, amp::StrongField.SphericalAmplitude)\r\n sa = string(amp); print(io, sa)\r\n end\r\n\r\n\r\n \"\"\"\r\n `struct StrongField.OutcomeEnergyDistribution` \r\n ... to comprise the energy distribution of photoelectrons at given energies and angles, for instance,\r\n for later graphical representation.\r\n\r\n + theta ::Float64 ... polar angle of the energy distribution\r\n + phi ::Float64 ... azimuthal angle of the energy distribution\r\n + energies ::Array{Float64,1} ... selected energies of the distribution.\r\n + probabilities ::Array{Float64,1} ... calculated probabilities of the energy distribution.\r\n \"\"\"\r\n struct OutcomeEnergyDistribution\r\n theta ::Float64\r\n phi ::Float64\r\n energies ::Array{Float64,1}\r\n probabilities ::Array{Float64,1}\r\n end\r\n\r\n\r\n # `Base.show(io::IO, outcome::StrongField.OutcomeEnergyDistribution)` ... prepares a proper printout of the variable outcome::StrongField.OutcomeEnergyDistribution.\r\n function Base.show(io::IO, outcome::StrongField.OutcomeEnergyDistribution) \r\n println(io, \"theta: $(outcome.theta) \")\r\n println(io, \"phi: $(outcome.phi) \")\r\n println(io, \"energies: $(outcome.energies) \")\r\n println(io, \"probabilities: $(outcome.probabilities) \")\r\n end\r\n \r\n \r\n \"\"\"\r\n `struct StrongField.OutcomeMomentumDistribution` \r\n ... to comprise the momentum distribution of photoelectrons at given energies and angles, for instance,\r\n for later graphical representation.\r\n\r\n + theta ::Float64 ... polar angle of the momentum distribution\r\n + momenta ::Array{Float64} ... pairs [px py] of momenta of the momentum distribution\r\n + probabilities ::Array{Float64,1} ... calculated probabilities of the energy distribution.\r\n \"\"\"\r\n struct OutcomeMomentumDistribution\r\n theta ::Float64\r\n momenta ::Array{Float64}\r\n probabilities ::Array{Float64,1}\r\n end\r\n\r\n\r\n # `Base.show(io::IO, outcome::StrongField.OutcomeMomentumDistribution)` ... prepares a proper printout of the variable outcome::StrongField.OutcomeMomentumDistribution.\r\n function Base.show(io::IO, outcome::StrongField.OutcomeMomentumDistribution) \r\n println(io, \"theta: $(outcome.theta) \")\r\n println(io, \"momenta: $(outcome.momenta) \")\r\n println(io, \"probabilities: $(outcome.probabilities) \")\r\n end\r\n \r\n \r\n ##################################################################################################################################################\r\n ##################################################################################################################################################\r\n ##################################################################################################################################################\r\n\r\n \r\n ####################################################################################################################\r\n ######The following four functions will be replaced later and serve only for comparison with previous results#######\r\n ####################################################################################################################\r\n \r\n \"\"\"\r\n `StrongField.HydrogenPnl(epsiloni::Float64, n::Int, l::Int, rGrid::Array{Float64,1})` \r\n ... returns the non-relativistic hydrogen-like radial wave function with modified binding energy epsiloni\r\n at the radial grid points rGrid\r\n \"\"\"\r\n function HydrogenPnl(epsiloni::Float64, n::Int, l::Int, rGrid::Array{Float64,1})\r\n Pnl = Float64[]\r\n Z = n*sqrt(-2*epsiloni)\r\n \r\n for j = 1:length(rGrid)\r\n r = rGrid[j]\r\n p = r * sqrt( (2*Z/n)^3 * factorial(n-l-1)/(2*n*factorial(n+l)) ) * exp(-Z*r/n) * (2*Z*r/n)^l * GSL.sf_laguerre_n(n-l-1,2*l+1,2*Z*r/n)\r\n push!( Pnl, p )\r\n end\r\n \r\n return( Pnl )\r\n end\r\n \r\n \"\"\"\r\n `StrongField.HydrogenDPnlDr(epsiloni::Float64, n::Int, l::Int, rGrid::Array{Float64,1})` \r\n ... returns the r-derivative of the non-relativistic hydrogen-like radial wave function with modified binding energy epsiloni\r\n at the radial grid points rGrid\r\n \"\"\"\r\n function HydrogenDPnlDr(epsiloni::Float64, n::Int, l::Int, rGrid::Array{Float64,1})\r\n DPnl = Float64[]\r\n Z = n*sqrt(-2*epsiloni)\r\n \r\n for j = 1:length(rGrid)\r\n r = rGrid[j]\r\n if n-l-2 >= 0\r\n p = 1/n * 2^(l+1) * exp(-r*Z/n) * (r*Z/n)^l * sqrt( Z^3 * factorial(n-l-1) / (n^4*factorial(l+n)) ) * ( (n+l*n-r*Z) * GSL.sf_laguerre_n(n-l-1,2*l+1,2*r*Z/n) - 2*r*Z * GSL.sf_laguerre_n(n-l-2,2+2*l,2*r*Z/n) )\r\n elseif n == 1 && l == 0\r\n p = -2 * exp(-r*Z) * sqrt(Z^3) * (r*Z - 1)\r\n else #not implemented\r\n p = 0\r\n end\r\n push!( DPnl, p )\r\n end\r\n \r\n return( DPnl )\r\n end\r\n \r\n \"\"\"\r\n `StrongField.VolkovP(epsilonp::Float64, lp::Int, rGrid::Array{Float64,1})` \r\n ... returns the (plane-wave) Volkov radial wave function\r\n at the radial grid points rGrid\r\n \"\"\"\r\n function VolkovP(epsilonp::Float64, lp::Int, rGrid::Array{Float64,1})\r\n P = Float64[]\r\n \r\n for j = 1:length(rGrid)\r\n r = rGrid[j]\r\n p = r * GSL.sf_bessel_jl( lp, sqrt(2*epsilonp)*r )\r\n push!( P, p )\r\n end\r\n \r\n return( P )\r\n end\r\n \r\n \"\"\"\r\n `StrongField.CoulombVolkovP(epsilonp::Float64, lp::Int, ZContinuum::Float64, rGrid::Array{Float64,1})` \r\n ... returns the Coulomb-Volkov radial wave function\r\n at the radial grid points rGrid\r\n \"\"\"\r\n function CoulombVolkovP(epsilonp::Float64, lp::Int, ZContinuum::Float64, rGrid::Array{Float64,1})\r\n sqrtTwoEps = sqrt(2*epsilonp)\r\n \r\n P = ComplexF64[]\r\n \r\n for j = 1:length(rGrid)\r\n r = rGrid[j]\r\n rho = sqrtTwoEps*r\r\n eta = -ZContinuum/sqrtTwoEps\r\n GammaValue = gamma( lp + 1 + eta * im )\r\n sigma = angle( GammaValue )\r\n Fl = 2.0^lp * exp(-0.5*pi*eta) * abs( GammaValue ) / factorial(2*lp+1) * rho^(lp+1) * exp( rho * im ) * HypergeometricFunctions.drummond1F1(lp+1+eta*im,2*lp+2,-2*rho*im)\r\n \r\n \r\n p = Fl * exp( sigma * im ) / sqrtTwoEps\r\n \r\n push!( P, p )\r\n end\r\n \r\n return( P )\r\n end\r\n \r\n \r\n \"\"\"\r\n `StrongField.pReducedME(epsilonp::Float64, lp::Int, n::Int, l::Int, epsiloni::Float64, volkov::AbstractVolkovState)` \r\n ... computes the reduced matrix elements of the momentum operator in the one-particle picture\r\n \"\"\"\r\n function pReducedME(epsilonp::Float64, lp::Int, n::Int, l::Int, epsiloni::Float64, volkov::AbstractVolkovState)\r\n rmax = 100.\r\n orderGL = 1000\r\n gaussLegendre = Radial.GridGL(\"Finite\",0.0,rmax,orderGL)\r\n rgrid = gaussLegendre.t\r\n weights = gaussLegendre.wt\r\n \r\n Pnl = HydrogenPnl( epsiloni, n, l, rgrid )\r\n if typeof(volkov) == FreeVolkov\r\n Pepsplp = VolkovP( epsilonp, lp, rgrid )\r\n elseif typeof(volkov) == CoulombVolkov\r\n Pepsplp = CoulombVolkovP( epsilonp, lp, volkov.Z, rgrid )\r\n end\r\n \r\n DPnl = HydrogenDPnlDr( epsiloni, n, l, rgrid )\r\n \r\n integral = 0. * im\r\n \r\n #Sum over grid and compute Gauss-Legendre sum\r\n for j = 1:orderGL\r\n r = rgrid[j]\r\n integrand = conj( Pepsplp[j] )/r * ( r*DPnl[j] - ((lp-l)*(lp+l+1))/2 * Pnl[j] )\r\n\r\n #Gauss-Legendre sum\r\n integral = integral + weights[j] * integrand\r\n end\r\n\r\n #Note that GSL.sf_coupling_3j takes takes the input (2*j1,2*j2,2*j3,2*m1,2*m2,2*m3)\r\n integral = integral * (-im)^(lp+1) * (-1)^lp * GSL.sf_coupling_3j( 2*lp, 2*1, 2*l, 0, 0, 0 )\r\n \r\n return( integral )\r\n end\r\n \r\n \"\"\"\r\n `StrongField.scalarProdBoundCont(epsilonp::Float64, lp::Int, n::Int, l::Int, epsiloni::Float64, volkov::AbstractVolkovState)` \r\n ... computes the scalar product of the bound (hydrogenic) and continuum (Volkov) states in the one-particle picture\r\n \"\"\"\r\n function scalarProdBoundCont(epsilonp::Float64, lp::Int, n::Int, l::Int, m::Int, epsiloni::Float64, volkov::AbstractVolkovState)\r\n rmax = 1000.\r\n orderGL = 1000\r\n gaussLegendre = Radial.GridGL(\"Finite\",0.0,rmax,orderGL)\r\n rgrid = gaussLegendre.t\r\n weights = gaussLegendre.wt\r\n \r\n Pnl = HydrogenPnl( epsiloni, n, l, rgrid )\r\n \r\n if typeof(volkov) == FreeVolkov\r\n Pepsplp = VolkovP( epsilonp, lp, rgrid )\r\n elseif typeof(volkov) == CoulombVolkov\r\n Pepsplp = CoulombVolkovP( epsilonp, lp, volkov.Z, rgrid )\r\n end\r\n \r\n DPnl = HydrogenDPnlDr( epsiloni, n, l, rgrid )\r\n \r\n integral = 0. * im\r\n \r\n #Sum over grid and compute Gauss-Legendre sum\r\n for j = 1:orderGL\r\n r = rgrid[j]\r\n integrand = conj( Pepsplp[j] ) * Pnl[j]\r\n\r\n #Gauss-Legendre sum\r\n integral = integral + weights[j] * integrand\r\n end\r\n \r\n return((-im)^l * integral)\r\n end\r\n \r\n ####################################################################################################################\r\n\r\n \"\"\"\r\n `StrongField.computeEnvelopeIntegrals(envelope::Pulse.AbstractEnvelope, beam::AbstractBeam, polarization::Basics.AbstractPolarization,\r\n thetap::Float64, phip::Float64, energyp::Float64, initialEn::Float64)` \r\n ... computes the pulse-envelope integrals for the given laser pulse; this pulse is completely specified by its beam character\r\n and parameters, the pulse-envelope parameters and the polarization of the light. A tuple of the two integrals\r\n (fVolkov, fVolkovSquared)::Tuple{Complex{Float64},Complex{Float64}} is returned.\r\n \"\"\"\r\n function computeEnvelopeIntegrals(envelope::Pulse.AbstractEnvelope, beam::AbstractBeam, polarization::Basics.AbstractPolarization,\r\n thetap::Float64, phip::Float64, energyp::Float64, initialEn::Float64)\r\n fVolkovPlus = Pulse.envelopeVolkovIntegral(true, envelope, beam, polarization, thetap::Float64, phip::Float64, energyp::Float64, initialEn::Float64)\r\n fVolkovMinus = Pulse.envelopeVolkovIntegral(false, envelope, beam, polarization, thetap::Float64, phip::Float64, energyp::Float64, initialEn::Float64)\r\n fVolkovSquared = Pulse.envelopeQuadVolkovIntegral(envelope, beam, polarization, thetap::Float64, phip::Float64, energyp::Float64, initialEn::Float64)\r\n \r\n #println(\"> Envelope integrals for an $(string(envelope)) with A0=$(beam.A0), omega=$(beam.omega) [a.u.], cep=$(beam.cep)\" * \r\n # \" and for $(string(polarization)) light are:\" )\r\n #println(\" F^(Volkov) [+; omega; f^(env); A] = $fVolkovPlus\" )\r\n #println(\" F^(Volkov) [-; omega; f^(env); A] = $fVolkovMinus\" )\r\n #println(\" F^(quad, Volkov) [f^(env); A] = $fVolkovSquared\" )\r\n \r\n return( (fVolkovPlus, fVolkovMinus, fVolkovSquared) )\r\n end\r\n\r\n\r\n \"\"\"\r\n `StrongField.computeOutcome(observable::StrongField.SfaEnergyDistribution, amplitudes::Array{SphericalAmplitude,1})` \r\n ... computes the requested photoelectron energy distribution and returns the results in the variable\r\n outcome::StrongField.OutcomeEnergyDistribution\r\n \"\"\"\r\n function computeOutcome(obs::StrongField.SfaEnergyDistribution, amplitudes::Array{SphericalAmplitude,1})\r\n probabilities = Float64[]\r\n for amp in amplitudes pp = sqrt(2*amp.energy); push!(probabilities, pp * (amp.value * conj(amp.value)) ) end\r\n outcome = OutcomeEnergyDistribution(obs.theta, obs.phi, obs.energies, probabilities)\r\n return( outcome )\r\n end\r\n\r\n \"\"\"\r\n `StrongField.computeOutcome(observable::StrongField.SfaMomentumDistribution, amplitudes::Array{SphericalAmplitude,1})` \r\n ... computes the requested photoelectron momentum distribution and returns the results in the variable\r\n outcome::StrongField.OutcomeMomentumDistribution\r\n \"\"\"\r\n function computeOutcome(obs::StrongField.SfaMomentumDistribution, amplitudes::Array{SphericalAmplitude,1})\r\n probabilities = Float64[]\r\n momenta = Array{Float64}(undef,0,2)\r\n for amp in amplitudes \r\n pp = sqrt(2*amp.energy)\r\n px = pp*sin(amp.theta)*cos(amp.phi)\r\n py = pp*sin(amp.theta)*sin(amp.phi)\r\n momenta = [momenta ; [px py]]\r\n push!( probabilities, pp * (amp.value * conj(amp.value)) )\r\n end\r\n outcome = OutcomeMomentumDistribution(obs.theta, momenta, probabilities)\r\n return( outcome )\r\n end\r\n\r\n \"\"\"\r\n `StrongField.computeSphericalAmplitudes(comp::StrongField.Computation)` \r\n ... computes all necessary spherical amplitudes for the given initial and final levels, the Volkov states\r\n and polarization and by using the pulse envelope integrals. A newAmplitudes::Array{SphericalAmplitude,1} is returned.\r\n \"\"\"\r\n function computeSphericalAmplitudes(comp::StrongField.Computation)\r\n newAmplitudes = SphericalAmplitude[]\r\n #\r\n # First determine which spherical SFA amplitudes need to be computed before the actual computation starts\r\n sfaAmplitudes = StrongField.determineSphericalAmplitudes(comp.observable)\r\n # Determine quantum numbers of the initial and final state\r\n nqn = 1; lqn = 0; n = 1; l = 0; m = 0; initialEn = convertUnits(\"energy: from eV to atomic\", comp.initialLevel.energy)\r\n #\r\n \r\n lpMin = abs(l-1)\r\n lpMax = l+1\r\n \r\n # Compute the requested amplitudes\r\n for amp in sfaAmplitudes\r\n thetap = amp.theta; phip = amp.phi; energyp = amp.energy\r\n envIntegrals = StrongField.computeEnvelopeIntegrals(comp.envelope, comp.beam, comp.polarization, thetap, phip, energyp, initialEn)\r\n fVolkovPlus, fVolkovMinus, fVolkovSquared = envIntegrals\r\n #\r\n reducedMEArray = ComplexF64[]\r\n for lp = lpMin:lpMax\r\n push!( reducedMEArray, pReducedME(energyp, lp, n, l, initialEn, comp.volkov) )\r\n end\r\n #\r\n \r\n wminus = 0.0im; wplus = 0.0im\r\n # Collect contributions from all l_p, q terms; this summation will change in a (nljm) representation\r\n for lp = lpMin:lpMax\r\n reducedME = reducedMEArray[lp-lpMin+1]\r\n for q in [-1, 0, 1]\r\n wplus = wplus + AngularMomentum.sphericalYlm(lp, m-q, amp.theta, amp.phi) * (-1)^q * \r\n Basics.determinePolarizationVector(q, comp.polarization, star=false) *\r\n AngularMomentum.ClebschGordan(l, m, 1, -q, lp, m-q) * reducedME\r\n wminus = wminus + AngularMomentum.sphericalYlm(lp, m+q, amp.theta, amp.phi) * \r\n Basics.determinePolarizationVector(q, comp.polarization, star=true) *\r\n AngularMomentum.ClebschGordan(l, m, 1, q, lp, m+q) * reducedME\r\n end\r\n end\r\n scalarProd = scalarProdBoundCont(energyp, l, n, l, m, initialEn, comp.volkov)\r\n wa = -im * sqrt(2/pi) * (fVolkovPlus * wminus + fVolkovMinus * wplus) - im / sqrt(2*pi) * fVolkovSquared * AngularMomentum.sphericalYlm(l, m, amp.theta, amp.phi) * scalarProd\r\n push!(newAmplitudes, SphericalAmplitude(amp.energy, amp.theta, amp.phi, wa))\r\n \r\n println(\">> $(SphericalAmplitude(amp.energy, amp.theta, amp.phi, wa))\")\r\n end\r\n \r\n return( newAmplitudes )\r\n end\r\n\r\n\r\n \"\"\"\r\n `StrongField.determineSphericalAmplitudes(observable::StrongField.SfaEnergyDistribution)` \r\n ... determines which direct (and other) SFA amplitudes need to be computed; these amplitudes are not yet computed here but can be arranged\r\n so that only a minimum number of Volkov states and/or reduced many-electron matrix elements need to be computed.\r\n A list of amplitudes::Array{StrongField.SphericalAmplitude,1} is returned.\r\n \"\"\"\r\n function determineSphericalAmplitudes(observable::StrongField.SfaEnergyDistribution)\r\n amplitudes = StrongField.SphericalAmplitude[]\r\n for energy in observable.energies push!(amplitudes, SphericalAmplitude(energy, observable.theta, observable.phi, 0.)) end\r\n \r\n println(\"> A total of $(length(amplitudes)) spherical amplitudes need to be calculated.\")\r\n return( amplitudes )\r\n end\r\n \r\n \r\n \"\"\"\r\n `StrongField.determineSphericalAmplitudes(observable::StrongField.SfaMomentumDistribution)` \r\n ... determines which direct (and other) SFA amplitudes need to be computed; these amplitudes are not yet computed here but can be arranged\r\n so that only a minimum number of Volkov states and/or reduced many-electron matrix elements need to be computed.\r\n A list of amplitudes::Array{StrongField.SphericalAmplitude,1} is returned.\r\n \"\"\"\r\n function determineSphericalAmplitudes(observable::StrongField.SfaMomentumDistribution)\r\n amplitudes = StrongField.SphericalAmplitude[]\r\n for energy in observable.energies\r\n for phi in observable.phis\r\n push!(amplitudes, SphericalAmplitude(energy, observable.theta, phi, 0.))\r\n end\r\n end\r\n \r\n println(\"> A total of $(length(amplitudes)) spherical amplitudes need to be calculated.\")\r\n return( amplitudes )\r\n end\r\n \r\n \r\n \"\"\"\r\n `StrongField.plot( comp::StrongField.Computation, results::Dict{String,Any}, energyScale::String = \"atomic\", probabilityScaling::String = \"linear\" )` \r\n ... generates a graphical representation of the observable (either StrongField.SfaEnergyDistribution or StrongField.SfaMomentumDistribution).\r\n energyScale determines the scaling of the energy axis either in atomic units (energyScale = \"atomic\") or in units of hbar*omega (energyScale = \"omega\").\r\n The y-axis is scaled either linearly (probabilityScaling = \"linear\") or logarithmically (probabilityScaling = \"log\")\r\n \"\"\"\r\n function plot( comp::StrongField.Computation, results::Dict{String,Any}, energyScale::String = \"atomic\", probabilityScaling::String = \"linear\" )\r\n \r\n #---Photoelectron energy spectrum---\r\n if typeof(comp.observable) == StrongField.SfaEnergyDistribution\r\n #prepare data and rescale the x-axis if neccessary\r\n if energyScale == \"atomic\"\r\n energyLabel = \"E (a.u.)\"\r\n energies = results[\"energy distribution\"].energies\r\n elseif energyScale == \"omega\"\r\n energyLabel = \"E/omega\"\r\n energies = results[\"energy distribution\"].energies / comp.beam.omega\r\n end\r\n probabilities = results[\"energy distribution\"].probabilities\r\n gr() #sets the plotting backend to the package \"GR\"\r\n \r\n #set scaling of the y-axis\r\n scaling = :identity\r\n if probabilityScaling == \"log\"\r\n scaling = :log10\r\n end\r\n \r\n #generate the plot\r\n p = Plots.plot(energies, probabilities, \r\n title = \"Photoelectron energy spectrum\",\r\n xlabel = energyLabel,\r\n ylabel = \"P(E)\",\r\n xscale = :identity,\r\n yscale = scaling,\r\n framestyle = :box,\r\n legend = :none,\r\n #markershape = :circle,\r\n #markershape = :none,\r\n line = 2,\r\n linecolor = :black,\r\n gridlinewidth = 2,\r\n tickfontsize = 10,\r\n labelfontsize = 10,\r\n labelfontfamily = \"Latin Modern Roman\",\r\n titlefontfamily = \"Latin Modern Roman\"\r\n \r\n )\r\n \r\n #export the plot as png-file\r\n png(\"energy_spectrum\")\r\n #-----------------------------------\r\n \r\n #---Photoelectron momentum distribution---\r\n elseif typeof(comp.observable) == StrongField.SfaMomentumDistribution\r\n #prepare data\r\n pList = results[\"momentum distribution\"].momenta\r\n probList = results[\"momentum distribution\"].probabilities\r\n\r\n #generate the plot\r\n #pyplot()\r\n #r = range(0,stop=10,length=11)\r\n #theta = range(0,stop=360,length=361)\r\n #f(r,theta) = r^2\r\n #println(\"$(f.(r,theta'))\")\r\n #Plots.plot( heatmap( f.(r,theta'), proj=:polar ) )\r\n #println(\"$(transpose(probList))\")\r\n #Plots.plot( heatmap( pList, transpose(probList), proj=:polar ) )\r\n #imshow(pList,transpose(probList))\r\n #probList = probList[2:-1]\r\n #matplotlib.pyplot.pcolormesh(pList[:,1], pList[:,2], transpose(probList))\r\n contourf( pList[:,1], pList[:,2], probList )\r\n #matplotlib.pyplot.imshow(pList)\r\n #heatmap( pList[:,1], pList[:,2], probList, proj=:polar, legend=true\r\n #heatmap( probList\r\n # )\r\n\r\n #p = Plots.plot( #heatmap( pList[:,1], pList[:,2], probList\r\n # Plots.GR.polarheatmap( probList \r\n ##heatmap( probList\r\n # )\r\n # )\r\n \r\n \r\n #export the plot as png-file\r\n png(\"momentum_distribution\")\r\n #-----------------------------------------\r\n \r\n #---Not a valid obserable---\r\n else \r\n error(\"Undefined observable for strong-field computations.\")\r\n end\r\n #---------------------------\r\n \r\n end\r\n\r\n \"\"\"\r\n `StrongField.perform(comp::StrongField.Computation; output::Bool=false)` \r\n ... to perform a computation of (one) selected observable that is related to SFA, such as a photoelectron energy \r\n distribution, momentum distribution or the computation of sidebands.\r\n \"\"\"\r\n function perform(comp::StrongField.Computation; output::Bool=false)\r\n if output results = Dict{String, Any}() else results = nothing end\r\n nModel = comp.nuclearModel\r\n \r\n if typeof(comp.observable) == StrongField.SfaEnergyDistribution\r\n sfaAmplitudes = StrongField.computeSphericalAmplitudes(comp)\r\n sfaOutcome = StrongField.computeOutcome(comp.observable, sfaAmplitudes)\r\n if output results = Base.merge( results, Dict(\"computation\" => comp, \"energy distribution\" => sfaOutcome) ) end\r\n elseif typeof(comp.observable) == StrongField.SfaMomentumDistribution\r\n sfaAmplitudes = StrongField.computeSphericalAmplitudes(comp)\r\n sfaOutcome = StrongField.computeOutcome(comp.observable, sfaAmplitudes)\r\n if output results = Base.merge( results, Dict(\"computation\" => comp, \"momentum distribution\" => sfaOutcome) ) end\r\n else error(\"Undefined observable for strong-field computations.\")\r\n end\r\n \r\n if output return( results ) else return( nothing ) end\r\n end\r\n\r\nend # module\r\n\r\n", "meta": {"hexsha": "8d48b69e96d6798ce22126bba12c36e08e8efd91", "size": 36577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-StrongField.jl", "max_stars_repo_name": "sostock/JAC.jl", "max_stars_repo_head_hexsha": "ae70a6b3277ea7e46f53f97cdc7a6ffd12e1faf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module-StrongField.jl", "max_issues_repo_name": "sostock/JAC.jl", "max_issues_repo_head_hexsha": "ae70a6b3277ea7e46f53f97cdc7a6ffd12e1faf9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-StrongField.jl", "max_forks_repo_name": "sostock/JAC.jl", "max_forks_repo_head_hexsha": "ae70a6b3277ea7e46f53f97cdc7a6ffd12e1faf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.3122420908, "max_line_length": 224, "alphanum_fraction": 0.560406813, "num_tokens": 8608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24276019912445276}} {"text": "include(\"default_params.jl\")\ninclude(\"model_def.jl\")\n\nks_errors = DataFrame(DG=[],DG_limit=[],Order_1=[],QBDRAP=[])\nl1_errors = DataFrame(DG=[],DG_limit=[],Order_1=[],QBDRAP=[])\nl1_cell_probs_errors = DataFrame(DG=[],DG_limit=[],Order_1=[],QBDRAP=[])\nks_error_row = zeros(4)\nl1_error_row = zeros(4)\nl1_cell_probs_row = zeros(4)\n\nsim_cdf = CSV.read(\n (@__DIR__)*\"/data/sims_cdf_evaluated.csv\",\n DataFrame,\n)\n\nfor o in orders\n cols = [1;3;4]\n for (c,m) in enumerate(string.(approx_types[[1;3;4]]).*string.([1;3;4]))\n approx_data = CSV.read(\n (@__DIR__)*\"/data/first_return_cdf_approximations/order_\"*string(o)*\"_model_\"*m*\".csv\",\n DataFrame,\n )\n ks_error = max(\n maximum(abs.(approx_data.phase_2-sim_cdf.phase_2)),\n maximum(abs.(approx_data.phase_4-sim_cdf.phase_4)),\n )\n ks_error_row[cols[c]] = ks_error\n l1_cdf = sum(abs.(approx_data.phase_2[1:end-1]+approx_data.phase_2[2:end]-\n sim_cdf.phase_2[1:end-1]-sim_cdf.phase_2[2:end]).*diff(approx_data.x))/2 + \n sum(abs.(approx_data.phase_4[1:end-1]+approx_data.phase_4[2:end]-\n sim_cdf.phase_4[1:end-1]-sim_cdf.phase_4[2:end]).*diff(approx_data.x))/2\n l1_error_row[cols[c]] = l1_cdf\n cell_edges_idx = findall(mod.(approx_data.x,0.4).==0.0)\n sim_cell_probs = DataFrame(\n x=[approx_data.x[1]; approx_data.x[cell_edges_idx[2:end]] - approx_data.x[cell_edges_idx[1:end-1]]],\n phase_2=[sim_cdf.phase_2[1]; sim_cdf.phase_2[cell_edges_idx[2:end]] - sim_cdf.phase_2[cell_edges_idx[1:end-1]]],\n phase_4=[sim_cdf.phase_4[1]; sim_cdf.phase_4[cell_edges_idx[2:end]] - sim_cdf.phase_4[cell_edges_idx[1:end-1]]],\n )\n approx_cell_probs = DataFrame(\n x=[approx_data.x[1]; approx_data.x[cell_edges_idx[2:end]] - approx_data.x[cell_edges_idx[1:end-1]]],\n phase_2=[approx_data.phase_2[1]; approx_data.phase_2[cell_edges_idx[2:end]] - approx_data.phase_2[cell_edges_idx[1:end-1]]],\n phase_4=[approx_data.phase_4[1]; approx_data.phase_4[cell_edges_idx[2:end]] - approx_data.phase_4[cell_edges_idx[1:end-1]]],\n )\n l1_cell_probs_row[cols[c]] = sum(abs.(approx_cell_probs.phase_2-sim_cell_probs.phase_2)) + \n sum(abs.(approx_cell_probs.phase_4-sim_cell_probs.phase_4))\n end\n push!(ks_errors,ks_error_row)\n push!(l1_errors,l1_error_row)\n push!(l1_cell_probs_errors,l1_cell_probs_row)\nend\n\nCSV.write((@__DIR__)*\"/data/errors/ks_error.csv\",ks_errors)\nCSV.write((@__DIR__)*\"/data/errors/l1_error.csv\",l1_errors)\nCSV.write((@__DIR__)*\"/data/errors/l1_cell_probs_error.csv\",l1_cell_probs_errors)\n\nks_errors_lwr = DataFrame(DG=[],DG_limit=[],Order_1=[],QBDRAP=[])\nl1_errors_lwr = DataFrame(DG=[],DG_limit=[],Order_1=[],QBDRAP=[])\nl1_cell_probs_errors_lwr = DataFrame(DG=[],DG_limit=[],Order_1=[],QBDRAP=[])\nks_error_row_lwr = zeros(4)\nl1_error_row_lwr = zeros(4)\nl1_cell_probs_error_row_lwr = zeros(4)\n\nks_errors_upr = DataFrame(DG=[],DG_limit=[],Order_1=[],QBDRAP=[])\nl1_errors_upr = DataFrame(DG=[],DG_limit=[],Order_1=[],QBDRAP=[])\nl1_cell_probs_errors_upr = DataFrame(DG=[],DG_limit=[],Order_1=[],QBDRAP=[])\nks_error_row_upr = zeros(4)\nl1_error_row_upr = zeros(4)\nl1_cell_probs_error_row_upr = zeros(4)\n\nks_error_boot = zeros(n_boot)\nl1_error_boot = zeros(n_boot)\nl1_cell_probs_error_boot = zeros(n_boot)\nfor o in orders\n cols = [1;3;4]\n for (c,m) in enumerate(string.(approx_types[[1;3;4]]).*string.([1;3;4]))\n approx_data = CSV.read(\n (@__DIR__)*\"/data/first_return_cdf_approximations/order_\"*string(o)*\"_model_\"*m*\".csv\",\n DataFrame,\n )\n cell_edges_idx = findall(mod.(approx_data.x,0.4).==0.0)\n approx_cell_probs = DataFrame(\n x=[approx_data.x[1]; approx_data.x[cell_edges_idx[2:end]] - approx_data.x[cell_edges_idx[1:end-1]]],\n phase_2=[approx_data.phase_2[1]; approx_data.phase_2[cell_edges_idx[2:end]] - approx_data.phase_2[cell_edges_idx[1:end-1]]],\n phase_4=[approx_data.phase_4[1]; approx_data.phase_4[cell_edges_idx[2:end]] - approx_data.phase_4[cell_edges_idx[1:end-1]]],\n )\n for n in 1:n_boot\n sim_cdf = CSV.read(\n (@__DIR__)*\"/data/bootstrap_first_return/sample_\"*string(n)*\".csv\",\n DataFrame,\n )\n ks_error = max(\n maximum(abs.(approx_data.phase_2-sim_cdf.phase_2)),\n maximum(abs.(approx_data.phase_4-sim_cdf.phase_4)),\n )\n ks_error_boot[n] = ks_error\n l1_cdf = sum(abs.(approx_data.phase_2[1:end-1]+approx_data.phase_2[2:end]-\n sim_cdf.phase_2[1:end-1]-sim_cdf.phase_2[2:end]).*diff(approx_data.x))/2 + \n sum(abs.(approx_data.phase_4[1:end-1]+approx_data.phase_4[2:end]-\n sim_cdf.phase_4[1:end-1]-sim_cdf.phase_4[2:end]).*diff(approx_data.x))/2\n l1_error_boot[n] = l1_cdf\n sim_cell_probs = DataFrame(\n x=[approx_data.x[1]; approx_data.x[cell_edges_idx[2:end]] - approx_data.x[cell_edges_idx[1:end-1]]],\n phase_2=[sim_cdf.phase_2[1]; sim_cdf.phase_2[cell_edges_idx[2:end]] - sim_cdf.phase_2[cell_edges_idx[1:end-1]]],\n phase_4=[sim_cdf.phase_4[1]; sim_cdf.phase_4[cell_edges_idx[2:end]] - sim_cdf.phase_4[cell_edges_idx[1:end-1]]],\n )\n l1_cell_probs_error_boot[n] = sum(abs.(approx_cell_probs.phase_2-sim_cell_probs.phase_2)) + \n sum(abs.(approx_cell_probs.phase_4-sim_cell_probs.phase_4))\n end\n ks_error_row_lwr[cols[c]] = quantile(ks_error_boot,qtiles[1])\n l1_error_row_lwr[cols[c]] = quantile(l1_error_boot,qtiles[1])\n l1_cell_probs_error_row_lwr[cols[c]] = quantile(l1_cell_probs_error_boot,qtiles[1])\n ks_error_row_upr[cols[c]] = quantile(ks_error_boot,qtiles[2])\n l1_error_row_upr[cols[c]] = quantile(l1_error_boot,qtiles[2])\n l1_cell_probs_error_row_upr[cols[c]] = quantile(l1_cell_probs_error_boot,qtiles[2])\n end\n push!(ks_errors_lwr,ks_error_row_lwr)\n push!(l1_errors_lwr,l1_error_row_lwr)\n push!(l1_cell_probs_errors_lwr,l1_cell_probs_error_row_lwr)\n push!(ks_errors_upr,ks_error_row_upr)\n push!(l1_errors_upr,l1_error_row_upr)\n push!(l1_cell_probs_errors_upr,l1_cell_probs_error_row_upr)\nend\n\nCSV.write((@__DIR__)*\"/data/errors/ks_error_lwr.csv\",ks_errors_lwr)\nCSV.write((@__DIR__)*\"/data/errors/l1_error_lwr.csv\",l1_errors_lwr)\nCSV.write((@__DIR__)*\"/data/errors/l1_cell_probs_error_lwr.csv\",l1_cell_probs_errors_lwr)\nCSV.write((@__DIR__)*\"/data/errors/ks_error_upr.csv\",ks_errors_upr)\nCSV.write((@__DIR__)*\"/data/errors/l1_error_upr.csv\",l1_errors_upr)\nCSV.write((@__DIR__)*\"/data/errors/l1_cell_probs_error_upr.csv\",l1_cell_probs_errors_upr)\n\n", "meta": {"hexsha": "33177deaadbf6cb1de0d8924bbf1a31ba911624a", "size": 6839, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fluidfluid_discontinuous/evaluate_errors.jl", "max_stars_repo_name": "angus-lewis/DFQExamples.jl", "max_stars_repo_head_hexsha": "1dc23e42205e985a16552e4c4b21e4472525e36b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fluidfluid_discontinuous/evaluate_errors.jl", "max_issues_repo_name": "angus-lewis/DFQExamples.jl", "max_issues_repo_head_hexsha": "1dc23e42205e985a16552e4c4b21e4472525e36b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fluidfluid_discontinuous/evaluate_errors.jl", "max_forks_repo_name": "angus-lewis/DFQExamples.jl", "max_forks_repo_head_hexsha": "1dc23e42205e985a16552e4c4b21e4472525e36b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.2061068702, "max_line_length": 140, "alphanum_fraction": 0.6740751572, "num_tokens": 2101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.24238178604150765}} {"text": "module TIFFtoRegression\n\n############################################################################\n# Reading the values of the TIFF according to TIFF v0.6\n\nfunction FieldValues(ValueOffset::Int64,FileNumber::Array{Int16},FieldCount::Int64,FieldType=4::Int64) #v2\n# =========================== Value or Pointer ? ===============================\nValuePointer=0::Int64\nif FieldCount==1 # Simplified criterion of \"can hold that much info on 4 bytes\"\n Value=ValueOffset\nelse\n ValuePointer=ValueOffset+1 # correction due to the first being 0 and not 1\nend\n\nif ValuePointer==0\n DesiredV=Value\nelse\n #println(\"$ValuePointer, Count=$FieldCount, Type=$FieldType\")\n DesiredV=zeros(1,FieldCount)\n for i=1:FieldCount\n Vi=0\n if FieldType == 2 || FieldType==1 #ASCII or BYTE\n FieldTypeByte=1\n elseif FieldType==3 # Short\n FieldTypeByte=2\n elseif FieldType==4 # Long\n FieldTypeByte=4\n elseif FieldType==5 # Rational\n FieldTypeByte=8\n end\n\n for jj=1:FieldTypeByte\n Vjj=FileNumber[ValuePointer+FieldTypeByte*(i-1)+jj-1]*256^(jj-1)\n Vi=Vi+Vjj\n end\n DesiredV[i]=convert(Int64,Vi)\n end\nend\n\nreturn DesiredV\nend\n#############################################################################\n\n# Reading a TIFF (also able to read special Dantec TIFF that are pseudo Std)\n\nfunction AquiTiff(FilePath::String)\n # Opening File\n FileString=read(FilePath)\n L=length(FileString)\n FileNumber=zeros(Int16,L,1)\n for i=1:L\n NumberI=convert(Int16,FileString[i])\n FileNumber[i]=NumberI\n end\n # ============================ Reading Header ================================\n IFD=FileNumber[5]+1+FileNumber[6]*256+FileNumber[7]*256^2+FileNumber[8]*256^3 # indicates where the Image File Directory starts (i e where the meta data start)\n # +1 in the indexes is a consequence of the starting count from 0 to 1 in tiff ==> JuliaVector\n if FileNumber[1]==73 & FileNumber[2]==73 # Small endian (determines the order of the bites from bigger to smaller)\n # ======================== Reading Metadata: ================================\n # ------------------------- Opening Values ----------------------------------\n Entries=FileNumber[IFD]+256*FileNumber[IFD+1] # Number of Entries in the IFD\n # Opening Values that might be in the Metadata\n Height=0::Int64\n Width=0::Int64\n BPS=0::Int64 #Bit per Sample\n CompType=0::Int64 #Type of Compression\n BlackWhite=0::Int64 #Photometric Interpretation # 0=White is Zero; 1<=Black is Zero\n StripOffsets=0::Int64 #Places where data is stored\n NFragData=0::Int64 # Number of those Places\n Orientation=0::Int64 # 1=Start Top-left\n SPPx=0::Int64 # Sample per Pixel\n RowsPStrip=0::Int64 # Rows per data strip: ceilling(Height/RowsPStrip)=Number of strip (p19)\n StripByteCount=0::Int64 #For each strip the number of bytes in that strip AFTER compression\n XRes=0::Int64 # X-Resolution : nbr of px per Resolution unit (cm/inch see 296)\n YRes=0::Int64 # Y-Resolution\n PlanConfig=0::Int64 # Planar Configuration ???\n ResUnit=0::Int64 # Resolution Unit : abstract (=0), cm (=1) or inch (=2)\n Software=0::Int64 # Software used to create the Tiff\n SBCType=0::Int64\n StripOffsets=[]\n NBytesPPx=0::Int64 # Spec Dantec Dynamics\n # --------------------------------------------------------------------------\n\n for i=1:Entries # All MetaData there are\n # ----------------------- Initiating Entry--------------------------------\n # Delimiting entry\n StartE=IFD+12*(i-1)+2\n EndE=StartE+11\n EntryN=FileNumber[StartE:EndE] #Taking one entry of 12 hexa bytes\n # Reading Entry\n FieldID=EntryN[1]+EntryN[2]*256\n FieldType=EntryN[3]+EntryN[4]*256\n FieldCount=EntryN[5]+EntryN[6]*256+EntryN[7]*65536+EntryN[8]*16777216\n ValueOffset=EntryN[9]+EntryN[10]*256+EntryN[11]*65536+EntryN[12]*16777216\n # Is either the value of the entry or a pointer towards the place where the values are kept if the entry can't be held on 8bits\n # ----------------------- Switch on FieldID ------------------------------\n if FieldID==254 # NewSubFileType\n NewSubFileType=FieldValues(ValueOffset,FileNumber,FieldCount)\n # 2 : Multipage\n # 4 : Defines a transparency mask\n elseif FieldID==256 # Image Width= n° of column in the Image\n Width=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==257 # Height\n Height=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==258 # Bits/sample ==> number of shade of gray allowable\n BPS=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==259 # Compression Type\n CompType=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==262 # Photometric Interpretation\n # 0=White is Zero; 1<=Black is Zero\n BlackXhite=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==273 # StripOffsets= Position of all data StripOffsets\n NFragData=FieldCount\n StripOffsets=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==274 # Orientation of the Picture\n # 1=Start Top-left\n Orientation=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==277 # Sample/px (3 or more ==> Number of colors allowable)\n SPPx=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==278 # Rows per Strip\n RowsPStrip=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==279 # StripByteCount\n StripByteCount=FieldValues(ValueOffset,FileNumber,FieldCount)\n SBCType=FieldType\n elseif FieldID==282 # X-Resolution\n XRes=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==283 # Y-Resolution\n YRes=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==284 # Planar Configuration\n PlanConfig=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==285\n PageName=FieldValues(ValueOffset,FileNumber,FieldCount,FieldType)\n elseif FieldID==296 # Resolution Unit (cm/inch)\n ResUnit=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==297\n PageNumber=FieldValues(ValueOffset,FileNumber,FieldCount,FieldType)\n elseif FieldID==305 # Software\n #Software=FieldValues(ValueOffset,FileNumber,FieldCount)\n elseif FieldID==32997\n #Specific to DynamicStudio, Dantec\n # Number of bytes/ px? TBC\n NBytesPPx=FieldValues(ValueOffset,FileNumber,FieldCount)\n if SPPx==0\n SPPx=2 #NBytesPPx/8 # Works?\n SPPx=convert(Int64,SPPx)\n end\n end # Metadata Aquisition\n end\n EndIFD=IFD+12*(Entries-1)+13\n elseif FileNumber[1]==77 & FileNumber[2]==77 #big endian\n println(\"Big Endian Still to be implemented, nearly same as small endian\")\n end\n # ======================= Creating the Img Matrix ============================\n # ----------------------- Finding and Ordering Px ---------------------------\n PixelString=[]\n PixelNumber=ones(1,length(FileNumber))\n CountLeng=0\n for i=1:NFragData\n PxStrip=FileNumber[convert(Int64,StripOffsets[i]):convert(Int64,StripOffsets[i]+StripByteCount[i])]\n l=length(PxStrip)\n PixelNumber[1+1+CountLeng:1+l+CountLeng]=PxStrip[1:l]\n CountLeng=CountLeng+l\n end\n PixelNumber=PixelNumber[1:CountLeng] # cutting the exedentary ones (due to the last strip being sometimes shorter than the others)\n # ------------------------ Making Order in the Px ----------------------------\n ImgArray=zeros(Int64,Height,Width,SPPx)\n for i=1:Height\n for j=1:Width\n for k=1:SPPx\n if NBytesPPx==0\n Pxijk=((i-1)*Width+(j-1))*SPPx+k\n else # Why ? 171 dtmed empirically for Dynamic Studio Tif)\n #Pxijk=((i-1)*Width+(j-1))*SPPx+k\n Pxijk=((i-1)*Width+(j+convert(Int64,floor(171*i/Height))-1))*SPPx+k # ???????????????????????????????????????????????????\n end\n ImgArray[i,j,k]=PixelNumber[Pxijk]\n end\n end\n end\n #--------------------- Making it Gray Matrix ---------------------------------\n if NBytesPPx==0 # Suposedly \"Normal Img or Color Img\"\n #GrayArray=sum(ImgArray,3)/SPPx\n GrayArray=ImgArray[:,:,3]\n else\n GrayArray=ImgArray[:,:,1]*256+ImgArray[:,:,2] # Dantec Spec\n end\nreturn GrayArray[:,:,1]\nend\n\n###########################################################################\n\n# Loading a Serie of TIFF from Dantec Dynamics\n\nfunction AquiSerieD(Folder::String, File0::String, NbrImg=189::Int64)\n # ========================== Making Img Path =================================\n # ----------------Cutting File0 (Dantec DynamicsStudio Naming)----------------\n j=1\n while File0[j]!='.'\n j=j+1\n end\n p1=j\n #println(p1)\n BaseName=File0[1:p1-1] # Input by User exporting Img\n j=j+1\n while File0[j]!='.'\n j=j+1\n end\n p2=j\n FileSerie=File0[p1+1:p2-1] #Auto Serie Numbering\n NumberInSerie=File0[p2+1:end] # Auto Img Numbering\n N=NbrImg-1 # Numbering Starts at 0 not 1\n ImgArray=[]\n OneAdress=[]\n # ------------------------ Making Image Number String -------------------------\n for i=0:N\n # Finding k\n LNIS=length(NumberInSerie)\n k=LNIS\n while floor(i/(10.0^k))<1 && k>=0\n k=k-1\n end\n # completing the NumberIn Serie String\n NIS=\"\"\n ik=i\n for kk=LNIS:-1:1\n if kk>k+1\n NIS=\"$(NIS)0\"\n else\n V=convert(Int64,floor(ik/(10^(kk-1))))\n NIS=\"$(NIS)$V\"\n ik=ik-V*10^(kk-1)\n end\n end\n OneAdress=\"$(Folder)\\\\$(BaseName).$(FileSerie).$(NIS).tif\"\n #println(OneAdress)\n # ========================= Aquiring Images ==================================\n OneImg=AquiTiff(OneAdress)\n if isempty(ImgArray)\n ImgArray=zeros(Int64,size(OneImg,1),size(OneImg,2),N+1)\n ImgArray[:,:,1]=OneImg\n else\n ImgArray[:,:,i+1]=OneImg\n end\n end\nreturn ImgArray # to assure Julia wont print the Array\nend\n#############################################################################\n\n# Loading a Serie of TIFF automaticaly renamed with Windows 10\n\nfunction AquiSerieW(Folder::String, File0::String, NbrImg=189::Int64)\n # ========================== Making Img Path =================================\n # ----------------Cutting File0 (Dantec DynamicsStudio Naming)----------------\n j=1\n while File0[j]!='('\n j=j+1\n end\n p1=j\n #println(p1)\n BaseName=File0[1:p1-1] # Input by User + 1 space (std windows renumerotation)\n j=j+1\n\n ImgArray=[]\n OneAdress=[]\n # ------------------------ Making Image Number String -------------------------\n for i=1:NbrImg\n OneAdress=\"$(Folder)\\\\$(BaseName)($i).tif\"\n #println(OneAdress)\n # ========================= Aquiring Images ==================================\n OneImg=AquiTiff(OneAdress)\n if isempty(ImgArray)\n ImgArray=zeros(Int64,size(OneImg,1),size(OneImg,2),NbrImg)\n ImgArray[:,:,1]=OneImg\n else\n ImgArray[:,:,i]=OneImg\n end\n end\nreturn ImgArray # to assure Julia wont print the Array\nend\n\n#############################################################################\n\n# Creating a Special type to stock the start of a line and its values\ntype Line # Creates type Line\n YValues::Vector\n XStart::Int64\nend\n##############################################################################\n\n# Detecting the Lines in an image matrix (also retourning a Binary matrix)\n\nfunction DetectLine(Img::Matrix)\n # only for bicolor ImgLine\n BiMat=zeros(Bool,size(Img))\n BiMat0=zeros(Bool,size(Img))\n Max=maximum(Img)\n min=minimum(Img)\n moy=(Max+min)/2\n# --------------------------BiColoring----------------------------------\n k=0\n for i=1:size(Img,1) #BiLeveling\n for j=1:size(Img,2)\n if Img[i,j]<=moy\n BiMat[i,j]=0\n BiMat0[i,j]=0\n else\n BiMat[i,j]=1\n BiMat0[i,j]=1\n end\n end\n end\n\nSumMat=sum(BiMat)\nH=size(BiMat,1)\nL=size(BiMat,2)\nNPx=H*L\nif SumMat=2 && ConLine# going up to top\n # find [Background; Line]\n YmeanV=[]\n if [LinePx; BckGrnd]==[BiMat[y-1,x]; BiMat[y,x]] # Line Start Detect\n #Xcount=Xcount-1 #Stay in the same column and check further\n # Special Start in case of Split\n if YmeanM1 != H\n push!(YmeanV,YmeanM1)\n XStart=x-1\n YmeanM1=H\n else #End Spec Split\n XStart=x\n end\n y=y-1\n YStart=y\n # Start of a Line\n while BiMat[y,x]==LinePx\n y=y-1\n end\n YEnd=y+1\n # following that one line\n Width=abs(YStart-YEnd)+1\n BiMat[YEnd:YStart,x]=repmat([BckGrnd],Width,1)\n Ymean=(YStart+YEnd)/2\n push!(YmeanV,Ymean)\n while ConLine && x1\n if sum(BiMat[YEnd-1:YStart+1,x].==repmat([BckGrnd],Width+2,1))==Width+2\n # Line Stop\n ConLine=false\n YStart=0\n YEnd=0\n x=Xcount\n Xcount=Xcount-1\n else\n # Line continue\n if BiMat[YEnd-1:YStart+1,x]==[BckGrnd;repmat([LinePx],Width,1);BckGrnd]\n # Line constant in Value and Width\n else\n # Line continue but changed\n if (BiMat[YStart:YStart+1,x]==[LinePx;LinePx])||(BiMat[YEnd-1:YEnd,x]==[LinePx;LinePx])\n # Line increase or decrease\n if (BiMat[YStart:YStart+1,x]==[LinePx;LinePx]) && !(BiMat[YEnd-1:YEnd,x]==[LinePx;LinePx])\n # Decreasing\n YEnd=YEnd+minimum(findin(BiMat[YEnd:YStart,x].==repmat([LinePx],Width,1),true))-1\n yy=YStart\n while BiMat[yy+1,x]==LinePx && yy1\n yy=yy-1\n end\n YEnd=yy\n elseif (BiMat[YStart:YStart+1,x]==[LinePx;LinePx]) && (BiMat[YEnd-1:YEnd,x]==[LinePx;LinePx]) # Increse in up and down\n if sum(BiMat[YEnd-1:YStart+1,x].==LinePx)==(YStart+1-(YEnd-1)+1)# No hole\n # Increse in Width in both side\n ydown=YStart\n while BiMat[ydown+1,x]==LinePx && ydown1\n yup=yup-1\n end\n YEnd=yup\n else # there is a hole\n # Split in two curves\n Split= true\n PosHole=findin(BiMat[YEnd-1:YStart+1,x].==BckGrnd,true)\n # Down Part Continues\n YEnd=(YEnd-1+minimum(PosHole))-1 # (below hole)\n ydown=YStart\n while BiMat[ydown+1,x]==LinePx && ydown1 #!isempty(YmeanV)\n Line1=Line(H+1-YmeanV,XStart) # Assuming left bottom axis =0\n #then complete Lines\n push!(Lines,Line1)\n ConLine=false # end current line\n end\n end\n Xcount=Xcount+1\nend\n# from bottom to top\n# 1 First column -> detect LinePx\n# 1b if no LinePx go to the right\n# 2 continue climbing until Px!=LinePx\n# 3 from there moove to the right following the line\n# 3a check same Px and Px+1 and Px-1\n# 3b if Px+-1 check also Px+-2, etc\n# if no Px: line stop\n# 3c repeat 3 until line stop\n# 4 remoove selected Px\n# 5 repeat operation until top right\nreturn BiMat0, Lines\nend\n\n#############################################################################\n\n# Allowing to plot the new type created, eventually on the matrix (thanks to PyPlot)\n\nfunction PlotLine(Lines::Array{Any},H=0::Int64)\n for i=1:length(Lines)\n XS=Lines[i].XStart\n YV=Lines[i].YValues\n if H==0\n plot(XS:XS+length(YV)-1,YV,\"-\")\n else\n plot(XS-1:XS-1+length(YV)-1,H-YV,\"-\")\n end\n end\nend\n\n############################################################################\n\n# Creating the next function for the Multiple Regression Function below\n\nfunction NextFun(Xin::Vector,RegFuns=\"Poly\"::String,i=1::Int64)\n n=length(Xin)\n if RegFuns==\"Poly\"\n Xout=Xin.^(i)\n XT=(\"Poly Order $i\")\n elseif RegFuns==\"Trigo\"\n if isinteger(i/2)\n Xout=cos.(Xin/maximum(Xin)*(i/2))\n XT=(\"Standirdize cos($i x/2)\")\n else\n Xout=cos.(Xin/maximum(Xin)/((i+1)/2))\n XT=(\"Standirdize cos($(1/(i+1)) x/2)\")\n end\n elseif RegFuns==\"Frac\"\n F=findin(Xin,0)\n for j=1:length(F)\n X[F[j]]=mean(abs(Xin))*10^-5\n end\n Xout=1./Xin.^i\n if abs(minimum(Xout))< 2e-15 # all becoming too small\n println(\"Elements becoming too small X=ones\")\n Xout=ones(size(Xin))\n XT=(\"Ones\")\n else\n XT=(\"Frac Order $i\")\n end\n elseif RegFuns==\"Expo\"\n Xout=exp.(i*Xin/maximum(Xin))\n XT=(\"Standardize exp($i x)\")\n elseif RegFuns==\"Loga\"\n Xout=log.(abs(Xin+(i-2)*sqrt(maximum(Xin))))\n XT=(\"log(x+$(i-2) sqrt(Max))\")\n elseif RegFuns==\"Mixte\"\n NFam=5 #nbr of family used (code written could be improoved)\n if isinteger((i+NFam-1)/NFam)\n k=(i+NFam-1)/NFam\n Xout=Xin.^k\n XT=(\"Poly Order $k\") #Poly\n elseif isinteger((i+NFam-2)/NFam)\n k=(i+NFam-2)/NFam\n F=findin(Xin,0)\n for j=1:length(F)\n X[F[j]]=mean(abs(Xin))*10^-5\n end\n Xout=1./Xin.^k\n if abs(minimum(Xout))< 2e-15 # all becoming too small\n println(\"Elements becoming too small X=rand\")\n Xout=rand(size(Xin))\n else\n XT=(\"Frac Order $k\")\n end #Frac\n elseif isinteger((i+NFam-3)/NFam)\n k=(i+NFam-3)/NFam\n #NTrigo=4\n if isinteger(k/2)\n Xout=cos.(Xin/maximum(Xin)*(k/2))\n XT=(\"Standirdize cos($k x/2)\")\n else\n Xout=cos.(Xin/maximum(Xin)/(k+1)/2)\n XT=(\"Standirdize cos($(1/(k+1)) x/2)\")\n end #Trigo\n elseif isinteger((i+NFam-4)/NFam)\n k=(i+NFam-3)/NFam\n Xout=exp.(k*Xin/maximum(Xin))\n XT=(\"Standardize exp($k x)\") #Expo\n elseif isinteger((i+NFam-5)/NFam)\n k=(i+NFam-5)/NFam\n Xout=log.(abs(Xin+(k-2)*sqrt(maximum(Xin))))\n XT=(\"log(x+$(k-2) sqrt(Max))\")\n end\n elseif RegFuns==\"Custom\" # Would their be another interesting family\n println(\"What next fun do you want ? (Existing type: Poly, Trigo, Frac, Expo or Loga) \\n Your choice is :\")\n SwCu=input() #Switch Custom\n if SwCu==\"Poly\"\n println(\"Order of the wanted term : y=x^{Order} ? \\n Order=\")\n u=parse(Float64,input())\n if isinteger(u)\n Xu=Xin\n else\n Xu=Xin\n Xu[find(Xu.<0)]=zeros(size(find(Xu.<0)))\n println(\"All smaller than 0 elements have been replaced by zero for Poly Order $u\")\n end\n Xout=Xu.^(u)\n XT=(\"Poly Order $u\")\n elseif SwCu==\"Trigo\"\n println(\"Normal or Inverse ? \\n Your choice is :\")\n TTrig=input()\n if TTrig==\"Normal\"\n println(\"What type do you want ? (Possible choices: cos, sin, tan or cot) \\n Your choice is :\")\n TrigN=input()\n if TrigN==\"sin\"\n pritnln(\"What Angulat fequency (omega) do you want ? \\n omega =\")\n omega=parse(Float64,input())\n println(\"What Dephasage (phi) do you want ? \\n phi =\")\n phi=parse(Float64,input())\n Xout=sin.(omega*Xin+phi)\n XT=(\"sin($omega x+$phi)\")\n elseif TrigN==\"cos\"\n pritnln(\"What Angulat fequency (omega) do you want ? \\n omega =\")\n omega=parse(Float64,input())\n println(\"What Dephasage (phi) do you want ? \\n phi =\")\n phi=parse(Float64,input())\n Xout=cos.(omega*Xin+phi)\n XT=(\"cos($omega x+$phi)\")\n elseif TrigN==\"tan\"\n pritnln(\"What Angulat fequency (omega) do you want ? \\n omega =\")\n omega=parse(Float64,input())\n println(\"What Dephasage (phi) do you want ? \\n phi =\")\n phi=parse(Float64,input())\n Xout=tan.(omega*Xin+phi)\n XT=(\"tan($omega x+$phi)\")\n elseif TrigN==\"cot\"\n pritnln(\"What Angulat fequency (omega) do you want ? \\n omega =\")\n omega=parse(Float64,input())\n println(\"What Dephasage (phi) do you want ? \\n phi =\")\n phi=parse(Float64,input())\n Xout=cot.(omega*Xin+phi)\n XT=(\"cot($omega x+$phi)\")\n end\n elseif TTrig==\"Inverse\"\n println(\"What type do you want ? (Possible choices: acos, asin, atan or acot) \\n Your choice is :\")\n TrigN=input()\n if TrigN==\"asin\"\n pritnln(\"Vector is standardize (Divided by Max)\")\n println(\"f ? : asin(XStd/f) (abs(f)>1)? \\n f=\")\n f=parse(Float64,input())\n if abs(f)<1\n f=1\n end\n Xout=asin.(Xin/maximum(abs(Xin))/f)\n XT=(\"asin(XStd/$f)\")\n elseif TrigN==\"acos\"\n pritnln(\"Vector is standardize (Divided by Max)\")\n println(\"f ? : acos(XStd/f) (abs(f)>1)? \\n f=\")\n f=parse(Float64,input())\n if abs(f)<1\n f=1\n end\n Xout=acos.(Xin/maximum(abs(Xin))/f)\n XT=(\"acos(XStd/$f)\")\n elseif TrigN==\"atan\"\n println(\"What Factor f ? (atan(fX+t)) \\n f=\")\n f=parse(Float64,input())\n println(\"What terme ? \\n t=\")\n t=parse(Float64,input())\n Xout=atan.(f*Xin+t)\n XT=(\"atan(fX+t)\")\n elseif TrigN==\"acot\"\n println(\"What Factor f ? (acot(fX+t)) \\n f=\")\n f=parse(Float64,input())\n println(\"What terme ? \\n t=\")\n t=parse(Float64,input())\n Xout=acot.(f*Xin+t)\n XT=(\"acot(fX+t)\")\n end\n end\n elseif SwCu==\"Frac\"\n println(\"Order of the wanted term : y=x^-{Order} ? \\n Order=\")\n u=parse(Float64,input())\n if isinteger(u)\n Xu=Xin\n else\n Xu=Xin\n Xu[find(Xu.<=0)]=ones(size(find(Xu.<0)))\n println(\"All smaller than or equal to 0 elements have been replaced by one for Frac Order $u\")\n end\n Xout=1./(Xu.^(u))\n XT=(\"Frac Order $u\")\n elseif SwCu==\"Expo\"\n println(\"Order of the wanted Exponential ? : y=exp(x*{Order}) ? \\n Order=\")\n u=parse(Float64,input())\n Xout=exp.(u*Xin)\n XT=(\"exp($u x)\")\n elseif SwCu==\"Loga\"\n println(\"Terme of the wanted Logarithme ? : y=log|x+t|) ? \\n t=\")\n t=parse(Float64,input())\n Xout=log.(abs(Xin+t))\n XT=(\"log(x+t)\")\n end\n end\nreturn Xout,XT\nend\n\n###############################################################################\n\n# Statistics discrabing the Regression using ANOVA analysis thanks to distributions\n# functions\n\nfunction StatReg(Xin,Yin,XMat,XName,p)\n Yb=mean(Yin)\n SquareX=(transpose(XMat)*XMat)\n n=length(Yin)\n Bh=(SquareX^-1)*transpose(XMat)*Yin # Estimator for Inv(Mat) ?\n Yh=XMat*Bh\n SSE=sum((Yin-Yh).^2)\n SSR=sum((Yh-Yb).^2)\n SSTot=sum((Yin-Yb).^2)\n R2=SSR/SSTot # the biggest the best\n dfR=p-1\n MSR=SSR/dfR\n dfE=n-p\n MSE=SSE/dfE\n F=MSE/MSR\n # ---------------------- Calc p-Value Model --------------------------\n FD=FDist(dfR,dfE)\n pModel=cdf(FD,F) #Smallest the best\n # p- Values indie\n TD=TDist(dfE)\n pVect=ones(size(Bh))\n for i=1:length(Bh)\n Yh=XMat[:,i]*Bh[i]\n SSE=sum((Yin-Yh).^2)\n if XName[i]==\"Constant\"\n SX2=sum((Xin-mean(Xin)).^2)\n SEBh=sqrt(SSE*(1/n+mean(Xin)^2/SX2))\n else\n X=XMat[:,i]\n SX2=sum((X-mean(X)).^2)\n SEBh=sqrt(SSE/SX2)\n end\n t=Bh[i]*sqrt(dfE)/SEBh\n pVar=2*(1-cdf(TD,t))\n pVect[i]=pVar\n end\n\n return pVect,pModel,Bh\nend\n\n#############################################################################\n\n# Main function of Multiple Regression implementing ANOVA tests\n# and a user friendly approach to regression\n\nfunction MultiRegOpt(Xin::Vector, Yin::Vector, FunFamily=\"Poly\"::String, p=3::Int64,Stepwise=\"None\"::String, threshold=0.05::Float64)\n n=length(Xin)\n pVModels=[]\n XMatArray=[]\n BArray=[]\n YhA=[]\n XMatA=[]\n pVarA=[]\n XNameA=[]\n NbrModelTested=0\n if FunFamily==\"Custom\"\n NbrModel=p\n XMat=ones(Float64,n,NbrModel)\n XName=[]\n for Counti=0:NbrModel-1 # Nombre of function involved\n if Counti==0\n FX=ones(size(Xin))\n push!(XName,\"Constant\")\n else\n Xout=NextFun(Xin,FunFamily,Counti)\n FX=Xout[1]\n push!(XName,Xout[2])\n end\n XMat[:,Counti+1]=FX\n end\n pVect,pModel,Bh=StatReg(Xin,Yin,XMat,XName,p)\n # Stepwise, taking out not necessary variables\n OldXMat=XMat\n OldpVect=pVect\n OldBh=Bh\n OldXMat=XMat\n OldpModel=pModel\n while sum(pVect.>threshold)>0 && Stepwise==\"Student\"# There is pVect>0.05\n i=findmax(pVect)[2] #eliminated fun\n if (NbrModel-1)==0\n println(\"Impossible to find a acceptable regression with given number of function for threshold=$threshold, First Result given\")\n XMat=OldXMat\n pVect=OldpVect\n Bh=OldBh\n XMat=OldXMat\n break\n else\n NewXMat=ones(Float64,n,NbrModel-1)\n NewXName=[]\n for j=1:NbrModel\n if ji\n NewXMat[:,j-1]=XMat[:,j]\n push!(NewXName,XName[j])\n end\n end\n println(\"MultiReg New:NewXName=$NewXName\")\n pVect,pModel,Bh=StatReg(Xin,Yin,NewXMat,NewXName,p)\n XMat=NewXMat\n XName=NewXName\n NbrModel=NbrModel-1\n end\n end\n push!(pVarA,pVect)\n push!(pVModels,pModel)\n push!(BArray,Bh)\n push!(XMatA,XMat)\n push!(XNameA,XName)\n else\n for NbrModel=1:p\n XMat=ones(Float64,n,NbrModel)\n XName=[]\n for Counti=0:NbrModel-1 # Nombre of function involved\n if Counti==0\n FX=ones(size(Xin))\n push!(XName,\"Constant\")\n else\n Xout=NextFun(Xin,FunFamily,Counti)\n FX=Xout[1]\n push!(XName,Xout[2])\n end\n XMat[:,Counti+1]=FX\n end\n pVect,pModel,Bh=StatReg(Xin,Yin,XMat,XName,p)\n # Stepwise, taking out not necessary variables\n OldpVect=pVect\n OldBh=Bh\n OldXMat=XMat\n OldpModel=pModel\n while sum(pVect.>threshold)>0 && Stepwise==\"Student\"# there is pVect>0.05\n i=findmax(pVect)[2] #eliminated fun\n if (NbrModel-1)==0\n println(\"Impossible to find a acceptable regression with given number of function for threshold=$threshold, First Result given\")\n XMat=OldXMat\n pVect=OldpVect\n Bh=OldBh\n XMat=OldXMat\n break\n else\n NewXMat=ones(Float64,n,NbrModel-1)\n NewXName=[]\n for j=1:NbrModel\n if ji\n NewXMat[:,j-1]=XMat[:,j]\n push!(NewXName,XName[j])\n end\n end\n pVect,pModel,Bh=StatReg(Xin,Yin,NewXMat,NewXName,p)\n XMat=NewXMat\n XName=NewXName\n NbrModel=NbrModel-1\n end\n end\n if Stepwise==\"Fleussu\"\n Yb=mean(Yin)\n if sum(abs(Bh).0\n println(abs(Bh). LinearAlgebra.checksquare(block(bm, blk)),\n +, 1:nblocks(bm), init=0)\n return (n, n)\nend\nfunction Base.getindex(bm::AbstractBlockMatrix, i::Integer, j::Integer)\n (i < 0 || j < 0) && throw(BoundsError(i, j))\n for k in 1:nblocks(bm)\n blk = block(bm, k)\n n = size(blk, 1)\n if i <= n && j <= n\n return blk[i, j]\n elseif i <= n || j <= n\n return 0\n else\n i -= n\n j -= n\n end\n end\n i, j = (i, j) .+ size(bm)\n throw(BoundsError(i, j))\nend\nBase.getindex(A::AbstractBlockMatrix, I::Tuple) = getindex(A, I...)\n\nabstract type BlockSolution{T} <: AbstractBlockMatrix{T} end\nstruct PrimalSolution{T} <: BlockSolution{T}\n blocks::Vector{Matrix{T}}\nend\n# getptr(X::PrimalSolution, blk) = getResultYMat(X.problem, blk)\nstruct VarDualSolution{T} <: BlockSolution{T}\n blocks::Vector{Matrix{T}}\nend\n# getptr(X::VarDualSolution, blk) = getResultXMat(X.problem, blk)\nnblocks(X::BlockSolution) = length(X.blocks)\nfunction block(X::BlockSolution, blk::Integer)\n return X.blocks[blk]\nend\n# Needed by MPB_wrapper\nfunction Base.getindex(A::BlockSolution, i::Integer)\n block(A, i)\nend\n\nmutable struct Optimizer{T} <: MOI.AbstractOptimizer\n objconstant::T\n objsign::Int\n blockdims::Vector{Int}\n varmap::Vector{Tuple{Int, Int, Int}} # Variable Index vi -> blk, i, j\n b::Vector{T}\n solve_time::Float64\n silent::Bool\n options::Dict{Symbol, Any}\n y::Vector{T}\n X::PrimalSolution{T}\n Z::VarDualSolution{T}\n primalobj::T\n dualobj::T\n phasevalue::Symbol\n tempfile::String\n elemdata::Vector{Any}\n\tpresolve::Bool\n function Optimizer{T}(; presolve::Bool = true) where T\n\t\toptimizer = new(\n zero(T), 1, Int[], Tuple{Int, Int, Int}[], T[],\n NaN, false, Dict{Symbol, Any}(), T[], PrimalSolution{T}(Matrix{T}[]), VarDualSolution{T}(Matrix{T}[]), zero(T), zero(T), :noINFO, mktempdir(), [], true)\n\t\tif !presolve\n\t\t\toptimizer.presolve = false\n\t\tend\n\t\treturn optimizer\n end\nend\n\nvarmap(optimizer::Optimizer, vi::MOI.VariableIndex) = optimizer.varmap[vi.value]\n\nfunction MOI.supports(optimizer::Optimizer, param::MOI.RawParameter)\n\treturn param.name in keys(SET_PARAM)\nend\nfunction MOI.set(optimizer::Optimizer, param::MOI.RawParameter, value)\n\tif !MOI.supports(optimizer, param)\n\t\tthrow(MOI.UnsupportedAttribute(param))\n\tend\n\toptimizer.options[param.name] = value\nend\nfunction MOI.get(optimizer::Optimizer, param::MOI.RawParameter)\n\t# TODO: This gives a poor error message if the name of the parameter is invalid.\n\treturn optimizer.options[param.name]\nend\n\nMOI.supports(::Optimizer, ::MOI.Silent) = true\nfunction MOI.set(optimizer::Optimizer, ::MOI.Silent, value::Bool)\n\toptimizer.silent = value\nend\nMOI.get(optimizer::Optimizer, ::MOI.Silent) = optimizer.silent\n\nMOI.get(::Optimizer, ::MOI.SolverName) = \"SDPA-GMP\"\n\n# See https://www.researchgate.net/publication/247456489_SDPA_SemiDefinite_Programming_Algorithm_User's_Manual_-_Version_600\n# \"SDPA (SemiDefinite Programming Algorithm) User's Manual — Version 6.00\" Section 6.2\nconst RAW_STATUS = Dict(\n :noINFO => \"The iteration has exceeded the maxIteration and stopped with no informationon the primal feasibility and the dual feasibility.\",\n :pdOPT => \"The normal termination yielding both primal and dual approximate optimal solutions.\",\n :pFEAS => \"The primal problem got feasible but the iteration has exceeded the maxIteration and stopped.\",\n :dFEAS => \"The dual problem got feasible but the iteration has exceeded the maxIteration and stopped.\",\n :pdFEAS => \"Both primal problem and the dual problem got feasible, but the iterationhas exceeded the maxIteration and stopped.\",\n :pdINF => \"At least one of the primal problem and the dual problem is expected to be infeasible.\",\n :pFEAS_dINF => \"The primal problem has become feasible but the dual problem is expected to be infeasible.\",\n :pINF_dFEAS => \"The dual problem has become feasible but the primal problem is expected to be infeasible.\",\n :pUNBD => \"The primal problem is expected to be unbounded.\",\n :dUNBD => \"The dual problem is expected to be unbounded.\")\n\nfunction MOI.get(optimizer::Optimizer, ::MOI.RawStatusString)\n\treturn RAW_STATUS[optimizer.phasevalue]\nend\nfunction MOI.get(optimizer::Optimizer, ::MOI.SolveTime)\n\treturn optimizer.solve_time\nend\n\nfunction MOI.is_empty(optimizer::Optimizer)\n return iszero(optimizer.objconstant) &&\n optimizer.objsign == 1 &&\n isempty(optimizer.blockdims) &&\n isempty(optimizer.varmap) &&\n isempty(optimizer.b) &&\n optimizer.elemdata == []\nend\nfunction MOI.empty!(optimizer::Optimizer{T}) where T\n optimizer.objconstant = zero(Cdouble)\n optimizer.objsign = 1\n empty!(optimizer.blockdims)\n empty!(optimizer.varmap)\n empty!(optimizer.b)\n optimizer.X = PrimalSolution{T}(Matrix{T}[])\n optimizer.Z = VarDualSolution{T}(Matrix{T}[])\n optimizer.y = T[]\n optimizer.phasevalue = :noINFO\n optimizer.tempfile = mktempdir()\n optimizer.elemdata = []\n optimizer.primalobj = zero(T)\n optimizer.dualobj = zero(T)\nend\n\nfunction MOI.supports(\n optimizer::Optimizer,\n ::Union{MOI.ObjectiveSense,\n MOI.ObjectiveFunction{<:Union{MOI.SingleVariable,\n MOI.ScalarAffineFunction{T}}}}) where T\n return true\nend\n\nfunction MOI.supports_constraint(\n ::Optimizer, ::Type{MOI.VectorOfVariables}, ::Type{MOI.Reals})\n return false\nend\nconst SupportedSets = Union{MOI.Nonnegatives, MOI.PositiveSemidefiniteConeTriangle}\nfunction MOI.supports_constraint(\n ::Optimizer, ::Type{MOI.VectorOfVariables},\n ::Type{<:SupportedSets})\n return true\nend\nfunction MOI.supports_constraint(\n ::Optimizer, ::Type{MOI.ScalarAffineFunction{T}},\n ::Type{MOI.EqualTo{T}}) where T\n return true\nend\n\nfunction MOI.copy_to(dest::Optimizer, src::MOI.ModelLike; kws...)\n return MOIU.automatic_copy_to(dest, src; kws...)\nend\nMOIU.supports_allocate_load(::Optimizer, copy_names::Bool) = !copy_names\n\nfunction MOIU.allocate(optimizer::Optimizer, ::MOI.ObjectiveSense, sense::MOI.OptimizationSense)\n # To be sure that it is done before load(optimizer, ::ObjectiveFunction, ...), we do it in allocate\n optimizer.objsign = sense == MOI.MIN_SENSE ? -1 : 1\nend\nfunction MOIU.allocate(::Optimizer, ::MOI.ObjectiveFunction, ::Union{MOI.SingleVariable, MOI.ScalarAffineFunction}) end\n\nfunction MOIU.load(::Optimizer, ::MOI.ObjectiveSense, ::MOI.OptimizationSense) end\n# Loads objective coefficient α * vi\nfunction load_objective_term!(optimizer::Optimizer{T}, α, vi::MOI.VariableIndex) where {T}\n blk, i, j = varmap(optimizer, vi)\n coef = optimizer.objsign * α\n if i != j\n coef /= 2\n end\n # in SDP format, it is max and in MPB Conic format it is min\n inputElement(optimizer, 0, blk, i, j, convert(T, coef))\nend\nfunction MOIU.load(optimizer::Optimizer, ::MOI.ObjectiveFunction, f::MOI.ScalarAffineFunction)\n obj = MOIU.canonical(f)\n optimizer.objconstant = f.constant\n for t in obj.terms\n if !iszero(t.coefficient)\n load_objective_term!(optimizer, t.coefficient, t.variable_index)\n end\n end\nend\nfunction MOIU.load(optimizer::Optimizer{T}, ::MOI.ObjectiveFunction, f::MOI.SingleVariable) where T\n load_objective_term!(optimizer, one(T), f.variable)\nend\n\nfunction new_block(optimizer::Optimizer, set::MOI.Nonnegatives)\n push!(optimizer.blockdims, -MOI.dimension(set))\n blk = length(optimizer.blockdims)\n for i in 1:MOI.dimension(set)\n push!(optimizer.varmap, (blk, i, i))\n end\nend\n\nfunction new_block(optimizer::Optimizer, set::MOI.PositiveSemidefiniteConeTriangle)\n push!(optimizer.blockdims, set.side_dimension)\n blk = length(optimizer.blockdims)\n for i in 1:set.side_dimension\n for j in 1:i\n push!(optimizer.varmap, (blk, i, j))\n end\n end\nend\n\nfunction MOIU.allocate_constrained_variables(optimizer::Optimizer,\n set::SupportedSets)\n offset = length(optimizer.varmap)\n new_block(optimizer, set)\n ci = MOI.ConstraintIndex{MOI.VectorOfVariables, typeof(set)}(offset + 1)\n return [MOI.VariableIndex(i) for i in offset .+ (1:MOI.dimension(set))], ci\nend\n\nfunction MOIU.load_constrained_variables(\n optimizer::Optimizer, vis::Vector{MOI.VariableIndex},\n ci::MOI.ConstraintIndex{MOI.VectorOfVariables},\n set::SupportedSets)\nend\n\nfunction MOIU.allocate_variables(model::Optimizer, nvars)\nend\n\nfunction MOIU.load_variables(optimizer::Optimizer{T}, nvars) where T\n @assert nvars == length(optimizer.varmap)\n dummy = isempty(optimizer.b)\n if dummy\n optimizer.b = [one(T)]\n optimizer.blockdims = [optimizer.blockdims; -1]\n end\n if dummy\n inputElement(optimizer, 1, length(optimizer.blockdims), 1, 1, one(T))\n end\nend\n\nfunction MOIU.allocate_constraint(optimizer::Optimizer{T},\n func::MOI.ScalarAffineFunction,\n set::MOI.EqualTo) where T\n push!(optimizer.b, MOI.constant(set))\n return AFFEQ{T}(length(optimizer.b))\nend\n\nfunction MOIU.load_constraint(m::Optimizer{T}, ci::AFFEQ,\n f::MOI.ScalarAffineFunction, s::MOI.EqualTo) where T\n if !iszero(MOI.constant(f))\n throw(MOI.ScalarFunctionConstantNotZero{\n T, MOI.ScalarAffineFunction{T}, MOI.EqualTo{T}}(\n MOI.constant(f)))\n end\n f = MOIU.canonical(f) # sum terms with same variables and same outputindex\n for t in f.terms\n if !iszero(t.coefficient)\n blk, i, j = varmap(m, t.variable_index)\n coef = t.coefficient\n if i != j\n coef /= 2\n end\n inputElement(m, ci.value, blk, i, j, convert(T, coef))\n end\n end\nend\n\nfunction MOI.optimize!(m::Optimizer)\n\tstart_time = time()\n # SDPA.initializeUpperTriangle(m.problem, false)\n redundant_F = initializeSolve(m)\n # SDPA.solve(m)\n inputname = \"input.dat-s\"\n outputname = \"output.dat\"\n full_input_path = joinpath(m.tempfile, inputname)\n full_output_path = joinpath(m.tempfile, outputname)\n sdpa_gmp_binary_solve!(m, full_input_path, full_output_path, redundant_entries = redundant_F)\n m.solve_time = time() - start_time\nend\n\nfunction MOI.get(m::Optimizer, ::MOI.TerminationStatus)\n status = m.phasevalue\n if status == :noINFO\n return MOI.OPTIMIZE_NOT_CALLED\n elseif status == :pFEAS\n return MOI.SLOW_PROGRESS\n elseif status == :dFEAS\n return MOI.SLOW_PROGRESS\n elseif status == :pdFEAS\n return MOI.OPTIMAL\n elseif status == :pdINF\n return MOI.INFEASIBLE_OR_UNBOUNDED\n elseif status == :pFEAS_dINF\n return MOI.DUAL_INFEASIBLE\n elseif status == :pINF_dFEAS\n return MOI.INFEASIBLE\n elseif status == :pdOPT\n return MOI.OPTIMAL\n elseif status == :pUNBD\n return MOI.DUAL_INFEASIBLE\n elseif status == :dUNBD\n return MOI.INFEASIBLE\n end\nend\n\nfunction MOI.get(m::Optimizer, ::MOI.PrimalStatus)\n status = m.phasevalue\n if status == :noINFO\n return MOI.UNKNOWN_RESULT_STATUS\n elseif status == :pFEAS\n return MOI.FEASIBLE_POINT\n elseif status == :dFEAS\n return MOI.UNKNOWN_RESULT_STATUS\n elseif status == :pdFEAS\n return MOI.FEASIBLE_POINT\n elseif status == :pdINF\n return MOI.UNKNOWN_RESULT_STATUS\n elseif status == :pFEAS_dINF\n return MOI.INFEASIBILITY_CERTIFICATE\n elseif status == :pINF_dFEAS\n return MOI.INFEASIBLE_POINT\n elseif status == :pdOPT\n return MOI.FEASIBLE_POINT\n elseif status == :pUNBD\n return MOI.INFEASIBILITY_CERTIFICATE\n elseif status == :dUNBD\n return MOI.INFEASIBLE_POINT\n end\nend\n\nfunction MOI.get(m::Optimizer, ::MOI.DualStatus)\n status = m.phasevalue\n if status == :noINFO\n return MOI.UNKNOWN_RESULT_STATUS\n elseif status == :pFEAS\n return MOI.UNKNOWN_RESULT_STATUS\n elseif status == :dFEAS\n return MOI.FEASIBLE_POINT\n elseif status == :pdFEAS\n return MOI.FEASIBLE_POINT\n elseif status == :pdINF\n return MOI.UNKNOWN_RESULT_STATUS\n elseif status == :pFEAS_dINF\n return MOI.INFEASIBLE_POINT\n elseif status == :pINF_dFEAS\n return MOI.INFEASIBILITY_CERTIFICATE\n elseif status == :pdOPT\n return MOI.FEASIBLE_POINT\n elseif status == :pUNBD\n return MOI.INFEASIBLE_POINT\n elseif status == :dUNBD\n return MOI.INFEASIBILITY_CERTIFICATE\n end\nend\n\nMOI.get(m::Optimizer, ::MOI.ResultCount) = 1\nfunction MOI.get(m::Optimizer, ::MOI.ObjectiveValue)\n return m.objsign * m.primalobj + m.objconstant\nend\nfunction MOI.get(m::Optimizer, ::MOI.DualObjectiveValue)\n return m.objsign * m.dualobj + m.objconstant\nend\nstruct PrimalSolutionMatrix <: MOI.AbstractModelAttribute end\nMOI.is_set_by_optimize(::PrimalSolutionMatrix) = true\nMOI.get(optimizer::Optimizer, ::PrimalSolutionMatrix) = optimizer.X\n\nstruct DualSolutionVector <: MOI.AbstractModelAttribute end\nMOI.is_set_by_optimize(::DualSolutionVector) = true\nfunction MOI.get(optimizer::Optimizer, ::DualSolutionVector)\n return optimizer.y\nend\n\nstruct DualSlackMatrix <: MOI.AbstractModelAttribute end\nMOI.is_set_by_optimize(::DualSlackMatrix) = true\nMOI.get(optimizer::Optimizer, ::DualSlackMatrix) = optimizer.Z\n\nfunction block(optimizer::Optimizer, ci::MOI.ConstraintIndex{MOI.VectorOfVariables})\n return optimizer.varmap[ci.value][1]\nend\nfunction dimension(optimizer::Optimizer, ci::MOI.ConstraintIndex{MOI.VectorOfVariables})\n blockdim = optimizer.blockdims[block(optimizer, ci)]\n if blockdim < 0\n return -blockdim\n else\n return MOI.dimension(MOI.PositiveSemidefiniteConeTriangle(blockdim))\n end\nend\nfunction vectorize_block(M, blk::Integer, s::Type{MOI.Nonnegatives})\n return diag(block(M, blk))\nend\nfunction vectorize_block(M::AbstractMatrix{T}, blk::Integer, s::Type{MOI.PositiveSemidefiniteConeTriangle}) where T\n B = block(M, blk)\n d = LinearAlgebra.checksquare(B)\n n = MOI.dimension(MOI.PositiveSemidefiniteConeTriangle(d))\n v = Vector{T}(undef, n)\n k = 0\n for j in 1:d\n for i in 1:j\n k += 1\n v[k] = B[i, j]\n end\n end\n @assert k == n\n return v\nend\n\nfunction MOI.get(optimizer::Optimizer, ::MOI.VariablePrimal, vi::MOI.VariableIndex)\n blk, i, j = varmap(optimizer, vi)\n return block(MOI.get(optimizer, PrimalSolutionMatrix()), blk)[i, j]\nend\n\nfunction MOI.get(optimizer::Optimizer, ::MOI.ConstraintPrimal,\n ci::MOI.ConstraintIndex{MOI.VectorOfVariables, S}) where S<:SupportedSets\n return vectorize_block(MOI.get(optimizer, PrimalSolutionMatrix()), block(optimizer, ci), S)\nend\nfunction MOI.get(m::Optimizer, ::MOI.ConstraintPrimal, ci::AFFEQ)\n return m.b[ci.value]\nend\n\nfunction MOI.get(optimizer::Optimizer, ::MOI.ConstraintDual,\n ci::MOI.ConstraintIndex{MOI.VectorOfVariables, S}) where S<:SupportedSets\n return vectorize_block(MOI.get(optimizer, DualSlackMatrix()), block(optimizer, ci), S)\nend\nfunction MOI.get(optimizer::Optimizer, ::MOI.ConstraintDual, ci::AFFEQ)\n return -MOI.get(optimizer, DualSolutionVector())[ci.value]\nend\n", "meta": {"hexsha": "b886103e0707d69cb4726fde4fa9d05b44f2f96c", "size": 15696, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MOI_wrapper.jl", "max_stars_repo_name": "JiazhengZhu/SDPA_GMP.jl", "max_stars_repo_head_hexsha": "adacd0ccde986f9a4929601a1a9c07d861599bf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MOI_wrapper.jl", "max_issues_repo_name": "JiazhengZhu/SDPA_GMP.jl", "max_issues_repo_head_hexsha": "adacd0ccde986f9a4929601a1a9c07d861599bf9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MOI_wrapper.jl", "max_forks_repo_name": "JiazhengZhu/SDPA_GMP.jl", "max_forks_repo_head_hexsha": "adacd0ccde986f9a4929601a1a9c07d861599bf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3513513514, "max_line_length": 164, "alphanum_fraction": 0.691832314, "num_tokens": 4201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24230356684122373}} {"text": "\nmodule DynamicsUtils\n\nusing NQCDynamics:\n AbstractSimulation,\n Simulation,\n RingPolymerSimulation,\n Calculators,\n masses\n\ndivide_by_mass!(dv, masses) = dv ./= masses'\nvelocity!(dr, v, r, sim, t) = dr .= v\n\n\"\"\"\n apply_interbead_coupling!(du::DynamicalVariables, u::DynamicalVariables,\n sim::RingPolymerSimulation)\n \nApplies the force that arises from the harmonic springs between adjacent beads.\n\nOnly applies the force for atoms labelled as quantum within the `RingPolymerParameters`.\n\"\"\"\nfunction apply_interbead_coupling!(dr::AbstractArray{T,3}, r::AbstractArray{T,3}, sim::RingPolymerSimulation) where {T}\n for i in axes(dr, 3)\n iplus = mod1(i+1, sim.beads.n_beads)\n iminus = mod1(i-1, sim.beads.n_beads)\n for j in sim.beads.quantum_atoms\n for k in axes(dr, 1)\n dr[k,j,i] -= sim.beads.ω_n² * (2r[k,j,i] - r[k,j,iplus] - r[k,j,iminus])\n end\n end\n end\n return nothing\nend\n\nfunction classical_hamiltonian end\n\nfunction classical_kinetic_energy(sim::Simulation, v::AbstractMatrix)\n kinetic = zero(eltype(v))\n for i in axes(v, 2)\n for j in axes(v, 1)\n kinetic += masses(sim, i) * v[j,i]^2\n end\n end\n return kinetic / 2\nend\n\nfunction classical_kinetic_energy(sim::RingPolymerSimulation, v::AbstractArray{T,3}) where {T}\n kinetic = zero(eltype(v))\n for k in axes(v, 3)\n for i in axes(v, 2)\n for j in axes(v, 1)\n kinetic += masses(sim, i) * v[j,i,k]^2\n end\n end\n end\n return kinetic / 2\nend\n\nfunction classical_potential_energy(sim::Simulation, r::AbstractMatrix)\n Calculators.evaluate_potential!(sim.calculator, r)\n sim.calculator.potential\nend\n\nfunction classical_potential_energy(sim::RingPolymerSimulation, r::AbstractArray{T,3}) where {T}\n Calculators.evaluate_potential!(sim.calculator, r)\n sum(sim.calculator.potential) + RingPolymers.get_spring_energy(sim.beads, masses(sim), r)\nend\n\ninclude(\"dynamics_variables.jl\")\ninclude(\"callbacks.jl\")\nexport CellBoundaryCallback\nexport TerminatingCallback\n\ninclude(\"density_matrix_dynamics.jl\")\ninclude(\"plot.jl\")\n\nend # module\n", "meta": {"hexsha": "f48b46566155ab959589eccac622f882c00fa537", "size": 2208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DynamicsUtils/DynamicsUtils.jl", "max_stars_repo_name": "NQCD/NonadiabaticMolecularDynamics.jl", "max_stars_repo_head_hexsha": "491937e0878f15881201e7d637235a5e7f6feb6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-23T04:13:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T04:13:13.000Z", "max_issues_repo_path": "src/DynamicsUtils/DynamicsUtils.jl", "max_issues_repo_name": "NQCD/NonadiabaticMolecularDynamics.jl", "max_issues_repo_head_hexsha": "491937e0878f15881201e7d637235a5e7f6feb6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2021-08-18T11:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T14:32:58.000Z", "max_forks_repo_path": "src/DynamicsUtils/DynamicsUtils.jl", "max_forks_repo_name": "NQCD/NonadiabaticMolecularDynamics.jl", "max_forks_repo_head_hexsha": "491937e0878f15881201e7d637235a5e7f6feb6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3076923077, "max_line_length": 119, "alphanum_fraction": 0.6698369565, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24221612779523757}} {"text": "module CTImages\n\nexport rescale!, rescale, rotate\nexport polar2cart\nexport AbstractCTImage, CTImage, CTSinogram, CTTomogram\nexport CTImageOrTomog, CTImageMat, CTSinogMat, CTTomogMat\nexport ctimage, ctsinogram, cttomogram\n\nusing IntervalSets, SimpleTraits\nimport ..Monads: mjoin\nusing ..Utils: linspace, half, _compute_radius, _compute_angle, _wrap_angle\nimport ..Utils: _atype\nusing ..Applicative, ..Monads, ..Interpolation\nusing ..Geometry:\n AbstractParallelBeamGeometry, AbstractFanBeamGeometry, ParallelBeamGeometry\nimport Base: size, convert, similar, eltype, getindex, setindex!, IndexStyle\nusing Base: @propagate_inbounds\n\n\nfunction ctimage end\nfunction ctsinogram end\nfunction cttomogram end\n\n\nabstract type AbstractCTImage{T<:Number} <: AbstractMatrix{T} end\n\n@traitimpl Monad{AbstractCTImage}\nmjoin(img::AbstractCTImage) = img.data\n\n# struct CTImageStyle <: Broadcast.AbstractArrayStyle{2} end\n# Base.BroadcastStyle(::Type{<:AbstractCTImage}) = CTImageStyle()\n# CTImageStyle(::Val{2}) = CTImageStyle()\n# CTImageStyle(::Val{N}) where N = Broadcast.DefaultArrayStyle{N}()\n\n_atype(img::M) where {M <: AbstractCTImage} = _atype(M)\neltype(::Type{M}) where {M<:AbstractCTImage{T}} where T = T\nsize(img::AbstractCTImage) = mbind(size, img)\nsize(img::AbstractCTImage, dim::Int) = size(mjoin(img), dim)\n@propagate_inbounds function getindex(img::AbstractCTImage, i::Int)\n @boundscheck checkbounds(img, i)\n @inbounds getindex(mjoin(img), i)\nend\n@propagate_inbounds function getindex(\n img::AbstractCTImage, I::Vararg{Int,2}\n)\n @boundscheck checkbounds(img, I...)\n @inbounds getindex(mjoin(img), I...)\nend\n@propagate_inbounds function setindex!(img::AbstractCTImage, v, i::Int)\n @boundscheck checkbounds(img, i)\n @inbounds setindex!(mjoin(img), v, i)\nend\n@propagate_inbounds function setindex!(\n img::AbstractCTImage, v, I::Vararg{Int,2}\n)\n @boundscheck checkbounds(img, I...)\n @inbounds setindex!(mjoin(img), v, I...)\nend\n\n\nconst ctnames = (image = :CTImage, sinog = :CTSinogram, tomog = :CTTomogram)\nconst ctfn = (image = :ctimage, sinog = :ctsinogram, tomog = :cttomogram)\n\n\nfor nm in ctnames\n @eval begin\n struct $nm{T<:Number,M<:AbstractMatrix{T}} <: AbstractCTImage{T}\n data::M\n end\n @inline _atype(::Type{$nm{T,M}}) where {T,M} = M\n IndexStyle(::Type{T}) where T<:$nm = IndexStyle(_atype(T))\n @inline function $nm{T,M}(\n ::UndefInitializer,\n dims::Vararg{Union{Integer,AbstractUnitRange},2}\n ) where {T,M}\n $nm(M(undef, dims...))\n end\n @inline $nm{T,M}(img::$nm) where {T,M} = $nm{T,M}(mjoin(img))\n @inline $nm{T}(img::M) where {T,M<:AbstractMatrix{T}} = $nm{T,M}(img)\n @inline $nm(img::$nm) = img\n @inline convert(::Type{M}, img::AbstractMatrix) where {M<:$nm} =\n mreturn(M, img)\n @inline convert(::Type{M}, img::$nm) where {M<:$nm} =\n mreturn($nm, convert(_atype(M), mjoin(img)))\n @inline function similar(img::M) where {M<:$nm}\n mreturn(M, similar(mjoin(img)))\n end\n @inline function similar(\n img::M,\n ::Type{S},\n dims::Tuple{Vararg{Int,2}}\n ) where {S,M<:$nm}\n mreturn(M, similar(mjoin(img), S, dims))\n end\n end\nend\n\nCTImage(::Union{CTSinogram,CTTomogram}) =\n @error \"Cannot construct a CT image from a sinogram or a tomogram\"\nCTSinogram(::Union{CTImage,CTTomogram}) =\n @error \"Cannot construct a CT sinogram from an image or a tomogram\"\nCTTomogram(::Union{CTImage,CTSinogram}) =\n @error \"Cannot construct a CT tomogram from an image or a sinogram\"\n\nconst CTImageOrTomog{T,M} = Union{CTImage{T,M},CTTomogram{T,M}}\nconst CTImageMat{T} = CTImage{T,Matrix{T}}\nconst CTSinogMat{T} = CTSinogram{T,Matrix{T}}\nconst CTTomogMat{T} = CTTomogram{T,Matrix{T}}\n\n\"\"\"\n rotate(mat::AbstractMatrix, α::Real; )\n\nRotate matrix `mat` about the center of angle `α` given in degrees.\nIf `rows` and `cols` are not given, the rotated matrix has the same\ndimensions of the original matrix.\n\n# Arguments\n- `mat`: matrix to rotate.\n- `α`: angle in degrees.\n- `rows=nothing`: number of rows of the rotated matrix.\n- `cols=nothing`: number of columns of the rotated matrix.\n- `interpolation`: interpolation strategy. By default is\n `BilinearInterpolation`.\n\"\"\"\nfunction rotate(\n mat::AbstractMatrix{T},\n α::Real;\n rows::Optional{Integer} = nothing,\n cols::Optional{Integer} = nothing,\n background::Optional{Real} = nothing,\n interpolation::Optional{Interp} = nothing,\n) where {T <: Number,Interp <: AbstractInterp2DOrNone}\n orows, ocols = size(mat)\n rows = maybe(orows, rows)\n cols = maybe(ocols, cols)\n sϕ, cϕ = sincos(deg2rad(α))\n interpolation = maybe(interpolate, interpolation)\n interp = interpolation(mat)\n x₀::T = (cols + 1) / 2\n y₀::T = (rows + 1) / 2\n x′₀::T = (ocols + 1) / 2\n y′₀::T = (orows + 1) / 2\n z::T = maybe(zero(T), background)\n rmat = similar(mat, rows, cols)\n fill!(rmat, z)\n for ix ∈ 1:rows, iy ∈ 1:cols\n x = T(ix) - x₀\n y = T(iy) - y₀\n x′ = x * cϕ + y * sϕ + x′₀\n y′ = y * cϕ - x * sϕ + y′₀\n if x′ ∈ 1..ocols && y′ ∈ 1..orows\n rmat[iy, ix] = interp(y′, x′)\n end\n end\n rmat\nend\n\n\n\"\"\"\n rescale!(x::AbstractArray;\n interval=nothing, calibration=nothing, window=nothing)\n\nRescale array x to the interval specified by `interval`.\n\nIf `calibration` is not `nothing`, then rescaling is done with\nreference to the values given by `calibration`. In other words,\nminimum and maximum are assumed to be the values specified by\n`calibration`.\n\nSee also: [`rescale`](@ref)\n\"\"\"\nfunction rescale!(\n img::AbstractArray{T};\n interval::ClosedInterval = zero(T)..one(T),\n calibration::Optional{ClosedInterval{U}} = nothing,\n window::Optional{ClosedInterval{W}} = nothing,\n) where {T <: Number,U <: Number,W <: Number}\n if isnothing(calibration)\n calibration = ClosedInterval(extrema(img)...)\n end\n a, b = T.(endpoints(interval))\n m, M = T.(endpoints(calibration))\n if m == M\n @warn \"Cannot calibrate image as calibration values ($calibration) are equal, image unchanged\"\n return img\n end\n f = (b - a) / (M - m)\n if m != zero(T)\n img .-= m\n end\n img .*= f\n if a != zero(T)\n img .+= a\n end\n isnothing(window) && return img\n a, b = T.(endpoints(window))\n map!(img, img) do x\n x < a && return a\n x > b && return b\n return x\n end\n img\nend\n\n\n\n\"\"\"\n rescale(x::AbstractArray, slope::Number, intercept::Number; window)\n\nLinear rescaling of `x` as `x * slope + intercept`.\n\nSee also: [`rescale!`](@ref)\n\"\"\"\nfunction rescale(\n image::AbstractArray{T},\n slope::Number,\n intercept::Number;\n window::Optional{ClosedInterval{U}} = nothing,\n) where {T <: Number,U <: Number}\n res = @. image * slope + intercept\n isnothing(window) && return res\n a, b = T.(endpoints(window))\n map!(res, res) do x\n x < a && return a\n x > b && return b\n return x\n end\nend\n\n\n\n\"\"\"\n rescale!(x::AbstractArray, slope::Number, intercept::Number)\n\nIn place linear rescaling of `x`.\n\nSee also: [`rescale`](@ref)\n\"\"\"\nfunction rescale!(\n img::AbstractArray{T},\n slope::Number,\n intercept::Number;\n window::Optional{ClosedInterval{U}} = nothing,\n) where {T <: Number,U <: Number}\n @. img = slope * img + intercept\n isnothing(window) && return img\n a, b = T.(endpoints(window))\n map!(img, img) do x\n x < a && return a\n x > b && return b\n return x\n end\n img\nend\n\n\n\n\"\"\"\n rescale(x::AbstractArray;\n interval=nothing, calibration=nothing, window=nothing)\n\nRescale array x to the interval specified by `interval`.\n\nIf `calibration` is not `nothing`, then rescaling is done with\nreference to the values given by `calibration`. In other words,\nminimum and maximum are assumed to be the values specified by\n`calibration`.\n\nSee also: [`rescale!`](@ref)\n\"\"\"\nfunction rescale(\n x::AbstractArray;\n interval = 0..1,\n calibration = nothing,\n window = nothing,\n)\n rescale!(deepcopy(x); interval, calibration, window)\nend\n\n\nfunction polar2cart(\n mp::M,\n xs::AbstractVector,\n ys::AbstractVector;\n ν::Real = 1,\n scale::Optional{Real} = nothing,\n diag::Bool = false,\n background::Optional{Real} = nothing,\n transposed::Bool = false,\n interpolation::Optional{Interp} = nothing,\n)::M where {\n M <: AbstractMatrix{T},\n Interp <: AbstractInterp2DOrNone,\n} where {T <: Real}\n if transposed\n nr, nθ = size(mp)\n mp′ = similar(mp, nθ, nr)\n permutedims!(mp′, mp, (2,1))\n return polar2cart(mp′, xs, ys; background, interpolation)\n end\n ν = maybe(ν, scale)\n @assert ν > 0\n nθ, nr = size(mp)\n x₀, y₀ = half(xs), half(ys)\n κ::T = min(x₀, y₀)\n if diag\n ν *= hypot(x₀, y₀) / κ\n end\n δri::T = (nr-1) / (κ * ν)\n δθi::T = nθ / 2π\n xs′ = xs * δri\n ys′ = ys * δri\n nt1 = nθ + 1\n nthalf = nθ + 1//2\n interpolation = maybe(interpolate, interpolation)\n interp = interpolation(mp)\n rows, cols = length(ys), length(xs)\n z::T = maybe(zero(T), background)\n mc = similar(mp, rows, cols)\n fill!(mc, z)\n Threads.@threads for ix ∈ axes(mc, 2)\n @inbounds @fastmath @simd for iy ∈ axes(mc, 1)\n x::T = xs′[ix]\n y::T = ys′[iy]\n r::T = _compute_radius(x, y)\n θ::T = _compute_angle(x, y, δθi)\n if 1 <= r <= nr && 1 <= θ <= nt1\n if θ >= nthalf\n θ = one(T)\n elseif θ > nθ\n θ = nθ\n end\n mc[iy,ix] = interp(θ, r)\n end\n end\n end\n mc\nend\n\n\n@inline function polar2cart(\n mp::AbstractMatrix{T};\n rows::Optional{Integer} = nothing,\n cols::Optional{Integer} = nothing,\n transposed::Bool = false,\n kwargs...\n) where {T <: Real,Interp <: AbstractInterp2DOrNone}\n mp = transposed ? permutedims(mp) : mp\n rows = isnothing(rows) ? maybe(2 * size(mp, 2), cols) : rows\n cols = maybe(rows, cols)\n y₀, x₀ = sincos(atan(rows, cols))\n xs = linspace(T, -x₀..x₀, cols)\n ys = linspace(T, -y₀..y₀, rows)\n polar2cart(mp, xs, ys; kwargs...)\nend\n\n\nfunction polar2cart(\n image::AbstractMatrix,\n geometry::AbstractParallelBeamGeometry;\n kwargs...\n)\n polar2cart(image; geometry.rows, geometry.cols, kwargs...)\nend\n\nfunction polar2cart(\n image::AbstractMatrix,\n geometry::AbstractFanBeamGeometry;\n kwargs...\n)\n polar2cart(image, ParallelBeamGeometry(geometry); kwargs...)\nend\n\npolar2cart(; kwargs...) = x -> polar2cart(x; kwargs...)\npolar2cart(g::AbstractParallelBeamGeometry; kwargs...) =\n x -> polar2cart(x, g; kwargs...)\n\nend # module\n", "meta": {"hexsha": "b265a29f6310d07d8dc72559579b0c0514670e7a", "size": 10860, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CTImages.jl", "max_stars_repo_name": "HomodyneCT/MartaCT.jl", "max_stars_repo_head_hexsha": "090fce88c91b79a4a8326589faee6cd2f869456e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-22T17:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T17:00:51.000Z", "max_issues_repo_path": "src/CTImages.jl", "max_issues_repo_name": "HomodyneCT/MartaCT.jl", "max_issues_repo_head_hexsha": "090fce88c91b79a4a8326589faee6cd2f869456e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-04-06T15:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-21T15:41:23.000Z", "max_forks_repo_path": "src/CTImages.jl", "max_forks_repo_name": "HomodyneCT/MartaCT.jl", "max_forks_repo_head_hexsha": "090fce88c91b79a4a8326589faee6cd2f869456e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.654353562, "max_line_length": 102, "alphanum_fraction": 0.6203499079, "num_tokens": 3234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24221509613290507}} {"text": "using KernelAbstractions: NoneEvent\nusing OffsetArrays: OffsetArray\nusing CUDA\n\nusing Oceananigans.Operators: Δzᵃᵃᶜ\nusing Oceananigans.BoundaryConditions: left_gradient, right_gradient, linearly_extrapolate, FBC, VBC, GBC\nusing Oceananigans.BoundaryConditions: fill_bottom_halo!, fill_top_halo!, apply_z_bottom_bc!, apply_z_top_bc!\nusing Oceananigans.Grids: Flat, Bounded\nusing Oceananigans.Coriolis: AbstractRotation\nusing Oceananigans.Architectures: device_event\nusing Oceananigans.TurbulenceClosures: AbstractTurbulenceClosure\nusing Oceananigans.TurbulenceClosures.CATKEVerticalDiffusivities: _top_tke_flux, CATKEVDArray\n\nimport Oceananigans.Utils: launch!\nimport Oceananigans.Grids: validate_size, validate_halo\nimport Oceananigans.BoundaryConditions: fill_halo_regions!\nimport Oceananigans.TurbulenceClosures: time_discretization, calculate_diffusivities!\nimport Oceananigans.TurbulenceClosures: ∂ⱼ_τ₁ⱼ, ∂ⱼ_τ₂ⱼ, ∂ⱼ_τ₃ⱼ, ∇_dot_qᶜ\nimport Oceananigans.TurbulenceClosures.CATKEVerticalDiffusivities: top_tke_flux\nimport Oceananigans.Coriolis: x_f_cross_U, y_f_cross_U, z_f_cross_U\n\n#####\n##### Implements a \"single column model mode\" for HydrostaticFreeSurfaceModel\n#####\n\nconst SingleColumnGrid = AbstractGrid{<:AbstractFloat, <:Flat, <:Flat, <:Bounded}\n\n#####\n##### Model constructor utils\n#####\n\nPressureField(::SingleColumnGrid) = (; pHY′ = nothing)\nFreeSurface(free_surface::ExplicitFreeSurface{Nothing}, velocities, arch, ::SingleColumnGrid) = nothing\nFreeSurface(free_surface::ImplicitFreeSurface{Nothing}, velocities, arch, ::SingleColumnGrid) = nothing\n\nvalidate_momentum_advection(momentum_advection, ::SingleColumnGrid) = nothing\nvalidate_tracer_advection(tracer_advection::AbstractAdvectionScheme, ::SingleColumnGrid) = nothing, NamedTuple()\nvalidate_tracer_advection(tracer_advection::Nothing, ::SingleColumnGrid) = nothing, NamedTuple()\n\n#####\n##### Time-step optimizations\n#####\n\ncalculate_free_surface_tendency!(arch, ::SingleColumnGrid, args...) = NoneEvent()\n\n# Fast state update and halo filling\n\nfunction update_state!(model::HydrostaticFreeSurfaceModel, grid::SingleColumnGrid)\n\n fill_halo_regions!(prognostic_fields(model), model.architecture, model.clock, fields(model))\n\n compute_auxiliary_fields!(model.auxiliary_fields)\n\n # Calculate diffusivities\n calculate_diffusivities!(model.diffusivity_fields, model.closure, model)\n\n fill_halo_regions!(model.diffusivity_fields,\n model.architecture,\n model.clock,\n fields(model))\n\n return nothing\nend\n\n\nconst ClosureArray = AbstractArray{<:AbstractTurbulenceClosure}\n\n@inline function ∂ⱼ_τ₁ⱼ(i, j, k, grid::SingleColumnGrid, closure_array::ClosureArray, args...)\n @inbounds closure = closure_array[i, j]\n return ∂ⱼ_τ₁ⱼ(i, j, k, grid, closure, args...)\nend\n\n@inline function ∂ⱼ_τ₂ⱼ(i, j, k, grid::SingleColumnGrid, closure_array::ClosureArray, args...)\n @inbounds closure = closure_array[i, j]\n return ∂ⱼ_τ₂ⱼ(i, j, k, grid, closure, args...)\nend\n\n@inline function ∇_dot_qᶜ(i, j, k, grid::SingleColumnGrid, closure_array::ClosureArray, c, tracer_index, args...)\n @inbounds closure = closure_array[i, j]\n return ∇_dot_qᶜ(i, j, k, grid, closure, c, tracer_index, args...)\nend\n \nstruct ColumnEnsembleSize{C<:Tuple{Int, Int}}\n ensemble :: C\n Nz :: Int\n Hz :: Int\nend\n\nColumnEnsembleSize(; Nz, ensemble=(0, 0), Hz=1) = ColumnEnsembleSize(ensemble, Nz, Hz)\n\nvalidate_size(TX, TY, TZ, e::ColumnEnsembleSize) = tuple(e.ensemble[1], e.ensemble[2], e.Nz)\nvalidate_halo(TX, TY, TZ, e::ColumnEnsembleSize) = tuple(0, 0, e.Hz)\n\n@inline function time_discretization(closure_array::AbstractArray)\n first_closure = CUDA.@allowscalar first(closure_array) # assumes all closures have same time-discretization\n return time_discretization(first_closure)\nend\n\n#####\n##### CATKEVerticalDiffusivity helpers\n#####\n\n@inline tracer_tendency_kernel_function(model::HydrostaticFreeSurfaceModel, closure::CATKEVDArray, ::Val{:e}) =\n hydrostatic_turbulent_kinetic_energy_tendency\n\n\"\"\" Compute the flux of TKE through the surface / top boundary. \"\"\"\n@inline function top_tke_flux(i, j, grid::SingleColumnGrid, clock, fields, parameters, closure_array::CATKEVDArray, buoyancy)\n top_tracer_bcs = parameters.top_tracer_boundary_conditions\n top_velocity_bcs = parameters.top_velocity_boundary_conditions\n @inbounds closure = closure_array[i, j]\n\n return _top_tke_flux(i, j, grid, closure.surface_TKE_flux, closure,\n buoyancy, fields, top_tracer_bcs, top_velocity_bcs, clock)\nend\n\n@inline function hydrostatic_turbulent_kinetic_energy_tendency(i, j, k, grid::SingleColumnGrid,\n val_tracer_index::Val{tracer_index},\n advection,\n closure_array::CATKEVDArray, args...) where tracer_index\n\n @inbounds closure = closure_array[i, j]\n return hydrostatic_turbulent_kinetic_energy_tendency(i, j, k, grid, val_tracer_index, advection, closure, args...)\nend\n\n#####\n##### Arrays of Coriolises\n#####\n\nconst CoriolisMatrix = AbstractMatrix{<:AbstractRotation}\n\n@inline function x_f_cross_U(i, j, k, grid::SingleColumnGrid, coriolis_array::CoriolisMatrix, U)\n @inbounds coriolis = coriolis_array[i, j]\n return x_f_cross_U(i, j, k, grid, coriolis, U)\nend\n\n@inline function y_f_cross_U(i, j, k, grid::SingleColumnGrid, coriolis_array::CoriolisMatrix, U)\n @inbounds coriolis = coriolis_array[i, j]\n return y_f_cross_U(i, j, k, grid, coriolis, U)\nend\n\n@inline function z_f_cross_U(i, j, k, grid::SingleColumnGrid, coriolis_array::CoriolisMatrix, U)\n @inbounds coriolis = coriolis_array[i, j]\n return z_f_cross_U(i, j, k, grid, coriolis, U)\nend\n\n", "meta": {"hexsha": "d106844f1ea8db4e1df96a5639e6be93e2d95984", "size": 5824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Models/HydrostaticFreeSurfaceModels/single_column_model_mode.jl", "max_stars_repo_name": "ErikQQY/Oceananigans.jl", "max_stars_repo_head_hexsha": "cbeba9c586fa65e6e245cd992a08f7b8d0a15542", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Models/HydrostaticFreeSurfaceModels/single_column_model_mode.jl", "max_issues_repo_name": "ErikQQY/Oceananigans.jl", "max_issues_repo_head_hexsha": "cbeba9c586fa65e6e245cd992a08f7b8d0a15542", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Models/HydrostaticFreeSurfaceModels/single_column_model_mode.jl", "max_forks_repo_name": "ErikQQY/Oceananigans.jl", "max_forks_repo_head_hexsha": "cbeba9c586fa65e6e245cd992a08f7b8d0a15542", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8904109589, "max_line_length": 125, "alphanum_fraction": 0.7396978022, "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24214894266462175}} {"text": "# modified by N Laohakunakorn\n# University of Edinburgh 2020\n\nusing Statistics\n# ----------------------------------------------------------------------------------- #\n# Copyright (c) 2017 Varnerlab\n# School of Chemical Engineering Purdue University\n# W. Lafayette IN 46907 USA\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights \n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \n# copies of the Software, and to permit persons to whom the Software is \n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n# ----------------------------------------------------------------------------------- #\nfunction Control(t,x,rate_vector,data_dictionary)\n# ---------------------------------------------------------------------- #\n# Control.jl was generated using the Kwatee code generation system.\n# Username: nicholas\n# Type: CFPS-JULIA\n# Version: 1.0\n# Generation timestamp: 03-24-2017 13:01:36\n# \n# Arguments: \n# t - current time \n# x - state vector \n# rate_vector - vector of reaction rates \n# data_dictionary - Data dictionary instance (holds model parameters) \n# ---------------------------------------------------------------------- #\n\n# Set a default value for the allosteric control variables - \nnumber_of_reactions = length(rate_vector);\ncontrol_vector = ones(number_of_reactions);\ncontrol_parameter_array = data_dictionary[\"CONTROL_PARAMETER_ARRAY\"];\n\n# Alias the species vector - \nM_g6p_c = x[1];\nM_f6p_c = x[2];\nM_fdp_c = x[3];\nM_dhap_c = x[4];\nM_g3p_c = x[5];\nM_13dpg_c = x[6];\nM_3pg_c = x[7];\nM_2pg_c = x[8];\nM_oaa_c = x[9];\nM_coa_c = x[10];\nM_accoa_c = x[11];\nM_6pgl_c = x[12];\nM_6pgc_c = x[13];\nM_ru5p_D_c = x[14];\nM_xu5p_D_c = x[15];\nM_r5p_c = x[16];\nM_s7p_c = x[17];\nM_e4p_c = x[18];\nM_2ddg6p_c = x[19];\nM_cit_c = x[20];\nM_icit_c = x[21];\nM_akg_c = x[22];\nM_succoa_c = x[23];\nM_q8_c = x[24];\nM_fum_c = x[25];\nM_q8h2_c = x[26];\nM_mql8_c = x[27];\nM_mqn8_c = x[28];\nM_h_e = x[29];\nM_ppi_c = x[30];\nM_glx_c = x[31];\nM_actp_c = x[32];\nM_etoh_c = x[33];\nM_for_c = x[34];\nM_nh3_c = x[35];\nM_arg_L_c = x[36];\nM_h2s_c = x[37];\nM_thf_c = x[38];\nM_mlthf_c = x[39];\nM_aicar_c = x[40];\nM_5mthf_c = x[41];\nM_chor_c = x[42];\nM_h2o2_c = x[43];\nM_mglx_c = x[44];\nM_prop_c = x[45];\nM_indole_c = x[46];\nM_cadav_c = x[47];\nM_gaba_c = x[48];\nM_glycoA_c = x[49];\nM_78mdp_c = x[50];\nM_4adochor_c = x[51];\nM_4abz_c = x[52];\nM_78dhf_c = x[53];\nM_dhf_c = x[54];\nM_methf_c = x[55];\nM_10fthf_c = x[56];\nM_prpp_c = x[57];\nM_hco3_c = x[58];\nM_clasp_c = x[59];\nM_or_c = x[60];\nM_omp_c = x[61];\nM_5pbdra = x[62];\nM_gar_c = x[63];\nM_fgar_c = x[64];\nM_fgam_c = x[65];\nM_air_c = x[66];\nM_cair_c = x[67];\nM_saicar_c = x[68];\nM_faicar_c = x[69];\nM_imp_c = x[70];\nM_xmp_c = x[71];\nGENE_CAT = x[72];\nRNAP = x[73];\nOPEN_GENE_CAT = x[74];\nmRNA_CAT = x[75];\nRIBOSOME = x[76];\nRIBOSOME_START_CAT = x[77];\nM_ala_L_c_tRNA = x[78];\nM_arg_L_c_tRNA = x[79];\nM_asn_L_c_tRNA = x[80];\nM_asp_L_c_tRNA = x[81];\nM_cys_L_c_tRNA = x[82];\nM_glu_L_c_tRNA = x[83];\nM_gln_L_c_tRNA = x[84];\nM_gly_L_c_tRNA = x[85];\nM_his_L_c_tRNA = x[86];\nM_ile_L_c_tRNA = x[87];\nM_leu_L_c_tRNA = x[88];\nM_lys_L_c_tRNA = x[89];\nM_met_L_c_tRNA = x[90];\nM_phe_L_c_tRNA = x[91];\nM_pro_L_c_tRNA = x[92];\nM_ser_L_c_tRNA = x[93];\nM_thr_L_c_tRNA = x[94];\nM_trp_L_c_tRNA = x[95];\nM_tyr_L_c_tRNA = x[96];\nM_val_L_c_tRNA = x[97];\nPROTEIN_CAT = x[98];\ntRNA = x[99];\nM_glc_D_c = x[100];\nM_pep_c = x[101];\nM_pyr_c = x[102];\nM_ac_c = x[103];\nM_lac_D_c = x[104];\nM_mal_L_c = x[105];\nM_atp_c = x[106];\nM_adp_c = x[107];\nM_amp_c = x[108];\nM_gtp_c = x[109];\nM_gdp_c = x[110];\nM_gmp_c = x[111];\nM_utp_c = x[112];\nM_udp_c = x[113];\nM_ump_c = x[114];\nM_ctp_c = x[115];\nM_cdp_c = x[116];\nM_cmp_c = x[117];\nM_succ_c = x[118];\nM_asp_L_c = x[119];\nM_gly_L_c = x[120];\nM_ile_L_c = x[121];\nM_asn_L_c = x[122];\nM_cys_L_c = x[123];\nM_lys_L_c = x[124];\nM_his_L_c = x[125];\nM_ala_L_c = x[126];\nM_phe_L_c = x[127];\nM_pro_L_c = x[128];\nM_ser_L_c = x[129];\nM_thr_L_c = x[130];\nM_trp_L_c = x[131];\nM_tyr_L_c = x[132];\nM_val_L_c = x[133];\nM_met_L_c = x[134];\nM_leu_L_c = x[135];\nM_glu_L_c = x[136];\nM_gln_L_c = x[137];\nM_o2_c = x[138];\nM_co2_c = x[139];\nM_pi_c = x[140];\nM_nh4_c = x[141];\nM_so4_c = x[142];\nM_h_c = x[143];\nM_h2o_c = x[144];\nM_nad_c = x[145];\nM_nadh_c = x[146];\nM_nadp_c = x[147];\nM_nadph_c = x[148];\nE_R_glk_atp = x[149];\nE_R_pgi = x[150];\nE_R_pgi_R = x[151];\nE_R_pfk = x[152];\nE_R_fdp = x[153];\nE_R_fbaA = x[154];\nE_R_fbaA_R = x[155];\nE_R_tpiA = x[156];\nE_R_tpiA_R = x[157];\nE_R_gapA = x[158];\nE_R_gapA_R = x[159];\nE_R_pgk = x[160];\nE_R_pgk_R = x[161];\nE_R_gpm = x[162];\nE_R_gpm_R = x[163];\nE_R_eno = x[164];\nE_R_eno_R = x[165];\nE_R_pyk = x[166];\nE_R_pck = x[167];\nE_R_ppc = x[168];\nE_R_pdh = x[169];\nE_R_pps = x[170];\nE_R_zwf = x[171];\nE_R_zwf_R = x[172];\nE_R_pgl = x[173];\nE_R_gnd = x[174];\nE_R_rpe = x[175];\nE_R_rpe_R = x[176];\nE_R_rpi = x[177];\nE_R_rpi_R = x[178];\nE_R_talAB = x[179];\nE_R_talAB_R = x[180];\nE_R_tkt1 = x[181];\nE_R_tkt1_R = x[182];\nE_R_tkt2 = x[183];\nE_R_tkt2_R = x[184];\nE_R_edd = x[185];\nE_R_eda = x[186];\nE_R_gltA = x[187];\nE_R_acn = x[188];\nE_R_acn_R = x[189];\nE_R_icd = x[190];\nE_R_icd_R = x[191];\nE_R_sucAB = x[192];\nE_R_sucCD = x[193];\nE_R_sdh = x[194];\nE_R_frd = x[195];\nE_R_fum = x[196];\nE_R_fum_R = x[197];\nE_R_mdh = x[198];\nE_R_mdh_R = x[199];\nE_R_cyd = x[200];\nE_R_cyo = x[201];\nE_R_app = x[202];\nE_R_atp = x[203];\nE_R_nuo = x[204];\nE_R_pnt1 = x[205];\nE_R_pnt2 = x[206];\nE_R_ndh1 = x[207];\nE_R_ndh2 = x[208];\nE_R_ppa = x[209];\nE_R_aceA = x[210];\nE_R_aceB = x[211];\nE_R_maeA = x[212];\nE_R_maeB = x[213];\nE_R_pta = x[214];\nE_R_pta_R = x[215];\nE_R_ackA = x[216];\nE_R_ackA_R = x[217];\nE_R_acs = x[218];\nE_R_adhE = x[219];\nE_R_adhE_R = x[220];\nE_R_ldh = x[221];\nE_R_ldh_R = x[222];\nE_R_pflAB = x[223];\nE_R_alaAC = x[224];\nE_R_alaAC_R = x[225];\nE_R_arg = x[226];\nE_R_aspC = x[227];\nE_R_asnB = x[228];\nE_R_asnA = x[229];\nE_R_cysEMK = x[230];\nE_R_gltBD = x[231];\nE_R_gdhA = x[232];\nE_R_gdhA_R = x[233];\nE_R_glnA = x[234];\nE_R_glyA = x[235];\nE_R_his = x[236];\nE_R_ile = x[237];\nE_R_leu = x[238];\nE_R_lys = x[239];\nE_R_met = x[240];\nE_R_phe = x[241];\nE_R_pro = x[242];\nE_R_serABC = x[243];\nE_R_thr = x[244];\nE_R_trp = x[245];\nE_R_tyr = x[246];\nE_R_val = x[247];\nE_R_arg_deg = x[248];\nE_R_asp_deg = x[249];\nE_R_asn_deg = x[250];\nE_R_gly_deg = x[251];\nE_R_mglx_deg = x[252];\nE_R_ser_deg = x[253];\nE_R_pro_deg = x[254];\nE_R_thr_deg1 = x[255];\nE_R_thr_deg2 = x[256];\nE_R_thr_deg3 = x[257];\nE_R_trp_deg = x[258];\nE_R_cys_deg = x[259];\nE_R_lys_deg = x[260];\nE_R_gln_deg = x[261];\nE_R_glu_deg = x[262];\nE_R_gaba_deg1 = x[263];\nE_R_gaba_deg2 = x[264];\nE_R_chor = x[265];\nE_R_fol_e = x[266];\nE_R_fol_1 = x[267];\nE_R_fol_2a = x[268];\nE_R_fol_2b = x[269];\nE_R_fol_3 = x[270];\nE_R_fol_4 = x[271];\nE_R_gly_fol = x[272];\nE_R_gly_fol_R = x[273];\nE_R_mthfd = x[274];\nE_R_mthfd_R = x[275];\nE_R_mthfc = x[276];\nE_R_mthfc_R = x[277];\nE_R_mthfr2a = x[278];\nE_R_mthfr2b = x[279];\nE_R_prpp_syn = x[280];\nE_R_or_syn_1 = x[281];\nE_R_or_syn_2 = x[282];\nE_R_omp_syn = x[283];\nE_R_ump_syn = x[284];\nE_R_ctp_1 = x[285];\nE_R_ctp_2 = x[286];\nE_R_A_syn_1 = x[287];\nE_R_A_syn_2 = x[288];\nE_R_A_syn_3 = x[289];\nE_R_A_syn_4 = x[290];\nE_R_A_syn_5 = x[291];\nE_R_A_syn_6 = x[292];\nE_R_A_syn_7 = x[293];\nE_R_A_syn_8 = x[294];\nE_R_A_syn_9 = x[295];\nE_R_A_syn_10 = x[296];\nE_R_A_syn_12 = x[297];\nE_R_xmp_syn = x[298];\nE_R_gmp_syn = x[299];\nE_R_atp_amp = x[300];\nE_R_utp_ump = x[301];\nE_R_ctp_cmp = x[302];\nE_R_gtp_gmp = x[303];\nE_R_atp_adp = x[304];\nE_R_utp_adp = x[305];\nE_R_ctp_adp = x[306];\nE_R_gtp_adp = x[307];\nE_R_udp_utp = x[308];\nE_R_cdp_ctp = x[309];\nE_R_gdp_gtp = x[310];\nE_R_atp_ump = x[311];\nE_R_atp_cmp = x[312];\nE_R_atp_gmp = x[313];\nE_R_adk_atp = x[314];\nE_Import_o2 = x[315];\nE_Import_co2 = x[316];\nE_Import_pi = x[317];\nE_Import_nh4 = x[318];\nE_Import_so4 = x[319];\nE_Import_h2o = x[320];\nE_Export_o2 = x[321];\nE_Export_co2 = x[322];\nE_Export_pi = x[323];\nE_Export_nh4 = x[324];\nE_Export_so4 = x[325];\nE_Export_h2o = x[326];\nE_Proton_gradient = x[327];\nE_transcriptional_initiation_CAT = x[328];\nE_transcription_CAT = x[329];\nE_mRNA_degradation_CAT = x[330];\nE_translation_initiation_CAT = x[331];\nE_translation_CAT = x[332];\nE_tRNA_charging_M_ala_L_c_CAT = x[333];\nE_tRNA_charging_M_arg_L_c_CAT = x[334];\nE_tRNA_charging_M_asn_L_c_CAT = x[335];\nE_tRNA_charging_M_asp_L_c_CAT = x[336];\nE_tRNA_charging_M_cys_L_c_CAT = x[337];\nE_tRNA_charging_M_glu_L_c_CAT = x[338];\nE_tRNA_charging_M_gln_L_c_CAT = x[339];\nE_tRNA_charging_M_gly_L_c_CAT = x[340];\nE_tRNA_charging_M_his_L_c_CAT = x[341];\nE_tRNA_charging_M_ile_L_c_CAT = x[342];\nE_tRNA_charging_M_leu_L_c_CAT = x[343];\nE_tRNA_charging_M_lys_L_c_CAT = x[344];\nE_tRNA_charging_M_met_L_c_CAT = x[345];\nE_tRNA_charging_M_phe_L_c_CAT = x[346];\nE_tRNA_charging_M_pro_L_c_CAT = x[347];\nE_tRNA_charging_M_ser_L_c_CAT = x[348];\nE_tRNA_charging_M_thr_L_c_CAT = x[349];\nE_tRNA_charging_M_trp_L_c_CAT = x[350];\nE_tRNA_charging_M_tyr_L_c_CAT = x[351];\nE_tRNA_charging_M_val_L_c_CAT = x[352];\n\ntransfer_function_vector = Float64[];\n# type: inhibition actor: M_pep_c target: R_pfk\npush!(transfer_function_vector,1.0 - control_parameter_array[1,1]*M_pep_c^control_parameter_array[1,2]/(1+control_parameter_array[1,1]*M_pep_c^control_parameter_array[1,2]));\ncontrol_vector[4] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: activation actor: M_pep_c target: R_fdp\npush!(transfer_function_vector,control_parameter_array[2,1]*M_pep_c^control_parameter_array[2,2]/(1+control_parameter_array[2,1]*M_pep_c^control_parameter_array[2,2]));\ncontrol_vector[5] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: activation actor: M_fdp_c target: R_pyk\npush!(transfer_function_vector,control_parameter_array[3,1]*M_fdp_c^control_parameter_array[3,2]/(1+control_parameter_array[3,1]*M_fdp_c^control_parameter_array[3,2]));\ncontrol_vector[18] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: inhibition actor: M_pep_c target: R_pck\npush!(transfer_function_vector,1.0 - control_parameter_array[4,1]*M_pep_c^control_parameter_array[4,2]/(1+control_parameter_array[4,1]*M_pep_c^control_parameter_array[4,2]));\ncontrol_vector[19] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: activation actor: M_fdp_c target: R_ppc\npush!(transfer_function_vector,control_parameter_array[5,1]*M_fdp_c^control_parameter_array[5,2]/(1+control_parameter_array[5,1]*M_fdp_c^control_parameter_array[5,2]));\ncontrol_vector[20] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: inhibition actor: M_pyr_c target: R_pdh\npush!(transfer_function_vector,1.0 - control_parameter_array[6,1]*M_pyr_c^control_parameter_array[6,2]/(1+control_parameter_array[6,1]*M_pyr_c^control_parameter_array[6,2]));\ncontrol_vector[21] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: inhibition actor: M_pep_c target: R_pps\npush!(transfer_function_vector,1.0 - control_parameter_array[7,1]*M_pep_c^control_parameter_array[7,2]/(1+control_parameter_array[7,1]*M_pep_c^control_parameter_array[7,2]));\ncontrol_vector[22] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: inhibition actor: M_akg_c target: R_gltA\npush!(transfer_function_vector,1.0 - control_parameter_array[8,1]*M_akg_c^control_parameter_array[8,2]/(1+control_parameter_array[8,1]*M_akg_c^control_parameter_array[8,2]));\ncontrol_vector[39] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: inhibition actor: M_pep_c target: R_icd\npush!(transfer_function_vector,1.0 - control_parameter_array[9,1]*M_pep_c^control_parameter_array[9,2]/(1+control_parameter_array[9,1]*M_pep_c^control_parameter_array[9,2]));\ncontrol_vector[42] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: inhibition actor: M_akg_c target: R_aceA\npush!(transfer_function_vector,1.0 - control_parameter_array[10,1]*M_akg_c^control_parameter_array[10,2]/(1+control_parameter_array[10,1]*M_akg_c^control_parameter_array[10,2]));\n# type: inhibition actor: M_pep_c target: R_aceA\npush!(transfer_function_vector,1.0 - control_parameter_array[11,1]*M_pep_c^control_parameter_array[11,2]/(1+control_parameter_array[11,1]*M_pep_c^control_parameter_array[11,2]));\n# type: inhibition actor: M_3pg_c target: R_aceA\npush!(transfer_function_vector,1.0 - control_parameter_array[12,1]*M_3pg_c^control_parameter_array[12,2]/(1+control_parameter_array[12,1]*M_3pg_c^control_parameter_array[12,2]));\ncontrol_vector[62] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: inhibition actor: M_akg_c target: R_aceB\npush!(transfer_function_vector,1.0 - control_parameter_array[13,1]*M_akg_c^control_parameter_array[13,2]/(1+control_parameter_array[13,1]*M_akg_c^control_parameter_array[13,2]));\n# type: inhibition actor: M_pep_c target: R_aceB\npush!(transfer_function_vector,1.0 - control_parameter_array[14,1]*M_pep_c^control_parameter_array[14,2]/(1+control_parameter_array[14,1]*M_pep_c^control_parameter_array[14,2]));\n# type: inhibition actor: M_3pg_c target: R_aceB\npush!(transfer_function_vector,1.0 - control_parameter_array[15,1]*M_3pg_c^control_parameter_array[15,2]/(1+control_parameter_array[15,1]*M_3pg_c^control_parameter_array[15,2]));\ncontrol_vector[63] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: inhibition actor: M_accoa_c target: R_maeB\npush!(transfer_function_vector,1.0 - control_parameter_array[16,1]*M_accoa_c^control_parameter_array[16,2]/(1+control_parameter_array[16,1]*M_accoa_c^control_parameter_array[16,2]));\ncontrol_vector[65] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\ntransfer_function_vector = Float64[];\n# type: activation actor: M_pyr_c target: R_ldh_R\npush!(transfer_function_vector,control_parameter_array[17,1]*M_pyr_c^control_parameter_array[17,2]/(1+control_parameter_array[17,1]*M_pyr_c^control_parameter_array[17,2]));\ncontrol_vector[74] = mean(transfer_function_vector);\ntransfer_function_vector = 0;\n\n# Modify the rate_vector with the control variables - \nrate_vector = rate_vector.*control_vector;\n\n# Return the modified rate vector - \nreturn rate_vector;\nend\n", "meta": {"hexsha": "5c5463af0df39e45153742db65eb6ebf80fa02b7", "size": 15229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "model/scripts/Control.jl", "max_stars_repo_name": "Laohakunakorn-Group/nllab-CFPSmetabolic", "max_stars_repo_head_hexsha": "31efb4518aef47fed33166d1fee280b2ae5ce224", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/scripts/Control.jl", "max_issues_repo_name": "Laohakunakorn-Group/nllab-CFPSmetabolic", "max_issues_repo_head_hexsha": "31efb4518aef47fed33166d1fee280b2ae5ce224", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/scripts/Control.jl", "max_forks_repo_name": "Laohakunakorn-Group/nllab-CFPSmetabolic", "max_forks_repo_head_hexsha": "31efb4518aef47fed33166d1fee280b2ae5ce224", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8279352227, "max_line_length": 182, "alphanum_fraction": 0.7234880819, "num_tokens": 5621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.24214893705561952}} {"text": "abstract type AbstractLShaped end\n\nStochasticPrograms.num_subproblems(lshaped::AbstractLShaped) = lshaped.num_subproblems\nnum_cuts(lshaped::AbstractLShaped) = lshaped.data.num_cuts\nnum_iterations(lshaped::AbstractLShaped) = lshaped.data.iterations\ntolerance(lshaped::AbstractLShaped) = lshaped.parameters.τ\n\n# Initialization #\n# ======================================================================== #\nfunction initialize!(lshaped::AbstractLShaped)\n # Initialize progress meter\n lshaped.progress.thresh = lshaped.parameters.τ\n # Initialize subproblems\n initialize_subproblems!(lshaped, scenarioproblems(lshaped.structure, 2))\n # Prepare the master optimization problem\n prepare_master!(lshaped)\n # Initialize regularization policy\n initialize_regularization!(lshaped)\n # Finish initialization\n finish_initilization!(lshaped)\n return nothing\nend\n# ======================================================================== #\n\n# Functions #\n# ======================================================================== #\nfunction prepare_master!(lshaped::AbstractLShaped)\n # Check sense first\n sense = MOI.get(lshaped.master, MOI.ObjectiveSense())\n if sense == MOI.FEASIBILITY_SENSE\n lshaped.data.no_objective = true\n # Use min-sense during L-shaped procedure\n MOI.set(lshaped.master, MOI.ObjectiveSense(), MOI.MIN_SENSE)\n F = AffineDecisionFunction{Float64}\n MOI.set(lshaped.master, MOI.ObjectiveFunction{F}(), zero(F))\n else\n # Cache the objective function\n F = MOI.get(lshaped.master, MOI.ObjectiveFunctionType())\n lshaped.data.master_objective = MOI.get(lshaped.master, MOI.ObjectiveFunction{F}())\n end\n # Initialize the required number of master variables. Use\n # MOI.VariableIndex(0) as an undef value\n append!(lshaped.master_variables, fill(MOI.VariableIndex(0), num_thetas(lshaped)))\nend\n\nfunction add_master_variable!(lshaped::AbstractLShaped, index::Integer)\n F = MOI.get(lshaped.master, MOI.ObjectiveFunctionType())\n master_variable = MOI.add_variable(lshaped.master)\n # Set name\n MOI.set(lshaped.master, MOI.VariableName(), master_variable,\n add_subscript(\"θ\", index))\n # Get sense\n sense = MOI.get(lshaped.master, MOI.ObjectiveSense())\n coeff = sense == MOI.MIN_SENSE ? 1.0 : -1.0\n # Add to objective\n MOI.modify(lshaped.master, MOI.ObjectiveFunction{F}(), MOI.ScalarCoefficientChange(master_variable, coeff))\n lshaped.master_variables[index] = master_variable\n return nothing\nend\n\nfunction remove_cut_constraints!(lshaped::AbstractLShaped)\n # Decrease count\n lshaped.data.num_cuts -= length(lshaped.cut_constraints)\n # Remove cuts\n for ci in lshaped.cut_constraints\n if !iszero(ci.value)\n MOI.delete(lshaped.master, ci)\n end\n end\n empty!(lshaped.cut_constraints)\n return nothing\nend\n\nfunction restore_master!(lshaped::AbstractLShaped)\n # Remove cut constraints\n remove_cut_constraints!(lshaped)\n # Remove master variables\n for var in lshaped.master_variables\n if !iszero(var.value)\n MOI.delete(lshaped.master, var)\n end\n end\n empty!(lshaped.master_variables)\n # Remove any regularization terms\n restore_regularized_master!(lshaped)\n if lshaped.data.no_objective\n # Re-set FEASIBILITY_SENSE\n MOI.set(lshaped.master, MOI.ObjectiveSense(), MOI.FEASIBILITY_SENSE)\n else\n # Re-add original objective\n @unpack master_objective = lshaped.data\n F = typeof(master_objective)\n MOI.set(lshaped.master, MOI.ObjectiveFunction{F}(), master_objective)\n end\n return nothing\nend\n\nfunction filter_cuts!(lshaped::AbstractLShaped, list)\n # Nothing to do if constraints do not match\n return nothing\nend\n\nfunction filter_cuts!(lshaped::AbstractLShaped, list::Vector{<:CutConstraint})\n # Filter out the cut constraints\n for cut in optimizer.lshaped.cut_constraints\n i = something(findfirst(isequal(c), list), 0)\n if !iszero(i)\n MOI.deleteat!(list, i)\n end\n end\n return nothing\nend\n\nfunction active_model_objectives(lshaped::AbstractLShaped)\n return map(lshaped.master_variables) do var\n var.value != 0\n end\nend\n\nfunction update_solution!(lshaped::AbstractLShaped)\n ncols = num_decisions(lshaped.structure)\n nb = num_thetas(lshaped)\n lshaped.x .= MOI.get.(lshaped.master, MOI.VariablePrimal(), all_decisions(lshaped.decisions))\n θs = map(lshaped.master_variables) do vi\n if vi.value == 0\n -1e10\n else\n MOI.get(lshaped.master, MOI.VariablePrimal(), vi)\n end\n end\n set_model_objectives(lshaped, θs)\n return nothing\nend\n\nfunction decision(lshaped::AbstractLShaped, index::MOI.VariableIndex)\n i = something(findfirst(i -> i == index, all_decisions(lshaped.decisions)), 0)\n if iszero(i)\n throw(MOI.InvalidIndex(index))\n end\n return decision(lshaped)[i]\nend\n\nfunction evaluate_first_stage(lshaped::AbstractLShaped, x::AbstractVector)\n model = lshaped.master\n # Get objective\n @unpack master_objective = lshaped.data\n # Evaluate objective\n decisions = all_decisions(lshaped.decisions)\n obj_val = MOIU.eval_variables(master_objective) do vi\n if vi in decisions\n # Only evaluate decision\n x[vi.value]\n else\n 0.0\n end\n end\n # Return value\n return obj_val\nend\n\nfunction current_objective_value(lshaped::AbstractLShaped)\n # Get sense\n sense = MOI.get(lshaped.master, MOI.ObjectiveSense())\n correction = sense == MOI.MIN_SENSE ? 1.0 : -1.0\n # Return sense-corrected value\n return evaluate_first_stage(lshaped, current_decision(lshaped)) +\n correction * sum(subobjectives(lshaped))\nend\n\nfunction calculate_estimate(lshaped::AbstractLShaped)\n # Get sense\n sense = MOI.get(lshaped.master, MOI.ObjectiveSense())\n correction = sense == MOI.MIN_SENSE ? 1.0 : -1.0\n # Return sense-corrected value\n return evaluate_first_stage(lshaped, lshaped.x) +\n correction * sum(model_objectives(lshaped))\nend\n\nfunction log!(lshaped::AbstractLShaped; optimal = false, status = nothing)\n @unpack Q, θ, iterations = lshaped.data\n @unpack keep, offset, indent = lshaped.parameters\n # Early termination log\n if status != nothing && lshaped.parameters.log\n lshaped.progress.thresh = Inf\n lshaped.progress.printed = true\n val = if status == MOI.INFEASIBLE\n Inf\n elseif status == MOI.DUAL_INFEASIBLE\n -Inf\n else\n 0.0\n end\n ProgressMeter.update!(lshaped.progress, val,\n showvalues = [\n (\"$(indentstr(indent))Objective\", val),\n (\"$(indentstr(indent))Early termination\", status),\n (\"$(indentstr(indent))Number of cuts\", num_cuts(lshaped)),\n (\"$(indentstr(indent))Iterations\", iterations)\n ], keep = keep, offset = offset)\n return nothing\n end\n # Value update\n push!(lshaped.Q_history, Q)\n push!(lshaped.θ_history, θ)\n lshaped.data.iterations += 1\n # Log\n log_regularization!(lshaped)\n if lshaped.parameters.log\n current_gap = optimal ? 0.0 : gap(lshaped)\n ProgressMeter.update!(lshaped.progress, current_gap,\n showvalues = [\n (\"$(indentstr(indent))Objective\", objective_value(lshaped)),\n (\"$(indentstr(indent))Gap\", current_gap),\n (\"$(indentstr(indent))Number of cuts\", num_cuts(lshaped)),\n (\"$(indentstr(indent))Iterations\", iterations)\n ], keep = keep, offset = offset)\n end\n return nothing\nend\n\nfunction log!(lshaped::AbstractLShaped, t::Integer; optimal = false, status = nothing)\n @unpack Q,θ,iterations = lshaped.data\n @unpack keep, offset, indent = lshaped.parameters\n lshaped.Q_history[t] = Q\n lshaped.θ_history[t] = θ\n if status != nothing && lshaped.parameters.log\n lshaped.progress.thresh = Inf\n lshaped.progress.printed = true\n val = if status == MOI.INFEASIBLE\n Inf\n elseif status == MOI.DUAL_INFEASIBLE\n -Inf\n else\n 0.0\n end\n ProgressMeter.update!(lshaped.progress, val,\n showvalues = [\n (\"$(indentstr(indent))Objective\", val),\n (\"$(indentstr(indent))Early termination\", status),\n (\"$(indentstr(indent))Number of cuts\", num_cuts(lshaped)),\n (\"$(indentstr(indent))Iterations\", iterations)\n ], keep = keep, offset = offset)\n return nothing\n end\n log_regularization!(lshaped,t)\n if lshaped.parameters.log\n current_gap = optimal ? 0.0 : gap(lshaped)\n ProgressMeter.update!(lshaped.progress, current_gap,\n showvalues = [\n (\"$(indentstr(indent))Objective\", objective_value(lshaped)),\n (\"$(indentstr(indent))Gap\", current_gap),\n (\"$(indentstr(indent))Number of cuts\", num_cuts(lshaped)),\n (\"$(indentstr(indent))Iterations\", iterations)\n ], keep = keep, offset = offset)\n end\n return nothing\nend\n\nfunction indentstr(n::Integer)\n return repeat(\" \", n)\nend\n\nfunction check_optimality(lshaped::AbstractLShaped)\n @unpack τ = lshaped.parameters\n @unpack θ = lshaped.data\n return θ > -Inf && gap(lshaped) <= τ\nend\n# ======================================================================== #\n\n# Cut functions #\n# ======================================================================== #\nactive(lshaped::AbstractLShaped, hyperplane::AbstractHyperPlane) = active(hyperplane, decision(lshaped), tolerance(lshaped))\nactive(lshaped::AbstractLShaped, cut::HyperPlane{OptimalityCut}) = optimal(cut, decision(lshaped), model_objectives(lshaped)[cut.id], tolerance(lshaped))\nactive(lshaped::AbstractLShaped, cut::AggregatedOptimalityCut) = optimal(cut, decision(lshaped), sum(model_objectives(lshaped)[cut.ids]), tolerance(lshaped))\nsatisfied(lshaped::AbstractLShaped, hyperplane::AbstractHyperPlane) = satisfied(hyperplane, decision(lshaped), tolerance(lshaped))\nsatisfied(lshaped::AbstractLShaped, cut::HyperPlane{OptimalityCut}) = satisfied(cut, decision(lshaped), model_objectives(lshaped)[cut.id], tolerance(lshaped))\nsatisfied(lshaped::AbstractLShaped, cut::AggregatedOptimalityCut) = satisfied(cut, decision(lshaped), sum(model_objectives(lshaped)[cut.ids]), tolerance(lshaped))\nviolated(lshaped::AbstractLShaped, hyperplane::AbstractHyperPlane) = !satisfied(lshaped, hyperplane)\ngap(lshaped::AbstractLShaped, hyperplane::AbstractHyperPlane) = gap(hyperplane, decision(lshaped))\ngap(lshaped::AbstractLShaped, cut::HyperPlane{OptimalityCut}) = gap(cut, decision(lshaped), model_objectives(lshaped)[cut.id])\ngap(lshaped::AbstractLShaped, cut::AggregatedOptimalityCut) = gap(cut, decision(lshaped), sum(model_objectives(lshaped)[cut.ids]))\n\nfunction add_cut!(lshaped::AbstractLShaped, cut::AbstractHyperPlane; consider_consolidation = true, check = true)\n added = add_cut!(lshaped, cut, model_objectives(lshaped), subobjectives(lshaped), check = check)\n if consider_consolidation\n added && add_cut!(lshaped, lshaped.consolidation, cut)\n end\n return added\nend\n\nfunction add_cut!(lshaped::AbstractLShaped, cut::HyperPlane{OptimalityCut}, θs::AbstractVector, subobjectives::AbstractVector, Q::AbstractFloat; check = true)\n if lshaped.master_variables[cut.id].value == 0\n # Add master variable if cut is encountered for the first time\n add_master_variable!(lshaped, cut.id)\n end\n # Get the model value\n θ = θs[cut.id]\n @unpack cut_scaling = lshaped.parameters\n # Update objective\n subobjectives[cut.id] = Q\n # Check if cut gives new information\n if check && θ > -Inf && (θ + sqrt(eps()) >= Q || θ + sqrt(eps()) >= cut(lshaped.x))\n # Optimal with respect to this subproblem\n return false\n end\n # Add optimality cut\n process_cut!(lshaped, cut)\n f, set = moi_constraint(cut, lshaped.master_variables, cut_scaling)\n push!(lshaped.cut_constraints, MOI.add_constraint(lshaped.master, f, set))\n lshaped.data.num_cuts += 1\n if lshaped.parameters.debug\n push!(lshaped.cuts, cut)\n end\n return true\nend\nfunction add_cut!(lshaped::AbstractLShaped, cut::AggregatedOptimalityCut, θs::AbstractVector, subobjectives::AbstractVector, Q::AbstractFloat; check = true)\n for id in cut.ids\n if lshaped.master_variables[id].value == 0\n # Add master variable if cut is encountered for the first time\n add_master_variable!(lshaped, id)\n end\n end\n θs = θs[cut.ids]\n θ = sum(θs)\n @unpack cut_scaling = lshaped.parameters\n # Update objective\n subobjectives[cut.ids] .= Q/length(cut.ids)\n # Check if cut gives new information\n if check && θ > -Inf && (θ + sqrt(eps()) >= Q || θ + sqrt(eps()) >= cut(lshaped.x))\n # Optimal with respect to these subproblems\n return false\n end\n # Add optimality cut\n process_cut!(lshaped, cut)\n f, set = moi_constraint(cut, lshaped.master_variables, cut_scaling)\n push!(lshaped.cut_constraints, MOI.add_constraint(lshaped.master, f, set))\n lshaped.data.num_cuts += 1\n if lshaped.parameters.debug\n push!(lshaped.cuts, cut)\n end\n return true\nend\nadd_cut!(lshaped::AbstractLShaped, cut::AnyOptimalityCut, θs::AbstractVector, subobjectives::AbstractVector, x::AbstractVector; check = true) = add_cut!(lshaped, cut, θs, subobjectives, cut(x); check = check)\nadd_cut!(lshaped::AbstractLShaped, cut::AnyOptimalityCut, θs::AbstractVector, subobjectives::AbstractVector; check = true) = add_cut!(lshaped, cut, θs, subobjectives, current_decision(lshaped); check = check)\n\nfunction add_cut!(lshaped::AbstractLShaped, cut::HyperPlane{FeasibilityCut}, ::AbstractVector, subobjectives::AbstractVector, Q::AbstractFloat; check = true)\n # Ensure that there is no false convergence\n subobjectives[cut.id] = Q\n # Add feasibility cut\n process_cut!(lshaped, cut)\n f, set = moi_constraint(cut, lshaped.master_variables, 1.0)\n push!(lshaped.cut_constraints, MOI.add_constraint(lshaped.master, f, set))\n lshaped.data.num_cuts += 1\n if lshaped.parameters.debug\n push!(lshaped.feasibility.cuts, cut)\n end\n return true\nend\nadd_cut!(lshaped::AbstractLShaped, cut::HyperPlane{FeasibilityCut}, θs::AbstractVector, subobjectives::AbstractVector; check = true) = add_cut!(lshaped, cut, θs, subobjectives, Inf)\n\nfunction add_cut!(lshaped::AbstractLShaped, cut::HyperPlane{Infeasible}, ::AbstractVector, subobjectives::AbstractVector; check = true)\n subobjectives[cut.id] = Inf\n return true\nend\n\nfunction add_cut!(lshaped::AbstractLShaped, cut::HyperPlane{Unbounded}, ::AbstractVector, subobjectives::AbstractVector; check = true)\n subobjectives[cut.id] = -Inf\n return true\nend\n", "meta": {"hexsha": "61a4eeb939456a2a9de56990ca1690432b8bac0c", "size": 15376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solvers/structured/lshaped/types/AbstractLShaped.jl", "max_stars_repo_name": "rtwalker/StochasticPrograms.jl", "max_stars_repo_head_hexsha": "2e59f0ad0504515855bbef411c67653b5723b3a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solvers/structured/lshaped/types/AbstractLShaped.jl", "max_issues_repo_name": "rtwalker/StochasticPrograms.jl", "max_issues_repo_head_hexsha": "2e59f0ad0504515855bbef411c67653b5723b3a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/structured/lshaped/types/AbstractLShaped.jl", "max_forks_repo_name": "rtwalker/StochasticPrograms.jl", "max_forks_repo_head_hexsha": "2e59f0ad0504515855bbef411c67653b5723b3a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5567567568, "max_line_length": 208, "alphanum_fraction": 0.6532908429, "num_tokens": 3982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061556288288, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.24211616351674256}} {"text": "#####\n##### apply flux boundary conditions to tracer tendency `Gc`\n##### \n\n# a positive west flux is associated with an *increase* in `Gc` near the west boundary.\n# same for south and bottom.\n@kernel function apply_west_bcs_kernel!(Gc, grid, west_bc, iter, ΔT)\n j, k = @index(Global, NTuple)\n jj = j + grid.Hy\n kk = k + grid.Hz\n @inbounds Gc[1+grid.Hx, jj, kk] += getbc(west_bc, j, k, iter) * ΔT * Ax(1+grid.Hx, jj, kk, grid) / volume(1+grid.Hx, jj, kk, grid)\nend\n\n@kernel function apply_south_bcs_kernel!(Gc, grid, south_bc, iter, ΔT)\n i, k = @index(Global, NTuple)\n ii = i + grid.Hx\n kk = k + grid.Hz\n @inbounds Gc[ii, 1+grid.Hy, kk] += getbc(south_bc, i, k, iter) * ΔT * Ay(ii, 1+grid.Hy, kk, grid) / volume(ii, 1+grid.Hy, kk, grid)\nend\n\n@kernel function apply_bottom_bcs_kernel!(Gc, grid, bottom_bc, iter, ΔT)\n i, j = @index(Global, NTuple)\n ii = i + grid.Hx\n jj = j + grid.Hy\n @inbounds Gc[ii, jj, grid.Nz+grid.Hz] += getbc(bottom_bc, i, j, iter) * ΔT * Az(ii, jj, grid.Nz+grid.Hz, grid) / volume(ii, jj, grid.Nz+grid.Hz, grid)\nend\n\n# a positive east flux is associated with an *decrease* in `Gc` near the east boundary.\n# same for north and top.\n@kernel function apply_east_bcs_kernel!(Gc, grid, east_bc, iter, ΔT)\n j, k = @index(Global, NTuple)\n jj = j + grid.Hy\n kk = k + grid.Hz\n @inbounds Gc[grid.Nx+grid.Hx, jj, kk] -= getbc(east_bc, j, k, iter) * ΔT * Ax(grid.Nx+grid.Hx, jj, kk, grid) / volume(grid.Nx+grid.Hx, jj, kk, grid)\nend\n\n@kernel function apply_north_bcs_kernel!(Gc, grid, north_bc, iter, ΔT)\n i, k = @index(Global, NTuple)\n ii = i + grid.Hx\n kk = k + grid.Hz\n @inbounds Gc[ii, grid.Ny+grid.Hy, kk] -= getbc(north_bc, i, k, iter) * ΔT * Ay(ii, grid.Ny+grid.Hy, kk, grid) / volume(ii, grid.Ny+grid.Hy, kk, grid)\nend\n\n@kernel function apply_top_bcs_kernel!(Gc, grid, top_bc, iter, ΔT)\n i, j = @index(Global, NTuple)\n ii = i + grid.Hx\n jj = j + grid.Hy\n @inbounds Gc[ii, jj, 1+grid.Hz] -= getbc(top_bc, i, j, iter) * ΔT * Az(ii, jj, 1+grid.Hz, grid) / volume(ii, jj, 1+grid.Hz, grid)\nend\n\n##### apply flux boundary conditions in x direction (west and east)\nfunction apply_west_bcs!(Gc, grid, west_bc, iter, ΔT, arch, dep)\n kernel! = apply_west_bcs_kernel!(device(arch), (16,16), (grid.Ny, grid.Nz))\n event = kernel!(Gc, grid, west_bc, iter, ΔT, dependencies=dep)\n wait(device(arch), event)\n return nothing\nend\nfunction apply_east_bcs!(Gc, grid, east_bc, iter, ΔT, arch, dep)\n kernel! = apply_east_bcs_kernel!(device(arch), (16,16), (grid.Ny, grid.Nz))\n event = kernel!(Gc, grid, east_bc, iter, ΔT, dependencies=dep)\n wait(device(arch), event)\n return nothing\nend\n\n##### apply flux boundary conditions in y direction (south and north)\nfunction apply_south_bcs!(Gc, grid, south_bc, iter, ΔT, arch, dep)\n kernel! = apply_south_bcs_kernel!(device(arch), (16,16), (grid.Nx, grid.Nz))\n event = kernel!(Gc, grid, south_bc, iter, ΔT, dependencies=dep)\n wait(device(arch), event)\n return nothing\nend\nfunction apply_north_bcs!(Gc, grid, north_bc, iter, ΔT, arch, dep)\n kernel! = apply_north_bcs_kernel!(device(arch), (16,16), (grid.Nx, grid.Nz))\n event = kernel!(Gc, grid, north_bc, iter, ΔT, dependencies=dep)\n wait(device(arch), event)\n return nothing\nend\n\n##### apply flux boundary conditions in z direction (bottom and top)\nfunction apply_bottom_bcs!(Gc, grid, bottom_bc, iter, ΔT, arch, dep)\n kernel! = apply_bottom_bcs_kernel!(device(arch), (16,16), (grid.Nx, grid.Ny))\n event = kernel!(Gc, grid, bottom_bc, iter, ΔT, dependencies=dep)\n wait(device(arch), event)\n return nothing\nend\nfunction apply_top_bcs!(Gc, grid, top_bc, iter, ΔT, arch, dep)\n kernel! = apply_top_bcs_kernel!(device(arch), (16,16), (grid.Nx, grid.Ny))\n event = kernel!(Gc, grid, top_bc, iter, ΔT, dependencies=dep)\n wait(device(arch), event)\n return nothing\nend\n\n\n##### apply flux boundary conditions in all three directions, six faces.\nfunction apply_bcs!(Gcs, nuts, grid, iter, ΔT, arch)\n barrier = Event(device(arch))\n events = []\n for name in nut_names\n west_event = apply_west_bcs!(Gcs[name].data, grid, nuts[name].bc.west, iter, ΔT, arch, barrier)\n east_event = apply_east_bcs!(Gcs[name].data, grid, nuts[name].bc.east, iter, ΔT, arch, barrier)\n south_event = apply_south_bcs!(Gcs[name].data, grid, nuts[name].bc.south, iter, ΔT, arch, barrier)\n north_event = apply_north_bcs!(Gcs[name].data, grid, nuts[name].bc.north, iter, ΔT, arch, barrier)\n bottom_event = apply_bottom_bcs!(Gcs[name].data, grid, nuts[name].bc.bottom, iter, ΔT, arch, barrier)\n top_event = apply_top_bcs!(Gcs[name].data, grid, nuts[name].bc.top, iter, ΔT, arch, barrier)\n push!(events, west_event, east_event, south_event, north_event, bottom_event, top_event)\n end\n\n # filter out ::Nothing\n events = filter(e -> typeof(e) <: Event, events)\n\n wait(device(arch), MultiEvent(Tuple(events)))\n return nothing\nend\n\n# Avoid some computation / memory accesses when no flux boundary conditions will be applied\n apply_west_bcs!(Gc, grid, ::Nothing, iter, ΔT, arch, dep) = nothing\n apply_east_bcs!(Gc, grid, ::Nothing, iter, ΔT, arch, dep) = nothing\n apply_north_bcs!(Gc, grid, ::Nothing, iter, ΔT, arch, dep) = nothing\n apply_south_bcs!(Gc, grid, ::Nothing, iter, ΔT, arch, dep) = nothing\napply_bottom_bcs!(Gc, grid, ::Nothing, iter, ΔT, arch, dep) = nothing\n apply_top_bcs!(Gc, grid, ::Nothing, iter, ΔT, arch, dep) = nothing", "meta": {"hexsha": "a2fc48b873cd82252677ded5769535eed37badc3", "size": 5526, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Fields/apply_bcs.jl", "max_stars_repo_name": "zhenwu0728/PlanktonIndividuals.jl", "max_stars_repo_head_hexsha": "aa2edffcab3b38ae1d7f188bc421ed8e01ac9ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-03-14T08:48:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-08T19:35:57.000Z", "max_issues_repo_path": "src/Fields/apply_bcs.jl", "max_issues_repo_name": "zhenwu0728/PlanktonIndividuals.jl", "max_issues_repo_head_hexsha": "aa2edffcab3b38ae1d7f188bc421ed8e01ac9ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-03-13T19:27:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-06T19:54:00.000Z", "max_forks_repo_path": "src/Fields/apply_bcs.jl", "max_forks_repo_name": "zhenwu0728/PlanktonIndividuals.jl", "max_forks_repo_head_hexsha": "aa2edffcab3b38ae1d7f188bc421ed8e01ac9ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-11T21:23:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T21:23:27.000Z", "avg_line_length": 45.6694214876, "max_line_length": 154, "alphanum_fraction": 0.6625045241, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24209872243133926}} {"text": "\"\"\"\n struct JSONModel <: MetabolicModel\n json::Dict{String,Any}\n end\n\nA struct used to store the contents of a JSON model, i.e. a model read from a\nfile ending with `.json`. These model files typically store all the model\nparameters in arrays of JSON objects (i.e. Julia dictionaries).\n\nUsually, not all of the fields of the input JSON can be easily represented when\nconverting to other models, care should be taken to avoid losing information.\n\nDirect work on this precise model type is not very efficient, as the accessor\nfunctions need to repeatedly find the information in the JSON tree. This gets\nvery slow especially if calling many accessor functions sequentially. To avoid\nthat, convert to e.g. [`StandardModel`](@ref) as soon as possible.\n\n# Example\n````\nmodel = load_json_model(\"some_model.json\")\nmodel.json # see the actual underlying JSON\nreactions(model) # see the list of reactions\n````\n\"\"\"\nstruct JSONModel <: MetabolicModel\n json::Dict{String,Any}\nend\n\n\n# helper access macros, see examples below for usage\nmacro _json_sectionkey(namesConstant::Symbol, error)\n esc(:(\n begin\n _key = _guesskey(keys(model.json), _constants.keynames.$namesConstant)\n if isnothing(_key)\n $error\n end\n _key\n end\n ))\nend\n\nmacro _json_section(namesConstant::Symbol, error)\n esc(:(\n begin\n _key = @_json_sectionkey $namesConstant ($error)\n model.json[_key]\n end\n ))\nend\n\nmacro _json_section_firstid(namesConstant::Symbol, id::Symbol, error)\n return esc(:(\n begin\n _s = @_json_section $namesConstant ($error)\n _s[findfirst(x -> x[\"id\"] == $id, _s)]\n end\n ))\nend\n\nfunction _parse_annotations(x)::Annotations\n Annotations([k => if typeof(v) == String\n [v]\n else\n convert(Vector{String}, v)\n end for (k, v) in x])\nend\n\n_parse_notes(x)::Notes = _parse_annotations(x)\n\n\"\"\"\n reactions(model::JSONModel)\n\nExtract reaction names (stored as `.id`) from JSON model.\n\"\"\"\nfunction reactions(model::JSONModel)\n rs = @_json_section rxns throw(\n DomainError(keys(model.json), \"JSON model has no reaction keys\"),\n )\n\n return [string(get(rs[i], \"id\", \"rxn$i\")) for i in eachindex(rs)]\nend\n\n\"\"\"\n metabolites(model::JSONModel)\n\nExtract metabolite names (stored as `.id`) from JSON model.\n\"\"\"\nfunction metabolites(model::JSONModel)\n ms = @_json_section mets throw(\n DomainError(keys(model.json), \"JSON model has no metabolite keys\"),\n )\n\n return [string(get(ms[i], \"id\", \"met$i\")) for i in eachindex(ms)]\nend\n\n\"\"\"\n genes(model::JSONModel)\n\nExtract gene names from a JSON model.\n\"\"\"\nfunction genes(model::JSONModel)\n gs = @_json_section genes return []\n\n return [string(get(gs[i], \"id\", \"gene$i\")) for i in eachindex(gs)]\nend\n\n\"\"\"\n stoichiometry(model::JSONModel)\n\nGet the stoichiometry. Assuming the information is stored in reaction object\nunder key `.metabolites`.\n\"\"\"\nfunction stoichiometry(model::JSONModel)\n rxn_ids = reactions(model)\n met_ids = metabolites(model)\n\n rs = @_json_section rxns throw(\n DomainError(keys(model.json), \"JSON model has no reaction keys\"),\n )\n\n S = SparseArrays.spzeros(length(met_ids), length(rxn_ids))\n for (i, rid) in enumerate(rxn_ids)\n r = rs[findfirst(x -> x[\"id\"] == rid, rs)]\n for (met_id, coeff) in r[\"metabolites\"]\n j = findfirst(==(met_id), met_ids)\n if isnothing(j)\n throw(\n DomainError(\n met_id,\n \"Unknown metabolite found in stoichiometry of $(rxn_ids[i])\",\n ),\n )\n end\n S[j, i] = coeff\n end\n end\n return S\nend\n\n\"\"\"\n bounds(model::JSONModel)\n\nGet the bounds for reactions, assuming the information is stored in\n`.lower_bound` and `.upper_bound`.\n\"\"\"\nfunction bounds(model::JSONModel)\n rs = @_json_section rxns return (\n sparse(fill(-_constants.default_reaction_bound, n_reactions(model))),\n sparse(fill(_constants.default_reaction_bound, n_reactions(model))),\n )\n return (\n sparse([get(rxn, \"lower_bound\", -_constants.default_reaction_bound) for rxn in rs]),\n sparse([get(rxn, \"upper_bound\", _constants.default_reaction_bound) for rxn in rs]),\n )\nend\n\n\"\"\"\n objective(model::JSONModel)\n\nCollect `.objective_coefficient` keys from model reactions.\n\"\"\"\nfunction objective(model::JSONModel)\n rs = @_json_section rxns return spzeros(n_reactions(model))\n\n return sparse([float(get(rxn, \"objective_coefficient\", 0.0)) for rxn in rs])\nend\n\n\"\"\"\n reaction_gene_associaton(model::JSONModel, rid::String)\n\nParses the `.gene_reaction_rule` from reactions.\n\"\"\"\nfunction reaction_gene_association(model::JSONModel, rid::String)\n rxn = @_json_section_firstid rxns rid return nothing\n return _maybemap(_parse_grr, get(rxn, \"gene_reaction_rule\", nothing))\nend\n\n\"\"\"\n reaction_subsystem(model::JSONModel, rid::String)\n\nParses the `.subsystem` out from reactions.\n\"\"\"\nfunction reaction_subsystem(model::JSONModel, rid::String)\n rxn = @_json_section_firstid rxns rid return nothing\n return get(rxn, \"subsystem\", nothing)\nend\n\n\"\"\"\n metabolite_formula(model::JSONModel, mid::String)\n\nParse and return the metabolite `.formula`\n\"\"\"\nfunction metabolite_formula(model::JSONModel, mid::String)\n met = @_json_section_firstid mets mid return nothing\n return _maybemap(_parse_formula, get(met, \"formula\", nothing))\nend\n\n\"\"\"\n metabolite_charge(model::JSONModel, mid::String)\n\nReturn the metabolite `.charge`\n\"\"\"\nfunction metabolite_charge(model::JSONModel, mid::String)\n met = @_json_section_firstid mets mid return nothing\n return get(met, \"charge\", 0)\nend\n\n\"\"\"\n metabolite_compartment(model::JSONModel, mid::String)\n\nReturn the metabolite `.compartment`\n\"\"\"\nfunction metabolite_compartment(model::JSONModel, mid::String)\n met = @_json_section_firstid mets mid return nothing\n return get(met, \"compartment\", nothing)\nend\n\n\"\"\"\n gene_annotations(model::JSONModel, gid::String)::Annotations\n\nGene annotations from the [`JSONModel`](@ref).\n\"\"\"\nfunction gene_annotations(model::JSONModel, gid::String)::Annotations\n gene = @_json_section_firstid genes gid return Dict()\n _maybemap(_parse_annotations, get(gene, \"annotation\", nothing))\nend\n\n\"\"\"\n gene_notes(model::JSONModel, gid::String)::Notes\n\nGene notes from the [`JSONModel`](@ref).\n\"\"\"\nfunction gene_notes(model::JSONModel, gid::String)::Notes\n gene = @_json_section_firstid genes gid return Dict()\n _maybemap(_parse_notes, get(gene, \"notes\", nothing))\nend\n\n\"\"\"\n reaction_annotations(model::JSONModel, rid::String)::Annotations\n\nReaction annotations from the [`JSONModel`](@ref).\n\"\"\"\nfunction reaction_annotations(model::JSONModel, rid::String)::Annotations\n rxn = @_json_section_firstid rxns rid return Dict()\n _maybemap(_parse_annotations, get(rxn, \"annotation\", nothing))\nend\n\n\"\"\"\n reaction_notes(model::JSONModel, rid::String)::Notes\n\nReaction notes from the [`JSONModel`](@ref).\n\"\"\"\nfunction reaction_notes(model::JSONModel, rid::String)::Notes\n rxn = @_json_section_firstid rxns rid return Dict()\n _maybemap(_parse_notes, get(rxn, \"notes\", nothing))\nend\n\n\"\"\"\n metabolite_annotations(model::JSONModel, mid::String)::Annotations\n\nMetabolite annotations from the [`JSONModel`](@ref).\n\"\"\"\nfunction metabolite_annotations(model::JSONModel, mid::String)::Annotations\n met = @_json_section_firstid mets mid return Dict()\n _maybemap(_parse_annotations, get(met, \"annotation\", nothing))\nend\n\n\"\"\"\n metabolite_notes(model::JSONModel, mid::String)::Notes\n\nMetabolite notes from the [`JSONModel`](@ref).\n\"\"\"\nfunction metabolite_notes(model::JSONModel, mid::String)::Notes\n met = @_json_section_firstid mets mid return Dict()\n _maybemap(_parse_notes, get(met, \"notes\", nothing))\nend\n\n\"\"\"\n reaction_stoichiometry(model::JSONModel, rxn_id::String)::Dict{String, Float64}\n\nReturn the reaction equation of reaction with id `rxn_id` in model. The reaction\nequation maps metabolite ids to their stoichiometric coefficients.\n\"\"\"\nfunction reaction_stoichiometry(m::JSONModel, rxn_id::String)::Dict{String, Float64}\n ind = findfirst(x -> x[\"id\"] == rxn_id, m.json[\"reactions\"])\n m.json[\"reactions\"][ind][\"metabolites\"]\nend\n\n\"\"\"\n Base.convert(::Type{JSONModel}, mm::MetabolicModel)\n\nConvert any [`MetabolicModel`](@ref) to [`JSONModel`](@ref).\n\"\"\"\nfunction Base.convert(::Type{JSONModel}, mm::MetabolicModel)\n if typeof(mm) == JSONModel\n return mm\n end\n\n rxn_ids = reactions(mm)\n met_ids = metabolites(mm)\n gene_ids = genes(mm)\n S = stoichiometry(mm)\n lbs, ubs = bounds(mm)\n ocs = objective(mm)\n\n json_model = JSONModel(Dict{String,Any}())\n json = Dict{String,Any}()\n json[\"id\"] = \"model\" # default\n\n #TODO: add notes, names and similar fun stuff when they are available\n\n json[first(_constants.keynames.genes)] = [\n Dict([\n \"id\" => gid,\n \"annotation\" => gene_annotations(mm, gid),\n \"notes\" => gene_notes(mm, gid),\n ],) for gid in gene_ids\n ]\n\n json[first(_constants.keynames.mets)] = [\n Dict([\n \"id\" => mid,\n \"formula\" => _maybemap(_unparse_formula, metabolite_formula(mm, mid)),\n \"charge\" => metabolite_charge(mm, mid),\n \"compartment\" => metabolite_compartment(mm, mid),\n \"annotation\" => metabolite_annotations(mm, mid),\n \"notes\" => metabolite_notes(mm, mid),\n ]) for mid in met_ids\n ]\n\n json[first(_constants.keynames.rxns)] = [\n begin\n res = Dict{String,Any}()\n res[\"id\"] = rid\n res[\"subsystem\"] = reaction_subsystem(mm, rid)\n res[\"annotation\"] = reaction_annotations(mm, rid)\n res[\"notes\"] = reaction_notes(mm, rid)\n\n grr = reaction_gene_association(mm, rid)\n if !isnothing(grr)\n res[\"gene_reaction_rule\"] = _unparse_grr(String, grr)\n end\n\n res[\"lower_bound\"] = lbs[ri]\n res[\"upper_bound\"] = ubs[ri]\n res[\"objective_coefficient\"] = ocs[ri]\n I, V = findnz(S[:, ri])\n res[\"metabolites\"] =\n Dict{String,Float64}([met_ids[ii] => vv for (ii, vv) in zip(I, V)])\n res\n end for (ri, rid) in enumerate(rxn_ids)\n ]\n\n return JSONModel(json)\nend\n", "meta": {"hexsha": "48f26aebc8bcadd748e5bea5dde9fe225aa03193", "size": 10469, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/base/types/JSONModel.jl", "max_stars_repo_name": "htpusa/COBREXA.jl", "max_stars_repo_head_hexsha": "a1987d7d3081cf58c56df4bd50c4e235ecad20ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/base/types/JSONModel.jl", "max_issues_repo_name": "htpusa/COBREXA.jl", "max_issues_repo_head_hexsha": "a1987d7d3081cf58c56df4bd50c4e235ecad20ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/types/JSONModel.jl", "max_forks_repo_name": "htpusa/COBREXA.jl", "max_forks_repo_head_hexsha": "a1987d7d3081cf58c56df4bd50c4e235ecad20ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.324929972, "max_line_length": 92, "alphanum_fraction": 0.6613812207, "num_tokens": 2585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24209872243133926}} {"text": "export LazyDiscretePost,\n ApproximatingDiscretePost\n\nimport LazySets.use_precise_ρ\n\n\"\"\"\n LazyDiscretePost <: DiscretePost\n\nTextbook implementation of a discrete post operator, but with lazy intersections.\n\n### Fields\n\n- `options` -- an `Options` structure that holds the algorithm-specific options\n\n### Algorithm\n\nThe algorithm is based on [Flowpipe-Guard Intersection for Reachability\nComputations with Support Functions](http://spaceex.imag.fr/sites/default/files/frehser_adhs2012.pdf).\n\"\"\"\nstruct LazyDiscretePost <: DiscretePost\n options::Options\n\n function LazyDiscretePost(𝑂::Options)\n 𝑂copy = copy(𝑂)\n # TODO: pass 𝑂 directly?\n check_aliases_and_add_default_value!(𝑂.dict, 𝑂copy.dict, [:check_invariant_intersection], false)\n check_aliases_and_add_default_value!(𝑂.dict, 𝑂copy.dict, [:overapproximation], Hyperrectangle)\n check_aliases_and_add_default_value!(𝑂.dict, 𝑂copy.dict, [:lazy_R⋂I], false)\n check_aliases_and_add_default_value!(𝑂.dict, 𝑂copy.dict, [:lazy_R⋂G], true)\n check_aliases_and_add_default_value!(𝑂.dict, 𝑂copy.dict, [:lazy_A⌜R⋂G⌟], \"invertible\")\n check_aliases_and_add_default_value!(𝑂.dict, 𝑂copy.dict, [:lazy_A⌜R⋂G⌟⋂I], true)\n check_aliases_and_add_default_value!(𝑂.dict, 𝑂copy.dict, [:combine_invariant_guard], 𝑂copy[:lazy_R⋂I])\n\n if 𝑂copy[:combine_invariant_guard] && !𝑂copy[:lazy_R⋂I]\n throw(ArgumentError(\"option :combine_invariant_guard only makes \" *\n \"sense in combination with option :lazy_R⋂I\"))\n end\n\n return new(𝑂copy)\n end\nend\n\n# convenience constructor from pairs of symbols\nLazyDiscretePost(𝑂::Pair{Symbol,<:Any}...) = LazyDiscretePost(Options(Dict{Symbol,Any}(𝑂)))\n\n# default options for the LazyDiscretePost discrete post operator\nLazyDiscretePost() = LazyDiscretePost(Options())\n\n\"\"\"\n ApproximatingDiscretePost()\n\nTextbook implementation of a discrete post operator, but with lazy intersections\nfollowed by an overapproximation. This is a particular case of the\n`LazyDiscretePost`.\n\"\"\"\nfunction ApproximatingDiscretePost()\n return LazyDiscretePost(:check_invariant_intersection=>false,\n :overapproximation=>Hyperrectangle,\n :lazy_R⋂I=>false,\n :lazy_R⋂G=>false,\n :lazy_A⌜R⋂G⌟⋂I=>false)\nend\n\nfunction ApproximatingDiscretePost(𝑂::Options)\n 𝑂_default = Options(:lazy_R⋂I=>false,\n :lazy_R⋂G=>false,\n :lazy_A⌜R⋂G⌟⋂I=>false)\n merge!(𝑂_default, 𝑂)\n LazyDiscretePost(𝑂_default)\nend\n\ninit(𝒫::LazyDiscretePost, 𝒮::AbstractSystem, 𝑂::Options) = init!(𝒫, 𝒮, copy(𝑂))\n\n# TODO: use 𝑂 only?\nfunction init!(𝒫::LazyDiscretePost, 𝒮::AbstractSystem, 𝑂::Options)\n 𝑂[:n] = statedim(𝒮, 1)\n\n # solver-specific options (adds default values for unspecified options)\n 𝑂out = validate_solver_options_and_add_default_values!(𝑂)\n\n return 𝑂out\nend\n\nfunction tube⋂inv(𝒫::LazyDiscretePost,\n reach_tube::Vector{<:AbstractReachSet{<:LazySet{N}}},\n invariant,\n start_interval\n ) where {N}\n\n dirs = 𝒫.options[:overapproximation]\n\n Rsets = Vector{AbstractReachSet{<:LazySet{N}}}()\n @inbounds for reach_set in reach_tube\n R⋂I = Intersection(set(reach_set), invariant)\n if 𝒫.options[:check_invariant_intersection] && isempty(R⋂I)\n break\n end\n if !𝒫.options[:lazy_R⋂I]\n R⋂I = overapproximate(R⋂I, dirs)\n end\n push!(Rsets,\n substitute(reach_set, set=R⋂I,\n time_start=time_start(reach_set) + start_interval[1],\n time_end=time_end(reach_set) + start_interval[2]))\n end\n\n return Rsets\nend\n\nfunction post(𝒫::LazyDiscretePost,\n HS::HybridSystem,\n waiting_list::Vector{Tuple{Int, <:AbstractReachSet{LazySet{N}}, Int}},\n passed_list,\n source_loc_id,\n tube⋂inv,\n jumps,\n options\n ) where {N}\n jumps += 1\n oa = 𝒫.options[:overapproximation]\n source_invariant = HS.modes[source_loc_id].X\n inv_isa_Hrep, inv_isa_H_polytope = get_Hrep_info(source_invariant)\n\n for trans in out_transitions(HS, source_loc_id)\n info(\"Considering transition: $trans\")\n target_loc_id = target(HS, trans)\n target_loc = HS.modes[target(HS, trans)]\n target_invariant = target_loc.X\n constrained_map = resetmap(HS, trans)\n guard = stateset(constrained_map)\n\n guard_isa_Hrep, guard_isa_H_polytope = get_Hrep_info(guard)\n combine_constraints = 𝒫.options[:combine_invariant_guard] &&\n inv_isa_Hrep && guard_isa_Hrep\n if combine_constraints # combine the constraints of invariant and guard\n T = inv_isa_H_polytope || guard_isa_H_polytope ? HPolytope : HPolyhedron\n # TODO: remove redundant constraints => use intersection(..)\n invariant_guard = T([constraints_list(source_invariant);\n constraints_list(guard)])\n end\n\n # perform jumps\n post_jump = Vector{ReachSet{LazySet{N}}}()\n sizehint!(post_jump, length(tube⋂inv))\n for reach_set in tube⋂inv\n # check intersection with guard\n if combine_constraints\n R⋂G = Intersection(set(reach_set).X, invariant_guard)\n else\n R⋂G = Intersection(set(reach_set), guard)\n end\n if isempty(R⋂G)\n continue\n end\n if !𝒫.options[:lazy_R⋂G]\n R⋂G = overapproximate(R⋂G, oa)\n end\n\n # apply assignment\n A⌜R⋂G⌟ = apply_assignment(𝒫, constrained_map, R⋂G)\n if 𝒫.options[:lazy_A⌜R⋂G⌟] == \"always\" ||\n (𝒫.options[:lazy_A⌜R⋂G⌟] == \"invertible\" &&\n !isinvertible(constrained_map))\n A⌜R⋂G⌟ = overapproximate(A⌜R⋂G⌟, oa)\n end\n\n # intersect with target invariant\n A⌜R⋂G⌟⋂I = Intersection(target_invariant, A⌜R⋂G⌟)\n if isempty(A⌜R⋂G⌟⋂I)\n continue\n end\n if !𝒫.options[:lazy_A⌜R⋂G⌟⋂I]\n A⌜R⋂G⌟⋂I = overapproximate(A⌜R⋂G⌟⋂I, oa)\n end\n\n # store result\n push!(post_jump, ReachSet{LazySet{N}}(A⌜R⋂G⌟⋂I,\n time_start(reach_set),\n time_end(reach_set)))\n end\n\n postprocess(𝒫, HS, post_jump, options, waiting_list, passed_list,\n target_loc_id, jumps)\n end\nend\n\nfunction get_Hrep_info(set::LazySet)\n return (false, false)\nend\n\nfunction get_Hrep_info(set::AbstractPolytope)\n return (true, true)\nend\n\nfunction get_Hrep_info(set::AbstractPolyhedron)\n return (true, false)\nend\n\n# --- line-search policies ---\n\n# usually do not use line search\nfunction use_precise_ρ(𝒫::LazyDiscretePost,\n cap::Intersection{N})::Bool where N<:Real\n return false\nend\n\n# use line search for the outermost level, which is a LinearMap\nfunction use_precise_ρ(𝒫::LazyDiscretePost,\n cap::Intersection{N, <:LinearMap{N}}\n )::Bool where N<:Real\n return true\nend\n", "meta": {"hexsha": "ecb4d8e8028238b28e66bee05aca504ea65c87be", "size": 7408, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ReachSets/DiscretePost/LazyDiscretePost.jl", "max_stars_repo_name": "JuliaReach/Reachability.jl", "max_stars_repo_head_hexsha": "a8322cf6eee050d07ca21f0f6df2512d2f9cd391", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2017-10-24T06:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:20:51.000Z", "max_issues_repo_path": "src/ReachSets/DiscretePost/LazyDiscretePost.jl", "max_issues_repo_name": "mforets/ReachabilityAffineSystems.jl", "max_issues_repo_head_hexsha": "a8322cf6eee050d07ca21f0f6df2512d2f9cd391", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 530, "max_issues_repo_issues_event_min_datetime": "2017-10-26T14:38:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-16T12:30:35.000Z", "max_forks_repo_path": "src/ReachSets/DiscretePost/LazyDiscretePost.jl", "max_forks_repo_name": "mforets/ReachabilityAffineSystems.jl", "max_forks_repo_head_hexsha": "a8322cf6eee050d07ca21f0f6df2512d2f9cd391", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-08-01T00:46:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T03:15:35.000Z", "avg_line_length": 34.779342723, "max_line_length": 110, "alphanum_fraction": 0.6143358531, "num_tokens": 2103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24201280108417803}} {"text": "struct DeviceEnergyBalanceConstraintSpec\n constraint_name::Symbol\n energy_variable::Symbol\n initial_condition::Type{<:InitialConditionType}\n pin_variable_names::Vector{Symbol}\n pout_variable_names::Vector{Symbol}\n parameter_name::Union{Nothing, String}\n forecast_label::Union{Nothing, String}\n multiplier_func::Union{Nothing, Function}\n constraint_func::Function\nend\n\nfunction DeviceEnergyBalanceConstraintSpec(;\n constraint_name::Symbol,\n energy_variable::Symbol,\n initial_condition::Type{<:InitialConditionType},\n constraint_func::Function,\n pin_variable_names::Vector{Symbol} = Vector{Symbol}(),\n pout_variable_names::Vector{Symbol} = Vector{Symbol}(),\n parameter_name::Union{Nothing, String} = nothing,\n forecast_label::Union{Nothing, String} = nothing,\n multiplier_func::Union{Nothing, Function} = nothing,\n)\n return DeviceEnergyBalanceConstraintSpec(\n constraint_name,\n energy_variable,\n initial_condition,\n pin_variable_names,\n pout_variable_names,\n parameter_name,\n forecast_label,\n multiplier_func,\n constraint_func,\n )\nend\n\nfunction add_constraints!(\n optimization_container::OptimizationContainer,\n ::Type{T},\n ::Type{U},\n devices::IS.FlattenIteratorWrapper{V},\n model::DeviceModel{V, W},\n ::Type{X},\n feedforward::Union{Nothing, AbstractAffectFeedForward},\n) where {\n T <: EnergyBalanceConstraint,\n U <: VariableType,\n V <: PSY.Device,\n W <: AbstractDeviceFormulation,\n X <: PM.AbstractPowerModel,\n}\n use_parameters = model_has_parameters(optimization_container)\n use_forecasts = model_uses_forecasts(optimization_container)\n # @assert !(use_parameters && !use_forecasts)\n spec = DeviceEnergyBalanceConstraintSpec(\n T,\n U,\n V,\n W,\n X,\n feedforward,\n use_parameters,\n use_forecasts,\n )\n energy_balance_constraints!(optimization_container, devices, model, feedforward, spec)\nend\n\nfunction energy_balance_constraints!(\n optimization_container::OptimizationContainer,\n devices::IS.FlattenIteratorWrapper{T},\n model::DeviceModel{T, U},\n feedforward::Union{Nothing, AbstractAffectFeedForward},\n spec::DeviceEnergyBalanceConstraintSpec,\n) where {T <: PSY.Device, U <: AbstractDeviceFormulation}\n initial_conditions =\n get_initial_conditions(optimization_container, spec.initial_condition, T)\n _apply_energy_balance_constraint_spec!(\n optimization_container,\n spec,\n devices,\n initial_conditions,\n model,\n feedforward,\n )\nend\n\nstruct DeviceEnergyBalanceConstraintSpecInternal\n constraint_infos::Vector{<:EnergyBalanceConstraintInfo}\n constraint_name::Symbol\n energy_variable::Symbol\n pin_variable_names::Vector{Symbol}\n pout_variable_names::Vector{Symbol}\n param_reference::Union{Nothing, UpdateRef}\nend\n\nfunction _apply_energy_balance_constraint_spec!(\n optimization_container,\n spec,\n devices::IS.FlattenIteratorWrapper{T},\n initial_conditions::Vector{InitialCondition},\n model,\n ff_affected_variables,\n) where {T <: PSY.Device}\n constraint_infos = Vector{EnergyBalanceConstraintInfo}(undef, length(devices))\n for (ix, ic) in enumerate(initial_conditions)\n device = ic.device\n dev_name = PSY.get_name(device)\n if !isnothing(spec.forecast_label)\n ts_vector = get_time_series(optimization_container, device, spec.forecast_label)\n multiplier = spec.multiplier_func(device)\n constraint_info = EnergyBalanceConstraintInfo(\n dev_name,\n get_efficiency(device, spec.initial_condition),\n ic,\n multiplier,\n ts_vector,\n )\n else\n constraint_info = EnergyBalanceConstraintInfo(;\n component_name = dev_name,\n efficiency_data = get_efficiency(device, spec.initial_condition),\n ic_energy = ic,\n )\n end\n constraint_infos[ix] = constraint_info\n end\n\n spec.constraint_func(\n optimization_container,\n DeviceEnergyBalanceConstraintSpecInternal(\n constraint_infos,\n spec.constraint_name,\n spec.energy_variable,\n spec.pin_variable_names,\n spec.pout_variable_names,\n spec.parameter_name === nothing ? nothing :\n UpdateRef{T}(spec.parameter_name, spec.forecast_label),\n ),\n )\n return\nend\n\n@doc raw\"\"\"\nConstructs multi-timestep constraint from initial condition, efficiency data, and variable tuple\n# Constraints\nIf t = 1:\n``` varenergy[name, 1] == initial_conditions[ix].value + varin[name, 1]*eff_in*fraction_of_hour - varout[name, 1]*fraction_of_hour/eff_out ```\nIf t > 1:\n``` varenergy[name, t] == varenergy[name, t-1] + varin[name, t]*eff_in*fraction_of_hour - varout[name, t]*fraction_of_hour/eff_out ```\n# LaTeX\n`` x^{energy}_1 == x^{energy}_{init} + frhr \\eta^{in} x^{in}_1 - \\frac{frhr}{\\eta^{out}} x^{out}_1, \\text{ for } t = 1 ``\n`` x^{energy}_t == x^{energy}_{t-1} + frhr \\eta^{in} x^{in}_t - \\frac{frhr}{\\eta^{out}} x^{out}_t, \\forall t \\geq 2 ``\n# Arguments\n* optimization_container::OptimizationContainer : the optimization_container model built in PowerSimulations\n* inputs::Vector{DeviceEnergyBalanceConstraintSpecInternal} : stores constraint information \n\"\"\"\nfunction energy_balance!(\n optimization_container::OptimizationContainer,\n inputs::DeviceEnergyBalanceConstraintSpecInternal,\n)\n time_steps = model_time_steps(optimization_container)\n resolution = model_resolution(optimization_container)\n fraction_of_hour = Dates.value(Dates.Minute(resolution)) / MINUTES_IN_HOUR\n names = [get_component_name(x) for x in inputs.constraint_infos]\n\n varenergy = get_variable(optimization_container, inputs.energy_variable)\n varin = [get_variable(optimization_container, var) for var in inputs.pin_variable_names]\n varout =\n [get_variable(optimization_container, var) for var in inputs.pout_variable_names]\n\n constraint = add_cons_container!(\n optimization_container,\n inputs.constraint_name,\n names,\n time_steps,\n )\n\n for info in inputs.constraint_infos\n eff_in = info.efficiency_data.in\n eff_out = info.efficiency_data.out\n name = get_component_name(info)\n # Create the PGAE outside of the constraint definition\n !isnothing(info.timeseries) ? ts_value = info.timeseries[1] * info.multiplier :\n ts_value = 0.0\n expr = JuMP.AffExpr(0.0)\n for var in varin\n JuMP.add_to_expression!(expr, var[name, 1], eff_in * fraction_of_hour)\n end\n for var in varout\n JuMP.add_to_expression!(expr, var[name, 1], -1.0 * fraction_of_hour / eff_out)\n end\n constraint[name, 1] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, 1] == info.ic_energy.value + expr + ts_value\n )\n end\n\n for t in time_steps[2:end], info in inputs.constraint_infos\n eff_in = info.efficiency_data.in\n eff_out = info.efficiency_data.out\n name = get_component_name(info)\n !isnothing(info.timeseries) ? ts_value = info.timeseries[t] * info.multiplier :\n ts_value = 0.0\n expr = JuMP.AffExpr(0.0, varenergy[name, t - 1] => 1.0)\n for var in varin\n JuMP.add_to_expression!(expr, var[name, t], eff_in * fraction_of_hour)\n end\n for var in varout\n JuMP.add_to_expression!(expr, var[name, t], -1.0 * fraction_of_hour / eff_out)\n end\n constraint[name, t] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, t] == expr + ts_value\n )\n end\n\n return\nend\n\n@doc raw\"\"\"\nConstructs multi-timestep constraint from initial condition, efficiency data, and variable tuple\n# Constraints\nIf t = 1:\n``` varenergy[name, 1] == initial_conditions[ix].value + varin[name, 1]*eff_in*fraction_of_hour - varout[name, 1]*fraction_of_hour/eff_out ```\nIf t > 1:\n``` varenergy[name, t] == varenergy[name, t-1] + varin[name, t]*eff_in*fraction_of_hour - varout[name, t]*fraction_of_hour/eff_out ```\n# LaTeX\n`` x^{energy}_1 == x^{energy}_{init} + frhr \\eta^{in} x^{in}_1 - \\frac{frhr}{\\eta^{out}} x^{out}_1, \\text{ for } t = 1 ``\n`` x^{energy}_t == x^{energy}_{t-1} + frhr \\eta^{in} x^{in}_t - \\frac{frhr}{\\eta^{out}} x^{out}_t, \\forall t \\geq 2 ``\n# Arguments\n* optimization_container::OptimizationContainer : the optimization_container model built in PowerSimulations\n* inputs::Vector{DeviceEnergyBalanceConstraintSpecInternal} : stores constraint information \n\"\"\"\nfunction energy_balance_param!(\n optimization_container::OptimizationContainer,\n inputs::DeviceEnergyBalanceConstraintSpecInternal,\n)\n time_steps = model_time_steps(optimization_container)\n resolution = model_resolution(optimization_container)\n fraction_of_hour = Dates.value(Dates.Minute(resolution)) / MINUTES_IN_HOUR\n names = [get_component_name(x) for x in inputs.constraint_infos]\n has_parameter_data = !isnothing(inputs.param_reference)\n\n varenergy = get_variable(optimization_container, inputs.energy_variable)\n varin = [get_variable(optimization_container, var) for var in inputs.pin_variable_names]\n varout =\n [get_variable(optimization_container, var) for var in inputs.pout_variable_names]\n\n if has_parameter_data\n container = add_param_container!(\n optimization_container,\n inputs.param_reference,\n names,\n time_steps,\n )\n multiplier = get_multiplier_array(container)\n param = get_parameter_array(container)\n end\n\n constraint = add_cons_container!(\n optimization_container,\n inputs.constraint_name,\n names,\n time_steps,\n )\n\n for info in inputs.constraint_infos\n eff_in = info.efficiency_data.in\n eff_out = info.efficiency_data.out\n name = get_component_name(info)\n # Create the PGAE outside of the constraint definition\n expr = zero(PGAE)\n for var in varin\n JuMP.add_to_expression!(expr, var[name, 1], eff_in * fraction_of_hour)\n end\n for var in varout\n JuMP.add_to_expression!(expr, var[name, 1], -1 * fraction_of_hour / eff_out)\n end\n if has_parameter_data\n multiplier[name, 1] = info.multiplier\n param[name, 1] =\n PJ.add_parameter(optimization_container.JuMPmodel, info.timeseries[1])\n JuMP.add_to_expression!(expr, param[name, 1], multiplier[name, 1])\n end\n constraint[name, 1] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, 1] == info.ic_energy.value + expr\n )\n end\n\n for t in time_steps[2:end], info in inputs.constraint_infos\n eff_in = info.efficiency_data.in\n eff_out = info.efficiency_data.out\n name = get_component_name(info)\n expr = expr = zero(PGAE)\n JuMP.add_to_expression!(expr, varenergy[name, t - 1])\n for var in varin\n JuMP.add_to_expression!(expr, var[name, t], eff_in * fraction_of_hour)\n end\n for var in varout\n JuMP.add_to_expression!(expr, var[name, t], -1 * fraction_of_hour / eff_out)\n end\n if has_parameter_data\n multiplier[name, t] = info.multiplier\n param[name, t] =\n PJ.add_parameter(optimization_container.JuMPmodel, info.timeseries[t])\n JuMP.add_to_expression!(expr, param[name, t], multiplier[name, t])\n end\n constraint[name, t] =\n JuMP.@constraint(optimization_container.JuMPmodel, varenergy[name, t] == expr)\n end\n\n return\nend\n\n########## Old constraint function that will be deleted after storage refactor is complete\n\n@doc raw\"\"\"\nConstructs multi-timestep constraint from initial condition, efficiency data, and variable tuple\n\n# Constraints\n\nIf t = 1:\n\n``` varenergy[name, 1] == initial_conditions[ix].value + varin[name, 1]*eff_in*fraction_of_hour - varout[name, 1]*fraction_of_hour/eff_out ```\n\nIf t > 1:\n\n``` varenergy[name, t] == varenergy[name, t-1] + varin[name, t]*eff_in*fraction_of_hour - varout[name, t]*fraction_of_hour/eff_out ```\n\n# LaTeX\n\n`` x^{energy}_1 == x^{energy}_{init} + frhr \\eta^{in} x^{in}_1 - \\frac{frhr}{\\eta^{out}} x^{out}_1, \\text{ for } t = 1 ``\n\n`` x^{energy}_t == x^{energy}_{t-1} + frhr \\eta^{in} x^{in}_t - \\frac{frhr}{\\eta^{out}} x^{out}_t, \\forall t \\geq 2 ``\n\n# Arguments\n* optimization_container::OptimizationContainer : the optimization_container model built in PowerSimulations\n* initial_conditions::Vector{InitialCondition} : for time zero 'varenergy'\n* efficiency_data::Tuple{Vector{String}, Vector{InOut}} :: charging/discharging efficiencies\n* cons_name::Symbol : name of the constraint\n* var_names::Tuple{Symbol, Symbol, Symbol} : the names of the variables\n- : var_names[1] : varin\n- : var_names[2] : varout\n- : var_names[3] : varenergy\n\n\"\"\"\nfunction energy_balance(\n optimization_container::OptimizationContainer,\n initial_conditions::Vector{InitialCondition},\n efficiency_data::Tuple{Vector{String}, Vector{InOut}},\n cons_name::Symbol,\n var_names::Tuple{Symbol, Symbol, Symbol},\n)\n parameters = model_has_parameters(optimization_container)\n time_steps = model_time_steps(optimization_container)\n resolution = model_resolution(optimization_container)\n fraction_of_hour = Dates.value(Dates.Minute(resolution)) / MINUTES_IN_HOUR\n name_index = efficiency_data[1]\n\n varin = get_variable(optimization_container, var_names[1])\n varout = get_variable(optimization_container, var_names[2])\n varenergy = get_variable(optimization_container, var_names[3])\n\n constraint =\n add_cons_container!(optimization_container, cons_name, name_index, time_steps)\n\n for (ix, name) in enumerate(name_index)\n eff_in = efficiency_data[2][ix].in\n eff_out = efficiency_data[2][ix].out\n # Create the PGAE outside of the constraint definition\n balance =\n initial_conditions[ix].value + varin[name, 1] * eff_in * fraction_of_hour -\n (varout[name, 1]) * fraction_of_hour / eff_out\n constraint[name, 1] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, 1] == balance\n )\n end\n\n for t in time_steps[2:end], (ix, name) in enumerate(name_index)\n eff_in = efficiency_data[2][ix].in\n eff_out = efficiency_data[2][ix].out\n\n constraint[name, t] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, t] ==\n varenergy[name, t - 1] + varin[name, t] * eff_in * fraction_of_hour -\n (varout[name, t]) * fraction_of_hour / eff_out\n )\n end\n\n return\nend\n\n@doc raw\"\"\"\nConstructs multi-timestep constraint from initial condition, efficiency data, and variable tuple\n# Constraints\nIf t = 1:\n`` varenergy[name, 1] == initial_conditions[ix].value + (paraminflow[name, t] - varspill[name, 1] - varout[name, 1])*fraction_of_hour ``\nIf t > 1:\n`` varenergy[name, t] == varenergy[name, t-1] + (paraminflow[name, t] - varspill[name, t] - varout[name, t])*fraction_of_hour ``\n`` varenergy[name, end] >= paramenergytarget[name, end]\n# LaTeX\n`` x^{energy}_1 == x^{energy}_{init} + frhr (x^{in}_1 - x^{spillage}_1 - x^{out}_1), \\text{ for } t = 1 ``\n`` x^{energy}_t == x^{energy}_{t-1} + frhr (x^{in}_t - x^{spillage}_t - x^{out}_t), \\forall t \\geq 2 ``\n`` x^{energy}_t >= x^{energy}_{target} \\text{ for } t = end ``\n# Arguments\n* optimization_container::OptimizationContainer : the optimization_container model built in PowerSimulations\n* initial_conditions::Vector{InitialCondition} : for time zero 'varenergy'\n* time_series_data::Tuple{Vector{DeviceTimeSeriesConstraintInfo}, Vector{DeviceTimeSeriesConstraintInfo}} : forecast information\n- : time_series_data[1] : Inflow energy forecast information\n- : time_series_data[2] : Target reservoir storage forecast information\n* cons_names::Tuple{Symbol, Symbol} : name of the constraints\n- : cons_names[1] : energy balance constraint name\n- : cons_names[2] : energy target constraint name\n* var_names::Tuple{Symbol, Symbol, Symbol} : the names of the variables\n- : var_names[1] : varspill\n- : var_names[2] : varout\n- : var_names[3] : varenergy\n* param_reference::UpdateRef : UpdateRef to access the inflow parameter\n\"\"\"\nfunction energy_balance_hydro_param!(\n optimization_container::OptimizationContainer,\n initial_conditions::Vector{InitialCondition},\n time_series_data::Tuple{\n Vector{DeviceTimeSeriesConstraintInfo},\n Vector{DeviceTimeSeriesConstraintInfo},\n },\n cons_names::Tuple{Symbol, Symbol},\n var_names::Tuple{Symbol, Symbol, Symbol},\n param_references::Tuple{UpdateRef, UpdateRef},\n)\n time_steps = model_time_steps(optimization_container)\n resolution = model_resolution(optimization_container)\n fraction_of_hour = Dates.value(Dates.Second(resolution)) / SECONDS_IN_HOUR\n\n inflow_data = time_series_data[1]\n target_data = time_series_data[2]\n\n name_index = [get_component_name(d) for d in inflow_data]\n\n varspill = get_variable(optimization_container, var_names[1])\n varout = get_variable(optimization_container, var_names[2])\n varenergy = get_variable(optimization_container, var_names[3])\n\n balance_cons_name = cons_names[1]\n target_cons_name = cons_names[2]\n balance_param_reference = param_references[1]\n target_param_reference = param_references[2]\n\n container_inflow = add_param_container!(\n optimization_container,\n balance_param_reference,\n name_index,\n time_steps,\n )\n param_inflow = get_parameter_array(container_inflow)\n multiplier_inflow = get_multiplier_array(container_inflow)\n container_target = add_param_container!(\n optimization_container,\n target_param_reference,\n name_index,\n time_steps,\n )\n param_target = get_parameter_array(container_target)\n multiplier_target = get_multiplier_array(container_target)\n\n balance_constraint = add_cons_container!(\n optimization_container,\n balance_cons_name,\n name_index,\n time_steps,\n )\n target_constraint =\n add_cons_container!(optimization_container, target_cons_name, name_index, 1)\n\n for (ix, d) in enumerate(inflow_data)\n name = get_component_name(d)\n multiplier_inflow[name, 1] = d.multiplier\n param_inflow[name, 1] =\n add_parameter(optimization_container.JuMPmodel, d.timeseries[1])\n exp =\n initial_conditions[ix].value +\n (\n multiplier_inflow[name, 1] * param_inflow[name, 1] - varspill[name, 1] -\n varout[name, 1]\n ) * fraction_of_hour\n balance_constraint[name, 1] =\n JuMP.@constraint(optimization_container.JuMPmodel, varenergy[name, 1] == exp)\n\n for t in time_steps[2:end]\n multiplier_inflow[name, t] = d.multiplier\n param_inflow[name, t] =\n add_parameter(optimization_container.JuMPmodel, d.timeseries[t])\n exp =\n varenergy[name, t - 1] +\n (\n multiplier_inflow[name, t] * param_inflow[name, t] - varspill[name, t] -\n varout[name, t]\n ) * fraction_of_hour\n balance_constraint[name, t] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, t] == exp\n )\n end\n end\n\n for (ix, d) in enumerate(target_data)\n name = get_component_name(d)\n for t in time_steps\n param_target[name, t] =\n add_parameter(optimization_container.JuMPmodel, d.timeseries[t])\n multiplier_target[name, t] = d.multiplier\n end\n target_constraint[name, 1] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, time_steps[end]] >=\n d.multiplier * param_target[name, time_steps[end]]\n )\n end\n\n return\nend\n\n@doc raw\"\"\"\nConstructs multi-timestep constraint from initial condition, efficiency data, and variable tuple\n# Constraints\nIf t = 1:\n`` varenergy[name, 1] == initial_conditions[ix].value + (paraminflow[name, t] - varspill[name, 1] - varout[name, 1])*fraction_of_hour ``\nIf t > 1:\n`` varenergy[name, t] == varenergy[name, t-1] + (paraminflow[name, t] - varspill[name, t] - varout[name, t])*fraction_of_hour ``\n`` varenergy[name, end] >= paramenergytarget[name, end]\n# LaTeX\n`` x^{energy}_1 == x^{energy}_{init} + frhr (x^{in}_1 - x^{spillage}_1 - x^{out}_1), \\text{ for } t = 1 ``\n`` x^{energy}_t == x^{energy}_{t-1} + frhr (x^{in}_t - x^{spillage}_t - x^{out}_t), \\forall t \\geq 2 ``\n`` x^{energy}_t >= x^{energy}_{target} \\text{ for } t = end ``\n# Arguments\n* optimization_container::OptimizationContainer : the optimization_container model built in PowerSimulations\n* initial_conditions::Vector{InitialCondition} : for time zero 'varenergy'\n* time_series_data::Tuple{Vector{DeviceTimeSeriesConstraintInfo}, Vector{DeviceTimeSeriesConstraintInfo}} : forecast information\n- : time_series_data[1] : Inflow energy forecast information\n- : time_series_data[2] : Target reservoir storage forecast information\n* cons_names::Tuple{Symbol, Symbol} : name of the constraints\n- : cons_names[1] : energy balance constraint name\n- : cons_names[2] : energy target constraint name\n* var_names::Tuple{Symbol, Symbol, Symbol} : the names of the variables\n- : var_names[1] : varspill\n- : var_names[2] : varout\n- : var_names[3] : varenergy\n\"\"\"\nfunction energy_balance_hydro!(\n optimization_container::OptimizationContainer,\n initial_conditions::Vector{InitialCondition},\n time_series_data::Tuple{\n Vector{DeviceTimeSeriesConstraintInfo},\n Vector{DeviceTimeSeriesConstraintInfo},\n },\n cons_names::Tuple{Symbol, Symbol},\n var_names::Tuple{Symbol, Symbol, Symbol},\n)\n time_steps = model_time_steps(optimization_container)\n resolution = model_resolution(optimization_container)\n fraction_of_hour = Dates.value(Dates.Minute(resolution)) / MINUTES_IN_HOUR\n\n inflow_data = time_series_data[1]\n target_data = time_series_data[2]\n\n name_index = [get_component_name(d) for d in inflow_data]\n\n varspill = get_variable(optimization_container, var_names[1])\n varout = get_variable(optimization_container, var_names[2])\n varenergy = get_variable(optimization_container, var_names[3])\n\n balance_cons_name = cons_names[1]\n target_cons_name = cons_names[2]\n\n balance_constraint = add_cons_container!(\n optimization_container,\n balance_cons_name,\n name_index,\n time_steps,\n )\n target_constraint =\n add_cons_container!(optimization_container, target_cons_name, name_index, 1)\n\n for (ix, d) in enumerate(inflow_data)\n name = get_component_name(d)\n balance_constraint[name, 1] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, 1] ==\n initial_conditions[ix].value +\n (d.multiplier * d.timeseries[1] - varspill[name, 1] - varout[name, 1]) *\n fraction_of_hour\n )\n\n for t in time_steps[2:end]\n balance_constraint[name, t] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, t] ==\n varenergy[name, t - 1] +\n (d.multiplier * d.timeseries[t] - varspill[name, t] - varout[name, t]) *\n fraction_of_hour\n )\n end\n end\n\n for (ix, d) in enumerate(target_data)\n name = get_component_name(d)\n target_constraint[name, 1] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy[name, time_steps[end]] >=\n d.multiplier * d.timeseries[time_steps[end]]\n )\n end\n\n return\nend\n\n@doc raw\"\"\"\nConstructs multi-timestep constraint from initial condition, efficiency data, and variable tuple for pumped hydro\n# Constraints\nIf t = 1:\n``` varenergy_up[name, 1] == initial_conditions[ix].value + (param_inflow[name, t] + varin[name, 1] - varspill[name, 1] - varout[name, 1])*fraction_of_hour ```\nIf t > 1:\n``` varenergy_up[name, t] == varenergy_up[name, t-1] + (param_inflow[name, t] + varin[name, t] - varspill[name, t] - varout[name, t])*fraction_of_hour ```\n# LaTeX\n`` x^{energy}_1 == x^{energy}_{init} + frhr (x^{in}_1 + x^{in}_1 - x^{spillage}_1 - x^{out}_1), \\text{ for } t = 1 ``\n`` x^{energy}_t == x^{energy}_{t-1} + frhr (x^{in}_t + x^{in}_t - x^{spillage}_t - x^{out}_t), \\forall t \\geq 2 ``\n# Arguments\n* optimization_container::OptimizationContainer : the optimization_container model built in PowerSimulations\n* initial_conditions::Vector{InitialCondition} : for time zero 'varenergy_up'\n* inflow_data::Vector{DeviceTimeSeriesConstraintInfo} :: Inflow energy forecast information\n* cons_name::Symbol : name of the constraint\n* var_names::Tuple{Symbol, Symbol, Symbol, Symbol} : the names of the variables\n- : var_names[1] : varspill\n- : var_names[2] : varout\n- : var_names[3] : varenergy_up\n- : var_names[4] : varin\n* param_reference::UpdateRef : UpdateRef to access the inflow parameter\n\"\"\"\nfunction energy_balance_hydro_param!(\n optimization_container::OptimizationContainer,\n initial_conditions::Vector{InitialCondition},\n ts_data::Tuple{\n Vector{DeviceTimeSeriesConstraintInfo},\n Vector{DeviceTimeSeriesConstraintInfo},\n },\n cons_name::Tuple{Symbol, Symbol},\n var_names::Tuple{Symbol, Symbol, Symbol, Symbol, Symbol},\n param_reference::Tuple{UpdateRef, UpdateRef},\n)\n time_steps = model_time_steps(optimization_container)\n resolution = model_resolution(optimization_container)\n fraction_of_hour = Dates.value(Dates.Second(resolution)) / SECONDS_IN_HOUR\n inflow_data = ts_data[1]\n outflow_data = ts_data[2]\n inflow_name_index = [get_component_name(d) for d in inflow_data]\n outflow_name_index = [get_component_name(d) for d in outflow_data]\n\n varspill = get_variable(optimization_container, var_names[1])\n varout = get_variable(optimization_container, var_names[2])\n varenergy_up = get_variable(optimization_container, var_names[3])\n varin = get_variable(optimization_container, var_names[4])\n varenergy_down = get_variable(optimization_container, var_names[5])\n\n container_inflow = add_param_container!(\n optimization_container,\n param_reference[1],\n inflow_name_index,\n time_steps,\n )\n param_inflow = get_parameter_array(container_inflow)\n multiplier_inflow = get_multiplier_array(container_inflow)\n container_outflow = add_param_container!(\n optimization_container,\n param_reference[2],\n outflow_name_index,\n time_steps,\n )\n param_outflow = get_parameter_array(container_outflow)\n multiplier_outflow = get_multiplier_array(container_outflow)\n constraint_up = add_cons_container!(\n optimization_container,\n cons_name[1],\n inflow_name_index,\n time_steps,\n )\n constraint_down = add_cons_container!(\n optimization_container,\n cons_name[2],\n outflow_name_index,\n time_steps,\n )\n\n for (ix, d) in enumerate(inflow_data)\n name = get_component_name(d)\n pump_eff = 1.0 # TODO: get pump efficiency PSY.get_pump_efficiency(d)\n multiplier_inflow[name, 1] = d.multiplier\n param_inflow[name, 1] =\n add_parameter(optimization_container.JuMPmodel, d.timeseries[1])\n exp =\n initial_conditions[ix].value +\n (\n multiplier_inflow[name, 1] * param_inflow[name, 1] +\n varin[name, 1] * pump_eff - varspill[name, 1] - varout[name, 1]\n ) * fraction_of_hour\n constraint_up[name, 1] =\n JuMP.@constraint(optimization_container.JuMPmodel, varenergy_up[name, 1] == exp)\n\n for t in time_steps[2:end]\n multiplier_inflow[name, t] = d.multiplier\n param_inflow[name, t] =\n add_parameter(optimization_container.JuMPmodel, d.timeseries[t])\n exp =\n varenergy_up[name, t - 1] +\n (\n multiplier_inflow[name, t] * param_inflow[name, t] +\n varin[name, t] * pump_eff - varspill[name, t] - varout[name, t]\n ) * fraction_of_hour\n constraint_up[name, t] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy_up[name, t] == exp\n )\n end\n end\n\n for (ix, d) in enumerate(outflow_data)\n name = get_component_name(d)\n pump_eff = 1.0 # TODO: get pump efficiency PSY.get_pump_efficiency(d)\n multiplier_outflow[name, 1] = d.multiplier\n param_outflow[name, 1] =\n add_parameter(optimization_container.JuMPmodel, d.timeseries[1])\n exp =\n initial_conditions[ix].value +\n (\n varspill[name, 1] + varout[name, 1] -\n multiplier_outflow[name, 1] * param_outflow[name, 1] -\n varin[name, 1] * pump_eff\n ) * fraction_of_hour\n constraint_down[name, 1] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy_down[name, 1] == exp\n )\n\n for t in time_steps[2:end]\n multiplier_outflow[name, t] = d.multiplier\n param_outflow[name, t] =\n add_parameter(optimization_container.JuMPmodel, d.timeseries[t])\n exp =\n varenergy_down[name, t - 1] +\n (\n varspill[name, t] + varout[name, t] -\n multiplier_outflow[name, t] * param_outflow[name, t] -\n varin[name, t] * pump_eff\n ) * fraction_of_hour\n constraint_down[name, t] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy_down[name, t] == exp\n )\n end\n end\n\n return\nend\n\n@doc raw\"\"\"\nConstructs multi-timestep constraint from initial condition, efficiency data, and variable tuple for pumped hydro\n# Constraints\nIf t = 1:\n``` varenergy[name, 1] == initial_conditions[ix].value + (paraminflow[name, t] + varin[name, 1] - varspill[name, 1] - varout[name, 1])*fraction_of_hour ```\nIf t > 1:\n``` varenergy[name, t] == varenergy[name, t-1] + (paraminflow[name, t] + varin[name, t] - varspill[name, t] - varout[name, t])*fraction_of_hour ```\n# LaTeX\n`` x^{energy}_1 == x^{energy}_{init} + frhr (x^{in}_1 + x^{in}_1 - x^{spillage}_1 - x^{out}_1), \\text{ for } t = 1 ``\n`` x^{energy}_t == x^{energy}_{t-1} + frhr (x^{in}_t + x^{in}_t - x^{spillage}_t - x^{out}_t), \\forall t \\geq 2 ``\n# Arguments\n* optimization_container::OptimizationContainer : the optimization_container model built in PowerSimulations\n* initial_conditions::Vector{InitialCondition} : for time zero 'varenergy'\n* inflow_data::TVector{DeviceTimeSeriesConstraintInfo} :: Inflow energy forecast information\n* cons_name::Symbol : name of the constraint\n* var_names::Tuple{Symbol, Symbol, Symbol, Symbol} : the names of the variables\n- : var_names[1] : varspill\n- : var_names[2] : varout\n- : var_names[3] : varenergy\n- : var_names[4] : varin\n\"\"\"\nfunction energy_balance_hydro!(\n optimization_container::OptimizationContainer,\n initial_conditions::Vector{InitialCondition},\n ts_data::Tuple{\n Vector{DeviceTimeSeriesConstraintInfo},\n Vector{DeviceTimeSeriesConstraintInfo},\n },\n cons_name::Tuple{Symbol, Symbol},\n var_names::Tuple{Symbol, Symbol, Symbol, Symbol, Symbol},\n)\n time_steps = model_time_steps(optimization_container)\n resolution = model_resolution(optimization_container)\n fraction_of_hour = Dates.value(Dates.Minute(resolution)) / MINUTES_IN_HOUR\n inflow_data = ts_data[1]\n outflow_data = ts_data[2]\n inflow_name_index = [get_component_name(d) for d in inflow_data]\n outflow_name_index = [get_component_name(d) for d in outflow_data]\n\n varspill = get_variable(optimization_container, var_names[1])\n varout = get_variable(optimization_container, var_names[2])\n varenergy_up = get_variable(optimization_container, var_names[3])\n varin = get_variable(optimization_container, var_names[4])\n varenergy_down = get_variable(optimization_container, var_names[5])\n\n constraint_up = add_cons_container!(\n optimization_container,\n cons_name[1],\n inflow_name_index,\n time_steps,\n )\n constraint_down = add_cons_container!(\n optimization_container,\n cons_name[2],\n outflow_name_index,\n time_steps,\n )\n\n for (ix, d) in enumerate(inflow_data)\n name = get_component_name(d)\n pump_eff = 1.0 # TODO: get pump efficiency PSY.get_pump_efficiency(d)\n constraint_up[name, 1] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy_up[name, 1] ==\n initial_conditions[ix].value +\n (\n d.multiplier * d.timeseries[1] + varin[name, 1] * pump_eff -\n varspill[name, 1] - varout[name, 1]\n ) * fraction_of_hour\n )\n\n for t in time_steps[2:end]\n constraint_up[name, t] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy_up[name, t] ==\n varenergy_up[name, t - 1] +\n (\n d.multiplier * d.timeseries[t] + varin[name, t] * pump_eff -\n varspill[name, t] - varout[name, t]\n ) * fraction_of_hour\n )\n end\n end\n\n for (ix, d) in enumerate(outflow_data)\n name = get_component_name(d)\n pump_eff = 1.0 # TODO: get pump efficiency PSY.get_pump_efficiency(d)\n constraint_down[name, 1] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy_down[name, 1] ==\n initial_conditions[ix].value +\n (\n varspill[name, 1] + varout[name, 1] - d.multiplier * d.timeseries[1] -\n varin[name, 1] * pump_eff\n ) * fraction_of_hour\n )\n\n for t in time_steps[2:end]\n constraint_down[name, t] = JuMP.@constraint(\n optimization_container.JuMPmodel,\n varenergy_down[name, t] ==\n varenergy_down[name, t - 1] +\n (\n varspill[name, t] + varout[name, t] - d.multiplier * d.timeseries[t] - varin[name, t] * pump_eff\n ) * fraction_of_hour\n )\n end\n end\n return\nend\n", "meta": {"hexsha": "cee5e24e310dc6820e925680a1ce0df1cf624647", "size": 34793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/devices_models/devices/common/energy_balance_constraint.jl", "max_stars_repo_name": "sambuddhac/PowerSimulations.jl", "max_stars_repo_head_hexsha": "5e485fab40dcd16d1cb4ed497b07373171ee0aa7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/devices_models/devices/common/energy_balance_constraint.jl", "max_issues_repo_name": "sambuddhac/PowerSimulations.jl", "max_issues_repo_head_hexsha": "5e485fab40dcd16d1cb4ed497b07373171ee0aa7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/devices_models/devices/common/energy_balance_constraint.jl", "max_forks_repo_name": "sambuddhac/PowerSimulations.jl", "max_forks_repo_head_hexsha": "5e485fab40dcd16d1cb4ed497b07373171ee0aa7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6727480046, "max_line_length": 159, "alphanum_fraction": 0.6645014802, "num_tokens": 8689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24187998375596861}} {"text": "# *********************************************************************************\n# REopt, Copyright (c) 2019-2020, Alliance for Sustainable Energy, LLC.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# Redistributions of source code must retain the above copyright notice, this list\n# of conditions and the following disclaimer.\n#\n# Redistributions in binary form must reproduce the above copyright notice, this\n# list of conditions and the following disclaimer in the documentation and/or other\n# materials provided with the distribution.\n#\n# Neither the name of the copyright holder nor the names of its contributors may be\n# used to endorse or promote products derived from this software without specific\n# prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n# OF THE POSSIBILITY OF SUCH DAMAGE.\n# *********************************************************************************\n\"\"\"\n Metrics\n\nConvenience mutable struct for passing data between proforma methods\n\"\"\"\nmutable struct Metrics\n federal_itc::Float64\n om_series::Array{Float64, 1}\n om_series_bau::Array{Float64, 1}\n total_pbi::Array{Float64, 1}\n total_pbi_bau::Array{Float64, 1}\n total_depreciation::Array{Float64, 1}\n total_ibi_and_cbi::Float64\nend\n\n\n\"\"\"\n calculate_proforma_metrics(p::REoptInputs, d::Dict)\n\nRecreates the ProForma spreadsheet calculations to get the simple payback period, irr, net present cost (3rd\nparty case), and payment to third party (3rd party case).\n\nreturn Dict(\n \"simple_payback_years\" => 0.0,\n \"internal_rate_of_return\" => 0.0,\n \"net_present_cost\" => 0.0,\n \"annualized_payment_to_third_party\" => 0.0,\n \"offtaker_annual_free_cashflows\" => Float64[],\n \"offtaker_annual_free_cashflows_bau\" => Float64[],\n \"offtaker_discounted_annual_free_cashflows\" => Float64[],\n \"offtaker_discounted_annual_free_cashflows_bau\" => Float64[],\n \"developer_annual_free_cashflows\" => Float64[]\n)\n\"\"\"\nfunction proforma_results(p::REoptInputs, d::Dict)\n r = Dict(\n \"simple_payback_years\" => 0.0,\n \"internal_rate_of_return\" => 0.0,\n \"net_present_cost\" => 0.0,\n \"annualized_payment_to_third_party\" => 0.0,\n \"offtaker_annual_free_cashflows\" => Float64[],\n \"offtaker_annual_free_cashflows_bau\" => Float64[],\n \"offtaker_discounted_annual_free_cashflows\" => Float64[],\n \"offtaker_discounted_annual_free_cashflows_bau\" => Float64[],\n \"developer_annual_free_cashflows\" => Float64[]\n )\n years = p.s.financial.analysis_years\n escalate_elec(val) = [-1 * val * (1 + p.s.financial.elec_cost_escalation_pct)^yr for yr in 1:years]\n escalate_om(val) = [val * (1 + p.s.financial.om_cost_escalation_pct)^yr for yr in 1:years]\n third_party = p.s.financial.third_party_ownership\n \n # Create placeholder variables to store summed totals across all relevant techs\n m = Metrics(0, zeros(years), zeros(years), zeros(years), zeros(years), zeros(years), 0)\n\n # calculate PV o+m costs, incentives, and depreciation\n for pv in p.s.pvs\n update_metrics(m, p, pv, pv.name, d, third_party)\n end\n\n # calculate Wind o+m costs, incentives, and depreciation\n if \"Wind\" in keys(d) && d[\"Wind\"][\"size_kw\"] > 0\n update_metrics(m, p, p.s.wind, \"Wind\", d, third_party)\n end\n\n # calculate Storage o+m costs, incentives, and depreciation\n if \"Storage\" in keys(d) && d[\"Storage\"][\"size_kw\"] > 0\n # TODO handle other types of storage\n storage = p.s.storage.raw_inputs[:elec]\n total_kw = d[\"Storage\"][\"size_kw\"]\n total_kwh = d[\"Storage\"][\"size_kwh\"]\n capital_cost = total_kw * storage.installed_cost_per_kw + total_kwh * storage.installed_cost_per_kwh\n battery_replacement_year = storage.battery_replacement_year\n battery_replacement_cost = -1 * ((total_kw * storage.replace_cost_per_kw) + (\n total_kwh * storage.replace_cost_per_kwh))\n m.om_series += [yr != battery_replacement_year ? 0 : battery_replacement_cost for yr in 1:years]\n\n # storage only has cbi in the API\n cbi = total_kw * storage.total_rebate_per_kw + total_kwh * storage.total_rebate_per_kwh\n m.total_ibi_and_cbi += cbi\n\n # ITC\n federal_itc_basis = capital_cost # bug in v1 subtracted cbi from capital_cost here\n federal_itc_amount = storage.total_itc_pct * federal_itc_basis\n m.federal_itc += federal_itc_amount\n\n # Depreciation\n if storage.macrs_option_years in [5, 7]\n schedule = []\n if storage.macrs_option_years == 5\n schedule = p.s.financial.macrs_five_year\n elseif storage.macrs_option_years == 7\n schedule = p.s.financial.macrs_seven_year\n end\n macrs_bonus_basis = federal_itc_basis * (1 - storage.total_itc_pct * storage.macrs_itc_reduction)\n macrs_basis = macrs_bonus_basis * (1 - storage.macrs_bonus_pct)\n\n depreciation_schedule = zeros(years)\n for (i, r) in enumerate(schedule)\n if i < length(depreciation_schedule)\n depreciation_schedule[i] = macrs_basis * r\n end\n end\n depreciation_schedule[1] += storage.macrs_bonus_pct * macrs_bonus_basis\n m.total_depreciation += depreciation_schedule\n end\n end\n\n # calculate Generator o+m costs, incentives, and depreciation\n if \"Generator\" in keys(d) && d[\"Generator\"][\"size_kw\"] > 0\n # In the two party case the developer does not include the fuel cost in their costs\n # It is assumed that the offtaker will pay for this at a rate that is not marked up\n # to cover developer profits\n fixed_and_var_om = d[\"Generator\"][\"year_one_fixed_om_cost\"] + d[\"Generator\"][\"year_one_variable_om_cost\"]\n fixed_and_var_om_bau = 0.0\n year_one_fuel_cost_bau = 0.0\n if p.s.generator.existing_kw > 0\n fixed_and_var_om_bau = d[\"Generator\"][\"year_one_fixed_om_cost_bau\"] + \n d[\"Generator\"][\"year_one_variable_om_cost_bau\"]\n year_one_fuel_cost_bau = d[\"Generator\"][\"year_one_fuel_cost_bau\"]\n end\n if !third_party\n annual_om = -1 * (fixed_and_var_om + d[\"Generator\"][\"year_one_fuel_cost\"])\n\n annual_om_bau = -1 * (fixed_and_var_om_bau + year_one_fuel_cost_bau)\n else\n annual_om = -1 * fixed_and_var_om\n\n annual_om_bau = -1 * fixed_and_var_om_bau\n end\n\n m.om_series += escalate_om(annual_om)\n m.om_series_bau += escalate_om(annual_om_bau)\n end\n\n # Optimal Case calculations\n electricity_bill_series = escalate_elec(d[\"ElectricTariff\"][\"year_one_bill\"])\n export_credit_series = escalate_elec(d[\"ElectricTariff\"][\"year_one_export_benefit\"])\n\n # In the two party case the electricity and export credits are incurred by the offtaker not the developer\n if third_party\n total_operating_expenses = m.om_series\n tax_pct = p.s.financial.owner_tax_pct\n else\n total_operating_expenses = electricity_bill_series + export_credit_series + m.om_series\n tax_pct = p.s.financial.offtaker_tax_pct\n end\n\n # Apply taxes to operating expenses\n if tax_pct > 0\n deductable_operating_expenses_series = copy(total_operating_expenses)\n else\n deductable_operating_expenses_series = zeros(years)\n end\n\n operating_expenses_after_tax = (total_operating_expenses - deductable_operating_expenses_series) + \n deductable_operating_expenses_series * (1 - tax_pct)\n total_cash_incentives = m.total_pbi * (1 - tax_pct)\n free_cashflow_without_year_zero = m.total_depreciation * tax_pct + total_cash_incentives + operating_expenses_after_tax\n free_cashflow_without_year_zero[1] += m.federal_itc\n free_cashflow = append!([(-1 * d[\"Financial\"][\"initial_capital_costs\"]) + m.total_ibi_and_cbi], free_cashflow_without_year_zero)\n\n # At this point the logic branches based on third-party ownership or not - see comments \n if third_party # get cumulative cashflow for developer\n r[\"developer_annual_free_cashflows\"] = copy(free_cashflow)\n discounted_developer_cashflow = [v / ((1 + p.s.financial.owner_discount_pct)^(yr-1)) for (yr, v) in\n enumerate(r[\"developer_annual_free_cashflows\"])]\n r[\"net_present_cost\"] = sum(discounted_developer_cashflow) * -1\n\n if p.s.financial.owner_discount_pct != 0\n capital_recovery_factor = (p.s.financial.owner_discount_pct * (1 + p.s.financial.owner_discount_pct)^years) / \n ((1 + p.s.financial.owner_discount_pct)^years - 1) / (1 - tax_pct)\n else\n capital_recovery_factor = (1 / years) / (1 - tax_pct)\n end\n\n r[\"annualized_payment_to_third_party\"] = r[\"net_present_cost\"] * capital_recovery_factor\n annual_income_from_host = -1 * sum(discounted_developer_cashflow) * capital_recovery_factor * (1 - tax_pct)\n r[\"developer_annual_free_cashflows\"][2:end] .+= annual_income_from_host\n r[\"internal_rate_of_return\"] = irr(r[\"developer_annual_free_cashflows\"])\n cumulative_cashflow = cumsum(r[\"developer_annual_free_cashflows\"])\n net_free_cashflow = r[\"developer_annual_free_cashflows\"]\n r[\"developer_annual_free_cashflows\"] = round.(r[\"developer_annual_free_cashflows\"], digits=2)\n\n electricity_bill_series = escalate_elec(d[\"ElectricTariff\"][\"year_one_bill\"])\n electricity_bill_series_bau = escalate_elec(d[\"ElectricTariff\"][\"year_one_bill_bau\"])\n\n export_credit_series = escalate_elec(-d[\"ElectricTariff\"][\"lifecycle_export_benefit\"])\n export_credit_series_bau = escalate_elec(-d[\"ElectricTariff\"][\"lifecycle_export_benefit_bau\"])\n\n annual_income_from_host_series = repeat([-1 * r[\"annualized_payment_to_third_party\"]], years)\n\n if \"Generator\" in keys(d) && d[\"Generator\"][\"size_kw\"] > 0\n existing_genertor_fuel_cost_series = escalate_om(-1 * d[\"Generator\"][\"year_one_fuel_cost_bau\"])\n generator_fuel_cost_series = escalate_om(-1 * d[\"Generator\"][\"year_one_fuel_cost\"])\n else\n existing_genertor_fuel_cost_series = zeros(years)\n generator_fuel_cost_series = zeros(years)\n end\n net_energy_costs = -electricity_bill_series_bau - export_credit_series_bau + electricity_bill_series + \n export_credit_series + annual_income_from_host_series - existing_genertor_fuel_cost_series + \n generator_fuel_cost_series\n\n if p.s.financial.owner_tax_pct > 0\n deductable_net_energy_costs = copy(net_energy_costs)\n else\n deductable_net_energy_costs = zeros(years)\n end\n\n r[\"offtaker_annual_free_cashflows\"] = append!([0.0], \n electricity_bill_series + export_credit_series + generator_fuel_cost_series + annual_income_from_host_series\n )\n r[\"offtaker_annual_free_cashflows_bau\"] = append!([0.0], \n electricity_bill_series_bau + export_credit_series_bau + existing_genertor_fuel_cost_series\n )\n\n else # get cumulative cashflow for offtaker\n electricity_bill_series_bau = escalate_elec(d[\"ElectricTariff\"][\"year_one_bill_bau\"])\n export_credit_series_bau = escalate_elec(-d[\"ElectricTariff\"][\"lifecycle_export_benefit_bau\"])\n total_operating_expenses_bau = electricity_bill_series_bau + export_credit_series_bau + m.om_series_bau\n total_cash_incentives_bau = m.total_pbi_bau * (1 - p.s.financial.offtaker_tax_pct)\n\n if p.s.financial.offtaker_tax_pct > 0\n deductable_operating_expenses_series_bau = copy(total_operating_expenses_bau)\n else\n deductable_operating_expenses_series_bau = zeros(years)\n end\n\n operating_expenses_after_tax_bau = total_operating_expenses_bau - deductable_operating_expenses_series_bau + \n deductable_operating_expenses_series_bau * (1 - p.s.financial.offtaker_tax_pct)\n free_cashflow_bau = operating_expenses_after_tax_bau + total_cash_incentives_bau\n free_cashflow_bau = append!([0.0], free_cashflow_bau)\n r[\"offtaker_annual_free_cashflows\"] = round.(free_cashflow, digits=2)\n r[\"offtaker_discounted_annual_free_cashflows\"] = [round(\n v / ((1 + p.s.financial.offtaker_discount_pct)^(yr-1)), \n digits=2) for (yr, v) in enumerate(r[\"offtaker_annual_free_cashflows\"])]\n r[\"offtaker_annual_free_cashflows_bau\"] = round.(free_cashflow_bau, digits=2)\n r[\"offtaker_discounted_annual_free_cashflows_bau\"] = [round(\n v / ((1 + p.s.financial.offtaker_discount_pct)^(yr-1)), \n digits=2) for (yr, v) in enumerate(free_cashflow_bau)]\n # difference optimal and BAU\n net_free_cashflow = free_cashflow - free_cashflow_bau\n r[\"internal_rate_of_return\"] = irr(net_free_cashflow)\n cumulative_cashflow = cumsum(net_free_cashflow)\n end\n\n # At this point we have the cumulative_cashflow for the developer or offtaker so the payback calculation is the same\n if cumulative_cashflow[end] < 0 \n # case where the system does not pay itself back in the analysis period, do not caculate SPP and IRR\n return r\n end\n\n for i in 2:years\n # add years where the cumulative cashflow is negative\n if cumulative_cashflow[i] < 0\n r[\"simple_payback_years\"] += 1\n # fractionally add years where the cumulative cashflow became positive\n elseif cumulative_cashflow[i - 1] < 0 && cumulative_cashflow[i] > 0\n r[\"simple_payback_years\"] += -(cumulative_cashflow[i - 1] / net_free_cashflow[i])\n # skip years where cumulative cashflow is positive and the previous year's is too\n end\n end\n r[\"simple_payback_years\"] = round(r[\"simple_payback_years\"], digits=2)\n\n return r\nend\n\n\n\"\"\"\n update_metrics(m::Metrics, p::REoptInputs, tech::AbstractTech, tech_name::String, results::Dict, third_party::Bool)\n\nUpdate the Metrics struct for the given `tech`\n\"\"\"\nfunction update_metrics(m::Metrics, p::REoptInputs, tech::AbstractTech, tech_name::String, results::Dict, third_party::Bool)\n total_kw = results[tech_name][\"size_kw\"]\n existing_kw = :existing_kw in fieldnames(typeof(tech)) ? tech.existing_kw : 0\n new_kw = total_kw - existing_kw\n capital_cost = new_kw * tech.installed_cost_per_kw\n\n # owner is responsible for both new and existing PV maintenance in optimal case\n if third_party\n annual_om = -1 * new_kw * tech.om_cost_per_kw\n else\n annual_om = -1 * total_kw * tech.om_cost_per_kw\n end\n years = p.s.financial.analysis_years\n escalate_om(val) = [val * (1 + p.s.financial.om_cost_escalation_pct)^yr for yr in 1:years]\n m.om_series += escalate_om(annual_om)\n m.om_series_bau += escalate_om(-1 * existing_kw * tech.om_cost_per_kw)\n\n # incentive calculations, in the spreadsheet utility incentives are applied first\n utility_ibi = minimum([capital_cost * tech.utility_ibi_pct, tech.utility_ibi_max])\n utility_cbi = minimum([new_kw * tech.utility_rebate_per_kw, tech.utility_rebate_max])\n state_ibi = minimum([(capital_cost - utility_ibi - utility_cbi) * tech.state_ibi_pct, tech.state_ibi_max])\n state_cbi = minimum([new_kw * tech.state_rebate_per_kw, tech.state_rebate_max])\n federal_cbi = new_kw * tech.federal_rebate_per_kw\n ibi = utility_ibi + state_ibi\n cbi = utility_cbi + federal_cbi + state_cbi\n m.total_ibi_and_cbi += ibi + cbi\n\n # Production-based incentives\n pbi_series = Float64[]\n pbi_series_bau = Float64[]\n existing_energy_bau = third_party ? get(results[tech_name], \"year_one_energy_produced_kwh_bau\", 0) : 0\n for yr in range(0, stop=years-1)\n if yr < tech.production_incentive_years\n degredation_pct = :degradation_pct in fieldnames(typeof(tech)) ? (1 - tech.degradation_pct)^yr : 1.0\n base_pbi = minimum([\n tech.production_incentive_per_kwh * (results[tech_name][\"year_one_energy_produced_kwh\"] - existing_energy_bau) * degredation_pct, \n tech.production_incentive_max_benefit * degredation_pct\n ])\n base_pbi_bau = minimum([\n tech.production_incentive_per_kwh * get(results[tech_name], \"year_one_energy_produced_kwh_bau\", 0) * degredation_pct, \n tech.production_incentive_max_benefit * degredation_pct \n ])\n push!(pbi_series, base_pbi)\n push!(pbi_series_bau, base_pbi_bau)\n else\n push!(pbi_series, 0.0)\n push!(pbi_series_bau, 0.0)\n end\n end\n m.total_pbi += pbi_series\n m.total_pbi_bau += pbi_series_bau\n\n # Federal ITC \n # NOTE: bug in v1 has the ITC within the `if tech.macrs_option_years in [5 ,7]` block.\n # NOTE: bug in v1 reduces the federal_itc_basis with the federal_cbi, which is incorrect\n federal_itc_basis = capital_cost - state_ibi - utility_ibi - state_cbi - utility_cbi\n federal_itc_amount = tech.federal_itc_pct * federal_itc_basis\n m.federal_itc += federal_itc_amount\n\n # Depreciation\n if tech.macrs_option_years in [5 ,7]\n schedule = []\n if tech.macrs_option_years == 5\n schedule = p.s.financial.macrs_five_year\n elseif tech.macrs_option_years == 7\n schedule = p.s.financial.macrs_seven_year\n end\n\n macrs_bonus_basis = federal_itc_basis - federal_itc_basis * tech.federal_itc_pct * tech.macrs_itc_reduction\n macrs_basis = macrs_bonus_basis * (1 - tech.macrs_bonus_pct)\n\n depreciation_schedule = zeros(years)\n for (i, r) in enumerate(schedule)\n if i < length(depreciation_schedule)\n depreciation_schedule[i] = macrs_basis * r\n end\n end\n depreciation_schedule[1] += (tech.macrs_bonus_pct * macrs_bonus_basis)\n m.total_depreciation += depreciation_schedule\n end\n nothing\nend\n\n\nfunction npv(cashflows::AbstractArray{Float64, 1}, rate::Float64)\n years = collect(0:length(cashflows)-1)\n return sum( cashflows ./ (1+rate).^years)\nend\n\n\nfunction irr(cashflows::AbstractArray{Float64, 1})\n if npv(cashflows, 0.0) < 0\n return 0.0\n end\n f(r) = npv(cashflows, r)\n rate = 0.0\n try\n rate = fzero(f, [0.0, 0.99])\n finally\n return round(rate, digits=2)\n end\nend\n", "meta": {"hexsha": "6fbb76a3c8642217a1ccd8fe2239f7f0836d876b", "size": 19312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/results/proforma.jl", "max_stars_repo_name": "sericson0/REopt.jl", "max_stars_repo_head_hexsha": "413b7390e1b69b7cb2d358dd776e3802f2c1e555", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-07-16T15:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T02:00:50.000Z", "max_issues_repo_path": "src/results/proforma.jl", "max_issues_repo_name": "sericson0/REopt.jl", "max_issues_repo_head_hexsha": "413b7390e1b69b7cb2d358dd776e3802f2c1e555", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-05-17T18:50:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T20:37:48.000Z", "max_forks_repo_path": "src/results/proforma.jl", "max_forks_repo_name": "sericson0/REopt.jl", "max_forks_repo_head_hexsha": "413b7390e1b69b7cb2d358dd776e3802f2c1e555", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-07-21T03:30:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-19T02:38:01.000Z", "avg_line_length": 47.801980198, "max_line_length": 147, "alphanum_fraction": 0.6879142502, "num_tokens": 4883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2418187312932928}} {"text": "export load_obj\n\n# ------------------------- #\n# - Parse OBJ & MTL Files - #\n# ------------------------- #\n\"\"\"\n triangulate_faces(vertices::Vector, texture_coordinates::Vector,\n faces::Vector, material_map::Dict)\n\nTriangulates the `faces` and converts it into valid [`Triangle`](@ref) objects.\n\n!!! warning\n Avoid using this function in itself. It is designed to be used internally\n by the [`load_obj`](@ref) function.\n\"\"\"\nfunction triangulate_faces(vertices::Vector, texture_coordinates::Vector,\n faces::Vector, material_map::Dict)\n scene = Vector{Triangle}()\n for face in faces\n for i in 2:(length(face[1]) - 1)\n if isnothing(face[2])\n uv_coordinates = nothing\n else\n uv_coordinates = [[texture_coordinates[face[2][1]]...],\n [texture_coordinates[face[2][i]]...],\n [texture_coordinates[face[2][i + 1]]...]]\n end\n mat = Material(;uv_coordinates = uv_coordinates,\n material_map[face[3]]...)\n push!(scene, Triangle(deepcopy(vertices[face[1][1]]),\n deepcopy(vertices[face[1][i]]),\n deepcopy(vertices[face[1][i + 1]]),\n mat))\n end\n end\n try\n scene_stable = Vector{typeof(scene[1])}()\n for s in scene\n push!(scene_stable, s)\n end\n return scene_stable\n catch e\n # If all the triangles are not of the same type return the non-infered\n # version of the scene. In this case type inference for `raytrace` will\n # also fail\n @warn \"Could not convert the triangles to the same type. Type inference for raytrace will fail\"\n return scene\n end\nend\n\n\"\"\"\n parse_mtllib!(file, material_map, outtype)\n\nParses `.mtl` file and creates a map from the material name to \n[`Material`](@ref) objects.\n\nNot all fields of the `mtl` file are parsed. We only parse :\n`newmtl`, `Ka`, `Kd`, `Ks`, `Ns`, `d`, `Tr`, `map_Kd`, `map_Ks`,\nand `map_Ka`.\n\"\"\"\nfunction parse_mtllib!(file, material_map, outtype)\n color_diffuse = Vec3(outtype(1.0f0))\n color_ambient = Vec3(outtype(1.0f0))\n color_specular = Vec3(outtype(1.0f0))\n specular_exponent = outtype(50.0f0)\n reflection = outtype(0.5f0)\n texture_ambient = nothing\n texture_diffuse = nothing\n texture_specular = nothing\n last_mat = \"RayTracer Default\"\n if isnothing(file)\n material_map[last_mat] = (color_diffuse = color_diffuse,\n color_ambient = color_ambient,\n color_specular = color_specular,\n specular_exponent = specular_exponent,\n reflection = reflection,\n texture_ambient = texture_ambient,\n texture_diffuse = texture_diffuse,\n texture_specular = texture_specular)\n return nothing\n end\n for line in eachline(file)\n wrds = split(line)\n isempty(wrds) && continue\n if wrds[1] == \"newmtl\"\n material_map[last_mat] = (color_diffuse = color_diffuse,\n color_ambient = color_ambient,\n color_specular = color_specular,\n specular_exponent = specular_exponent,\n reflection = reflection,\n texture_ambient = texture_ambient,\n texture_diffuse = texture_diffuse,\n texture_specular = texture_specular)\n last_mat = wrds[2]\n # In case any of these values are not defined for the material\n # we shall use the default values\n color_diffuse = Vec3(outtype(1.0f0))\n color_ambient = Vec3(outtype(1.0f0))\n color_specular = Vec3(outtype(1.0f0))\n specular_exponent = outtype(50.0f0)\n reflection = outtype(0.5f0)\n texture_ambient = nothing\n texture_diffuse = nothing\n texture_specular = nothing\n elseif wrds[1] == \"Ka\"\n color_ambient = Vec3(parse.(outtype, wrds[2:4])...)\n elseif wrds[1] == \"Kd\"\n color_diffuse = Vec3(parse.(outtype, wrds[2:4])...)\n elseif wrds[1] == \"Ks\"\n color_specular = Vec3(parse.(outtype, wrds[2:4])...)\n elseif wrds[1] == \"Ns\"\n specular_exponent = parse(outtype, wrds[2])\n elseif wrds[1] == \"d\"\n reflection = parse(outtype, wrds[2])\n elseif wrds[1] == \"Tr\"\n reflection = 1 - parse(outtype, wrds[2])\n elseif wrds[1] == \"map_Ka\"\n texture_file = \"$(rsplit(file, '/', limit = 2)[1])/$(wrds[2])\"\n texture_ambient = Vec3([outtype.(permutedims(channelview(load(texture_file)),\n (3, 2, 1)))[:,end:-1:1,i]\n for i in 1:3]...)\n elseif wrds[1] == \"map_Kd\"\n texture_file = \"$(rsplit(file, '/', limit = 2)[1])/$(wrds[2])\"\n texture_diffuse = Vec3([outtype.(permutedims(channelview(load(texture_file)),\n (3, 2, 1)))[:,end:-1:1,i]\n for i in 1:3]...)\n elseif wrds[1] == \"map_Ks\"\n texture_file = \"$(rsplit(file, '/', limit = 2)[1])/$(wrds[2])\"\n texture_specular = Vec3([outtype.(permutedims(channelview(load(texture_file)),\n (3, 2, 1)))[:,end:-1:1,i]\n for i in 1:3]...)\n end\n end\n material_map[last_mat] = (color_diffuse = color_diffuse,\n color_ambient = color_ambient,\n color_specular = color_specular,\n specular_exponent = specular_exponent,\n texture_ambient = texture_ambient,\n texture_diffuse = texture_diffuse,\n texture_specular = texture_specular)\n return nothing\nend\n\n\"\"\"\n load_obj(file; outtype = Float32)\n\nParser for `obj` file. It returns a set of Triangles that make up the scene.\n\nOnly the following things are parsed as of now: `v`, `vt`, `vn`, `f`, `usemtl`\nand `mtllib`.\n\"\"\"\nfunction load_obj(file; outtype = Float32)\n vertices = Vector{Vec3{Vector{outtype}}}()\n texture_coordinates = Vector{Tuple}()\n normals = Vector{Vec3{Vector{outtype}}}()\n faces = Vector{Tuple{Vector{Int}, Union{Vector{Int}, Nothing}, String}}()\n material_map = Dict{String, Union{NamedTuple, Nothing}}()\n last_mat = \"RayTracer Default\"\n mtllib = nothing\n for line in eachline(file)\n wrds = split(line)\n isempty(wrds) && continue\n if wrds[1] == \"v\" # Vertices\n push!(vertices, Vec3(parse.(outtype, wrds[2:4])...))\n elseif wrds[1] == \"vt\" # Texture Coordinates\n push!(texture_coordinates, tuple(parse.(outtype, wrds[2:3])...))\n elseif wrds[1] == \"vn\" # Normal\n push!(normals, Vec3(parse.(outtype, wrds[2:4])...))\n elseif wrds[1] == \"f\" # Faces\n # Currently we shall only be concerned with the vertices of the face\n # and safely throw away vertex normal information\n fstwrd = split(wrds[2], '/')\n texture_c = isempty(fstwrd[2]) ? nothing : [parse(Int, fstwrd[2])]\n @assert length(fstwrd) == 3 \"Incorrect number of /'s in the obj file\"\n push!(faces, ([parse(Int, fstwrd[1])], texture_c, last_mat))\n for wrd in wrds[3:end]\n splitwrd = split(wrd, '/')\n @assert length(splitwrd) == 3 \"Incorrect number of /'s in the obj file\"\n push!(faces[end][1], parse(Int, splitwrd[1]))\n !isnothing(texture_c) && push!(faces[end][2], parse(Int, splitwrd[2]))\n end\n elseif wrds[1] == \"usemtl\" # Key for parsing mtllib file\n last_mat = wrds[2]\n material_map[last_mat] = nothing\n elseif wrds[1] == \"mtllib\" # Material file\n mtllib = \"$(rsplit(file, '/', limit = 2)[1])/$(wrds[2])\"\n end\n end\n \n if !isnothing(mtllib)\n parse_mtllib!(mtllib, material_map, outtype)\n else\n parse_mtllib!(nothing, material_map, outtype)\n end\n\n return triangulate_faces(vertices, texture_coordinates, faces, material_map)\nend\n\n", "meta": {"hexsha": "603a1535a1f17697270d36e40efac91bd42133c5", "size": 8698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/objects/obj_parser.jl", "max_stars_repo_name": "matbesancon/RayTracer.jl", "max_stars_repo_head_hexsha": "17aa5e592cd1fc0cfdf5322c57397a68aaefe2de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 149, "max_stars_repo_stars_event_min_datetime": "2019-03-18T05:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T02:41:01.000Z", "max_issues_repo_path": "src/objects/obj_parser.jl", "max_issues_repo_name": "matbesancon/RayTracer.jl", "max_issues_repo_head_hexsha": "17aa5e592cd1fc0cfdf5322c57397a68aaefe2de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2019-05-18T16:09:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T19:38:25.000Z", "max_forks_repo_path": "src/objects/obj_parser.jl", "max_forks_repo_name": "matbesancon/RayTracer.jl", "max_forks_repo_head_hexsha": "17aa5e592cd1fc0cfdf5322c57397a68aaefe2de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-07-09T06:15:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:34:58.000Z", "avg_line_length": 43.7085427136, "max_line_length": 103, "alphanum_fraction": 0.5300068981, "num_tokens": 2108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2417177833927635}} {"text": "using JLD2\n\n@doc \"\"\"\n runMC(param::Parameter)\n runMC(params::AbstractArray{Parameter}\n ;\n parallel::Bool=false,\n autoID::Bool=true)\n\nRuns Monte Carlo simulation(s) and returns calculated observables.\n\nIf a checkpoint file named `\"\\$(param[\"Checkpoint Filename Prefix\"])_\\$(param[\"ID\"]).jld2\"` exists and\n`param[\"Checkpoint Interval\"] > 0.0`, `runMC` loads this file and restarts the pending simulation.\n\n# Keyward aruguments\n- `autoID`: If true, `\"ID\"`s will be set (overwritten) as `params[i][\"ID\"] = i`.\n- `parallel`: If true, runs simulations in parallel (uses `pmap` instead of `map`).\n\n# Required keys in `param`\n- \"Model\"\n- \"Update Method\"\n\n# Optional keys in `param`\n- \"MCS\": The number of Monte Carlo steps after thermalization\n - Default: `8192`\n- \"Thermalization\": The number of Monte Carlo steps for thermalization\n - Default: `MCS>>3`\n- \"Seed\": The initial seed of the random number generator, `MersenneTwister`\n - Default: determined randomly (see `Random.srand`)\n- \"Checkpoint Filename Prefix\": See above document.\n - Default: `\"cp\"`\n- \"ID\": See above document.\n - Default: `0`\n- \"Checkpoint Interval\": Time interval between writing checkpoint file in seconds.\n - Default: `0.0`, this means that NO checkpoint file will be loaded and saved.\n\"\"\"\nfunction runMC(params::AbstractArray{T}; parallel::Bool=false, autoID::Bool=true) where T<:Dict\n map_fn = ifelse(parallel, pmap, map)\n return map_fn(enumerate(params)) do idp\n id,p = idp\n if autoID\n p[\"ID\"] = id\n end\n return runMC(p)\n end\nend\n\nfunction runMC(param::Parameter)\n model = param[\"Model\"](param)\n if \"Seed\" in keys(param)\n srand(model, param[\"Seed\"])\n end\n ret = runMC(model, param)\n return ret\nend\n\nfunction runMC(model, param::Parameter)\n MODEL = typeof(model)\n verbose = get(param, \"Verbose\", false) :: Bool\n if verbose\n println(\"Start: \", param)\n end\n cp_filename = @sprintf(\"%s_%d.jld2\",\n get(param, \"Checkpoint Filename Prefix\", \"cp\")::String,\n get(param, \"ID\", 0)::Int)\n cp_interval = get(param, \"Checkpoint Interval\", 0.0) :: Float64\n if VERSION > v\"0.6.4\" && cp_interval != 0.0\n Compat.@info \"\"\"\"Checkpoint Interval\" is set to 0.0 automatically since current JLD2.jl cannot save/load Random.MersenneTwister object properly in julia-0.7\"\"\"\n cp_interval = 0.0\n end\n tm = time()\n\n MCS = get(param, \"MCS\", 8192) :: Int\n Therm = get(param, \"Thermalization\", MCS>>3) :: Int\n\n mcs = 0\n MCS += Therm\n obs = BinningObservableSet()\n makeMCObservable!(obs, \"Time per MCS\")\n makeMCObservable!(obs, \"MCS per Second\")\n\n if cp_interval > 0.0 && ispath(cp_filename)\n jld = jldopen(cp_filename)\n model = jld[\"model\"] :: MODEL\n obs = jld[\"obs\"] :: BinningObservableSet\n mcs = convert(Int, jld[\"mcs\"]) :: Int\n close(jld)\n end\n\n if \"UpdateMethod\" in keys(param)\n warn(\"\\\"UpdateMethod\\\" is deprecated. Use instead \\\"Update Method\\\".\")\n param[\"Update Method\"] = param[\"UpdateMethod\"] :: Function\n end\n update! = param[\"Update Method\"] :: Function\n estimator = get(param, \"Estimator\", default_estimator(model, update!)) :: Function\n p = convert_parameter(model, param)\n\n while mcs < MCS\n if mcs < Therm\n update!(model, p...)\n else\n t = @elapsed begin\n st = update!(model,p...)\n localobs = estimator(model, p..., st)\n end\n obs[\"Time per MCS\"] << t\n obs[\"MCS per Second\"] << 1.0/t\n accumulateObservables!(model, obs, localobs)\n end\n mcs += 1\n if cp_interval > 0.0 && time() - tm > cp_interval\n jld = jldopen(cp_filename, \"w\")\n jld[\"model\"] = model\n jld[\"obs\"] = obs\n jld[\"mcs\"] = mcs\n close(jld)\n tm += cp_interval\n end\n end\n\n if cp_interval > 0.0\n jld = jldopen(cp_filename, \"w\")\n jld[\"model\"] = model\n jld[\"obs\"] = obs\n jld[\"mcs\"] = mcs\n close(jld)\n end\n\n jk = postproc(model, param, obs)\n\n if verbose\n println(\"Finish: \", param)\n end\n return jk\nend\n\n@doc \"\"\"\n accumulateObservables!(model, obs::MCObservableSet, localobs::Dict)\n\nAccumulates `localobs` into `obs`. For example, `obs[\"Energy\"] << localobs[\"Energy\"]`.\n\"\"\"\nfunction accumulateObservables!(::Model, obs::MCObservableSet, localobs::Measurement)\n if length(obs) < 3\n @inbounds for key in keys(localobs)\n makeMCObservable!(obs, key)\n obs[key] << localobs[key]\n end\n else\n @inbounds for key in keys(localobs)\n obs[key] << localobs[key]\n end\n end\n return obs\nend\n\n@doc \"\"\"\n postproc(model::Model, param::Parameter, obs::MCObservableSet)\n\nPost process of observables. For example, Specific heat will be calculated from energy, energy^2, and temperature.\n\"\"\"\nfunction postproc end\n\n@doc doc\"\"\"\n postproc(model::Union{Ising, Potts}, param::Parameter, obs::MCObservableSet)\n\n# Observables to be calculated\nIn the following, $m$ is total magnetization per site and $\\epsilon$ is total energy per site.\n\n- `\"Binder Ratio\"`\n - $R := \\frac{\\left \\langle m^4 \\right \\rangle}{\\left \\langle m^2 \\right\\rangle^2}$\n- `\"Susceptibility\"`\n - $\\chi := \\frac{N}{T}\\left(\\left\\langle m^2\\right\\rangle\\right)$\n- `\"Connected Susceptibility\"`\n - $\\frac{N}{T}\\left(\\left\\langle m^2\\right\\rangle - \\left\\langle |m| \\right\\rangle^2\\right)$\n- `\"Specific Heat\"`\n - $\\frac{N}{T^2}\\left(\\left\\langle \\epsilon^2\\right\\rangle - \\left\\langle \\epsilon \\right\\rangle^2\\right)$\n\"\"\"\nfunction postproc(model::Union{Ising, Potts}, param::Parameter, obs::MCObservableSet)\n nsites = numsites(model)\n T = param[\"T\"] :: Float64\n beta = 1.0/T\n\n jk = jackknife(obs)\n jk[\"Binder Ratio\"] = jk[\"Magnetization^4\"] / (jk[\"Magnetization^2\"]^2)\n jk[\"Susceptibility\"] = (nsites*beta)*jk[\"Magnetization^2\"]\n jk[\"Connected Susceptibility\"] = (nsites*beta)*(jk[\"Magnetization^2\"] - jk[\"|Magnetization|\"]^2)\n jk[\"Specific Heat\"] = (nsites*beta*beta)*(jk[\"Energy^2\"] - jk[\"Energy\"]^2)\n return jk\nend\n\n@doc doc\"\"\"\n postproc(model::Union{Clock, XY}, param::Parameter, obs::MCObservableSet)\n\n# Observables to be calculated\nIn the following, $m$ is total magnetization per site and $\\epsilon$ is total energy per site.\n\n- `\"Binder Ratio x\"`\n - $\\frac{\\left \\langle m_x^4 \\right \\rangle}{\\left \\langle m_x^2 \\right\\rangle^2}$\n- `\"Binder Ratio y\"`\n - $\\frac{\\left \\langle m_y^4 \\right \\rangle}{\\left \\langle m_y^2 \\right\\rangle^2}$\n- `\"Binder Ratio\"`\n - $\\frac{\\left \\langle |m|^4 \\right \\rangle}{\\left \\langle |m|^2 \\right\\rangle^2}$\n- `\"Susceptibility x\"`\n - $\\frac{N}{T}\\left(\\left\\langle m_x^2\\right\\rangle\\right)$\n- `\"Susceptibility y\"`\n - $\\frac{N}{T}\\left(\\left\\langle m_y^2\\right\\rangle\\right)$\n- `\"Susceptibility y\"`\n - $\\frac{N}{T}\\left(\\left\\langle |m|^2\\right\\rangle\\right)$\n- `\"Connected Susceptibility x\"`\n - $\\frac{N}{T}\\left(\\left\\langle m_x^2\\right\\rangle - \\left\\langle |m_x| \\right\\rangle^2\\right)$\n- `\"Connected Susceptibility y\"`\n - $\\frac{N}{T}\\left(\\left\\langle m_y^2\\right\\rangle - \\left\\langle |m_y| \\right\\rangle^2\\right)$\n- `\"Connected Susceptibility\"`\n - $\\frac{N}{T}\\left(\\left\\langle |m|^2\\right\\rangle - \\left\\langle |m| \\right\\rangle^2\\right)$\n- `\"Specific Heat\"`\n - $\\frac{N}{T^2}\\left(\\left\\langle \\epsilon^2\\right\\rangle - \\left\\langle \\epsilon \\right\\rangle^2\\right)$\n\"\"\"\nfunction postproc(model::Union{Clock, XY}, param::Parameter, obs::MCObservableSet)\n nsites = numsites(model)\n T = param[\"T\"]\n beta = 1.0/T\n\n jk = jackknife(obs)\n jk[\"Binder Ratio x\"] = jk[\"Magnetization x^4\"] / (jk[\"Magnetization x^2\"]^2)\n jk[\"Binder Ratio y\"] = jk[\"Magnetization y^4\"] / (jk[\"Magnetization y^2\"]^2)\n jk[\"Binder Ratio\"] = jk[\"|Magnetization|^4\"] / (jk[\"|Magnetization|^2\"]^2)\n jk[\"Susceptibility x\"] = (nsites*beta)*jk[\"Magnetization x^2\"]\n jk[\"Susceptibility y\"] = (nsites*beta)*jk[\"Magnetization y^2\"]\n jk[\"Susceptibility\"] = (nsites*beta)*jk[\"|Magnetization|^2\"]\n jk[\"Connected Susceptibility x\"] = (nsites*beta)*(jk[\"Magnetization x^2\"] - jk[\"|Magnetization x|\"]^2)\n jk[\"Connected Susceptibility y\"] = (nsites*beta)*(jk[\"Magnetization y^2\"] - jk[\"|Magnetization y|\"]^2)\n jk[\"Connected Susceptibility\"] = (nsites*beta)*(jk[\"|Magnetization|^2\"] - jk[\"|Magnetization|\"]^2)\n jk[\"Specific Heat\"] = (nsites*beta*beta)*(jk[\"Energy^2\"] - jk[\"Energy\"]^2)\n return jk\nend\n\n@doc doc\"\"\"\n postproc(model::QuantumXXZ, param::Parameter, obs::MCObservableSet)\n\n# Observables to be calculated\nIn the following, $s$ is sign of weight, $m$ is total magnetization per site,\nand $\\epsilon$ is total energy per site.\n\n- `\"Magnetization\"`\n - $\\left\\langle m s\\right\\rangle\\Big/\\left\\langle s \\right\\rangle$\n- `\"|Magnetization|\"`\n - $\\left\\langle |m| s\\right\\rangle\\Big/\\left\\langle s \\right\\rangle$\n- `\"Magnetization^2\"`\n - $\\left\\langle m^2 s\\right\\rangle\\Big/\\left\\langle s \\right\\rangle$\n- `\"Magnetization^4\"`\n - $\\left\\langle m^4 s\\right\\rangle\\Big/\\left\\langle s \\right\\rangle$\n- `\"Energy\"`\n - $\\left\\langle \\epsilon s\\right\\rangle\\Big/\\left\\langle s \\right\\rangle$\n- `\"Energy^2\"`\n - $\\left\\langle \\epsilon^2 s\\right\\rangle\\Big/\\left\\langle s \\right\\rangle$\n- `\"Binder Ratio\"`\n - $\\frac{\\left \\langle m^4 \\right \\rangle}{\\left \\langle m^2 \\right\\rangle^2}$\n- `\"Susceptibility\"`\n - $\\frac{N}{T}\\left(\\left\\langle m^2\\right\\rangle\\right)$\n- `\"Connected Susceptibility\"`\n - $\\frac{N}{T}\\left(\\left\\langle m^2\\right\\rangle - \\left\\langle |m| \\right\\rangle^2\\right)$\n- `\"Specific Heat\"`\n - $\\frac{N}{T^2}\\left(\\left\\langle \\epsilon^2\\right\\rangle - \\left\\langle \\epsilon \\right\\rangle^2\\right)$\n\"\"\"\nfunction postproc(model::QuantumXXZ, param::Parameter, obs::MCObservableSet)\n nsites = numsites(model)\n T = param[\"T\"]\n beta = 1.0/T\n\n jk = jackknife(obs)\n\n for oname in (\"Magnetization\", \"|Magnetization|\",\n \"Magnetization^2\", \"Magnetization^4\",\n \"Energy\", \"Energy^2\",\n )\n jk[oname] = jk[\"Sign * $oname\"] / jk[\"Sign\"]\n end\n\n jk[\"Binder Ratio\"] = jk[\"Magnetization^4\"] / (jk[\"Magnetization^2\"]^2)\n jk[\"Susceptibility\"] = (nsites*beta)*jk[\"Magnetization^2\"]\n jk[\"Connected Susceptibility\"] = (nsites*beta)*(jk[\"Magnetization^2\"] - jk[\"|Magnetization|\"]^2)\n jk[\"Specific Heat\"] = (nsites*beta*beta)*(jk[\"Energy^2\"] - jk[\"Energy\"]^2)\n return jk\nend\n", "meta": {"hexsha": "590d658cac7a7ffa3bd6b1bd9b16348920a7544c", "size": 10606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/runMC.jl", "max_stars_repo_name": "StefanKarpinski/SpinMonteCarlo.jl", "max_stars_repo_head_hexsha": "cd58f08e3f3f004de21e3dd975ddcafd7cd3a81f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/runMC.jl", "max_issues_repo_name": "StefanKarpinski/SpinMonteCarlo.jl", "max_issues_repo_head_hexsha": "cd58f08e3f3f004de21e3dd975ddcafd7cd3a81f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/runMC.jl", "max_forks_repo_name": "StefanKarpinski/SpinMonteCarlo.jl", "max_forks_repo_head_hexsha": "cd58f08e3f3f004de21e3dd975ddcafd7cd3a81f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2140350877, "max_line_length": 167, "alphanum_fraction": 0.6223835565, "num_tokens": 3294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2417177833927635}} {"text": "function similar_cells( cell_connectivity1::Vector{Int}, \n cell_type1::Int, \n cell_connectivity2::Union{Tuple{Vararg{Int}}, Vector{Int}},\n cell_type2::Int\n )\n for k in cell_connectivity2\n in(k, cell_connectivity1) || return false\n end\n cell_type1 == cell_type2 || return false\n return true\nend\n\nfunction coherent(a::T, b::T) where {T<:AbstractVTKMultiblockData}\n return same_ordered_geometry_shape(a,b) && same_data_shape(a,b)\nend\nfunction coherent(a::T, b::T) where {T<:AbstractVTKSimpleData}\n return same_geometry_shape(a, b) && same_data_shape(a, b)\nend\nfunction coherent(dataset::AbstractTimeSeriesVTKData)\n length(dataset) == 0 && return true \n block1 = dataset[1]\n for block in dataset[2:end]\n coherent(block1, block) || return false\n end\n return true\nend\nfunction coherent(a::T, b::T) where {T<:AbstractTimeSeriesVTKData}\n length(a) == length(b) && \n coherent(a) && coherent(b) && begin \n _out = true\n for i in 1:length(a)\n (_out = coherent(a[i], b[i])) || break\n end\n _out\n end || return false\n return true\nend\ncoherent(a::AbstractVTKData, b::AbstractVTKData) = false\n\nextents(dataset::VTKStructuredData) = Base.tail(size(dataset.point_coords))\nfunction extents(dataset::VTKRectilinearData)\n return ntuple(i->length(dataset.point_coords[i]), Val(length(dataset.point_coords)))\nend\nextents(dataset::VTKUniformRectilinearData) = dataset.extents\nextents(dataset::AbstractVTKStructuredData, ind::Int) = extents(dataset)[ind]\nextents(dataset::AbstractVTKStructuredData, ind::Int...) = extents.(Ref(dataset), ind)\ncell_extents(dataset::AbstractVTKStructuredData) = ntuple(i -> extents(dataset, i) .- 1, dim(dataset))\ncell_extents(dataset::AbstractVTKStructuredData, ind::Int) = cell_extents(dataset)[ind]\ncell_extents(dataset::AbstractVTKStructuredData, ind::Int...) = cell_extents.(Ref(dataset), ind)\n\ndim(dataset::AbstractVTKUnstructuredData) = size(dataset.point_coords, 1)\ndim(dataset::AbstractVTKStructuredData) = length(extents(dataset))\nfunction dim(dataset::AbstractVTKMultiblockData)\n return maximum(i -> dim(dataset[i]), 1:length(dataset))\nend\n\nnum_of_points(dataset::AbstractVTKUnstructuredData) = size(dataset.point_coords, 2)\nnum_of_points(dataset::AbstractVTKStructuredData) = prod(extents(dataset))\nnum_of_points(dataset::AbstractVTKMultiblockData) = sum(num_of_points(i) for i in dataset)\nnum_of_points(dataset::AbstractTimeSeriesVTKData, ind::Int=1) = num_of_points(dataset[ind]) \n\nnum_of_cells(dataset::AbstractVTKUnstructuredData) = length(dataset.cell_types)\nnum_of_cells(dataset::AbstractVTKStructuredData) = prod(extents(dataset) .- 1)\nnum_of_cells(dataset::AbstractVTKMultiblockData) = sum(num_of_cells(i) for i in dataset)\nnum_of_cells(dataset::AbstractTimeSeriesVTKData, ind::Int=1) = num_of_cells(dataset[ind])\n\nnum_of_point_vars(dataset::AbstractVTKSimpleData) = length(dataset.point_data)\nnum_of_cell_vars(dataset::AbstractVTKSimpleData) = length(dataset.cell_data)\n\nfunction cell_type(dataset::Union{VTKUnstructuredData, VTKPolyData}, ind::Int)\n return dataset.cell_types[ind]\nend\nfunction cell_type(dataset::Union{VTKStructuredData, VTKRectilinearData}, ind::Int)\n if ind < 1 || ind > num_of_cells(dataset)\n throw(\"Out of bounds.\")\n else\n return dim(dataset) == 2 ? 9 : 12\n end\nend\nfunction cell_type(dataset::VTKUniformRectilinearData, ind::Int)\n if ind < 1 || ind > num_of_cells(dataset)\n throw(\"Out of bounds.\")\n else\n return dim(dataset) == 2 ? 8 : 11\n end\nend\nfunction cell_type(dataset::AbstractVTKStructuredData, ind::Tuple{Vararg{Int}})\n return cell_type(dataset, (LinearIndices(cell_extents(dataset)))[ind...])\nend\n\nfunction cell_connectivity(dataset::AbstractVTKUnstructuredData, cell_ind::Int)\n return dataset.cell_connectivity[cell_ind]\nend\nfunction cell_connectivity(dataset::T, cell_ind::Tuple{Vararg{Int}}) where {T<:AbstractVTKStructuredData}\n pextents = extents(dataset)\n return cell_connectivity(T, pextents, cell_ind)\nend\n\nfunction cell_connectivity(dataset::T, cell_ind) where {T<:AbstractVTKStructuredData}\n return cell_connectivity(T, extents(dataset), cell_ind)\nend\n\nfunction cell_connectivity(T::DataType, pextents::NTuple{N,Int}, cell_ind::NTuple{N,Int}) where {N}\n corner_point_ind = (LinearIndices(pextents))[cell_ind...]\n if N == 2 \n #1 <= cell_ind <= num_of_cells(dataset) || throw(\"Out of bounds.\")\n if T <: VTKUniformRectilinearData\n return [corner_point_ind, corner_point_ind + 1, corner_point_ind + pextents[1], \n corner_point_ind + pextents[1] + 1]\n else\n return [corner_point_ind, corner_point_ind + 1, corner_point_ind + pextents[1] + 1, \n corner_point_ind + pextents[1]]\n end\n elseif N == 3\n #1 <= cell_ind <= num_of_cells(dataset) || throw(\"Out of bounds.\")\n if T <: VTKUniformRectilinearData\n return [corner_point_ind, corner_point_ind + 1, corner_point_ind + pextents[1], \n corner_point_ind + pextents[1] + 1, \n corner_point_ind + pextents[1] * pextents[2], \n corner_point_ind + pextents[1] * pextents[2] + 1, \n corner_point_ind + pextents[1] * pextents[2] + pextents[1], \n corner_point_ind + pextents[1] * pextents[2] + pextents[1] + 1]\n else\n return [corner_point_ind, corner_point_ind + 1, corner_point_ind + pextents[1] + 1, corner_point_ind + pextents[1], \n corner_point_ind + pextents[1] * pextents[2], \n corner_point_ind + pextents[1] * pextents[2] + 1, \n corner_point_ind + pextents[1] * pextents[2] + pextents[1] + 1, corner_point_ind + pextents[1] * pextents[2] + pextents[1]]\n end\n end\n\n throw(\"Invalid mesh dimension.\")\nend\n\nfunction has_var(dataset::AbstractStaticVTKData, var_name::String)\n if haskey(dataset.point_data, var_name)\n return true, \"Point\"\n elseif haskey(dataset.cell_data, var_name)\n return true, \"Cell\"\n else\n return false, \"\"\n end\nend\n\nfunction var_dim(dataset::AbstractVTKUnstructuredData, var_name::String, var_type::String=\"\")\n if var_type == \"Point\" && haskey(dataset.point_data, var_name)\n if length(size(dataset.point_data[var_name])) == 1\n return 1\n else\n return length(dataset.point_data[var_name][:,1])\n end\n elseif var_type == \"Cell\" && haskey(dataset.cell_data, var_name)\n if length(size(dataset.cell_data[var_name])) == 1\n return 1\n else\n return length(dataset.cell_data[var_name][:,1])\n end\n elseif var_type == \"\"\n try \n return var_dim(dataset, var_name, \"Point\")\n catch\n return var_dim(dataset, var_name, \"Cell\")\n end\n else\n throw(\"Variable $var_name doesn't exist, please use has_var to check if the variable exists before using this function.\")\n end\nend\n\nfunction var_dim(dataset::AbstractVTKStructuredData, var_name::String, var_type::String=\"\")\n if var_type == \"Point\" && haskey(dataset.point_data, var_name)\n if length(size(dataset.point_data[var_name])) == length(extents(dataset))\n return 1\n else\n return size(dataset.point_data[var_name], 1)\n end\n elseif var_type == \"Cell\" && haskey(dataset.cell_data, var_name)\n if length(size(dataset.cell_data[var_name])) == length(extents(dataset))\n return 1\n else\n return size(dataset.cell_data[var_name], 1)\n end\n elseif var_type == \"\"\n try \n return var_dim(dataset, var_name, \"Point\")\n catch\n return var_dim(dataset, var_name, \"Cell\")\n end\n else\n throw(\"Variable $var_name doesn't exist, please use has_var to check if the variable exists before using this function.\")\n end\nend\n\nfunction vtk_cell_type_name(dataset::AbstractVTKStructuredData, cell_id)\n return VTK_CELL_TYPE[cell_type(dataset, cell_id)]\nend\nfunction is_homogeneous(dataset::AbstractVTKUnstructuredData)\n begin\n out = true\n for i in 2:num_of_cells(dataset)\n (out = cell_type(dataset, 1) == cell_type(dataset, i)) || break\n end\n out\n end || return false\n return true\nend\n\nis_homogeneous(dataset::AbstractVTKStructuredData) = true\n\nfunction is_homogeneous(dataset::AbstractVTKMultiblockData)\n return all(i -> typeof(dataset[1]) == typeof(dataset[i]), 2:length(dataset))\nend\nfunction is_homogeneous(dataset::AbstractTimeSeriesVTKData)\n length(dataset) == 0 || \n is_homogeneous(dataset[1]) && begin\n out = true\n i = dataset[1]\n T = typeof(i)\n for j in dataset\n (out = isa(j, T)) || break\n if T <: AbstractVTKMultiblockData || T <: AbstractVTKUnstructuredData \n (out = same_ordered_geometry_shape(i,j)) || break\n else\n (out = same_geometry_shape(i,j)) || break\n end\n end\n out\n end || return false\n return true\nend\n\nfunction get_cell_ids(dataset::AbstractVTKUnstructuredData, cell_types::Vector{Int})\n cell_ids = Int[]\n for (i, c) in enumerate(dataset.cell_types)\n if in(c, cell_types)\n push!(cell_ids, i)\n end\n end\n return cell_ids\nend\n\nfunction get_lowest_index(cell_connectivity)\n return minimum(i -> minimum(cell_connectivity[i]), 1:length(cell_connectivity))\nend\nfunction get_highest_index(cell_connectivity)\n return maximum(i -> maximum(cell_connectivity[i]), 1:length(cell_connectivity))\nend\nfunction is_valid_cell(cell_connectivity, cell_type)\n return VTK_CELL_TYPE[cell_type].nodes == -1 || \n length(_cell_connectivity) == VTK_CELL_TYPE[cell_type].nodes\nend\nnum_of_blocks(dataset::AbstractVTKMultiblockData) = length(dataset.blocks)\n\ntimespan(dataset::VTKTimeSeriesData) = dataset.timemarkers[end] - dataset.timemarkers[1]\n\nnum_of_timesteps(dataset::VTKTimeSeriesData) = length(dataset.timemarkers)\n\ntriangular(dataset::AbstractVTKUnstructuredData) = all(i -> i == 5, dataset.cell_types)\n\nfunction bb(dataset::T) where {T<:AbstractVTKData}\n if T <: AbstractVTKUnstructuredData\n return bb_unstruct(dataset)\n elseif T <: VTKStructuredData\n return bb_struct(dataset)\n elseif T <: VTKRectilinearData\n return bb_rect(dataset)\n elseif T <: VTKUniformRectilinearData\n return bb_image(dataset)\n elseif T <: Union{AbstractVTKMultiblockData, AbstractTimeSeriesVTKData}\n return bb_multiblock_time(dataset)\n end\n throw(\"Unsupported type.\")\nend\n\nfunction bb_unstruct(dataset::AbstractVTKUnstructuredData)\n _dim = dim(dataset)\n min_x = max_x = dataset.point_coords[1,1]\n min_y = max_y = dataset.point_coords[2,1]\n if _dim == 2\n for i in 2:num_of_points(dataset)\n if dataset.point_coords[1,i] > max_x\n max_x = dataset.point_coords[1,i]\n elseif dataset.point_coords[1,i] < min_x\n min_x = dataset.point_coords[1,i] \n end\n \n if dataset.point_coords[2,i] > max_y\n max_y = dataset.point_coords[2,i]\n elseif dataset.point_coords[2,i] < min_y\n min_y = dataset.point_coords[2,i] \n end\n end\n return (min_x, max_x, min_y, max_y)\n elseif _dim == 3\n min_z = max_z = dataset.point_coords[3,1]\n for i in 2:num_of_points(dataset)\n if dataset.point_coords[1,i] > max_x\n max_x = dataset.point_coords[1,i]\n elseif dataset.point_coords[1,i] < min_x\n min_x = dataset.point_coords[1,i] \n end\n \n if dataset.point_coords[2,i] > max_y\n max_y = dataset.point_coords[2,i]\n elseif dataset.point_coords[2,i] < min_y\n min_y = dataset.point_coords[2,i] \n end\n\n if dataset.point_coords[3,i] > max_z\n max_z = dataset.point_coords[3,i]\n elseif dataset.point_coords[3,i] < min_z\n min_z = dataset.point_coords[3,i] \n end\n end\n return (min_x, max_x, min_y, max_y, min_z, max_z)\n else\n throw(\"Invalid dimension.\")\n end\nend\n\n@resumable function surface_cell_inds(dataset::AbstractVTKStructuredData)\n cextents = cell_extents(dataset)\n if dim(dataset) == 2\n i = 1\n for j in 1:cextents[2]\n @yield (i,j)\n end\n j = 1\n for i in 2:cextents[1]\n @yield (i,j)\n end\n\n i = cextents[1]\n for j in 2:cextents[2]\n @yield (i,j)\n end\n j = cextents[2]\n for i in 2:cextents[1]-1\n @yield (i,j)\n end\n else\n i = 1\n for j in 1:cextents[2], k in 1:cextents[3]\n @yield (i,j,k)\n end\n \n j = 1\n for i in 2:cextents[1], k in 1:cextents[3]\n @yield (i,j,k)\n end\n\n k = 1\n for i in 2:cextents[1], j in 2:cextents[2]\n @yield (i,j,k)\n end\n\n i = cextents[1]\n for j in 2:cextents[2], k in 2:cextents[3]\n @yield (i,j,k)\n end\n \n j = cextents[2]\n for i in 2:cextents[1]-1, k in 2:cextents[3]\n @yield (i,j,k)\n end\n\n k = cextents[3]\n for i in 2:cextents[1]-1, j in 2:cextents[3]-1\n @yield (i,j,k)\n end\n end\nend\n\nfunction bb_struct(dataset::VTKStructuredData)\n cextents = cell_extents(dataset)\n _dim = dim(dataset)\n\n min_x = max_x = dataset.point_coords[1,1]\n min_y = max_y = dataset.point_coords[2,1]\n if _dim == 2\n for (i,j) in surface_cell_inds(dataset)\n if dataset.point_coords[1,i] > max_x\n max_x = dataset.point_coords[1,i]\n elseif dataset.point_coords[1,i] < min_x\n min_x = dataset.point_coords[1,i] \n end\n \n if dataset.point_coords[2,i] > max_y\n max_y = dataset.point_coords[2,i]\n elseif dataset.point_coords[2,i] < min_y\n min_y = dataset.point_coords[2,i] \n end\n end\n return (min_x, max_x, min_y, max_y)\n elseif _dim == 3\n min_z = max_z = dataset.point_coords[3,1]\n for (i,j,k) in surface_cell_inds(dataset)\n if dataset.point_coords[1,i] > max_x\n max_x = dataset.point_coords[1,i]\n elseif dataset.point_coords[1,i] < min_x\n min_x = dataset.point_coords[1,i] \n end\n \n if dataset.point_coords[2,i] > max_y\n max_y = dataset.point_coords[2,i]\n elseif dataset.point_coords[2,i] < min_y\n min_y = dataset.point_coords[2,i] \n end\n\n if dataset.point_coords[3,i] > max_z\n max_z = dataset.point_coords[3,i]\n elseif dataset.point_coords[3,i] < min_z\n min_z = dataset.point_coords[3,i] \n end\n end\n return (min_x, max_x, min_y, max_y, min_z, max_z)\n else\n throw(\"Invalid dimension.\")\n end\nend\n\nfunction bb_rect(dataset::VTKRectilinearData)\n min_x = dataset.point_coords[1][1]\n max_x = dataset.point_coords[1][end]\n min_y = dataset.point_coords[2][1]\n max_y = dataset.point_coords[2][end]\n\n if dim(dataset) == 2\n return (min_x, max_x, min_y, max_y)\n elseif dim(dataset) == 3\n min_z = dataset.point_coords[3][1]\n max_z = dataset.point_coords[3][end]\n return (min_x, max_x, min_y, max_y, min_z, max_z)\n else\n throw(\"Invalid dimension.\")\n end\nend\n\nfunction bb_image(dataset::VTKUniformRectilinearData)\n min_x = dataset.origin[1]\n max_x = dataset.origin[1] + (dataset.extents[1]-1)*dataset.spacing[1]\n min_x = dataset.origin[2]\n max_x = dataset.origin[2] + (dataset.extents[2]-1)*dataset.spacing[2]\n\n if dim(dataset) == 2\n return (min_x, max_x, min_y, max_y)\n elseif dim(dataset) == 3\n min_x = dataset.origin[3]\n max_x = dataset.origin[3] + (dataset.extents[3]-1)*dataset.spacing[3]\n return (min_x, max_x, min_y, max_y, min_z, max_z)\n else\n throw(\"Invalid dimension.\")\n end\nend\n\nfunction bb_multiblock_time(dataset::Union{AbstractVTKMultiblockData, AbstractTimeSeriesVTKData})\n _bbs = [bb(block) for block in dataset]\n min_x = minimum(i -> _bbs[i][1], 1:length(_bbs))\n max_x = maximum(i -> _bbs[i][2], 1:length(_bbs))\n min_y = minimum(i -> _bbs[i][3], 1:length(_bbs))\n max_y = maximum(i -> _bbs[i][4], 1:length(_bbs))\n\n _first = true\n min_z = max_z = 0\n for _bb in _bbs\n if length(_bb) == 6\n if _first\n min_z = _bb[5]\n max_z = _bb[6]\n _first = false\n end\n if _bb[5] < min_z\n min_z = _bb[5]\n end\n if _bb[5] > max_z\n max_z = _bb[6]\n end\n end\n end\n\n if min_z == max_z == 0\n return (min_x, max_x, min_y, max_y)\n else\n return (min_x, max_x, min_y, max_y, min_z, max_z)\n end\nend\n\nfunction pseudo_center(dataset::T) where {T<:AbstractVTKData}\n _bb = bb(dataset)\n return ntuple(i -> (_bb[2i-1] + _bb[2i])/2, Val(length(_bb)÷2))\nend\n", "meta": {"hexsha": "11741a270ec14bed17b89df561f233cb73d53ec7", "size": 17592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/properties_utils.jl", "max_stars_repo_name": "mohamed82008/VTKDataTypes.jl", "max_stars_repo_head_hexsha": "f1434139863b5d2c6b46f0c0d133dca56993c1b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-07-07T05:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T05:44:51.000Z", "max_issues_repo_path": "src/properties_utils.jl", "max_issues_repo_name": "mohamed82008/VTKDataTypes.jl", "max_issues_repo_head_hexsha": "f1434139863b5d2c6b46f0c0d133dca56993c1b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-07-06T21:21:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-04T19:03:03.000Z", "max_forks_repo_path": "src/properties_utils.jl", "max_forks_repo_name": "mohamed82008/VTKDataTypes.jl", "max_forks_repo_head_hexsha": "f1434139863b5d2c6b46f0c0d133dca56993c1b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-31T17:21:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T14:26:03.000Z", "avg_line_length": 35.9020408163, "max_line_length": 143, "alphanum_fraction": 0.6218167349, "num_tokens": 4715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24147948289856724}} {"text": "# This file is a part of Julia. License is MIT: http://julialang.org/license\n\nmodule MPFR3\n\nexport\n BigFloat,\n setprecision,\n big_str\n\nimport\n Base: @big_str, *, +, -, /, <, <=, ==, >, >=, ^,\n besselj, besselj0, besselj1, bessely, bessely0, bessely1,\n ceil, cmp, convert, copysign, div, cbrt, typemax, typemin,\n unsafe_trunc, realmin, realmax, rounding,\n cosh, sinh, tanh, sech, csch, coth, acosh, asinh, atanh, atan2,\n eps, signbit, sin, cos, tan, sec, csc, cot, acos, asin, atan,\n exp, exp2, exponent, factorial, floor, fma, hypot, isinteger,\n gamma, lgamma, digamma, erf, erfc, zeta, eta, airyai,\n isfinite, isinf, isnan, ldexp, log, log2, log10, log1p, exp10, expm1,\n max, min, mod, modf, nextfloat, prevfloat, promote_rule, rem, round,\n show, setrounding, maxintfloat, widen, significand, frexp, tryparse,\n sum, sqrt, string, print, trunc, precision, setprecision\n\nimport Base.Rounding: rounding_raw, setrounding_raw\n\nimport Base.GMP: ClongMax, CulongMax, CdoubleMax, Limb\n\nimport Base.Math.lgamma_r\n\nfunction __init__()\n try\n # set exponent to full range by default\n set_emin!(get_emin_min())\n set_emax!(get_emax_max())\n catch ex\n Base.showerror_nostdio(ex,\n \"WARNING: Error during initialization of module MPFR\")\n end\nend\n\nconst ROUNDING_MODE = Ref{Cint}(0)\nconst DEFAULT_PRECISION = [256]\n\n# Basic type and initialization definitions\n\ntype BigFloat{P} <: AbstractFloat\n prec::Clong\n sign::Cint\n exp::Clong\n d::Ptr{Limb}\n function BigFloat()\n N = Clong(P)\n z = BigFloat{P}(zero(Clong), zero(Cint), zero(Clong), C_NULL)\n ccall((:mpfr_init2,:libmpfr), Void, (Ptr{BigFloat}, Clong), &z, N)\n finalizer(z, cglobal((:mpfr_clear, :libmpfr)))\n return z\n end\n # Not recommended for general use\n function BigFloat(prec::Clong, sign::Cint, exp::Clong, d::Ptr{Void})\n new(prec, sign, exp, d)\n end\nend\n\n\nprecision{P}(::Type{BigFloat{P}}) = P\nprecision{P}(x::BigFloat{P}) = P\n\nfunction initializer{P}(::Type{BigFloat{P}})\n N = Clong(P)\n z = BigFloat{P}(zero(Clong), zero(Cint), zero(Clong), C_NULL)\n ccall((:mpfr_init2,:libmpfr), Void, (Ptr{BigFloat}, Clong), &z, N)\n finalizer(z, cglobal((:mpfr_clear, :libmpfr)))\n return z\nend\ninitializer(::Type{BigFloat}) = initializer(BigFloat{precision(BigFloat)})\n\nBigFloat{P}(::Type{BigFloat{P}}) = initializer(BigFloat{P})\nBigFloat() = initializer(BigFloat)\nfunction BigFloat(prec::Int64, sign::Int32, exp::Int64, d::Ptr{Void})\n P = Int(prec)\n return BigFloat{P}(prec, sign, exp, d)\nend\n\n\n\n\nwiden(::Type{Float64}) = BigFloat\nwiden(::Type{BigFloat}) = BigFloat\n\nconvert{BF<:BigFloat}(::Type{BF}, x::BF) = x\n\n# convert to BF\nfor (fJ, fC) in ((:si,:Clong), (:ui,:Culong), (:d,:Float64))\n @eval begin\n function convert{BF<:BigFloat}(::Type{BF}, x::($fC))\n z = BF()\n ccall(($(string(:mpfr_set_,fJ)), :libmpfr), Int32, (Ptr{BF}, ($fC), Int32), &z, x, ROUNDING_MODE[])\n return z\n end\n end\nend\n\nfunction convert{BF<:BigFloat}(::Type{BF}, x::BigInt)\n z = BF()\n ccall((:mpfr_set_z, :libmpfr), Int32, (Ptr{BF}, Ptr{BigInt}, Int32), &z, &x, ROUNDING_MODE[])\n return z\nend\n\nconvert{BF<:BigFloat}(::Type{BF}, x::Integer) = BF(BigInt(x))\n\nconvert{BF<:BigFloat}(::Type{BF}, x::Union{Bool,Int8,Int16,Int32}) = BF(convert(Clong,x))\nconvert{BF<:BigFloat}(::Type{BF}, x::Union{UInt8,UInt16,UInt32}) = BF(convert(Culong,x))\n\nconvert{BF<:BigFloat}(::Type{BF}, x::Union{Float16,Float32}) = BF(Float64(x))\nconvert{BF<:BigFloat}(::Type{BF}, x::Rational) = BF(num(x)) / BF(den(x))\n\nfunction tryparse{BF<:BigFloat}(::Type{BF}, s::AbstractString, base::Int=0)\n z = BF()\n err = ccall((:mpfr_set_str, :libmpfr), Int32, (Ptr{BF}, Cstring, Int32, Int32), &z, s, base, ROUNDING_MODE[])\n err == 0 ? Nullable(z) : Nullable{BF}()\nend\n\nconvert{BF<:BigFloat}(::Type{Rational}, x::BF) = convert(Rational{BigInt}, x)\nconvert(::Type{AbstractFloat}, x::BigInt) = BigFloat(x)\n\n## BF -> Integer\nfunction unsafe_cast{BF<:BigFloat}(::Type{Int64}, x::BF, ri::Cint)\n ccall((:__gmpfr_mpfr_get_sj,:libmpfr), Cintmax_t,\n (Ptr{BF}, Cint), &x, ri)\nend\nfunction unsafe_cast{BF<:BigFloat}(::Type{UInt64}, x::BF, ri::Cint)\n ccall((:__gmpfr_mpfr_get_uj,:libmpfr), Cuintmax_t,\n (Ptr{BF}, Cint), &x, ri)\nend\n\nfunction unsafe_cast{T<:Signed,BF<:BigFloat}(::Type{T}, x::BF, ri::Cint)\n unsafe_cast(Int64, x, ri) % T\nend\nfunction unsafe_cast{T<:Unsigned,BF<:BigFloat}(::Type{T}, x::BF, ri::Cint)\n unsafe_cast(UInt64, x, ri) % T\nend\n\nfunction unsafe_cast{BF<:BigFloat}(::Type{BigInt}, x::BF, ri::Cint)\n # actually safe, just keep naming consistent\n z = BigInt()\n ccall((:mpfr_get_z, :libmpfr), Int32, (Ptr{BigInt}, Ptr{BF}, Int32),\n &z, &x, ri)\n z\nend\nunsafe_cast{BF<:BigFloat}(::Type{Int128}, x::BF, ri::Cint) = Int128(unsafe_cast(BigInt,x,ri))\nunsafe_cast{BF<:BigFloat}(::Type{UInt128}, x::BF, ri::Cint) = UInt128(unsafe_cast(BigInt,x,ri))\nunsafe_cast{T<:Integer,BF<:BigFloat}(::Type{T}, x::BF, r::RoundingMode) = unsafe_cast(T,x,to_mpfr(r))\n\nunsafe_trunc{T<:Integer,BF<:BigFloat}(::Type{T}, x::BF) = unsafe_cast(T,x,RoundToZero)\n\nfunction trunc{T<:Union{Signed,Unsigned},BF<:BigFloat}(::Type{T}, x::BF)\n (typemin(T) <= x <= typemax(T)) || throw(InexactError())\n unsafe_cast(T,x,RoundToZero)\nend\nfunction floor{T<:Union{Signed,Unsigned},BF<:BigFloat}(::Type{T}, x::BF)\n (typemin(T) <= x <= typemax(T)) || throw(InexactError())\n unsafe_cast(T,x,RoundDown)\nend\nfunction ceil{T<:Union{Signed,Unsigned},BF<:BigFloat}(::Type{T}, x::BF)\n (typemin(T) <= x <= typemax(T)) || throw(InexactError())\n unsafe_cast(T,x,RoundUp)\nend\n\nfunction round{T<:Union{Signed,Unsigned},BF<:BigFloat}(::Type{T}, x::BF)\n (typemin(T) <= x <= typemax(T)) || throw(InexactError())\n unsafe_cast(T,x,ROUNDING_MODE[])\nend\n\ntrunc{BF<:BigFloat}(::Type{BigInt}, x::BF) = unsafe_cast(BigInt, x, RoundToZero)\nfloor{BF<:BigFloat}(::Type{BigInt}, x::BF) = unsafe_cast(BigInt, x, RoundDown)\nceil{BF<:BigFloat}(::Type{BigInt}, x::BF) = unsafe_cast(BigInt, x, RoundUp)\nround{BF<:BigFloat}(::Type{BigInt}, x::BF) = unsafe_cast(BigInt, x, ROUNDING_MODE[])\n\n# convert/round/trunc/floor/ceil(Integer, x) should return a BigInt\ntrunc{BF<:BigFloat}(::Type{Integer}, x::BF) = trunc(BigInt, x)\nfloor{BF<:BigFloat}(::Type{Integer}, x::BF) = floor(BigInt, x)\nceil{BF<:BigFloat}(::Type{Integer}, x::BF) = ceil(BigInt, x)\nround{BF<:BigFloat}(::Type{Integer}, x::BF) = round(BigInt, x)\n\nconvert{BF<:BigFloat}(::Type{Bool}, x::BF) = x==0 ? false : x==1 ? true : throw(InexactError())\nfunction convert{BF<:BigFloat}(::Type{BigInt},x::BF)\n isinteger(x) || throw(InexactError())\n trunc(BigInt,x)\nend\n\nfunction convert{T<:Integer,BF<:BigFloat}(::Type{T},x::BF)\n isinteger(x) || throw(InexactError())\n trunc(T,x)\nend\n\n## BF -> AbstractFloat\nconvert{BF<:BigFloat}(::Type{Float64}, x::BF) =\n ccall((:mpfr_get_d,:libmpfr), Float64, (Ptr{BF},Int32), &x, ROUNDING_MODE[])\nconvert{BF<:BigFloat}(::Type{Float32}, x::BF) =\n ccall((:mpfr_get_flt,:libmpfr), Float32, (Ptr{BF},Int32), &x, ROUNDING_MODE[])\n# TODO: avoid double rounding\nconvert{BF<:BigFloat}(::Type{Float16}, x::BF) = convert(Float16, convert(Float32, x))\n\n(::Type{Float64}){BF<:BigFloat}(x::BF, r::RoundingMode) =\n ccall((:mpfr_get_d,:libmpfr), Float64, (Ptr{BF},Int32), &x, to_mpfr(r))\n(::Type{Float32}){BF<:BigFloat}(x::BF, r::RoundingMode) =\n ccall((:mpfr_get_flt,:libmpfr), Float32, (Ptr{BF},Int32), &x, to_mpfr(r))\n# TODO: avoid double rounding\n(::Type{Float16}){BF<:BigFloat}(x::BF, r::RoundingMode) =\n convert(Float16, Float32(x, r))\n\n\n\npromote_rule(::Type{BigInt},::Type{BigFloat}) = BigFloat\npromote_rule{T<:Real}(::Type{BigFloat}, ::Type{T}) = BigFloat\npromote_rule{T<:AbstractFloat}(::Type{BigInt},::Type{T}) = BigFloat\npromote_rule{T<:AbstractFloat}(::Type{BigFloat},::Type{T}) = BigFloat\n\npromote_rule{P}(::Type{BigInt},::Type{BigFloat{P}}) = BigFloat{P}\npromote_rule{BF<:BigFloat}(::Type{BigInt},::Type{BF}) = BF\npromote_rule{T<:Real,BF<:BigFloat}(::Type{BF}, ::Type{T}) = BF\npromote_rule{T<:AbstractFloat,BF<:BigFloat}(::Type{BF},::Type{T}) = BF\n\nfunction convert(::Type{Rational{BigInt}}, x::AbstractFloat)\n if isnan(x); return zero(BigInt)//zero(BigInt); end\n if isinf(x); return copysign(one(BigInt),x)//zero(BigInt); end\n if x == 0; return zero(BigInt) // one(BigInt); end\n s = max(precision(x) - exponent(x), 0)\n BigInt(ldexp(x,s)) // (BigInt(1) << s)\nend\n\n# Basic arithmetic without promotion\nfor (fJ, fC) in ((:+,:add), (:*,:mul))\n @eval begin\n # BF\n function ($fJ){BF<:BigFloat}(x::BF, y::BF)\n z = BF()\n ccall(($(string(:mpfr_,fC)),:libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &x, &y, ROUNDING_MODE[])\n return z\n end\n\n # Unsigned Integer\n function ($fJ){BF<:BigFloat}(x::BF, c::CulongMax)\n z = BF()\n ccall(($(string(:mpfr_,fC,:_ui)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Culong, Int32), &z, &x, c, ROUNDING_MODE[])\n return z\n end\n ($fJ){BF<:BigFloat}(c::CulongMax, x::BF) = ($fJ)(x,c)\n\n # Signed Integer\n function ($fJ){BF<:BigFloat}(x::BF, c::ClongMax)\n z = BF()\n ccall(($(string(:mpfr_,fC,:_si)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Clong, Int32), &z, &x, c, ROUNDING_MODE[])\n return z\n end\n ($fJ){BF<:BigFloat}(c::ClongMax, x::BF) = ($fJ)(x,c)\n\n # Float32/Float64\n function ($fJ){BF<:BigFloat}(x::BF, c::CdoubleMax)\n z = BF()\n ccall(($(string(:mpfr_,fC,:_d)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Cdouble, Int32), &z, &x, c, ROUNDING_MODE[])\n return z\n end\n ($fJ){BF<:BigFloat}(c::CdoubleMax, x::BF) = ($fJ)(x,c)\n\n # BigInt\n function ($fJ){BF<:BigFloat}(x::BF, c::BigInt)\n z = BF()\n ccall(($(string(:mpfr_,fC,:_z)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BigInt}, Int32), &z, &x, &c, ROUNDING_MODE[])\n return z\n end\n ($fJ){BF<:BigFloat}(c::BigInt, x::BF) = ($fJ)(x,c)\n end\nend\n\nfor (fJ, fC) in ((:-,:sub), (:/,:div))\n @eval begin\n # BF\n function ($fJ){BF<:BigFloat}(x::BF, y::BF)\n z = BF()\n ccall(($(string(:mpfr_,fC)),:libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &x, &y, ROUNDING_MODE[])\n return z\n end\n\n # Unsigned Int\n function ($fJ){BF<:BigFloat}(x::BF, c::CulongMax)\n z = BF()\n ccall(($(string(:mpfr_,fC,:_ui)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Culong, Int32), &z, &x, c, ROUNDING_MODE[])\n return z\n end\n function ($fJ){BF<:BigFloat}(c::CulongMax, x::BF)\n z = BF()\n ccall(($(string(:mpfr_,:ui_,fC)), :libmpfr), Int32, (Ptr{BF}, Culong, Ptr{BF}, Int32), &z, c, &x, ROUNDING_MODE[])\n return z\n end\n\n # Signed Integer\n function ($fJ){BF<:BigFloat}(x::BF, c::ClongMax)\n z = BF()\n ccall(($(string(:mpfr_,fC,:_si)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Clong, Int32), &z, &x, c, ROUNDING_MODE[])\n return z\n end\n function ($fJ){BF<:BigFloat}(c::ClongMax, x::BF)\n z = BF()\n ccall(($(string(:mpfr_,:si_,fC)), :libmpfr), Int32, (Ptr{BF}, Clong, Ptr{BF}, Int32), &z, c, &x, ROUNDING_MODE[])\n return z\n end\n\n # Float32/Float64\n function ($fJ){BF<:BigFloat}(x::BF, c::CdoubleMax)\n z = BF()\n ccall(($(string(:mpfr_,fC,:_d)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Cdouble, Int32), &z, &x, c, ROUNDING_MODE[])\n return z\n end\n function ($fJ){BF<:BigFloat}(c::CdoubleMax, x::BF)\n z = BF()\n ccall(($(string(:mpfr_,:d_,fC)), :libmpfr), Int32, (Ptr{BF}, Cdouble, Ptr{BF}, Int32), &z, c, &x, ROUNDING_MODE[])\n return z\n end\n\n # BigInt\n function ($fJ){BF<:BigFloat}(x::BF, c::BigInt)\n z = BF()\n ccall(($(string(:mpfr_,fC,:_z)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BigInt}, Int32), &z, &x, &c, ROUNDING_MODE[])\n return z\n end\n # no :mpfr_z_div function\n end\nend\n\nfunction -{BF<:BigFloat}(c::BigInt, x::BF)\n z = BF()\n ccall((:mpfr_z_sub, :libmpfr), Int32, (Ptr{BF}, Ptr{BigInt}, Ptr{BF}, Int32), &z, &c, &x, ROUNDING_MODE[])\n return z\nend\n\nfunction fma{BF<:BigFloat}(x::BF, y::BF, z::BF)\n r = BF()\n ccall((\"mpfr_fma\",:libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &r, &x, &y, &z, ROUNDING_MODE[])\n return r\nend\n\n# div\n# BF\nfunction div{BF<:BigFloat}(x::BF, y::BF)\n z = BF()\n ccall((:mpfr_div,:libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &x, &y, to_mpfr(RoundToZero))\n ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &z)\n return z\nend\n\n# Unsigned Int\nfunction div{BF<:BigFloat}(x::BF, c::CulongMax)\n z = BF()\n ccall((:mpfr_div_ui, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Culong, Int32), &z, &x, c, to_mpfr(RoundToZero))\n ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &z)\n return z\nend\nfunction div{BF<:BigFloat}(c::CulongMax, x::BF)\n z = BF()\n ccall((:mpfr_ui_div, :libmpfr), Int32, (Ptr{BF}, Culong, Ptr{BF}, Int32), &z, c, &x, to_mpfr(RoundToZero))\n ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &z)\n return z\nend\n\n# Signed Integer\nfunction div{BF<:BigFloat}(x::BF, c::ClongMax)\n z = BF()\n ccall((:mpfr_div_si, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Clong, Int32), &z, &x, c, to_mpfr(RoundToZero))\n ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &z)\n return z\nend\nfunction div{BF<:BigFloat}(c::ClongMax, x::BF)\n z = BF()\n ccall((:mpfr_si_div, :libmpfr), Int32, (Ptr{BF}, Clong, Ptr{BF}, Int32), &z, c, &x, to_mpfr(RoundToZero))\n ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &z)\n return z\nend\n\n# Float32/Float64\nfunction div{BF<:BigFloat}(x::BF, c::CdoubleMax)\n z = BF()\n ccall((:mpfr_div_d, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Cdouble, Int32), &z, &x, c, to_mpfr(RoundToZero))\n ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &z)\n return z\nend\nfunction div{BF<:BigFloat}(c::CdoubleMax, x::BF)\n z = BF()\n ccall((:mpfr_d_div, :libmpfr), Int32, (Ptr{BF}, Cdouble, Ptr{BF}, Int32), &z, c, &x, to_mpfr(RoundToZero))\n ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &z)\n return z\nend\n\n# BigInt\nfunction div{BF<:BigFloat}(x::BF, c::BigInt)\n z = BF()\n ccall((:mpfr_div_z, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BigInt}, Int32), &z, &x, &c, to_mpfr(RoundToZero))\n ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &z)\n return z\nend\n\n\n# More efficient commutative operations\nfor (fJ, fC, fI) in ((:+, :add, 0), (:*, :mul, 1))\n @eval begin\n function ($fJ){BF<:BigFloat}(a::BF, b::BF, c::BF)\n z = BF()\n ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &a, &b, ROUNDING_MODE[])\n ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &z, &c, ROUNDING_MODE[])\n return z\n end\n function ($fJ){BF<:BigFloat}(a::BF, b::BF, c::BF, d::BF)\n z = BF()\n ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &a, &b, ROUNDING_MODE[])\n ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &z, &c, ROUNDING_MODE[])\n ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &z, &d, ROUNDING_MODE[])\n return z\n end\n function ($fJ){BF<:BigFloat}(a::BF, b::BF, c::BF, d::BF, e::BF)\n z = BF()\n ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &a, &b, ROUNDING_MODE[])\n ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &z, &c, ROUNDING_MODE[])\n ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &z, &d, ROUNDING_MODE[])\n ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &z, &e, ROUNDING_MODE[])\n return z\n end\n end\nend\n\nfunction -{BF<:BigFloat}(x::BF)\n z = BF()\n ccall((:mpfr_neg, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n return z\nend\n\nfunction sqrt{BF<:BigFloat}(x::BF)\n isnan(x) && return x\n z = BF()\n ccall((:mpfr_sqrt, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n if isnan(z)\n throw(DomainError())\n end\n return z\nend\n\nsqrt(x::BigInt) = sqrt(BF(x))\n\nfunction ^{BF<:BigFloat}(x::BF, y::BF)\n z = BF()\n ccall((:mpfr_pow, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &x, &y, ROUNDING_MODE[])\n return z\nend\n\nfunction ^{BF<:BigFloat}(x::BF, y::CulongMax)\n z = BF()\n ccall((:mpfr_pow_ui, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Culong, Int32), &z, &x, y, ROUNDING_MODE[])\n return z\nend\n\nfunction ^{BF<:BigFloat}(x::BF, y::ClongMax)\n z = BF()\n ccall((:mpfr_pow_si, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Clong, Int32), &z, &x, y, ROUNDING_MODE[])\n return z\nend\n\nfunction ^{BF<:BigFloat}(x::BF, y::BigInt)\n z = BF()\n ccall((:mpfr_pow_z, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BigInt}, Int32), &z, &x, &y, ROUNDING_MODE[])\n return z\nend\n\n^{BF<:BigFloat}(x::BF, y::Integer) = typemin(Clong) <= y <= typemax(Clong) ? x^Clong(y) : x^BigInt(y)\n^{BF<:BigFloat}(x::BF, y::Unsigned) = typemin(Culong) <= y <= typemax(Culong) ? x^Culong(y) : x^BigInt(y)\n\nfor f in (:exp, :exp2, :exp10, :expm1, :digamma, :erf, :erfc, :zeta,\n :cosh,:sinh,:tanh,:sech,:csch,:coth, :cbrt)\n @eval function $f{BF<:BigFloat}(x::BF)\n z = BF()\n ccall(($(string(:mpfr_,f)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n return z\n end\nend\n\n# return log(2)\nfunction big_ln2()\n c = BF()\n ccall((:mpfr_const_log2, :libmpfr), Cint, (Ptr{BF}, Int32),\n &c, MPFR.ROUNDING_MODE[])\n return c\nend\n\nfunction eta{BF<:BigFloat}(x::BF)\n x == 1 && return big_ln2()\n return -zeta(x) * expm1(big_ln2()*(1-x))\nend\n\nfunction airyai{BF<:BigFloat}(x::BF)\n z = BF()\n ccall((:mpfr_ai, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n return z\nend\nairy{BF<:BigFloat}(x::BF) = airyai(x)\n\nfunction ldexp{BF<:BigFloat}(x::BF, n::Clong)\n z = BF()\n ccall((:mpfr_mul_2si, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Clong, Int32), &z, &x, n, ROUNDING_MODE[])\n return z\nend\nfunction ldexp{BF<:BigFloat}(x::BF, n::Culong)\n z = BF()\n ccall((:mpfr_mul_2ui, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Culong, Int32), &z, &x, n, ROUNDING_MODE[])\n return z\nend\nldexp{BF<:BigFloat}(x::BF, n::ClongMax) = ldexp(x, convert(Clong, n))\nldexp{BF<:BigFloat}(x::BF, n::CulongMax) = ldexp(x, convert(Culong, n))\nldexp{BF<:BigFloat}(x::BF, n::Integer) = x*exp2(BF(n))\n\nfunction besselj0{BF<:BigFloat}(x::BF)\n z = BF()\n ccall((:mpfr_j0, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n return z\nend\n\nfunction besselj1{BF<:BigFloat}(x::BF)\n z = BF()\n ccall((:mpfr_j1, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n return z\nend\n\nfunction besselj{BF<:BigFloat}(n::Integer, x::BF)\n z = BF()\n ccall((:mpfr_jn, :libmpfr), Int32, (Ptr{BF}, Clong, Ptr{BF}, Int32), &z, n, &x, ROUNDING_MODE[])\n return z\nend\n\nfunction bessely0{BF<:BigFloat}(x::BF)\n if x < 0\n throw(DomainError())\n end\n z = BF()\n ccall((:mpfr_y0, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n return z\nend\n\nfunction bessely1{BF<:BigFloat}(x::BF)\n if x < 0\n throw(DomainError())\n end\n z = BF()\n ccall((:mpfr_y1, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n return z\nend\n\nfunction bessely{BF<:BigFloat}(n::Integer, x::BF)\n if x < 0\n throw(DomainError())\n end\n z = BF()\n ccall((:mpfr_yn, :libmpfr), Int32, (Ptr{BF}, Clong, Ptr{BF}, Int32), &z, n, &x, ROUNDING_MODE[])\n return z\nend\n\nfunction factorial{BF<:BigFloat}(x::BF)\n if x < 0 || !isinteger(x)\n throw(DomainError())\n end\n ui = convert(Culong, x)\n z = BF()\n ccall((:mpfr_fac_ui, :libmpfr), Int32, (Ptr{BF}, Culong, Int32), &z, ui, ROUNDING_MODE[])\n return z\nend\n\nfunction hypot{BF<:BigFloat}(x::BF, y::BF)\n z = BF()\n ccall((:mpfr_hypot, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &x, &y, ROUNDING_MODE[])\n return z\nend\n\nfor f in (:log, :log2, :log10)\n @eval function $f{BF<:BigFloat}(x::BF)\n if x < 0\n throw(DomainError())\n end\n z = BF()\n ccall(($(string(:mpfr_,f)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n return z\n end\nend\n\nfunction log1p{BF<:BigFloat}(x::BF)\n if x < -1\n throw(DomainError())\n end\n z = BF()\n ccall((:mpfr_log1p, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n return z\nend\n\nfunction max{BF<:BigFloat}(x::BF, y::BF)\n z = BF()\n ccall((:mpfr_max, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &x, &y, ROUNDING_MODE[])\n return z\nend\n\nfunction min{BF<:BigFloat}(x::BF, y::BF)\n z = BF()\n ccall((:mpfr_min, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &x, &y, ROUNDING_MODE[])\n return z\nend\n\nfunction modf{BF<:BigFloat}(x::BF)\n if isinf(x)\n return (BF(NaN), x)\n end\n zint = BF()\n zfloat = BF()\n ccall((:mpfr_modf, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &zint, &zfloat, &x, ROUNDING_MODE[])\n return (zfloat, zint)\nend\n\nfunction rem{BF<:BigFloat}(x::BF, y::BF)\n z = BF()\n ccall((:mpfr_fmod, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &x, &y, ROUNDING_MODE[])\n return z\nend\n\nfunction sum{BF<:BigFloat}(arr::AbstractArray{BF})\n z = BF(0)\n for i in arr\n ccall((:mpfr_add, :libmpfr), Int32,\n (Ptr{BF}, Ptr{BF}, Ptr{BF}, Cint),\n &z, &z, &i, 0)\n end\n return z\nend\n\n# Functions for which NaN results are converted to DomainError, following Base\nfor f in (:sin,:cos,:tan,:sec,:csc,\n :acos,:asin,:atan,:acosh,:asinh,:atanh, :gamma)\n @eval begin\n function ($f){BF<:BigFloat}(x::BF)\n if isnan(x)\n return x\n end\n z = BF()\n ccall(($(string(:mpfr_,f)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32), &z, &x, ROUNDING_MODE[])\n if isnan(z)\n throw(DomainError())\n end\n return z\n end\n end\nend\n\n# log of absolute value of gamma function\nconst lgamma_signp = Array{Cint}(1)\nfunction lgamma{BF<:BigFloat}(x::BF)\n z = BF()\n ccall((:mpfr_lgamma,:libmpfr), Cint, (Ptr{BF}, Ptr{Cint}, Ptr{BF}, Int32), &z, lgamma_signp, &x, ROUNDING_MODE[])\n return z\nend\n\nlgamma_r{BF<:BigFloat}(x::BF) = (lgamma(x), lgamma_signp[1])\n\nfunction atan2{BF<:BigFloat}(y::BF, x::BF)\n z = BF()\n ccall((:mpfr_atan2, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &y, &x, ROUNDING_MODE[])\n return z\nend\n\n# Utility functions\n=={BF<:BigFloat}(x::BF, y::BF) = ccall((:mpfr_equal_p, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &x, &y) != 0\n<={BF<:BigFloat}(x::BF, y::BF) = ccall((:mpfr_lessequal_p, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &x, &y) != 0\n>={BF<:BigFloat}(x::BF, y::BF) = ccall((:mpfr_greaterequal_p, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &x, &y) != 0\n<{BF<:BigFloat}(x::BF, y::BF) = ccall((:mpfr_less_p, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &x, &y) != 0\n>{BF<:BigFloat}(x::BF, y::BF) = ccall((:mpfr_greater_p, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &x, &y) != 0\n\nfunction cmp{BF<:BigFloat}(x::BF, y::BigInt)\n isnan(x) && throw(DomainError())\n ccall((:mpfr_cmp_z, :libmpfr), Int32, (Ptr{BF}, Ptr{BigInt}), &x, &y)\nend\nfunction cmp{BF<:BigFloat}(x::BF, y::ClongMax)\n isnan(x) && throw(DomainError())\n ccall((:mpfr_cmp_si, :libmpfr), Int32, (Ptr{BF}, Clong), &x, y)\nend\nfunction cmp{BF<:BigFloat}(x::BF, y::CulongMax)\n isnan(x) && throw(DomainError())\n ccall((:mpfr_cmp_ui, :libmpfr), Int32, (Ptr{BF}, Culong), &x, y)\nend\ncmp{BF<:BigFloat}(x::BF, y::Integer) = cmp(x,big(y))\ncmp{BF<:BigFloat}(x::Integer, y::BF) = -cmp(y,x)\n\nfunction cmp{BF<:BigFloat}(x::BF, y::CdoubleMax)\n (isnan(x) || isnan(y)) && throw(DomainError())\n ccall((:mpfr_cmp_d, :libmpfr), Int32, (Ptr{BF}, Cdouble), &x, y)\nend\ncmp{BF<:BigFloat}(x::CdoubleMax, y::BF) = -cmp(y,x)\n\n=={BF<:BigFloat}(x::BF, y::Integer) = !isnan(x) && cmp(x,y) == 0\n=={BF<:BigFloat}(x::Integer, y::BF) = y == x\n=={BF<:BigFloat}(x::BF, y::CdoubleMax) = !isnan(x) && !isnan(y) && cmp(x,y) == 0\n=={BF<:BigFloat}(x::CdoubleMax, y::BF) = y == x\n\n<{BF<:BigFloat}(x::BF, y::Integer) = !isnan(x) && cmp(x,y) < 0\n<{BF<:BigFloat}(x::Integer, y::BF) = !isnan(y) && cmp(y,x) > 0\n<{BF<:BigFloat}(x::BF, y::CdoubleMax) = !isnan(x) && !isnan(y) && cmp(x,y) < 0\n<{BF<:BigFloat}(x::CdoubleMax, y::BF) = !isnan(x) && !isnan(y) && cmp(y,x) > 0\n\n<={BF<:BigFloat}(x::BF, y::Integer) = !isnan(x) && cmp(x,y) <= 0\n<={BF<:BigFloat}(x::Integer, y::BF) = !isnan(y) && cmp(y,x) >= 0\n<={BF<:BigFloat}(x::BF, y::CdoubleMax) = !isnan(x) && !isnan(y) && cmp(x,y) <= 0\n<={BF<:BigFloat}(x::CdoubleMax, y::BF) = !isnan(x) && !isnan(y) && cmp(y,x) >= 0\n\nsignbit{BF<:BigFloat}(x::BF) = ccall((:mpfr_signbit, :libmpfr), Int32, (Ptr{BF},), &x) != 0\n\nfunction precision{BF<:BigFloat}(x::BF) # precision of an object of type BF\n return ccall((:mpfr_get_prec, :libmpfr), Clong, (Ptr{BF},), &x)\nend\n\nprecision{BF<:BigFloat}(::Type{BF}) = DEFAULT_PRECISION[end] # precision of the type BF itself\n\n\"\"\"\n setprecision([T=BF,] precision::Int)\n\nSet the precision (in bits) to be used for `T` arithmetic.\n\"\"\"\nfunction setprecision(::Type{BigFloat}, precision::Int)\n if precision < 2\n throw(DomainError())\n end\n DEFAULT_PRECISION[end] = precision\nend\n\nsetprecision(precision::Int) = setprecision(BigFloat, precision)\n\nmaxintfloat{BF<:BigFloat}(x::BF) = BF(2)^precision(x)\nmaxintfloat{BF<:BigFloat}(::Type{BF}) = BF(2)^precision(BF)\n\nto_mpfr(::RoundingMode{:Nearest}) = Cint(0)\nto_mpfr(::RoundingMode{:ToZero}) = Cint(1)\nto_mpfr(::RoundingMode{:Up}) = Cint(2)\nto_mpfr(::RoundingMode{:Down}) = Cint(3)\nto_mpfr(::RoundingMode{:FromZero}) = Cint(4)\n\nfunction from_mpfr(c::Integer)\n if c == 0\n return RoundNearest\n elseif c == 1\n return RoundToZero\n elseif c == 2\n return RoundUp\n elseif c == 3\n return RoundDown\n elseif c == 4\n return RoundFromZero\n else\n throw(ArgumentError(\"invalid MPFR rounding mode code: $c\"))\n end\n RoundingMode(c)\nend\n\nrounding_raw{BF<:BigFloat}(::Type{BF}) = ROUNDING_MODE[]\nsetrounding_raw{BF<:BigFloat}(::Type{BF},i::Integer) = ROUNDING_MODE[] = i\n\nrounding{BF<:BigFloat}(::Type{BF}) = from_mpfr(rounding_raw(BF))\nsetrounding{BF<:BigFloat}(::Type{BF},r::RoundingMode) = setrounding_raw(BF,to_mpfr(r))\n\nfunction copysign{BF<:BigFloat}(x::BF, y::BF)\n z = BF()\n ccall((:mpfr_copysign, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Ptr{BF}, Int32), &z, &x, &y, ROUNDING_MODE[])\n return z\nend\n\nfunction exponent{BF<:BigFloat}(x::BF)\n if x == 0 || !isfinite(x)\n throw(DomainError())\n end\n # The '- 1' is to make it work as Base.exponent\n return ccall((:mpfr_get_exp, :libmpfr), Clong, (Ptr{BF},), &x) - 1\nend\n\nfunction frexp{BF<:BigFloat}(x::BF)\n z = BF()\n c = Ref{Clong}()\n ccall((:mpfr_frexp, :libmpfr), Int32, (Ptr{Clong}, Ptr{BF}, Ptr{BF}, Cint), c, &z, &x, ROUNDING_MODE[])\n return (z, c[])\nend\n\nfunction significand{BF<:BigFloat}(x::BF)\n z = BF()\n c = Ref{Clong}()\n ccall((:mpfr_frexp, :libmpfr), Int32, (Ptr{Clong}, Ptr{BF}, Ptr{BF}, Cint), c, &z, &x, ROUNDING_MODE[])\n # Double the significand to make it work as Base.significand\n ccall((:mpfr_mul_si, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Clong, Int32), &z, &z, 2, ROUNDING_MODE[])\n return z\nend\n\nfunction isinteger{BF<:BigFloat}(x::BF)\n return ccall((:mpfr_integer_p, :libmpfr), Int32, (Ptr{BF},), &x) != 0\nend\n\nfor f in (:ceil, :floor, :trunc)\n @eval begin\n function ($f){BF<:BigFloat}(x::BF)\n z = BF()\n ccall(($(string(:mpfr_,f)), :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &x)\n return z\n end\n end\nend\n\nfunction round{BF<:BigFloat}(x::BF)\n z = BF()\n ccall((:mpfr_rint, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Cint), &z, &x, ROUNDING_MODE[])\n return z\nend\nfunction round{BF<:BigFloat}(x::BF,::RoundingMode{:NearestTiesAway})\n z = BF()\n ccall((:mpfr_round, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}), &z, &x)\n return z\nend\n\nfunction isinf{BF<:BigFloat}(x::BF)\n return ccall((:mpfr_inf_p, :libmpfr), Int32, (Ptr{BF},), &x) != 0\nend\n\nfunction isnan{BF<:BigFloat}(x::BF)\n return ccall((:mpfr_nan_p, :libmpfr), Int32, (Ptr{BF},), &x) != 0\nend\n\nisfinite{BF<:BigFloat}(x::BF) = !isinf(x) && !isnan(x)\n\n@eval typemax(::Type{BigFloat}) = $(BigFloat( Inf))\n@eval typemin(::Type{BigFloat}) = $(BigFloat(-Inf))\ntypemax{BF<:BigFloat}(::Type{BF}) = BF( Inf)\ntypemin{BF<:BigFloat}(::Type{BF}) = BF(-Inf)\n\nfunction nextfloat{BF<:BigFloat}(x::BF)\n z = BF()\n ccall((:mpfr_set, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32),\n &z, &x, ROUNDING_MODE[])\n ccall((:mpfr_nextabove, :libmpfr), Int32, (Ptr{BF},), &z) != 0\n return z\nend\n\nfunction prevfloat{BF<:BigFloat}(x::BF)\n z = BF()\n ccall((:mpfr_set, :libmpfr), Int32, (Ptr{BF}, Ptr{BF}, Int32),\n &z, &x, ROUNDING_MODE[])\n ccall((:mpfr_nextbelow, :libmpfr), Int32, (Ptr{BF},), &z) != 0\n return z\nend\n\neps{BF<:BigFloat}(::Type{BF}) = nextfloat(BF(1)) - BF(1)\n\nrealmin{BF<:BigFloat}(::Type{BF}) = nextfloat(zero(BF))\nrealmax{BF<:BigFloat}(::Type{BF}) = prevfloat(BF(Inf))\n\n\"\"\"\n setprecision(f::Function, [T=BF,] precision::Integer)\n\nChange the `T` arithmetic precision (in bits) for the duration of `f`.\nIt is logically equivalent to:\n\n old = precision(BF)\n setprecision(BF, precision)\n f()\n setprecision(BF, old)\n\nOften used as `setprecision(T, precision) do ... end`\n\"\"\"\nfunction setprecision{T}(f::Function, ::Type{T}, prec::Integer)\n old_prec = precision(T)\n setprecision(T, prec)\n try\n return f()\n finally\n setprecision(T, old_prec)\n end\nend\n\nsetprecision(f::Function, precision::Integer) = setprecision(f, BigFloat, precision)\n\nfunction string(x::BigFloat)\n # In general, the number of decimal places needed to read back the number exactly\n # is, excluding the most significant, ceil(log(10, 2^precision(x)))\n k = ceil(Int32, precision(x) * 0.3010299956639812)\n lng = k + Int32(8) # Add space for the sign, the most significand digit, the dot and the exponent\n buf = Array{UInt8}(lng + 1)\n # format strings are guaranteed to contain no NUL, so we don't use Cstring\n lng = ccall((:mpfr_snprintf,:libmpfr), Int32, (Ptr{UInt8}, Culong, Ptr{UInt8}, Ptr{BigFloat}...), buf, lng + 1, \"%.Re\", &x)\n if lng < k + 5 # print at least k decimal places\n lng = ccall((:mpfr_sprintf,:libmpfr), Int32, (Ptr{UInt8}, Ptr{UInt8}, Ptr{BigFloat}...), buf, \"%.$(k)Re\", &x)\n elseif lng > k + 8\n buf = Array{UInt8}(lng + 1)\n lng = ccall((:mpfr_snprintf,:libmpfr), Int32, (Ptr{UInt8}, Culong, Ptr{UInt8}, Ptr{BigFloat}...), buf, lng + 1, \"%.Re\", &x)\n end\n n = (1 <= x < 10 || -10 < x <= -1 || x == 0) ? lng - 4 : lng\n return String(buf[1:n])\nend\n\nfunction string{BF<:BigFloat}(x::BF)\n # In general, the number of decimal places needed to read back the number exactly\n # is, excluding the most significant, ceil(log(10, 2^precision(x)))\n k = ceil(Int32, precision(x) * 0.3010299956639812)\n lng = k + Int32(8) # Add space for the sign, the most significand digit, the dot and the exponent\n buf = Array{UInt8}(lng + 1)\n # format strings are guaranteed to contain no NUL, so we don't use Cstring\n lng = ccall((:mpfr_snprintf,:libmpfr), Int32, (Ptr{UInt8}, Culong, Ptr{UInt8}, Ptr{BF}...), buf, lng + 1, \"%.Re\", &x)\n if lng < k + 5 # print at least k decimal places\n lng = ccall((:mpfr_sprintf,:libmpfr), Int32, (Ptr{UInt8}, Ptr{UInt8}, Ptr{BF}...), buf, \"%.$(k)Re\", &x)\n elseif lng > k + 8\n buf = Array{UInt8}(lng + 1)\n lng = ccall((:mpfr_snprintf,:libmpfr), Int32, (Ptr{UInt8}, Culong, Ptr{UInt8}, Ptr{BF}...), buf, lng + 1, \"%.Re\", &x)\n end\n n = (1 <= x < 10 || -10 < x <= -1 || x == 0) ? lng - 4 : lng\n return String(buf[1:n])\nend\n\nprint(io::IO, b::BigFloat) = print(io, string(b))\nshow(io::IO, b::BigFloat) = print(io, string(b))\nprint{BF<:BigFloat}(io::IO, b::BF) = print(io, string(b))\nshow{BF<:BigFloat}(io::IO, b::BF) = print(io, string(b))\n\n\n# get/set exponent min/max\nget_emax() = ccall((:mpfr_get_emax, :libmpfr), Clong, ())\nget_emax_min() = ccall((:mpfr_get_emax_min, :libmpfr), Clong, ())\nget_emax_max() = ccall((:mpfr_get_emax_max, :libmpfr), Clong, ())\n\nget_emin() = ccall((:mpfr_get_emin, :libmpfr), Clong, ())\nget_emin_min() = ccall((:mpfr_get_emin_min, :libmpfr), Clong, ())\nget_emin_max() = ccall((:mpfr_get_emin_max, :libmpfr), Clong, ())\n\nset_emax!(x) = ccall((:mpfr_set_emax, :libmpfr), Void, (Clong,), x)\nset_emin!(x) = ccall((:mpfr_set_emin, :libmpfr), Void, (Clong,), x)\n\nfunction Base.deepcopy_internal(x::BigFloat, stackdict::ObjectIdDict)\n if haskey(stackdict, x)\n return stackdict[x]\n end\n N = precision(x)\n y = BigFloat(zero(Clong), zero(Cint), zero(Clong), C_NULL)\n ccall((:mpfr_init2,:libmpfr), Void, (Ptr{BigFloat}, Clong), &y, N)\n finalizer(y, cglobal((:mpfr_clear, :libmpfr)))\n ccall((:mpfr_set, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32),\n &y, &x, ROUNDING_MODE[])\n stackdict[x] = y\n return y\nend\n\nconvert{BF<:BigFloat}(::Type{BF}, x::BF) = x\nfunction convert{BF1<:BigFloat, BF2<:BigFloat}(::Type{BF1}, x::BF2)\n return parse(BF1, string(x))\nend\nfunction promote_rule{BF1<:BigFloat, BF2<:BigFloat}(::Type{BF1}, ::Type{BF2})\n return ifelse(precision(BF1) > precision(BF2), BF2, BF1)\nend\n\n(+){BF1<:BigFloat, BF2<:BigFloat}(a::BF1, b::BF2) = (+)(promote(a,b)...)\n(-){BF1<:BigFloat, BF2<:BigFloat}(a::BF1, b::BF2) = (-)(promote(a,b)...)\n(*){BF1<:BigFloat, BF2<:BigFloat}(a::BF1, b::BF2) = (*)(promote(a,b)...)\n(/){BF1<:BigFloat, BF2<:BigFloat}(a::BF1, b::BF2) = (/)(promote(a,b)...)\n(hypot){BF1<:BigFloat, BF2<:BigFloat}(a::BF1, b::BF2) = (hypot)(promote(a,b)...)\n(^){BF1<:BigFloat, BF2<:BigFloat}(a::BF1, b::BF2) = (^)(promote(a,b)...)\n\n\nend #module\n\n", "meta": {"hexsha": "feae18edcc3dccb5642a0929c23252d396ecb209", "size": 34696, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MPFR3.jl", "max_stars_repo_name": "JuliaNumberTypes/MPFR3.jl", "max_stars_repo_head_hexsha": "6a2641b28c3abd3fcf5401e660b7b29401883cea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MPFR3.jl", "max_issues_repo_name": "JuliaNumberTypes/MPFR3.jl", "max_issues_repo_head_hexsha": "6a2641b28c3abd3fcf5401e660b7b29401883cea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MPFR3.jl", "max_forks_repo_name": "JuliaNumberTypes/MPFR3.jl", "max_forks_repo_head_hexsha": "6a2641b28c3abd3fcf5401e660b7b29401883cea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7690721649, "max_line_length": 131, "alphanum_fraction": 0.5915379294, "num_tokens": 13055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24147947637463404}} {"text": "\n\nimport Base: ==, convert, Dict\n\nconst zklmTuple = NamedTuple{(:z, :k, :l, :m), Tuple{Int16, IntS, IntS, IntS}}\n\n\"\"\"\n`AList` : datastructure to help compute the A_zklm density projections\n\n* `i2zklm` : list of all admissible `(z,k,l,m)` tuples\n* `zklm2i` : dictionary with (z,k,l,m) keys to compute the map `(z,k,l,m) -> i`\n* `firstz` : `firstz[iz]` stores the first index in the A_zklm array for with\n z = zi. This can be used to iterate over all A entries for which\n z = zi. (they are sorted by z first)\n\"\"\"\nstruct AList\n i2zklm::Vector{zklmTuple}\n zklm2i::Dict{zklmTuple, IntS}\n firstz::Vector{IntS}\nend\n\n# --------------(de-)serialisation----------------------------------------\nDict(alist::AList) = Dict(\"__id__\" => \"SHIPs_AList\",\n \"i2zklm\" => zklm2vec.(alist.i2zklm))\nAList(D::Dict) = AList(vec2zklm.(D[\"i2zklm\"]))\nzklm2vec(t) = [t.z, t.k, t.l, t.m]\nvec2zklm(v) = (z=Int16(v[1]), k=IntS(v[2]), l=IntS(v[3]), m=IntS(v[4]))\n==(al1::AList, al2::AList) = (al1.i2zklm == al2.i2zklm)\n# ------------------------------------------------------------------------\n\nBase.length(alist::AList) = length(alist.i2zklm)\nBase.getindex(alist::AList, i::Integer) = alist.i2zklm[i]\nBase.getindex(alist::AList, zklm::zklmTuple) = alist.zklm2i[zklm]\n\nalloc_A(alist::AList, T=Float64) = zeros(Complex{T}, length(alist))\n\nfunction AList(zklmlist::AbstractVector{zklmTuple})\n # sort the tuples - by z, then k, then l, then m\n i2zklm = sort(zklmlist)\n # create the inverse mapping\n zklm2i = Dict{zklmTuple, IntS}()\n for i = 1:length(i2zklm)\n zklm2i[i2zklm[i]] = IntS(i)\n end\n # find the first index for each z\n zmax = maximum( a.z for a in i2zklm )\n firstz = [ findfirst([a.z == iz for a in i2zklm])\n for iz = 1:zmax ]\n return AList( i2zklm, zklm2i, [firstz; length(i2zklm)+1] )\nend\n\n\n\"\"\"\nThis fills the A-array stored in tmp with the A_zklm density projections in\nthe order specified by AList. It also evaluates the radial and angular basis\nfunctions along the way.\n\"\"\"\nfunction precompute_A!(A, tmp, alist, Rs, Zs, ship)\n fill!(A, 0)\n for (R, Z) in zip(Rs, Zs)\n # evaluate the r-basis and the R̂-basis for the current neighbour at R\n eval_basis!(tmp.J, tmp.tmpJ, ship.J, norm(R))\n eval_basis!(tmp.Y, tmp.tmpY, ship.SH, R)\n # add the contributions to the A_zklm\n iz = z2i(ship, Z)\n for i = alist.firstz[iz]:(alist.firstz[iz+1]-1)\n zklm = alist[i]\n A[i] += tmp.J[zklm.k+1] * tmp.Y[index_y(zklm.l, zklm.m)]\n end\n end\n return A\nend\n\n\n\n\nfunction precompute_dA!(A, dA, tmp, alist, Rs, Zs, ship)\n fill!(A, 0)\n fill!(dA, zero(eltype(dA)))\n for (iR, (R, Z)) in enumerate(zip(Rs, Zs))\n # precompute the derivatives of the Jacobi polynomials and Ylms\n eval_basis_d!(tmp.J, tmp.dJ, tmp.tmpJ, ship.J, norm(R))\n eval_basis_d!(tmp.Y, tmp.dY, tmp.tmpY, ship.SH, R)\n # deduce the A and dA values\n iz = z2i(ship, Z)\n R̂ = R / norm(R)\n for i = alist.firstz[iz]:(alist.firstz[iz+1]-1)\n zklm = alist[i]\n ik = zklm.k+1; iy = index_y(zklm.l, zklm.m)\n A[i] += tmp.J[ik] * tmp.Y[iy]\n # and into dA # grad_phi_Rj(R, iR, zklm, tmp)\n ∇ϕ_zklm = tmp.dJ[ik] * tmp.Y[iy] * R̂ + tmp.J[ik] * tmp.dY[iy]\n dA[iR, i] = ∇ϕ_zklm\n end\n end\n return dA\nend\n\n# ---------\n\n\n\"\"\"\n`AAList` : datastructure to help compute the A_𝐳𝐤𝐥𝐦 = ∏ A_zklm\n\n* `i2Aidx` : indices in AList of the zklms to avoid the Dict lookup\n* `len` : len[i] is the number of relevant entries of i2zklm[i,:]\n i.e. the body-order of this entry\n* `zklm2i` : dictionary of all (z,k,l,m) tuples to compute the\n map `(zz,kk,ll,mm) -> i`\n* `firstz` : `firstz[iz]` stores the first index in the A_zklm array for with\n z = zi. This can be used to iterate over all A entries for which\n z = zi. (they are sorted by z first)\n\"\"\"\nstruct AAList\n i2Aidx::Matrix{IntS} # where in A can we find these\n len::Vector{IntS} # body-order\n zklm2i::Dict{Any, IntS} # inverse mapping\nend\n\n# --------------(de-)serialisation----------------------------------------\n\n==\nfunction Dict(aalist::AAList)\n ZKLM_list = Vector{Any}(undef, length(aalist))\n for (zzkkllmm, i) in aalist.zklm2i\n ZKLM_list[i] = zzkkllmm\n end\n return Dict(\"__id__\" => \"SHIPs_AAList\", \"ZKLM_list\" => ZKLM_list)\nend\nzzkkllmm2vec(zzkkllmm) = Vector.([zzkkllmm...])\nvec2zzkkllmm(v) = (SVector(Int16.(v[1])...),\n SVector(IntS.(v[2])...),\n SVector(IntS.(v[3])...),\n SVector(IntS.(v[4])...))\nAAList(D::Dict, alist) = AAList(vec2zzkkllmm.(D[\"ZKLM_list\"]), alist)\n==(aal1::AAList, aal2::AAList) = (aal1.i2Aidx == aal2.i2Aidx)\n# ------------------------------------------------------------------------\n\n\nbodyorder(aalist::AAList) = maximum(aalist.len) + 1\n\nBase.length(aalist::AAList) = length(aalist.len)\n\nBase.getindex(aalist::AAList, t::Tuple) = aalist.zklm2i[t]\n\nalloc_AA(aalist::AAList, T = Float64) = zeros(Complex{T}, length(aalist))\n\n\"\"\"\n`AAList(ZKLM_list, alist)` : standard AAList constructor,\n* `ZKLM_list` : a collection of (izz=?, kk=?, ll=?, mm=?) tuples\n* `alist` a compatible `AList`\n\"\"\"\nfunction AAList(ZKLM_list, alist)\n BO = maximum(ν -> length(ν[1]), ZKLM_list) # body-order -> size of iAidx\n\n # create arrays to construct AAList\n iAidx = IntS[]\n len = IntS[]\n zklm2i = Dict{Any, IntS}()\n\n idx = 0\n for (izz, kk, ll, mm) in ZKLM_list\n # store in the index of the current row in the reverse map\n idx += 1\n zklm2i[(izz, kk, ll, mm)] = idx\n # store the body-order of the current ∏A function\n push!(len, length(ll))\n\n # fill the row of the i2Aidx matrix\n for α = 1:length(ll)\n zklm = (z=izz[α], k=kk[α], l=ll[α], m=IntS(mm[α]))\n iA = alist[zklm]\n push!(iAidx, iA)\n end\n # fill up the iAidx vector with zeros up to the body-order\n # this will create 0 entries in the matrix after reshaping\n for α = (length(ll)+1):BO\n push!(iAidx, 0)\n end\n end\n return AAList( reshape(iAidx, (BO, idx))', len, zklm2i )\nend\n\n\nfunction precompute_AA!(AA, A, aalist) # tmp, ship::SHIPBasis{T}, iz0) where {T}\n fill!(AA, 1)\n for i = 1:length(aalist)\n for α = 1:aalist.len[i]\n iA = aalist.i2Aidx[i, α]\n AA[i] *= A[iA]\n end\n end\n return nothing\nend\n\n\n# --------------------------------------------------------\n# this section of functions is for computing\n# ∂∏A / ∂R_j\n\n# function grad_phi_Rj(Rj, j, zklm, tmp)\n# ik = zklm.k + 1\n# iy = index_y(zklm.l, zklm.m)\n# return ( tmp.dJJ[j, ik] * tmp.YY[j, iy] * (Rj/norm(Rj))\n# + tmp.JJ[j, ik] * tmp.dYY[j, iy] )\n# end\n\nfunction grad_AA_Ab(iAA, b, alist, aalist, A)\n g = one(eltype(A))\n for a = 1:aalist.len[iAA]\n if a != b\n iA = aalist.i2Aidx[iAA, a]\n g *= A[iA]\n end\n end\n return g\nend\n\nfunction grad_AAi_Rj(iAA, j, Rj::JVec{T}, izj::Integer,\n alist, aalist, A, AA, dA, tmp) where {T}\n g = zero(JVec{Complex{T}})\n for b = 1:aalist.len[iAA] # body-order\n # A_{n_b} = A[iA]\n iA = aalist.i2Aidx[iAA, b]\n # daa_dab = ∂(∏A_{n_a}) / ∂A_{n_b}\n daa_dab = grad_AA_Ab(iAA, b, alist, aalist, A)\n zklm = alist[iA] # (zklm corresponding to A_{n_b})\n ∇ϕ_zklm = dA[j, iA] # grad_phi_Rj(Rj, j, zklm, tmp)\n g += daa_dab * ∇ϕ_zklm\n end\n return g\nend\n\nfunction grad_AA_Rj!(tmp, ship, j, Rs, Zs, iz0) where {T}\n for iAA = 1:length(ship.aalists[iz0])\n # g = ∂(∏_a A_a) / ∂Rj \n tmp.dAAj[iz0][iAA] = grad_AAi_Rj(iAA, j, Rs[j], z2i(ship, Zs[j]),\n ship.alists[iz0], ship.aalists[iz0],\n tmp.A[iz0], tmp.AA[iz0], tmp.dA[iz0],\n tmp)\n end\n return tmp.dAAj[iz0]\nend\n\n\n# --------------------------------------------------------\n\n\"\"\"\nconvert the \"old\" `(NuZ, ZKL)` format into the simpler (zz, kk, ll, mm)\nformat, and at the same time extract the one-particle basis (z, k, l, m)\n\"\"\"\nfunction alists_from_bgrps(bgrps::Tuple)\n NZ = length(bgrps)\n zzkkllmm_list = [ Tuple[] for _=1:NZ ]\n zklm_set = [ Set() for _=1:NZ ]\n for iz0 = 1:NZ\n for (izz, kk, ll) in bgrps[iz0], mm in _mrange(ll)\n push!(zzkkllmm_list[iz0], (izz, kk, ll, IntS.(mm)))\n for α = 1:length(ll)\n zklm = (z=izz[α], k=kk[α], l=ll[α], m=IntS(mm[α]))\n push!(zklm_set[iz0], zklm)\n end\n end\n end\n\n alist = ntuple(iz0 -> AList([ zklm for zklm in collect(zklm_set[iz0]) ]), NZ)\n aalist = ntuple(iz0 -> AAList(zzkkllmm_list[iz0], alist[iz0]), NZ)\n return alist, aalist\nend\n\n\n# --------------------------------------------------------\n\nusing SparseArrays: SparseMatrixCSC\n\nfunction _my_mul!(C::AbstractVector, A::SparseMatrixCSC, B::AbstractVector)\n A.n == length(B) || throw(DimensionMismatch())\n A.m == length(C) || throw(DimensionMismatch())\n nzv = A.nzval\n rv = A.rowval\n fill!(C, zero(eltype(C)))\n @inbounds for col = 1:A.n\n b = B[col]\n for j = A.colptr[col]:(A.colptr[col + 1] - 1)\n C[rv[j]] += nzv[j] * b\n end\n end\n return C\nend\n", "meta": {"hexsha": "fb90f4385ed1078b4c530b26eebad9a051b9e048", "size": 9231, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Alist.jl", "max_stars_repo_name": "cortner/SHIPs", "max_stars_repo_head_hexsha": "77f994c47d50f268968c8b41f412594122c66adc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-10-15T19:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T07:47:10.000Z", "max_issues_repo_path": "src/Alist.jl", "max_issues_repo_name": "cortner/SHIPs", "max_issues_repo_head_hexsha": "77f994c47d50f268968c8b41f412594122c66adc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-06-21T10:33:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-15T16:52:11.000Z", "max_forks_repo_path": "src/Alist.jl", "max_forks_repo_name": "cortner/SHIPs", "max_forks_repo_head_hexsha": "77f994c47d50f268968c8b41f412594122c66adc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-29T14:27:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-05T19:37:46.000Z", "avg_line_length": 31.8310344828, "max_line_length": 81, "alphanum_fraction": 0.5598526703, "num_tokens": 3274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24147947637463404}} {"text": "# By default, Julia/LLVM does not use fused multiply-add operations (FMAs).\n# Since these FMAs can increase the performance of many numerical algorithms,\n# we need to opt-in explicitly.\n# See https://ranocha.de/blog/Optimizing_EC_Trixi for further details.\n@muladd begin\n\n\n# TODO: Taal refactor\n# - analysis_interval part as PeriodicCallback called after a certain amount of simulation time\n\"\"\"\n AnalysisCallback(semi; interval=0,\n save_analysis=false,\n output_directory=\"out\",\n analysis_filename=\"analysis.dat\",\n extra_analysis_errors=Symbol[],\n extra_analysis_integrals=())\n\nAnalyze a numerical solution every `interval` time steps and print the\nresults to the screen. If `save_analysis`, the results are also saved in\n`joinpath(output_directory, analysis_filename)`.\n\nAdditional errors can be computed, e.g. by passing `extra_analysis_errors = [:primitive]`.\n\nFurther scalar functions `func` in `extra_analysis_integrals` are applied to the numerical\nsolution and integrated over the computational domain.\nSee `Trixi.analyze`, `Trixi.pretty_form_utf`, `Trixi.pretty_form_ascii` for further\ninformation on how to create custom analysis quantities.\n\"\"\"\nmutable struct AnalysisCallback{Analyzer, AnalysisIntegrals, InitialStateIntegrals, Cache}\n start_time::Float64\n interval::Int\n save_analysis::Bool\n output_directory::String\n analysis_filename::String\n analyzer::Analyzer\n analysis_errors::Vector{Symbol}\n analysis_integrals::AnalysisIntegrals\n initial_state_integrals::InitialStateIntegrals\n cache::Cache\nend\n\n\n# TODO: Taal bikeshedding, implement a method with less information and the signature\n# function Base.show(io::IO, analysis_callback::AnalysisCallback)\n# end\nfunction Base.show(io::IO, ::MIME\"text/plain\", cb::DiscreteCallback{<:Any, <:AnalysisCallback})\n @nospecialize cb # reduce precompilation time\n\n if get(io, :compact, false)\n show(io, cb)\n else\n analysis_callback = cb.affect!\n\n setup = Pair{String,Any}[\n \"interval\" => analysis_callback.interval,\n \"analyzer\" => analysis_callback.analyzer,\n ]\n for (idx, error) in enumerate(analysis_callback.analysis_errors)\n push!(setup, \"│ error \" * string(idx) => error)\n end\n for (idx, integral) in enumerate(analysis_callback.analysis_integrals)\n push!(setup, \"│ integral \" * string(idx) => integral)\n end\n push!(setup, \"save analysis to file\" => analysis_callback.save_analysis ? \"yes\" : \"no\")\n if analysis_callback.save_analysis\n push!(setup, \"│ filename\" => analysis_callback.analysis_filename)\n push!(setup, \"│ output directory\" => abspath(normpath(analysis_callback.output_directory)))\n end\n summary_box(io, \"AnalysisCallback\", setup)\n end\nend\n\n\nfunction AnalysisCallback(semi::AbstractSemidiscretization; kwargs...)\n mesh, equations, solver, cache = mesh_equations_solver_cache(semi)\n AnalysisCallback(mesh, equations, solver, cache; kwargs...)\nend\n\nfunction AnalysisCallback(mesh, equations::AbstractEquations, solver, cache;\n interval=0,\n save_analysis=false,\n output_directory=\"out\",\n analysis_filename=\"analysis.dat\",\n extra_analysis_errors=Symbol[],\n analysis_errors=union(default_analysis_errors(equations), extra_analysis_errors),\n extra_analysis_integrals=(),\n analysis_integrals=union(default_analysis_integrals(equations), extra_analysis_integrals),\n RealT=real(solver),\n uEltype=eltype(cache.elements),\n kwargs...)\n # Decide when the callback is activated.\n # With error-based step size control, some steps can be rejected. Thus,\n # `integrator.iter >= integrator.destats.naccept`\n # (total #steps) (#accepted steps)\n # We need to check the number of accepted steps since callbacks are not\n # activated after a rejected step.\n condition = (u, t, integrator) -> interval > 0 && ( (integrator.destats.naccept % interval == 0 &&\n !(integrator.destats.naccept == 0 && integrator.iter > 0)) ||\n isfinished(integrator))\n\n analyzer = SolutionAnalyzer(solver; kwargs...)\n cache_analysis = create_cache_analysis(analyzer, mesh, equations, solver, cache, RealT, uEltype)\n\n analysis_callback = AnalysisCallback(0.0, interval, save_analysis, output_directory, analysis_filename,\n analyzer,\n analysis_errors, Tuple(analysis_integrals),\n SVector(ntuple(_ -> zero(uEltype), Val(nvariables(equations)))),\n cache_analysis)\n\n DiscreteCallback(condition, analysis_callback,\n save_positions=(false,false),\n initialize=initialize!)\nend\n\n\nfunction initialize!(cb::DiscreteCallback{Condition,Affect!}, u_ode, t, integrator) where {Condition, Affect!<:AnalysisCallback}\n semi = integrator.p\n initial_state_integrals = integrate(u_ode, semi)\n _, equations, _, _ = mesh_equations_solver_cache(semi)\n\n analysis_callback = cb.affect!\n analysis_callback.initial_state_integrals = initial_state_integrals\n @unpack save_analysis, output_directory, analysis_filename, analysis_errors, analysis_integrals = analysis_callback\n\n if save_analysis && mpi_isroot()\n mkpath(output_directory)\n\n # write header of output file\n open(joinpath(output_directory, analysis_filename), \"w\") do io\n @printf(io, \"#%-8s\", \"timestep\")\n @printf(io, \" %-14s\", \"time\")\n @printf(io, \" %-14s\", \"dt\")\n if :l2_error in analysis_errors\n for v in varnames(cons2cons, equations)\n @printf(io, \" %-14s\", \"l2_\" * v)\n end\n end\n if :linf_error in analysis_errors\n for v in varnames(cons2cons, equations)\n @printf(io, \" %-14s\", \"linf_\" * v)\n end\n end\n if :conservation_error in analysis_errors\n for v in varnames(cons2cons, equations)\n @printf(io, \" %-14s\", \"cons_\" * v)\n end\n end\n if :residual in analysis_errors\n for v in varnames(cons2cons, equations)\n @printf(io, \" %-14s\", \"res_\" * v)\n end\n end\n if :l2_error_primitive in analysis_errors\n for v in varnames(cons2prim, equations)\n @printf(io, \" %-14s\", \"l2_\" * v)\n end\n end\n if :linf_error_primitive in analysis_errors\n for v in varnames(cons2prim, equations)\n @printf(io, \" %-14s\", \"linf_\" * v)\n end\n end\n\n for quantity in analysis_integrals\n @printf(io, \" %-14s\", pretty_form_ascii(quantity))\n end\n\n println(io)\n end\n\n end\n\n analysis_callback.start_time = time_ns()\n analysis_callback(integrator)\n return nothing\nend\n\n\n# TODO: Taal refactor, allow passing an IO object (which could be devnull to avoid cluttering the console)\nfunction (analysis_callback::AnalysisCallback)(integrator)\n semi = integrator.p\n mesh, equations, solver, cache = mesh_equations_solver_cache(semi)\n @unpack dt, t = integrator\n iter = integrator.destats.naccept\n\n runtime_absolute = 1.0e-9 * (time_ns() - analysis_callback.start_time)\n runtime_relative = 1.0e-9 * take!(semi.performance_counter) / ndofs(semi)\n\n @trixi_timeit timer() \"analyze solution\" begin\n # General information\n mpi_println()\n mpi_println(\"─\"^100)\n # TODO: Taal refactor, polydeg is specific to DGSEM\n mpi_println(\" Simulation running '\", get_name(equations), \"' with \", summary(solver))\n mpi_println(\"─\"^100)\n mpi_println(\" #timesteps: \" * @sprintf(\"% 14d\", iter) *\n \" \" *\n \" run time: \" * @sprintf(\"%10.8e s\", runtime_absolute))\n mpi_println(\" Δt: \" * @sprintf(\"%10.8e\", dt) *\n \" \" *\n \" time/DOF/rhs!: \" * @sprintf(\"%10.8e s\", runtime_relative))\n mpi_println(\" sim. time: \" * @sprintf(\"%10.8e\", t))\n mpi_println(\" #DOF: \" * @sprintf(\"% 14d\", ndofs(semi)))\n mpi_println(\" #elements: \" * @sprintf(\"% 14d\", nelements(mesh, solver, cache)))\n\n # Level information (only show for AMR)\n print_amr_information(integrator.opts.callback, mesh, solver, cache)\n mpi_println()\n\n # Open file for appending and store time step and time information\n if mpi_isroot() && analysis_callback.save_analysis\n io = open(joinpath(analysis_callback.output_directory, analysis_callback.analysis_filename), \"a\")\n @printf(io, \"% 9d\", iter)\n @printf(io, \" %10.8e\", t)\n @printf(io, \" %10.8e\", dt)\n else\n io = devnull\n end\n\n # Calculate current time derivative (needed for semidiscrete entropy time derivative, residual, etc.)\n du_ode = first(get_tmp_cache(integrator))\n @notimeit timer() rhs!(du_ode, integrator.u, semi, t)\n u = wrap_array(integrator.u, mesh, equations, solver, cache)\n du = wrap_array(du_ode, mesh, equations, solver, cache)\n l2_error, linf_error = analysis_callback(io, du, u, integrator.u, t, semi)\n\n mpi_println(\"─\"^100)\n mpi_println()\n\n # Add line break and close analysis file if it was opened\n if mpi_isroot() && analysis_callback.save_analysis\n # This resolves a possible type instability introduced above, since `io`\n # can either be an `IOStream` or `devnull`, but we know that it must be\n # an `IOStream here`.\n println(io::IOStream)\n close(io::IOStream)\n end\n end\n\n # avoid re-evaluating possible FSAL stages\n u_modified!(integrator, false)\n\n # Return errors for EOC analysis\n return l2_error, linf_error\nend\n\n\n# This method is just called internally from `(analysis_callback::AnalysisCallback)(integrator)`\n# and serves as a function barrier. Additionally, it makes the code easier to profile and optimize.\nfunction (analysis_callback::AnalysisCallback)(io, du, u, u_ode, t, semi)\n @unpack analyzer, analysis_errors, analysis_integrals = analysis_callback\n cache_analysis = analysis_callback.cache\n _, equations, _, _ = mesh_equations_solver_cache(semi)\n\n # Calculate and print derived quantities (error norms, entropy etc.)\n # Variable names required for L2 error, Linf error, and conservation error\n if any(q in analysis_errors for q in\n (:l2_error, :linf_error, :conservation_error, :residual)) && mpi_isroot()\n print(\" Variable: \")\n for v in eachvariable(equations)\n @printf(\" %-14s\", varnames(cons2cons, equations)[v])\n end\n println()\n end\n\n # Calculate L2/Linf errors, which are also returned\n l2_error, linf_error = calc_error_norms(u_ode, t, analyzer, semi, cache_analysis)\n\n if mpi_isroot()\n # L2 error\n if :l2_error in analysis_errors\n print(\" L2 error: \")\n for v in eachvariable(equations)\n @printf(\" % 10.8e\", l2_error[v])\n @printf(io, \" % 10.8e\", l2_error[v])\n end\n println()\n end\n\n # Linf error\n if :linf_error in analysis_errors\n print(\" Linf error: \")\n for v in eachvariable(equations)\n @printf(\" % 10.8e\", linf_error[v])\n @printf(io, \" % 10.8e\", linf_error[v])\n end\n println()\n end\n end\n\n\n # Conservation errror\n if :conservation_error in analysis_errors\n @unpack initial_state_integrals = analysis_callback\n state_integrals = integrate(u_ode, semi)\n\n if mpi_isroot()\n print(\" |∑U - ∑U₀|: \")\n for v in eachvariable(equations)\n err = abs(state_integrals[v] - initial_state_integrals[v])\n @printf(\" % 10.8e\", err)\n @printf(io, \" % 10.8e\", err)\n end\n println()\n end\n end\n\n # Residual (defined here as the vector maximum of the absolute values of the time derivatives)\n if :residual in analysis_errors\n mpi_print(\" max(|Uₜ|): \")\n for v in eachvariable(equations)\n # Calculate maximum absolute value of Uₜ\n res = maximum(abs, view(du, v, ..))\n if mpi_isparallel()\n # TODO: Debugging, here is a type instability\n global_res = MPI.Reduce!(Ref(res), max, mpi_root(), mpi_comm())\n if mpi_isroot()\n res::eltype(du) = global_res[]\n end\n end\n if mpi_isroot()\n @printf(\" % 10.8e\", res)\n @printf(io, \" % 10.8e\", res)\n end\n end\n mpi_println()\n end\n\n # L2/L∞ errors of the primitive variables\n if :l2_error_primitive in analysis_errors || :linf_error_primitive in analysis_errors\n l2_error_prim, linf_error_prim = calc_error_norms(cons2prim, u_ode, t, analyzer, semi, cache_analysis)\n\n if mpi_isroot()\n print(\" Variable: \")\n for v in eachvariable(equations)\n @printf(\" %-14s\", varnames(cons2prim, equations)[v])\n end\n println()\n\n # L2 error\n if :l2_error_primitive in analysis_errors\n print(\" L2 error prim.: \")\n for v in eachvariable(equations)\n @printf(\"%10.8e \", l2_error_prim[v])\n @printf(io, \" % 10.8e\", l2_error_prim[v])\n end\n println()\n end\n\n # L∞ error\n if :linf_error_primitive in analysis_errors\n print(\" Linf error pri.:\")\n for v in eachvariable(equations)\n @printf(\"%10.8e \", linf_error_prim[v])\n @printf(io, \" % 10.8e\", linf_error_prim[v])\n end\n println()\n end\n end\n end\n\n # additional integrals\n analyze_integrals(analysis_integrals, io, du, u, t, semi)\n\n return l2_error, linf_error\nend\n\n\n# Print level information only if AMR is enabled\nfunction print_amr_information(callbacks, mesh, solver, cache)\n\n # Return early if there is nothing to print\n uses_amr(callbacks) || return nothing\n\n levels = Vector{Int}(undef, nelements(solver, cache))\n min_level = typemax(Int)\n max_level = typemin(Int)\n for element in eachelement(solver, cache)\n current_level = mesh.tree.levels[cache.elements.cell_ids[element]]\n levels[element] = current_level\n min_level = min(min_level, current_level)\n max_level = max(max_level, current_level)\n end\n\n for level = max_level:-1:min_level+1\n mpi_println(\" ├── level $level: \" * @sprintf(\"% 14d\", count(==(level), levels)))\n end\n mpi_println(\" └── level $min_level: \" * @sprintf(\"% 14d\", count(==(min_level), levels)))\n\n return nothing\nend\n\n# Print level information only if AMR is enabled\nfunction print_amr_information(callbacks, mesh::P4estMesh, solver, cache)\n\n # Return early if there is nothing to print\n uses_amr(callbacks) || return nothing\n\n elements_per_level = zeros(P4EST_MAXLEVEL + 1)\n\n for tree in unsafe_wrap_sc(p4est_tree_t, mesh.p4est.trees)\n elements_per_level .+= tree.quadrants_per_level\n end\n\n min_level = findfirst(i -> i > 0, elements_per_level) - 1\n max_level = findlast(i -> i > 0, elements_per_level) - 1\n\n for level = max_level:-1:min_level+1\n mpi_println(\" ├── level $level: \" * @sprintf(\"% 14d\", elements_per_level[level + 1]))\n end\n mpi_println(\" └── level $min_level: \" * @sprintf(\"% 14d\", elements_per_level[min_level + 1]))\n\n return nothing\nend\n\n\n# Iterate over tuples of analysis integrals in a type-stable way using \"lispy tuple programming\".\nfunction analyze_integrals(analysis_integrals::NTuple{N,Any}, io, du, u, t, semi) where {N}\n\n # Extract the first analysis integral and process it; keep the remaining to be processed later\n quantity = first(analysis_integrals)\n remaining_quantities = Base.tail(analysis_integrals)\n\n res = analyze(quantity, du, u, t, semi)\n if mpi_isroot()\n @printf(\" %-12s:\", pretty_form_utf(quantity))\n @printf(\" % 10.8e\", res)\n @printf(io, \" % 10.8e\", res)\n end\n mpi_println()\n\n # Recursively call this method with the unprocessed integrals\n analyze_integrals(remaining_quantities, io, du, u, t, semi)\n return nothing\nend\n\n# terminate the type-stable iteration over tuples\nfunction analyze_integrals(analysis_integrals::Tuple{}, io, du, u, t, semi)\n nothing\nend\n\n\n# used for error checks and EOC analysis\nfunction (cb::DiscreteCallback{Condition,Affect!})(sol) where {Condition, Affect!<:AnalysisCallback}\n analysis_callback = cb.affect!\n semi = sol.prob.p\n @unpack analyzer = analysis_callback\n cache_analysis = analysis_callback.cache\n\n l2_error, linf_error = calc_error_norms(sol.u[end], sol.t[end], analyzer, semi, cache_analysis)\n (; l2=l2_error, linf=linf_error)\nend\n\n\n# some common analysis_integrals\n# to support another analysis integral, you can overload\n# Trixi.analyze, Trixi.pretty_form_utf, Trixi.pretty_form_ascii\nfunction analyze(quantity, du, u, t, semi::AbstractSemidiscretization)\n mesh, equations, solver, cache = mesh_equations_solver_cache(semi)\n analyze(quantity, du, u, t, mesh, equations, solver, cache)\nend\nfunction analyze(quantity, du, u, t, mesh, equations, solver, cache)\n integrate(quantity, u, mesh, equations, solver, cache, normalize=true)\nend\npretty_form_utf(quantity) = get_name(quantity)\npretty_form_ascii(quantity) = get_name(quantity)\n\n\nfunction entropy_timederivative end\npretty_form_utf(::typeof(entropy_timederivative)) = \"∑∂S/∂U ⋅ Uₜ\"\npretty_form_ascii(::typeof(entropy_timederivative)) = \"dsdu_ut\"\n\npretty_form_utf(::typeof(entropy)) = \"∑S\"\n\npretty_form_utf(::typeof(energy_total)) = \"∑e_total\"\npretty_form_ascii(::typeof(energy_total)) = \"e_total\"\n\npretty_form_utf(::typeof(energy_kinetic)) = \"∑e_kinetic\"\npretty_form_ascii(::typeof(energy_kinetic)) = \"e_kinetic\"\n\npretty_form_utf(::typeof(energy_kinetic_nondimensional)) = \"∑e_kinetic*\"\npretty_form_ascii(::typeof(energy_kinetic_nondimensional)) = \"e_kinetic*\"\n\npretty_form_utf(::typeof(energy_internal)) = \"∑e_internal\"\npretty_form_ascii(::typeof(energy_internal)) = \"e_internal\"\n\npretty_form_utf(::typeof(energy_magnetic)) = \"∑e_magnetic\"\npretty_form_ascii(::typeof(energy_magnetic)) = \"e_magnetic\"\n\npretty_form_utf(::typeof(cross_helicity)) = \"∑v⋅B\"\npretty_form_ascii(::typeof(cross_helicity)) = \"v_dot_B\"\n\npretty_form_utf(::Val{:l2_divb}) = \"L2 ∇⋅B\"\npretty_form_ascii(::Val{:l2_divb}) = \"l2_divb\"\n\npretty_form_utf(::Val{:linf_divb}) = \"L∞ ∇⋅B\"\npretty_form_ascii(::Val{:linf_divb}) = \"linf_divb\"\n\npretty_form_utf(::typeof(lake_at_rest_error)) = \"∑|H₀-(h+b)|\"\npretty_form_ascii(::typeof(lake_at_rest_error)) = \"|H0-(h+b)|\"\n\n# specialized implementations specific to some solvers\ninclude(\"analysis_dg1d.jl\")\ninclude(\"analysis_dg2d.jl\")\ninclude(\"analysis_dg2d_parallel.jl\")\ninclude(\"analysis_dg3d.jl\")\ninclude(\"analysis_dg3d_parallel.jl\")\n\n\nend # @muladd\n", "meta": {"hexsha": "65fd417c69172ba07af83ceddc6bad3ebaadebcb", "size": 18616, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/callbacks_step/analysis.jl", "max_stars_repo_name": "panalluri/Trixi.jl", "max_stars_repo_head_hexsha": "faab9964204923c1a21b55ebf788c8a37aa01e90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/callbacks_step/analysis.jl", "max_issues_repo_name": "panalluri/Trixi.jl", "max_issues_repo_head_hexsha": "faab9964204923c1a21b55ebf788c8a37aa01e90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/callbacks_step/analysis.jl", "max_forks_repo_name": "panalluri/Trixi.jl", "max_forks_repo_head_hexsha": "faab9964204923c1a21b55ebf788c8a37aa01e90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4305283757, "max_line_length": 128, "alphanum_fraction": 0.6692629996, "num_tokens": 4854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24147947637463404}} {"text": "function codegen(::Type{Val{:iterate}}, ::Type{HMC}, job::BasicMCJob)\n result::Expr\n update = []\n noupdate = []\n burninbody = []\n ifburninbody = []\n body = []\n dindex::Integer\n\n vform = variate_form(job.pstate)\n if vform != Univariate && vform != Multivariate\n error(\"Only univariate or multivariate parameter states allowed in HMC code generation\")\n end\n\n if isa(job.tuner, DualAveragingMCTuner)\n push!(body, :(_job.sstate.count += 1))\n end\n\n if (isa(job.tuner, VanillaMCTuner) && job.tuner.verbose) ||\n isa(job.tuner, AcceptanceRateMCTuner) ||\n (isa(job.tuner, DualAveragingMCTuner) && job.tuner.verbose)\n push!(body, :(_job.sstate.tune.proposed += 1))\n end\n\n if vform == Univariate\n push!(body, :(_job.sstate.momentum = randn()))\n elseif vform == Multivariate\n push!(body, :(_job.sstate.momentum[:] = randn(_job.pstate.size)))\n end\n\n push!(body, :(_job.sstate.oldhamiltonian = hamiltonian(_job.pstate.logtarget, _job.sstate.momentum)))\n\n if vform == Univariate\n push!(body, :(_job.sstate.pstate.value = _job.pstate.value))\n push!(body, :(_job.sstate.pstate.gradlogtarget = _job.pstate.gradlogtarget))\n elseif vform == Multivariate\n push!(body, :(_job.sstate.pstate.value = copy(_job.pstate.value)))\n push!(body, :(_job.sstate.pstate.gradlogtarget = copy(_job.pstate.gradlogtarget)))\n end\n\n if isa(job.tuner, DualAveragingMCTuner)\n push!(body, :(_job.sstate.nleaps = max(1, Int(round(_job.sstate.tune.λ/_job.sstate.tune.step)))))\n end\n\n if vform == Univariate\n push!(body, :(\n for i in 1:_job.sstate.nleaps\n _job.sstate.momentum =\n leapfrog!(\n _job.sstate.pstate,\n _job.sstate.pstate,\n _job.sstate.momentum,\n _job.sstate.tune.step,\n _job.parameter.gradlogtarget!\n )\n end\n ))\n elseif vform == Multivariate\n push!(body, :(\n for i in 1:_job.sstate.nleaps\n leapfrog!(\n _job.sstate.pstate,\n _job.sstate.momentum,\n _job.sstate.pstate,\n _job.sstate.momentum,\n _job.sstate.tune.step,\n _job.parameter.gradlogtarget!\n )\n end\n ))\n end\n\n push!(body, :(_job.parameter.logtarget!(_job.sstate.pstate)))\n\n push!(body, :(_job.sstate.newhamiltonian = hamiltonian(_job.sstate.pstate.logtarget, _job.sstate.momentum)))\n\n push!(body, :(_job.sstate.ratio = _job.sstate.newhamiltonian-_job.sstate.oldhamiltonian))\n\n push!(body, :(_job.sstate.a = min(1., exp(_job.sstate.ratio))))\n\n if vform == Univariate\n push!(update, :(_job.pstate.value = _job.sstate.pstate.value))\n push!(update, :(_job.pstate.gradlogtarget = _job.sstate.pstate.gradlogtarget))\n if in(:gradloglikelihood, job.outopts[:monitor]) && job.parameter.gradloglikelihood! != nothing\n push!(update, :(_job.pstate.gradloglikelihood = _job.sstate.pstate.gradloglikelihood))\n end\n if in(:gradlogprior, job.outopts[:monitor]) && job.parameter.gradlogprior! != nothing\n push!(update, :(_job.pstate.gradlogprior = _job.sstate.pstate.gradlogprior))\n end\n elseif vform == Multivariate\n push!(update, :(_job.pstate.value = copy(_job.sstate.pstate.value)))\n push!(update, :(_job.pstate.gradlogtarget = copy(_job.sstate.pstate.gradlogtarget)))\n if in(:gradloglikelihood, job.outopts[:monitor]) && job.parameter.gradloglikelihood! != nothing\n push!(update, :(_job.pstate.gradloglikelihood = copy(_job.sstate.pstate.gradloglikelihood)))\n end\n if in(:gradlogprior, job.outopts[:monitor]) && job.parameter.gradlogprior! != nothing\n push!(update, :(_job.pstate.gradlogprior = copy(_job.sstate.pstate.gradlogprior)))\n end\n end\n push!(update, :(_job.pstate.logtarget = _job.sstate.pstate.logtarget))\n if in(:loglikelihood, job.outopts[:monitor]) && job.parameter.loglikelihood! != nothing\n push!(update, :(_job.pstate.loglikelihood = _job.sstate.pstate.loglikelihood))\n end\n if in(:logprior, job.outopts[:monitor]) && job.parameter.logprior! != nothing\n push!(update, :(_job.pstate.logprior = _job.sstate.pstate.logprior))\n end\n dindex = findfirst(job.outopts[:diagnostics], :accept)\n if dindex != 0\n push!(update, :(_job.pstate.diagnosticvalues[$dindex] = true))\n push!(noupdate, :(_job.pstate.diagnosticvalues[$dindex] = false))\n end\n if (isa(job.tuner, VanillaMCTuner) && job.tuner.verbose) ||\n isa(job.tuner, AcceptanceRateMCTuner) ||\n (isa(job.tuner, DualAveragingMCTuner) && job.tuner.verbose)\n push!(update, :(_job.sstate.tune.accepted += 1))\n end\n\n push!(body, Expr(:if, :(rand() < _job.sstate.a), Expr(:block, update...), noupdate...))\n\n if (isa(job.tuner, VanillaMCTuner) && job.tuner.verbose) || isa(job.tuner, AcceptanceRateMCTuner)\n push!(burninbody, :(rate!(_job.sstate.tune)))\n\n if isa(job.tuner, AcceptanceRateMCTuner)\n push!(burninbody, :(tune!(_job.sstate.tune, _job.tuner)))\n end\n\n if job.tuner.verbose\n fmt_iter = format_iteration(ndigits(job.range.burnin))\n fmt_perc = format_percentage()\n\n push!(burninbody, :(println(\n \"Burnin iteration \",\n $(fmt_iter)(_job.sstate.tune.totproposed),\n \" of \",\n _job.range.burnin,\n \": \",\n $(fmt_perc)(100*_job.sstate.tune.rate),\n \" % acceptance rate\"\n )))\n end\n\n push!(burninbody, :(reset_burnin!(_job.sstate.tune)))\n\n push!(\n body,\n Expr(\n :if,\n :(_job.sstate.tune.totproposed <= _job.range.burnin && mod(_job.sstate.tune.proposed, _job.tuner.period) == 0),\n Expr(:block, burninbody...)\n )\n )\n elseif isa(job.tuner, DualAveragingMCTuner)\n push!(burninbody, :(tune!(_job.sstate.tune, _job.tuner, _job.sstate.count, _job.sstate.a)))\n\n if job.tuner.verbose\n fmt_iter = format_iteration(ndigits(job.tuner.nadapt))\n fmt_perc = format_percentage()\n\n push!(ifburninbody, :(rate!(_job.sstate.tune)))\n\n push!(ifburninbody, :(println(\n \"Burnin iteration \",\n $(fmt_iter)(_job.sstate.tune.totproposed),\n \" of \",\n _job.tuner.nadapt,\n \": \",\n $(fmt_perc)(100*_job.sstate.tune.rate),\n \" % acceptance rate\"\n )))\n\n push!(ifburninbody, :(reset_burnin!(_job.sstate.tune)))\n\n push!(burninbody, Expr(:if, :(mod(_job.sstate.tune.proposed, _job.tuner.period) == 0), Expr(:block, ifburninbody...)))\n end\n\n push!(\n body,\n Expr(\n :if,\n :(_job.sstate.count <= _job.tuner.nadapt),\n Expr(:block, burninbody...),\n :(_job.sstate.tune.step = _job.sstate.tune.εbar)\n )\n )\n end\n\n if !job.plain\n push!(body, :(produce()))\n end\n\n @gensym _iterate\n\n result = quote\n function $_iterate(_job::BasicMCJob)\n $(body...)\n end\n end\n\n result\nend\n", "meta": {"hexsha": "af952a28ff56ccad96ec48f76566690666290b81", "size": 6715, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/samplers/iterate/HMC.jl", "max_stars_repo_name": "JuliaPackageMirrors/Klara.jl", "max_stars_repo_head_hexsha": "366d1e3829ebdc5021d6cd1fa2cc2b85d8abbc9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-10-05T21:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-30T15:32:39.000Z", "max_issues_repo_path": "src/samplers/iterate/HMC.jl", "max_issues_repo_name": "JuliaPackageMirrors/Lora.jl", "max_issues_repo_head_hexsha": "366d1e3829ebdc5021d6cd1fa2cc2b85d8abbc9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/samplers/iterate/HMC.jl", "max_forks_repo_name": "JuliaPackageMirrors/Lora.jl", "max_forks_repo_head_hexsha": "366d1e3829ebdc5021d6cd1fa2cc2b85d8abbc9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.407960199, "max_line_length": 124, "alphanum_fraction": 0.6464631422, "num_tokens": 1990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2414589830372118}} {"text": "mutable struct DQMCStack{\n GreensElType <: Number, \n HoppingElType <: Number, \n GreensMatType <: AbstractArray{GreensElType},\n HoppingMatType <: AbstractArray{HoppingElType},\n InteractionMatType <: AbstractArray\n } <: AbstractDQMCStack\n\n u_stack::Vector{GreensMatType}\n d_stack::Vector{Vector{Float64}}\n t_stack::Vector{GreensMatType}\n\n Ul::GreensMatType\n Ur::GreensMatType\n Dl::Vector{Float64}\n Dr::Vector{Float64}\n Tl::GreensMatType\n Tr::GreensMatType\n pivot::Vector{Int64}\n tempv::Vector{GreensElType}\n tempvf::Vector{Float64}\n\n greens::GreensMatType\n greens_temp::GreensMatType\n\n tmp1::GreensMatType\n tmp2::GreensMatType\n\n ranges::Array{UnitRange, 1}\n n_elements::Int\n current_slice::Int # running internally over 0:mc.parameters.slices+1, where 0 and mc.parameters.slices+1 are artifcial to prepare next sweep direction.\n direction::Int\n\n # # -------- Global update backup\n # gb_u_stack::Array{GreensElType, 3}\n # gb_d_stack::Matrix{Float64}\n # gb_t_stack::Array{GreensElType, 3}\n\n # gb_greens::GreensMatType\n # gb_log_det::Float64\n\n # gb_conf::Array{Float64, 3}\n # # --------\n\n\n # preallocated, reused arrays\n curr_U::GreensMatType\n eV::InteractionMatType\n\n # hopping matrices (mu included)\n hopping_matrix::HoppingMatType\n hopping_matrix_exp::HoppingMatType\n hopping_matrix_exp_inv::HoppingMatType\n hopping_matrix_exp_squared::HoppingMatType\n hopping_matrix_exp_inv_squared::HoppingMatType\n\n # checkerboard hopping matrices\n checkerboard::Matrix{Int} # src, trg, bondid\n groups::Vector{UnitRange}\n n_groups::Int\n chkr_hop_half::Vector{SparseMatrixCSC{HoppingElType, Int64}}\n chkr_hop_half_inv::Vector{SparseMatrixCSC{HoppingElType, Int64}}\n chkr_hop_half_dagger::Vector{SparseMatrixCSC{HoppingElType, Int64}}\n chkr_hop::Vector{SparseMatrixCSC{HoppingElType, Int64}} # without prefactor 0.5 in matrix exponentials\n chkr_hop_inv::Vector{SparseMatrixCSC{HoppingElType, Int64}}\n chkr_hop_dagger::Vector{SparseMatrixCSC{HoppingElType, Int64}}\n chkr_mu_half::SparseMatrixCSC{HoppingElType, Int64}\n chkr_mu_half_inv::SparseMatrixCSC{HoppingElType, Int64}\n chkr_mu::SparseMatrixCSC{HoppingElType, Int64}\n chkr_mu_inv::SparseMatrixCSC{HoppingElType, Int64}\n\n\n function DQMCStack{GET, HET, GMT, HMT, IMT}() where {\n GET<:Number, HET<:Number, \n GMT<:AbstractArray{GET}, HMT<:AbstractArray{HET}, IMT<:AbstractArray\n }\n @assert isconcretetype(GET);\n @assert isconcretetype(HET);\n @assert isconcretetype(GMT);\n @assert isconcretetype(HMT);\n @assert isconcretetype(IMT);\n @assert eltype(GMT) == GET;\n @assert eltype(HMT) == HET;\n new{GET, HET, GMT, HMT, IMT}()\n end\nend\n\n# type helpers\ngeltype(::DQMCStack{GET, HET, GMT, HMT, IMT}) where {GET, HET, GMT, HMT, IMT} = GET\nheltype(::DQMCStack{GET, HET, GMT, HMT, IMT}) where {GET, HET, GMT, HMT, IMT} = HET\ngmattype(::DQMCStack{GET, HET, GMT, HMT, IMT}) where {GET, HET, GMT, HMT, IMT} = GMT\nhmattype(::DQMCStack{GET, HET, GMT, HMT, IMT}) where {GET, HET, GMT, HMT, IMT} = HMT\nimattype(::DQMCStack{GET, HET, GMT, HMT, IMT}) where {GET, HET, GMT, HMT, IMT} = IMT\n\ngeltype(mc::DQMC) = geltype(mc.stack)\nheltype(mc::DQMC) = heltype(mc.stack)\ngmattype(mc::DQMC) = gmattype(mc.stack)\nhmattype(mc::DQMC) = hmattype(mc.stack)\nimattype(mc::DQMC) = imattype(mc.stack)\n\n\n\n################################################################################\n### Stack Initialization\n################################################################################\n\n\n\nfunction initialize_stack(mc::DQMC, ::DQMCStack)\n GreensElType = geltype(mc)\n GreensMatType = gmattype(mc)\n HoppingElType = heltype(mc)\n N = length(lattice(mc))\n flv = nflavors(mc.model)\n\n mc.stack.n_elements = convert(Int, mc.parameters.slices / mc.parameters.safe_mult) + 1\n\n mc.stack.u_stack = [GreensMatType(undef, flv*N, flv*N) for _ in 1:mc.stack.n_elements]\n mc.stack.d_stack = [zeros(Float64, flv*N) for _ in 1:mc.stack.n_elements]\n mc.stack.t_stack = [GreensMatType(undef, flv*N, flv*N) for _ in 1:mc.stack.n_elements]\n\n mc.stack.greens = GreensMatType(undef, flv*N, flv*N)\n mc.stack.greens_temp = GreensMatType(undef, flv*N, flv*N)\n\n # used in calculate_greens\n # do not change in slice_matrices.jl or interaction_matrix_exp!\n mc.stack.Ul = GreensMatType(I, flv*N, flv*N)\n mc.stack.Ur = GreensMatType(I, flv*N, flv*N)\n mc.stack.Tl = GreensMatType(I, flv*N, flv*N)\n mc.stack.Tr = GreensMatType(I, flv*N, flv*N)\n mc.stack.Dl = ones(Float64, flv*N)\n mc.stack.Dr = ones(Float64, flv*N)\n # can be changed anywhere\n mc.stack.pivot = Vector{Int64}(undef, flv*N)\n mc.stack.tempv = Vector{GreensElType}(undef, flv*N)\n mc.stack.tempvf = Vector{Float64}(undef, flv*N)\n\n # can be changed anywhere\n mc.stack.tmp1 = GreensMatType(undef, flv*N, flv*N)\n mc.stack.tmp2 = GreensMatType(undef, flv*N, flv*N)\n\n\n # # Global update backup\n # mc.stack.gb_u_stack = zero(mc.stack.u_stack)\n # mc.stack.gb_d_stack = zero(mc.stack.d_stack)\n # mc.stack.gb_t_stack = zero(mc.stack.t_stack)\n # mc.stack.gb_greens = zero(mc.stack.greens)\n # mc.stack.gb_log_det = 0.\n # mc.stack.gb_conf = zero(mc.conf)\n\n mc.stack.ranges = UnitRange[]\n\n for i in 1:mc.stack.n_elements - 1\n push!(mc.stack.ranges, 1 + (i - 1) * mc.parameters.safe_mult:i * mc.parameters.safe_mult)\n end\n\n mc.stack.curr_U = GreensMatType(undef, flv*N, flv*N)\n mc.stack.eV = init_interaction_matrix(mc.model)\n\n nothing\nend\n\n# hopping\nfunction init_hopping_matrices(mc::DQMC{M,CB}, m::Model) where {M, CB<:Checkerboard}\n init_hopping_matrix_exp(mc, m)\n CB <: CheckerboardTrue && init_checkerboard_matrices(mc, m)\n nothing\nend\nfunction init_hopping_matrix_exp(mc::DQMC, m::Model)\n N = length(lattice(m))\n flv = nflavors(m)\n dtau = mc.parameters.delta_tau\n\n T = hopping_matrix(mc, m)\n size(T) == (flv*N, flv*N) || error(\"Hopping matrix should have size \"*\n \"$((flv*N, flv*N)) but has size $(size(T)) .\")\n mc.stack.hopping_matrix = T\n mc.stack.hopping_matrix_exp = exp(-0.5 * dtau * T)\n mc.stack.hopping_matrix_exp_inv = exp(0.5 * dtau * T)\n mc.stack.hopping_matrix_exp_squared = mc.stack.hopping_matrix_exp * mc.stack.hopping_matrix_exp\n mc.stack.hopping_matrix_exp_inv_squared = mc.stack.hopping_matrix_exp_inv * mc.stack.hopping_matrix_exp_inv\n nothing\nend\n\n# checkerboard\nrem_eff_zeros!(X::AbstractArray) = map!(e -> abs.(e)<1e-15 ? zero(e) : e,X,X)\nfunction init_checkerboard_matrices(mc::DQMC, m::Model)\n s = mc.stack\n l = lattice(m)\n flv = nflavors(m)\n H = heltype(mc)\n N = length(l)\n dtau = mc.parameters.delta_tau\n mu = m.mu\n\n s.checkerboard, s.groups, s.n_groups = build_checkerboard(l)\n n_grps = s.n_groups\n cb = s.checkerboard\n\n T = reshape(hopping_matrix(mc, m), (N, flv, N, flv))\n\n s.chkr_hop_half = Vector{SparseMatrixCSC{H, Int}}(undef, n_grps)\n s.chkr_hop_half_inv = Vector{SparseMatrixCSC{H, Int}}(undef, n_grps)\n s.chkr_hop = Vector{SparseMatrixCSC{H, Int}}(undef, n_grps)\n s.chkr_hop_inv = Vector{SparseMatrixCSC{H, Int}}(undef, n_grps)\n\n for (g, gr) in enumerate(s.groups)\n Tg = zeros(H, N, flv, N, flv)\n for i in gr\n src, trg = cb[1:2,i]\n for f1 in 1:flv, f2 in 1:flv\n Tg[trg, f1, src, f2] = T[trg, f1, src, f2]\n end\n end\n\n Tgg = reshape(Tg, (N*flv, N*flv))\n s.chkr_hop_half[g] = sparse(rem_eff_zeros!(exp(-0.5 * dtau * Tgg)))\n s.chkr_hop_half_inv[g] = sparse(rem_eff_zeros!(exp(0.5 * dtau * Tgg)))\n s.chkr_hop[g] = sparse(rem_eff_zeros!(exp(- dtau * Tgg)))\n s.chkr_hop_inv[g] = sparse(rem_eff_zeros!(exp(dtau * Tgg)))\n end\n\n s.chkr_hop_half_dagger = adjoint.(s.chkr_hop_half)\n s.chkr_hop_dagger = adjoint.(s.chkr_hop)\n\n mus = diag(reshape(T, (N*flv, N*flv)))\n s.chkr_mu_half = spdiagm(0 => exp.(-0.5 * dtau * mus))\n s.chkr_mu_half_inv = spdiagm(0 => exp.(0.5 * dtau * mus))\n s.chkr_mu = spdiagm(0 => exp.(-dtau * mus))\n s.chkr_mu_inv = spdiagm(0 => exp.(dtau * mus))\n\n # hop_mat_exp_chkr = foldl(*,s.chkr_hop_half) * sqrt.(s.chkr_mu)\n # r = effreldiff(s.hopping_matrix_exp,hop_mat_exp_chkr)\n # r[find(x->x==zero(x),hop_mat_exp_chkr)] = 0.\n # println(\"Checkerboard - Exact ≈ \", round(maximum(absdiff(s.hopping_matrix_exp,hop_mat_exp_chkr)), 4))\n nothing\nend\n\n\"\"\"\n build_stack(mc::DQMC)\n\nBuild slice matrix stack from scratch.\n\"\"\"\n@bm function build_stack(mc::DQMC, ::DQMCStack)\n copyto!(mc.stack.u_stack[1], I)\n mc.stack.d_stack[1] .= one(eltype(mc.stack.d_stack[1]))\n copyto!(mc.stack.t_stack[1], I)\n\n @inbounds for i in 1:length(mc.stack.ranges)\n add_slice_sequence_left(mc, i)\n end\n\n mc.stack.current_slice = mc.parameters.slices + 1\n mc.stack.direction = -1\n\n nothing\nend\n\n\n@bm function reverse_build_stack(mc::DQMC, ::DQMCStack)\n copyto!(mc.stack.u_stack[end], I)\n mc.stack.d_stack[end] .= one(eltype(mc.stack.d_stack[end]))\n copyto!(mc.stack.t_stack[end], I)\n\n @inbounds for i in length(mc.stack.ranges):-1:1\n add_slice_sequence_right(mc, i)\n end\n\n mc.stack.current_slice = 0\n mc.stack.direction = 1\n\n nothing\nend\n\n\n################################################################################\n### Slice matrix stack manipulations/updates\n################################################################################\n\n\n\n\"\"\"\n add_slice_sequence_left(mc::DQMC, idx)\n\nComputes the next `mc.parameters.safe_mult` slice matrix products from the current `idx`\nand writes them to `idx+1`. The index `idx` does not refer to the slice index, \nbut `mc.parameters.safe_mult` times the slice index.\n\"\"\"\n@bm function add_slice_sequence_left(mc::DQMC, idx::Int)\n @inbounds begin\n copyto!(mc.stack.curr_U, mc.stack.u_stack[idx])\n\n # println(\"Adding slice seq left $idx = \", mc.stack.ranges[idx])\n for slice in mc.stack.ranges[idx]\n multiply_slice_matrix_left!(mc, mc.model, slice, mc.stack.curr_U)\n end\n\n vmul!(mc.stack.tmp1, mc.stack.curr_U, Diagonal(mc.stack.d_stack[idx]))\n udt_AVX_pivot!(\n mc.stack.u_stack[idx + 1], mc.stack.d_stack[idx + 1], mc.stack.tmp1, \n mc.stack.pivot, mc.stack.tempv\n )\n vmul!(mc.stack.t_stack[idx + 1], mc.stack.tmp1, mc.stack.t_stack[idx])\n end\nend\n\n\"\"\"\n add_slice_sequence_right(mc::DQMC, idx)\n\nComputes the next `mc.parameters.safe_mult` slice matrix products from the current \n`idx+1` and writes them to `idx`. The index `idx` does not refer to the slice \nindex, but `mc.parameters.safe_mult` times the slice index.\n\"\"\"\n@bm function add_slice_sequence_right(mc::DQMC, idx::Int)\n @inbounds begin\n copyto!(mc.stack.curr_U, mc.stack.u_stack[idx + 1])\n\n for slice in reverse(mc.stack.ranges[idx])\n multiply_daggered_slice_matrix_left!(mc, mc.model, slice, mc.stack.curr_U)\n end\n\n vmul!(mc.stack.tmp1, mc.stack.curr_U, Diagonal(mc.stack.d_stack[idx + 1]))\n udt_AVX_pivot!(\n mc.stack.u_stack[idx], mc.stack.d_stack[idx], mc.stack.tmp1, mc.stack.pivot, mc.stack.tempv\n )\n vmul!(mc.stack.t_stack[idx], mc.stack.tmp1, mc.stack.t_stack[idx + 1])\n end\nend\n\n\n\n################################################################################\n### Green's function calculation\n################################################################################\n\n\n\n\"\"\"\n calculate_greens_AVX!(Ul, Dl, Tl, Ur, Dr, Tr, G[, pivot, temp])\n\nCalculates the effective Greens function matrix `G` from two UDT decompositions\n`Ul, Dl, Tl` and `Ur, Dr, Tr`. Additionally a `pivot` vector can be given. Note\nthat all inputs will be overwritten.\n\nThe UDT should follow from a set of slice_matrix multiplications, such that\n`Ur, Dr, Tr = udt(B(slice)' ⋯ B(M)')` and `Ul, Dl, Tl = udt(B(slice-1) ⋯ B(1))`.\nThe computed Greens function is then given as `G = inv(I + Ul Dl Tl Tr Dr Ur)`\nand computed here.\n\n`Ul, Tl, Ur, Tr, G` should be square matrices, `Dl, Dr` real Vectors (from \nDiagonal matrices), `pivot` an integer Vector and `temp` a Vector with the same\nelement type as the matrices.\n\"\"\"\n@bm function calculate_greens_AVX!(\n Ul, Dl, Tl, Ur, Dr, Tr, G::AbstractArray{T},\n pivot = Vector{Int64}(undef, length(Dl)),\n temp = Vector{T}(undef, length(Dl))\n ) where T\n # @bm \"B1\" begin\n # Used: Ul, Dl, Tl, Ur, Dr, Tr\n # TODO: [I + Ul Dl Tl Tr^† Dr Ur^†]^-1\n # Compute: Dl * ((Tl * Tr) * Dr) -> Tr * Dr * G (UDT)\n vmul!(G, Tl, adjoint(Tr))\n vmul!(Tr, G, Diagonal(Dr))\n vmul!(G, Diagonal(Dl), Tr)\n udt_AVX_pivot!(Tr, Dr, G, pivot, temp, Val(false)) # Dl available\n # end\n\n # @bm \"B2\" begin\n # Used: Ul, Ur, G, Tr, Dr (Ul, Ur, Tr unitary (inv = adjoint))\n # TODO: [I + Ul Tr Dr G Ur^†]^-1\n # = [(Ul Tr) ((Ul Tr)^-1 (G Ur^†) + Dr) (G Ur)]^-1\n # = Ur G^-1 [(Ul Tr)^† Ur G^-1 + Dr]^-1 (Ul Tr)^†\n # Compute: Ul Tr -> Tl\n # (Ur G^-1) -> Ur\n # ((Ul Tr)^† Ur G^-1) -> Tr\n vmul!(Tl, Ul, Tr)\n rdivp!(Ur, G, Ul, pivot) # requires unpivoted udt decompostion (Val(false))\n vmul!(Tr, adjoint(Tl), Ur)\n # end\n\n # @bm \"B3\" begin\n # Used: Tl, Ur, Tr, Dr\n # TODO: Ur [Tr + Dr]^-1 Tl^† -> Ur [Tr]^-1 Tl^†\n rvadd!(Tr, Diagonal(Dr))\n # end\n\n # @bm \"B4\" begin\n # Used: Ur, Tr, Tl\n # TODO: Ur [Tr]^-1 Tl^† -> Ur [Ul Dr Tr]^-1 Tl^† \n # -> Ur Tr^-1 Dr^-1 Ul^† Tl^† -> Ur Tr^-1 Dr^-1 (Tl Ul)^†\n # Compute: Ur Tr^-1 -> Ur, Tl Ul -> Tr\n udt_AVX_pivot!(Ul, Dr, Tr, pivot, temp, Val(false)) # Dl available\n rdivp!(Ur, Tr, G, pivot) # requires unpivoted udt decompostion (false)\n vmul!(Tr, Tl, Ul)\n # end\n\n # @bm \"B5\" begin\n @turbo for i in eachindex(Dr)\n Dl[i] = 1.0 / Dr[i]\n end\n # end\n\n # @bm \"B6\" begin\n # Used: Ur, Tr, Dl, Ul, Tl\n # TODO: (Ur Dl) Tr^† -> G\n vmul!(Ul, Ur, Diagonal(Dl))\n vmul!(G, Ul, adjoint(Tr))\n # end\nend\n\n\"\"\"\n calculate_greens(mc::DQMC)\n\nComputes the effective greens function from the current state of the stack and\nsaves the result to `mc.stack.greens`.\n\nThis assumes the `mc.stack.Ul, mc.stack.Dl, mc.stack.Tl = udt(B(slice-1) ⋯ B(1))` and\n`mc.stack.Ur, mc.stack.Dr, mc.stack.Tr = udt(B(slice)' ⋯ B(M)')`. \n\nThis should only used internally.\n\"\"\"\n@bm function calculate_greens(mc::DQMC, output::AbstractMatrix = mc.stack.greens)\n calculate_greens_AVX!(\n mc.stack.Ul, mc.stack.Dl, mc.stack.Tl,\n mc.stack.Ur, mc.stack.Dr, mc.stack.Tr,\n output, mc.stack.pivot, mc.stack.tempv\n )\n output\nend\n\n\"\"\"\n calculate_greens(mc::DQMC, slice[, output=mc.stack.greens, safe_mult])\n\nCompute the effective equal-time greens function from scratch at a given `slice`.\n\nThis does not invalidate the stack, but it does overwrite `mc.stack.greens`.\n\"\"\"\n@bm function calculate_greens(\n mc::DQMC, slice::Int, output::AbstractMatrix = mc.stack.greens, \n conf::AbstractArray = mc.conf, safe_mult::Int = mc.parameters.safe_mult\n )\n copyto!(mc.stack.curr_U, I)\n copyto!(mc.stack.Ur, I)\n mc.stack.Dr .= one(eltype(mc.stack.Dr))\n copyto!(mc.stack.Tr, I)\n\n # Calculate Ur,Dr,Tr=B(slice)' ... B(M)'\n if slice+1 <= mc.parameters.slices\n start = slice+1\n stop = mc.parameters.slices\n for k in reverse(start:stop)\n if mod(k,safe_mult) == 0\n multiply_daggered_slice_matrix_left!(mc, mc.model, k, mc.stack.curr_U, conf)\n vmul!(mc.stack.tmp1, mc.stack.curr_U, Diagonal(mc.stack.Dr))\n udt_AVX_pivot!(mc.stack.curr_U, mc.stack.Dr, mc.stack.tmp1, mc.stack.pivot, mc.stack.tempv)\n copyto!(mc.stack.tmp2, mc.stack.Tr)\n vmul!(mc.stack.Tr, mc.stack.tmp1, mc.stack.tmp2)\n else\n multiply_daggered_slice_matrix_left!(mc, mc.model, k, mc.stack.curr_U, conf)\n end\n end\n vmul!(mc.stack.tmp1, mc.stack.curr_U, Diagonal(mc.stack.Dr))\n udt_AVX_pivot!(mc.stack.Ur, mc.stack.Dr, mc.stack.tmp1, mc.stack.pivot, mc.stack.tempv)\n copyto!(mc.stack.tmp2, mc.stack.Tr)\n vmul!(mc.stack.Tr, mc.stack.tmp1, mc.stack.tmp2)\n end\n\n\n copyto!(mc.stack.curr_U, I)\n copyto!(mc.stack.Ul, I)\n mc.stack.Dl .= one(eltype(mc.stack.Dl))\n copyto!(mc.stack.Tl, I)\n\n # Calculate Ul,Dl,Tl=B(slice-1) ... B(1)\n if slice >= 1\n start = 1\n stop = slice\n for k in start:stop\n if mod(k,safe_mult) == 0\n multiply_slice_matrix_left!(mc, mc.model, k, mc.stack.curr_U, conf)\n vmul!(mc.stack.tmp1, mc.stack.curr_U, Diagonal(mc.stack.Dl))\n udt_AVX_pivot!(mc.stack.curr_U, mc.stack.Dl, mc.stack.tmp1, mc.stack.pivot, mc.stack.tempv)\n copyto!(mc.stack.tmp2, mc.stack.Tl)\n vmul!(mc.stack.Tl, mc.stack.tmp1, mc.stack.tmp2)\n else\n multiply_slice_matrix_left!(mc, mc.model, k, mc.stack.curr_U, conf)\n end\n end\n vmul!(mc.stack.tmp1, mc.stack.curr_U, Diagonal(mc.stack.Dl))\n udt_AVX_pivot!(mc.stack.Ul, mc.stack.Dl, mc.stack.tmp1, mc.stack.pivot, mc.stack.tempv)\n copyto!(mc.stack.tmp2, mc.stack.Tl)\n vmul!(mc.stack.Tl, mc.stack.tmp1, mc.stack.tmp2)\n end\n\n return calculate_greens(mc, output)\nend\n\n\n\n################################################################################\n### Stack update\n################################################################################\n\n\n\n# Green's function propagation\n@inline @bm function wrap_greens!(mc::DQMC, gf, curr_slice::Int, direction::Int)\n if direction == -1\n multiply_slice_matrix_inv_left!(mc, mc.model, curr_slice - 1, gf)\n multiply_slice_matrix_right!(mc, mc.model, curr_slice - 1, gf)\n else\n multiply_slice_matrix_left!(mc, mc.model, curr_slice, gf)\n multiply_slice_matrix_inv_right!(mc, mc.model, curr_slice, gf)\n end\n nothing\nend\n\n@bm function propagate(mc::DQMC)\n @inbounds if mc.stack.direction == 1\n if mod(mc.stack.current_slice, mc.parameters.safe_mult) == 0\n mc.stack.current_slice +=1 # slice we are going to\n if mc.stack.current_slice == 1\n copyto!(mc.stack.Ur, mc.stack.u_stack[1])\n copyto!(mc.stack.Dr, mc.stack.d_stack[1])\n copyto!(mc.stack.Tr, mc.stack.t_stack[1])\n copyto!(mc.stack.u_stack[1], I)\n mc.stack.d_stack[1] .= one(eltype(mc.stack.d_stack[1]))\n copyto!(mc.stack.t_stack[1], I)\n copyto!(mc.stack.Ul, mc.stack.u_stack[1])\n copyto!(mc.stack.Dl, mc.stack.d_stack[1])\n copyto!(mc.stack.Tl, mc.stack.t_stack[1])\n\n calculate_greens(mc) # greens_1 ( === greens_{m+1} )\n\n elseif 1 < mc.stack.current_slice <= mc.parameters.slices\n idx = Int((mc.stack.current_slice - 1)/mc.parameters.safe_mult)\n\n copyto!(mc.stack.Ur, mc.stack.u_stack[idx+1])\n copyto!(mc.stack.Dr, mc.stack.d_stack[idx+1])\n copyto!(mc.stack.Tr, mc.stack.t_stack[idx+1])\n add_slice_sequence_left(mc, idx)\n copyto!(mc.stack.Ul, mc.stack.u_stack[idx+1])\n copyto!(mc.stack.Dl, mc.stack.d_stack[idx+1])\n copyto!(mc.stack.Tl, mc.stack.t_stack[idx+1])\n\n if mc.parameters.check_propagation_error\n copyto!(mc.stack.greens_temp, mc.stack.greens)\n end\n\n # Should this be mc.stack.greens_temp?\n # If so, shouldn't this only run w/ mc.parameters.all_checks = true?\n wrap_greens!(mc, mc.stack.greens_temp, mc.stack.current_slice - 1, 1)\n\n calculate_greens(mc) # greens_{slice we are propagating to}\n\n if mc.parameters.check_propagation_error\n # OPT: could probably be optimized through explicit loop\n greensdiff = maximum(abs.(mc.stack.greens_temp - mc.stack.greens)) \n if greensdiff > 1e-7\n push!(mc.analysis.propagation_error, greensdiff)\n mc.parameters.silent || @printf(\n \"->%d \\t+1 Propagation instability\\t %.1e\\n\", \n mc.stack.current_slice, greensdiff\n )\n end\n end\n\n else # we are going to mc.parameters.slices+1\n idx = mc.stack.n_elements - 1\n add_slice_sequence_left(mc, idx)\n mc.stack.direction = -1\n mc.stack.current_slice = mc.parameters.slices+1 # redundant\n propagate(mc)\n end\n\n else\n # Wrapping\n wrap_greens!(mc, mc.stack.greens, mc.stack.current_slice, 1)\n mc.stack.current_slice += 1\n end\n\n else # mc.stack.direction == -1\n if mod(mc.stack.current_slice-1, mc.parameters.safe_mult) == 0\n mc.stack.current_slice -= 1 # slice we are going to\n if mc.stack.current_slice == mc.parameters.slices\n copyto!(mc.stack.Ul, mc.stack.u_stack[end])\n copyto!(mc.stack.Dl, mc.stack.d_stack[end])\n copyto!(mc.stack.Tl, mc.stack.t_stack[end])\n copyto!(mc.stack.u_stack[end], I)\n mc.stack.d_stack[end] .= one(eltype(mc.stack.d_stack[end]))\n copyto!(mc.stack.t_stack[end], I)\n copyto!(mc.stack.Ur, mc.stack.u_stack[end])\n copyto!(mc.stack.Dr, mc.stack.d_stack[end])\n copyto!(mc.stack.Tr, mc.stack.t_stack[end])\n\n calculate_greens(mc) # greens_{mc.parameters.slices+1} === greens_1\n\n # wrap to greens_{mc.parameters.slices}\n wrap_greens!(mc, mc.stack.greens, mc.stack.current_slice + 1, -1)\n\n elseif 0 < mc.stack.current_slice < mc.parameters.slices\n idx = Int(mc.stack.current_slice / mc.parameters.safe_mult) + 1\n\n copyto!(mc.stack.Ul, mc.stack.u_stack[idx])\n copyto!(mc.stack.Dl, mc.stack.d_stack[idx])\n copyto!(mc.stack.Tl, mc.stack.t_stack[idx])\n add_slice_sequence_right(mc, idx)\n copyto!(mc.stack.Ur, mc.stack.u_stack[idx])\n copyto!(mc.stack.Dr, mc.stack.d_stack[idx])\n copyto!(mc.stack.Tr, mc.stack.t_stack[idx])\n\n if mc.parameters.check_propagation_error\n copyto!(mc.stack.greens_temp, mc.stack.greens)\n end\n\n calculate_greens(mc)\n\n if mc.parameters.check_propagation_error\n # OPT: could probably be optimized through explicit loop\n greensdiff = maximum(abs.(mc.stack.greens_temp - mc.stack.greens)) \n if greensdiff > 1e-7\n push!(mc.analysis.propagation_error, greensdiff)\n mc.parameters.silent || @printf(\n \"->%d \\t-1 Propagation instability\\t %.1e\\n\", \n mc.stack.current_slice, greensdiff\n )\n end\n end\n\n wrap_greens!(mc, mc.stack.greens, mc.stack.current_slice + 1, -1)\n\n else # we are going to 0\n idx = 1\n add_slice_sequence_right(mc, idx)\n mc.stack.direction = 1\n mc.stack.current_slice = 0 # redundant\n propagate(mc)\n end\n\n else\n # Wrapping\n wrap_greens!(mc, mc.stack.greens, mc.stack.current_slice, -1)\n mc.stack.current_slice -= 1\n end\n end\n nothing\nend\n", "meta": {"hexsha": "55ea4ab9b810aedd0b31c726734e4ac29de7471c", "size": 24077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/flavors/DQMC/stack.jl", "max_stars_repo_name": "crstnbr/MonteCarlo.jl", "max_stars_repo_head_hexsha": "1c3a678a9991ce9770222e658aee358d39f3693e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 121, "max_stars_repo_stars_event_min_datetime": "2018-03-06T16:43:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T18:01:19.000Z", "max_issues_repo_path": "src/flavors/DQMC/stack.jl", "max_issues_repo_name": "crstnbr/MonteCarlo.jl", "max_issues_repo_head_hexsha": "1c3a678a9991ce9770222e658aee358d39f3693e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 88, "max_issues_repo_issues_event_min_datetime": "2018-08-08T12:36:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-16T14:46:36.000Z", "max_forks_repo_path": "src/flavors/DQMC/stack.jl", "max_forks_repo_name": "crstnbr/MonteCarlo.jl", "max_forks_repo_head_hexsha": "1c3a678a9991ce9770222e658aee358d39f3693e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-02-05T16:17:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T16:13:07.000Z", "avg_line_length": 37.0986132512, "max_line_length": 156, "alphanum_fraction": 0.5923495452, "num_tokens": 6950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.24141290125295242}} {"text": "# The code in this file is a small port from scikit-learn's and numpy's\n# library which is distributed under the 3-Clause BSD license.\n# The rest of DecisionTree.jl is released under the MIT license.\n\n# written by Poom Chiarawongse \n\nmodule treeregressor\n include(\"../util.jl\")\n\n import Random\n export fit\n\n mutable struct NodeMeta{S}\n l :: NodeMeta{S} # right child\n r :: NodeMeta{S} # left child\n label :: Float64 # most likely label\n feature :: Int # feature used for splitting\n threshold :: S # threshold value\n is_leaf :: Bool\n depth :: Int\n region :: UnitRange{Int} # a slice of the samples used to decide the split of the node\n features :: Vector{Int} # a list of features not known to be constant\n split_at :: Int # index of samples\n function NodeMeta{S}(\n features :: Vector{Int},\n region :: UnitRange{Int},\n depth :: Int) where S\n node = new{S}()\n node.depth = depth\n node.region = region\n node.features = features\n node.is_leaf = false\n node\n end\n end\n\n struct Tree{S}\n root :: NodeMeta{S}\n labels :: Vector{Int}\n end\n\n # find an optimal split that satisfy the given constraints\n # (max_depth, min_samples_split, min_purity_increase)\n function _split!(\n X :: AbstractMatrix{S}, # the feature array\n Y :: AbstractVector{Float64}, # the label array\n W :: AbstractVector{U},\n node :: NodeMeta{S}, # the node to split\n max_features :: Int, # number of features to consider\n max_depth :: Int, # the maximum depth of the resultant tree\n min_samples_leaf :: Int, # the minimum number of samples each leaf needs to have\n min_samples_split :: Int, # the minimum number of samples in needed for a split\n min_purity_increase :: Float64, # minimum purity needed for a split\n indX :: AbstractVector{Int}, # an array of sample indices,\n # we split using samples in indX[node.region]\n # the two arrays below are given for optimization purposes\n Xf :: AbstractVector{S},\n Yf :: AbstractVector{Float64},\n Wf :: AbstractVector{U},\n rng :: Random.AbstractRNG) where {S, U}\n\n region = node.region\n n_samples = length(region)\n r_start = region.start - 1\n\n @inbounds @simd for i in 1:n_samples\n Yf[i] = Y[indX[i + r_start]]\n Wf[i] = W[indX[i + r_start]]\n end\n\n tssq = zero(U)\n tsum = zero(U)\n wsum = zero(U)\n @inbounds @simd for i in 1:n_samples\n tssq += Wf[i]*Yf[i]*Yf[i]\n tsum += Wf[i]*Yf[i]\n wsum += Wf[i]\n end\n\n node.label = tsum / wsum\n if (min_samples_leaf * 2 > n_samples\n || min_samples_split > n_samples\n || max_depth <= node.depth\n # equivalent to old_purity > -1e-7\n || tsum * node.label > -1e-7 * wsum + tssq)\n node.is_leaf = true\n return\n end\n\n features = node.features\n n_features = length(features)\n best_purity = typemin(U)\n best_feature = -1\n threshold_lo = X[1]\n threshold_hi = X[1]\n\n indf = 1\n # the number of new constants found during this split\n n_constant = 0\n # true if every feature is constant\n unsplittable = true\n # the number of non constant features we will see if\n # only sample n_features used features\n # is a hypergeometric random variable\n total_features = size(X, 2)\n\n # this is the total number of features that we expect to not\n # be one of the known constant features. since we know exactly\n # what the non constant features are, we can sample at 'non_constants_used'\n # non constant features instead of going through every feature randomly.\n non_constants_used = util.hypergeometric(n_features, total_features-n_features, max_features, rng)\n @inbounds while (unsplittable || indf <= non_constants_used) && indf <= n_features\n feature = let\n indr = rand(rng, indf:n_features)\n features[indf], features[indr] = features[indr], features[indf]\n features[indf]\n end\n\n rssq = tssq\n lssq = zero(U)\n rsum = tsum\n lsum = zero(U)\n\n @simd for i in 1:n_samples\n Xf[i] = X[indX[i + r_start], feature]\n end\n\n # sort Yf and indX by Xf\n util.q_bi_sort!(Xf, indX, 1, n_samples, r_start)\n @simd for i in 1:n_samples\n Yf[i] = Y[indX[i + r_start]]\n Wf[i] = W[indX[i + r_start]]\n end\n nl, nr = zero(U), wsum\n # lo and hi are the indices of\n # the least upper bound and the greatest lower bound\n # of the left and right nodes respectively\n hi = 0\n last_f = Xf[1]\n is_constant = true\n while hi < n_samples\n lo = hi + 1\n curr_f = Xf[lo]\n hi = (lo < n_samples && curr_f == Xf[lo+1]\n ? searchsortedlast(Xf, curr_f, lo, n_samples, Base.Order.Forward)\n : lo)\n\n (lo != 1) && (is_constant = false)\n # honor min_samples_leaf\n if lo-1 >= min_samples_leaf && n_samples - (lo-1) >= min_samples_leaf\n unsplittable = false\n purity = (rsum * rsum / nr) + (lsum * lsum / nl)\n if purity > best_purity && !isapprox(purity, best_purity)\n # will take average at the end, if possible\n threshold_lo = last_f\n threshold_hi = curr_f\n best_purity = purity\n best_feature = feature\n end\n end\n\n # update, lssq, rssq, lsum, rsum in the direction\n # that would require the smaller number of iterations\n if (hi << 1) < n_samples + lo # i.e., hi - lo < n_samples - hi\n @simd for i in lo:hi\n nr -= Wf[i]\n rsum -= Wf[i]*Yf[i]\n rssq -= Wf[i]*Yf[i]*Yf[i]\n end\n else\n nr = rsum = rssq = zero(U)\n @simd for i in (hi+1):n_samples\n nr += Wf[i]\n rsum += Wf[i]*Yf[i]\n rssq += Wf[i]*Yf[i]*Yf[i]\n end\n end\n lsum = tsum - rsum\n lssq = tssq - rssq\n nl = wsum - nr\n\n last_f = curr_f\n end\n\n # keep track of constant features to be used later.\n if is_constant\n n_constant += 1\n features[indf], features[n_constant] = features[n_constant], features[indf]\n end\n\n indf += 1\n end\n\n # no splits honor min_samples_leaf\n @inbounds if (unsplittable\n || best_purity - tsum * node.label < min_purity_increase * wsum)\n node.is_leaf = true\n return\n else\n # new_purity - old_purity < stop.min_purity_increase\n @simd for i in 1:n_samples\n Xf[i] = X[indX[i + r_start], best_feature]\n end\n\n try\n node.threshold = (threshold_lo + threshold_hi) / 2.0\n catch\n node.threshold = threshold_hi\n end\n # split the samples into two parts: ones that are greater than\n # the threshold and ones that are less than or equal to the threshold\n # ---------------------\n # (so we partition at threshold_lo instead of node.threshold)\n node.split_at = util.partition!(indX, Xf, threshold_lo, region)\n node.feature = best_feature\n node.features = features[(n_constant+1):n_features]\n end\n\n end\n\n @inline function fork!(node :: NodeMeta{S}) where S\n ind = node.split_at\n region = node.region\n features = node.features\n # no need to copy because we will copy at the end\n node.l = NodeMeta{S}(features, region[ 1:ind], node.depth + 1)\n node.r = NodeMeta{S}(features, region[ind+1:end], node.depth + 1)\n end\n\n function _fit(\n X :: AbstractMatrix{S},\n Y :: AbstractVector{Float64},\n W :: AbstractVector{U},\n max_features :: Int,\n max_depth :: Int,\n min_samples_leaf :: Int,\n min_samples_split :: Int,\n min_purity_increase :: Float64,\n rng=Random.GLOBAL_RNG :: Random.AbstractRNG) where {S, U}\n\n n_samples, n_features = size(X)\n\n Yf = Array{Float64}(undef, n_samples)\n Xf = Array{S}(undef, n_samples)\n Wf = Array{U}(undef, n_samples)\n\n indX = collect(1:n_samples)\n root = NodeMeta{S}(collect(1:n_features), 1:n_samples, 0)\n stack = NodeMeta{S}[root]\n\n @inbounds while length(stack) > 0\n node = pop!(stack)\n _split!(\n X, Y, W,\n node,\n max_features,\n max_depth,\n min_samples_leaf,\n min_samples_split,\n min_purity_increase,\n indX,\n Xf, Yf, Wf,\n rng)\n if !node.is_leaf\n fork!(node)\n push!(stack, node.r)\n push!(stack, node.l)\n end\n end\n return (root, indX)\n end\n\n function fit(;\n X :: AbstractMatrix{S},\n Y :: AbstractVector{Float64},\n W :: Union{Nothing, AbstractVector{U}},\n max_features :: Int,\n max_depth :: Int,\n min_samples_leaf :: Int,\n min_samples_split :: Int,\n min_purity_increase :: Float64,\n rng=Random.GLOBAL_RNG :: Random.AbstractRNG) where {S, U}\n\n n_samples, n_features = size(X)\n if W == nothing\n W = fill(1.0, n_samples)\n end\n\n util.check_input(\n X,\n Y,\n W,\n max_features,\n max_depth,\n min_samples_leaf,\n min_samples_split,\n min_purity_increase)\n\n root, indX = _fit(\n X,\n Y,\n W,\n max_features,\n max_depth,\n min_samples_leaf,\n min_samples_split,\n min_purity_increase,\n rng)\n\n return Tree{S}(root, indX)\n\n end\nend\n", "meta": {"hexsha": "4769d81bb9295d4f0fcb6d0777d2e9442325671a", "size": 11411, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regression/tree.jl", "max_stars_repo_name": "BereniceAlexiaJocteur/CausalForest.jl", "max_stars_repo_head_hexsha": "b1adcbc2203b3a6befba13af8106b9980715eb37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/regression/tree.jl", "max_issues_repo_name": "BereniceAlexiaJocteur/CausalForest.jl", "max_issues_repo_head_hexsha": "b1adcbc2203b3a6befba13af8106b9980715eb37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2022-02-09T16:34:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T00:52:24.000Z", "max_forks_repo_path": "src/regression/tree.jl", "max_forks_repo_name": "BereniceAlexiaJocteur/CausalForest.jl", "max_forks_repo_head_hexsha": "b1adcbc2203b3a6befba13af8106b9980715eb37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3407643312, "max_line_length": 106, "alphanum_fraction": 0.4883007624, "num_tokens": 2643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2413216195074579}} {"text": "\n\"\"\"\n`module JAC.CoulombIonization` \n ... a submodel of JAC that contains all methods for computing Coulomb ionization cross sections and alignment parameters \n for the excitation of target or projectile electrons by fast ion impact.\n\"\"\"\nmodule CoulombIonization\n\n using ..Basics, ..ManyElectron, ..Radial\n\n \"\"\"\n `struct CoulombIonization.Settings` ... defines a type for the details and parameters of computing Coulomb-ionization lines.\n\n + multipoles ::Array{EmMultipole} ... Specifies the multipoles of the radiation field that are to be included.\n + gauges ::Array{UseGauge} ... Specifies the gauges to be included into the computations.\n + energies ::Array{Float64,1} ... List of ... energies.\n + calcAlignment ::Bool ... True, if alignment parameters to be calculated and false otherwise.\n + printBefore ::Bool ... True, if all energies and lines are printed before their evaluation.\n + selectLines ::Bool ... True, if lines are selected individually for the computations.\n + selectedLines ::Array{Tuple{Int64,Int64},1} ... List of lines, given by tupels (inital-level, final-level).\n \"\"\"\n struct Settings \n multipoles ::Array{EmMultipole}\n gauges ::Array{UseGauge}\n photonEnergies ::Array{Float64,1} \n calcAlignment ::Bool \n printBefore ::Bool\n selectLines ::Bool\n selectedLines ::Array{Tuple{Int64,Int64},1} \n end \n\n\n \"\"\"\n `CoulombIonization.Settings()` ... constructor for the default values of Coulomb-excitation line computations.\n \"\"\"\n function Settings()\n Settings(EmMultipole[], UseGauge[], Float64[], false, false, false, Tuple{Int64,Int64}[])\n end\n\n\n # `Base.show(io::IO, settings::CoulombIonization.Settings)` ... prepares a proper printout of the variable settings::CoulombIonization.Settings.\n function Base.show(io::IO, settings::CoulombIonization.Settings) \n println(io, \"multipoles: $(settings.multipoles) \")\n println(io, \"gauges: $(settings.gauges) \")\n println(io, \"photonEnergies: $(settings.photonEnergies) \")\n println(io, \"calcAlignment: $(settings.calcAlignment) \")\n println(io, \"printBefore: $(settings.printBefore) \")\n println(io, \"selectLines: $(settings.selectLines) \")\n println(io, \"selectedLines: $(settings.selectedLines) \")\n end\n\n\n \"\"\"\n `struct CoulombIonization.Channel` \n ... defines a type for a Coulomb-excitation channel to help characterize a single magnetic substate. !!! This need to adapted !!!\n\n + multipole ::EmMultipole ... Multipole of the photon absorption.\n + gauge ::EmGauge ... Gauge for dealing with the (coupled) radiation field.\n + kappa ::Int64 ... partial-wave of the free electron\n + symmetry ::LevelSymmetry ... total angular momentum and parity of the scattering state\n + phase ::Float64 ... phase of the partial wave\n + amplitude ::Complex{Float64} ... Photoionization amplitude associated with the given channel.\n \"\"\"\n struct Channel\n multipole ::EmMultipole\n gauge ::EmGauge\n kappa ::Int64\n symmetry ::LevelSymmetry\n phase ::Float64\n amplitude ::Complex{Float64}\n end\n\n\n \"\"\"\n `struct Line` ... defines a type for a Coulomb-excitation line that may include the definition of channels.\n\n + initialLevel ::Level ... initial-(state) level\n + finalLevel ::Level ... final-(state) level\n + crossSection ::EmProperty ... Cross section for this photoionization.\n + alignmentA2 ::EmProperty ... Alignment A_2 parameter.\n + hasChannels ::Bool ... Determines whether the individual (sub-) channels are defined in terms of their \n magnetic substates, etc., or not.\n + channels ::Array{CoulombIonization.Channel,1} ... List of CoulombIonization.Channels of this line.\n \"\"\"\n struct Line\n initialLevel ::Level\n finalLevel ::Level\n crossSection ::EmProperty\n alignmentA2 ::EmProperty\n hasChannels ::Bool\n channels ::Array{CoulombIonization.Channel,1}\n end\n\n\n # `Base.show(io::IO, line::CoulombIonization.Line)` ... prepares a proper printout of the variable line::CoulombIonization.Line.\n function Base.show(io::IO, line::CoulombIonization.Line) \n println(io, \"initialLevel: $(line.initialLevel) \")\n println(io, \"finalLevel: $(line.finalLevel) \")\n println(io, \"crossSection: $(line.crossSection) \")\n end\n\nend # module\n", "meta": {"hexsha": "69d9532192c971527255375960c64e65e5c452f9", "size": 5237, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-CoulombIonization.jl", "max_stars_repo_name": "mfherbst/JAC.jl", "max_stars_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115, "max_stars_repo_stars_event_min_datetime": "2019-03-11T11:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:33:28.000Z", "max_issues_repo_path": "src/module-CoulombIonization.jl", "max_issues_repo_name": "mfherbst/JAC.jl", "max_issues_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-04-02T22:04:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T06:21:57.000Z", "max_forks_repo_path": "src/module-CoulombIonization.jl", "max_forks_repo_name": "mfherbst/JAC.jl", "max_forks_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2019-03-20T10:28:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T12:51:19.000Z", "avg_line_length": 50.8446601942, "max_line_length": 149, "alphanum_fraction": 0.5736108459, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24132161950745787}} {"text": "import Base: isfinite, isnan, precision, iszero, eps,\n typemin, typemax, floatmin, floatmax,\n sign_mask, exponent_mask, exponent_one, exponent_half,\n significand_mask, round, Int32, Int64,\n +, -, *, /, ^, ==, <, <=, >=, >, !=, inv,\n abs, sqrt, exp, log, log2, log10, sin, cos, tan, asin,\n acos, atan, sinh, cosh, tanh, asinh, acosh, atan,\n exponent,\n bitstring\n\nprimitive type BFloat16 <: AbstractFloat 16 end\n\n# Floating point property queries\nfor f in (:sign_mask, :exponent_mask, :exponent_one,\n :exponent_half, :significand_mask)\n @eval $(f)(::Type{BFloat16}) = UInt16($(f)(Float32) >> 16)\nend\n\niszero(x::BFloat16) = reinterpret(UInt16, x) & ~sign_mask(BFloat16) == 0x0000\nisfinite(x::BFloat16) = (reinterpret(UInt16,x) & exponent_mask(BFloat16)) != exponent_mask(BFloat16)\nisnan(x::BFloat16) = (reinterpret(UInt16,x) & ~sign_mask(BFloat16)) > exponent_mask(BFloat16)\nprecision(::Type{BFloat16}) = 8\neps(::Type{BFloat16}) = Base.bitcast(BFloat16, 0x3c00)\n\nround(x::BFloat16, r::RoundingMode{:Up}) = BFloat16(ceil(Float32(x)))\nround(x::BFloat16, r::RoundingMode{:Down}) = BFloat16(floor(Float32(x)))\nround(x::BFloat16, r::RoundingMode{:Nearest}) = BFloat16(round(Float32(x)))\n\nInt64(x::BFloat16) = Int64(Float32(x))\nInt32(x::BFloat16) = Int32(Float32(x))\n\n## floating point traits ##\n\"\"\"\n InfB16\nPositive infinity of type [`BFloat16`](@ref).\n\"\"\"\nconst InfB16 = reinterpret(BFloat16, 0x7f80)\n\n\"\"\"\n NaNB16\nA not-a-number value of type [`BFloat16`](@ref).\n\"\"\"\nconst NaNB16 = reinterpret(BFloat16, 0x7fc0)\n\n# More floating point property queries\ntypemin(::Type{BFloat16}) = -InfB16\ntypemax(::Type{BFloat16}) = InfB16\nfloatmax(::Type{BFloat16}) = reinterpret(BFloat16, 0x7f7f)\nfloatmin(::Type{BFloat16}) = reinterpret(BFloat16, 0x0080)\n\n\n# Truncation from Float32\nBase.uinttype(::Type{BFloat16}) = UInt16\nBase.trunc(::Type{BFloat16}, x::Float32) = reinterpret(BFloat16,\n (reinterpret(UInt32, x) >> 16) % UInt16\n )\n\n# Conversion from Float32\nfunction BFloat16(x::Float32)\n isnan(x) && return NaNB16\n # Round to nearest even (matches TensorFlow and our convention for\n # rounding to lower precision floating point types).\n h = reinterpret(UInt32, x)\n h += 0x7fff + ((h >> 16) & 1)\n return reinterpret(BFloat16, (h >> 16) % UInt16)\nend\n\n# Conversion from Float64\nfunction BFloat16(x::Float64)\n\tBFloat16(Float32(x))\nend\n\n# Conversion from Integer\nfunction BFloat16(x::Integer)\n\tconvert(BFloat16, convert(Float32, x))\nend\n\n# Expansion to Float32\nfunction Base.Float32(x::BFloat16)\n reinterpret(Float32, UInt32(reinterpret(UInt16, x)) << 16)\nend\n\n# Expansion to Float64\nfunction Base.Float64(x::BFloat16)\n Float64(Float32(x))\nend\n\n# Truncation to integer types\nBase.unsafe_trunc(T::Type{<:Integer}, x::BFloat16) = unsafe_trunc(T, Float32(x))\n\n# Basic arithmetic\nfor f in (:+, :-, :*, :/, :^)\n @eval ($f)(x::BFloat16, y::BFloat16) = BFloat16($(f)(Float32(x), Float32(y)))\nend\n-(x::BFloat16) = reinterpret(BFloat16, reinterpret(UInt16, x) ⊻ sign_mask(BFloat16))\n^(x::BFloat16, y::Integer) = BFloat16(^(Float32(x), y))\n\nfor F in (:abs, :sqrt, :exp, :log, :log2, :log10,\n :sin, :cos, :tan, :asin, :acos, :atan,\n :sinh, :cosh, :tanh, :asinh, :acosh, :atanh)\n @eval begin\n $F(x::BFloat16) = BFloat16($F(Float32(x)))\n end\nend\n\nconst ZeroBFloat16 = BFloat16(0.0f0)\nconst OneBFloat16 = BFloat16(1.0f0)\nBase.zero(::Type{BFloat16}) = ZeroBFloat16\nBase.one(::Type{BFloat16}) = OneBFloat16\n\ninv(x::BFloat16) = one(BFloat16) / x\n\n# Floating point comparison\nfunction ==(x::BFloat16, y::BFloat16)\n ix = reinterpret(UInt16, x)\n iy = reinterpret(UInt16, y)\n # NaNs (isnan(x) || isnan(y))\n if (ix|iy)&~sign_mask(BFloat16) > exponent_mask(BFloat16)\n return false\n end\n # Signed zeros\n if (ix|iy)&~sign_mask(BFloat16) == 0\n return true\n end\n return ix == iy\nend\n\nfor op in (:<, :<=, :>, :>=, :!=)\n @eval ($op)(a::BFloat16, b::BFloat16) = ($op)(Float32(a), Float32(b))\nend\n\nBase.widen(::Type{BFloat16}) = Float32\nBase.promote_rule(::Type{Float32}, ::Type{BFloat16}) = Float32\nBase.promote_rule(::Type{Float64}, ::Type{BFloat16}) = Float64\nfor t in (Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128)\n @eval Base.promote_rule(::Type{BFloat16}, ::Type{$t}) = BFloat16\nend\n\n# Wide multiplication\nBase.widemul(x::BFloat16, y::BFloat16) = Float32(x) * Float32(y)\n\n# Showing\nfunction Base.show(io::IO, x::BFloat16)\n hastypeinfo = BFloat16 === get(io, :typeinfo, Any)\n if isinf(x)\n print(io, x < 0 ? \"-InfB16\" : \"InfB16\")\n elseif isnan(x)\n print(io, \"NaNB16\")\n else\n hastypeinfo || print(io, \"BFloat16(\")\n show(IOContext(io, :typeinfo=>Float32), Float32(x))\n hastypeinfo || print(io, \")\")\n end\nend\n\n# Random\nimport Random: rand, randn, randexp, AbstractRNG, Sampler\nrand(rng::AbstractRNG, ::Sampler{BFloat16}) = convert(BFloat16, rand(rng))\nrandn(rng::AbstractRNG, ::Type{BFloat16}) = convert(BFloat16, randn(rng))\nrandexp(rng::AbstractRNG, ::Type{BFloat16}) = convert(BFloat16, randexp(rng))\n \n# Exponent\nexponent(x::BFloat16) = exponent(Float32(x))\n\n# Bitstring\nbitstring(x::BFloat16) = bitstring(reinterpret(UInt16, x))\n", "meta": {"hexsha": "7744578fe29d3f1ed6fc0ea6c65dce1e1a1d3de7", "size": 5221, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bfloat16.jl", "max_stars_repo_name": "Jorispilot/BFloat16s.jl", "max_stars_repo_head_hexsha": "ef6051e4308ed0c02f10168b99d226237e0ae33c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2018-09-01T07:02:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T00:15:09.000Z", "max_issues_repo_path": "src/bfloat16.jl", "max_issues_repo_name": "Jorispilot/BFloat16s.jl", "max_issues_repo_head_hexsha": "ef6051e4308ed0c02f10168b99d226237e0ae33c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-07-14T14:06:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T15:06:51.000Z", "max_forks_repo_path": "src/bfloat16.jl", "max_forks_repo_name": "Jorispilot/BFloat16s.jl", "max_forks_repo_head_hexsha": "ef6051e4308ed0c02f10168b99d226237e0ae33c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-08-31T23:47:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-07T13:20:29.000Z", "avg_line_length": 31.2634730539, "max_line_length": 100, "alphanum_fraction": 0.6678797165, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.24130592333619968}} {"text": "### BasicContMuvParameter\n\ntype BasicContMuvParameter <: Parameter{Continuous, Multivariate}\n key::Symbol\n index::Integer\n pdf::Union{ContinuousMultivariateDistribution, Void}\n prior::Union{ContinuousMultivariateDistribution, Void}\n setpdf::Union{Function, Void}\n setprior::Union{Function, Void}\n loglikelihood!::Union{Function, Void}\n logprior!::Union{Function, Void}\n logtarget!::Union{Function, Void}\n gradloglikelihood!::Union{Function, Void}\n gradlogprior!::Union{Function, Void}\n gradlogtarget!::Union{Function, Void}\n tensorloglikelihood!::Union{Function, Void}\n tensorlogprior!::Union{Function, Void}\n tensorlogtarget!::Union{Function, Void}\n dtensorloglikelihood!::Union{Function, Void}\n dtensorlogprior!::Union{Function, Void}\n dtensorlogtarget!::Union{Function, Void}\n uptogradlogtarget!::Union{Function, Void}\n uptotensorlogtarget!::Union{Function, Void}\n uptodtensorlogtarget!::Union{Function, Void}\n states::VariableStateVector\n\n function BasicContMuvParameter(\n key::Symbol,\n index::Integer,\n pdf::Union{ContinuousMultivariateDistribution, Void},\n prior::Union{ContinuousMultivariateDistribution, Void},\n setpdf::Union{Function, Void},\n setprior::Union{Function, Void},\n ll::Union{Function, Void},\n lp::Union{Function, Void},\n lt::Union{Function, Void},\n gll::Union{Function, Void},\n glp::Union{Function, Void},\n glt::Union{Function, Void},\n tll::Union{Function, Void},\n tlp::Union{Function, Void},\n tlt::Union{Function, Void},\n dtll::Union{Function, Void},\n dtlp::Union{Function, Void},\n dtlt::Union{Function, Void},\n uptoglt::Union{Function, Void},\n uptotlt::Union{Function, Void},\n uptodtlt::Union{Function, Void},\n states::VariableStateVector\n )\n args = (setpdf, setprior, ll, lp, lt, gll, glp, glt, tll, tlp, tlt, dtll, dtlp, dtlt, uptoglt, uptotlt, uptodtlt)\n fnames = fieldnames(BasicContMuvParameter)[5:21]\n\n # Check that all generic functions have correct signature\n for i in 1:17\n if isa(args[i], Function) &&\n isgeneric(args[i]) &&\n !method_exists(args[i], (BasicContMuvParameterState, VariableStateVector))\n error(\"$(fnames[i]) has wrong signature\")\n end\n end\n\n new(\n key,\n index,\n pdf,\n prior,\n setpdf,\n setprior,\n ll,\n lp,\n lt,\n gll,\n glp,\n glt,\n tll,\n tlp,\n tlt,\n dtll,\n dtlp,\n dtlt,\n uptoglt,\n uptotlt,\n uptodtlt,\n states\n )\n end\nend\n\nfunction BasicContMuvParameter!(\n parameter::BasicContMuvParameter,\n setpdf::Union{Function, Void},\n setprior::Union{Function, Void},\n ll::Union{Function, Void},\n lp::Union{Function, Void},\n lt::Union{Function, Void},\n gll::Union{Function, Void},\n glp::Union{Function, Void},\n glt::Union{Function, Void},\n tll::Union{Function, Void},\n tlp::Union{Function, Void},\n tlt::Union{Function, Void},\n dtll::Union{Function, Void},\n dtlp::Union{Function, Void},\n dtlt::Union{Function, Void},\n uptoglt::Union{Function, Void},\n uptotlt::Union{Function, Void},\n uptodtlt::Union{Function, Void}\n)\n args = (setpdf, setprior, ll, lp, lt, gll, glp, glt, tll, tlp, tlt, dtll, dtlp, dtlt, uptoglt, uptotlt, uptodtlt)\n\n # Define setpdf (i = 1) and setprior (i = 2)\n for (i, setter, distribution) in ((1, :setpdf, :pdf), (2, :setprior, :prior))\n setfield!(\n parameter,\n setter,\n if isa(args[i], Function)\n eval(codegen_setfield(parameter, distribution, args[i]))\n else\n nothing\n end\n )\n end\n\n # Define loglikelihood! (i = 3) and gradloglikelihood! (i = 6)\n # plfield stands for parameter likelihood-related field respectively\n for (i, plfield) in ((3, :loglikelihood!), (6, :gradloglikelihood!))\n setfield!(\n parameter,\n plfield,\n if isa(args[i], Function)\n eval(codegen_closure(parameter, args[i]))\n else\n nothing\n end\n )\n end\n\n # Define logprior! (i = 4) and gradlogprior! (i = 7)\n # ppfield and spfield stand for parameter prior-related field and state prior-related field repsectively\n for (i , ppfield, spfield, f) in ((4, :logprior!, :logprior, logpdf), (7, :gradlogprior!, :gradlogprior, gradlogpdf))\n setfield!(\n parameter,\n ppfield,\n if isa(args[i], Function)\n eval(codegen_closure(parameter, args[i]))\n else\n if (\n isa(parameter.prior, ContinuousMultivariateDistribution) &&\n method_exists(f, (typeof(parameter.prior), Vector{eltype(parameter.prior)}))\n ) ||\n isa(args[2], Function)\n eval(codegen_target_closure_via_distribution(parameter, :prior, f, spfield))\n else\n nothing\n end\n end\n )\n end\n\n # Define logtarget! (i = 5) and gradlogtarget! (i = 8)\n # ptfield, plfield and ppfield stand for parameter target, likelihood and prior-related field respectively\n # stfield, slfield and spfield stand for state target, likelihood and prior-related field respectively\n for (i , ptfield, plfield, ppfield, stfield, slfield, spfield, f) in (\n (5, :logtarget!, :loglikelihood!, :logprior!, :logtarget, :loglikelihood, :logprior, logpdf),\n (8, :gradlogtarget!, :gradloglikelihood!, :gradlogprior!, :gradlogtarget, :gradloglikelihood, :gradlogprior, gradlogpdf)\n )\n setfield!(\n parameter,\n ptfield,\n if isa(args[i], Function)\n eval(codegen_closure(parameter, args[i]))\n else\n if isa(args[i-2], Function) && isa(getfield(parameter, ppfield), Function)\n eval(codegen_sumtarget_closure(parameter, plfield, ppfield, stfield, slfield, spfield))\n elseif (\n isa(parameter.pdf, ContinuousMultivariateDistribution) &&\n method_exists(f, (typeof(parameter.pdf), Vector{eltype(parameter.pdf)}))\n ) ||\n isa(args[1], Function)\n eval(codegen_target_closure_via_distribution(parameter, :pdf, f, stfield))\n else\n nothing\n end\n end\n )\n end\n\n # Define tensorloglikelihood! (i = 9) and dtensorloglikelihood! (i = 12)\n # plfield stands for parameter likelihood-related field respectively\n for (i, plfield) in ((9, :tensorloglikelihood!), (12, :dtensorloglikelihood!))\n setfield!(\n parameter,\n plfield,\n if isa(args[i], Function)\n eval(codegen_closure(parameter, args[i]))\n else\n nothing\n end\n )\n end\n\n # Define tensorlogprior! (i = 10) and dtensorlogprior! (i = 13)\n # ppfield stands for parameter prior-related field respectively\n for (i, ppfield) in ((10, :tensorlogprior!), (13, :dtensorlogprior!))\n setfield!(\n parameter,\n ppfield,\n if isa(args[i], Function)\n eval(codegen_closure(parameter, args[i]))\n else\n nothing\n end\n )\n end\n\n # Define tensorlogtarget! (i = 11) and dtensorlogtarget! (i = 14)\n for (i , ptfield, plfield, ppfield, stfield, slfield, spfield) in (\n (\n 11,\n :tensorlogtarget!, :tensorloglikelihood!, :tensorlogprior!,\n :tensorlogtarget, :tensorloglikelihood, :tensorlogprior\n ),\n (\n 14,\n :dtensorlogtarget!, :dtensorloglikelihood!, :dtensorlogprior!,\n :dtensorlogtarget, :dtensorloglikelihood, :dtensorlogprior\n )\n )\n setfield!(\n parameter,\n ptfield,\n if isa(args[i], Function)\n eval(codegen_closure(parameter, args[i]))\n else\n if isa(args[i-2], Function) && isa(args[i-1], Function)\n eval(codegen_sumtarget_closure(parameter, plfield, ppfield, stfield, slfield, spfield))\n else\n nothing\n end\n end\n )\n end\n\n # Define uptogradlogtarget!\n setfield!(\n parameter,\n :uptogradlogtarget!,\n if isa(args[15], Function)\n eval(codegen_closure(parameter, args[15]))\n else\n if isa(parameter.logtarget!, Function) && isa(parameter.gradlogtarget!, Function)\n eval(codegen_uptotarget_closures(parameter, [:logtarget!, :gradlogtarget!]))\n else\n nothing\n end\n end\n )\n\n # Define uptotensorlogtarget!\n setfield!(\n parameter,\n :uptotensorlogtarget!,\n if isa(args[16], Function)\n eval(codegen_closure(parameter, args[16]))\n else\n if isa(parameter.logtarget!, Function) &&\n isa(parameter.gradlogtarget!, Function) &&\n isa(parameter.tensorlogtarget!, Function)\n eval(codegen_uptotarget_closures(parameter, [:logtarget!, :gradlogtarget!, :tensorlogtarget!]))\n else\n nothing\n end\n end\n )\n\n # Define uptodtensorlogtarget!\n setfield!(\n parameter,\n :uptodtensorlogtarget!,\n if isa(args[17], Function)\n eval(codegen_closure(parameter, args[17]))\n else\n if isa(parameter.logtarget!, Function) &&\n isa(parameter.gradlogtarget!, Function) &&\n isa(parameter.tensorlogtarget!, Function) &&\n isa(parameter.dtensorlogtarget!, Function)\n eval(codegen_uptotarget_closures(parameter, [:logtarget!, :gradlogtarget!, :tensorlogtarget!, :dtensorlogtarget!]))\n else\n nothing\n end\n end\n )\nend\n\nBasicContMuvParameter(key::Symbol, index::Integer=0; signature::Symbol=:high, args...) =\n BasicContMuvParameter(key, Val{signature}, index; args...)\n\nfunction BasicContMuvParameter(\n key::Symbol,\n ::Type{Val{:low}},\n index::Integer=0;\n pdf::Union{ContinuousMultivariateDistribution, Void}=nothing,\n prior::Union{ContinuousMultivariateDistribution, Void}=nothing,\n setpdf::Union{Function, Void}=nothing,\n setprior::Union{Function, Void}=nothing,\n loglikelihood::Union{Function, Void}=nothing,\n logprior::Union{Function, Void}=nothing,\n logtarget::Union{Function, Void}=nothing,\n gradloglikelihood::Union{Function, Void}=nothing,\n gradlogprior::Union{Function, Void}=nothing,\n gradlogtarget::Union{Function, Void}=nothing,\n tensorloglikelihood::Union{Function, Void}=nothing,\n tensorlogprior::Union{Function, Void}=nothing,\n tensorlogtarget::Union{Function, Void}=nothing,\n dtensorloglikelihood::Union{Function, Void}=nothing,\n dtensorlogprior::Union{Function, Void}=nothing,\n dtensorlogtarget::Union{Function, Void}=nothing,\n uptogradlogtarget::Union{Function, Void}=nothing,\n uptotensorlogtarget::Union{Function, Void}=nothing,\n uptodtensorlogtarget::Union{Function, Void}=nothing,\n states::VariableStateVector=VariableState[]\n)\n parameter = BasicContMuvParameter(key, index, pdf, prior, fill(nothing, 17)..., states)\n\n BasicContMuvParameter!(\n parameter,\n setpdf,\n setprior,\n loglikelihood,\n logprior,\n logtarget,\n gradloglikelihood,\n gradlogprior,\n gradlogtarget,\n tensorloglikelihood,\n tensorlogprior,\n tensorlogtarget,\n dtensorloglikelihood,\n dtensorlogprior,\n dtensorlogtarget,\n uptogradlogtarget,\n uptotensorlogtarget,\n uptodtensorlogtarget\n )\n\n parameter\nend\n\nfunction BasicContMuvParameter(\n key::Symbol,\n ::Type{Val{:high}},\n index::Integer=0;\n pdf::Union{ContinuousMultivariateDistribution, Void}=nothing,\n prior::Union{ContinuousMultivariateDistribution, Void}=nothing,\n setpdf::Union{Function, Void}=nothing,\n setprior::Union{Function, Void}=nothing,\n loglikelihood::Union{Function, Expr, Void}=nothing,\n logprior::Union{Function, Expr, Void}=nothing,\n logtarget::Union{Function, Expr, Void}=nothing,\n gradloglikelihood::Union{Function, Void}=nothing,\n gradlogprior::Union{Function, Void}=nothing,\n gradlogtarget::Union{Function, Void}=nothing,\n tensorloglikelihood::Union{Function, Void}=nothing,\n tensorlogprior::Union{Function, Void}=nothing,\n tensorlogtarget::Union{Function, Void}=nothing,\n dtensorloglikelihood::Union{Function, Void}=nothing,\n dtensorlogprior::Union{Function, Void}=nothing,\n dtensorlogtarget::Union{Function, Void}=nothing,\n uptogradlogtarget::Union{Function, Void}=nothing,\n uptotensorlogtarget::Union{Function, Void}=nothing,\n uptodtensorlogtarget::Union{Function, Void}=nothing,\n states::VariableStateVector=VariableState[],\n nkeys::Integer=0,\n vfarg::Bool=false,\n autodiff::Symbol=:none,\n order::Integer=1,\n chunksize::Integer=0,\n init::Vector=fill(Any[], 3)\n)\n inargs = (\n setpdf,\n setprior,\n loglikelihood,\n logprior,\n logtarget,\n gradloglikelihood,\n gradlogprior,\n gradlogtarget,\n tensorloglikelihood,\n tensorlogprior,\n tensorlogtarget,\n dtensorloglikelihood,\n dtensorlogprior,\n dtensorlogtarget,\n uptogradlogtarget,\n uptotensorlogtarget,\n uptodtensorlogtarget\n )\n\n fnames = Array(Any, 17)\n fnames[1:2] = fill(Symbol[], 2)\n fnames[3:14] = [Symbol[f] for f in fieldnames(BasicContMuvParameterState)[2:13]]\n for i in 1:3\n fnames[14+i] = Symbol[fnames[j][1] for j in 5:3:(5+i*3)]\n end\n\n for i in 3:5\n if isa(inargs[i], Expr) && autodiff != :reverse\n error(\"The only case $(fnames[i][1]) can be an expression is when used in conjunction with reverse mode autodiff\")\n end\n end\n\n if nkeys > 0\n if (autodiff == :forward || autodiff == :reverse) && vfarg\n error(\"In the case of autodiff, if nkeys is not 0, then vfarg must be false\")\n end\n elseif nkeys < 0\n \"nkeys must be non-negative, got $nkeys\"\n end\n\n if !in(autodiff, (:none, :forward, :reverse))\n error(\"autodiff must be :nore or :forward or :reverse, got $autodiff\")\n end\n\n if order < 0 || order > 2\n error(\"Derivative order must be 0, 1 or 2, got $order\")\n elseif autodiff != :reverse && order == 0\n error(\"Zero order can be used only with reverse mode autodiff\")\n end\n\n @assert chunksize >= 0 \"chunksize must be non-negative, got $chunksize\"\n\n initarg = Array(Any, 3)\n initlen = length(init)\n\n if initlen == 1 || initlen == 2\n if autodiff != :reverse\n @assert all(isempty, init) \"init option is used only for reverse mode autodiff\"\n end\n\n for i in 1:3\n initarg[i] = (inargs[i+2] != nothing) ? init : Any[]\n end\n elseif initlen == 3\n if autodiff != :reverse\n @assert all(isempty, init) \"init option is used only for reverse mode autodiff\"\n end\n\n initarg = init\n else\n error(\"init must be a vector of length 1, 2 or 3, got vector of length $initlen\")\n end\n\n parameter = BasicContMuvParameter(key, index, pdf, prior, fill(nothing, 17)..., states)\n\n outargs = Union{Function, Void}[nothing for i in 1:17]\n\n for i in 1:17\n if isa(inargs[i], Function)\n outargs[i] = eval(\n codegen_lowlevel_variable_method(inargs[i], :BasicContMuvParameterState, true, fnames[i], nkeys, vfarg)\n )\n end\n end\n\n if autodiff == :forward\n fadclosure = Array(Union{Function, Void}, 3)\n for i in 3:5\n fadclosure[i-2] =\n if isa(inargs[i], Function)\n nkeys == 0 ? inargs[i] : eval(codegen_internal_autodiff_closure(parameter, inargs[i], nkeys))\n else\n nothing\n end\n end\n\n for i in 6:8\n if !isa(inargs[i], Function) && isa(inargs[i-3], Function)\n outargs[i] = eval(codegen_lowlevel_variable_method(\n eval(codegen_forward_autodiff_function(Val{:gradient}, fadclosure[i-5], chunksize)),\n :BasicContMuvParameterState,\n true,\n fnames[i],\n 0\n ))\n end\n end\n\n if !isa(inargs[15], Function) && isa(inargs[5], Function)\n outargs[15] = eval(codegen_lowlevel_variable_method(\n eval(codegen_forward_autodiff_uptofunction(Val{:gradient}, fadclosure[3], chunksize)),\n :BasicContMuvParameterState,\n true,\n fnames[15],\n 0\n ))\n end\n\n if order >= 2\n for i in 9:11\n if !isa(inargs[i], Function) && isa(inargs[i-6], Function)\n outargs[i] = eval(codegen_lowlevel_variable_method(\n eval(codegen_forward_autodiff_target(:hessian, fadclosure[i-8], chunksize)),\n :BasicContMuvParameterState,\n true,\n fnames[i],\n 0\n ))\n end\n end\n\n if !isa(inargs[16], Function) && isa(inargs[5], Function)\n outargs[16] = eval(codegen_lowlevel_variable_method(\n eval(codegen_forward_autodiff_uptotarget(:hessian, fadclosure[3], chunksize)),\n :BasicContMuvParameterState,\n true,\n fnames[16],\n 0\n ))\n end\n end\n elseif autodiff == :reverse\n local f::Function\n\n for i in 3:5\n if isa(inargs[i], Expr)\n if nkeys == 0\n f = eval(codegen_reverse_autodiff_function(inargs[i], :Vector, initarg[i-2][1], 0, false))\n else\n f = eval(codegen_reverse_autodiff_function(inargs[i], :Vector, initarg[i-2], 0, false))\n f = eval(codegen_internal_autodiff_closure(parameter, f, nkeys))\n end\n\n outargs[i] = eval(codegen_lowlevel_variable_method(f, :BasicContMuvParameterState, true, fnames[i], 0))\n end\n end\n\n for i in 6:8\n if !isa(inargs[i], Function)\n if isa(inargs[i-3], Function)\n if nkeys == 0\n f = ReverseDiffSource.rdiff(inargs[i-3], (initarg[i-5][1][2],), order=1, allorders=false)\n else\n f = ReverseDiffSource.rdiff(\n inargs[i-3], (initarg[i-5][1][2], initarg[i-5][2][2]), ignore=[initarg[i-5][2][1]], order=1, allorders=false\n )\n f = eval(codegen_internal_autodiff_closure(parameter, f, nkeys))\n end\n\n outargs[i] = eval(codegen_lowlevel_variable_method(f, :BasicContMuvParameterState, true, fnames[i], 0))\n elseif isa(inargs[i-3], Expr)\n if nkeys == 0\n f = eval(codegen_reverse_autodiff_function(inargs[i-3], :Vector, initarg[i-5][1], 1, false))\n else\n f = eval(codegen_reverse_autodiff_function(inargs[i-3], :Vector, initarg[i-5], 1, false))\n f = eval(codegen_internal_autodiff_closure(parameter, f, nkeys))\n end\n\n outargs[i] = eval(codegen_lowlevel_variable_method(f, :BasicContMuvParameterState, true, fnames[i], 0))\n end\n end\n end\n\n if !isa(inargs[15], Function)\n if isa(inargs[5], Function)\n if nkeys == 0\n f = ReverseDiffSource.rdiff(inargs[5], (initarg[3][1][2],), order=1, allorders=true)\n else\n f = ReverseDiffSource.rdiff(\n inargs[5], (initarg[3][1][2], initarg[3][2][2]), ignore=[initarg[3][2][1]], order=1, allorders=true\n )\n f = eval(codegen_internal_autodiff_closure(parameter, f, nkeys))\n end\n\n outargs[15] = eval(codegen_lowlevel_variable_method(f, :BasicContMuvParameterState, true, fnames[15], 0))\n elseif isa(inargs[5], Expr)\n if nkeys == 0\n f = eval(codegen_reverse_autodiff_function(inargs[5], :Vector, initarg[3][1], 1, true))\n else\n f = eval(codegen_reverse_autodiff_function(inargs[5], :Vector, initarg[3], 1, true))\n f = eval(codegen_internal_autodiff_closure(parameter, f, nkeys))\n end\n\n outargs[15] = eval(codegen_lowlevel_variable_method(f, :BasicContMuvParameterState, true, fnames[15], 0))\n end\n end\n\n if order >= 2\n for i in 9:11\n if !isa(inargs[i], Function)\n if isa(inargs[i-6], Function) || isa(inargs[i-6], Expr)\n if nkeys == 0\n f = eval(codegen_reverse_autodiff_target(:hessian, inargs[i-6], :Vector, initarg[i-8][1]))\n else\n f = eval(codegen_reverse_autodiff_target(:hessian, inargs[i-6], :Vector, initarg[i-8]))\n f = eval(codegen_internal_autodiff_closure(parameter, f, nkeys))\n end\n\n outargs[i] = eval(codegen_lowlevel_variable_method(f, :BasicContMuvParameterState, true, fnames[i], 0))\n end\n end\n end\n\n if !isa(inargs[16], Function)\n if isa(inargs[5], Function) || isa(inargs[5], Expr)\n if nkeys == 0\n f = eval(codegen_reverse_autodiff_uptotarget(:hessian, inargs[5], :Vector, initarg[3][1]))\n else\n f = eval(codegen_reverse_autodiff_uptotarget(:hessian, inargs[5], :Vector, initarg[3]))\n f = eval(codegen_internal_autodiff_closure(parameter, f, nkeys))\n end\n\n outargs[16] = eval(codegen_lowlevel_variable_method(f, :BasicContMuvParameterState, true, fnames[16], 0))\n end\n end\n end\n end\n\n BasicContMuvParameter!(parameter, outargs...)\n\n parameter\nend\n\nfunction codegen_internal_autodiff_closure(parameter::BasicContMuvParameter, f::Function, nkeys::Integer)\n fstatesarg = [Expr(:ref, :Any, [:($(parameter).states[$i].value) for i in 1:nkeys]...)]\n\n @gensym internal_forward_autodiff_closure\n\n quote\n function $internal_forward_autodiff_closure(_x::Vector)\n $(f)(_x, $(fstatesarg...))\n end\n end\nend\n\nvalue_support(::Type{BasicContMuvParameter}) = Continuous\nvalue_support(::BasicContMuvParameter) = Continuous\n\nvariate_form(::Type{BasicContMuvParameter}) = Multivariate\nvariate_form(::BasicContMuvParameter) = Multivariate\n\ndefault_state_type(::BasicContMuvParameter) = BasicContMuvParameterState\n\ndefault_state{N<:Real}(variable::BasicContMuvParameter, value::Vector{N}, outopts::Dict) =\n BasicContMuvParameterState(\n value,\n [getfield(variable, fieldnames(BasicContMuvParameter)[i]) == nothing ? false : true for i in 10:18],\n (haskey(outopts, :diagnostics) && in(:accept, outopts[:diagnostics])) ? [:accept] : Symbol[]\n )\n\nBase.show(io::IO, ::Type{BasicContMuvParameter}) = print(io, \"BasicContMuvParameter\")\nBase.writemime(io::IO, ::MIME\"text/plain\", t::Type{BasicContMuvParameter}) = show(io, t)\n", "meta": {"hexsha": "ba96f288b5379013e7077d01fb03cec26994928a", "size": 21304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/variables/parameters/BasicContMuvParameter.jl", "max_stars_repo_name": "JuliaPackageMirrors/Klara.jl", "max_stars_repo_head_hexsha": "366d1e3829ebdc5021d6cd1fa2cc2b85d8abbc9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-10-05T21:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-30T15:32:39.000Z", "max_issues_repo_path": "src/variables/parameters/BasicContMuvParameter.jl", "max_issues_repo_name": "JuliaPackageMirrors/Lora.jl", "max_issues_repo_head_hexsha": "366d1e3829ebdc5021d6cd1fa2cc2b85d8abbc9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/variables/parameters/BasicContMuvParameter.jl", "max_forks_repo_name": "JuliaPackageMirrors/Lora.jl", "max_forks_repo_head_hexsha": "366d1e3829ebdc5021d6cd1fa2cc2b85d8abbc9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5749235474, "max_line_length": 124, "alphanum_fraction": 0.6551821254, "num_tokens": 6046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.24130592333619968}} {"text": "const sense_alias = Dict(\n\"max\" => :Max,\n\"maximize\" => :Max,\n\"maximise\" => :Max,\n\"maximum\" => :Max,\n\"min\" => :Min,\n\"minimize\" => :Min,\n\"minimise\" => :Min,\n\"minimum\" => :Min\n)\n\nconst subject_to_alias = [\"subject to\", \"such that\", \"st\", \"s.t.\"]\n\n# a list of section keywords in lower-case\nconst KEYWORDS = Dict(\n \"max\" => Val{:obj},\n \"maximize\" => Val{:obj},\n \"maximise\" => Val{:obj},\n \"maximum\" => Val{:obj},\n \"min\" => Val{:obj},\n \"minimize\" => Val{:obj},\n \"minimise\" => Val{:obj},\n \"minimum\" => Val{:obj},\n\n \"subject to\" => Val{:constraints},\n \"such that\" => Val{:constraints},\n \"st\" => Val{:constraints},\n \"s.t.\" => Val{:constraints},\n\n \"bounds\" => Val{:bounds},\n \"bound\" => Val{:bounds},\n\n \"gen\" => Val{:integer},\n \"general\" => Val{:integer},\n \"generals\" => Val{:integer},\n\n \"bin\" => Val{:binary},\n \"binary\" => Val{:binary},\n \"binaries\" => Val{:binary},\n\n \"end\" => Val{:quit}\n)\n\nconst COMMENT_REG = r\"(.*?)\\\\(.*)\"\nfunction stripcomment(line::String)\n if contains(line, \"\\\\\")\n m = match(COMMENT_REG, line)\n return strip(String(m[1]))\n else\n return strip(line)\n end\nend\n\nimmutable TempSparseMatrix\n i::Vector{Int}\n j::Vector{Int}\n v::Vector{Float64}\nend\nTempSparseMatrix() = TempSparseMatrix(Int[], Int[], Float64[])\nBase.sparse(m::TempSparseMatrix, nr::Int, nc::Int) = sparse(m.i, m.j, m.v, nr, nc)\n\nnewdatastore() = Dict(\n :A => TempSparseMatrix(),\n :collb => Float64[],\n :colub => Float64[],\n :c => Float64[],\n :rowlb => Float64[],\n :rowub => Float64[],\n :sense => :Min,\n :colcat => Symbol[],\n :sos => SOS[],\n :Q => TempSparseMatrix(),\n :modelname => \"\",\n :colnames => String[],\n :rownames => String[],\n :open_constraint => false\n)\nsetsense!(T, data, line) = nothing\nfunction setsense!(::Type{Val{:obj}}, data, line)\n data[:sense] = sense_alias[lowercase(line)]\nend\nfunction read(filename::String)\n data = newdatastore()\n open(filename, \"r\") do io\n section = :none\n while !eof(io)\n line = stripcomment(readline(io))\n if line == \"\" # skip blank lines\n continue\n end\n if haskey(KEYWORDS, lowercase(line)) # section has changed\n section = KEYWORDS[lowercase(line)]\n setsense!(section, data, line)\n continue\n end\n parsesection!(section, data, line)\n end\n end\n return sparse(data[:A], length(data[:rownames]), length(data[:colnames])),\n data[:collb],\n data[:colub],\n data[:c],\n data[:rowlb],\n data[:rowub],\n data[:sense],\n data[:colcat],\n data[:sos],\n sparse(data[:Q], length(data[:rownames]), length(data[:colnames])),\n data[:modelname],\n data[:colnames],\n data[:rownames]\nend\n\nparsesection!(::Type{Val{:quit}}, data, line) = error(\"Corrupted LP File. You have the lne $(line) after an end.\")\n\nfunction parsesection!(::Type{Val{:obj}}, data, line)\n # okay so line should be the start of the objective\n if contains(line, \":\")\n # throw away name\n m = match(r\"(.*?)\\:(.*)\", line)\n line = String(m[2])\n end\n tokens = tokenize(line)\n if length(tokens) == 0 # no objective\n return\n end\n # tokens should be in order (+/-) (numeric) (variable) ...\n while length(tokens) > 0\n variable = String(pop!(tokens))\n idx = getvariableindex!(data, variable) # catch in here for malformed variables\n coef_token = pop!(tokens)\n try\n coefficient = parse(Float64, coef_token)\n catch\n error(\"Unable to parse objective. Expected numeric coefficient. Got $(coef_token)\")\n end\n if length(tokens) > 0\n _sign = pop!(tokens)\n if _sign == \"-\"\n coefficient *= -1\n elseif _sign == \"+\"\n else\n error(\"Unable to parse objective due to bad operator: $(_sign) $(line)\")\n end\n end\n data[:c][idx] = coefficient\n end\nend\n\nconst constraintsense = Dict(\n \"<\" => :le,\n \"<=\" => :le,\n \"=\" => :eq,\n \"==\" => :eq,\n \">\" => :ge,\n \">=\" => :ge,\n)\n\nfunction parseconstraintcoefficients!(data, line, tokens, rowidx)\n # tokens should be in order (+/-) (numeric) (variable) ...\n while length(tokens) > 0\n variable = String(pop!(tokens))\n idx = getvariableindex!(data, variable) # catch in here for malformed variables\n coef_token = pop!(tokens)\n try\n coefficient = parse(Float64, coef_token)\n catch\n error(\"Unable to parse constraint $(line). Expected numeric coefficient. Got $(coef_token)\")\n end\n if length(tokens) > 0\n _sign = pop!(tokens)\n if _sign == \"-\"\n coefficient *= -1\n elseif _sign == \"+\"\n else\n error(\"Unable to parse objective due to bad operator: $(_sign) $(line)\")\n end\n end\n push!(data[:A].i, rowidx)\n push!(data[:A].j, idx)\n push!(data[:A].v, coefficient)\n end\nend\n\nfunction parsesos!(data, line)\n tokens = tokenize(line)\n if length(tokens) < 3\n error(string(\"Malformed SOS constraint: \", line))\n end\n if tokens[2] == \"S1::\"\n order = 1\n elseif tokens[2] == \"S2::\"\n order = 2\n else\n error(\"SOS of type $(tokens[2]) not recognised\")\n end\n names = String[]\n weights = Float64[]\n for token in tokens[3:end]\n items = split(token, \":\")\n if length(items) != 2\n error(string(\"Invalid sequence: \", token))\n end\n push!(names, String(items[1]))\n push!(weights, parsefloat(String(items[2])))\n end\n indices = Int[]\n for name in names\n idx = findfirst(data[:colnames], name)\n if idx == 0\n push!(data[:colnames], name)\n push!(indices, length(data[:colnames]))\n else\n push!(indices, idx)\n end\n end\n push!(data[:sos], (order, indices, weights))\nend\n\nfunction parsesection!(::Type{Val{:constraints}}, data, line)\n if match(r\" S([0-9]):: \", line) != nothing\n # it's an SOS constraint\n parsesos!(data, line)\n return\n end\n if data[:open_constraint] == false\n push!(data[:rownames], \"R$(length(data[:rownames]) + 1)\")\n push!(data[:rowlb], -Inf)\n push!(data[:rowub], Inf)\n end\n if contains(line, \":\")\n if data[:open_constraint] == true\n error(\"Malformed constraint $(line). Is the previous one valid?\")\n end\n # throw away name\n m = match(r\"(.*?)\\:(.*)\", line)\n data[:rownames][end] = String(m[1])\n line = String(m[2])\n end\n data[:open_constraint] = true\n\n tokens = tokenize(line)\n if length(tokens) == 0 # no entries\n return\n elseif length(tokens) >= 2 && haskey(constraintsense, tokens[end-1])# test if constraint ends this line\n rhs = parsefloat(pop!(tokens))\n sym = pop!(tokens)\n if constraintsense[sym] == :le\n data[:rowub][end] = rhs\n elseif constraintsense[sym] == :ge\n data[:rowlb][end] = rhs\n elseif constraintsense[sym] == :eq\n data[:rowlb][end] = rhs\n data[:rowub][end] = rhs\n end\n data[:open_constraint] = false # finished\n end\n parseconstraintcoefficients!(data, line, tokens, length(data[:rownames]))\nend\n\n\nfunction getvariableindex!(data, v)\n i = findfirst(data[:colnames], v)\n if i == 0\n if !verifyname(v)\n error(\"Invalid variable name $v\")\n end\n addnewvariable!(data, v)\n return length(data[:colnames])\n end\n return i\nend\n\nfunction addnewvariable!(data, name)\n push!(data[:collb], -Inf)\n push!(data[:colub], Inf)\n push!(data[:c], 0)\n push!(data[:colcat], :Cont)\n push!(data[:colnames], name)\nend\n\nfunction parsevariabletype!(data, line, cat)\n items = tokenize(line)\n for v in items\n i = getvariableindex!(data, v)\n data[:colcat][i] = cat\n end\nend\nparsesection!(::Type{Val{:integer}}, data, line) = parsevariabletype!(data, line, :Int)\nparsesection!(::Type{Val{:binary}}, data, line) = parsevariabletype!(data, line, :Bin)\n\nfunction parsefloat(val::String)\n if lowercase(val) == \"-inf\" || lowercase(val) == \"-infinity\"\n return -Inf\n elseif lowercase(val) == \"+inf\" || lowercase(val) == \"+infinity\"\n return Inf\n else\n return parse(Float64, val)\n end\nend\nfunction tokenize(line)\n items = String.(split(line, \" \"))\n items[items .!= \"\"]\nend\nbounderror(line) = error(\"Unable to parse bound: $(line)\")\nfunction parsesection!(::Type{Val{:bounds}}, data, line)\n items = tokenize(line)\n v = \"\"\n lb = -Inf\n ub = Inf\n if length(items) == 5 # ranged bound\n v = items[3]\n if (items[2] == \"<=\" || items[2] == \"<\") && (items[4] == \"<=\" || items[4] == \"<\") # le\n lb = parsefloat(items[1])\n ub = parsefloat(items[5])\n elseif (items[2] == \">=\" || items[2] == \">\") && (items[4] == \">=\" || items[4] == \">\") # ge\n lb = parsefloat(items[5])\n ub = parsefloat(items[1])\n else\n bounderror(line)\n end\n elseif length(items) == 3 # one sided\n v = items[1]\n if items[2] == \"<=\" || items[2] == \"<\" # le\n ub = parsefloat(items[3])\n elseif items[2] == \">=\" || items[2] == \">\" # ge\n lb = parsefloat(items[3])\n elseif items[2] == \"==\" || items[2] == \"=\" # eq\n lb = ub = parsefloat(items[3])\n else\n bounderror(line)\n end\n elseif length(items) == 2 # free\n if items[2] != \"free\"\n bounderror(line)\n end\n v = items[1]\n else\n bounderror(line)\n end\n i = getvariableindex!(data, v)\n data[:collb][i] = lb\n data[:colub][i] = ub\n\nend\n", "meta": {"hexsha": "f24cf5b4ccb077d88e12fa95ec4338f45a3fa5c5", "size": 10025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/reader.jl", "max_stars_repo_name": "odow/LPWriter.jl", "max_stars_repo_head_hexsha": "b04707fd028fd95e61f3aef90c5b258096f48f1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-07-05T16:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-19T12:32:50.000Z", "max_issues_repo_path": "src/reader.jl", "max_issues_repo_name": "odow/LPWriter.jl", "max_issues_repo_head_hexsha": "b04707fd028fd95e61f3aef90c5b258096f48f1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-07-04T06:04:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-24T00:07:53.000Z", "max_forks_repo_path": "src/reader.jl", "max_forks_repo_name": "odow/LPWriter.jl", "max_forks_repo_head_hexsha": "b04707fd028fd95e61f3aef90c5b258096f48f1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-21T15:27:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T15:27:24.000Z", "avg_line_length": 28.9739884393, "max_line_length": 114, "alphanum_fraction": 0.532967581, "num_tokens": 2757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24130592333619963}} {"text": "\n\n\n# This needs actual performance testing.\n@generated function Chunk(::Val{N}) where N\n if 4N <= VectorizationBase.REGISTER_SIZE\n P = N\n else\n p1 = round(Int, 4N / VectorizationBase.REGISTER_SIZE, RoundUp)\n P = round(Int, N / p1, RoundUp)\n end\n ForwardDiff.Chunk{P}()\nend\n@generated ValP1(::Val{N}) where N = Val{N+1}()\n@generated ValM1(::Val{N}) where N = Val{N-1}()\n\n\nmutable struct GradientDiffResult{V,P,R} <: DiffResults.DiffResult{1,V,Tuple{ConstantFixedSizeVector{P,V,R,R}}}\n grad::ConstantFixedSizeVector{P,V,R,R}\n value::V\n function GradientDiffResult{V,P,R}(::UndefInitializer) where {V, P, R}\n new{V,P,R}()\n end\n @generated function GradientDiffResult{V,P}(::UndefInitializer) where {V, P}\n R = PaddedMatrices.calc_padding(P, V)\n :(GradientDiffResult{$V,$P,$R}(undef))\n end\n function GradientDiffResult(g::ConstantFixedSizeVector{P,V,R,R}, v::V = zero(V)) where {P,V,R}\n GradientDiffResult{P,V,R}(g, v)\n end\nend\nmutable struct HessianDiffResult{V,P,R,L} <: DiffResults.DiffResult{2,V,Tuple{ConstantFixedSizeVector{P,V,R,R},ConstantFixedSizeMatrix{P,P,V,R,L}}}\n grad::ConstantFixedSizeVector{P,V,R,R}\n hess::ConstantFixedSizeMatrix{P,P,V,R,L}\n value::V\n function HessianDiffResult{V,P,R,L}(::UndefInitializer) where {V,P,R,L}\n new{V,P,R,L}()\n end\n @generated function HessianDiffResult{V,P}(::UndefInitializer) where {V, P}\n N,R,L = PaddedMatrices.calc_NPL((P,P), V)\n :(HessianDiffResult{$V,$P,$R,$L}(undef))\n end\n function GradientDiffResult(g::ConstantFixedSizeVector{P,V,R,R}, H::ConstantFixedSizeMatrix{P,P,V,R,L}, v::V = zero(V)) where {P,V,R,L}\n GradientDiffResult{P,V,R,R}(g, H, v)\n end\nend\nconst GradResult{V,P,R} = Union{GradientDiffResult{V,P,R},HessianDiffResult{V,P,R}}\n@inline Base.pointer(result::GradResult{V}) where {V} = Base.unsafe_convert(Ptr{V}, pointer_from_objref(result))\n@inline DiffResults.derivative(result::GradResult{V,P,R}) where {V,P,R} = PtrVector{P,V,R}(pointer(result))\n@inline DiffResults.derivative(result::GradResult{V,P,R}, ::Type{Val{1}}) where {V,P,R} = PtrVector{P,V,R}(pointer(result))\n@inline DiffResults.derivative(result::HessianDiffResult{V,P,R}, ::Type{Val{2}}) where {V,P,R} = PtrVector{P,V,R}(pointer(result) + sizeof(V)*R )\n@inline DiffResults.gradient(result::GradResult{V,P,R}) where {V,P,R} = PtrVector{P,V,R}(pointer(result))\n@inline DiffResults.hessian(result::HessianDiffResult{V,P,R}) where {V,P,R}= PtrMatrix{P,P,V,R}(pointer(result) + sizeof(V)*R )\n\n@inline DiffResults.value!(r::GradResult, x::Number) = (r.value = x; return r)\n# @inline DiffResults.value!(r::GradResult, x::AbstractArray) = (copyto!(value(r), x); return r)\n@inline DiffResults.value!(f::F, r::GradResult, x::Number) where {F} = (r.value = f(x); return r)\n# @inline DiffResults.value!(f, r::GradResult, x::AbstractArray) = (map!(f, value(r), x); return r)\n\nfunction DiffResults.derivative!(r::GradResult, x::AbstractArray)\n copyto!(DiffResults.gradient(r), x)\n return r\nend\nfunction DiffResults.derivative!(r::GradResult, x::AbstractArray, ::Type{Val{1}})\n copyto!(DiffResults.gradient(r), x)\n return r\nend\nfunction DiffResults.derivative!(r::HessianDiffResult, x::AbstractArray, ::Type{Val{2}})\n copyto!(DiffResults.hessian(r), x)\n return r\nend\nfunction DiffResults.derivative!(r::GradResult{P,V,R}, x::ConstantFixedSizeVector{P,V,R}) where {P,V,R}\n r.grad = x\n return r\nend\nfunction DiffResults.derivative!(r::GradResult{P,V,R}, x::ConstantFixedSizeVector{P,V,R}, ::Type{Val{1}}) where {P,V,R}\n r.grad = x\n return r\nend\nfunction DiffResults.derivative!(r::HessianDiffResult{P,V,R,L}, x::ConstantFixedSizeMatrix{P,P,V,R,L}, ::Type{Val{2}}) where {P,V,R,L}\n r.hess = x\n return r\nend\n# function DiffResults.derivative!(f, r::GradResult, x::Number)\n# r.grad = f(x)\n# return r\n# end\n# function DiffResults.derivative!(f, r::GradResult, x::AbstractArray)\n# map!(f, r.grad, x)\n# return r\n# end\n\n\nfunction GradientDiffResult(x::SizedVector{P,T}) where {T,P}\n GradientDiffResult{T,P}(undef)\nend\nfunction HessianDiffResult(x::SizedVector{P,T}) where {T,P}\n HessianDiffResult{T,P}(undef)\n # HessianDiffResult(zero(T), similar(x), FixedSizeMatrix{P,P,T}(undef))\nend\n# function HessianDiffResult(x::MVector{P,T}) where {T,P}\n# HessianDiffResult{T,P}(undef)\n# # HessianDiffResult(zero(T), similar(x), MMatrix{P,P,T}(undef))\n# end\n\nabstract type AbstractAutoDiffDifferentiable{P,T} <: AbstractDifferentiableObject{P,T} end\nabstract type AbstractOnceDifferentiableObject{P,T} <: AbstractAutoDiffDifferentiable{P,T} end\nabstract type AbstractTwiceDifferentiableObject{P,T} <: AbstractAutoDiffDifferentiable{P,T} end\nabstract type Configuration{P,V,F} end\n\nstruct GradientConfiguration{P,V,F,T,ND,DG,R} <: Configuration{P,V,F}\n f::F\n result::GradientDiffResult{V,P,R}\n gconfig::ForwardDiff.GradientConfig{T,V,ND,DG}\nend\n\nstruct HessianConfiguration{P,V,F,T,T2,ND,DJ,DG,DG2, R_V, R_D, LSQM} <: Configuration{P,V,F}\n f::F\n result::HessianDiffResult{V,P,R_V,LSQM}\n inner_result::GradientDiffResult{ForwardDiff.Dual{T,V,ND},P,R_D}\n jacobian_config::ForwardDiff.JacobianConfig{T,V,ND,DJ}\n gradient_config::ForwardDiff.GradientConfig{T,ForwardDiff.Dual{T,V,ND},ND,DG}\n gconfig::ForwardDiff.GradientConfig{T2,V,ND,DG2}\nend\n\n\nstruct TwiceDifferentiable{P,T,F,C<:Configuration{P,T,F}, SV_V <: SizedVector{P,T}} <: AbstractTwiceDifferentiableObject{P,T}\n x_f::SV_V # x used to evaluate f (stored in F)\n x_df::SV_V # x used to evaluate df (stored in DF)\n x_h::SV_V #??\n config::C\nend\nstruct OnceDifferentiable{P,T,F,C<:GradientConfiguration{P,T,F}, SV_V <: SizedVector{P,T}} <: AbstractOnceDifferentiableObject{P,T}\n x_f::SV_V# x used to evaluate f (stored in F)\n x_df::SV_V # x used to evaluate df (stored in DF)\n config::C\nend\n\n\nfunction GradientConfiguration(f::F, x::SizedVector{P,T}) where {F,T,P}\n result = GradientDiffResult(x)\n chunk = Chunk(Val{P}())\n tag = ForwardDiff.Tag(f, T)\n gconfig = ForwardDiff.GradientConfig(f, x, chunk, tag)\n\n GradientConfiguration(f, result, gconfig)\nend\nextract_tag(::T) where {T} = T\nfunction HessianConfiguration(f::F, x::SizedVector{P,T}) where {F,T,P}\n result = HessianDiffResult(x)\n chunk = Chunk(Val{P}())\n # tag = ForwardDiff.Tag(f, T)\n\n # here we construct a JacobianConfig so that yduals is a PtrVector to DiffResults.gradient(inner_result)\n tag_instance = ForwardDiff.Tag(f, T)\n tag_type = extract_tag(tag_instance)\n # @show tag\n seeds = ForwardDiff.construct_seeds(ForwardDiff.Partials{P,T})\n # inner_result = GradientDiffResult(jacobian_config.duals[2])\n inner_result = GradientDiffResult{ForwardDiff.Dual{tag_type,T,P},P}(undef)\n duals = (DiffResults.gradient(inner_result), similar(x, ForwardDiff.Dual{tag_type,T,P}))\n jacobian_config = ForwardDiff.JacobianConfig{tag_type,T,P,typeof(duals)}(seeds, duals)\n\n\n # jacobian_config = ForwardDiff.JacobianConfig((f,ForwardDiff.gradient), DiffResults.gradient(result), x, chunk, tag)\n # jacobian_config = ForwardDiff.JacobianConfig((f,ForwardDiff.gradient), DiffResults.gradient(result), x, chunk, tag)\n gradient_config = ForwardDiff.GradientConfig(f, jacobian_config.duals[2], chunk, tag_instance)\n \n gconfig = ForwardDiff.GradientConfig(f, x, chunk, tag_instance)\n\n HessianConfiguration(f, result, inner_result, jacobian_config, gradient_config, gconfig)\nend\n\nTwiceDifferentiable(f::F, ::Val{P}) where {F,P} = TwiceDifferentiable(f, FixedSizeVector{P,Float64}(undef))\nfunction TwiceDifferentiable(f::F, x::SV_V) where {F,T,P,SV_V <: SizedVector{P,T}}\n TwiceDifferentiable(x, similar(x), similar(x), HessianConfiguration(f, x))\nend\nfunction TwiceDifferentiable(x_f::SV_V,x_df::SV_V,x_h::SV_V,config::C) where {T,F,C<:Configuration{T,F},P,SV_V <: SizedVector{P,T}}\n TwiceDifferentiable{P,T,F,C}(x_f, x_df, x_h, config)\nend\n\n\n\nfunction OnceDifferentiable(f, x_f::SizedVector{P,T}) where {T,P}\n OnceDifferentiable(x_f, similar(x_f), GradientConfiguration(f, x_f))\nend\nfunction OnceDifferentiable(x_f::SV_V, config::C) where {T,F,C<:GradientConfiguration{T,F},P,SV_V <: SizedVector{P,T}}\n OnceDifferentiable{P,T,F,C}(x_f, similar(x_f), config)\nend\n\n# ProfileDifferentiable(f::F, ::Val{N}) where {F,N} = ProfileDifferentiable(f, Vector{Float64}(undef, N), Val{N}())\n# function ProfileDifferentiable(f::F, x::AbstractArray{T}, ::Val{N}) where {F,T,N}\n# x_f = Vector{T}(undef, N-1)\n# ProfileDifferentiable(x_f, similar(x_f), similar(x_f), Configuration(f, x_f, ValM1(Val{N}())), x, Ref(N), Ref{T}(),::Val{N})\n# end\n# function ProfileDifferentiable(x_f::Vector{T},x_df::Vector{T},x_h::Vector{T}, config::C, x,::A i::RefValue{Int}, v::RefValue{T},::Val{N}) where {T,A<:AbstractArray{T},C,N}\n# ProfileDifferentiable{N,T,A,C}(x_f, x_df, x_h, config, x, i, v)\n# end\n\n\n@inline DiffResults.value!(obj::AbstractAutoDiffDifferentiable, x::Real) = DiffResults.value!(obj.config.result, x)\n\n@inline value(obj::AbstractAutoDiffDifferentiable) = obj.config.result.value\n@inline gradient(obj::AbstractAutoDiffDifferentiable) = DiffResults.gradient(obj.config.result)\n# @inline gradient(obj::AbstractAutoDiffDifferentiable, i::Integer) = DiffResults.gradient(obj.config.result)[i]\n@inline hessian(obj::TwiceDifferentiable) = DiffResults.hessian(obj.config.result)\n\n\n@inline f(obj::AbstractAutoDiffDifferentiable, x) = obj.config.f(x)\n\n# \"\"\"\n# For DynamicHMC support. Copies data.\n# \"\"\"\n# @inline function (obj::OnceDifferentiable)(x)\n# fdf(obj, x)\n# DiffResults.ImmutableDiffResult(-obj.config.result.value, (-1 .* obj.config.result.grad,))\n# end\n# @inline function (obj::TwiceDifferentiable)(x)\n# fdf(obj, x)\n# DiffResults.ImmutableDiffResult(-obj.config.result.value, (-1 .* obj.config.result.grad,))\n# end\n\n@inline function df(obj::AbstractAutoDiffDifferentiable, x)\n ForwardDiff.gradient!(gradient(obj), obj.config.f, x, obj.config.gconfig, Val{false}())\nend\n\n@inline function fdf(obj::AbstractAutoDiffDifferentiable, x)\n # obj.config.result.grad = gradient(obj)\n ForwardDiff.gradient!(obj.config.result, obj.config.f, x, obj.config.gconfig, Val{false}())\n # DiffResults.value(obj.config.result)\n obj.config.result.value\nend\n@inline function scale_fdf(obj::AbstractAutoDiffDifferentiable, x, scale_target)\n # obj.config.result.grad = gradient(obj)\n scale = scale_gradient!(obj.config.result, obj.config.f, x, scale_target, obj.config.gconfig, Val{false}())\n # DiffResults.value(obj.config.result)\n obj.config.result.value, scale\nend\n@inline function scaled_fdf(obj::AbstractAutoDiffDifferentiable, x, scale)\n # obj.config.result.grad = gradient(obj)\n scaled_gradient!(obj.config.result, obj.config.f, x, scale, obj.config.gconfig, Val{false}())\n # DiffResults.value(obj.config.result)\n obj.config.result.value\nend\n\n# function Configuration(f::F, x::AbstractArray{V}, chunk::Chunk = Chunk(x), tag = Tag(f, V)) where {F,V}\n# result = DiffResults.HessianResult(x)\n# jacobian_config = ForwardDiff.JacobianConfig((f,gradient), DiffResults.gradient(result), x, chunk, tag)\n# gradient_config = ForwardDiff.GradientConfig(f, jacobian_config.duals[2], chunk, tag)\n# inner_result = DiffResults.DiffResult(zero(eltype(jacobian_config.duals[2])), jacobian_config.duals[2])\n# gconfig = ForwardDiff.GradientConfig(f, x, chunk, tag)\n# Configuration(f, result, inner_result, jacobian_config, gradient_config, gconfig)\n# end\n\n@inline function (c::HessianConfiguration)(y, z)\n # c.inner_result.grad = y #Already true?\n # @show typeof(y), typeof(z)\n ForwardDiff.gradient!(c.inner_result, c.f, z, c.gradient_config, Val{false}())\n DiffResults.value!(c.result, ForwardDiff.value(DiffResults.value(c.inner_result)))\n # copyto!(y, DiffResults.gradient(c.inner_result))\n y\nend\n@inline function hessian!(c::HessianConfiguration, x::AbstractArray)\n ForwardDiff.jacobian!(DiffResults.hessian(c.result), c, DiffResults.gradient(c.result), x, c.jacobian_config, Val{false}())\n # DiffResults.hessian(c.result)\n DiffResults.hessian(c.result)\nend\n\n\"\"\"\nForce (re-)evaluation of the objective value at `x`.\n\nReturns `f(x)` and stores the value in `obj.F`\n\"\"\"\n@inline function value!!(obj::AbstractAutoDiffDifferentiable, x)\n # obj.f_calls .+= 1\n # copyto!(obj.x_f, x)\n DiffResults.value!(obj, f(obj, x) )\n value(obj)\nend\n# \"\"\"\n# Evaluates the objective value at `x`.\n#\n# Returns `f(x)`, but does *not* store the value in `obj.F`\n# \"\"\"\n# @inline function value(obj::AbstractAutoDiffDifferentiable, x)\n# if x != obj.x_f\n# # obj.f_calls .+= 1\n# value!!(obj, x)\n# end\n# value(obj)\n# end\n\"\"\"\nEvaluates the objective value at `x`.\n\nReturns `f(x)` and stores the value in `obj.F`\n\"\"\"\n@inline function value!(obj::AbstractAutoDiffDifferentiable, x)\n # if x != obj.x_f\n value!!(obj, x)\n # end\n value(obj)\nend\n\n\"\"\"\nEvaluates the gradient value at `x`\n\nThis does *not* update `obj.DF`.\n\"\"\"\n@inline function gradient(obj::AbstractAutoDiffDifferentiable, x)\n DF = gradient(obj)\n gradient!!(obj, x)\n DF\nend\n\"\"\"\nEvaluates the gradient value at `x`.\n\nStores the value in `obj.DF`.\n\"\"\"\n@inline function gradient!(obj::AbstractAutoDiffDifferentiable, x)\n # if x != obj.x_df\n gradient!!(obj, x)\n # end\n gradient(obj)\nend\n\"\"\"\nForce (re-)evaluation of the gradient value at `x`.\n\nStores the value in `obj.DF`.\n\"\"\"\n@inline function gradient!!(obj::AbstractAutoDiffDifferentiable, x)\n # obj.df_calls .+= 1\n copyto!(obj.x_df, x)\n df(obj, x)\nend\n\n@inline function value_gradient!(obj::AbstractAutoDiffDifferentiable, x)\n # if x != obj.x_f && x != obj.x_df\n value_gradient!!(obj, x)\n # elseif x != obj.x_f\n # value!!(obj, x)\n # elseif x != obj.x_df\n # gradient!!(obj, x)\n # end\n value(obj)\nend\n@inline function value_gradient!!(obj::AbstractAutoDiffDifferentiable, x)\n # obj.f_calls .+= 1\n # obj.df_calls .+= 1\n # copyto!(obj.x_f, x)\n # copyto!(obj.x_df, x)\n DiffResults.value!(obj, fdf(obj, x))\nend\n\n@inline function hessian!(obj::AbstractAutoDiffDifferentiable, x)\n # if x != obj.x_h\n hessian!!(obj, x)\n # end\n nothing\nend\n@inline function hessian!!(obj::AbstractAutoDiffDifferentiable, x)\n # obj.h_calls .+= 1\n # copyto!(obj.x_h, x)\n hessian!(obj.config, x)\nend\n\n\n\n# function ForwardDiff.vector_mode_dual_eval(f::F, x::FixedSizeVector, cfg::Union{JacobianConfig,GradientConfig}) where F\n# xdual = cfg.duals\n# seed!(xdual, x, cfg.seeds)\n# return f(xdual)\n# end\n\n@inline function ForwardDiff.seed!(duals::AbstractMutableFixedSizeVector{P,ForwardDiff.Dual{T,V,N}}, x,\n seed::ForwardDiff.Partials{N,V}) where {T,V,N,P}\n @inbounds for i in 1:N\n duals[i] = ForwardDiff.Dual{T,V,N}(x[i], seed)\n end\n return duals\nend\n\n@inline function ForwardDiff.seed!(duals::AbstractMutableFixedSizeVector{P,ForwardDiff.Dual{T,V,N}}, x,\n seeds::NTuple{N,ForwardDiff.Partials{N,V}}) where {T,V,N,P}\n @inbounds for i in 1:N\n duals[i] = ForwardDiff.Dual{T,V,N}(x[i], seeds[i])\n end\n return duals\nend\n\n@inline function ForwardDiff.seed!(duals::AbstractMutableFixedSizeVector{P,ForwardDiff.Dual{T,V,N}}, x, index,\n seed::ForwardDiff.Partials{N,V} = zero(ForwardDiff.Partials{N,V})) where {T,V,N,P}\n offset = index - 1\n @inbounds for i in 1:N\n j = i + offset\n duals[j] = ForwardDiff.Dual{T,V,N}(x[j], seed)\n end\n return duals\nend\n\n@inline function ForwardDiff.seed!(duals::AbstractMutableFixedSizeVector{P,ForwardDiff.Dual{T,V,N}}, x, index,\n seeds::NTuple{N,ForwardDiff.Partials{N,V}}, chunksize = N) where {T,V,N,P}\n offset = index - 1\n @inbounds for i in 1:chunksize\n j = i + offset\n duals[j] = ForwardDiff.Dual{T,V,N}(x[j], seeds[i])\n end\n return duals\nend\nfunction ForwardDiff.extract_jacobian!(::Type{T}, result::AbstractMutableFixedSizeMatrix{M,N}, ydual::AbstractArray, n) where {M,N,T}\n # out_reshaped = reshape(result, length(ydual), n)\n # @inbounds for col in 1:size(out_reshaped, 2), row in 1:size(out_reshaped, 1)\n # out_reshaped[row, col] = partials(T, ydual[row], col)\n # end\n @inbounds for col in 1:N, row in 1:M\n # result[row, col] = ForwardDiff.partials(T, ydual[row], col)\n result[row, col] = ForwardDiff.partials(T, ydual[col], row)\n end\n return result\nend\n", "meta": {"hexsha": "b43eeb4470036bec89e874ab6a34f78c693d14fd", "size": 16579, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/forward_diff_differentiable.jl", "max_stars_repo_name": "chriselrod/DifferentiableObjects.jl", "max_stars_repo_head_hexsha": "2c088ac7c7e87d5562ce367548002f2117e5fe82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/forward_diff_differentiable.jl", "max_issues_repo_name": "chriselrod/DifferentiableObjects.jl", "max_issues_repo_head_hexsha": "2c088ac7c7e87d5562ce367548002f2117e5fe82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/forward_diff_differentiable.jl", "max_forks_repo_name": "chriselrod/DifferentiableObjects.jl", "max_forks_repo_head_hexsha": "2c088ac7c7e87d5562ce367548002f2117e5fe82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:55:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:55:10.000Z", "avg_line_length": 39.4738095238, "max_line_length": 173, "alphanum_fraction": 0.6894867, "num_tokens": 4886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24118198136642008}} {"text": "\n\"\"\"\nData structure\n--------------\nmutable struct: SELF.recording\n\nFunctions\n---------\nSELF.recording.filter()\n\nSELF.recording.resample()\n\nSELF.recording.detect_spikes()\n\"\"\"\nmodule Neurons\n\nexport recording, normalize_trace, filter_trace, resample, detect_spikes, detect_spikes1, get_PSD, extract_spikes, extract_features, cluster_spikes, find_redundant, extract_isih,\n\t\tplot_detection, plot_waveforms\n\nusing DSP\nusing Images\nusing Statistics\nusing MultivariateStats\nusing GaussianMixtures\nusing Clustering\nusing LinearAlgebra\nusing Distances\nusing PyPlot\n\nusing ..MyUtils\n\n# main type\n\"\"\"\nFields\n------\n+ file::String\n+ sf::Real\n+ sf_preprocessed::Real\n+ n_channels::Real\n+ trace::AbstractArray # supposed to contain sample X channel\n+ trial_marker::AbstractArray\n+ trace_preprocessed::AbstractArray\n+ preprocessing_steps::Vector{String}\n+ spike_idx::AbstractArray\n+ detection_threshold::AbstractArray\n+ isih::AbstractArray\n+ spikeforms::AbstractArray # channel (val_source) X channel (t_source) X time of spike/spikeform X sample\n+ features::AbstractArray # channel X feature space representation of spikes\n+ spike_class::AbstractArray # channel X clusters (as spike indices)\n+ BIC::AbstractArray\n\"\"\"\nmutable struct recording\n ### FIELDS\n file::String\n sf::Real\n sf_preprocessed::Real\n n_channels::Real\n trace::Array{Array{Float64,2}}#AbstractArray # supposed to contain sample X channel\n trial_marker::AbstractArray\n trace_preprocessed::Array{Array{Float64,2}}#AbstractArray\n preprocessing_steps::Vector{String}\n spike_idx::AbstractArray\n\tdetection_threshold::AbstractArray\n isih::AbstractArray\n spikeforms::AbstractArray # channel (val_source) X channel (t_source) X time of spike/spikeform X sample\n features::AbstractArray # channel X feature space representation of spikes\n spike_class::AbstractArray # channel X clusters (as spike indices)\n BIC::AbstractArray\n\n ### CONSTRUCTOR\n # recording(file, sf, trace, trial_marker) =\n # new(file, sf, 0, trace, trial_marker, Array{Float64,2}(undef,0,0), Vector{String}(undef,0), Array{Float64,3}Array{Float64,2}(undef,0,0,0))\n # recording() = new(\"\", 0, 0, Array{Float64,2}(undef,0,0), Array{Float64,2}(undef,0,0), Array{Float64,2}(undef,0,0), Vector{String}(undef,0), Array{Float64,3}(undef,0,0,0))\n recording() = new(\"\", 0, 0, 0, [], [], [], Vector{String}(undef,0), [], [], [], [], [], [])\nend\n\n\n\n# functions\n\nfunction normalize_trace(n::Neurons.recording, what=\"trace\")\n\n\n\tx = deepcopy( getfield( n, Symbol(what) ) )\n\tsd = std.(x)\n\tmn = mean.(x)\n\t[x[ii]=(x[ii] .- mn[ii]) ./ sd[ii] for ii in 1:n.n_channels] ### normalization\n\tn.trace_preprocessed = x\n\tn.preprocessing_steps = [\"normalized\"];\n\nend\n\n\"\"\"\nDocumentation ...\n\"\"\"\nfunction filter_trace(n::Neurons.recording, filter_type::String, freqs::AbstractArray, filter_design::AbstractArray, filter_order::AbstractArray, bandwidth::AbstractArray, from_chnnls::AbstractArray, what::String=\"trace\")\n\"\"\"\n filter(n::recording, band::Tuple{Real}, filter_type)\n filter_type: lowpass, highpass, bandpass, notch\n freqs = highpass: freq | lowpass: freq | passband (Wn1,Wn2) frequency | Notch: array of frequencies | CommonAverage: channels used for averaging\n what: spcifies whether filter works on trace or trace_preprocessed. If the latter trace_preprocessed is replaced, respectively.\n\"\"\"\n\n ######################\n ### raw trace\n ######################\n if what == \"trace\"\n nyq = n.sf/2;\n freqs_n = freqs./nyq; # normalized to nquist frequncy\n n.trace_preprocessed = []\n n.sf_preprocessed = n.sf # restore original sampling frequency\n\n if filter_type == \"Bandpass\"\n rt = Bandpass( freqs_n[1], freqs_n[2] );\n dm = getfield( Main, Symbol(filter_design[1]) )(filter_order[1]);\n f = digitalfilter(rt, dm);\n ### loop over channels and filter trace\n for trc in n.trace\n #trc_padded = flatten([[.0 for ii in 1:pads], trc, [.0 for ii in 1:pads]])\n #push!(n.trace_preprocessed, filtfilt(f, trc_padded)[pads+1:end-pads]);\n push!(n.trace_preprocessed, filtfilt(f, trc));\n end\n elseif filter_type == \"Lowpass\"\n rt = Lowpass( freqs_n[1] );\n dm = getfield( Main,Symbol(filter_design[1]) )(filter_order[1]);\n f = digitalfilter(rt, dm);\n for trc in n.trace\n # trc_padded = flatten([[.0 for ii in 1:pads], trc, [.0 for ii in 1:pads]])\n # push!(n.trace_preprocessed, filtfilt(f, trc_padded)[pads+1:end-pads]);\n push!(n.trace_preprocessed, filtfilt(f, trc));\n end\n elseif filter_type == \"Highpass\"\n rt = Highpass( freqs_n[1] );\n dm = getfield( Main,Symbol(filter_design[1]) )(filter_order[1]);\n f = digitalfilter(rt, dm);\n for trc in n.trace\n # trc_padded = flatten([[.0 for ii in 1:pads], trc, [.0 for ii in 1:pads]])\n # push!(n.trace_preprocessed, filt(f, trc_padded)[pads+1:end-pads]);\n push!(n.trace_preprocessed, filtfilt(f, trc));\n end\n elseif filter_type == \"Notch\"\n for trc in n.trace\n trc = flatten(trc)\n for ff in freqs_n.*nyq\n nn = iirnotch(ff, bandwidth[1]; fs=n.sf)\n trc = filtfilt(nn, trc);\n end\n push!(n.trace_preprocessed, trc);\n end\n elseif filter_type == \"CommonAverage\"\n chnnls = freqs\n average_trace = [median([n.trace[ch][idx] for ch in chnnls]) for idx in 1:length(n.trace[1])]\n # n.trace_preprocessed = [channel .- average_trace for channel in n.trace[from_chnnls]]\n\t\t\t[n.trace_preprocessed[ch] = n.trace_preprocessed[ch] .- average_trace for ch in from_chnnls]\n #n.trace_preprocessed = [ch .- mean(n.trace) for ch in n.trace]\n end\n n.preprocessing_steps = [string( filter_type, \": \",freqs )];\n\n ######################\n ### preprocessed trace\n ######################\n elseif what == \"trace_preprocessed\" && !isempty(n.preprocessing_steps)\n nyq = n.sf_preprocessed/2;\n freqs_n = freqs./nyq; # normalized to nquist frequncy\n\n if filter_type == \"Bandpass\"\n rt = Bandpass( freqs_n[1], freqs_n[2] );\n dm = getfield( Main,Symbol(filter_design[1]) )(filter_order[1]);\n f = digitalfilter(rt, dm);\n for (itrc, trc) in enumerate(n.trace_preprocessed)\n # trc_padded = flatten([[.0 for ii in 1:pads], trc, [.0 for ii in 1:pads]])\n # n.trace_preprocessed[itrc] = filt(f, trc_padded)[pads+1:end-pads];\n n.trace_preprocessed[itrc] = filtfilt(f, trc);\n end\n elseif filter_type == \"Lowpass\"\n rt = Lowpass( freqs_n[1] );\n dm = getfield( Main,Symbol(filter_design[1]) )(filter_order[1]);\n f = digitalfilter(rt, dm);\n for (itrc, trc) in enumerate(n.trace_preprocessed)\n # trc_padded = flatten([[.0 for ii in 1:pads], trc, [.0 for ii in 1:pads]])\n # n.trace_preprocessed[itrc] = filt(f, trc_padded)[pads+1:end-pads];\n n.trace_preprocessed[itrc] = filtfilt(f, trc);\n end\n elseif filter_type == \"Highpass\"\n rt = Highpass( freqs_n[1] );\n dm = getfield( Main,Symbol(filter_design[1]) )(filter_order[1]);\n f = digitalfilter(rt, dm);\n for (itrc, trc) in enumerate(n.trace_preprocessed)\n # trc_padded = flatten([[.0 for ii in 1:pads], trc, [.0 for ii in 1:pads]])\n # n.trace_preprocessed[itrc] = filt(f, trc_padded)[pads+1:end-pads];\n n.trace_preprocessed[itrc] = filtfilt(f, trc);\n end\n elseif filter_type == \"Notch\"\n for (itrc, trc) in enumerate(n.trace_preprocessed)\n trc = flatten(trc)\n for ff in freqs_n.*nyq\n nn = iirnotch(ff, bandwidth[1]; fs=n.sf_preprocessed)\n trc = filtfilt(nn, trc);\n end\n n.trace_preprocessed[itrc] = trc;\n end\n elseif filter_type == \"CommonAverage\"\n chnnls = freqs\n average_trace = [median([n.trace_preprocessed[ch][idx] for ch in chnnls]) for idx in 1:length(n.trace_preprocessed[1])]\n # n.trace_preprocessed = [channel .- average_trace for channel in n.trace_preprocessed]\n\t\t\t[n.trace_preprocessed[ch] = n.trace_preprocessed[ch] .- average_trace for ch in from_chnnls]\n\t\t\t#n.trace_preprocessed = [ch .- mean(n.trace_preprocessed) for ch in n.trace_preprocessed]\n end\n push!(n.preprocessing_steps, string( filter_type, \": \", freqs ));\n else\n print(n.preprocessing_steps)\n @warn \"SELF.trace_preprocessed is empty. Process SELF.trace first\"\n end\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\"\nArguments:\n\n+ n::Neurons.recording\n+ chans::Array{Int64,1}\n+ SNR::Array{Float64,1}\n+ lockout::Int64=30;\n+ polarity::String=\"negative\",\n+ ww::Array{Int64,1}=[5,15],\n+ stp::Int64=1,\n+ w_lockout::Array{Int64,1}=[10],\n+ method::String=\"petrantonakis\"\n\n\"\"\"\nfunction detect_spikes(\n\tn::Neurons.recording,\n\tchans::Array{Int64,1},\n\tSNR::Array{Float64,1},\n\tlockout::Int64=30;\n\t#\n\tpolarity::String=\"negative\",\n\tww::Array{Int64,1}=[5,15],\n\tstp::Int64=1,\n\tw_lockout::Array{Int64,1}=[10],\n\tmethod::String=\"petrantonakis\")\n#\n# spikes are stored as:s\n# n.spike_idx: channel X w X Dw/indices of peaks (Dw only if method is \"petrantonakis\")\n#\n# w: window length if method is \"petrantonakis\"\n# (for consistency if method is \"threshold\" the same structure is stored )\n\n\n### WAVEFORM/THRESHOLD BASED SPIKE DETECITON\n if method == \"petrantonakis\" ### ref: https://www.frontiersin.org/articles/10.3389/fnins.2015.00452/full\n # Dw = [ [[] for ii in 1:n.n_channels] for jj in eachindex(ww) ] # ww X channel\n # Spks = [ [CartesianIndex{1}[] for ii in 1:n.n_channels] for jj in eachindex(ww) ] # ww X channel\n Dw_spk = [ [[[],[]] for ii in eachindex(ww)] for jj in 1:n.n_channels ] ### ch X w X Dw,spk_idx\n\t\tn.detection_threshold = []\n\n # for (ii,ch) in enumerate([n.trace_preprocessed[2]]) ### loop over channels\n\t\tfor ii in chans ### loop over channels\n\n\t\t\tch = n.trace_preprocessed[ii]\n\n\t\t\tfor (jj,w) in enumerate(ww) ### loop over w\n\n ### compute the Dw signal (euklidean distance signal)\n f = ch[collect(0:w-1).+collect(1:stp:length(ch)-w+1)'] ### cut signal in overlapping chunks\n\t\t\t\tDw_spk[ii][jj][1] = flatten(sqrt.(sum(diff(f, dims=2).^2, dims=1))); ### compute euclidean distance between consecutive chunks\n\n ### normalization of Dw\n\t\t\t\tsig = median( Dw_spk[ii][jj][1] ./ 0.6745 )\n\t\t\t\tthr = SNR[jj]*sig\n\t\t\t\tappend!(n.detection_threshold, thr)\n # Dw_spk[ii][jj][1] = Dw_spk[ii][jj][1] ./ th ### store the standardized Dw signal\n ### find all local mixima in Dw\n loc_maxima = findlocalmaxima(Float64.(Dw_spk[ii][jj][1])) ### find all local maxima\n ### remove local mixima < thr\n Dw_spk[ii][jj][2] = loc_maxima[findall(Dw_spk[ii][jj][1][loc_maxima] .> thr)] ### extract all local maxima > SNR, SNR depends on w\n\n ### remove redundant triggered spikes and keep the maximum of each\n if length(Dw_spk[ii][jj][2]) > 1\n\n\t\t\t\t\tDw_spk[ii][jj][2] = find_redundant( Dw_spk[ii][jj][1], Dw_spk[ii][jj][2], lockout );\n\n\t\t\t\tend\n\n\t\t\tend #for w: jj\n\n ### remove spikes that are detected only by one value of w\n\t\t\tloop_cntr = 0\n\t\t\twhile length(Dw_spk[ii][1][2]) != length(Dw_spk[ii][2][2]) ### necessary if there a spikes in value of w with less spikes that are not in w with more spikes\n\n\t\t\t\tloop_cntr += 1\n\n\t\t\t\tif loop_cntr == 10 ### 2 should be enough\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tend\n\n\t\t\t\tif !any( [(length(Dw_spk[ii][1][2])==0), (length(Dw_spk[ii][2][2])==0)] )\n\n\t\t\t\t\tif length(Dw_spk[ii][1][2]) > length(Dw_spk[ii][2][2])\n\n\t\t\t\t\t\tdd = pairwise(Euclidean(), cartesian2matrix(Dw_spk[ii][2][2])', cartesian2matrix(Dw_spk[ii][1][2])', dims=2)\n\t\t\t\t\t deleteat!(Dw_spk[ii][1][2], findall(flatten(.!any(dd .< w_lockout, dims=1)))) ### delete all spikes in Dw_spk[ii][1][2] that do not have a partner spike in Dw_spk[ii][2][2]\n\n\t\t\t\t\telseif length(Dw_spk[ii][1][2]) < length(Dw_spk[ii][2][2])\n\n\t\t\t\t\t\tdd = pairwise(Euclidean(), cartesian2matrix(Dw_spk[ii][1][2])', cartesian2matrix(Dw_spk[ii][2][2])', dims=2)\n\t\t\t\t\t deleteat!(Dw_spk[ii][2][2], findall(flatten(.!any(dd .< w_lockout, dims=1))))\n\n\t\t\t\t\tend\n\n\t\t\t\telse ### if one has no spikes at all\n\n\t\t\t\t\tDw_spk[ii][1][2] = [];\n\t\t\t\t\tDw_spk[ii][2][2] = [];\n\t\t\t\t\t# Dw_spk[ii][1][1] = []\n\t\t\t\t\t# Dw_spk[ii][2][1] = []\n\n\t\t\t\tend\n\n\t\t\tend\n\n\t\t\tif length(Dw_spk[ii][1][2]) != length(Dw_spk[ii][2][2])\n\n\t\t\t\t@info \"@Channel \", ii, \": different spike numbers for values of w\"\n\n\t\t\tend\n\n\t\t\t### scatter plot of w1 X w2\n\t if (length(spk_idx_w1)-length(spk_idx_w1) == 0) && length(recording.spike_idx[channel][1][2]) != 0\n\n\t ax1 = subplot(1,3,1)\n\t w1 = recording.spike_idx[channel][1][1][spk_idx_w1]\n\t w2 = recording.spike_idx[channel][2][1][spk_idx_w2]\n\t pols = cartesian2polar(w1, w2)\n\t r = pols[:,1]\n\t phi = pols[:,2]\n\t ax1.scatter( r, phi, color=pcols[2])\n\n\t end\n\n end #for channels: ii\n\n ### THRESHOLD BASED SPIKE DETECTION\n elseif method == \"threshold\"\n\n\t\tDw_spk = [ [[[],[]] for ii in [1]] for jj in 1:n.n_channels ] ### ch X w X DW,spk_idx\n\t\tn.detection_threshold = ones(n.n_channels) .* NaN\n x = n.trace_preprocessed[chans]\n\n sig = [median(abs.(ch) ./ 0.6745 ) for ch in x]\n\t\tthr = SNR[1] .* sig\n\t\tn.detection_threshold[chans] = thr\n\n # x = .-x ./ th\n\n if polarity == \"both\"\n\n\t\t\tind_max = findlocalmaxima.(x)\n ind_max = [[lm[1] for lm in ch] for ch in ind_max] # cartesian coordinates to indices\n ind_min = findlocalminima.(x)\n ind_min = [[lm[1] for lm in ch] for ch in ind_min]\n ind_max = [ind_max[ii][findall(x[ii][ind_max[ii]] .> thr[ii])] for ii in eachindex(chans)] # local minima with minimal SNR\n ind_min = [ind_min[ii][findall(x[ii][ind_min[ii]] .< -thr[ii])] for ii in eachindex(chans)] # local maxima with minimal SNR\n ind = [sort(flatten([ind_max[ii], ind_min[ii]])) for ii in 1:length(ind_max)] # channel X index_of_spikes\n\n\t\telseif polarity == \"positive\"\n\n\t\t\tind = findlocalmaxima.(x)\n ind = [[lm[1] for lm in ch] for ch in ind] # cartesian coordinates to indices\n ind = [ind[ii][findall(x[ii][ind[ii]] .> thr[ii])] for ii in eachindex(chans)] # local minima with minimal SNR\n\n\t\telseif polarity == \"negative\"\n\n\t\t\tind = findlocalminima.(x)\n ind = [[lm[1] for lm in ch] for ch in ind] # cartesian coordinates to indices\n ind = [ind[ii][findall(x[ii][ind[ii]] .< -thr[ii])] for ii in eachindex(chans)]\n\n\t\tend\n\n ### remove redundantly triggered spikes and store the maximum respectively\n for (ii,ch) in enumerate(chans)\n\n\t\t\tchans_spike_idxs = ind[ii]\n \t\tDw_spk[ch][1][2] = CartesianIndex.( find_redundant( x[ii], chans_spike_idxs, lockout ) )\n\n\t\tend\n\n end # method\n\n ### store clean indices in struct\n # n.spike_idx = ind_clean#[ind_clean[ii][d[ii]] for ii in 1:length(ind_clean)]\n n.spike_idx = Dw_spk; # channel X w X Dw/index of peak (Dw only if method is \"petrantonakis\")\nend\n\n\n\n\n\"\"\"\nDocumentation ...\n\"\"\"\nfunction extract_isih(n::Neurons.recording)\n### Extracts the inter-spike intervals\n dt = 1/n.sf_preprocessed\n isih = []\n for ch in eachindex(n.spike_idx)\n push!(isih, [])\n for w in eachindex(n.spike_idx[1])\n push!(isih[ch], [])\n if length(n.spike_idx[ch][w][2]) > 1\n isih[ch][w] = cartesian2matrix(diff(n.spike_idx[ch][w][2])) .* dt\n end\n end\n end\n n.isih = isih # value_source X w X time_source X time/values\nend\n\n\n\n\n\"\"\"\nDocumentation ...\n\"\"\"\nfunction extract_spikes(n::Neurons.recording, mp, w::Int64=1)\n### Extract spike spikeforms and time stamps in ms.\n# extracts the spikeforms at indices n.spike_idx (normalized around zero)\n# from the filtered signal x using a fixed window around the\n# window +-mp of the spikes.\n#\tONLY FOR ONE VALUE OF w\n# structure: n.spikeforms[val_source][time_source][spike_time/value]\n#\n\n dt = 1/n.sf_preprocessed\n\twindow = collect(mp[1]:1:mp[2]);\n\tspkfrms = []\n\n\tfor ii in 1:n.n_channels # loop over channels as value source\n\n\t\tpush!(spkfrms, [])\n\t # for w in 1:size(n.spike_idx[1],1)\n\t # push!(spkfrms[ii], [])\n\n\t\t\tfor (jj,spk_idxs) in enumerate(n.spike_idx) # loop over channels for time source\n\n\t\t\t\tpush!(spkfrms[ii], [[],[]]) ### t, s\n\n\t\t\t\tfor spk in spk_idxs[w][2] # loop over individual spikes\n\n\t\t\t\t # skip spikes that have negative indices\n\t spike_window_idxs = spk.I .+ window # generate window for each spike\n\t spike_window_times = spike_window_idxs .* dt .* 1000 # spike times in ms\n\n\t\t\t\t\tif spike_window_idxs[1] > 0 && spike_window_idxs[end] <= length(n.trace_preprocessed[ii])# skip spikes that are not complete in window\n\n\t\t\t\t\t\tpush!( spkfrms[ii][jj][1], spike_window_times ) # store spike times\n\t push!( spkfrms[ii][jj][2], n.trace_preprocessed[ii][spike_window_idxs] .- mean( n.trace_preprocessed[ii][spike_window_idxs]) ) #store spike values\n\n\t\t\t\t\tend\n\t end\n\t end\n\t # end\n\tend\n\tn.spikeforms = spkfrms # value_source X w X time_source X time/values\n\nend\n\n\n\n\n\n\"\"\"\nDocumentation ...\n\"\"\"\nfunction extract_features(n::Neurons.recording)\n n.features = []\n for ch in 1:n.n_channels\n push!(n.features, [])\n if !isempty(n.spikeforms[ch][ch][2])\n ### make matrix for PCA\n m = zeros(length(n.spikeforms[ch][ch][2]), length(n.spikeforms[ch][ch][2][1])); # #spikes X #samples per spike\n [m[ii,:] = n.spikeforms[ch][ch][2][ii] for ii = 1:length(n.spikeforms[ch][ch][2])]; # spike X sample\n ### fit PCA\n M = fit(PCA, m)\n n.features[ch] = projection(M) # projection(M): spike X PC\n end\n end\nend\n\n\n\n\"\"\"\nDocumentation ...\n\"\"\"\nfunction cluster_spikes(n::Neurons.recording, algorithm::AbstractArray, init_method::AbstractArray, feats::AbstractArray, n_clusters::AbstractArray, nIter_EM::AbstractArray, nIter_kmeans_init::AbstractArray, cov_kind::AbstractArray)\n\n############\n# cluster given features using _algorithm_\n# BIC optimization for cluster number\n#\n########\n# algorithm: kmeans\n#\n########\n# algorithm: gmm\n# init_method: :split or :kmeans\n\n n.spike_class = []\n ###\n if algorithm[1] == \"kmeans\"\n for ch in 1:n.n_channels\n #push!(n.spike_class, [])\n if size(n.features[ch], 2) > feats[end] # if there are enough features\n result = kmeans(n.features[ch][:,feats]', n_clusters[1]);\n clusters = []\n for cl = 1:n_clusters[1]\n push!(clusters, findall(result.assignments .== cl))\n end\n push!(n.spike_class, clusters)\n else ### push empty array for that channel\n push!(n.spike_class, [])\n end\n end\n ###\n elseif algorithm[1] == \"gmm\"\n n.BIC = []\n ### for each channel fit gmm with n components specified in\n ### n_clusters, compute BIC fear each value, find minimum BIC and use\n ### for clustering\n for ch in 1:n.n_channels\n if size(n.features[ch],2) > length(feats) ### if enough features\n N = size(n.features[ch][:,feats], 1)\n BICS = Array{Float64,2}(undef, 0, 2)\n for cmpnts in n_clusters\n if size(n.features[ch], 1) > cmpnts\n M = GMM(cmpnts, n.features[ch][:,feats];\n method=init_method[1], kind=cov_kind[1], nInit=nIter_kmeans_init[1], nIter=nIter_EM[1], nFinal=nIter_EM[1])\n LL = sum(llpg(M, n.features[ch][:,feats]))\n par = cmpnts + cmpnts*length(feats) + cmpnts* length(feats)*(length(feats)+1)/2 # number of parameters\n bic = -2*LL + log.(N)*par\n BICS = vcat(BICS, [cmpnts bic])\n end\n end\n push!(n.BIC, BICS)\n ### fit model with optimal number of components and cluster spikes\n opt_cmpnts = Int(BICS[findmin(BICS[:,2])[2]])\n push!(n.spike_class, [])\n M = GMM(opt_cmpnts, n.features[ch][:,feats];\n method=init_method[1], kind=cov_kind[1], nInit=nIter_kmeans_init[1], nIter=nIter_EM[1], nFinal=nIter_EM[1])\n posteriors = gmmposterior( M, n.features[ch][:,feats] )\n classes = [findmax(posteriors[1], dims=2)[2][spk][2] for spk in 1:length(findmax(posteriors[1], dims=2)[2])] ### extract cluster index for each spike from CartesianCoordinates\n n.spike_class[ch] = [[] for ii in 1:opt_cmpnts]\n for (spk_idx,cl) in enumerate(classes)\n push!(n.spike_class[ch][cl], spk_idx)\n end\n else\n push!(n.spike_class, [])\n push!(n.BIC, [])\n end\n end\n # for ch in 1:n.n_channels\n # print(ch)\n # push!(n.spike_class, [])\n # if size(n.features[ch],2) > length(feats) ### if enough features\n # M = GMM(n_clusters[1], n.features[ch][:,feats];\n # method=:kmeans, kind=cov_kind[1], nInit=nIter_kmeans_init[1], nIter=nIter_EM[1], nFinal=nIter_EM[1])\n # posteriors = gmmposterior( M, n.features[ch][:,feats] )\n # classes = [findmax(posteriors[1], dims=2)[2][spk][2] for spk in 1:length(findmax(posteriors[1], dims=2)[2])] ### extract cluster index for each spike from CartesianCoordinates\n # n.spike_class[ch] = [[] for ii in 1:n_clusters[1]]\n # for (spk_idx,cl) in enumerate(classes)\n # push!(n.spike_class[ch][cl], spk_idx)\n # end\n # else\n # n.spike_class[ch] = [[] for ii in 1:n_clusters[1]]\n # end\n # end\n end\nend\n\n\n\n\n\n\n\"\"\"\nUp- or downsampling\nActs on either n.trace or n.trace_preprocessed\n\"\"\"\nfunction resample(n::Neurons.recording, frequency::Real)\n #idx = 1:factor:size(n.trace)[1]\n #n.trace_preprocessed = n.trace[idx];\n #n.sf_decimated = n.sf/factor;\n if isempty(n.preprocessing_steps)\n n.trace_preprocessed = DSP.resample( n.trace,frequency//convert(Int64, n.sf) );\n else\n n.trace_preprocessed = DSP.resample( n.trace_preprocessed,frequency//convert(Int64, n.sf_preprocessed) );\n end\n n.sf_preprocessed = frequency;\n push!(n.preprocessing_steps, string( \"Decimated to: \",frequency ))\nend\n\n\"\"\"\nUp- or downsampling\nActs on either n.trace or n.trace_preprocessed\n\"\"\"\nfunction get_PSD(n::Neurons.recording, which, psd_type)\n if which == \"trace\"\n return [getfield( Main, Symbol(psd_type) )( flatten(ch), fs=n.sf ) for ch in n.trace]\n elseif which == \"trace_preprocessed\"\n return [getfield( Main, Symbol(psd_type) )( flatten(ch), fs=n.sf_preprocessed ) for ch in n.trace_preprocessed]\n end\nend\n\n\n\n\nfunction find_redundant(ref::AbstractArray, ind::AbstractArray, lockout::Int)\n ### ref: 1D array containing amplitude like values\n ### ind: 1D array containing indices of identified events, e.g. spikes\n ### lockout: Integer defining minimum distance of evvents in samples that are treated as separate events\n\n ### make sure it's cartesian!\n ind = CartesianIndex.(ind)\n ### matrix with all pairs of spike indices\n # mm = Iterators.product(flatten(cartesian2matrix(ind)), flatten(cartesian2matrix(ind)))\n\t### differences between all pairs of spike indices\n\t# dd = [ float(abs(diff([x for x in m])[1][1])) for m in mm ]\n\tdd = pairwise(Euclidean(), flatten(cartesian2matrix(ind))', flatten(cartesian2matrix(ind))', dims=2)\n\tdd[diagind(dd)] .= NaN # set diagonal to NaN\n\tsup_diag = dd[diagind(dd, 1)]\n\tgg = findall(x -> x > lockout, sup_diag )\n\n\tif all(sup_diag .> lockout) ### no double triggered spikes\n\n\t\tgroups = [[spk_idx] for spk_idx in ind]\n\n\telseif all(sup_diag .< lockout) ### only one double triggered spike\n\n\t\tgroups = [ind]\n\n\telse ### single and double triggered spikes\n\n\t\tgroups = []\n\t current_group = []\n\n\t\tfor (ij,spk_id) in enumerate(ind)\n\n\t\t\tpush!(current_group, spk_id)\n\n\t\t\tif in(ij, gg) || ij == length(ind) ### ij == length(ind) required for last element\n\n\t\t\t\tpush!(groups, current_group)\n\t current_group = []\n\n\t\t\tend\n\t\tend\n\tend\n\t### find maxima of groups and store indices\n ind_clean = []\n for gr in groups\n\n\t\tmax_id = findmax( abs.(ref[CartesianIndex.( gr )]) )\n\t\t# max_id = findmax(ref[gr])\n \tpush!(ind_clean, gr[max_id[2]])\n\n\tend\n\n #################\n ### DELETE ME ###a\n #################\n # ind_clean = []\n # ind_ = deepcopy(ind)\n # if length(ind_) > 1\n # groups = []\n # current_group = []\n # push!(current_group, ind_[1])\n # deleteat!(ind_, 1)\n #\n # ### extract groups of detected event that are too close to each other to represent seperate spikes\n # while !isempty(ind_)\n # ### while next data point is to close to preceeding one, add it to current group\n # while ind_[1][1]-current_group[end][1] < lockout ### double index because CartesianIndex\n # push!(current_group, ind_[1])\n # deleteat!(ind_, 1)\n # if isempty(ind_) ### if already at the last spike index\n # break;\n # end\n # end\n #\n # ### add current_group to group\n # push!(groups, current_group)\n # current_group = []\n # if !isempty(ind_) ### deals with if last index was already deleted in while loop\n # push!(current_group, ind_[1])\n # deleteat!(ind_, 1)\n # end\n # end\n #\n # ### for each group extract the maximum as representation\n # ind_c = []\n # for gr in groups\n # if length(gr) > 1 ### if the group is a \"group\"\n # gg = [gr[ii] for ii in eachindex(gr)]\n # push!( ind_c, gg[findmax(ref[gg])[2]] )\n # else ### if the group has only one entry\n # push!(ind_c, gr[1])\n # end\n # end\n # push!(ind_clean, ind_c)\n # else ### if no spikes in channel, add empty list to kepp size consistent\n # push!(ind_clean, [])\n # end\n\n return ind_clean\nend\n\n\n\n################\n### PLOTTING ###\n################\n\nfunction plot_detection(\n recording::Neurons.recording;\n channel::Int64,\n method::String=\"petrantonakis\",\n polarity::String=\"negative\")\n\n\tcolors = myColors() # from MyHelpers.jl\n\tpcols = map(col -> (red(col), green(col), blue(col)), colors)\n\n if method == \"petrantonakis\"\n\n fig = figure(figsize=(13,5))\n rc(\"xtick\",labelsize=8)\n rc(\"ytick\",labelsize=8)\n\n\t\t### time course of Dw signal\n Dw_w1 = recording.spike_idx[channel][1][1]\n Dw_w2 = recording.spike_idx[channel][2][1]\n\t\t### indices of spikes\n\t\tspk_idx_w1 = recording.spike_idx[channel][1][2]\n spk_idx_w2 = recording.spike_idx[channel][2][2]\n\t\t### spike indices from cartesian to matrix\n\t\tif !isempty(spk_idx_w1) && !isempty(spk_idx_w2)\n\t\t\tspk_idx_w1 = cartesian2matrix(spk_idx_w1)\n\t\t\tspk_idx_w2 = cartesian2matrix(spk_idx_w2)\n\t\tend\n w1_threshold = recording.detection_threshold[1]\n w2_threshold = recording.detection_threshold[2]\n\n ### scatter plot of w1 X w2\n if (length(spk_idx_w1)-length(spk_idx_w1) == 0) && length(recording.spike_idx[channel][1][2]) != 0\n\n ax1 = subplot(1,3,1)\n w1 = recording.spike_idx[channel][1][1][spk_idx_w1]\n w2 = recording.spike_idx[channel][2][1][spk_idx_w2]\n pols = cartesian2polar(w1, w2)\n r = pols[:,1]\n phi = pols[:,2]\n ax1.scatter( r, phi, color=pcols[2])\n\n end\n\n ax2 = subplot(1,3,2)\n ax2.plot( Dw_w1, color=pcols[1], zorder=1 )\n ax2.plot( 1:length(Dw_w1), ones(length(Dw_w1))*w1_threshold, color=:red, linestyle=\"--\" )\n if length(recording.spike_idx[channel][1][2]) > 0\n\n spk_idx_w1 = cartesian2matrix(recording.spike_idx[channel][1][2])\n ax2.scatter(spk_idx_w1, Dw_w1[spk_idx_w1], color=pcols[2], zorder=2)\n\n end\n\n ax3 = subplot(1,3,3)\n ax3.plot(Dw_w2, color=pcols[1], zorder=1)\n ax3.plot( 1:length(Dw_w2), ones(length(Dw_w2))*w2_threshold, color=:red, linestyle=\"--\" )\n\t\tif length(recording.spike_idx[channel][2][2]) > 0\n\n spk_idx_w2 = cartesian2matrix(recording.spike_idx[channel][2][2])\n ax3.scatter(spk_idx_w2, Dw_w2[spk_idx_w2], color=pcols[2], zorder=2)\n\n end\n\n elseif method == \"threshold\"\n\n fig = figure(figsize=(13,5))\n rc(\"xtick\",labelsize=8)\n rc(\"ytick\",labelsize=8)\n\n x = recording.trace_preprocessed[channel]\n spk_idx = cartesian2matrix(recording.spike_idx[channel][1][2])\n\n\t\tif polarity == \"negative\"\n\n\t\t\tthr = -recording.detection_threshold[channel]\n\n\t\telseif polarity == \"positive\"\n\n\t\t\tthr = recording.detection_threshold[channel]\n\n\t\telseif polarity == \"both\"\n\n\t\t\tthr = [-recording.detection_threshold[channel], recording.detection_threshold[channel]]\n end\n\n plot( x )\n scatter( spk_idx, x[spk_idx], color=pcols[2], zorder=2 )\n\n if length(thr) != 2\n\n\t\t\tplot( 1:length(x), ones(length(x))*thr, color=:red, linestyle=\"--\" )\n\n\t\telse\n\n\t\t\tplot( 1:length(x), ones(length(x))*thr[1], color=:red, linestyle=\"--\" )\n plot( 1:length(x), ones(length(x))*thr[2], color=:red, linestyle=\"--\" )\n end\n end\nend\n\n\nfunction plot_waveforms(\n\trecording::Neurons.recording,\n\tt::Array{Float64,1},\n\tylims::Array{Int64,2},\n\tw::Int64=1;\n\t#\n\tt_source )\n\t##########################\n\t##########################\n\t##########################\n\n\tcolors = myColors() # from MyHelpers.jl\n\tpcols = map(col -> (red(col), green(col), blue(col)), colors)\n\thalf_window = abs(minimum(t))/1000\n\n\tfig = figure(figsize=(15,7), dpi=300)\n\trc(\"xtick\",labelsize=4)\n\trc(\"ytick\",labelsize=4)\n\n\t# ylims = [-1000 1000]\n\n\tif t_source == \"val_source\"\n\t\tcorresponding = true\n\telse\n\t\tcorresponding = false\n\tend\n\n\tfor val_source = 1:recording.n_channels\n\t #### t_cource determines whose channels spike times are used to cut out the the waveforms: if t_cource = val_source then channel and spiketimes are matched, i.e. 1<->1, 2<->2 etc\n\t\tif corresponding\n\t\t\tt_source = val_source\n\t\tend\n\t# t_source = val_source\n\n\t ### sort spikes according to amplitude\n\t sorted_idx = sortperm([maximum(spk) for spk in recording.spikeforms[val_source][t_source][2]] .- [minimum(spk) for spk in recording.spikeforms[val_source][t_source][2]], rev=true )\n\t ### how many spikes to plot\n\t # n = length(sorted_idx)\n\t n = 10\n\n\t if !isempty(sorted_idx) ### if there are spikes in sorted_idx, i.e. if channel has spikes\n\n\t spks_to_plot = []\n\n\t ### loop over clusters of current channel\n\t if !isempty(recording.spike_class)\n\t for cl in recording.spike_class[t_source] ### plot the clusters based on the t_source channel\n\t push!(spks_to_plot, intersect(cl, sorted_idx))\n\t end\n\t else\n\t push!(spks_to_plot, sorted_idx) ### i.e. one \"cluster\" if not yet clustered\n\t end\n\n\n\t ### check if there are enough spikes if number of spikes to plot is specified\n\t if length(sorted_idx) < n\n\t n = length(sorted_idx)\n\t end\n\n\t ### plot spikes belonging to clusters\n\t\t\toffset = 0\n\t for (ii,spk_cl) in enumerate(spks_to_plot)\n\t if !isempty(spk_cl) ### cluster is not empty\n\t subplot(2,5,val_source)\n\t\t\t\t ### plot individual traces\n\t\t\t\t plot(t, reduce(hcat, recording.spikeforms[val_source][t_source][2][spk_cl]),\n\t\t\t\t\t color=pcols[ii], alpha=0.3, linewidth=0.1, zorder=1) ### plot individual spikes\n\t\t\t\t ### plot mean waveform +- std\n\t\t\t\t clusters_mean = mean(reduce(hcat, recording.spikeforms[val_source][t_source][2][spk_cl]), dims=2) .+ offset\n\t\t\t\t clusters_std = std(reduce(hcat, recording.spikeforms[val_source][t_source][2][spk_cl]), dims=2)\n\t\t\t\t plot(t, clusters_mean, color=pcols[ii], alpha=0.5, linewidth=0.5, zorder=2) ### plot mean spike waveform of cluster\n\t\t\t\t fill_between(t, flatten(clusters_mean+clusters_std), flatten(clusters_mean-clusters_std), color=pcols[ii], alpha=0.2, linewidth= 0.1)\n\t\t\t\t ###\n\t\t\t\t title(string(\"Channel \", val_source, \" (\", n, \")\"), fontsize=5)\n\t\t\t\t ylim(ylims[1], ylims[2])\n\t# \t\t\t legend()\n\t end\n\t\t\t\toffset = offset +0\n\t end\n\n\t ### add x- and ylabel\n\t if val_source in collect(6:10)\n\t subplot(2,5,val_source)\n\t xlabel(\"ms\", fontsize=5)\n\t elseif val_source in [1,6]\n\t subplot(2,5,val_source)\n\t# ylabel(\"amplitude\")\n\t end\n\t\t\tif val_source in collect(1:5)\n\t\t\t xticks(-half_window*1000:1:half_window*1000, []) ### half_window comes from waveform extraction step\n\t\t\tend\n\t\t\tif val_source in [2:5 7:10]\n\t\t\t yticks(ylims[1]:100:ylims[2], [])\n\t\t\tend\n\n\t else ### plot empty axes of channel has no spikes\n\t subplot(2,5,val_source)\n\t plot(t, t,\n\t linewidth=0)\n\t title(string(\"Channel \", val_source, \" (\", n, \")\"))\n\t ### add x- and ylabel\n\t ### add x- and ylabel\n\t if val_source in collect(6:10)\n\t subplot(2,5,val_source)\n\t xlabel(\"ms\", fontsize=5)\n\t elseif val_source in [1,6]\n\t subplot(2,5,val_source)\n\t# ylabel(\"amplitude\")\n\t end\n\t\t\tif val_source in collect(1:5)\n\t\t\t xticks(-4:2:4, [])\n\t\t\tend\n\t\t\tif val_source in [2:5 7:10]\n\t\t\t yticks(ylims[1]:100:ylims[2], [])\n\t\t\tend\n\n\t end\n\n\tend\n\nend\n\n\n\n\n\n\n###\nend\n", "meta": {"hexsha": "519a08ed4a35eaa08ccc3696178777562c9bc757", "size": 34191, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Neurons.jl", "max_stars_repo_name": "maalaria/Newbe", "max_stars_repo_head_hexsha": "d389fbd2d8e776c524601dc1f0e3552160ea9eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Neurons.jl", "max_issues_repo_name": "maalaria/Newbe", "max_issues_repo_head_hexsha": "d389fbd2d8e776c524601dc1f0e3552160ea9eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-06-17T19:22:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T21:29:12.000Z", "max_forks_repo_path": "src/Neurons.jl", "max_forks_repo_name": "maalaria/Newbe", "max_forks_repo_head_hexsha": "d389fbd2d8e776c524601dc1f0e3552160ea9eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2484536082, "max_line_length": 232, "alphanum_fraction": 0.598052119, "num_tokens": 9585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24106884341669138}} {"text": "module NAG\nexport\n nag_licence_query, nag_license_query,\n nag_complex_polygamma,\n nag_opt_read!,\n nag_opt_nlp!,\n nag_1d_quad_inf_1,\n nag_zero_cont_func_brent,\n nag_opt_lp!,\n last_nag_error\n\nnag_licence_query() = ccall((:a00acc, :libnagc_nag), Cint, ()) == 1\nconst nag_license_query = nag_licence_query # US vs UK spelling\nnag_license_query() || warn(\"Cannot acquire a NAG license.\")\n\nconst NagInt = Int32\nconst NagComplex = Complex128\n\ntype NagError <: Exception\n code::Int\n name::ASCIIString\n message::UTF8String\nend\n\nBase.showerror(io::IO, e::NagError) =\n print(io, \"NAG function \\\"$(e.name)\\\" [$(e.code)] – $(e.message)\")\n\nconst NAG_ERROR = zeros(Uint8,544)\nconst nag_errors = Array(NagError)\nnag_errors[] = NagError(0, \"\", \"NO_ERROR\")\n\ncstr_to_array(p::Ptr{Uint8}, own::Bool = false) =\n pointer_to_array(p, int(ccall(:strlen, Csize_t, (Ptr{Uint8},), p)), own)\n\nfunction error_handler(msg::Ptr{Uint8}, code::Cint, name::Ptr{Uint8})\n code == 0 && return\n msg = UTF8String(copy(cstr_to_array(msg)))\n name = ASCIIString(copy(cstr_to_array(name)))\n nag_errors[] = NagError(int(code), name, msg)\n throw(nag_errors[])\nend\nconst ptr_error_handler = cfunction(error_handler, Void, (Ptr{Uint8}, Cint, Ptr{Uint8}))\n\nfunction reset_nag_error()\n fill!(NAG_ERROR, 0)\n unsafe_store!(\n convert(Ptr{Ptr{Void}}, pointer(NAG_ERROR)) + 2*sizeof(Cint) + 512,\n ptr_error_handler\n )\nend\nreset_nag_error()\n\nlast_nag_error() = nag_errors[]\n\nconst objfunref = Array(Function)\nconst confunref = Array(Function)\n\nfunction objfun_wrapper(\n n::NagInt, x::Ptr{Float64}, objf::Ptr{Float64}, g::Ptr{Float64}, comm::Ptr{NagInt}\n)\n x = pointer_to_array(x,int(n),false)\n g = pointer_to_array(g,int(n),false)\n f = unsafe_load(comm)\n unsafe_store!(objf,objfunref[1](x,g,f))\n return nothing\nend\nconst c_objfun = cfunction(objfun_wrapper, Void,\n (NagInt, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{NagInt}))\n\nfunction confun_wrapper(\n n::NagInt, ncnlin::NagInt, needc::Ptr{NagInt}, x::Ptr{Float64},\n conf::Ptr{Float64}, conjac::Ptr{Float64}, comm::Ptr{NagInt}\n)\n needc = pointer_to_array(needc,int(ncnlin),false)\n x = pointer_to_array(x,int(n),false)\n conf = pointer_to_array(conf,int(ncnlin),false)\n conjac = pointer_to_array(conjac,(int(n),int(ncnlin)),false)\n flag = unsafe_load(comm)\n confunref[1](needc,x,conf,conjac,flag)\n return nothing\nend\nconst c_confun = cfunction(confun_wrapper, Void,\n (NagInt, NagInt, Ptr{NagInt}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{NagInt}))\n\nfunction nag_complex_polygamma(z::Number, k::Integer)\n ccall((:s14afc, :libnagc_nag), NagComplex,\n (NagComplex, NagInt, Ptr{Void}),\n z, k, NAG_ERROR)\nend\n\n# if Base.polygamma doesn't support complex args, use NAG\nif !applicable(Base.polygamma, 1, 1+2im)\n Base.polygamma(k::Int, z::Complex) = nag_complex_polygamma(z, k)\n Base.digamma(z::Complex) = polygamma(0, z)\n Base.trigamma(z::Complex) = polygamma(1, z)\nend\n\nfunction nag_opt_read!(name::ByteString, optfile::ByteString, print::Bool = false)\n options = zeros(Uint8,1440)\n ccall((:e04xxc, :libnagc_nag), Void, (Ptr{Void},), options)\n ccall((:e04xyc, :libnagc_nag), Void,\n (Ptr{Uint8}, Ptr{Uint8}, Ptr{Void}, Cint, Ptr{Uint8}, Ptr{Void}),\n name, optfile, options, print, \"stdout\", NAG_ERROR)\n return options\nend\n\nfunction nag_opt_lp!(\n A :: Matrix{Float64},\n bl :: Vector{Float64},\n bu :: Vector{Float64},\n c :: Vector{Float64},\n x :: Vector{Float64};\n optfile :: ByteString = \"\",\n transpose :: Bool = true,\n)\n # since NAG is row-major\n # when transpose == true the rows are linear constraints\n # when transpose == false the columns are linear constraints\n transpose && (A = A')\n \n n = length(c)\n tda, nclin = size(A)\n\n nclin > 0 && tda >= n ||\n error(\"bad linear constraint dimensions (tda ≱ n): $tda ≱ $n\")\n length(bl) == n + nclin ||\n error(\"wrong number of lower bounds: $(length(bl)) ≠ $(n + nclin)\")\n length(bu) == n + nclin ||\n error(\"wrong number of upper bounds: $(length(bu)) ≠ $(n + nclin)\")\n length(c) == n ||\n error(\"wrong number of coefficients: $(length(c)) ≠ $n\")\n length(x) == n ||\n error(\"wrong data vector size: $(length(x)) ≠ $n\")\n\n objf = zeros()\n options = isempty(optfile) ? C_NULL :\n convert(Ptr{Void}, nag_opt_read!(\"e04mfc\", optfile))\n\n reset_nag_error()\n ccall((:e04mfc,:libnagc_nag), Void,\n (NagInt, NagInt, Ptr{Float64}, NagInt, Ptr{Float64}, Ptr{Float64},\n Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Void}, Ptr{Void}, Ptr{Void}),\n n, nclin, A, tda, bl, bu, c, x, objf, options, C_NULL, NAG_ERROR)\n\n return x, objf[]\nend\n\nfunction nag_opt_nlp!(\n A :: Matrix{Float64},\n bl :: Vector{Float64},\n bu :: Vector{Float64},\n x :: Vector{Float64},\n objfun! :: Function,\n confun! :: Function,\n optfile :: ByteString = \"\",\n transpose :: Bool = true,\n)\n # since NAG is row-major\n # when transpose == true the rows are linear constraints\n # when transpose == false the columns are linear constraints\n transpose && (A = A')\n\n # extract various dimensions\n n = length(x)\n tda, nclin = size(A)\n ncnlin = length(bl) - n - nclin\n\n # check for usage problems\n length(bl) == length(bu) ||\n error(\"bounds vectors must have matching length\")\n lexcmp(bl,bu) <= 0 ||\n error(\"lower bounds cannot be greater than upper bounds\")\n 0 <= ncnlin ||\n error(\"as many bounds as variables and linear constraints must be given\")\n nclin == 0 || n <= tda ||\n error(\"second dimension of linear coefficients too small\")\n\n # allocate output variables\n objf = zeros()\n g = zeros(n)\n\n # save callbacks in globals\n objfunref[1] = objfun!\n confunref[1] = confun!\n\n options = isempty(optfile) ? C_NULL :\n convert(Ptr{Void}, nag_opt_read!(\"e04ucc\", optfile))\n\n reset_nag_error()\n ccall((:e04ucc, :libnagc_nag), Void,\n (NagInt, NagInt, NagInt, Ptr{Float64},\n NagInt, Ptr{Float64}, Ptr{Float64},\n Ptr{Void}, Ptr{Void},\n Ptr{Float64}, Ptr{Float64}, Ptr{Float64},\n Ptr{Void}, Ptr{Void}, Ptr{Void}),\n n, nclin, ncnlin, A,\n tda, bl, bu,\n c_objfun, c_confun,\n x, objf, g,\n options, C_NULL, NAG_ERROR)\n\n return x, objf[], g\nend\n\nconst quadfunref = Array(Function)\nquad_fun_wrapper(x::Float64, comm::Ptr{NagInt}) = quadfunref[1](x)::Float64\nconst c_quadfun = cfunction(quad_fun_wrapper, Float64, (Float64, Ptr{NagInt}))\n\nfunction nag_1d_quad_inf_1(\n f :: Function,\n boundinf :: Symbol = :Infinite,\n bound :: Float64 = 0.0;\n epsabs :: Float64 = 0.0,\n epsrel :: Float64 = sqrt(eps(Float64)),\n max_num_subint :: NagInt = int32(1e7),\n)\n max_num_subint > 0 || error(\"max num subint must be > 0\")\n boundinf_val =\n boundinf == :UpperSemiInfinite ? int32(1076 + 0) :\n boundinf == :LowerSemiInfinite ? int32(1076 + 1) :\n boundinf == :Infinite ? int32(1076 + 2) :\n error(\"\"\"\n invalid boundinf symbol: $boundinf\n must be one of: UpperSemiInfinite, LowerSemiInfinite, Infinite\n \"\"\")\n\n # allocate output variables\n result = zeros()\n abserr = zeros()\n qp = zeros(Uint8, 48)\n comm = zeros(Uint8, 8)\n\n quadfunref[] = f\n\n reset_nag_error()\n ccall((:d01smc, :libnagc_nag), Void,\n (Ptr{Void}, NagInt, Float64, Float64,\n Float64, NagInt, Ptr{Float64}, Ptr{Float64},\n Ptr{Void}, Ptr{Void}, Ptr{Void}),\n c_quadfun, boundinf_val, bound, epsabs,\n epsrel, max_num_subint, result, abserr,\n qp, comm, NAG_ERROR)\n\n return result[], abserr[]\nend\n\nconst quadfunref_brent = Array(Function)\nquad_fun_wrapper_brent(x::Float64, comm::Ptr{NagInt}) = quadfunref_brent[1](x)::Float64\nconst c_quadfun_brent = cfunction(quad_fun_wrapper_brent, Float64, (Float64, Ptr{NagInt}))\n\nfunction nag_zero_cont_func_brent(\n a :: Float64,\n b :: Float64,\n f :: Function;\n eps :: Float64 = 1e-5,\n eta :: Float64 = 0.0,\n)\n f(a)*f(b) <= 0 || error(\"f(a)*f(b) must be <= 0\")\n quadfunref_brent[1] = f\n\n x = zeros()\n comm = zeros(Uint8, 8)\n\n reset_nag_error()\n ccall((:c05ayc, :libnagc_nag), Void,\n (Float64, Float64, Float64, Float64,\n Ptr{Void}, Ptr{Float64}, Ptr{Void}, Ptr{Void}),\n a, b, eps, eta, NAG.c_quadfun_brent, x, comm, NAG_ERROR)\n\n return x[]\nend\n\nend # module\n", "meta": {"hexsha": "022acbe3e43133d76cfcf34ed3e92491250073b0", "size": 8665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NAG.jl", "max_stars_repo_name": "StefanKarpinski/NAG.jl", "max_stars_repo_head_hexsha": "309dab05d8e6407ed7a452f8f7ed698dc3ef9afa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-06-15T12:09:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T00:54:52.000Z", "max_issues_repo_path": "src/NAG.jl", "max_issues_repo_name": "StefanKarpinski/NAG.jl", "max_issues_repo_head_hexsha": "309dab05d8e6407ed7a452f8f7ed698dc3ef9afa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NAG.jl", "max_forks_repo_name": "StefanKarpinski/NAG.jl", "max_forks_repo_head_hexsha": "309dab05d8e6407ed7a452f8f7ed698dc3ef9afa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-06-15T12:09:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-29T00:56:40.000Z", "avg_line_length": 31.6240875912, "max_line_length": 90, "alphanum_fraction": 0.6250432776, "num_tokens": 2686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2410557442266242}} {"text": "function tabulated_properties()\n # Various properties. Taken from CoolProp.\n data = Dict{String, MolecularProperty}()\n data[\"R507A\"] = MolecularProperty(0.0988592, 3704900, 343.765, 0.0002014492399, 0.286)\n data[\"RC318\"] = MolecularProperty(0.2000312, 2777500, 388.38, 0.0003226451742, 0.355345)\n data[\"SES36\"] = MolecularProperty(0.18485, 2849000, 450.7, 0.0003571428571, 0.352)\n data[\"SulfurDioxide\"] = MolecularProperty(0.0640638, 7886587.6, 430.64, 0.0001220256254, 0.2561299362)\n data[\"SulfurHexafluoride\"] = MolecularProperty(0.1460554192, 3754983, 318.7232, 0.0001967606348, 0.21)\n data[\"Toluene\"] = MolecularProperty(0.09213842, 4126000, 591.75, 0.000315556958, 0.2657)\n data[\"trans-2-Butene\"] = MolecularProperty(0.05610632, 4027300, 428.61, 0.0002373605507, 0.2100768344)\n data[\"Water\"] = MolecularProperty(0.018015268, 22064000, 647.096, 5.594803727e-05, 0.3442920843)\n data[\"Xenon\"] = MolecularProperty(0.131293, 5842000, 289.733, 0.000119047619, 0.00363)\n data[\"1-Butene\"] = MolecularProperty(0.05610632, 4005100, 419.29, 0.0002358490566, 0.1918606474)\n data[\"Acetone\"] = MolecularProperty(0.05807914, 4700000, 508.1, 0.0002127659574, 0.3071)\n data[\"Air\"] = MolecularProperty(0.02896546, 3786000, 132.5306, 8.452513778e-05, 0.0335)\n data[\"Ammonia\"] = MolecularProperty(0.01703026, 11333000, 405.4, 7.569004444e-05, 0.25601)\n data[\"Argon\"] = MolecularProperty(0.039948, 4863000, 150.687, 7.458551158e-05, -0.00219)\n data[\"Benzene\"] = MolecularProperty(0.0781118, 4894000, 562.02, 0.0002562788314, 0.2108369733)\n data[\"CarbonDioxide\"] = MolecularProperty(0.0440098, 7377300, 304.1282, 9.411847707e-05, 0.22394)\n data[\"CarbonMonoxide\"] = MolecularProperty(0.0280101, 3494000, 132.86, 9.216589862e-05, 0.0497)\n data[\"CarbonylSulfide\"] = MolecularProperty(0.0600751, 6370000, 378.77, 0.0001349527665, 0.0978)\n data[\"cis-2-Butene\"] = MolecularProperty(0.05610632, 4225500, 435.75, 0.0002356267672, 0.2023595859)\n data[\"CycloHexane\"] = MolecularProperty(0.08415948, 4082400, 553.6, 0.0003101736973, 0.20926)\n data[\"Cyclopentane\"] = MolecularProperty(0.0701329, 4571200, 511.72, 0.0002617801047, 0.2011125734)\n data[\"CycloPropane\"] = MolecularProperty(0.042081, 5579700, 398.3, 0.0001627891671, 0.1305495664)\n data[\"D4\"] = MolecularProperty(0.29661576, 1347215.356, 586.5, 0.0009587727709, 0.5981248268)\n data[\"D5\"] = MolecularProperty(0.3707697, 1160000, 619.15, 0.001216000031, 0.658)\n data[\"D6\"] = MolecularProperty(0.444924, 961000, 645.78, 0.001594162692, 0.736)\n data[\"Deuterium\"] = MolecularProperty(0.0040282, 1679600, 38.34, 5.803830528e-05, -0.1362902741)\n data[\"Dichloroethane\"] = MolecularProperty(0.098959, 5227585.103, 561.6, 0.0002309468822, 0.2685785009)\n data[\"DiethylEther\"] = MolecularProperty(0.0741216, 3649016.897, 466.7, 0.0002807636367, 0.2819293312)\n data[\"DimethylCarbonate\"] = MolecularProperty(0.0900779, 4908800, 557, 0.00025, 0.346)\n data[\"DimethylEther\"] = MolecularProperty(0.04606844, 5336800, 400.378, 0.0001683501684, 0.196)\n data[\"Ethane\"] = MolecularProperty(0.03006904, 4872200, 305.322, 0.0001458387816, 0.099)\n data[\"Ethanol\"] = MolecularProperty(0.04606844, 6268000, 514.71, 0.0001686340641, 0.644)\n data[\"EthylBenzene\"] = MolecularProperty(0.106165, 3622400, 617.12, 0.0003648282243, 0.304)\n data[\"Ethylene\"] = MolecularProperty(0.02805376, 5041800, 282.35, 0.0001309454817, 0.0866)\n data[\"EthyleneOxide\"] = MolecularProperty(0.04405256, 7304686.16, 468.92, 0.0001394700139, 0.210195489)\n data[\"Fluorine\"] = MolecularProperty(0.03799681, 5172400, 144.414, 6.409023906e-05, 0.0449)\n data[\"HeavyWater\"] = MolecularProperty(0.020027508, 21672051.48, 643.847, 5.625704971e-05, 0.3643005688)\n data[\"Helium\"] = MolecularProperty(0.004002602, 227600, 5.1953, 5.515719801e-05, -0.385)\n data[\"HFE143m\"] = MolecularProperty(0.10004, 3635000, 377.921, 0.0002151397849, 0.2888713657)\n data[\"Hydrogen\"] = MolecularProperty(0.00201588, 1296400, 33.145, 6.448284756e-05, -0.219)\n data[\"HydrogenChloride\"] = MolecularProperty(0.0364609, 8288160.904, 324.55, 8.474576271e-05, 0.1281892174)\n data[\"HydrogenSulfide\"] = MolecularProperty(0.03408088, 9000000, 373.1, 9.813542689e-05, 0.1005)\n data[\"IsoButane\"] = MolecularProperty(0.0581222, 3629000, 407.817, 0.0002577481153, 0.1835317832)\n data[\"IsoButene\"] = MolecularProperty(0.05610632, 4009800, 418.09, 0.0002398081535, 0.1925934522)\n data[\"Isohexane\"] = MolecularProperty(0.08617536, 3040000, 497.7, 0.0003683241252, 0.2797)\n data[\"Isopentane\"] = MolecularProperty(0.07214878, 3378000, 460.35, 0.0003057169061, 0.2274)\n data[\"Krypton\"] = MolecularProperty(0.083798, 5525000, 209.48, 9.216589862e-05, -0.00089)\n data[\"m-Xylene\"] = MolecularProperty(0.106165, 3534600, 616.89, 0.0003752345216, 0.326)\n data[\"MD2M\"] = MolecularProperty(0.310685, 1227000, 599.4, 0.001093300515, 0.668)\n data[\"MD3M\"] = MolecularProperty(0.384839, 945000, 628.36, 0.001458154971, 0.722)\n data[\"MD4M\"] = MolecularProperty(0.45899328, 877000, 653.2, 0.001650000016, 0.8246471473)\n data[\"MDM\"] = MolecularProperty(0.23653146, 1410044.756, 564.09, 0.000921288245, 0.5280658491)\n data[\"Methane\"] = MolecularProperty(0.0160428, 4599200, 190.564, 9.862781099e-05, 0.01142)\n data[\"Methanol\"] = MolecularProperty(0.03204216, 8215850, 512.5, 0.0001173705495, 0.5720322)\n data[\"MethylLinoleate\"] = MolecularProperty(0.29447206, 1341000, 799, 0.001237011381, 0.8054063871)\n data[\"MethylLinolenate\"] = MolecularProperty(0.29245618, 1369000, 772, 0.001180219521, 1.142605259)\n data[\"MethylOleate\"] = MolecularProperty(0.29648794, 1246000, 782, 0.001230239282, 0.90584936)\n data[\"MethylPalmitate\"] = MolecularProperty(0.27045066, 1350000, 755, 0.001114827202, 0.910316178)\n data[\"MethylStearate\"] = MolecularProperty(0.29850382, 1239000, 775, 0.001258970162, 1.01756)\n data[\"MM\"] = MolecularProperty(0.16237752, 1939000, 518.75, 0.0006290000472, 0.418)\n data[\"n-Butane\"] = MolecularProperty(0.0581222, 3796000, 425.125, 0.0002549219298, 0.2008100946)\n data[\"n-Decane\"] = MolecularProperty(0.14228168, 2103000, 617.7, 0.0006097560976, 0.4884)\n data[\"n-Dodecane\"] = MolecularProperty(0.17033484, 1817000, 658.1, 0.0007518796992, 0.5741822212)\n data[\"n-Heptane\"] = MolecularProperty(0.100202, 2736000, 540.13, 0.0004319051724, 0.349)\n data[\"n-Hexane\"] = MolecularProperty(0.08617536, 3034000, 507.82, 0.000369565829, 0.299)\n data[\"n-Nonane\"] = MolecularProperty(0.1282551, 2281000, 594.55, 0.0005524861878, 0.4433)\n data[\"n-Octane\"] = MolecularProperty(0.1142285, 2497000, 569.32, 0.0004862867146, 0.395)\n data[\"n-Pentane\"] = MolecularProperty(0.07214878, 3370000, 469.7, 0.0003109861207, 0.251)\n data[\"n-Propane\"] = MolecularProperty(0.04409562, 4251200, 369.89, 0.0002, 0.1521)\n data[\"n-Undecane\"] = MolecularProperty(0.15630826, 1990400, 638.8, 0.00066010223, 0.5390371014)\n data[\"Neon\"] = MolecularProperty(0.020179, 2680000, 44.4918, 4.187253999e-05, -0.03844929927)\n data[\"Neopentane\"] = MolecularProperty(0.07214878, 3196000, 433.74, 0.0003058103976, 0.1961)\n data[\"Nitrogen\"] = MolecularProperty(0.02801348, 3395800, 126.192, 8.941423556e-05, 0.0372)\n data[\"NitrousOxide\"] = MolecularProperty(0.0440128, 7245000, 309.52, 9.737098345e-05, 0.1613)\n data[\"Novec649\"] = MolecularProperty(0.3160438, 1869026.583, 441.81, 0.0005208333333, 0.4710235936)\n data[\"o-Xylene\"] = MolecularProperty(0.106165, 3737500, 630.259, 0.0003725088471, 0.312)\n data[\"OrthoDeuterium\"] = MolecularProperty(0.0040282, 1679600, 38.34, 5.803830528e-05, -0.1362902741)\n data[\"OrthoHydrogen\"] = MolecularProperty(0.00201594, 1310650, 33.22, 6.474779953e-05, -0.219)\n data[\"Oxygen\"] = MolecularProperty(0.0319988, 5043000, 154.581, 7.336757153e-05, 0.0222)\n data[\"p-Xylene\"] = MolecularProperty(0.106165, 3531500, 616.168, 0.0003712062719, 0.324)\n data[\"ParaDeuterium\"] = MolecularProperty(0.0040282, 1679600, 38.34, 5.803830528e-05, -0.1362902741)\n data[\"ParaHydrogen\"] = MolecularProperty(0.00201588, 1285800, 32.938, 6.435834728e-05, -0.219)\n data[\"Propylene\"] = MolecularProperty(0.04207974, 4555000, 364.211, 0.0001832508704, 0.146)\n data[\"Propyne\"] = MolecularProperty(0.04006, 5626000, 402.38, 0.0001635769703, 0.204)\n data[\"R11\"] = MolecularProperty(0.137368, 4394000, 471.06, 0.0002431292035, 0.1887506483)\n data[\"R113\"] = MolecularProperty(0.187375, 3392200, 487.21, 0.0003345982143, 0.252535)\n data[\"R114\"] = MolecularProperty(0.170921, 3257000, 418.83, 0.0002947070612, 0.2523)\n data[\"R115\"] = MolecularProperty(0.154466416, 3129036.968, 353.1, 0.0002512562814, 0.2484349931)\n data[\"R116\"] = MolecularProperty(0.13801182, 3048000, 293.03, 0.0002250225023, 0.2566)\n data[\"R12\"] = MolecularProperty(0.120913, 4136100, 385.12, 0.0002140053097, 0.1794783173)\n data[\"R123\"] = MolecularProperty(0.152931, 3672000, 456.831, 0.0002780545193, 0.281922497)\n data[\"R1233zd(E)\"] = MolecularProperty(0.1304944, 3623637.776, 439.6, 0.0002717391304, 0.3024522936)\n data[\"R1234yf\"] = MolecularProperty(0.1140415928, 3382200, 367.85, 0.0002398081535, 0.276)\n data[\"R1234ze(E)\"] = MolecularProperty(0.1140415928, 3636250, 382.52, 0.0002331002331, 0.313)\n data[\"R1234ze(Z)\"] = MolecularProperty(0.1140415928, 3533000, 423.27, 0.0002426416868, 0.3274)\n data[\"R124\"] = MolecularProperty(0.1364762, 3624295, 395.425, 0.0002437075, 0.2880950842)\n data[\"R125\"] = MolecularProperty(0.1200214, 3617700, 339.173, 0.0002092487968, 0.3052)\n data[\"R13\"] = MolecularProperty(0.104459, 3879000, 301.88, 0.0001792114695, 0.1745863278)\n data[\"R134a\"] = MolecularProperty(0.102032, 4059280, 374.21, 0.0001993201985, 0.32684)\n data[\"R13I1\"] = MolecularProperty(0.1959104, 3952566.072, 396.44, 0.000225703065, 0.1761811178)\n data[\"R14\"] = MolecularProperty(0.0880046, 3750000, 227.51, 0.0001406584622, 0.1785)\n data[\"R141b\"] = MolecularProperty(0.11694962, 4212000, 477.5, 0.0002550369804, 0.2195)\n data[\"R142b\"] = MolecularProperty(0.10049503, 4055000, 410.26, 0.0002253267237, 0.2321)\n data[\"R143a\"] = MolecularProperty(0.084041, 3761000, 345.857, 0.0001949906892, 0.2614896462)\n data[\"R152A\"] = MolecularProperty(0.066051, 4520000, 386.411, 0.000179486413, 0.2752171145)\n data[\"R161\"] = MolecularProperty(0.0480595, 5010000, 375.25, 0.0001592356688, 0.2162428411)\n data[\"R21\"] = MolecularProperty(0.1029227, 5181200, 451.48, 0.0001956654009, 0.2061)\n data[\"R218\"] = MolecularProperty(0.18801933, 2640000, 345.02, 0.0002994011976, 0.3172)\n data[\"R22\"] = MolecularProperty(0.086468, 4990000, 369.295, 0.0001650649861, 0.22082)\n data[\"R227EA\"] = MolecularProperty(0.17002886, 2925242.234, 374.9, 0.0002861230329, 0.357641242)\n data[\"R23\"] = MolecularProperty(0.07001385, 4832000, 299.293, 0.0001329787234, 0.2629648925)\n data[\"R236EA\"] = MolecularProperty(0.1520384, 3420000, 412.44, 0.0002691065662, 0.3687823804)\n data[\"R236FA\"] = MolecularProperty(0.1520384, 3200000, 398.07, 0.0002757859901, 0.3769117976)\n data[\"R245ca\"] = MolecularProperty(0.13404794, 3940740.489, 447.57, 0.0002551020408, 0.3545654191)\n data[\"R245fa\"] = MolecularProperty(0.13404794, 3651000, 427.01, 0.0002580645161, 0.3776)\n data[\"R32\"] = MolecularProperty(0.052024, 5782000, 351.255, 0.0001226981129, 0.2769)\n data[\"R365MFC\"] = MolecularProperty(0.14807452, 3266207.068, 460, 0.0003125, 0.3774450972)\n data[\"R40\"] = MolecularProperty(0.05048752, 6671686.977, 416.3, 0.0001390002242, 0.1500684964)\n data[\"R404A\"] = MolecularProperty(0.0976038, 3734800, 345.27, 0.0002024291498, 0.293)\n data[\"R407C\"] = MolecularProperty(0.0862036, 4631700, 359.345, 0.0001901140668, 0.363)\n data[\"R41\"] = MolecularProperty(0.03403292, 5897000, 317.28, 0.0001075268817, 0.2004)\n data[\"R410A\"] = MolecularProperty(0.0725854, 4901200, 344.494, 0.0001581277672, 0.296)\n return data\nend\n\n\"\"\"\n cubic_benchmark(name)\n\nGet a benchmark equation-of-state instance together with some data for testing.\n\"\"\"\nfunction cubic_benchmark(name)\n psi = 6.894757293168360e+03\n Rankine = 0.555555555555556\n bar = 1e5\n data = Dict()\n eos_type = PengRobinson()\n\n bic = nothing\n if name == \"spe5\"\n T_c = [343, 665.7, 913.4, 1111.8, 1270.0, 1380.0]*Rankine;\n p_c = [667.8, 616.3, 436.9, 304.0, 200.0, 162.0]*psi;\n mw = [16.040, 44.100, 86.180, 142.290, 206.000, 282.000]/1000;\n acc = [0.0130, 0.1524, 0.3007, 0.4885, 0.6500, 0.8500];\n Z_c = [0.290, 0.277, 0.264, 0.257, 0.245, 0.235];\n # Convert critical volumes to critical densities\n V_c = Z_c.*8.314.*T_c./p_c;\n names = [\"C1\", \"C3\", \"C6\", \"C10\", \"C15\", \"C20\"];\n ncomp = length(names);\n bic = zeros(ncomp, ncomp);\n bic[1, 5] = 0.05;\n bic[1, 6] = 0.05;\n bic[2, 5] = 0.005;\n bic[2, 6] = 0.005;\n bic = Symmetric(bic)\n props = MolecularProperty.(mw, p_c, T_c, V_c, acc)\n\n z0 = [0.77, 0.20, 0.03, 0, 0, 0]\n z = [0.5, 0.03, 0.07, 0.20, 0.15, 0.05]\n p = 4000*psi\n T = 344.26\n p0 = p\n T0 = T\n\n initial_cond = (z = z0, p = p0, T = T0)\n displ_cond = (z = z, p = p, T = T)\n data[\"initial_condition\"] = initial_cond\n data[\"injection_condition\"] = displ_cond\n elseif name == \"simple\"\n names = [\"Methane\", \"CarbonDioxide\", \"n-Decane\"]\n props = MolecularProperty.(names)\n\n p = 75*bar\n T = 273.15 + 150\n z0 = [0.3, 0.1, 0.6]\n z = [0.1, 0.9, 0.0]\n initial_cond = (z = z0, p = p, T = T)\n displ_cond = (z = z, p = p, T = T)\n data[\"initial_condition\"] = initial_cond\n data[\"injection_condition\"] = displ_cond\n else\n error(\"Unknown benchmark $name\")\n end\n mixture = MultiComponentMixture(props, names = names, A_ij = bic)\n eos = GenericCubicEOS(mixture, eos_type)\n\n return (eos, data)\nend", "meta": {"hexsha": "6cdc3b52653c76e5ba0adad9ed5b572d456d8ab2", "size": 13923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tables.jl", "max_stars_repo_name": "longemen3000/MultiComponentFlash.jl", "max_stars_repo_head_hexsha": "98c82ac9e5e7e45e616b981551ee9ae6f425cd2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-11-01T14:03:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:44:34.000Z", "max_issues_repo_path": "src/tables.jl", "max_issues_repo_name": "longemen3000/MultiComponentFlash.jl", "max_issues_repo_head_hexsha": "98c82ac9e5e7e45e616b981551ee9ae6f425cd2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-12T00:45:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T09:17:32.000Z", "max_forks_repo_path": "src/tables.jl", "max_forks_repo_name": "longemen3000/MultiComponentFlash.jl", "max_forks_repo_head_hexsha": "98c82ac9e5e7e45e616b981551ee9ae6f425cd2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-05T01:04:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T01:04:52.000Z", "avg_line_length": 73.2789473684, "max_line_length": 111, "alphanum_fraction": 0.6966171084, "num_tokens": 6022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.24078940320464415}} {"text": "# include(\"Move.jl\")\n# include(\"Wavefunction.jl\")\n# include(\"SwapWavefunction.jl\")\n\nabstract Walk\n\nis_nontrivial_transition(walk::Walk) = walk.transition_is_nontrivial\n\nfunction get_probability_ratio(walk::Walk)\n if !walk.transition_is_nontrivial\n warn(\"Asking for the probability ratio ( = 1) of a trivial transition.\")\n return 1.\n else\n return walk.probability_ratio\n end\nend\n\n# Lots of code copying below since Julia does't really have abstract base classes. There has to be a better way..\n# I could have one class with finish_move! and cancel_move! functions passed to the constructor and held as members,\n# but that seems less safe and less explicit.\n\n# standard walk for ordinary wavefunctions / measurements\ntype StandardWalk <: Walk\n wf::Wavefunction\n transition_function::Function\n probability_ratio::Float64\n transition_is_nontrivial::Bool\n # transition_in_progress::Bool\n StandardWalk(wf::Wavefunction, transition_function::Function) = new(wf, transition_function)\nend\n\nfunction propose_and_assess_random_transition!(walk::StandardWalk)\n move = walk.transition_function(walk.wf)\n\n if !is_nontrivial(move)\n walk.transition_is_nontrivial = false\n else\n probrat = assess_move!(walk.wf, move)\n walk.transition_is_nontrivial = true\n walk.probability_ratio = probrat\n end\nend\n\naccept_transition!(walk::StandardWalk) = finish_move!(walk.wf)\nreject_transition!(walk::StandardWalk) = cancel_move!(walk.wf)\n\ncheck_for_numerical_error!(walk::StandardWalk) = check_for_numerical_error!(walk.wf)\n\n\n# walk for Renyi mod measurement\ntype RenyiModWalk <: Walk\n wf::Union{SwapWavefunction, SwapWavefunctionNS}\n transition_function::Function\n probability_ratio::Float64\n transition_is_nontrivial::Bool\n # transition_in_progress::Bool\n RenyiModWalk(wf::Union{SwapWavefunction, SwapWavefunctionNS}, transition_function::Function) = new(wf, transition_function)\nend\n\nfunction propose_and_assess_random_transition!(walk::RenyiModWalk)\n move = walk.transition_function(walk.wf)\n # move here is either a 2-tuple of moves for the different copies (SwapWavefunction) or a Tuple{ParticlesMove{LatticeParticleMove},Int64} (SwapWavefunctionNS),\n # where the Int here is the copy_to_move\n @assert length(move) == 2\n\n if isa(move[2], Int) # for SwapWavefunctionNS\n trivial_condition = !is_nontrivial(move[1])\n else # for SwapWavefunction\n trivial_condition = all(map(!, map(is_nontrivial, move)))\n end\n\n if trivial_condition\n walk.transition_is_nontrivial = false\n else\n probrat = assess_move_for_mod!(walk.wf, move...)\n walk.transition_is_nontrivial = true\n walk.probability_ratio = probrat\n end\nend\n\naccept_transition!(walk::RenyiModWalk) = finish_move_for_mod!(walk.wf)\nreject_transition!(walk::RenyiModWalk) = cancel_move_for_mod!(walk.wf)\n\ncheck_for_numerical_error!(walk::RenyiModWalk) = check_for_numerical_error_for_mod!(walk.wf)\n\n\n# walk for Renyi sign measurement\ntype RenyiSignWalk <: Walk\n wf::Union{SwapWavefunction, SwapWavefunctionNS}\n transition_function::Function\n probability_ratio::Float64\n transition_is_nontrivial::Bool\n # transition_in_progress::Bool\n RenyiSignWalk(wf::Union{SwapWavefunction, SwapWavefunctionNS}, transition_function::Function) = new(wf, transition_function)\nend\n\nfunction propose_and_assess_random_transition!(walk::RenyiSignWalk)\n move = walk.transition_function(walk.wf)\n @assert length(move) == 2 # a 2-tuple of moves for the different copies\n\n if isa(move[2], Int) # for SwapWavefunctionNS\n trivial_condition = !is_nontrivial(move[1])\n else # for SwapWavefunction\n trivial_condition = all(map(!, map(is_nontrivial, move)))\n end\n\n if trivial_condition\n walk.transition_is_nontrivial = false\n else\n probrat = assess_move_for_sign!(walk.wf, move...)\n walk.transition_is_nontrivial = true\n walk.probability_ratio = probrat\n end\nend\n\naccept_transition!(walk::RenyiSignWalk) = finish_move_for_sign!(walk.wf)\nreject_transition!(walk::RenyiSignWalk) = cancel_move_for_sign!(walk.wf)\n\ncheck_for_numerical_error!(walk::RenyiSignWalk) = check_for_numerical_error_for_sign!(walk.wf)\n\n\n# type RenyiWalk <: Walk\n# wf::SwapWavefunction\n# transition_function::Function\n# probability_ratio::Float64\n# transition_is_nontrivial::Bool\n# # transition_in_progress::Bool\n# RenyiWalk(wf::SwapWavefunction, transition_function::Function) = new(wf, transition_function)\n# end\n\n# type RenyiModWalk\n# walk::RenyiWalk\n# RenyiModWalk(wf::SwapWavefunction, transition_function::Function) = new(RenyiWalk(wf, transition_function))\n# end\n\n# How to then make, e.g., RenyiModWalk.wf invoke RenyiModWalk.walk.wf?\n", "meta": {"hexsha": "31d087e2b0c07bc8ffbd78baf77c25f1c83cdcd3", "size": 4797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Walk.jl", "max_stars_repo_name": "mishmash/VMC.jl", "max_stars_repo_head_hexsha": "f7619521e02993174787c87397461ca952755d8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-10-21T05:44:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T14:27:24.000Z", "max_issues_repo_path": "src/Walk.jl", "max_issues_repo_name": "mishmash/VMC.jl", "max_issues_repo_head_hexsha": "f7619521e02993174787c87397461ca952755d8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Walk.jl", "max_forks_repo_name": "mishmash/VMC.jl", "max_forks_repo_head_hexsha": "f7619521e02993174787c87397461ca952755d8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-21T03:26:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T14:27:31.000Z", "avg_line_length": 35.0145985401, "max_line_length": 163, "alphanum_fraction": 0.7504690432, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2407769355306709}} {"text": "\"\"\"\nSubtype of `LDScoreRegression`.\n\"\"\"\n\n\nmutable struct Hsq <: LDScoreRegression\n y; x; w; N; M;\n n_blocks; intercept; slow; step1_ii; old_weights;\n __null_intercept__\n\n constrain_intercept; n_annot; intercept_se; twostep_filtered;\n\n function Hsq(\n y, x, w, N, M; n_blocks = 200, slow = false, old_weights = false,\n intercept = nothing, step1_ii = nothing,\n )\n hsq = new(\n y, x, w, N, M, n_blocks, intercept, slow, step1_ii, old_weights, 1,\n )\n return ld_score_regression(\n hsq,\n y, x, w, N, M, n_blocks, intercept, slow, step1_ii, old_weights,\n )\n end\nend\n\n\nfunction hsq_weights(ld, w_ld, N, M, hsq; intercept=nothing)\n if intercept == nothing intercept = 1.0 end\n M = M[1][1]\n hsq = max(maximum(hsq), 0.0)\n hsq = min(hsq, 1.0)\n ld = fmax(ld, 1.0)\n w_ld = fmax(w_ld, 1.0)\n c = hsq .* N ./ M\n\n het_w = 1.0 ./ (2 .* (c .* ld .+ intercept).^2)\n oc_w = 1.0 ./ w_ld\n w = het_w .* oc_w\n return w\nend\n\n\nfunction update_weights(reg::Hsq, ld, w_ld, N, M, hsq, intercept)\n if intercept == nothing intercept = reg.__null_intercept__ end\n\n return hsq_weights(ld, w_ld, N, M, hsq; intercept=intercept)\nend\n\nfunction overlap_output(\n hsq::Hsq,\n category_names, overlap_matrix, M_annot, M_tot, print_coefficients,\n)\n overlap_matrix_prop = zeros([hsq.n_annot, hsq.n_annot])\n for i in range(hsq.n_annot)\n overlap_matrix_prop[i, :] = overlap_matrix[i, :] / M_annot\n end\n\n # TODO missing code here\n\n #=\n df = DataFrames.DataFrame({\n \"Category\": category_names,\n \"Prop._SNPs\": one_d_convert(prop_M_overlap),\n \"Prop._h2\": one_d_convert(prop_hsq_overlap),\n \"Prop._h2_std_error\": one_d_convert(prop_hsq_overlap_se),\n \"Enrichment\": one_d_convert(enrichment),\n \"Enrichment_std_error\": one_d_convert(enrichment_se),\n \"Enrichment_p\":diff_p,\n \"Coefficient\": one_d_convert(hsq.coef),\n \"Coefficient_std_error\": hsq.coef_se,\n \"Coefficient_z-score\": one_d_convert(hsq.coef) / one_d_convert(hsq.coef_se)\n })\n if print_coefficients\n return df[\n !,\n [\n \"Category\", \"Prop._SNPs\", \"Prop._h2\", \"Prop._h2_std_error\",\n \"Enrichment\",\"Enrichment_std_error\", \"Enrichment_p\",\n \"Coefficient\", \"Coefficient_std_error\",\"Coefficient_z-score\",\n ],\n ]\n else\n return df[\n !,\n [\n \"Category\", \"Prop._SNPs\", \"Prop._h2\", \"Prop._h2_std_error\",\n \"Enrichment\",\"Enrichment_std_error\", \"Enrichment_p\",\n ],\n ]\n end\n =#\nend\n", "meta": {"hexsha": "d83fe190017d7b421c07f19c497797a9b3aad6c8", "size": 2684, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LDScore/Hsq.jl", "max_stars_repo_name": "harvey2phase/LDScoreJulia", "max_stars_repo_head_hexsha": "d71cb2ed04d18329d51e3ab9961e1a26d9be200d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-13T12:00:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T12:00:22.000Z", "max_issues_repo_path": "src/LDScore/Hsq.jl", "max_issues_repo_name": "harvey2phase/LDScoreJulia", "max_issues_repo_head_hexsha": "d71cb2ed04d18329d51e3ab9961e1a26d9be200d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-08-09T14:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-09T14:25:38.000Z", "max_forks_repo_path": "src/LDScore/Hsq.jl", "max_forks_repo_name": "harvey2phase/LDScore.jl", "max_forks_repo_head_hexsha": "d71cb2ed04d18329d51e3ab9961e1a26d9be200d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-09T12:38:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T12:38:12.000Z", "avg_line_length": 28.5531914894, "max_line_length": 83, "alphanum_fraction": 0.5927719821, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2406760430162175}} {"text": "#### thermodynamics\n\nexport new_thermo_state_anelastic, recover_thermo_state_anelastic\n\n\"\"\"\n new_thermo_state_anelastic(atmos::AtmosModel, state::Vars, aux::Vars)\n\nCreate a new thermodynamic state, based on the `state`, and _not_\nthe `aux` state.\n\n!!! note\n This method calls the iterative saturation adjustment\n procedure for EquilMoist models.\n\"\"\"\nnew_thermo_state_anelastic(atmos::AtmosModel, state::Vars, aux::Vars) =\n new_thermo_state_anelastic(\n atmos,\n energy_model(atmos),\n moisture_model(atmos),\n state,\n aux,\n )\n\n\"\"\"\n recover_thermo_state_anelastic(atmos::AtmosModel, state::Vars, aux::Vars)\n\nAn atmospheric thermodynamic state.\n\n!!! warn\n For now, we are directly calling new_thermo_state_anelastic to avoid\n inconsistent aux states in kernels where the aux states are\n out of sync with the boundary state.\n\n# TODO: Define/call `recover_thermo_state_anelastic` when it's safely implemented\n (see https://github.com/CliMA/ClimateMachine.jl/issues/1648)\n\"\"\"\nrecover_thermo_state_anelastic(atmos::AtmosModel, state::Vars, aux::Vars) =\n new_thermo_state_anelastic(\n atmos,\n energy_model(atmos),\n moisture_model(atmos),\n state,\n aux,\n )\n\nfunction new_thermo_state_anelastic(\n atmos::AtmosModel,\n energy::TotalEnergyModel,\n moist::DryModel,\n state::Vars,\n aux::Vars,\n)\n param_set = parameter_set(atmos)\n e_int = internal_energy(atmos, state, aux)\n p = aux.ref_state.p\n return PhaseDry_pe(param_set, p, e_int)\nend\n\nfunction new_thermo_state_anelastic(\n atmos::AtmosModel,\n energy::TotalEnergyModel,\n moist::EquilMoist,\n state::Vars,\n aux::Vars,\n)\n param_set = parameter_set(atmos)\n e_int = internal_energy(atmos, state, aux)\n p = aux.ref_state.p\n ρ = density(atmos, state, aux)\n return PhaseEquil_peq(\n param_set,\n p,\n e_int,\n state.moisture.ρq_tot / ρ,\n moist.maxiter,\n moist.tolerance,\n )\nend\n\nfunction new_thermo_state_anelastic(\n atmos::AtmosModel,\n energy::TotalEnergyModel,\n moist::NonEquilMoist,\n state::Vars,\n aux::Vars,\n)\n param_set = parameter_set(atmos)\n e_int = internal_energy(atmos, state, aux)\n p = aux.ref_state.p\n ρ = density(atmos, state, aux)\n q = PhasePartition(\n state.moisture.ρq_tot / ρ,\n state.moisture.ρq_liq / ρ,\n state.moisture.ρq_ice / ρ,\n )\n\n return PhaseNonEquil_peq(param_set, p, e_int, q)\nend\n", "meta": {"hexsha": "9b85b51b1a2c8f160c57f7bcdca8d7e56f7c52a0", "size": 2492, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Atmos/Model/thermo_states_anelastic.jl", "max_stars_repo_name": "ErikQQY/ClimateMachine.jl", "max_stars_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 256, "max_stars_repo_stars_event_min_datetime": "2020-05-06T08:03:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:01:20.000Z", "max_issues_repo_path": "src/Atmos/Model/thermo_states_anelastic.jl", "max_issues_repo_name": "ErikQQY/ClimateMachine.jl", "max_issues_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1174, "max_issues_repo_issues_event_min_datetime": "2020-05-06T16:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T17:51:13.000Z", "max_forks_repo_path": "src/Atmos/Model/thermo_states_anelastic.jl", "max_forks_repo_name": "ErikQQY/ClimateMachine.jl", "max_forks_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2020-05-08T02:28:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T22:44:56.000Z", "avg_line_length": 25.1717171717, "max_line_length": 81, "alphanum_fraction": 0.6817817014, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2406760430162175}} {"text": "################################################################################\n#\n# NfOrd/Ideal/Prime.jl : Prime ideals in orders of absolute number fields\n#\n# This file is part of Hecke.\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n#\n# Copyright (C) 2015, 2016, 2017 Tommy Hofmann\n# Copyright (C) 2015, 2016, 2017 Claus Fieker\n#\n################################################################################\n\nexport PrimeIdealsSet\n\ndoc\"\"\"\n***\n isramified(O::NfOrd, p::Int) -> Bool\n\n> Returns whether the integer $p$ is ramified in $\\mathcal O$.\n> It is assumed that $p$ is prime.\n\"\"\"\nfunction isramified(O::NfOrd, p::Union{Int, fmpz})\n @assert ismaximal_known(O) && ismaximal(O)\n\n return mod(discriminant(O), p) == 0\nend\n\ndoc\"\"\"\n***\n degree(P::NfOrdIdl) -> Int\n> The inertia degree of the prime-ideal $P$.\n\"\"\"\nfunction degree(A::NfOrdIdl)\n @assert isprime(A)\n return A.splitting_type[2]\nend\n\ndoc\"\"\"\n***\n ramification_index(P::NfOrdIdl) -> Int\n> The ramification index of the prime-ideal $P$.\n\"\"\"\nfunction ramification_index(A::NfOrdIdl)\n @assert isprime(A)\n return A.splitting_type[1]\nend\n\ndoc\"\"\"\n***\n splitting_type(P::NfOrdIdl) -> Int, Int\n> The ramification index and inertia degree of the prime ideal $P$.\n> First value is the ramificatio index, the second the degree of $P$.\n\"\"\"\nfunction splitting_type(A::NfOrdIdl)\n @assert isprime(A)\n return A.splitting_type\nend\n\n################################################################################\n#\n# Prime decomposition\n#\n################################################################################\ndoc\"\"\"\n intersect_nonindex(f::Map, P::NfOrdIdl) -> NfOrdIdl\n> Given a prime ideal $P$ in $K$ and the inclusion map $f:k \\to K$ \n> of number fields, find the unique prime $p$ in $k$ below.\n\"\"\"\nfunction intersect_nonindex(f::Map, P::NfOrdIdl)\n @assert P.is_prime == 1\n #let g be minpoly of k, G minpoly of K and h in Qt the primitive\n #element of k in K (image of gen(k))\n #then\n # g(h) = 0 mod G\n k = domain(f)\n K = codomain(f)\n G = K.pol\n Qx = parent(G)\n g = k.pol(gen(Qx))\n h = Qx(f(gen(k)))\n\n Fp, xp = PolynomialRing(ResidueRing(FlintZZ, Int(minimum(P)), cached=false), cached=false)\n gp = factor(Fp(g))\n hp = Fp(h)\n Gp = gcd(Fp(K(P.gen_two)), Fp(G))\n for (f, e) = gp.fac\n if f(hp) % Gp == 0\n Zk = maximal_order(k)\n p = ideal_from_poly(Zk, Int(minimum(P)), f, 1)\n return p\n end\n end\nend\n\n\ndoc\"\"\"\n prime_decomposition_nonindex(f::Map, p::NfOrdIdl) -> Array{Tuple{NfOrdIdl, Int}, 1}\n> Given a map $f: k\\to K$ of number fields defined over $\\mathbb Q$ and\n> a prime ideal in the maximal order of $k$, find all prime ideals in\n> the maximal order of $K$ above.\n\"\"\"\nfunction prime_decomposition_nonindex(f::Map, p::NfOrdIdl)\n @assert p.is_prime == 1\n k = domain(f)\n K = codomain(f)\n ZK = maximal_order(K)\n G = K.pol\n Qx = parent(G)\n\n Fp, xp = PolynomialRing(ResidueRing(FlintZZ, Int(minimum(p)), cached=false), cached=false)\n Gp = factor(gcd(Fp(f(K(p.gen_two))), Fp(G)))\n res = []\n Zk = maximal_order(k)\n for (f, e) = Gp.fac\n P = ideal_from_poly(ZK, Int(minimum(p)), f, 1)\n push!(res, (P, e))\n end\n return res\nend\n\ndoc\"\"\"\n lift(K::AnticNumberField, f::nmod_poly) -> nf_elem\n> Given a polynomial $f$ over a finite field, lift it to an element of the\n> number field $K$. The lift if given by the eleemnt represented by the\n> canonical lift of $f$ to a polynomial over the integers.\n\"\"\"\nfunction lift(K::AnticNumberField, f::nmod_poly)\n if degree(f)>=degree(K)\n f = mod(f, parent(f)(K.pol))\n end\n r = K()\n for i=0:f.length-1\n u = ccall((:nmod_poly_get_coeff_ui, :libflint), UInt, (Ptr{nmod_poly}, Int), &f, i)\n _num_setcoeff!(r, i, u)\n end\n return r\nend\n\n##TODO: make fmpz-safe!!!!\n#return in 2-element normal presentation given the data\nfunction ideal_from_poly(O::NfOrd, p::Int, fi::nmod_poly, ei::Int)\n b = lift(nf(O), fi)\n idl = ideal(O, fmpz(p), O(b, false))\n idl.is_prime = 1\n idl.splitting_type = ei, degree(fi)\n idl.norm = FlintZZ(p)^degree(fi)\n idl.minimum = FlintZZ(p)\n\n # We have to do something to get 2-normal presentation:\n # if ramified or valuation val(b,P) == 1, (p,b)\n # is a P(p)-normal presentation\n # otherwise we need to take p+b\n # I SHOULD CHECK THAT THIS WORKS\n\n if !((mod(norm(b),(idl.norm)^2) != 0) || (ei > 1))\n idl.gen_two = idl.gen_two + O(p)\n end\n\n idl.gens_normal = p\n idl.gens_weakly_normal = true\n\n # Find an \"anti-uniformizer\" in case P is unramified\n # We don't call it anti-unfiformizer anymore\n\n #if ideal.splitting_type[1] == 1\n # t = parent(f)(lift(Zx, divexact(fmodp, fi)))\n # ideal.anti_uniformizer = O(K(t), false)\n #end\n\n if idl.splitting_type[2] == degree(O)\n # Prime number is inert, in particular principal\n idl.is_principal = 1\n idl.princ_gen = O(p)\n end\n return idl\nend\n\ndoc\"\"\"\n***\n prime_decomposition(O::NfOrd,\n p::Integer,\n degree_limit::Int = 0,\n lower_limit::Int = 0) -> Array{Tuple{NfOrdIdl, Int}, 1}\n\n> Returns an array of tuples $(\\mathfrak p_i,e_i)$ such that $p \\mathcal O$ is the product of\n> the $\\mathfrak p_i^{e_i}$ and $\\mathfrak p_i \\neq \\mathfrak p_j$ for $i \\neq j$.\n>\n> If `degree_limit` is a nonzero integer $k > 0$, then only those prime ideals\n> $\\mathfrak p$ with $\\deg(\\mathfrak p) \\leq k$ will be returned.\n> Similarly if `\\lower_limit` is a nonzero integer $l > 0$, then only those prime ideals\n> $\\mathfrak p$ with $l \\leq \\deg(\\mathfrak p)$ will be returned.\n> Note that in this case it may happen that $p\\mathcal O$ is not the product of the\n> $\\mathfrak p_i^{e_i}$.\n\"\"\"\nfunction prime_decomposition(O::NfAbsOrd{S, T}, p::Union{Integer, fmpz}, degree_limit::Int = 0, lower_limit::Int = 0, cached::Bool = true) where {S, T}\n if typeof(p) == fmpz && nbits(p) < 64\n return prime_decomposition(O, Int(p), degree_limit, lower_limit)\n end\n\n if mod(index(O),fmpz(p)) == 0 || !issimple(nf(O))\n if cached\n if haskey(O.index_div, fmpz(p))\n lp = O.index_div[fmpz(p)]\n z = Tuple{NfAbsOrdIdl{S, T}, Int}[]\n for (Q, e) in lp\n if degree(Q) <= degree_limit\n push!(z, (Q, e))\n end\n end\n return z\n end\n end\n return prime_dec_index(O, p, degree_limit, lower_limit)\n end\n return prime_dec_nonindex(O, p, degree_limit, lower_limit)\nend\n\nfunction _fac_and_lift(f::fmpz_poly, p, degree_limit, lower_limit)\n Zx = parent(f)\n Zmodpx = PolynomialRing(ResidueRing(FlintZZ, p, cached = false), \"y\", cached = false)[1]\n fmodp = Zmodpx(f)\n fac = factor(fmodp)\n lifted_fac = Array{Tuple{fmpz_poly, Int}, 1}()\n for (k, v) in fac\n if degree(k) <= degree_limit && degree(k) >= lower_limit\n push!(lifted_fac, (lift(Zx, k), v))\n end\n end\n return lifted_fac\nend\n\nfunction prime_dec_nonindex(O::NfOrd, p::Union{Integer, fmpz}, degree_limit::Int = 0, lower_limit::Int = 0)\n K = nf(O)\n f = K.pol\n R = parent(f)\n Zx, x = PolynomialRing(FlintIntegerRing(),\"x\")\n Zf = Zx(f)\n\n if degree_limit == 0\n degree_limit = degree(K)\n end\n\n fac = _fac_and_lift(Zf, p, degree_limit, lower_limit)\n\n result = Array{Tuple{ideal_type(O),Int}}(length(fac))\n\n for k in 1:length(fac)\n fi = fac[k][1]\n ei = fac[k][2]\n #ideal = ideal_from_poly(O, p, fi, ei)\n t = parent(f)(fi)\n b = K(t)\n ideal = NfAbsOrdIdl(O)\n ideal.gen_one = p\n ideal.gen_two = O(b, false)\n ideal.is_prime = 1\n ideal.splitting_type = ei, degree(fi)\n ideal.norm = FlintZZ(p)^degree(fi)\n ideal.minimum = FlintZZ(p)\n\n # We have to do something to get 2-normal presentation:\n # if ramified or valuation val(b,P) == 1, (p,b)\n # is a P(p)-normal presentation\n # otherwise we need to take p+b\n # I SHOULD CHECK THAT THIS WORKS\n\n if !((mod(norm(b),(ideal.norm)^2) != 0) || (ei > 1))\n ideal.gen_two = ideal.gen_two + O(p)\n end\n\n ideal.gens_normal = p\n ideal.gens_weakly_normal = true\n\n # Find an \"anti-uniformizer\" in case P is unramified\n # We don't call it anti-unfiformizer anymore\n\n #if ideal.splitting_type[1] == 1\n # t = parent(f)(lift(Zx, divexact(fmodp, fi)))\n # ideal.anti_uniformizer = O(K(t), false)\n #end\n\n if length(fac) == 1 && ideal.splitting_type[2] == degree(f)\n # Prime number is inert, in particular principal\n ideal.is_principal = 1\n ideal.princ_gen = O(p)\n end\n result[k] = (ideal, ei)\n k += 1\n end\n return result\nend\n\nfunction prime_dec_index(O::NfOrd, p::Union{Integer, fmpz}, degree_limit::Int = 0, lower_limit::Int = 0)\n if degree_limit == 0\n degree_limit = degree(O)\n end\n\n Ip = pradical(O, p)\n A, OtoA = AlgAss(O, Ip, p)\n AtoO = inv(OtoA)\n AA = split(A)\n\n basisO = basis(O)\n\n ideals = Vector{NfOrdIdl}()\n m = zero_matrix(FlintZZ, 1, degree(O))\n for (B, BtoA) in AA\n f = dim(B)\n idem = BtoA(B[1]) # Assumes that B == idem*A\n M = representation_matrix(idem)\n ker = left_kernel(M)\n N = basis_mat(Ip)\n for i = 1:length(ker)\n b = elem_in_basis(AtoO(A(ker[i])))\n for j = 1:degree(O)\n m[1, j] = b[j]\n end\n N = vcat(N, m)\n end\n N = sub(_hnf_modular_eldiv(N, fmpz(p), :lowerleft), rows(N) - degree(O) + 1:rows(N), 1:degree(O))\n P = ideal(O, N)\n P.norm = fmpz(p)^f\n P.splitting_type = (0, f)\n #\n fromOtosimplealgebra = Hecke._compose(inv(BtoA), OtoA)\n compute_residue_field_data!(P, fromOtosimplealgebra)\n #primB, minprimB, getcoordpowerbasis = _as_field(B)\n #@assert degree(minprimB) == f\n #P.prim_elem = AtoO(BtoA(primB))\n #P.min_poly_prim_elem = fmpz_poly(fmpz[FlintZZ(coeff(minprimB, i)) for i in 0:degree(minprimB)])\n #P.min_poly_prim_elem.parent = FmpzPolyRing(:$, false)\n #P.basis_in_prim = Vector{fmpz_mat}(degree(O))\n #for i in 1:degree(O)\n # P.basis_in_prim[i] = zero_matrix(FlintZZ, 1, f)\n # t = getcoordpowerbasis(BtoA\\(OtoA(basisO[i])))\n # for j in 1:f\n # P.basis_in_prim[i][1, j] = FlintZZ(t[1, j])\n # end\n #end\n push!(ideals, P)\n end\n\n result = Vector{Tuple{NfOrdIdl, Int}}()\n\n for j in 1:length(ideals)\n P = ideals[j]\n f = P.splitting_type[2]\n\n if f > degree_limit || f < lower_limit\n continue\n end\n\n # The following does not work if there is only one prime ideal\n if length(ideals) > 1 && (1-1/BigInt(p))^degree(O) < 0.1\n # This is roughly Algorithm 6.4 of Belabas' \"Topics in comptutational algebraic\n # number theory\".\n\n # Compute Vp = P_1 * ... * P_j-1 * P_j+1 * ... P_g\n\n B, BtoA = AA[j]\n J = ideal(O, AtoO(BtoA(B[1])))\n N = sub(_hnf_modular_eldiv(vcat(basis_mat(Ip), basis_mat(J)), fmpz(p), :lowerleft), degree(O) + 1:2*degree(O), 1:degree(O))\n Vp = ideal(O, N)\n\n u, v = idempotents(P, Vp)\n\n x = zero(parent(u))\n\n if !iszero(mod(norm(u), norm(P)*p))\n x = u\n elseif !iszero(mod(norm(u + p), norm(P)*p))\n x = u + p\n elseif !iszero(mod(norm(u - p), norm(P)*p))\n x = u - p\n else\n for i in 1:degree(O)\n if !iszero(mod(norm(v*basis(P)[i] + u), norm(P)*p))\n x = v*basis(P)[i] + u\n end\n end\n end\n\n @hassert :NfOrd 1 !iszero(x)\n @hassert :NfOrd 2 O*O(p) + O*x == P\n\n P.gen_one = p\n P.gen_two = x\n P.gens_normal = p\n P.gens_weakly_normal = 1\n else\n @vprint :NfOrd 1 \"Chances for finding second generator: ~$((1-1/p))\\n\"\n _assure_weakly_normal_presentation(P)\n assure_2_normal(P)\n end\n\n e = Int(valuation(nf(O)(p), P))\n P.splitting_type = e, f\n P.is_prime = 1\n push!(result, (P, e))\n end\n #=\n if degree_limit >= degree(O)\n O.index_div[fmpz(p)] = result\n end\n =#\n return result\nend\n\nfunction uniformizer(P::NfOrdIdl)\n p = minimum(P)\n if P.gens_normal == p\n return P.gen_two\n else\n if p > 250\n r = 500 # should still have enough elements...\n else\n r = Int(div(p, 2))\n end\n z = rand(P, r)\n while true \n if !iszero(z) && valuation(z, P) == 1\n break\n end\n z = rand(P, r)\n end\n return z\n end\nend\n\n# Belabas p. 40\nfunction anti_uniformizer(P::NfOrdIdl)\n if isdefined(P, :anti_uniformizer)\n return P.anti_uniformizer\n else\n p = minimum(P)\n M = representation_matrix(uniformizer(P))\n Mp = MatrixSpace(ResidueRing(FlintZZ, p, cached=false), rows(M), cols(M), false)(M)\n K = kernel(Mp)\n @assert length(K) > 0\n P.anti_uniformizer = elem_in_nf(order(P)(_lift(K[1])))//p\n return P.anti_uniformizer\n end\nend\n\n# Don't use the following function. It does not work for index divisors\n# TH: Or does it?\nfunction prime_decomposition_type(O::NfOrd, p::Integer)\n if (mod(discriminant(O), p)) != 0 && (mod(fmpz(index(O)), p) != 0)\n K = nf(O)\n f = K.pol\n R = parent(f)\n Zx, x = PolynomialRing(FlintZZ,\"x\", cached=false)\n Zf = Zx(f)\n fmodp = PolynomialRing(ResidueRing(FlintZZ,p, cached = false), \"y\", cached = false)[1](Zf)\n fac = factor_shape(fmodp)\n g = sum([ x for x in values(fac)])\n res = Array{Tuple{Int, Int}}(g)\n k = 1\n for (fi, ei) in fac\n for j in 1:ei\n res[k] = (fi, 1)\n k = k + 1\n end\n end\n else\n lp = prime_decomposition(O, p)\n res = Array{Tuple{Int, Int}}(length(lp))\n for i in 1:length(lp)\n res[i] = (lp[i][1].splitting_type[2], lp[i][1].splitting_type[1])\n end\n end\n return res\nend\n\ndoc\"\"\"\n***\n prime_ideals_up_to(O::NfOrd,\n B::Int;\n degree_limit::Int = 0) -> Array{NfOrdIdl, 1}\n\n> Computes the prime ideals $\\mathcal O$ with norm up to $B$.\n>\n> If `degree_limit` is a nonzero integer $k$, then prime ideals $\\mathfrak p$\n> with $\\deg(\\mathfrak p) > k$ will be discarded.\n\"\"\"\nfunction prime_ideals_up_to(O::NfOrd, B::Int;\n complete::Bool = false,\n degree_limit::Int = 0)\n p = 1\n r = NfOrdIdl[]\n while p < B\n p = next_prime(p)\n if p > B\n return r\n end\n if !complete\n deg_lim = Int(floor(log(B)/log(p)))\n if degree_limit >0\n deg_lim = min(deg_lim, degree_limit)\n end\n else\n deg_lim = 0\n end\n @vprint :ClassGroup 2 \"decomposing $p ... (bound is $B, deg_lim $deg_lim)\\n\"\n li = prime_decomposition(O, p, deg_lim)\n for P in li\n push!(r, P[1])\n end\n end\n return r\nend\n\ndoc\"\"\"\n***\n prime_ideals_over(O::NfOrd,\n lp::AbstractArray{Int, 1};\n degree_limit::Int = 0) -> Array{NfOrdIdl, 1}\n\n> Computes the prime ideals $\\mathcal O$ over prime numbers in $lp$.\n>\n> If `degree_limit` is a nonzero integer $k$, then prime ideals $\\mathfrak p$\n> with $\\deg(\\mathfrak p) > k$ will be discarded.\n\"\"\"\nfunction prime_ideals_over(O::NfOrd,\n lp::AbstractArray{T};\n degree_limit::Int = 0) where T <: Union{fmpz, Integer}\n p = 1\n r = NfOrdIdl[]\n for p in lp\n @vprint :ClassGroup 2 \"decomposing $p ... (deg_lim $deg_lim)\"\n li = prime_decomposition(O, p, degree_limit)\n for P in li\n push!(r, P[1])\n end\n end\n return r\nend\n\n\ndoc\"\"\"\n***\n prime_ideals_up_to(O::NfOrd,\n B::Int;\n complete::Bool = false,\n degree_limit::Int = 0,\n F::Function,\n bad::fmpz)\n\n> Computes the prime ideals $\\mathcal O$ with norm up to $B$.\n>\n> If `degree_limit` is a nonzero integer $k$, then prime ideals $\\mathfrak p$\n> with $\\deg(\\mathfrak p) > k$ will be discarded.\n>\n> The function $F$ must be a function on prime numbers not dividing `bad` such that\n> $F(p) = \\deg(\\mathfrak p)$ for all prime ideals $\\mathfrak p$ lying above $p$.\n\"\"\"\nfunction prime_ideals_up_to(O::NfOrd, B::Int, F::Function, bad::fmpz = discriminant(O);\n complete::Bool = false,\n degree_limit::Int = 0)\n p = 1\n r = NfOrdIdl[]\n while p < B\n p = next_prime(p)\n if p > B\n return r\n end\n if !complete\n deg_lim = flog(fmpz(B), p) # Int(floor(log(B)/log(p)))\n if degree_limit > 0\n deg_lim = min(deg_lim, degree_limit)\n end\n else\n deg_lim = 0\n end\n @vprint :ClassGroup 2 \"decomposing $p ... (bound is $B)\"\n if mod(bad, p) == 0\n li = prime_decomposition(O, p, deg_lim)\n for P in li\n push!(r, P[1])\n end\n else\n if F(p) <= deg_lim\n li = prime_decomposition(O, p, deg_lim)\n for P in li\n push!(r, P[1])\n end\n end\n end\n end\n return r\nend\n\n################################################################################\n#\n# Coprime\n#\n################################################################################\n\n#TODO: do sth. useful here!!!\nfunction divides(A::NfOrdIdl, B::NfOrdIdl)\n minimum(A) % minimum(B) == 0 || return false\n return valuation(A, B) > 0\nend\n\nfunction coprime_base(A::Array{NfOrdIdl, 1}, p::fmpz)\n #consider A^2 B and A B: if we do gcd with the minimum, we get twice AB\n #so the coprime base is AB\n #however using the p-part of the norm, the coprime basis becomes A, B...\n if iseven(p)\n lp = prime_decomposition(order(A[1]), 2)\n Ap = [x[1] for x = lp if any(y->divides(y, x[1]) > 0, A)]\n a = remove(p, 2)[2]\n if !isone(a)\n Bp = coprime_base(A, a)\n return vcat(Ap, Bp) \n else\n return Ap\n end\n else\n Ap = [gcd(x, p^valuation(norm(x), p)) for x = A if minimum(x) % p == 0]\n end\n return coprime_base_steel(Ap)\nend\n\ndoc\"\"\"\n***\n coprime_base(A::Array{NfOrdIdl, 1}) -> Array{NfOrdIdl, 1}\n coprime_base(A::Array{NfOrdElem, 1}) -> Array{NfOrdIdl, 1}\n> A coprime base for the (principal) ideals in $A$, ie. the returned array\n> generated multiplicatively the same ideals as the input and are pairwise\n> coprime.\n\"\"\"\nfunction coprime_base(A::Array{NfOrdIdl, 1})\n a = collect(Set(map(minimum, A)))\n a = coprime_base(a)\n C = Array{NfOrdIdl, 1}()\n\n for p = a\n if p == 1\n continue\n end\n cp = coprime_base(A, p)\n append!(C, cp)\n end\n return C\nend\n\nfunction coprime_base(A::Array{NfOrdElem, 1})\n O = parent(A[1])\n return coprime_base([ideal(O, x) for x = A])\nend\n\nfunction integral_split(A::NfOrdIdl)\n return A, ideal(Order(A), fmpz(1))\nend\n\n################################################################################\n#\n# Factorization into prime ideals\n#\n################################################################################\n\n#TODO: factoring type??? (with unit)\ndoc\"\"\"\n***\n factor(A::NfOrdIdl) -> Dict{NfOrdIdl, Int}\n\n> Computes the prime ideal factorization $A$ as a dictionary, the keys being\n> the prime ideal divisors:\n> If `lp = factor_dict(A)`, then `keys(lp)` are the prime ideal divisors of A\n> and `lp[P]` is the `P`-adic valuation of `A` for all `P` in `keys(lp)`.\n\"\"\"\nfactor(A::NfOrdIdl) = factor_dict(A)\n\nfunction factor_dict(A::NfOrdIdl)\n ## this should be fixed\n lf = factor(minimum(A))\n lF = Dict{NfOrdIdl, Int}()\n n = norm(A)\n O = order(A)\n for (i, (p, v)) in enumerate(lf)\n lP = prime_decomposition(O, p)\n for P in lP\n v = valuation(A, P[1])\n if v != 0\n lF[P[1]] = v\n n = n//norm(P[1])^v\n end\n if n == 1\n return lF\n end\n end\n end\n return lF\nend\n\n################################################################################\n#\n# Functions for index divisor splitting\n#\n################################################################################\n\nmutable struct quoringalg{T} <: Ring\n base_order::NfOrd\n ideal::NfOrdIdl\n prime::T\n basis::Array{NfOrdElem, 1}\n\n function quoringalg(O::NfOrd, I::NfOrdIdl, p::T) where {T}\n\n z = new{T}()\n z.base_order = O\n z.ideal = I\n z.prime = p\n\n # compute a basis\n Rp = ResidueRing(FlintZZ, p, cached=false)\n Amodp = MatrixSpace(Rp, degree(O), degree(O), false)(basis_mat(I))\n Amodp = vcat(Amodp, zero_matrix(Rp, 1, degree(O)))\n Amodp[1,1] = 1\n Amodp = sub(Amodp, 1:degree(O), 1:degree(O))\n\n r, B = _rref(Amodp)\n C = zero_matrix(Rp, degree(O)-r, degree(O))\n BB = Array{NfOrdElem}(degree(O) - r)\n pivots = Array{Int}(0)\n# # get he pivots of B\n for i in 1:r\n for j in 1:degree(O)\n if !iszero(B[i,j])\n push!(pivots, j)\n break\n end\n end\n end\n i = 1\n k = 1\n while i <= degree(O)-r\n for j in k:degree(O)\n if !in(j, pivots)\n BB[i] = basis(O)[j]\n C[i,j] = 1\n k = j + 1\n i = i + 1\n break\n end\n end\n end\n insert!(BB, 1, basis(O)[1])\n z.basis = BB\n return z\n end\nend\n\nmutable struct quoelem\n parent::quoringalg\n elem::NfOrdElem\n coord::Array{fmpz, 1}\n\n function quoelem(R::quoringalg, x::NfOrdElem)\n z = new()\n z.parent = R\n z.elem = x\n\n return z\n end\nend\n\nfunction _kernel_of_frobenius(R::quoringalg)\n O = R.base_order\n BB = R.basis\n p = R.prime\n Rp = ResidueRing(FlintZZ, R.prime, cached=false)\n C = zero_matrix(Rp, length(BB)+1, degree(O))\n D = zero_matrix(Rp, length(BB), degree(O))\n\n Q, mQ = quo(O, R.ideal)\n\n function g(x)\n return mQ\\(mQ(x)^p)\n end\n\n for i in 1:length(BB)\n A = elem_in_basis(mod(g(BB[i]) - BB[i], R.ideal))\n for j in 1:degree(O)\n D[i,j] = A[j]\n end\n end\n\n DD = NfOrdElem[ dot(BB, _lift(r)) for r in kernel(D) ]\n\n return [ quoelem(R, r) for r in DD ]\nend\n\nfunction _lift(T::Array{Generic.Res{fmpz}, 1})\n return [ z.data for z in T ]\nend\n\nfunction _lift(T::Array{Nemo.nmod, 1})\n return [ fmpz(z.data) for z in T ]\nend\n\n\nfunction *(x::quoelem, y::quoelem)\n z = mod(x.elem * y.elem, x.parent.ideal)\n return quoelem(x.parent, z)\nend\n\nfunction ^(x::quoelem, y::Int)\n z = mod(x.elem^y, x.parent.ideal)\n return quoelem(x.parent, z)\nend\n\nfunction ^(x::quoelem, y::Union{Integer, fmpz})\n # Do something stupid\n R, m = quo(x.parent.base_order, x.parent.ideal)\n return quoelem(x.parent, (m\\(m(x.elem)^y)))\nend\n\nfunction ==(x::quoelem, y::quoelem)\n z = mod(x.elem - y.elem, x.parent.ideal)\n return zero(parent(z)) == z\nend\n\nfunction minpoly(x::quoelem)\n O = x.parent.base_order\n p = x.parent.prime\n\n Rp = ResidueRing(FlintZZ, p, cached=false)\n A = zero_matrix(Rp, 0, degree(O))\n B = zero_matrix(Rp, 1, degree(O))\n\n for i in 0:degree(O)\n ar = elem_in_basis((x^i).elem)\n for j in 1:degree(O)\n B[1, j] = ar[j]\n end\n A = vcat(A, B)\n K = kernel(A)\n if length(K) > 0\n @assert length(K) == 1\n f = PolynomialRing(Rp, \"x\", cached=false)[1](K[1])\n return f\n end\n end\n error(\"cannot find minpoly\")\nend\n\nfunction split(R::quoringalg)\n if length(R.basis) == 1\n return [ R ]\n end\n K = _kernel_of_frobenius(R)\n O = R.base_order\n p = R.prime\n\n k = length(K)\n\n if k == 1\n # the algebra is a field over F_p\n # the ideal Ip is a prime ideal!\n return [ R ]\n end\n\n maxit = 1\n\n while true\n maxit = maxit + 1\n r = rand(0:p-1, length(K))\n\n x = quoelem(R, dot([ x.elem for x in K], r))\n\n if mod((x^p).elem, R.ideal) != mod(x.elem, R.ideal)\n #println(\"element^p: $(mod((x^p).elem, R.ideal))\")\n #println(\"element: $(mod(x.elem, R.ideal))\")\n #println(R.ideal.basis_mat)\n #println(K)\n error(\"Strange\")\n end\n\n f = minpoly(x)\n\n if degree(f) < 2\n continue\n end\n @assert issquarefree(f)\n\n# # By theory, all factors should have degree 1 # exploit this if p is small!\n fac = factor(f)\n F = first(keys(fac.fac))\n @assert length(fac) == degree(f)\n H = divexact(f,F)\n E, U, V = gcdx(F, H)\n @assert E == 1\n H = U*F;\n idem = O(coeff(H,0).data)\n for i in 1:degree(H)\n idem = idem + coeff(H,i).data*x.elem^i\n end\n\n I1 = R.ideal + ideal(O, idem)\n I2 = R.ideal + ideal(O, O(1)-idem)\n\n return vcat(split(quoringalg(O, I1, p)), split(quoringalg(O, I2, p)))\n break\n end\nend\n\n################################################################################\n#\n# Primality testing\n#\n################################################################################\n\ndoc\"\"\"\n***\n isprime_known(A::NfOrdIdl) -> Bool\n\n> Returns whether $A$ knows if it is prime.\n\"\"\"\nfunction isprime_known(A::NfOrdIdl)\n return A.is_prime != 0\nend\n\ndoc\"\"\"\n***\n isprime(A::NfOrdIdl) -> Bool\n\n> Returns whether $A$ is a prime ideal.\n\"\"\"\nfunction isprime(A::NfOrdIdl)\n if isprime_known(A)\n return A.is_prime == 1\n elseif minimum(A) == 0\n A.is_prime = 2\n return false\n end\n\n (n, p) = ispower(norm(A, Val{false}))\n\n if !isprime(p)\n A.is_prime = 2\n return false\n end\n\n p > 2^62 && error(\"Not implemented (yet)\")\n\n lp = prime_decomposition(order(A), Int(p))\n\n for (P, f) in lp\n e = valuation(A, P)\n if e == 1 && n == degree(P)\n A.is_prime = 1\n return true\n elseif e == 0\n continue\n else\n A.is_prime = 2\n return false\n end\n end\n\n error(\"Something wrong in isprime\")\nend\n\n################################################################################\n#\n# Valuation\n#\n################################################################################\n\n# CF:\n# Classical algorithm of Cohen, but take a valuation element with smaller (?)\n# coefficients. Core idea is that the valuation elementt is, originally, den*gen_two(p)^-1\n# where gen_two(p) is \"small\". Actually, we don't care about gen_two, we\n# need gen_two^-1 to be small, hence this version.\nfunction val_func_no_index(p::NfOrdIdl)\n P = p.gen_one\n K = nf(order(p))\n pi = inv(p)\n d = denominator(K(pi.num.gen_two))\n @assert gcd(d, P) == 1\n e = K(pi.num.gen_two)*d\n M = zero_matrix(FlintZZ, 1, degree(K))\n elem_to_mat_row!(M, 1, d, e)\n @assert d == 1\n P2 = P^2\n P22 = div(P2, 2)\n for i=1:degree(K)\n x = M[1,i] % P2\n if x>P22\n x -= P2\n end\n M[1,i] = x\n end\n e = elem_from_mat_row(K, M, 1, P)\n # e is still a valuation element, but with smaller coefficients.\n return function(x::nf_elem)\n v = 0\n d = denominator(x)\n x *= d\n x = x*e\n while denominator(x) % P != 0\n v += 1\n mul!(x, x, e)\n end\n return v-valuation(d, P)*p.splitting_type[1]\n end\nend\n\n# CF:\n# The idea is that valuations are mostly small, eg. in the class group\n# algorithm. So this version computes the completion and the embedding into it\n# at small precision and can thus compute (small) valuation at the effective\n# cost of an mod(nmod_poly, nmod_poly) operation.\n# Isn't it nice?\nfunction valuation(a::UInt, b::UInt)\n return ccall((:n_remove, :libflint), Int, (Ref{UInt}, UInt), a, b)\nend\n\n#=\nfunction valuation(a::UInt, b::UInt, bi::Cdouble)\n return ccall((:n_remove2_precomp, :libflint), Int, (Ref{UInt}, UInt, Cdouble), a, b, bi)\nend\n=#\n\nfunction val_func_no_index_small(p::NfOrdIdl)\n P = p.gen_one\n @assert P <= typemax(UInt)\n K = nf(order(p))\n Rx = PolynomialRing(ResidueRing(FlintZZ, UInt(P), cached=false), cached=false)[1]\n Zx = PolynomialRing(FlintZZ)[1]\n g = Rx(p.gen_two.elem_in_nf)\n f = Rx(K.pol)\n g = gcd!(g, g, f)\n g = lift(Zx, g)\n k = flog(fmpz(typemax(UInt)), P)\n g = hensel_lift(Zx(K.pol), g, P, k)\n Sx = PolynomialRing(ResidueRing(FlintZZ, UInt(P)^k, cached=false), cached=false)[1]\n g = Sx(g)\n h = Sx()\n uP = UInt(P)\n return function(x::nf_elem)\n d = denominator(x)\n nf_elem_to_nmod_poly!(h, x, false) # ignores the denominator\n h = rem!(h, h, g)\n c = Nemo.coeff_raw(h, 0)\n v = c==0 ? typemax(Int) : valuation(c, uP)\n for i=1:degree(h)\n c = Nemo.coeff_raw(h, i)\n v = min(v, c==0 ? typemax(Int) : valuation(c, uP))\n end\n return v-valuation(d, P)\n end\nend\n\nfunction val_func_index(p::NfOrdIdl)\n # We are in the index divisor case. In larger examples, a lot of\n # time is spent computing denominators of order elements.\n # By using the representation matrix to multiply, we can stay in the order\n # and still be fast (faster even than in field).\n\n pi = inv(p)\n M = representation_matrix(pi.num.gen_two)\n O = order(p)\n P = p.gen_one\n return function(x::nf_elem)\n v = 0\n d, x_mat = integral_split(x, O)\n Nemo.mul!(x_mat, x_mat, M)\n while gcd(content(x_mat), P) == P # should divide and test in place\n divexact!(x_mat, x_mat, P)\n Nemo.mul!(x_mat, x_mat, M)\n v += 1\n end\n return v-valuation(d, P)*p.splitting_type[1]\n end\nend\n\ndoc\"\"\"\n***\n valuation(a::nf_elem, p::NfOrdIdl) -> fmpz\n valuation(a::NfOrdElem, p::NfOrdIdl) -> fmpz\n valuation(a::fmpz, p::NfOrdIdl) -> fmpz\n\n> Computes the $\\mathfrak p$-adic valuation of $a$, that is, the largest $i$\n> such that $a$ is contained in $\\mathfrak p^i$.\n\"\"\"\nfunction valuation(a::nf_elem, p::NfOrdIdl)\n @hassert :NfOrd 0 !iszero(a)\n #assert(a !=0) # can't handle infinity yet\n if isdefined(p, :valuation)\n return p.valuation(a)::Int\n end\n O = order(p)\n P = p.gen_one\n\n # for generic ideals\n if p.splitting_type[2] == 0\n #global bad_ideal = p\n p.valuation = function(a::nf_elem)\n d = denominator(a, O)\n x = O(d*a)\n return valuation_naive(O(x), p)::Int - valuation_naive(O(d), p)::Int\n end\n return p.valuation(a)::Int\n end\n\n if p.splitting_type[1]*p.splitting_type[2] == degree(O)\n p.valuation = function(a::nf_elem)\n return divexact(valuation(norm(a), P)[1], p.splitting_type[2])::Int\n end\n elseif mod(index(O),P) != 0 && p.splitting_type[1] == 1\n if p.gen_one^2 <= typemax(UInt) \n f1 = val_func_no_index_small(p)\n f2 = val_func_no_index(p)\n p.valuation = function(x::nf_elem)\n v = f1(x)\n if v > 100 # can happen ONLY if the precision in the .._small function\n # was too small.\n return f2(x)::Int\n else\n return v::Int\n end\n end\n else\n p.valuation = val_func_no_index(p)\n end\n else\n p.valuation = val_func_index(p)\n end\n\n return p.valuation(a)::Int\nend\n\ndoc\"\"\"\n***\n valuation(a::nf_elem, p::NfOrdIdl) -> fmpz\n valuation(a::NfOrdElem, p::NfOrdIdl) -> fmpz\n valuation(a::fmpz, p::NfOrdIdl) -> fmpz\n\n> Computes the $\\mathfrak p$-adic valuation of $a$, that is, the largest $i$\n> such that $a$ is contained in $\\mathfrak p^i$.\n\"\"\"\nvaluation(a::NfOrdElem, p::NfOrdIdl) = valuation(a.elem_in_nf, p)\n\ndoc\"\"\"\n***\n valuation(a::nf_elem, p::NfOrdIdl) -> fmpz\n valuation(a::NfOrdElem, p::NfOrdIdl) -> fmpz\n valuation(a::fmpz, p::NfOrdIdl) -> fmpz\n\n> Computes the $\\mathfrak p$-adic valuation of $a$, that is, the largest $i$\n> such that $a$ is contained in $\\mathfrak p^i$.\n\"\"\"\nfunction valuation(a::fmpz, p::NfOrdIdl)\n if p.splitting_type[1] == 0\n return valuation_naive(order(p)(a), p)\n end\n P = p.gen_one\n return valuation(a, P)* p.splitting_type[1]\nend\nvaluation(a::Integer, p::NfOrdIdl) = valuation(fmpz(a), p)\n\n#TODO: some more intelligence here...\nfunction valuation_naive(A::NfOrdIdl, B::NfOrdIdl)\n @assert !isone(B)\n Bi = inv(B)\n i = 0\n C = simplify(A* Bi)\n while denominator(C) == 1\n C = simplify(Bi*C)\n i += 1\n end\n return i\nend\n\n#TODO: some more intelligence here...\n# in non-maximal orders, interesting ideals cannot be inverted\n# maybe this needs to be checked...\nfunction valuation_naive(x::NfOrdElem, B::NfOrdIdl)\n @assert !isone(B)\n i = 0\n C = B\n while x in C\n i += 1\n C *= B\n end\n return i\nend\n\n\ndoc\"\"\"\n***\n valuation(A::NfOrdIdl, p::NfOrdIdl) -> fmpz\n\n> Computes the $\\mathfrak p$-adic valuation of $A$, that is, the largest $i$\n> such that $A$ is contained in $\\mathfrak p^i$.\n\"\"\"\nfunction valuation(A::NfOrdIdl, p::NfOrdIdl)\n _assure_weakly_normal_presentation(A)\n if !isdefined(p, :splitting_type) || p.splitting_type[1] == 0 #ie. if p is non-prime...\n return valuation_naive(A, p)\n end\n return min(valuation(A.gen_one, p), valuation(elem_in_nf(A.gen_two), p))\nend\n\n################################################################################\n#\n# Prime ideals iterator\n#\n################################################################################\n\nmutable struct PrimeIdealsSet\n order::NfOrd\n from::fmpz\n to::fmpz\n primes::PrimesSet{fmpz}\n currentprime::fmpz\n currentindex::Int\n decomposition::Array{Tuple{NfOrdIdl, Int}, 1}\n proof::Bool\n indexdivisors::Bool\n ramified::Bool\n iscoprimeto::Bool\n coprimeto::NfOrdIdl\n degreebound::Int\n unbound::Bool\n\n function PrimeIdealsSet(O::NfOrd)\n z = new()\n z.order = O\n z.proof = false\n z.indexdivisors = true\n z.ramified = true\n z.unbound = false\n z.degreebound = degree(O)\n z.iscoprimeto = false\n return z\n end\nend\n\ndoc\"\"\"\n***\n PrimeIdealsSet(O::NfOrd, f, t; proof = false,\n indexdivisors = true,\n ramified = true,\n degreebound = degree(O),\n coprimeto = false) \n\nReturns an iterable object $S$ representing the prime ideals $\\mathfrak p$\nof $\\mathcal O$ with $f \\leq \\min(\\mathfrak p) \\leq t$. \n\nThe optional arguments can be used to exclude index divisors, ramified prime\nideals and to include only prime ideals with degree less or equal than\n`degreebound` and which are coprime to `coprimeto`.\n\nIf $t=-1$, then the upper bound is infinite.\n\nIf `coprimeto` is supplied, it must be either an integer, an element of $\\mathcal O$,\nor a non-zero ideal of $\\mathcal O$.\n\"\"\" \nfunction PrimeIdealsSet(O::NfOrd, from::T, to::S;\n proof::Bool = false,\n indexdivisors::Bool = true,\n ramified::Bool = true,\n degreebound::Int = degree(O),\n coprimeto = false) where {T <: Union{fmpz, Integer},\n S <: Union{fmpz, Integer}}\n from < 0 && error(\"Lower bound must be non-negative\")\n to < -1 && error(\"Upper bound must be non-negative or -1\")\n\n z = PrimeIdealsSet(O)\n z.from = fmpz(from)\n z.to = fmpz(to)\n z.primes = PrimesSet(z.from, z.to)\n if to == -1\n z.unbound = true\n end\n z.proof = proof\n z.indexdivisors = indexdivisors\n z.ramified = ramified\n z.degreebound = degreebound\n if !(coprimeto isa Bool)\n if coprimeto isa NfOrdIdl\n z.coprimeto = coprimeto\n elseif coprimeto isa Union{Integer, fmpz, NfOrdElem}\n z.coprimeto = ideal(O, coprimeto)\n else\n error(\"Coprime argument of wrong type ($(typeof(coprimeto)))\")\n end\n z.iscoprimeto = true\n end\n return z\nend\n\nfunction Base.start(S::PrimeIdealsSet)\n O = S.order\n pstate = start(S.primes)\n found_prime = false\n while !found_prime\n (p, pstate) = next(S.primes, pstate)\n if !S.indexdivisors && isindex_divisor(O, p)\n continue\n end\n lP = prime_decomposition(O, p)\n j = -1\n for i in 1:length(lP)\n e = lP[i][2]\n if !S.ramified && e > 1\n continue\n end\n P = lP[i][1]\n if P.splitting_type[2] > S.degreebound\n continue\n end\n if S.iscoprimeto && !iscoprime(P, S.coprimeto)\n continue\n end\n j = i\n break\n end\n if j != -1\n S.decomposition = lP\n S.currentprime = p\n S.currentindex = j\n return (p, j)\n end\n end\nend\n\nfunction Base.next(S::PrimeIdealsSet, x)\n pstate = x[1]\n j = x[2]\n Q = S.decomposition[j][1] # This we want to return\n newindex = -1\n lP = S.decomposition\n O = S.order\n\n # Find the next prime ideal in the current decomposition\n for i in (j + 1):length(S.decomposition)\n e = lP[i][2]\n if !S.ramified && e > 1\n continue\n end\n P = lP[i][1]\n if P.splitting_type[2] > S.degreebound\n continue\n end\n newindex = i\n break\n end\n\n if newindex != -1\n return Q, (pstate, newindex)\n else\n # We have to change the prime\n found_prime = false\n while !found_prime\n (p, pstate) = next(S.primes, pstate)\n if !S.indexdivisors && isindex_divisor(O, pstate)\n continue\n end\n lP = prime_decomposition(O, pstate)\n j = -1\n for i in 1:length(lP)\n e = lP[i][2]\n if !S.ramified && e > 1\n continue\n end\n P = lP[i][1]\n if P.splitting_type[2] > S.degreebound\n continue\n end\n if S.iscoprimeto && !iscoprime(P, S.coprimeto)\n continue\n end\n j = i\n break\n end\n if j != -1\n S.decomposition = lP\n S.currentprime = p\n S.currentindex = j\n return Q, (pstate, j)\n end\n end\n end\nend\n\nfunction Base.done(S::PrimeIdealsSet, x)\n pstate = x[1]\n index = x[2]\n return !S.unbound && pstate > S.to\nend\n\nBase.eltype(::PrimeIdealsSet) = NfOrdIdl\n\nBase.iteratorsize(::Type{PrimeIdealsSet}) = Base.SizeUnknown()\n", "meta": {"hexsha": "3a0b6b979c0842f9308a23452143f3798d8d4250", "size": 37649, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NfOrd/Ideal/Prime.jl", "max_stars_repo_name": "alexjbest/Hecke.jl", "max_stars_repo_head_hexsha": "ea59d93e7a29e73e1a1ffe103db8ce37c456e405", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NfOrd/Ideal/Prime.jl", "max_issues_repo_name": "alexjbest/Hecke.jl", "max_issues_repo_head_hexsha": "ea59d93e7a29e73e1a1ffe103db8ce37c456e405", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NfOrd/Ideal/Prime.jl", "max_forks_repo_name": "alexjbest/Hecke.jl", "max_forks_repo_head_hexsha": "ea59d93e7a29e73e1a1ffe103db8ce37c456e405", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4760900141, "max_line_length": 151, "alphanum_fraction": 0.5863635156, "num_tokens": 12097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24062990457402494}} {"text": "# included from Potentials.jl\n# part of the module JuLIP.Potentials\n\nusing JuLIP: JVec, JMat, neighbourlist\nusing LinearAlgebra: I\nusing JuLIP.Chemistry: atomic_number\nusing NeighbourLists\n\nexport ZeroPairPotential, ZBLPotential,\n LennardJones, lennardjones,\n Morse, morse\n\n# For PairPotentials we do something kind of weird - we create an intentional\n# stack overflow by redirecting\n# evaluate -> evaluate! -> evaluate -> evaluate! -> ...\n# A concrete instance of PairPotential must overload either evaluate or\n# evaluate! to break this infinite loop. The advantage though is that either\n# can be implemented.\n\nevaluate(V::PairPotential, r::Number, z1, z0) =\n evaluate!(alloc_temp(V, 1), V, r, z1, z0)\nevaluate_d(V::PairPotential, r::Number, z1, z0) =\n evaluate_d!(alloc_temp_d(V, 1), V, r, z1, z0)\nevaluate_dd(V::PairPotential, r::Number, z1, z0) =\n evaluate_dd!(alloc_temp_dd(V, 1), V, r, z1, z0)\nevaluate!(tmp, V::PairPotential, r::Number, z1, z0) =\n evaluate(V, r, z1, z0)\nevaluate_d!(tmp, V::PairPotential, r::Number, z1, z0) =\n evaluate_d(V, r, z1, z0)\nevaluate_dd!(tmp, V::PairPotential, r::Number, z1, z0) =\n evaluate_dd(V, r, z1, z0)\n\n# evaluate!(tmp, V::PairPotential, r::Union{Number, JVec}) = V(r)\n# evaluate_d!(tmp, V::PairPotential, r::Number) = @D V(r)\n# evaluate_dd!(tmp, V::PairPotential, r::Number) = @DD V(r)\n# evaluate_d!(tmp, V::PairPotential, R::JVec) =\n# evaluate_d!(tmp, V, norm(R), R)\n# evaluate_d!(tmp, V::PairPotential, r::Number, R::JVec) = ((@D V(r))/r) * R\n# evaluate_dd!(tmp, V::PairPotential, r::Number) = @DD V(r)\n# evaluate_dd!(tmp, V::PairPotential, R::JVec) =\n# evaluate_dd!(tmp, V, norm(R), R)\n# evaluate_dd!(tmp, V::PairPotential, r::Number, R::JVec) =\n# _hess!(tmp, V, r, R)\n\n\n\nfunction evaluate!(tmp, V::PairPotential,\n R::AbstractVector{JVec{T}}, Z, z0) where {T}\n Es = zero(T)\n for i = 1:length(R)\n Es += T(0.5) * evaluate!(tmp, V, norm(R[i]), Z[i], z0)\n end\n return Es\nend\n\nfunction evaluate_d!(dEs, tmp, V::PairPotential,\n R::AbstractVector{JVec{T}}, Z, z0) where {T}\n for i = 1:length(R)\n r = norm(R[i])\n dEs[i] = (T(0.5) * evaluate_d!(tmp, V, r, Z[i], z0) / r) * R[i]\n end\n return dEs\nend\n\nfunction evaluate_dd!(hEs, tmp, V::PairPotential,\n R::AbstractVector{<: JVec}, Z, z0)\n n = length(R)\n for i = 1:n\n hEs[i,i] = 0.5 * _hess!(tmp, V, norm(R[i]), R[i], Z[i], z0)\n end\n return hEs\nend\n\nfunction _hess!(tmp, V::PairPotential, r::Number, R::JVec, z1, z0)\n R̂ = R/r\n P = R̂ * R̂'\n dV = evaluate_d!(tmp, V, r, z1, z0) / r\n ddV = evaluate_dd!(tmp, V, r, z1, z0)\n return (ddV - dV) * P + dV * I\nend\n\nfunction precon!(hEs, tmp, V::PairPotential,\n R::AbstractVector{<: JVec{T}}, Z, z0,\n innerstab=T(0.0)) where {T}\n n = length(R)\n for i = 1:n\n hEs[i,i] = precon!(tmp, V, norm(R[i]), R[i], Z[i], z0, innerstab)\n end\n return hEs\nend\n\n\n# an FF preconditioner for pair potentials\nfunction precon!(tmp, V::PairPotential, r::T, R::JVec{T}, innerstab=T(0.1)\n ) where {T <: Number}\n r = norm(R)\n dV = evaluate_d!(tmp, V, r)\n ddV = evaluate_dd!(tmp, V, r)\n R̂ = R/r\n return (1-innerstab) * (abs(ddV) * R̂ * R̂' + abs(dV / r) * (I - R̂ * R̂')) +\n innerstab * (abs(ddV) + abs(dV / r)) * I\nend\n\n\n# ------- Implementation of SimplePairPotential\n\nevaluate!(tmp, V::SimplePairPotential, r::Number, z1, z0) = evaluate!(tmp, V, r)\nevaluate_d!(tmp, V::SimplePairPotential, r::Number, z1, z0) = evaluate_d!(tmp, V, r)\nevaluate_dd!(tmp, V::SimplePairPotential, r::Number, z1, z0) = evaluate_dd!(tmp, V, r)\nevaluate!(tmp, V::SimplePairPotential, r) = evaluate(V, r)\nevaluate_d!(tmp, V::SimplePairPotential, r) = evaluate_d(V, r)\nevaluate_dd!(tmp, V::SimplePairPotential, r) = evaluate_dd(V, r)\nevaluate(V::SimplePairPotential, r::Number) = evaluate!(alloc_temp(V, 1), V, r)\nevaluate_d(V::SimplePairPotential, r::Number) = evaluate_d!(alloc_temp_d(V, 1), V, r)\nevaluate_dd(V::SimplePairPotential, r::Number) = evaluate_dd!(alloc_temp_dd(V, 1), V, r)\n\nevaluate_d(V::SimplePairPotential, r::Number, R::JVec) =\n (evaluate_d(V, r)/r) * R\n\nfunction evaluate_dd(V::SimplePairPotential, r::Number, R::JVec)\n dV = evaluate_d(V, r) / r\n ddV = evaluate_dd(V, r)\n return ((ddV - dV)/r^2) * R * R' + dV * I\nend\n\n# ------- Implementation of ExplicitPairPotential\n\nevaluate(p::ExplicitPairPotential, r::Number) = p.f(r)\nevaluate_d(p::ExplicitPairPotential, r::Number) = p.f_d(r)\nevaluate_dd(p::ExplicitPairPotential, r::Number) = p.f_dd(r)\n\n\n# ------- Some concrete potentials\n\n\"\"\"\n`LennardJones(σ, e0):` constructs the 6-12 Lennard-Jones potential [wiki](https://en.wikipedia.org/wiki/Lennard-Jones_potential)\n\n e0 * 4 * ( (σ/r)¹² - (σ/r)⁶ )\n\nConstructor with kw arguments: `LennardJones(; kwargs...)`\n\n* `e0, σ` : standard LJ parameters, default `e0 = 1.0, σ = 1.0`\n* `r0` : equilibrium distance - if `r0` is specified then `σ` is ignored\n* `a0` : FCC lattice parameter, if `a0` is specified then `σ` is ignored\n\n(`r0, a0` cannot both be specified at the same time)\n\"\"\"\nLennardJones(σ, e0) = (@analytic r -> e0 * 4.0 * ((σ/r)^(12) - (σ/r)^(6)))\n\n\nfunction ljparams(; σ=1.0, e0=1.0, r0 = nothing, a0 = nothing)\n if r0 != nothing && a0 != nothing\n error(\"`LenndardJones`: cannot specify both `r0` and `a0`\")\n end\n if a0 != nothing # r0 = nn-dist = a0/sqrt(2) in FCC\n r0 = a0 / sqrt(2)\n end\n if r0 != nothing # standard LJ is minimised at r = 2^(1/6)\n σ = r0 / 2^(1/6)\n end\n return σ, e0\nend\n\nLennardJones(; kwargs...) = LennardJones(ljparams(;kwargs...)...)\n\n\n\"\"\"\n`lennardjones(; kwargs...)`\n\nsimplified constructor for `LennardJones` (note this is type unstable!)\n\nIn addition to the `kwargs` of `LennardJones`, this accepts also\n\n* `rcut` : default `:auto` which gives `rcut = (1.9*σ, 2.7*σ)`. Use\n`nothing` or `Inf` to specify no cutoff, or specify a tuple or\narray with two elements specifying the lower and upper cut-off radii to be\nused with `SplineCutoff`.\n\"\"\"\nfunction lennardjones(; rcut = :auto, kwargs...)\n σ, e0 = ljparams(; kwargs...)\n if (rcut == nothing || rcut == Inf)\n return LennardJones(σ, e0)\n elseif rcut == :auto\n rcut = (1.9*σ, 2.7*σ)\n end\n return SplineCutoff(rcut[1], rcut[2]) * LennardJones(σ, e0)\nend\n\n\"\"\"\n`Morse(A, e0, r0)` or `Morse(;A=4.0, e0=1.0, r0=1.0)`: constructs a\n`PairPotential` for\n```\n e0 ( exp( -2 A (r/r0 - 1) ) - 2 exp( - A (r/r0 - 1) ) )\n```\n\"\"\"\nMorse(A, e0, r0) = @analytic(\n r -> e0 * ( exp(-(2.0*A) * (r/r0 - 1.0)) - 2.0 * exp(-A * (r/r0 - 1.0)) ) )\nMorse(;A=4.0, e0=1.0, r0=1.0) = Morse(A, e0, r0)\n\n\"\"\"\n`morse(A=4.0, e0=1.0, r0=1.0, rcut=(1.9*r0, 2.7*r0))`\n\nsimplified constructor for `Morse` (type unstable)\n\"\"\"\nmorse(;A=4.0, e0=1.0, r0=1.0, rcut=(1.9*r0, 2.7*r0)) = (\n (rcut == nothing || rcut == Inf)\n ? Morse(A, e0, r0)\n : SplineCutoff(rcut[1], rcut[2]) * Morse(A, e0, r0) )\n\n\n\"\"\"\n`ZeroPairPotential()`: creates a potential that just returns zero\n\"\"\"\nstruct ZeroPairPotential <: SimplePairPotential end\n\n@pot ZeroPairPotential\n\nevaluate(p::ZeroPairPotential, r::T) where {T <: Number} = T(0.0)\nevaluate_d(p::ZeroPairPotential, r::T) where {T <: Number} = T(0.0)\nevaluate_dd(p::ZeroPairPotential, r::T) where {T <: Number} = T(0.0)\ncutoff(p::ZeroPairPotential) = Bool(0) # the weakest number type\n\n\n\n\n# ====================================================================\n# A product of two pair potentials: primarily used for cutoff mechanisms\n\n\"product of two `SimplePairPotential`\"\nmutable struct SimpleProdPot{P1, P2} <: SimplePairPotential\n p1::P1\n p2::P2\nend\n\n@pot SimpleProdPot\n\nimport Base.*\n*(p1::SimplePairPotential, p2::SimplePairPotential) = SimpleProdPot(p1, p2)\nevaluate(p::SimpleProdPot, r::Number) = p.p1(r) * p.p2(r)\nevaluate_d(p::SimpleProdPot, r::Number) = (p.p1(r) * (@D p.p2(r)) + (@D p.p1(r)) * p.p2(r))\nevaluate_dd(p::SimpleProdPot, r::Number) = (p.p1(r) * (@DD p.p2(r)) +\n 2 * (@D p.p1(r)) * (@D p.p2(r)) + (@DD p.p1(r)) * p.p2(r))\ncutoff(p::SimpleProdPot) = min(cutoff(p.p1), cutoff(p.p2))\n\n\"product of two `PairPotential`\"\nmutable struct ProdPot{P1, P2} <: PairPotential\n p1::P1\n p2::P2\nend\n\n@pot ProdPot\n\nimport Base.*\n*(p1::PairPotential, p2::PairPotential) = ProdPot(p1, p2)\nevaluate(p::ProdPot, r::Number, z1, z0) =\n p.p1(r, z1, z0) * p.p2(r, z1, z0)\nevaluate_d(p::ProdPot, r::Number, z1, z0) =\n (p.p1(r, z1, z0) * (@D p.p2(r, z1, z0)) + (@D p.p1(r, z1, z0)) * p.p2(r, z1, z0))\nevaluate_dd(p::ProdPot, r::Number, z1, z0) =\n ( p.p1(r, z1, z0) * (@DD p.p2(r, z1, z0))\n + 2 * (@D p.p1(r, z1, z0)) * (@D p.p2(r, z1, z0))\n + (@DD p.p1(r, z1, z0)) * p.p2(r, z1, z0)\n )\ncutoff(p::ProdPot) = min(cutoff(p.p1), cutoff(p.p2))\n\n# ====================================================================\n\n\n\n\"\"\"\n`struct WrappedPairPotential`\n\nwraps a pairpotential using `FunctionWrappers` in order to allow\ntype-stable storage of multiple potentials. This is the main technique\nrequired at the moment to work with multi-component systems.\nOtherwise, this is not advisable since it disables a range of\npossible compiler optimisations.\n\"\"\"\nstruct WrappedPairPotential <: ExplicitPairPotential\n f::F64fun\n f_d::F64fun\n f_dd::F64fun\n rcut::Float64\nend\n\n@pot WrappedPairPotential\n\ncutoff(V::WrappedPairPotential) = V.rcut\n# evaluate, etc are all derived from SimplePairPotential\n\nfunction WrappedPairPotential(V::AnalyticFunction, rcut)\n @assert (0 < rcut < Inf)\n f, f_d, f_dd = let V=V, rc = rcut\n (F64fun(r -> evaluate(V, r) * (r evaluate_d(V, r) * (r evaluate_dd(V, r) * (r evaluate(V, r) * (r evaluate_d(V, r) * (r evaluate_dd(V, r) * (r C * (E1*exp(-A1*r) + E2*exp(-A2*r) +\n E3*exp(-A4*r) + E4*exp(-A4*r) ) / r)\n ZBLPotential(V)\n end)\n\n_zbl_au(Z1, Z2) = (0.8854 * 0.529) / (Z1^0.23 + Z2^0.23)\n\nfunction evaluate(V::ZBLPotential, r::Number, z1, z0)\n au = _zbl_au(z1, z0)\n return evaluate(V.V, r / au)\nend\n\nfunction evaluate_d(V::ZBLPotential, r::Number, z1, z0)\n au = _zbl_au(z1, z0)\n return evaluate_d(V.V, r / au) / au\nend\n\ncutoff(::ZBLPotential) = Inf\n\nwrite_dict(V::ZBLPotential) = Dict(\"__id__\" => \"JuLIP_ZBLPotential\")\nread_dict(::Val{:JuLIP_ZBLPotential}, D::Dict) = ZBLPotential()\n", "meta": {"hexsha": "4e1f566a49a79cdac7db373c65cc020a849311a8", "size": 11301, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pairpotentials.jl", "max_stars_repo_name": "wcwitt/JuLIP.jl", "max_stars_repo_head_hexsha": "68e1f987ba7f51fc1145870cbc99b2718da38f1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2016-08-03T22:39:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-27T10:57:58.000Z", "max_issues_repo_path": "src/pairpotentials.jl", "max_issues_repo_name": "wcwitt/JuLIP.jl", "max_issues_repo_head_hexsha": "68e1f987ba7f51fc1145870cbc99b2718da38f1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2016-08-01T20:48:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T15:25:23.000Z", "max_forks_repo_path": "src/pairpotentials.jl", "max_forks_repo_name": "wcwitt/JuLIP.jl", "max_forks_repo_head_hexsha": "68e1f987ba7f51fc1145870cbc99b2718da38f1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2016-09-22T15:16:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-18T20:42:13.000Z", "avg_line_length": 31.8338028169, "max_line_length": 128, "alphanum_fraction": 0.6048137333, "num_tokens": 4043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.24062990457402486}} {"text": "\n@inline incrementp(A::AbstractStridedPointer{T,3} where T, a::Ptr) = VectorizationBase.increment_ptr(A, a, (Zero(), Zero(), One()))\n@inline increment2(B::AbstractStridedPointer{T,2} where T, b::Ptr, ::StaticInt{nᵣ}) where {nᵣ} = VectorizationBase.increment_ptr(B, b, (Zero(), StaticInt{nᵣ}()))\n@inline increment1(C::AbstractStridedPointer{T,2} where T, c::Ptr, ::StaticInt{mᵣW}) where {mᵣW} = VectorizationBase.increment_ptr(C, c, (StaticInt{mᵣW}(), Zero()))\nmacro kernel(pack::Bool, ex::Expr)\n ex.head === :for || throw(ArgumentError(\"Must be a matmul for loop.\"))\n mincrements = Expr[:(c = increment1(C, c, mᵣW)), :(ãₚ = incrementp(Ãₚ, ãₚ)), :(m = vsub_nsw(m, mᵣW))]\n # massumes = Expr[:(assume(m < mᵣW)),\n # :(assume(VectorizationBase.vgt(ãₚ, VectorizationBase.increment_ptr($(esc(:Ãₚ)), ãₚ, (vsub_nsw($(esc(:M)), mᵣW), LoopVectorization.Zero())), $(esc(:Ãₚ))))),\n # :(assume(VectorizationBase.vgt(c, VectorizationBase.increment_ptr($(esc(:C)), c, (vsub_nsw($(esc(:M)), mᵣW), LoopVectorization.Zero())), $(esc(:C)))))]\n offsetprecalc = GlobalRef(VectorizationBase,:offsetprecalc)\n preheader = quote\n mᵣ, nᵣ = matmul_params(Val($(esc(:T))))\n mᵣW = pick_vector_width($(esc(:T))) * mᵣ\n m = $(esc(:M)) % Int32\n n = $(esc(:N)) % Int32\n Ãₚ = $(esc(:Ãₚ))\n B = $offsetprecalc($(esc(:B)), Val{(9,9)}())\n C = $offsetprecalc($(esc(:C)), Val{(9,9)}())\n b = pointer(B); c = pointer(C); ãₚ = pointer(Ãₚ)\n end\n if pack\n push!(mincrements, :(a = increment1(A, a, mᵣW)))\n push!(preheader.args, :(A = $(esc(:A))), :(a = pointer(A)))\n areconstruct = Expr[:($(esc(:A)) = VectorizationBase.reconstruct_ptr(A, a))]\n # push!(massumes, :(assume(VectorizationBase.vgt(a, VectorizationBase.increment_ptr($(esc(:A)), a, (vsub_nsw($(esc(:M)), mᵣW), LoopVectorization.Zero())), $(esc(:A))))))\n else\n Ainit = areconstruct = Expr[]\n end\n lvkern = esc(:(@turbo inline=true $ex))\n\n loopnest = quote\n let ãₚ = ãₚ, c = c, $(esc(:B)) = VectorizationBase.reconstruct_ptr(B, b), m = m\n while m ≥ mᵣW#VectorizationBase.vle(a, amax, A)\n let $(esc(:M)) = mᵣW, $(esc(:N)) = nᵣ, $(esc(:Ãₚ)) = VectorizationBase.reconstruct_ptr(droplastdim(Ãₚ), ãₚ), $(esc(:C)) = VectorizationBase.reconstruct_ptr(C, c), $(areconstruct...)\n $lvkern\n $(mincrements...)\n end\n end\n if m > zero(Int32)#vne(a, amax, A)\n let $(esc(:M)) = UpperBoundedInteger((m%UInt)%Int, mᵣW - One()), $(esc(:N)) = nᵣ, $(esc(:Ãₚ)) = VectorizationBase.reconstruct_ptr(droplastdim(Ãₚ), ãₚ), $(esc(:C)) = VectorizationBase.reconstruct_ptr(C, c), $(areconstruct...)\n # $(massumes...)\n $lvkern\n end\n end\n end\n end\n\n if !pack\n loopnest = quote\n while n ≥ nᵣ#VectorizationBase.vle(c, cmax, C)\n $loopnest\n c = increment2(C, c, nᵣ)\n b = increment2(B, b, nᵣ)\n n = vsub_nsw(n, nᵣ)\n end\n if n > zero(Int32)#vne(c, cmax, C)\n let $(esc(:B)) = VectorizationBase.reconstruct_ptr(B, b), m = m\n while m ≥ mᵣW#VectorizationBase.vle(a, amax, A)\n let $(esc(:M)) = mᵣW, $(esc(:N)) = UpperBoundedInteger((n%UInt)%Int, nᵣ - One()), $(esc(:Ãₚ)) = VectorizationBase.reconstruct_ptr(droplastdim(Ãₚ), ãₚ), $(esc(:C)) = VectorizationBase.reconstruct_ptr(C, c), $(areconstruct...)\n # assume(n < nᵣ)\n # assume((VectorizationBase.vgt(c, VectorizationBase.increment_ptr($(esc(:C)), c, (Zero(), vsub_nsw($(esc(:N)), nᵣ))), $(esc(:C)))))\n # assume((VectorizationBase.vgt(b, VectorizationBase.increment_ptr($(esc(:B)), b, (Zero(), vsub_nsw($(esc(:N)), nᵣ))), $(esc(:B)))))\n $lvkern\n $(mincrements...)\n end\n end\n if m > zero(Int32)#vne(a, amax, A)\n let $(esc(:M)) = UpperBoundedInteger((m%UInt)%Int, mᵣW - One()), $(esc(:N)) = UpperBoundedInteger((n%UInt)%Int, nᵣ - One()), $(esc(:Ãₚ)) = VectorizationBase.reconstruct_ptr(droplastdim(Ãₚ), ãₚ), $(esc(:C)) = VectorizationBase.reconstruct_ptr(C, c), $(areconstruct...)\n # $(massumes...)\n # assume(n < nᵣ)\n # assume((VectorizationBase.vgt(c, VectorizationBase.increment_ptr($(esc(:C)), c, (Zero(), vsub_nsw($(esc(:N)), nᵣ))), $(esc(:C)))))\n # assume((VectorizationBase.vgt(b, VectorizationBase.increment_ptr($(esc(:B)), b, (Zero(), vsub_nsw($(esc(:N)), nᵣ))), $(esc(:B)))))\n $lvkern\n end\n end\n end\n end\n end\n end\n Expr(:block, preheader, loopnest)\nend\n@inline function loopmul!(C, A, B, α, β, M, K, N)\n @turbo for n ∈ CloseOpen(N), m ∈ CloseOpen(M)\n Cₘₙ = zero(eltype(C))\n for k ∈ CloseOpen(K)\n Cₘₙ += A[m,k] * B[k,n]\n end\n C[m,n] = α * Cₘₙ + β * C[m,n]\n end\n nothing\nend\n@inline function ploopmul!(C::AbstractStridedPointer{T}, Ãₚ, B, α, β, M, K, N) where {T}\n @kernel false for n ∈ CloseOpen(N), m ∈ CloseOpen(M)\n Cₘₙ = zero(eltype(C))\n for k ∈ CloseOpen(K)\n Cₘₙ += Ãₚ[m,k] * B[k,n]\n end\n C[m,n] = α * Cₘₙ + β * C[m,n]\n end\n nothing\nend\n@inline function packamul!(\n C::AbstractStridedPointer{T}, Ãₚ, A, B,\n α, β, M, K, N\n ) where {T}\n @kernel true for n ∈ CloseOpen(N), m ∈ CloseOpen(M)\n Cₘₙ = zero(eltype(C))\n for k ∈ CloseOpen(K)\n Aₘₖ = A[m,k]\n Cₘₙ += Aₘₖ * B[k,n]\n Ãₚ[m,k] = Aₘₖ \n end\n C[m,n] = α * Cₘₙ + β * C[m,n] \n end\nend\n@inline function alloc_a_pack(K, ::Val{T}) where {T}\n buffer = first_cache_buffer(Val(T))\n alloc_a_pack(K, buffer), buffer\nend\n@inline alloc_a_pack(K, buffer::MemoryBuffer) = alloc_a_pack(K, align(pointer(buffer)))\n@inline function alloc_a_pack(K, bufferptr::Ptr{T}) where {T}\n mᵣ, nᵣ = matmul_params(Val(T))\n mᵣW = mᵣ * pick_vector_width(T)\n Apack = default_zerobased_stridedpointer(bufferptr, (One(), mᵣW, mᵣW * K)) # mᵣW x K x cld(M, mᵣW)\n Apack\nend\nfunction packaloopmul!(\n C::AbstractStridedPointer{T},\n A::AbstractStridedPointer,\n B::AbstractStridedPointer,\n α, β, M, K, N\n) where {T}\n Ãₚ, buffer = alloc_a_pack(K, Val(T))\n GC.@preserve buffer begin\n Mᵣ, Nᵣ = matmul_params(Val(T))\n packamul!(C, Ãₚ, A, B, α, β, M, K, Nᵣ)\n ploopmul!(gesp(C, (Zero(), Nᵣ)), Ãₚ, gesp(B, (Zero(), Nᵣ)), α, β, M, K, N - Nᵣ)\n end\n nothing\nend\n\n@inline function inlineloopmul!(C, A, B, α, β, M, K, N)\n @turbo inline=true for m ∈ CloseOpen(M), n ∈ CloseOpen(N)\n Cₘₙ = zero(eltype(C))\n for k ∈ CloseOpen(K)\n Cₘₙ += A[m,k] * B[k,n]\n end\n C[m,n] = α * Cₘₙ + β * C[m,n]\n end\n C\nend\n\n\n", "meta": {"hexsha": "1b7568fc6d4e52fe051b26fa2d8732a307b044ba", "size": 6596, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/macrokernels.jl", "max_stars_repo_name": "ranocha/Octavian.jl", "max_stars_repo_head_hexsha": "9f56c5c3a86b2973b54882322d41d408774104b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 145, "max_stars_repo_stars_event_min_datetime": "2020-12-27T03:03:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T14:07:00.000Z", "max_issues_repo_path": "src/macrokernels.jl", "max_issues_repo_name": "ranocha/Octavian.jl", "max_issues_repo_head_hexsha": "9f56c5c3a86b2973b54882322d41d408774104b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 127, "max_issues_repo_issues_event_min_datetime": "2020-12-27T00:54:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T20:55:55.000Z", "max_forks_repo_path": "src/macrokernels.jl", "max_forks_repo_name": "ranocha/Octavian.jl", "max_forks_repo_head_hexsha": "9f56c5c3a86b2973b54882322d41d408774104b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-01-25T13:58:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T20:10:57.000Z", "avg_line_length": 42.5548387097, "max_line_length": 282, "alphanum_fraction": 0.5723165555, "num_tokens": 2458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24054145004180058}} {"text": "module Day15\n\n_inp = [3,1033,1008,1033,1,1032,1005,1032,31,1008,1033,2,1032,1005,1032,58,1008,1033,3,1032,1005,1032,81,1008,1033,4,1032,1005,1032,104,99,101,0,1034,1039,1001,1036,0,1041,1001,1035,-1,1040,1008,1038,0,1043,102,-1,1043,1032,1,1037,1032,1042,1105,1,124,1002,1034,1,1039,1001,1036,0,1041,1001,1035,1,1040,1008,1038,0,1043,1,1037,1038,1042,1106,0,124,1001,1034,-1,1039,1008,1036,0,1041,101,0,1035,1040,1001,1038,0,1043,1002,1037,1,1042,1105,1,124,1001,1034,1,1039,1008,1036,0,1041,1002,1035,1,1040,101,0,1038,1043,1001,1037,0,1042,1006,1039,217,1006,1040,217,1008,1039,40,1032,1005,1032,217,1008,1040,40,1032,1005,1032,217,1008,1039,33,1032,1006,1032,165,1008,1040,33,1032,1006,1032,165,1101,2,0,1044,1106,0,224,2,1041,1043,1032,1006,1032,179,1101,0,1,1044,1106,0,224,1,1041,1043,1032,1006,1032,217,1,1042,1043,1032,1001,1032,-1,1032,1002,1032,39,1032,1,1032,1039,1032,101,-1,1032,1032,101,252,1032,211,1007,0,68,1044,1106,0,224,1101,0,0,1044,1105,1,224,1006,1044,247,1002,1039,1,1034,102,1,1040,1035,1001,1041,0,1036,1002,1043,1,1038,1001,1042,0,1037,4,1044,1105,1,0,67,55,37,80,63,12,30,78,95,7,20,63,83,54,86,58,97,11,84,24,11,77,42,78,22,54,89,52,44,28,93,30,81,60,58,78,87,60,54,59,78,96,17,82,74,85,66,41,89,96,54,40,82,17,22,89,65,96,71,55,81,34,90,11,85,44,58,83,79,93,30,76,62,80,16,73,20,43,40,73,69,39,39,15,93,39,99,8,74,33,97,84,24,50,91,5,71,34,81,76,22,98,50,93,80,36,76,16,76,43,19,71,63,41,21,99,40,75,55,27,82,80,83,54,66,75,61,86,14,10,74,38,92,31,49,97,20,98,15,71,59,96,53,86,35,60,6,73,71,59,79,10,84,69,23,82,14,7,76,99,45,19,96,92,14,63,55,71,46,71,34,74,73,22,95,89,10,24,59,69,17,42,96,12,92,94,66,1,69,91,36,90,94,13,17,33,46,20,89,90,24,12,94,92,83,42,73,43,70,83,55,17,92,66,23,74,99,1,92,82,54,71,96,1,22,78,74,94,66,78,40,87,13,87,73,74,89,26,26,70,42,79,3,9,84,72,55,98,56,27,73,74,57,85,66,76,88,55,58,30,97,40,71,76,6,10,55,71,43,36,99,46,59,34,37,84,61,85,90,62,98,18,39,46,84,23,70,93,9,71,5,71,94,5,59,40,71,26,90,12,45,57,74,5,92,86,32,99,20,92,82,22,44,88,29,41,89,7,86,81,72,76,9,94,94,3,8,94,71,12,93,6,82,91,91,20,86,86,38,85,95,42,86,85,19,57,90,17,85,6,84,17,81,42,77,63,26,59,9,24,85,22,31,35,93,64,90,4,16,91,67,83,23,43,63,75,3,88,93,52,14,84,85,36,95,12,51,79,54,1,16,72,1,76,79,88,63,95,77,6,91,86,23,92,54,91,51,82,45,14,98,89,74,47,52,82,80,65,74,44,58,90,14,98,42,91,6,50,88,29,81,96,25,1,97,62,62,73,61,48,82,76,93,98,49,14,74,6,97,30,47,73,77,8,89,10,17,65,21,74,95,43,83,89,72,96,27,59,20,58,80,10,70,86,42,92,26,50,98,85,3,62,20,93,86,78,19,78,91,23,90,37,71,66,97,97,95,86,40,46,79,70,37,14,98,51,91,81,4,9,77,93,19,53,70,87,40,11,95,25,93,90,17,98,39,76,92,55,57,93,39,76,13,99,58,92,26,88,80,65,34,71,62,72,17,64,38,97,85,32,4,88,69,82,51,63,61,71,77,33,90,59,74,49,76,8,76,93,55,36,71,84,7,67,47,3,85,98,9,99,32,8,79,18,28,55,77,10,30,79,77,4,1,99,82,66,90,41,64,22,82,33,20,87,24,29,80,53,72,27,17,85,84,70,16,94,11,81,92,48,85,61,47,83,21,45,92,92,38,61,75,98,52,73,80,29,82,94,29,85,61,69,59,35,84,86,60,98,63,83,69,39,10,15,64,18,85,88,63,97,95,56,13,43,75,93,13,34,85,57,37,96,39,65,60,73,73,82,11,81,80,38,88,76,23,88,19,70,2,93,46,28,79,92,91,18,6,92,96,50,77,56,45,77,36,64,83,91,64,75,48,72,71,17,69,40,82,7,6,92,70,25,23,72,9,23,84,16,17,75,76,70,60,61,99,86,21,27,85,63,80,81,55,87,93,97,53,78,53,97,14,97,49,85,65,91,72,72,5,93,34,81,10,85,86,81,19,87,61,84,11,99,96,94,8,78,13,84,9,70,0,0,21,21,1,10,1,0,0,0,0,0,0]\n\ninp = Dict(zip(0:length(_inp) - 1, Ref.(_inp))) # convert to 0-based index\n\nnewref() = Ref(0)\n\nfunction simulate!(v, inc, outc)\n i = 0\n relbase = 0\n\n function getval(modes, idx)\n modes[idx] == 0 && return get!(newref, v, v[i + idx][])\n modes[idx] == 1 && return get(v, i + idx, 0)\n modes[idx] == 2 && return get!(newref, v, relbase + v[i + idx][])\n end\n\n while true\n opcode, modes = v[i][] % 100, digits(div(v[i][], 100), pad = 3)\n\n function rtype!(op)\n getval(modes, 3)[] = op(getval(modes, 1)[], getval(modes, 2)[])\n i += 4\n end\n\n jtype!(op) = i = op(getval(modes, 1)[], 0) ? getval(modes, 2)[] : i + 3\n\n function itype!(op)\n getval(modes, 3)[] = Int(op(getval(modes, 1)[], getval(modes, 2)[]))\n i += 4\n end\n\n opcode in 1:9 || return\n opcode == 1 && rtype!(+)\n opcode == 2 && rtype!(*)\n opcode == 5 && jtype!(!=)\n opcode == 6 && jtype!(==)\n opcode == 7 && itype!(<)\n opcode == 8 && itype!(==)\n\n if opcode == 3\n getval(modes, 1)[] = take!(inc)\n i += 2\n elseif opcode == 4\n put!(outc, getval(modes, 1)[])\n i += 2\n elseif opcode == 9\n relbase += getval(modes, 1)[]\n i += 2\n end\n end\nend\n\ndirs = Dict(1 => [0, 1], 2 => [0, -1], 3 => [-1, 0], 4 => [1, 0])\nrev = Dict(1 => 2, 2 => 1, 3 => 4, 4 => 3)\nfunction backtrack(positions, x, y, inc, outc, path, stop)\n for (k, v) in dirs\n _x, _y = (x, y) .+ v\n positions[_x, _y] == 3 || continue\n (_x ∉ 1:50 || _y ∉ 1:50) && continue\n put!(inc, k)\n\n res = take!(outc)\n positions[_x, _y] = res\n res == 0 || push!(path, (x, y))\n if res in 1:2\n res == stop && return true\n if backtrack(positions, _x, _y, inc, outc, path, stop)\n return true\n else\n put!(inc, rev[k])\n pop!(path)\n positions[x, y] == take!(outc) || @error 1\n end\n end\n end\n\n return false\nend\n\nfunction solvea(v)\n inc, outc = Channel(1), Channel(1)\n sizee = 50\n positions = fill(3, sizee, sizee)\n t = Threads.@spawn simulate!(v, inc, outc)\n\n start = (sizee ÷ 2, sizee ÷ 2)\n positions[start...] = 1 # walkway\n path = []\n backtrack(positions, sizee ÷ 2, sizee ÷ 2, inc, outc, path, 2)\n @info length(path)\n positions\nend\n\n\n\nfunction solveb(v)\n inc, outc = Channel(1), Channel(1)\n sizee = 50\n positions = fill(3, sizee, sizee)\n t = Threads.@spawn simulate!(v, inc, outc)\n\n start = [sizee ÷ 2, sizee ÷ 2]\n positions[start...] = 1 # walkway\n backtrack(positions, sizee ÷ 2, sizee ÷ 2, inc, outc, [], 4) # there is no 4\n sol = findfirst(==(2), positions) |> Tuple\n\n empty = Set(findall(==(1), positions))\n full = Set()\n push!(full, sol)\n\n ticks = 0\n while length(empty) > 0\n nextfull = copy(full)\n for f in full, v in values(dirs)\n if CartesianIndex((f .+ v)...) in empty\n pop!(empty, CartesianIndex((f .+ v)...))\n push!(nextfull, f .+ v)\n end\n end\n\n full = nextfull\n ticks += 1\n end\n\n ticks\nend\n\n end\n", "meta": {"hexsha": "38da1ee6e19c89ba37c3a724b646f87f49fbfb1a", "size": 6699, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "advent2019/day15.jl", "max_stars_repo_name": "AnAverageHuman/competitive", "max_stars_repo_head_hexsha": "4c4b9bdbe91fde1c52f731426f9a53bff97796e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "advent2019/day15.jl", "max_issues_repo_name": "AnAverageHuman/competitive", "max_issues_repo_head_hexsha": "4c4b9bdbe91fde1c52f731426f9a53bff97796e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "advent2019/day15.jl", "max_forks_repo_name": "AnAverageHuman/competitive", "max_forks_repo_head_hexsha": "4c4b9bdbe91fde1c52f731426f9a53bff97796e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.1374045802, "max_line_length": 3384, "alphanum_fraction": 0.5820271682, "num_tokens": 3387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24054144409323513}} {"text": "\"\"\"\n```\nforecast(m, system, z0; enforce_zlb = false, shocks = Matrix{S}(0,0))\n\nforecast(system, z0, shocks; enforce_zlb = false)\n```\n\n### Inputs\n\n- `m::AbstractModel`: model object. Only needed for the method in which `shocks`\n are not provided.\n- `system::System{S}`: state-space system matrices\n- `kal::Kalman{S}` or `z0::Vector{S}`: result of running the Kalman filter or\n state vector in the final historical period (aka initial forecast period)\n\nwhere `S<:AbstractFloat`.\n\n### Keyword Arguments\n\n- `cond_type::Symbol`: one of `:none`, `:semi`, or `:full`, used to determine\n how many periods to forecast ahead. If `cond_type in [:semi, :full]`, the\n forecast horizon is reduced by the number of periods of conditional\n data. Defaults to `:none`.\n- `enforce_zlb::Bool`: whether to enforce the zero lower bound. Defaults to\n `false`.\n- `shocks::Matrix{S}`: matrix of size `nshocks` x `shock_horizon` of shock\n innovations under which to forecast. If `shock_horizon > horizon`, the extra\n periods of shocks will be ignored; if `shock_horizon < horizon`, zeros will be\n filled in for the shocks hitting the remaining forecasted periods.\n- `draw_shocks::Bool`: if `isempty(shocks)`, indicates whether to draw shocks\n according to:\n\n 1. If `forecast_tdist_shocks(m)`, draw `horizons` many shocks from a\n `Distributions.TDist(forecast_tdist_df_val(m))`\n 2. Otherwise, draw `horizons` many shocks from a\n `DegenerateMvNormal(zeros(nshocks), sqrt(system[:QQ]))`\n\n or to set `shocks` to a `nshocks` x `horizon` matrix of zeros. Defaults to\n `false`. If `shocks` is provided as a keyword argument, this flag has no\n effect.\n\n### Outputs\n\n- `states::Matrix{S}`: matrix of size `nstates` x `horizon` of forecasted states\n- `obs::Matrix{S}`: matrix of size `nobs` x `horizon` of forecasted observables\n- `pseudo::Matrix{S}`: matrix of size `npseudo` x `horizon` of forecasted\n pseudo-observables\n- `shocks::Matrix{S}`: matrix of size `nshocks` x `horizon` of shock innovations\n\"\"\"\nfunction forecast{S<:AbstractFloat}(m::AbstractModel, system::System{S},\n z0::Vector{S}; cond_type::Symbol = :none, enforce_zlb::Bool = false,\n shocks::Matrix{S} = Matrix{S}(0, 0), draw_shocks::Bool = false)\n\n # Numbers of things\n nshocks = n_shocks_exogenous(m)\n horizon = forecast_horizons(m; cond_type = cond_type)\n\n if isempty(shocks)\n # Populate shocks matrix\n if draw_shocks\n μ = zeros(S, nshocks)\n σ = sqrt.(system[:QQ])\n dist = if forecast_tdist_shocks(m)\n # Use t-distributed shocks\n ν = forecast_tdist_df_val(m)\n DegenerateDiagMvTDist(μ, σ, ν)\n else\n # Use normally distributed shocks\n DegenerateMvNormal(μ, σ)\n end\n\n shocks = rand(dist, horizon)\n\n # Forecast without anticipated shocks\n if n_anticipated_shocks(m) > 0\n ind_ant1 = m.exogenous_shocks[:rm_shl1]\n ind_antn = m.exogenous_shocks[Symbol(\"rm_shl$(n_anticipated_shocks(m))\")]\n ant_shock_inds = ind_ant1:ind_antn\n shocks[ant_shock_inds, :] = 0\n end\n else\n shocks = zeros(S, nshocks, horizon)\n end\n else\n # Adjust size of shocks matrix, padding with zeros or cutting off\n # periods of shocks if necessary\n shock_horizon = size(shocks, 2)\n if shock_horizon <= horizon\n shocks0 = zeros(nshocks, horizon - shock_horizon)\n shocks = hcat(shocks, shocks0)\n else\n shocks = shocks[:, 1:horizon]\n end\n end\n\n # Populate shocks matrix under alternative policy, if\n # user has specified a function to do so\n alt_policy = alternative_policy(m)\n if alt_policy.solve != identity &&\n alt_policy.forecast_init != identity\n\n shocks, z0 = alt_policy.forecast_init(m, shocks, z0, cond_type = cond_type)\n end\n\n # Get variables necessary to enforce the zero lower bound in the forecast\n ind_r = m.observables[:obs_nominalrate]\n ind_r_sh = m.exogenous_shocks[:rm_sh]\n zlb_value = forecast_zlb_value(m)\n\n forecast(system, z0, shocks; enforce_zlb = enforce_zlb,\n ind_r = ind_r, ind_r_sh = ind_r_sh, zlb_value = zlb_value)\nend\n\nfunction forecast{S<:AbstractFloat}(system::System{S}, z0::Vector{S},\n shocks::Matrix{S}; enforce_zlb::Bool = false, ind_r::Int = -1,\n ind_r_sh::Int = -1, zlb_value::S = 0.13/4)\n\n # Unpack system\n T, R, C = system[:TTT], system[:RRR], system[:CCC]\n Q, Z, D = system[:QQ], system[:ZZ], system[:DD]\n Z_pseudo, D_pseudo = system[:ZZ_pseudo], system[:DD_pseudo]\n\n # Setup\n nshocks = size(R, 2)\n nstates = size(T, 2)\n nobs = size(Z, 1)\n npseudo = size(Z_pseudo, 1)\n horizon = size(shocks, 2)\n\n # Define our iteration function\n function iterate(z_t1, ϵ_t)\n z_t = C + T*z_t1 + R*ϵ_t\n\n # Change monetary policy shock to account for 0.13 interest rate bound\n if enforce_zlb\n interest_rate_forecast = getindex(D + Z*z_t, ind_r)\n if interest_rate_forecast < zlb_value\n # Solve for interest rate shock causing interest rate forecast to be exactly ZLB\n ϵ_t[ind_r_sh] = 0.\n z_t = C + T*z_t1 + R*ϵ_t\n ϵ_t[ind_r_sh] = getindex((zlb_value - D[ind_r] - Z[ind_r, :]'*z_t) / (Z[ind_r, :]' * R[:, ind_r_sh]), 1)\n\n # Forecast again with new shocks\n z_t = C + T*z_t1 + R*ϵ_t\n\n # Confirm procedure worked\n interest_rate_forecast = getindex(D + Z*z_t, ind_r)\n @assert interest_rate_forecast >= zlb_value - 0.01 \"interest_rate_forecast = $interest_rate_forecast must be >= zlb_value - 0.01 = $(zlb_value - 0.01)\"\n end\n end\n return z_t, ϵ_t\n end\n\n # Iterate state space forward\n states = zeros(S, nstates, horizon)\n states[:, 1], shocks[:, 1] = iterate(z0, shocks[:, 1])\n for t in 2:horizon\n states[:, t], shocks[:, t] = iterate(states[:, t-1], shocks[:, t])\n end\n\n # Apply measurement and pseudo-measurement equations\n obs = D .+ Z*states\n pseudo = D_pseudo .+ Z_pseudo * states\n\n # Return forecasts\n return states, obs, pseudo, shocks\nend\n", "meta": {"hexsha": "28da8876a234d72bcd980b09b6c487ce83476061", "size": 6293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/forecast/forecast.jl", "max_stars_repo_name": "wegamekinglc/DSGE.jl", "max_stars_repo_head_hexsha": "9681dcdd6c33fa39fcb8e9f67fd284015d071c27", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/forecast/forecast.jl", "max_issues_repo_name": "wegamekinglc/DSGE.jl", "max_issues_repo_head_hexsha": "9681dcdd6c33fa39fcb8e9f67fd284015d071c27", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/forecast/forecast.jl", "max_forks_repo_name": "wegamekinglc/DSGE.jl", "max_forks_repo_head_hexsha": "9681dcdd6c33fa39fcb8e9f67fd284015d071c27", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-18T17:27:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-18T17:27:27.000Z", "avg_line_length": 37.4583333333, "max_line_length": 167, "alphanum_fraction": 0.6332432862, "num_tokens": 1781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24054143814466963}} {"text": "module ActifMPCCmod\n\nimport Relaxation\nimport ParamSetmod\nimport NLPModels\n\n\"\"\"\nType MPCC_actif : problème MPCC pénalisé avec slack et ensemble des contraintes actives\n\nliste des constructeurs :\nMPCC_actif(nlp::NLPModels.AbstractNLPModel,r::Float64,s::Float64,t::Float64,nb_comp::Int64,paramset::ParamSetmod.ParamSet,direction::Function,linesearch::Function)\nMPCC_actif(nlp::NLPModels.AbstractNLPModel,r::Float64,s::Float64,t::Float64,w::Any,paramset::ParamSetmod.ParamSet,direction::Function,linesearch::Function)\n\nliste des méthodes :\nupdatew(ma::MPCC_actif)\nsetf(ma::MPCC_actif, f::Function, xj::Any)\nsetw(ma::MPCC_actif, w::Any)\nsetbeta(ma::MPCC_actif,b::Float64)\nsethess(ma::MPCC_actif,Hess::Array{Float64,2})\n\nliste des accesseurs :\nevalx(ma::MPCC_actif,x::Vector)\nevald(ma::MPCC_actif,d::Vector)\nredd(ma::MPCC_actif,d::Vector)\nobj(ma::MPCC_actif,x::Vector)\nExtddDirection(ma::ActifMPCCmod.MPCC_actif,dr::Vector,xp::Vector,step::Float64)\ngrad(ma::MPCC_actif,x::Vector)\ngrad(ma::MPCC_actif,x::Vector,gradf::Vector)\nhess(ma::MPCC_actif,x::Vector)\nhess(ma::MPCC_actif,x::Vector,H::Array{Float64,2})\n\nliste des fonctions :\nLSQComputationMultiplier(ma::MPCC_actif,gradpen::Vector,xj::Vector)\nRelaxationRule(ma::ActifMPCCmod.MPCC_actif,xj::Vector,lg::Vector,lh::Vector,lphi::Vector,wmax::Any)\nPasMaxComp(ma::MPCC_actif,x::Vector,d::Vector)\nAlphaChoix(alpha::Float64,alpha1::Float64,alpha2::Float64)\nAlphaChoix(alpha::Float64,alpha1::Float64,alpha2::Float64,alpha3::Float64,alpha4::Float64)\nPasMaxBound(ma::MPCC_actif,x::Vector,d::Vector) #TO DO\nPasMax(ma::MPCC_actif,x::Vector,d::Vector)\n\"\"\"\n\n#TO DO List :\n#Major :\n#- Changer les w en set ou en liste\n#- intégrer les contraintes de bornes sur x dans PasMax\n#Minor :\n#- copie de code dans PasMax\n#- Plutôt que de passer le point courant -> stocker en point initial de mpcc ?\n\ntype MPCC_actif\n nlp::NLPModels.AbstractNLPModel # en fait on demande juste une fonction objectif, point initial, contraintes de bornes\n r::Float64\n s::Float64\n t::Float64\n\n w::Array{Bool,2} #matrice à 2 colonnes et de longueur 2nb_comp -- sparse\n\n n::Int64 #dans le fond est optionnel si on a nb_comp\n nb_comp::Int64\n\n #ensembles d'indices :\n w1::Array{Int64,1} # ensemble des indices (entre 0 et nb_comp) où la contrainte yG>=-r est active\n w2::Array{Int64,1} # ensemble des indices (entre 0 et nb_comp) où la contrainte yH>=-r est active\n w3::Array{Int64,1} # ensemble des indices (entre 0 et nb_comp) où la contrainte yG<=s+t*theta(yH,r) est active\n w4::Array{Int64,1} # ensemble des indices (entre 0 et nb_comp) où la contrainte yH<=s+t*theta(yG,r) est active\n wcomp::Array{Int64,1} #ensemble des indices (entre 0 et nb_comp) où la contrainte Phi<=0 est active\n w13c::Array{Int64,1} #ensemble des indices où les variables yG sont libres\n w24c::Array{Int64,1} #ensemble des indices où les variables yH sont libres\n wc::Array{Int64,1} #ensemble des indices des contraintes où yG et yH sont libres\n wcc::Array{Int64,1} #ensemble des indices des contraintes où yG et yH sont fixés\n\n\n wnew::Array{Bool,2} #dernières contraintes ajoutés\n\n #paramètres pour le calcul de la direction de descente\n crho::Float64 #constant such that : ||c(x)||_2 \\approx crho*rho\n beta::Float64 #paramètre pour gradient conjugué\n Hess::Array{Float64,2} #inverse matrice hessienne approximée\n #Hd::Vector #produit inverse matrice hessienne et gradient (au lieu de la hessienne entière)\n\n paramset::ParamSetmod.ParamSet\n direction::Function #fonction qui calcul la direction de descente\n linesearch::Function #fonction qui calcul la recherche linéaire\nend\n\n\"\"\"\nConstructeur recommandé pour MPCC_actif\n\"\"\"\nfunction MPCC_actif(nlp::NLPModels.AbstractNLPModel,r::Float64,s::Float64,t::Float64,nb_comp::Int64,paramset::ParamSetmod.ParamSet,direction::Function,linesearch::Function)\n\n n=length(nlp.meta.x0)-2*nb_comp\n xk=nlp.meta.x0[1:n]\n ygk=nlp.meta.x0[n+1:n+nb_comp]\n yhk=nlp.meta.x0[n+nb_comp+1:n+2*nb_comp]\n\n w=zeros(Bool,2*nb_comp,2)\n\n for l=1:nb_comp\n if ygk[l]==nlp.meta.lvar[n+l]\n w[l,1]=true;\n elseif ygk[l]==Relaxation.psi(yhk[l],r,s,t)\n w[l+nb_comp,1]=true;\n end\n if yhk[l]==nlp.meta.lvar[n+l+nb_comp]\n w[l,2]=true;\n elseif yhk[l]==Relaxation.psi(ygk[l],r,s,t)\n w[l+nb_comp,2]=true;\n end\n end\n\n return MPCC_actif(nlp,r,s,t,w,paramset,direction,linesearch)\nend\n\nfunction MPCC_actif(nlp::NLPModels.AbstractNLPModel,r::Float64,s::Float64,t::Float64,w::Array{Bool,2},paramset::ParamSetmod.ParamSet,direction::Function,linesearch::Function)\n\n nb_comp=Int(size(w,1)/2)\n n=length(nlp.meta.x0)-2*nb_comp\n w1=find(w[1:nb_comp,1])\n w2=find(w[1:nb_comp,2])\n w3=find(w[nb_comp+1:2*nb_comp,1])\n w4=find(w[nb_comp+1:2*nb_comp,2])\n wcomp=find(w[nb_comp+1:2*nb_comp,1] .| w[nb_comp+1:2*nb_comp,2])\n w13c=find(.!w[1:nb_comp,1] .& .!w[nb_comp+1:2*nb_comp,1])\n w24c=find(.!w[1:nb_comp,2] .& .!w[nb_comp+1:2*nb_comp,2])\n wc=find(.!w[1:nb_comp,1] .& .!w[1:nb_comp,2] .& .!w[nb_comp+1:2*nb_comp,1] .& .!w[nb_comp+1:2*nb_comp,2])\n wcc=find((w[1:nb_comp,1] .| w[nb_comp+1:2*nb_comp,1]) .& (w[1:nb_comp,2] .| w[nb_comp+1:2*nb_comp,2]))\n\n wnew=zeros(Bool,0,0)\n\n crho=1.0\n beta=0.0\n Hess=eye(n+2*nb_comp)\n\n return MPCC_actif(nlp,r,s,t,w,n,nb_comp,w1,w2,w3,w4,wcomp,w13c,w24c,wc,wcc,wnew,crho,beta,Hess,paramset,direction,linesearch)\nend\n\n\"\"\"\nMethodes pour le MPCC_actif\n\"\"\"\n#Mise à jour des composantes liés à w\nfunction updatew(ma::MPCC_actif)\n\n ma.w1=find(ma.w[1:ma.nb_comp,1])\n ma.w2=find(ma.w[1:ma.nb_comp,2])\n ma.w3=find(ma.w[ma.nb_comp+1:2*ma.nb_comp,1])\n ma.w4=find(ma.w[ma.nb_comp+1:2*ma.nb_comp,2])\n ma.wcomp=find(ma.w[ma.nb_comp+1:2*ma.nb_comp,1] .| ma.w[ma.nb_comp+1:2*ma.nb_comp,2])\n ma.w13c=find(.!ma.w[1:ma.nb_comp,1] .& .!ma.w[ma.nb_comp+1:2*ma.nb_comp,1])\n ma.w24c=find(.!ma.w[1:ma.nb_comp,2] .& .!ma.w[ma.nb_comp+1:2*ma.nb_comp,2])\n ma.wc=find(.!ma.w[1:ma.nb_comp,1] .& .!ma.w[1:ma.nb_comp,2] .& .!ma.w[ma.nb_comp+1:2*ma.nb_comp,1] .& .!ma.w[ma.nb_comp+1:2*ma.nb_comp,2])\n ma.wcc=find((ma.w[1:ma.nb_comp,1] .| ma.w[ma.nb_comp+1:2*ma.nb_comp,1]) .& (ma.w[1:ma.nb_comp,2] .| ma.w[ma.nb_comp+1:2*ma.nb_comp,2]))\n return ma\nend\n\n#Mise à jour de w\nfunction setw(ma::MPCC_actif, w::Array{Bool,2})\n\n ma.wnew=w .& .!ma.w\n ma.w=w\n return updatew(ma)\nend\n\nfunction setbeta(ma::MPCC_actif,b::Float64)\n ma.beta=b\n return ma\nend\n\nfunction setcrho(ma::MPCC_actif,crho::Float64)\n ma.crho=crho\n return ma\nend\n\nfunction sethess(ma::MPCC_actif,Hess::Array{Float64,2})\n ma.Hess=Hess\n return ma\nend\n\n\"\"\"\nRenvoie le vecteur x=[x,yg,yh] au complet\n\"\"\"\nfunction evalx(ma::MPCC_actif,x::Vector)\n #construction du vecteur de taille n+2nb_comp que l'on évalue :\n xf=ma.s*ones(ma.n+2*ma.nb_comp)\n xf[1:ma.n]=x[1:ma.n]\n xf[ma.w13c+ma.n]=x[ma.n+1:ma.n+length(ma.w13c)]\n xf[ma.w24c+ma.n+ma.nb_comp]=x[ma.n+length(ma.w13c)+1:ma.n+length(ma.w13c)+length(ma.w24c)]\n\n #on regarde les variables yG fixées :\n xf[ma.w1+ma.n]=ma.nlp.meta.lvar[ma.w1+ma.n]\n xf[ma.w3+ma.n]=Relaxation.psi(xf[ma.w3+ma.n+ma.nb_comp],ma.r,ma.s,ma.t)\n #on regarde les variables yH fixées :\n xf[ma.w2+ma.n+ma.nb_comp]=ma.nlp.meta.lvar[ma.w2+ma.n+ma.nb_comp]\n xf[ma.w4+ma.n+ma.nb_comp]=Relaxation.psi(xf[ma.w4+ma.n],ma.r,ma.s,ma.t)\n\n return xf\nend\n\n\"\"\"\nRenvoie la direction d au complet (avec des 0 aux actifs)\n\"\"\"\nfunction evald(ma::MPCC_actif,d::Vector)\n df=zeros(ma.n+2*ma.nb_comp)\n df[1:ma.n]=d[1:ma.n]\n df[ma.w13c+ma.n]=d[ma.n+1:ma.n+length(ma.w13c)]\n df[ma.w24c+ma.nb_comp+ma.n]=d[ma.n+length(ma.w13c)+1:ma.n+length(ma.w13c)+length(ma.w24c)]\n return df\nend\n\n\"\"\"\nRenvoie la direction d réduite\n\"\"\"\nfunction redd(ma::MPCC_actif,d::Vector)\n\n df=zeros(ma.n+length(ma.w13c)+length(ma.w24c))\n df[1:ma.n]=d[1:ma.n]\n df[ma.n+1:ma.n+length(ma.w13c)]=d[ma.w13c+ma.n]\n df[ma.n+length(ma.w13c)+1:ma.n+length(ma.w13c)+length(ma.w24c)]=d[ma.w24c+ma.nb_comp+ma.n]\n\n return df\nend\n\nfunction redd(ma::MPCC_actif,d::Vector,w::Array{Int64,1})\n\n df=zeros(length(w))\n df[1:length(w)]=d[w]\n\n return df\nend\n\n\"\"\"\nEvalue la fonction objectif d'un MPCC actif : x\n\"\"\"\nfunction obj(ma::MPCC_actif,x::Vector)\n\n if length(x)==ma.n+2*ma.nb_comp\n return NLPModels.obj(ma.nlp,x)\n else\n return NLPModels.obj(ma.nlp,evalx(ma,x))\n end\n\nend\n\n\"\"\"\nCalcul la direction étendue à partir de la direction du sous-domaine\ncomplète une version étendue de la direction de descente :\ndr : la direction dans le sous-espace actif\nxp : le nouvel itéré\nstep : le pas utilisé pour calculé xp\n\nutilise la formule suivante :\nyG+=yG+alpha*dyG --> dyG=(yG+-yG)/alpha\n\"\"\"\nfunction ExtddDirection(ma::ActifMPCCmod.MPCC_actif,dr::Vector,xp::Vector,step::Float64)\n d=evald(ma,dr) #evald rempli les trous par des 0\n x=evalx(ma,xp)\n\n d[1:ma.n]=dr[1:ma.n]\n\n psip=Relaxation.psi(x[ma.n+1:ma.n+2*ma.nb_comp],ma.r,ma.s,ma.t)\n psi=Relaxation.psi(x[ma.n+1:ma.n+2*ma.nb_comp]-step*d[ma.n+1:ma.n+2*ma.nb_comp],ma.r,ma.s,ma.t)\n #d[ma.w1]=0 #yG fixé\n #d[ma.w2]=0 #yH fixé\n\n d[ma.n+ma.w3]=(psip[ma.w3+ma.nb_comp]-psi[ma.w3+ma.nb_comp])/step #yG fixé\n d[ma.n+ma.nb_comp+ma.w4]=(psip[ma.w4]-psi[ma.w4])/step #yH fixé\n #d[ma.n+ma.w13c]=dr[ma.n+ma.w13c] #yG est libre\n #d[ma.n+ma.nb_comp+ma.w24c]=dr[ma.n+ma.nb_comp+ma.w24c] #yG est libre\n\n return d\nend\n\n\"\"\"\nEvalue le gradient de la fonction objectif d'un MPCC actif\nx est le vecteur réduit\n\"\"\"\nfunction grad(ma::MPCC_actif,x::Vector)\n\n #on calcul xf le vecteur complet\n xf=evalx(ma,x)\n #construction du vecteur gradient de taille n+2nb_comp\n gradf=NLPModels.grad(ma.nlp,xf)\n\n return length(x)==ma.n+2*ma.nb_comp?gradf:grad(ma,x,gradf)\nend\n\nfunction grad(ma::MPCC_actif,x::Vector,gradf::Vector)\n\n #on calcul xf le vecteur complet\n xf=evalx(ma,x)\n #construction du vecteur gradient de taille n+2nb_comp\n #gradf=NLPModels.grad(ma.nlp,xf)\n\n gradg=Array{Float64}\n # Conditionnelles pour gérer le cas où w1 et w3 est vide\n #if isempty(ma.w1) && isempty(ma.w3)\n if isempty(ma.w4)\n gradg=zeros(length(ma.w13c))\n #elseif !isempty(ma.w13c) #certaines variables sont fixés\n elseif !isempty(ma.w4) #certaines variables sont fixés\n tmp=zeros(ma.nb_comp)\n #tmp[ma.w3]=Relaxation.dpsi(xf[ma.w3+ma.n+ma.nb_comp],ma.r,ma.s,ma.t).*gradf[ma.w3+ma.n]\n tmp[ma.w4]=Relaxation.dpsi(xf[ma.w4+ma.n],ma.r,ma.s,ma.t).*gradf[ma.w4+ma.nb_comp+ma.n]\n gradg=redd(ma,tmp,ma.w13c)\n else #ma.w13c est vide\n gradg=Float64[]\n end\n\n gradh=Array{Float64,1}\n #if isempty(ma.w2) && isempty(ma.w4)\n if isempty(ma.w3)\n gradh=zeros(length(ma.w24c))\n #elseif !isempty(ma.w24c)\n elseif !isempty(ma.w3)\n tmp=zeros(ma.nb_comp)\n #tmp[ma.w4]=Relaxation.dpsi(xf[ma.w4+ma.n],ma.r,ma.s,ma.t).*gradf[ma.w4+ma.nb_comp+ma.n]\n tmp[ma.w3]=Relaxation.dpsi(xf[ma.w3+ma.n+ma.nb_comp],ma.r,ma.s,ma.t).*gradf[ma.w3+ma.n]\n gradh=redd(ma,tmp,ma.w24c)\n else\n gradh=Float64[]\n end\n\n return vcat(gradf[1:ma.n],gradf[ma.w13c+ma.n]+gradg,gradf[ma.w24c+ma.nb_comp+ma.n]+gradh)\nend\n\n\"\"\"\nEvalue la matrice hessienne de la fonction objectif d'un MPCC actif\nx est le vecteur réduit\n\"\"\"\nfunction hess(ma::MPCC_actif,x::Vector)\n\n #on calcul xf le vecteur complet\n xf=evalx(ma,x)\n\n #construction de la hessienne de taille (n+2nb_comp)^2\n\n #H=NLPModels.hess(ma.nlp,xf) #renvoi la triangulaire inférieure tril(H,-1)'\n #H=H+tril(H,-1)'\n\n H=ma.nlp.H(xf)\n H=H+tril(H,-1)'\n\n if ma.nb_comp>0\n return hess(ma,x,H)\n else\n return H\n end\nend\n\n\"\"\"\nA partir de la hessienne complète (ou une approximation) : calcul la hessienne dans le sous-espace actif\n\"\"\"\nfunction hess(ma::MPCC_actif,x::Vector,H::Array{Float64,2})\n\n #on calcul xf le vecteur complet\n xf=evalx(ma,x)\n nred=length(x)\n nnb=ma.n+ma.nb_comp;nnbt=ma.n+2*ma.nb_comp;\n #construction du vecteur gradient de taille n+2nb_comp\n gradf=NLPModels.grad(ma.nlp,xf)\n\n#la hessienne des variables du sous-espace (nredxnred)\n Hred=vcat(hcat(H[1:ma.n,1:ma.n],H[1:ma.n,ma.n+ma.w13c],H[1:ma.n,nnb+ma.w24c]),\n hcat(H[ma.n+ma.w13c,1:ma.n],H[ma.n+ma.w13c,ma.n+ma.w13c],H[ma.n+ma.w13c,nnb+ma.w24c]),\n hcat(H[nnb+ma.w24c,1:ma.n],H[nnb+ma.w24c,ma.n+ma.w13c],H[nnb+ma.w24c,ma.n+ma.nb_comp+ma.w24c]))\n\n if isempty(ma.w4)\n hessg=sparse(zeros(length(ma.w13c),nred))\n else\n hessg=sparse(zeros(length(ma.w13c),nred))\n\n w4r=zeros(Int64,length(ma.w4))\n for i=1:length(ma.w4)\n w4r[i]=findfirst(x->x==ma.w4[i],ma.w13c)\n end\n hessg=diagm(Relaxation.ddpsi(xf[ma.w4+ma.n],ma.r,ma.s,ma.t).*gradf[ma.w4+ma.nb_comp+ma.n])\n hessg+=diagm(Relaxation.dpsi(xf[ma.w4+ma.n],ma.r,ma.s,ma.t))*H[ma.w4+ma.nb_comp+ma.n,ma.w4+ma.nb_comp+ma.n]\n\n Hred[ma.n+w4r,ma.n+w4r]+=hessg\n end\n\n if isempty(ma.w3)\n hessh=sparse(zeros(length(ma.w24c),nred))\n else\n hessh=sparse(zeros(length(ma.w24c),nred))\n\n w3r=zeros(Int64,length(ma.w3))\n for i=1:length(ma.w3)\n w3r[i]=findfirst(x->x==ma.w3[i],ma.w24c)\n end\n hessh=diagm(Relaxation.ddpsi(xf[ma.w3+ma.nb_comp+ma.n],ma.r,ma.s,ma.t).*gradf[ma.w3+ma.n])\n hessh+=diagm(Relaxation.dpsi(xf[ma.w3+ma.nb_comp+ma.n],ma.r,ma.s,ma.t))*H[ma.w3+ma.n,ma.w3+ma.n]\n\n Hred[ma.n+length(ma.w13c)+w3r,ma.n+length(ma.w13c)+w3r]+=hessh\n end\n\n return Hred\nend\n\n\"\"\"\nLSQComputationMultiplier(ma::MPCC_actif,x::Vector) :\nma MPCC_Actif\nxj in n+2nb_comp\ngradpen in n+2nb_comp\n\ncalcul la valeur des multiplicateurs de Lagrange pour la contrainte de complémentarité en utilisant moindre carré\n\"\"\"\nfunction LSQComputationMultiplier(ma::MPCC_actif,gradpen::Vector,xj::Vector)\n\n dg=Relaxation.dphi(xj[ma.n+1:ma.n+ma.nb_comp],xj[ma.n+ma.nb_comp+1:ma.n+2*ma.nb_comp],ma.r,ma.s,ma.t)\n gx=dg[1:ma.nb_comp];gy=dg[ma.nb_comp+1:2*ma.nb_comp]\n\n #matrices des contraintes actives : (lg,lh,lphi)'*A=b\n nw1=length(ma.w1)\n nw2=length(ma.w2)\n nwcomp=length(ma.wcomp)\n Dlg=-diagm(ones(nw1))\n Dlh=-diagm(ones(nw2))\n Dlphig=diagm(collect(gx)[ma.wcomp])\n Dlphih=diagm(collect(gy)[ma.wcomp])\n A=[hcat(Dlg,zeros(nw1,nw2+2*nwcomp));hcat(zeros(nw2,nw1),Dlh,zeros(nw2,2*nwcomp));hcat(zeros(nwcomp,nw1+nw2),Dlphig,Dlphih)] # nw1+nw2+nwcomp x nw1+nw2+2nwcomp\n #second membre\n b=-[gradpen[ma.w1+ma.n];gradpen[ma.wcomp+ma.n];gradpen[ma.w2+ma.n+ma.nb_comp];gradpen[ma.wcomp+ma.n+ma.nb_comp]] #nw1+nw2+2nwcomp\n #on calcule la solution par pseudo-inverse :\n l=pinv(A')*b\n\n lk=zeros(3*ma.nb_comp)\n lk[ma.w1]=l[1:nw1]\n lk[ma.nb_comp+ma.w2]=l[nw1+1:nw1+nw2]\n lk[2*ma.nb_comp+ma.wcomp]=l[nw1+nw2+1:nw1+nw2+nwcomp]\n \n return lk[1:ma.nb_comp],lk[ma.nb_comp+1:2*ma.nb_comp],lk[2*ma.nb_comp+1:3*ma.nb_comp]\nend\n\n\"\"\"\nDéfinit la règle de relaxation de l'ensemble des contraintes\nRelaxationRule(ma::ActifMPCCmod.MPCC_actif,xj::Vector,lg,lh,lphi,wmax)\nxj : de taille n+2nb_comp\n(lg,lh,phi) : valeur multiplicateurs\nwmax : ensemble des contraintes qui viennent d'être ajouté\n\noutput : MPCC_actif (avec les ensembles de contraintes actives mis à jour\n\"\"\"\nfunction RelaxationRule(ma::ActifMPCCmod.MPCC_actif,xj::Vector,lg::Vector,lh::Vector,lphi::Vector,wmax::Array{Bool,2})\n\n copy_wmax=copy(wmax)\n\n # Relaxation de l'ensemble d'activation : désactive toutes les contraintes négatives\n ma.w[find(x -> x<0,[lg;lphi;lh;lphi])]=zeros(Bool,length(find(x -> x<0,[lg;lphi;lh;lphi])))\n # Règle d'anti-cyclage : on enlève pas une contrainte qui vient d'être ajouté.\n ma.w[find(x->x==1.0,copy_wmax)]=ones(Bool,length(find(x->x==1.0,copy_wmax)))\n\n return ActifMPCCmod.updatew(ma)\nend\n\n\"\"\"\nCalcul le pas maximum que l'on peut prendre dans une direction d (par rapport à la contrainte de complémentarité relaxé)\nd : direction réduit\nxj : itéré réduit\n\noutput :\nalpha : le pas maximum\nw_save : l'ensemble des contraintes qui vont devenir actives si choisit alphamax\n\"\"\"\nfunction PasMaxComp(ma::MPCC_actif,x::Vector,d::Vector)\n\n #initialisation\n alpha=Inf #pas maximum que l'on peut prendre\n w_save=copy(ma.w) #double tableau des indices avec les contraintes activent en x+alpha*d\n\n #les indices où la première composante est libre\n for i in ma.w13c\n wr13=findfirst(x->x==i,ma.w13c) #l'indice relatif dans les variables libre\n iw13c=ma.n+wr13\n\n bloque=(i in ma.w2) && (i in ma.w4)\n if !(i in ma.w24c) && !bloque && d[iw13c]<0\n #on prend le plus petit entre x+alpha*dx>=-r et s+tTheta(x+alpha*dx-s)>=-r\n alpha11=(ma.nlp.meta.lvar[iw13c]-x[iw13c])/d[iw13c]\n alpha12=(Relaxation.invpsi(ma.nlp.meta.lvar[iw13c],ma.r,ma.s,ma.t)-x[iw13c])/d[iw13c]\n\n alphag=AlphaChoix(alpha,alpha11,alpha12)\n if alphag<=alpha\n alpha=alphag\n w_save=copy(ma.w)\n end\n\n #update of the active set\n if alpha11==alpha\n w_save[i,1]=true\n end\n if alpha12==alpha\n w_save[i+ma.nb_comp,2]=true\n w_save[i,2]=true\n end\n\n elseif bloque\n alpha=0.0\n end\n end\n\n #c'est un copie coller d'au dessus => exporter dans une fonction\n #les indices où la deuxième composante est libre\n for i in ma.w24c\n wr24=findfirst(x->x==i,ma.w24c) #l'indice relatif dans les variables libre\n iw24c=ma.n+length(ma.w13c)+wr24\n\n bloque=(i in ma.w1) && (i in ma.w3)\n if !(i in ma.w13c) && !bloque && d[iw24c]<0\n #on prend le plus petit entre y+alpha*dy>=-r et s+tTheta(y+alpha*dy-s)>=-r\n alpha21=(ma.nlp.meta.lvar[iw24c]-x[iw24c])/d[iw24c]\n alpha22=(Relaxation.invpsi(ma.nlp.meta.lvar[iw24c],ma.r,ma.s,ma.t)-x[iw24c])/d[iw24c]\n\n alphah=AlphaChoix(alpha,alpha21,alpha22)\n if alphah<=alpha\n alpha=alphah\n w_save=copy(ma.w)\n end\n\n #on met à jour les contraintes\n if alpha21==alpha\n w_save[i,2]=true\n end\n if alpha22==alpha\n w_save[i+ma.nb_comp,1]=true\n w_save[i,1]=true\n end\n elseif bloque\n alpha=0.0\n end\n end\n\n #enfin les indices où les deux sont libres\n for i in ma.wc\n #yG-psi(yH)=0 ou yH-psi(yG)=0\n wr1=findfirst(x->x==i,ma.w13c) #l'indice relatif dans les variables libre\n wr2=findfirst(x->x==i,ma.w24c) #l'indice relatif dans les variables libre\n iwr1=wr1+ma.n;iwr2=wr2+length(ma.w13c)+ma.n;\n\n #alphac=Relaxation.AlphaThetaMax(x[i+ma.n],d[i+ma.n],x[i+length(ma.w13c)+ma.n],d[i+length(ma.w13c)+ma.n],ma.r,ma.s,ma.t)\n alphac=Relaxation.AlphaThetaMax(x[iwr1],d[iwr1],x[iwr2],d[iwr2],ma.r,ma.s,ma.t)\n #yG-tb=0\n #alphac11=d[i+ma.n]<0 ? (ma.nlp.meta.lvar[ma.n+i]-x[i+ma.n])/d[i+ma.n] : Inf\n alphac11=d[iwr1]<0 ? (ma.nlp.meta.lvar[iwr1]-x[iwr1])/d[iwr1] : Inf\n #yH-tb=0\n #alphac21=d[i+length(ma.w13c)+ma.n]<0 ? (ma.nlp.meta.lvar[ma.n+length(ma.w13c)+i]-x[i+length(ma.w13c)+ma.n])/d[i+length(ma.w13c)+ma.n] : Inf \n alphac21=d[iwr2]<0 ? (ma.nlp.meta.lvar[iwr2]-x[iwr2])/d[iwr2] : Inf \n\n alphagh=AlphaChoix(alpha,alphac[1],alphac[2],alphac11,alphac21)\n\n if alphagh<=alpha\n alpha=alphagh\n w_save=copy(ma.w)\n end\n\n if alphac[1]==alpha\n w_save[i+ma.nb_comp,1]=true\n end\n if alphac[2]==alpha\n w_save[i+ma.nb_comp,2]=true\n end\n if alphac11==alpha\n w_save[i,1]=true\n end\n if alphac21==alpha\n w_save[i,2]=true\n end\n\n end #fin boucle for ma.wc\n\n return alpha,w_save,Array(w_save .& .!ma.w)\nend\n\n\"\"\"\nMet à jour alpha si :\n1) il est plus petit\n2) il est non-nul\n\"\"\"\nfunction AlphaChoix(alpha::Float64,alpha1::Float64,alpha2::Float64)\n return AlphaChoix(alpha,alpha1,alpha2,0.0,0.0)\nend\n\nfunction AlphaChoix(alpha::Float64,alpha1::Float64,alpha2::Float64,alpha3::Float64,alpha4::Float64)\n prec=eps(Float64)\n a=alpha1,alpha2,alpha3,alpha4\n a=a[find(x->x>=prec,collect(a))]\n if isempty(a)\n a=max(alpha1,alpha2,alpha3,alpha4)\n end\n\n return min(minimum(a),alpha)\nend\n\n\"\"\"\nCalcul le pas maximum que l'on peut prendre dans une direction d par rapport aux contraintes de bornes sur x.\nd : direction réduit\nxj : itéré réduit\n\noutput :\nalpha : le pas maximum\nw_save : l'ensemble des contraintes qui vont devenir actives si choisit alphamax\n\"\"\"\nfunction PasMaxBound(ma::MPCC_actif,x::Vector,d::Vector)\n if max(l-x)>0 || max(x-u)>0\n println(\"Error PasMaxBound: infeasible x\")\n end\n #ma.nlp.meta.lvar[1:ma.n]\n #ma.nlp.meta.uvar[1:ma.n]\n return #TO DO : nécessite d'ajouter les x dans l'ensemble des contraintes actives\nend\n\n\"\"\"\nCalcul le pas maximum que l'on peut prendre dans une direction d\nd : direction réduit\nxj : itéré réduit\n\noutput :\nalpha : le pas maximum\nw_save : l'ensemble des contraintes qui vont devenir actives si choisit alphamax\n\"\"\"\nfunction PasMax(ma::MPCC_actif,x::Vector,d::Vector)\n\n if ma.nb_comp>0\n #on récupère les infos sur la contrainte de complémentarité\n alpha,w_save,w_new=PasMaxComp(ma,x,d)\n else\n alpha=Inf;w_save=zeros(Bool,0,0);w_new=ma.w;\n end\n #alpha,w_save,w_new=PasMaxBound(ma,x,d)\n \n if alpha<0.0\n println(\"PasMax error: pas maximum négatif.\")\n return\n end\n\n return alpha,w_save,w_new\nend\n\n#end of module\nend\n", "meta": {"hexsha": "cadf4c5fbcceec07e7de808dddcf92966800a94e", "size": 20102, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "old/ALAS/ActifMPCCmod.jl", "max_stars_repo_name": "tmigot/MPCCsolver.jl", "max_stars_repo_head_hexsha": "31b44f12c9b1317f2bf8356aa75b9aba770a08fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old/ALAS/ActifMPCCmod.jl", "max_issues_repo_name": "tmigot/MPCCsolver.jl", "max_issues_repo_head_hexsha": "31b44f12c9b1317f2bf8356aa75b9aba770a08fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/ALAS/ActifMPCCmod.jl", "max_forks_repo_name": "tmigot/MPCCsolver.jl", "max_forks_repo_head_hexsha": "31b44f12c9b1317f2bf8356aa75b9aba770a08fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.409375, "max_line_length": 174, "alphanum_fraction": 0.7087354492, "num_tokens": 7818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.24037159216125226}} {"text": "du[1]=(-4).*(2+P1.^2+(-2).*2.^(1/2).*P2+P2.^2+2.*P1.*((-1).*2.^(1/2)+P2) +(Q1+(-1).*Q2).^2).^(-2).*(2+P1.^2+2.*2.^(1/2).*P2+P2.^2+2.*P1.*( 2.^(1/2)+P2)+(Q1+(-1).*Q2).^2).^(-2).*(P2.^2+Q2.^2).*(2+P1.^2+2.* P1.*(2.^(1/2)+(-1).*P2)+(-2).*2.^(1/2).*P2+P2.^2+(Q1+Q2).^2).^(-2) .*(2+P1.^2+2.*2.^(1/2).*P2+P2.^2+(-2).*P1.*(2.^(1/2)+P2)+(Q1+Q2) .^2).^(-2).*((P1.^2+Q1.^2).*(2+(-2).*2.^(1/2).*(P1+P2)+(P1+P2).^2+ (Q1+(-1).*Q2).^2).^(-1).*(2+2.*2.^(1/2).*(P1+P2)+(P1+P2).^2+(Q1+( -1).*Q2).^2).^(-1).*(P2.^2+Q2.^2).*(2+2.*2.^(1/2).*(P1+(-1).*P2)+( P1+(-1).*P2).^2+(Q1+Q2).^2).^(-1).*(2+(P1+(-1).*P2).^2+2.*2.^(1/2) .*((-1).*P1+P2)+(Q1+Q2).^2).^(-1)).^(-1/2).*(3.*P1.^9+24.*P1.^6.* P2.*Q1.*Q2+4.*P1.^7.*((-4)+(-2).*P2.^2+3.*Q1.^2+2.*Q2.^2)+8.* P1.^4.*P2.*Q1.*Q2.*(4+(-2).*P2.^2+7.*Q1.^2+2.*Q2.^2)+4.*P1.^3.* Q1.^2.*(12+3.*P2.^4+3.*Q1.^4+(-4).*Q2.^2+3.*Q2.^4+2.*Q1.^2.*((-2)+ Q2.^2)+(-2).*P2.^2.*((-2)+Q1.^2+Q2.^2))+8.*P2.*Q1.^3.*Q2.*(P2.^4+( Q1.^2+(-1).*Q2.^2).^2+2.*P2.^2.*(2+Q1.^2+Q2.^2)+(-4).*(3+Q1.^2+ Q2.^2))+2.*P1.^5.*(12+3.*P2.^4+9.*Q1.^4+(-4).*Q2.^2+3.*Q2.^4+8.* Q1.^2.*((-2)+Q2.^2)+(-2).*P2.^2.*((-2)+4.*Q1.^2+Q2.^2))+(-8).* P1.^2.*P2.*Q1.*Q2.*(P2.^4+(-5).*Q1.^4+Q2.^4+(-8).*Q1.^2.*(2+Q2.^2) +(-4).*(3+Q2.^2)+2.*P2.^2.*(2+4.*Q1.^2+Q2.^2))+P1.*((-1).*P2.^8+ 3.*Q1.^8+8.*Q1.^2.*((-2)+Q2.^2).*(2+Q2.^2).^2+(-1).*(2+Q2.^2).^4+( -4).*P2.^6.*((-2)+2.*Q1.^2+Q2.^2)+(-2).*Q1.^4.*(20+36.*Q2.^2+5.* Q2.^4)+(-2).*P2.^4.*(12+5.*Q1.^4+(-4).*Q2.^2+3.*Q2.^4+4.*Q1.^2.*(( -2)+Q2.^2))+4.*P2.^2.*((-1).*((-2)+Q2.^2).*(2+Q2.^2).^2+Q1.^4.*( 18+23.*Q2.^2)+2.*Q1.^2.*(4+20.*Q2.^2+Q2.^4))));\ndu[2]=4.*(P1.^2+Q1.^2).*(2+P1.^2+(-2).*2.^(1/2).*P2+P2.^2+2.*P1.*((-1).* 2.^(1/2)+P2)+(Q1+(-1).*Q2).^2).^(-2).*(2+P1.^2+2.*2.^(1/2).*P2+ P2.^2+2.*P1.*(2.^(1/2)+P2)+(Q1+(-1).*Q2).^2).^(-2).*(2+P1.^2+2.* P1.*(2.^(1/2)+(-1).*P2)+(-2).*2.^(1/2).*P2+P2.^2+(Q1+Q2).^2).^(-2) .*(2+P1.^2+2.*2.^(1/2).*P2+P2.^2+(-2).*P1.*(2.^(1/2)+P2)+(Q1+Q2) .^2).^(-2).*((P1.^2+Q1.^2).*(2+(-2).*2.^(1/2).*(P1+P2)+(P1+P2).^2+ (Q1+(-1).*Q2).^2).^(-1).*(2+2.*2.^(1/2).*(P1+P2)+(P1+P2).^2+(Q1+( -1).*Q2).^2).^(-1).*(P2.^2+Q2.^2).*(2+2.*2.^(1/2).*(P1+(-1).*P2)+( P1+(-1).*P2).^2+(Q1+Q2).^2).^(-1).*(2+(P1+(-1).*P2).^2+2.*2.^(1/2) .*((-1).*P1+P2)+(Q1+Q2).^2).^(-1)).^(-1/2).*((-3).*P2.^9+(-24).* P1.*P2.^6.*Q1.*Q2+8.*P1.*P2.^4.*Q1.*Q2.*((-4)+2.*P1.^2+(-2).* Q1.^2+(-7).*Q2.^2)+4.*P2.^7.*(4+2.*P1.^2+(-2).*Q1.^2+(-3).*Q2.^2)+ P2.*((P1.^4+2.*P1.^2.*((-2)+Q1.^2)+(2+Q1.^2).^2).^2+8.*(P1.^6+ P1.^4.*((-2)+Q1.^2)+(-1).*((-2)+Q1.^2).*(2+Q1.^2).^2+(-1).*P1.^2.* (4+20.*Q1.^2+Q1.^4)).*Q2.^2+2.*(20+5.*P1.^4+36.*Q1.^2+5.*Q1.^4+(-2).*P1.^2.*(18+23.*Q1.^2)).*Q2.^4+(-3).*Q2.^8)+(-4).*P2.^3.* Q2.^2.*(12+3.*P1.^4+(-4).*Q1.^2+3.*Q1.^4+2.*((-2)+Q1.^2).*Q2.^2+ 3.*Q2.^4+(-2).*P1.^2.*((-2)+Q1.^2+Q2.^2))+(-8).*P1.*Q1.*Q2.^3.*( P1.^4+(Q1.^2+(-1).*Q2.^2).^2+2.*P1.^2.*(2+Q1.^2+Q2.^2)+(-4).*(3+ Q1.^2+Q2.^2))+(-2).*P2.^5.*(12+3.*P1.^4+(-4).*Q1.^2+3.*Q1.^4+8.*(( -2)+Q1.^2).*Q2.^2+9.*Q2.^4+(-2).*P1.^2.*((-2)+Q1.^2+4.*Q2.^2))+8.* P1.*P2.^2.*Q1.*Q2.*((-12)+P1.^4+(-4).*Q1.^2+Q1.^4+(-8).*(2+Q1.^2) .*Q2.^2+(-5).*Q2.^4+2.*P1.^2.*(2+Q1.^2+4.*Q2.^2)));\ndu[3]=4.*(2+P1.^2+(-2).*2.^(1/2).*P2+P2.^2+2.*P1.*((-1).*2.^(1/2)+P2)+(Q1+(-1).*Q2).^2).^(-2).*(2+P1.^2+2.*2.^(1/2).*P2+P2.^2+2.*P1.*( 2.^(1/2)+P2)+(Q1+(-1).*Q2).^2).^(-2).*(P2.^2+Q2.^2).*(2+P1.^2+2.* P1.*(2.^(1/2)+(-1).*P2)+(-2).*2.^(1/2).*P2+P2.^2+(Q1+Q2).^2).^(-2) .*(2+P1.^2+2.*2.^(1/2).*P2+P2.^2+(-2).*P1.*(2.^(1/2)+P2)+(Q1+Q2) .^2).^(-2).*((P1.^2+Q1.^2).*(2+(-2).*2.^(1/2).*(P1+P2)+(P1+P2).^2+(Q1+(-1).*Q2).^2).^(-1).*(2+2.*2.^(1/2).*(P1+P2)+(P1+P2).^2+(Q1+( -1).*Q2).^2).^(-1).*(P2.^2+Q2.^2).*(2+2.*2.^(1/2).*(P1+(-1).*P2)+(P1+(-1).*P2).^2+(Q1+Q2).^2).^(-1).*(2+(P1+(-1).*P2).^2+2.*2.^(1/2).*((-1).*P1+P2)+(Q1+Q2).^2).^(-1)).^(-1/2).*(3.*Q1.^9+24.*P1.*P2.*Q1.^6.*Q2+4.*Q1.^7.*(4+3.*P1.^2+2.*P2.^2+(-2).*Q2.^2)+8.*P1.*P2.* Q1.^4.*Q2.*((-4)+7.*P1.^2+2.*P2.^2+(-2).*Q2.^2)+4.*P1.^2.*Q1.^3.*(12+3.*P1.^4+4.*P2.^2+3.*P2.^4+(-2).*(2+P2.^2).*Q2.^2+3.*Q2.^4+2.*P1.^2.*(2+P2.^2+(-1).*Q2.^2))+2.*Q1.^5.*(12+9.*P1.^4+4.*P2.^2+3.*P2.^4+(-2).*(2+P2.^2).*Q2.^2+3.*Q2.^4+8.*P1.^2.*(2+P2.^2+(-1).* Q2.^2))+8.*P1.*P2.*Q1.^2.*Q2.*(5.*P1.^4+8.*P1.^2.*((-2)+P2.^2+(-1) .*Q2.^2)+4.*(3+(-1).*P2.^2+Q2.^2)+(-1).*(P2.^2+Q2.^2).^2)+8.*P1.^3.*P2.*Q2.*(P1.^4+4.*((-3)+P2.^2+(-1).*Q2.^2)+2.*P1.^2.*(2+( -1).*P2.^2+Q2.^2)+(P2.^2+Q2.^2).^2)+Q1.*(3.*P1.^8+(-1).*(P2.^4+2.* P2.^2.*((-2)+Q2.^2)+(2+Q2.^2).^2).^2+(-2).*P1.^4.*(20+5.*P2.^4+ 36.*Q2.^2+5.*Q2.^4+(-2).*P2.^2.*(18+23.*Q2.^2))+8.*P1.^2.*(P2.^6+ P2.^4.*((-2)+Q2.^2)+(-1).*((-2)+Q2.^2).*(2+Q2.^2).^2+(-1).*P2.^2.*(4+20.*Q2.^2+Q2.^4))));\ndu[4]=(-4).*(P1.^2+Q1.^2).*(2+P1.^2+(-2).*2.^(1/2).*P2+P2.^2+2.*P1.*((-1).*2.^(1/2)+P2)+(Q1+(-1).*Q2).^2).^(-2).*(2+P1.^2+2.*2.^(1/2).*P2+P2.^2+2.*P1.*(2.^(1/2)+P2)+(Q1+(-1).*Q2).^2).^(-2).*((-8).*P1.*P2.^3.*Q1.*(P1.^4+4.*((-3)+P2.^2+(-1).*Q1.^2)+2.*P1.^2.*(2+(-1).*P2.^2+Q1.^2)+(P2.^2+Q1.^2).^2)+(P1.^8+(-3).*P2.^8+8.*P2.^2.*((-2)+Q1.^2).*(2+Q1.^2).^2+(2+Q1.^2).^4+4.*P1.^6.*((-2)+(-2).*P2.^2+Q1.^2)+2.*P1.^4.*(12+8.*P2.^2+5.*P2.^4+(-4).*(1+P2.^2).*Q1.^2+3.*Q1.^4)+2.*P2.^4.*(20+36.*Q1.^2+5.*Q1.^4)+4.*P1.^2.*(((-2)+Q1.^2).*(2+Q1.^2).^2+(-1).*P2.^4.*(18+23.*Q1.^2)+2.*P2.^2.*(4+20.*Q1.^2+Q1.^4))).*Q2+8.*P1.*P2.*Q1.*(P1.^4+(-5).*P2.^4+Q1.^4+8.*P2.^2.*(2+Q1.^2)+(-4).*(3+Q1.^2)+2.*P1.^2.*(2+(-4).*P2.^2+Q1.^2)).*Q2.^2+( -4).*P2.^2.*(12+3.*P1.^4+4.*P2.^2+3.*P2.^4+(-2).*(2+P2.^2).*Q1.^2+3.*Q1.^4+2.*P1.^2.*(2+P2.^2+(-1).*Q1.^2)).*Q2.^3+(-8).*P1.*P2.* Q1.*(2.*P1.^2+7.*P2.^2+(-2).*(2+Q1.^2)).*Q2.^4+(-2).*(12+3.*P1.^4+ 9.*P2.^4+(-4).*Q1.^2+3.*Q1.^4+P1.^2.*(4+8.*P2.^2+(-2).*Q1.^2)+(-8) .*P2.^2.*((-2)+Q1.^2)).*Q2.^5+(-24).*P1.*P2.*Q1.*Q2.^6+(-4).*(4+ 2.*P1.^2+3.*P2.^2+(-2).*Q1.^2).*Q2.^7+(-3).*Q2.^9).*(2+P1.^2+2.* P1.*(2.^(1/2)+(-1).*P2)+(-2).*2.^(1/2).*P2+P2.^2+(Q1+Q2).^2).^(-2) .*(2+P1.^2+2.*2.^(1/2).*P2+P2.^2+(-2).*P1.*(2.^(1/2)+P2)+(Q1+Q2) .^2).^(-2).*((P1.^2+Q1.^2).*(2+(-2).*2.^(1/2).*(P1+P2)+(P1+P2).^2+ (Q1+(-1).*Q2).^2).^(-1).*(2+2.*2.^(1/2).*(P1+P2)+(P1+P2).^2+(Q1+(-1).*Q2).^2).^(-1).*(P2.^2+Q2.^2).*(2+2.*2.^(1/2).*(P1+(-1).*P2)+( P1+(-1).*P2).^2+(Q1+Q2).^2).^(-1).*(2+(P1+(-1).*P2).^2+2.*2.^(1/2) .*((-1).*P1+P2)+(Q1+Q2).^2).^(-1)).^(-1/2);\n", "meta": {"hexsha": "9a585ce486e66006a479cbca55878138b7033e38", "size": 6163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a.jl", "max_stars_repo_name": "bmb29/Leap_Frog_Code", "max_stars_repo_head_hexsha": "6617b763f7311e6465f9c37901e010cedceb3242", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "a.jl", "max_issues_repo_name": "bmb29/Leap_Frog_Code", "max_issues_repo_head_hexsha": "6617b763f7311e6465f9c37901e010cedceb3242", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a.jl", "max_forks_repo_name": "bmb29/Leap_Frog_Code", "max_forks_repo_head_hexsha": "6617b763f7311e6465f9c37901e010cedceb3242", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 1232.6, "max_line_length": 1605, "alphanum_fraction": 0.3576180432, "num_tokens": 4180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.24029583388211437}} {"text": "function write_nl_file(f::IO, m::AmplNLMathProgModel)\n write_nl_header(f, m)\n\n if m.ncon > 0\n write_nl_c_blocks(f, m)\n end\n\n if has_objective(m)\n write_nl_o_block(f, m)\n end\n\n if m.ncon > 0\n write_nl_d_block(f, m)\n end\n\n write_nl_x_block(f, m)\n\n if m.ncon > 0\n write_nl_r_block(f, m)\n end\n\n write_nl_b_block(f, m)\n\n if m.ncon > 0\n write_nl_k_block(f, m)\n write_nl_j_blocks(f, m)\n end\n\n if has_objective(m)\n write_nl_g_block(f, m)\n end\nend\n\nfunction has_objective(m::AmplNLMathProgModel)\n return !isempty(m.lin_obj) || (isa(m.obj, Expr))\nend\n\nfunction write_nl_header(f, m::AmplNLMathProgModel)\n # Line 1: Always the same\n println(f, \"g3 1 1 0\")\n # Line 2: vars, constraints, objectives, ranges, eqns, logical constraints\n n_ranges = sum(m.r_codes .== 0)\n n_eqns = sum(m.r_codes .== 4)\n nobj = has_objective(m) ? 1 : 0\n println(f, \" $(m.nvar) $(m.ncon) $nobj $n_ranges $n_eqns 0\")\n # Line 3: nonlinear constraints, objectives\n nlc = sum(m.conlinearities .== :Nonlin)\n nlo = m.objlinearity == :Nonlin ? 1 : 0\n println(f, \" $nlc $nlo\")\n # Line 4: network constraints: nonlinear, linear\n println(f, \" 0 0\")\n # Line 5: nonlinear vars in constraints, objectives, both\n nonlinear_obj = m.varlinearities_obj .== :Nonlin\n nonlinear_con = m.varlinearities_con .== :Nonlin\n nonlinear = (nonlinear_con + nonlinear_obj) .> 0\n nonlinear_both = (nonlinear_con + nonlinear_obj) .> 1\n nlvc = sum(nonlinear_con .> 0)\n nlvo = sum(nonlinear_obj .> 0)\n nlvb = sum(nonlinear_both)\n println(f, \" $nlvc $nlvo $nlvb\")\n # Line 6: linear network variables; functions; arith, flags\n println(f, \" 0 0 0 1\") # flags set to 1 to get suffixes in .sol file\n # Line 7: discrete variables: binary, integer, nonlinear (b,c,o)\n binary = m.vartypes .== :Bin\n integer = m.vartypes .== :Int\n discrete = binary + integer .> 0\n # Julia 0.6 syntax\n nbv = sum(binary + .!nonlinear .> 1)\n niv = sum(integer + .!nonlinear .> 1)\n nlvbi = sum(nonlinear_both + discrete .> 1)\n nlvci = sum(nonlinear_con - nonlinear_obj + discrete .> 1)\n nlvoi = sum(nonlinear_obj - nonlinear_con + discrete .> 1)\n println(f, \" $nbv $niv $nlvbi $nlvci $nlvoi\")\n # Line 8: nonzeros in Jacobian, gradients\n nzc = sum(m.j_counts)\n nzo = length(m.lin_obj)\n println(f, \" $nzc $nzo\")\n # Line 9: max name lengths: constraints, variables\n println(f, \" 0 0\")\n # Line 10: common exprs: b,c,o,c1,o1\n println(f, \" 0 0 0 0 0\")\nend\n\n# Nonlinear constraint trees\nfunction write_nl_c_blocks(f, m::AmplNLMathProgModel)\n for index in 0:(m.ncon - 1)\n i = m.c_index_map_rev[index]\n println(f, \"C$index\")\n write_nl_expr(f, m, m.constrs[i])\n end\nend\n\n# Nonlinear objective tree\nfunction write_nl_o_block(f, m::AmplNLMathProgModel)\n println(f, string(\"O0 \", sense_to_nl[m.sense]))\n write_nl_expr(f, m, m.obj)\nend\n\n# Initial dual guesses - unused\nfunction write_nl_d_block(f, m::AmplNLMathProgModel)\n println(f, \"d$(m.ncon)\")\n for index in 0:(m.ncon - 1)\n i = m.c_index_map_rev[index]\n println(f, \"$index 0\")\n end\nend\n\n# Initial primal guesses\nfunction write_nl_x_block(f, m::AmplNLMathProgModel)\n println(f, \"x$(m.nvar)\")\n for index in 0:(m.nvar - 1)\n i = m.v_index_map_rev[index]\n println(f, \"$index $(m.x_0[i])\")\n end\nend\n\n# Constraint bounds\nfunction write_nl_r_block(f, m::AmplNLMathProgModel)\n println(f, \"r\")\n for index in 0:(m.ncon - 1)\n i = m.c_index_map_rev[index]\n lower = m.g_l[i]\n upper = m.g_u[i]\n rel = m.r_codes[i]\n if rel == 0\n println(f, \"$rel $lower $upper\")\n elseif rel == 1\n println(f, \"$rel $upper\")\n elseif rel == 2\n println(f, \"$rel $lower\")\n elseif rel == 3\n println(f, \"$rel\")\n elseif rel == 4\n println(f, \"$rel $lower\")\n end\n end\nend\n\n# Variable bounds\nfunction write_nl_b_block(f, m::AmplNLMathProgModel)\n println(f, \"b\")\n for index in 0:(m.nvar - 1)\n i = m.v_index_map_rev[index]\n lower = m.x_l[i]\n upper = m.x_u[i]\n if lower == -Inf\n if upper == Inf\n println(f, \"3\")\n else\n println(f, \"1 $upper\")\n end\n else\n if lower == upper\n println(f, \"4 $lower\")\n elseif upper == Inf\n println(f, \"2 $lower\")\n else\n println(f, \"0 $lower $upper\")\n end\n end\n end\nend\n\n# Jacobian counts\nfunction write_nl_k_block(f, m::AmplNLMathProgModel)\n println(f, \"k$(m.nvar - 1)\")\n total = 0\n for index = 0:(m.nvar - 2)\n i = m.v_index_map_rev[index]\n total += m.j_counts[i]\n println(f, total)\n end\nend\n\n# Linear constraint expressions\nfunction write_nl_j_blocks(f, m::AmplNLMathProgModel)\n for index in 0:(m.ncon - 1)\n i = m.c_index_map_rev[index]\n num_vars = length(m.lin_constrs[i])\n # Only print linear blocks with vars, .nl file is malformed otherwise\n if num_vars > 0\n println(f, \"J$index $num_vars\")\n\n # We need to output .nl index and constraint coeff, ordered by .nl\n # index. `lin_constrs` contains our variable index as the key and\n # constraint coeff as the value\n\n # Assemble tuples of (.nl index, constraint value)\n output = collect(zip(\n (m.v_index_map[j] for j in keys(m.lin_constrs[i])),\n values(m.lin_constrs[i]))\n )\n\n # Loop through output in .nl index order\n for (index2, value) in sort(output)\n println(f, \"$index2 $value\")\n end\n end\n end\nend\n\n# Linear objective expression\nfunction write_nl_g_block(f, m::AmplNLMathProgModel)\n println(f, string(\"G0 \", length(m.lin_obj)))\n for index in 0:(m.nvar - 1)\n i = m.v_index_map_rev[index]\n if i in keys(m.lin_obj)\n println(f, \"$index $(m.lin_obj[i])\")\n end\n end\nend\n\n# Convert an expression tree (with .nl formulae only) to .nl format\nwrite_nl_expr(f, m, c) = println(f, string(c))\n# Handle numerical constants e.g. pi\nwrite_nl_expr(f, m, c::Symbol) = write_nl_expr(f, m, float(eval(c)))\nfunction write_nl_expr(f, m, c::Real)\n println(f, nl_number(c == round(Integer, c) ? round(Integer, c) : c))\nend\nwrite_nl_expr(f, m, c::LinearityExpr) = write_nl_expr(f, m, c.c)\nfunction write_nl_expr(f, m, c::Expr)\n if c.head == :ref\n # Output variable as `v$index`\n if c.args[1] == :x\n @assert isa(c.args[2], Int)\n println(f, nl_variable(m.v_index_map[c.args[2]]))\n else\n error(\"Unrecognized reference expression $c\")\n end\n elseif c.head == :call\n # Output function as `o$opcode`\n println(f, nl_operator(c.args[1]))\n if c.args[1] in nary_functions\n # Output nargs on subsequent line if n-ary function\n println(f, (string(length(c.args) - 1)))\n end\n map(arg -> write_nl_expr(f, m, arg), c.args[2:end])\n\n elseif c.head == :comparison\n # .nl only handles binary comparison\n @assert length(c.args) == 3\n # Output comparison type first, followed by args\n println(f, nl_operator(c.args[2]))\n map(arg -> write_nl_expr(f, m, arg), c.args[1:2:end])\n\n elseif c.head in [:&&, :||]\n # Only support binary and/or for now\n @assert length(c.args) == 2\n println(f, nl_operator(c.head))\n map(arg -> write_nl_expr(f, m, arg), c.args)\n else\n error(\"Unrecognized expression $c\")\n end\nend\n\nnl_variable(index::Integer) = \"v$index\"\nnl_number(value::Real) = \"n$value\"\n\nfunction nl_operator(operator::Symbol)\n if !haskey(func_to_nl, operator)\n error(\"translation of the function \\\"$operator\\\" to NL is not defined\")\n end\n return \"o$(func_to_nl[operator])\"\nend\n\n", "meta": {"hexsha": "121961a32f8e2daf533147ffa578b64a5e5f8552", "size": 8040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nl_write.jl", "max_stars_repo_name": "deltova/AmplNLWriter.jl", "max_stars_repo_head_hexsha": "12e31bb1c42e88cc248a978909856ab63f7272ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nl_write.jl", "max_issues_repo_name": "deltova/AmplNLWriter.jl", "max_issues_repo_head_hexsha": "12e31bb1c42e88cc248a978909856ab63f7272ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nl_write.jl", "max_forks_repo_name": "deltova/AmplNLWriter.jl", "max_forks_repo_head_hexsha": "12e31bb1c42e88cc248a978909856ab63f7272ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2255639098, "max_line_length": 79, "alphanum_fraction": 0.5911691542, "num_tokens": 2388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24019737616445813}} {"text": "# Copyright (c) 2018: Matthew Wilhelm & Matthew Stuber.\n# This code is licensed under MIT license (see LICENSE.md for full details)\n#############################################################################\n# McCormick.jl\n# A McCormick operator library in Julia\n# See https://github.com/PSORLab/McCormick.jl\n#############################################################################\n# src/forward_operators/arithmetic.jl\n# Contains definitions of +, -, /, *, promotions, conversion, one, zero.\n#############################################################################\n\n# Defines functions required for linear algebra packages\n@inline nan(::Type{MC{N,T}}) where {N, T <: RelaxTag} = MC{N,T}(NaN, NaN, Interval{Float64}(NaN),\n fill(NaN, SVector{N,Float64}),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfill(NaN, SVector{N,Float64}), true)\n@inline nan(x::MC{N,T}) where {N, T <: RelaxTag} = MC{N,T}(NaN, NaN, Interval{Float64}(NaN),\n fill(NaN, SVector{N,Float64}),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t fill(NaN, SVector{N,Float64}), true)\n\n@inline one(::Type{MC{N,T}}) where {N, T <: RelaxTag} = MC{N,T}(1.0, 1.0, one(Interval{Float64}),\n zero(SVector{N,Float64}),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tzero(SVector{N,Float64}), true)\n@inline one(x::MC{N,T}) where {N, T <: RelaxTag} = MC{N,T}(1.0, 1.0, one(Interval{Float64}),\n zero(SVector{N,Float64}),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t zero(SVector{N,Float64}), true)\n\n@inline zero(::Type{MC{N,T}}) where {N, T <: RelaxTag} = MC{N,T}(0.0, 0.0, zero(Interval{Float64}),\n zero(SVector{N,Float64}),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t zero(SVector{N,Float64}), true)\n@inline zero(x::MC{N,T}) where {N, T <: RelaxTag} = zero(MC{N,T})\n\n@inline real(x::MC) = x\n@inline dist(x1::MC, x2::MC) = max(abs(x1.cc - x2.cc), abs(x1.cv - x2.cv))\n@inline eps(x::MC) = max(eps(x.cc), eps(x.cv))\n@inline mid(x::MC) = mid(x.Intv)\n\n# Unsafe addition\n@inline function plus_kernel(x::MC{N,T}, y::MC{N,T}, z::Interval{Float64}) where {N, T <: Union{NS, MV, Diff}}\n\tMC{N,T}(x.cv + y.cv, x.cc + y.cc, z, x.cv_grad + y.cv_grad, x.cc_grad + y.cc_grad, (x.cnst && y.cnst))\nend\n@inline +(x::MC, y::MC) = plus_kernel(x, y, x.Intv + y.Intv)\n@inline plus_kernel(x::MC, y::Interval{Float64}) = x\n@inline +(x::MC) = x\n\n@inline minus_kernel(x::MC{N,T}, z::Interval{Float64}) where {N, T <: RelaxTag} = MC{N,T}(-x.cc, -x.cv, z, -x.cc_grad, -x.cv_grad, x.cnst)\n@inline -(x::MC) = minus_kernel(x, -x.Intv)\n@inline -(x::MC{N,T}, y::MC{N,T}) where {N, T <: RelaxTag} = minus_kernel(x, y, x.Intv - y.Intv)\n\n# Unsafe subtraction\n@inline function minus_kernel(x::MC{N,T}, y::MC{N,T}, z::Interval{Float64}) where {N, T <: Union{NS, MV, Diff}}\n\tMC{N,T}(x.cv - y.cc, x.cc - y.cv, z, x.cv_grad - y.cc_grad, x.cc_grad - y.cv_grad, (x.cnst && y.cnst))\nend\n\n################## CONVERT THROUGH BINARY DEFINITIONS #########################\n# Unsafe scalar addition\n@inline function plus_kernel(x::MC{N,T}, y::Float64, z::Interval{Float64}) where {N, T <: Union{NS, MV, Diff}}\n\tMC{N,T}(x.cv + y, x.cc + y, z, x.cv_grad, x.cc_grad, x.cnst)\nend\n@inline +(x::MC, y::Float64) = plus_kernel(x, y, x.Intv + y)\n@inline +(y::Float64, x::MC) = plus_kernel(x, y, x.Intv + y)\n@inline +(x::MC{N,T}, y::Interval{Float64}) where {N, T<:RelaxTag} = x + MC{N,T}(y)\n@inline +(y::Interval{Float64}, x::MC{N,T}) where {N, T<:RelaxTag} = x + MC{N,T}(y)\n\n@inline plus_kernel(x::MC, y::C, z::Interval{Float64}) where {C <: NumberNotRelax} = plus_kernel(x, convert(Float64, y), z)\n@inline plus_kernel(x::C, y::MC, z::Interval{Float64}) where {C <: NumberNotRelax} = plus_kernel(y, convert(Float64, x), z)\n@inline +(x::MC, y::C) where {C <: NumberNotRelax} = x + convert(Float64, y)\n@inline +(y::C, x::MC) where {C <: NumberNotRelax} = x + convert(Float64, y)\n\n# Unsafe scalar subtraction\n@inline function minus_kernel(x::MC{N,T}, c::Float64, z::Interval{Float64}) where {N, T <: Union{NS, MV, Diff}}\n\tMC{N,T}(x.cv - c, x.cc - c, z, x.cv_grad, x.cc_grad, x.cnst)\nend\n@inline function minus_kernel(c::Float64, x::MC{N,T}, z::Interval{Float64}) where {N, T <: Union{NS, MV, Diff}}\n\tMC{N,T}(c - x.cc, c - x.cv, z, -x.cc_grad, -x.cv_grad, x.cnst)\nend\n@inline -(x::MC, c::Float64) = minus_kernel(x, c, x.Intv - c)\n@inline -(c::Float64, x::MC) = minus_kernel(c, x, c - x.Intv)\n@inline -(x::MC{N,T}, y::Interval{Float64}) where {N, T<:RelaxTag} = x - MC{N,T}(y)\n@inline -(y::Interval{Float64}, x::MC{N,T}) where {N, T<:RelaxTag} = MC{N,T}(y) - x\n\n@inline minus_kernel(x::MC, y::C, z::Interval{Float64}) where {C <: NumberNotRelax} = minus_kernel(x, convert(Float64, y), z)\n@inline minus_kernel(y::C, x::MC, z::Interval{Float64}) where {C <: NumberNotRelax} = minus_kernel(convert(Float64, y), x, z)\n@inline -(x::MC, c::C) where {C <: NumberNotRelax} = x - convert(Float64,c)\n@inline -(c::C, x::MC) where {C <: NumberNotRelax} = convert(Float64,c) - x\n\n# Unsafe Scalar Multiplication\n@inline function mult_kernel(x::MC{N,T}, c::Float64, z::Interval{Float64}) where {N, T <: Union{NS, MV, Diff}}\n\tif c >= 0.0\n\t\tzMC = MC{N,T}(c*x.cv, c*x.cc, z, c*x.cv_grad, c*x.cc_grad, x.cnst)\n\telse\n\t\tzMC = MC{N,T}(c*x.cc, c*x.cv, z, c*x.cc_grad, c*x.cv_grad, x.cnst)\n\tend\n\treturn zMC\nend\n@inline *(x::MC, c::Float64) = mult_kernel(x, c, c*x.Intv)\n@inline *(c::Float64, x::MC) = mult_kernel(x, c, c*x.Intv)\n@inline *(x::MC{N,T}, y::Interval{Float64}) where {N, T<:RelaxTag} = x*MC{N,T}(y)\n@inline *(y::Interval{Float64}, x::MC{N,T}) where {N, T<:RelaxTag} = MC{N,T}(y)*x\n\n@inline mult_kernel(x::MC, c::C, z::Interval{Float64}) where {C <: NumberNotRelax} = mult_kernel(x, convert(Float64, c), z)\n@inline mult_kernel(c::C, x::MC, z::Interval{Float64}) where {C <: NumberNotRelax} = mult_kernel(x, convert(Float64, c), z)\n@inline *(c::C, x::MC) where {C <: NumberNotRelax} = x*Float64(c)\n@inline *(x::MC, c::C) where {C <: NumberNotRelax} = x*Float64(c)\n\n# Unsafe scalar division\n@inline div_kernel(x::MC, y::Float64, z::Interval{Float64}) = mult_kernel(x, inv(y), z)\n@inline div_kernel(x::Float64, y::MC, z::Interval{Float64}) = mult_kernel(inv(y), x, z)\n@inline div_kernel(x::MC, y::C, z::Interval{Float64}) where {C <: NumberNotRelax} = mult_kernel(x, inv(y), z)\n@inline div_kernel(x::C, y::MC, z::Interval{Float64}) where {C <: NumberNotRelax} = mult_kernel(inv(y), x, z)\n@inline /(x::MC, y::Float64) = x*inv(y)\n@inline /(x::Float64, y::MC) = x*inv(y)\n@inline /(x::MC, y::C) where {C <: NumberNotRelax} = x*inv(convert(Float64,y))\n@inline /(x::C, y::MC) where {C <: NumberNotRelax} = convert(Float64,x)*inv(y)\n@inline /(x::MC{N,T}, y::Interval{Float64}) where {N, T<:RelaxTag} = x/MC{N,T}(y)\n@inline /(y::Interval{Float64}, x::MC{N,T}) where {N, T<:RelaxTag} = MC{N,T}(y)/x\n\n# Maximization\n@inline max_kernel(c::Float64, x::MC, z::Interval{Float64}) = max_kernel(x, c, z)\n@inline max_kernel(x::MC, c::C, z::Interval{Float64}) where {C <: NumberNotRelax} = max_kernel(x, convert(Float64, c), z)\n@inline max_kernel(c::C, x::MC, z::Interval{Float64}) where {C <: NumberNotRelax} = max_kernel(x, convert(Float64, c), z)\n\n@inline max(c::Float64, x::MC) = max_kernel(x, c, max(x.Intv, c))\n@inline max(x::MC, c::C) where {C <: NumberNotRelax} = max_kernel(x, convert(Float64, c), max(x.Intv, c))\n@inline max(c::C, x::MC) where {C <: NumberNotRelax} = max_kernel(x, convert(Float64, c), max(x.Intv, c))\n@inline max(x::MC{N,T}, y::Interval{Float64}) where {N, T<:RelaxTag} = max(x, MC{N,T}(y))\n@inline max(y::Interval{Float64}, x::MC{N,T}) where {N, T<:RelaxTag} = max(MC{N,T}(y), x)\n\n# Minimization\n@inline min_kernel(x::MC, c::C, z::Interval{Float64}) where {C <: NumberNotRelax} = min_kernel(x, convert(Float64, c), z)\n@inline min_kernel(c::C, x::MC, z::Interval{Float64}) where {C <: NumberNotRelax} = min_kernel(x, convert(Float64, c), z)\n\n@inline min(c::Float64, x::MC) = min_kernel(x, c, min(x.Intv, c))\n@inline min(x::MC, c::C) where {C <: NumberNotRelax} = min_kernel(x, convert(Float64, c), min(x.Intv, c))\n@inline min(c::C, x::MC) where {C <: NumberNotRelax} = min_kernel(x, convert(Float64, c), min(x.Intv, c))\n@inline min(x::MC{N,T}, y::Interval{Float64}) where {N, T<:RelaxTag} = min(x, MC{N,T}(y))\n@inline min(y::Interval{Float64}, x::MC{N,T}) where {N, T<:RelaxTag} = min(MC{N,T}(y), x)\n\n# Add fma function\n@inline fma(x::MC, y::Float64, z::Float64) = x*y + z\n@inline fma(x::MC, y::MC, z::Float64) = x*y + z\n@inline fma(x::MC, y::Float64, z::MC) = x*y + z\n@inline fma(x::MC, y::MC, z::MC) = x*y + z\n@inline fma(x::Float64, y::MC, z::Float64) = x*y + z\n@inline fma(x::Float64, y::MC, z::MC) = x*y + z\n@inline fma(x::Float64, y::Float64, z::MC) = x*y + z\n\n@inline fma(x::MC, y::Float64, z::Float64, q::Interval{Float64}) = x*y + z\n@inline fma(x::MC, y::MC, z::Float64, q::Interval{Float64}) = x*y + z\n@inline fma(x::MC, y::Float64, z::MC, q::Interval{Float64}) = x*y + z\n@inline fma(x::MC, y::MC, z::MC, q::Interval{Float64}) = x*y + z\n@inline fma(x::Float64, y::MC, z::Float64, q::Interval{Float64}) = x*y + z\n@inline fma(x::Float64, y::MC, z::MC, q::Interval{Float64}) = x*y + z\n@inline fma(x::Float64, y::Float64, z::MC, q::Interval{Float64}) = x*y + z\n\n# Promote and Convert\npromote_rule(::Type{MC{N,T}}, ::Type{S}) where {S<:NumberNotRelax, N, T <: RelaxTag} = MC{N,T}\npromote_rule(::Type{MC{N,T}}, ::Type{S}) where {S<:Real, N, T <: RelaxTag} = MC{N,T}\n\nconvert(::Type{MC{N,T}}, x::S) where {S<:NumberNotRelax, N, T <: RelaxTag} = MC{N,T}(Interval{Float64}(x))\nconvert(::Type{MC{N,T}}, x::S) where {S<:AbstractInterval, N, T <: RelaxTag} = MC{N,T}(Interval{Float64}(x.lo, x.hi))\nInterval(x::MC{N,T}) where {N,T<:RelaxTag} = x.Intv\nInterval{Float64}(x::MC{N,T}) where {N,T<:RelaxTag} = x.Intv\n", "meta": {"hexsha": "651e54709de8ebf191abe7987880da33311fe266", "size": 9768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "solver_benchmarking/McCormick.jl/src/forward_operators/arithmetic.jl", "max_stars_repo_name": "PSORLab/RSActivationFunctions", "max_stars_repo_head_hexsha": "0bf8b4500b21144c076ea958ce93dbdd19a53314", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-03-14T00:49:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T15:27:17.000Z", "max_issues_repo_path": "solver_benchmarking/McCormick.jl/src/forward_operators/arithmetic.jl", "max_issues_repo_name": "PSORLab/RSActivationFunctions", "max_issues_repo_head_hexsha": "0bf8b4500b21144c076ea958ce93dbdd19a53314", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-03-10T02:01:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T23:40:41.000Z", "max_forks_repo_path": "solver_benchmarking/McCormick.jl/src/forward_operators/arithmetic.jl", "max_forks_repo_name": "PSORLab/RSActivationFunctions", "max_forks_repo_head_hexsha": "0bf8b4500b21144c076ea958ce93dbdd19a53314", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-12T15:31:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T18:24:05.000Z", "avg_line_length": 59.9263803681, "max_line_length": 138, "alphanum_fraction": 0.5917280917, "num_tokens": 3519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24019737616445813}} {"text": "\n\"\"\"\ncollecting all needed functions required to calculate Housdorff distance\n\"\"\"\nmodule Housdorff\nusing CUDA\nusing ..CUDAGpuUtils ,..IterationUtils,..ReductionUtils , ..MemoryUtils,..CUDAAtomicUtils\nusing ..BitWiseUtils,..MetadataAnalyzePass,..MetaDataUtils,..WorkQueueUtils,..ProcessMainDataVerB,..HFUtils,..ResultListUtils,..PrepareArrtoBool, ..MainLoopKernel,..ScanForDuplicates\nexport get_shmemMainKernel, getHousedorffDistance,boolKernelLoad,mainKernelLoad,get_shmemMainKernel,get_shmemBoolKernel,preparehousedorfKernel\n\"\"\"\ncalculate housedorff distance of given arrays with given robustness percentage\n\n\"\"\"\nfunction getHousedorffDistance(goldGPUa,segmGPUa,boolKernelArgs,mainKernelArgs,threadsBoolKern,blocksBoolKern ,threadsMainKern,blocksMainKern,shmemSizeBool,shmemSizeMain)\n # boolKernelArgs[1]= goldGPU\n # boolKernelArgs[2]= segmGPU\n mainArrDims,dataBdim,metaData,metaDataDims,reducedGoldA,reducedSegmA,loopXinPlane,loopYinPlane,minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp ,numberToLooFor,inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength = boolKernelArgs\n\n @cuda threads=threadsBoolKern blocks=blocksBoolKern shmem=shmemSizeBool cooperative=true boolKernelLoad(goldGPUa,segmGPUa,boolKernelArgs...)\n #now time to get data structures dependent on bool kernel like for example loading subsections of meta data, creating work queue ...\n #some arrays needs to be instantiated only after we know the number of the false and true positives\n metaData,reducedGoldA ,reducedSegmA ,paddingStore,resList,workQueue,workQueueCounter= getBigGPUForHousedorffAfterBoolKernel(metaData,minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp,reducedGoldA,reducedSegmA,dataBdim)\n referenceArrs,dilatationArrs, mainArrDims,dataBdim,numberToLooFor,metaDataDims,metaData,iterThrougWarNumb,robustnessPercent,shmemSumLengthMaxDiv4,globalFpResOffsetCounter,globalFnResOffsetCounter ,globalIterationNumber,globalCurrentFnCount,globalCurrentFpCount ,globalIterationNumb,workQueue,workQueueCounter,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed ,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop ,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength, fn,fp,resList,inBlockLoopXZIterWithPadding,paddingStore,shmemblockDataLenght,shmemblockDataLoop= mainKernelArgs\n\n dilatationArrs= (reducedGoldA,reducedSegmA)\n #reverse order as when dilatating gold we want to establish do we cover segm voxels\n referenceArrs=(segmGPUa,goldGPUa )\n \n #main calculations\n @cuda threads=threadsMainKern blocks=blocksMainKern shmem=shmemSizeMain cooperative=true mainKernelLoadB( referenceArrs,dilatationArrs, mainArrDims,dataBdim\n ,numberToLooFor,metaDataDims,metaData,iterThrougWarNumb,robustnessPercent\n ,shmemSumLengthMaxDiv4,globalFpResOffsetCounter,globalFnResOffsetCounter\n ,globalIterationNumber,globalCurrentFnCount,globalCurrentFpCount\n ,globalIterationNumb,workQueue,workQueueCounter\n ,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed\n ,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY\n ,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop\n ,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength, fn,fp,resList,inBlockLoopXZIterWithPadding,paddingStore,shmemblockDataLenght,shmemblockDataLoop)\n #@cuda threads=threadsMainKern blocks=blocksMainKern shmem=shmemSizeMain cooperative=true mainKernelLoad(dilatationArrs,referenceArrs, mainArrDims,dataBdim,numberToLooFor,metaDataDims,metaData,iterThrougWarNumb,robustnessPercent,shmemSumLengthMaxDiv4,globalFpResOffsetCounter,globalFnResOffsetCounter,globalIterationNumber,globalCurrentFnCount,globalCurrentFpCount,globalIterationNumb,workQueaue,resList,resListIndicies,maxResListIndex,inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength, fn,fp)\n return globalIterationNumb\n \n end\n\n\"\"\"\nclearing data before next execution\n\"\"\"\nfunction housClearForExecution()\n\nend\n\n\n\"\"\"\nfor invoking getBoolCubeKernel\n\"\"\"\nfunction boolKernelLoad(goldGPU,segmGPU,mainArrDims,dataBdim,metaData,metaDataDims,reducedGoldA,reducedSegmA,loopXinPlane,loopYinPlane,minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp ,numberToLooFor,inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength)\n @getBoolCubeKernel()\n return\nend\n\"\"\"\nmain function responsible for calculations of Housedorff distance\n\"\"\"\nfunction mainKernelLoadB(referenceArrs,dilatationArrs, mainArrDims,dataBdim\n ,numberToLooFor,metaDataDims,metaData,iterThrougWarNumb,robustnessPercent\n ,shmemSumLengthMaxDiv4,globalFpResOffsetCounter,globalFnResOffsetCounter\n ,globalIterationNumber,globalCurrentFnCount,globalCurrentFpCount\n ,globalIterationNumb,workQueue,workQueueCounter\n ,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed\n ,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY\n ,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop\n ,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength, fn,fp,resList,inBlockLoopXZIterWithPadding,paddingStore,shmemblockDataLenght,shmemblockDataLoop)\n\n #@mainLoopKernel()\n return\nend\n\nfunction mainKernelLoad(referenceArrs,dilatationArrs, mainArrDims,dataBdim\n ,numberToLooFor,metaDataDims,metaData,iterThrougWarNumb,robustnessPercent\n ,shmemSumLengthMaxDiv4,globalFpResOffsetCounter,globalFnResOffsetCounter\n ,globalIterationNumber,globalCurrentFnCount,globalCurrentFpCount\n ,globalIterationNumb,workQueue,workQueueCounter\n ,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed\n ,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY\n ,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop\n ,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength, fn,fp,resList,inBlockLoopXZIterWithPadding,paddingStore,shmemblockDataLenght,shmemblockDataLoop)\n @mainLoopKernel()\n return\nend\n\n\nfunction get_shmemMainKernel(dataBdim)\n \n shmemblockData= sizeof(UInt32)*32*32\n # shmemblockData= sizeof(UInt32)*dataBdim[1]* dataBdim[2]\n resShmemblockData= sizeof(UInt32)*32*32\n # resShmemblockData= sizeof(UInt32)*dataBdim[1]* dataBdim[2]\n shmemPaddings= sizeof(Bool)*( max(dataBdim[1], dataBdim[2]))*( max(dataBdim[1], dataBdim[2]))*6\n shmemSum= sizeof(UInt32)*36*16\n areToBeValidated= sizeof(Bool)*14\n isAnythingInPadding= sizeof(Bool)*7\n alreadyCoveredInQueues= sizeof(UInt32)*14\n someBools = sizeof(Bool)*4\n someInt16 = sizeof(UInt16)*6\n workCountersInshmem = sizeof(UInt16)*2\nreturn workCountersInshmem+shmemSum+areToBeValidated+isAnythingInPadding+alreadyCoveredInQueues+someBools+shmemblockData+someInt16+resShmemblockData+shmemPaddings\nend\n\nfunction get_shmemBoolKernel(dataBdim)\n # shmemSum= sizeof(Float32)*32*2\n shmemblockData= sizeof(Int32)*(dataBdim[1])*(dataBdim[2])\n localQuesValues = sizeof(UInt32)*14\n minMaxes = sizeof(Float32)*6\nreturn minMaxes+localQuesValues+shmemblockData\nend\n\n\"\"\"\ncreates required cu arrays , calculates some kernel constants and uses occupancy API\nto calculate optimal number of threads and blocks to run a kernel\nrobustnessPercent - frequently we do not want to analyze all of the fap and fn in order to reduce the impact of the outliers \nnumberToLooFor - what we will look for in main arrays\n\"\"\"\nfunction preparehousedorfKernel(goldGPU,segmGPU,robustnessPercent,numberToLooFor)\n mainArrDims = size(goldGPU)\n dataBdim = (32,32,32) # will be modified after number of threads gets calculated by occupancy API\n\n metaData = MetaDataUtils.allocateMetadata(mainArrDims,dataBdim);\n metaDataDims= size(metaData);\n #for bool cube kernel\n threadsBoolKern= (30,32); blocksBoolKern = 10#just some dummy will be modified after invoking occupancy API\n #for main kernel\n threadsMainKern= (30,32); blocksMainKern = 10#just some dummy will be modified after invoking occupancy API\n iterThrougWarNumb = cld(14,threadsMainKern[2])\n\n inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength=calculateLoopsIter(dataBdim,threadsBoolKern[1],threadsBoolKern[2],metaDataDims,blocksBoolKern)\n minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp =getSmallForBoolKernel();\n reducedGoldA,reducedSegmA= getLargeForBoolKernel(mainArrDims,dataBdim);\n \n loopXinPlane,loopYinPlane = 1,1\n boolKernelArgs = (mainArrDims,dataBdim,metaData,metaDataDims,reducedGoldA,reducedSegmA,loopXinPlane,loopYinPlane,minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp ,numberToLooFor,inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength)\n #needed also in bool kernel\n \n #### main kernel\n fpLoc = 10\n fnLoc = 10\n resList= allocateResultLists(fpLoc,fnLoc)\n globalFpResOffsetCounter,globalFnResOffsetCounter,globalIterationNumber,globalCurrentFnCount,globalCurrentFpCount,globalIterationNumb= getSmallGPUForHousedorff()\n\n referenceArrs=(goldGPU,segmGPU)\n\n inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength=calculateLoopsIter(dataBdim,threadsBoolKern[1],threadsBoolKern[2],metaDataDims,blocksBoolKern)\n shmemSumLengthMaxDiv4= fld((36*14),4)*4 # subject to futre changes\n\n metaData,reducedGoldA ,reducedSegmA ,paddingStore,resList,workQueue,workQueueCounter = getBigGPUForHousedorffAfterBoolKernel(metaData,minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp,reducedGoldA,reducedSegmA,dataBdim)\n \n reducedGoldA,reducedSegmA= getLargeForBoolKernel(mainArrDims,dataBdim);\n\n dilatationArrs= (reducedGoldA,reducedSegmA)\n\n mainKernelArgs= (referenceArrs,dilatationArrs, mainArrDims,dataBdim\n ,numberToLooFor,metaDataDims,metaData,iterThrougWarNumb,robustnessPercent\n ,shmemSumLengthMaxDiv4,globalFpResOffsetCounter,globalFnResOffsetCounter\n ,globalIterationNumber,globalCurrentFnCount,globalCurrentFpCount\n ,globalIterationNumb,workQueue,workQueueCounter\n ,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed\n ,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY\n ,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop\n ,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength, fn,fp,resList,inBlockLoopXZIterWithPadding,paddingStore,shmemblockDataLenght,shmemblockDataLoop)\n \n function get_shmemMainKernelLoc(threads)\n dataBdim = (threads[1],threads[2],32)\n get_shmemMainKernel(dataBdim)\n end\n \n\n threadsMainKern,blocksMainKern = getThreadsAndBlocksNumbForKernel(get_shmemMainKernel,mainKernelLoad,(mainKernelArgs))\n function get_shmemBoolKernelLoc(threads)\n dataBdim = (threadsMainKern[1],threadsMainKern[2],32)\n get_shmemBoolKernel(dataBdim)\n end\n\n boolKernelArgs = (mainArrDims,dataBdim,metaData,metaDataDims,reducedGoldA,reducedSegmA,loopXinPlane,loopYinPlane,minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp ,numberToLooFor,inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength)\n\n ## now we need to make use of occupancy API to get optimal number of threads and blocks fo each kernel\n threadsBoolKern,blocksBoolKern = getThreadsAndBlocksNumbForKernel(get_shmemBoolKernelLoc,boolKernelLoad,(goldGPU,segmGPU,boolKernelArgs...))\n \n loopXinPlane,loopYinPlane = fld(threadsMainKern[1],threadsBoolKern[1] ), fld(threadsMainKern[2],threadsBoolKern[2] )\n#now we get defoult values of data b dim set on the basis of the threadsMainHKernel; and generally recalculating loops constants \n dataBdim = (threadsMainKern[1],threadsMainKern[2],32)\n metaData = MetaDataUtils.allocateMetadata(mainArrDims,dataBdim);\n metaDataDims= size(metaData);\n iterThrougWarNumb = cld(14,threadsMainKern[2])\n\n boolKernelArgs = (mainArrDims,dataBdim,metaData,metaDataDims,reducedGoldA,reducedSegmA,loopXinPlane,loopYinPlane,minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp ,numberToLooFor,inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength)\n\n inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength=calculateLoopsIter(dataBdim,threadsBoolKern[1],threadsBoolKern[2],metaDataDims,blocksBoolKern)\n \n\n boolKernelArgs = (mainArrDims,dataBdim,metaData,metaDataDims,reducedGoldA,reducedSegmA,loopXinPlane,loopYinPlane,minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp ,numberToLooFor,inBlockLoopXZIterWithPadding,shmemblockDataLoop,shmemblockDataLenght,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength)\n metaData,reducedGoldA ,reducedSegmA ,paddingStore,resList,workQueue,workQueueCounter= getBigGPUForHousedorffAfterBoolKernel(metaData,minxRes,maxxRes,minyRes,maxyRes,minzRes,maxzRes,fn,fp,reducedGoldA,reducedSegmA,dataBdim)\n \n reducedGoldA,reducedSegmA= getLargeForBoolKernel(mainArrDims,dataBdim);\n\n mainKernelArgs= (referenceArrs,dilatationArrs, mainArrDims,dataBdim\n ,numberToLooFor,metaDataDims,metaData,iterThrougWarNumb,robustnessPercent\n ,shmemSumLengthMaxDiv4,globalFpResOffsetCounter,globalFnResOffsetCounter\n ,globalIterationNumber,globalCurrentFnCount,globalCurrentFpCount\n ,globalIterationNumb,workQueue,workQueueCounter\n ,loopAXFixed,loopBXfixed,loopAYFixed,loopBYfixed,loopAZFixed,loopBZfixed\n ,loopdataDimMainX,loopdataDimMainY,loopdataDimMainZ,inBlockLoopX,inBlockLoopY\n ,inBlockLoopZ,metaDataLength,loopMeta,loopWarpMeta,clearIterResShmemLoop\n ,clearIterSourceShmemLoop,resShmemTotalLength,sourceShmemTotalLength, fn,fp,resList,inBlockLoopXZIterWithPadding,paddingStore,shmemblockDataLenght,shmemblockDataLoop) \n shmemSizeBool=get_shmemBoolKernelLoc(threadsBoolKern)\n shmemSizeMain=get_shmemMainKernelLoc(threadsMainKern)\n\n # CUDA.unsafe_free!(goldGPU)\n # CUDA.unsafe_free!(segmGPU)\n #CUDA.reclaim()\nreturn (boolKernelArgs, mainKernelArgs,threadsBoolKern,blocksBoolKern ,threadsMainKern,blocksMainKern ,shmemSizeBool,shmemSizeMain)\n\nend\n\nend# module\n\n \n", "meta": {"hexsha": "55e41dd3486f6a188f8a277acbe7a42b472b6e76", "size": 16955, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distanceMetrics/Housdorff/verB/Housdorff.jl", "max_stars_repo_name": "jakubMitura14/NuclearMedEval", "max_stars_repo_head_hexsha": "bf4502118d833dcd4c5de630594941801e984935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distanceMetrics/Housdorff/verB/Housdorff.jl", "max_issues_repo_name": "jakubMitura14/NuclearMedEval", "max_issues_repo_head_hexsha": "bf4502118d833dcd4c5de630594941801e984935", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distanceMetrics/Housdorff/verB/Housdorff.jl", "max_forks_repo_name": "jakubMitura14/NuclearMedEval", "max_forks_repo_head_hexsha": "bf4502118d833dcd4c5de630594941801e984935", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.6919642857, "max_line_length": 809, "alphanum_fraction": 0.8522559717, "num_tokens": 5170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24019737006086336}} {"text": "\"\"\"\nGenX: An Configurable Capacity Expansion Model\nCopyright (C) 2021, Massachusetts Institute of Technology\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\nA complete copy of the GNU General Public License v2 (GPLv2) is available\nin LICENSE.txt. Users uncompressing this from an archive may not have\nreceived this license file. If not, see .\n\"\"\"\n\n@doc raw\"\"\"\n\temissions(EP::Model, inputs::Dict, UCommit::Int)\n\nThis function creates expression to add the CO2 emissions by plants in each zone, which is subsequently added to the total emissions\n\"\"\"\nfunction emissions(EP::Model, inputs::Dict)\n\n\tprintln(\"Emissions Module (for CO2 Policy modularization\")\n\n\tdfGen = inputs[\"dfGen\"]\n\n\tG = inputs[\"G\"] # Number of resources (generators, storage, DR, and DERs)\n\tT = inputs[\"T\"] # Number of time steps (hours)\n\tZ = inputs[\"Z\"] # Number of zones\n\tCOMMIT = inputs[\"COMMIT\"] # For not, thermal resources are the only ones eligible for Unit Committment\n\n\t@expression(EP, eEmissionsByPlant[y=1:G,t=1:T],\n\t \tif y in inputs[\"COMMIT\"]\n\t\t \tdfGen[!,:CO2_per_MWh][y]*EP[:vP][y,t]+dfGen[!,:CO2_per_Start][y]*EP[:vSTART][y,t]\n\t \telse\n\t\t \tdfGen[!,:CO2_per_MWh][y]*EP[:vP][y,t]\n\t \tend\n \t)\n\n \t@expression(EP, eEmissionsByZone[z=1:Z, t=1:T], sum(eEmissionsByPlant[y,t] for y in dfGen[(dfGen[!,:Zone].==z),:R_ID]))\n\t\n\treturn EP\nend\n", "meta": {"hexsha": "5c4090f1b1ffe192e1b0c68c4385f14b4d81167f", "size": 1778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/model/core/emissions.jl", "max_stars_repo_name": "Betristor/LTESOM", "max_stars_repo_head_hexsha": "ef972e96764254974de31b7bcbc1a6e63aee0ce0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/model/core/emissions.jl", "max_issues_repo_name": "Betristor/LTESOM", "max_issues_repo_head_hexsha": "ef972e96764254974de31b7bcbc1a6e63aee0ce0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model/core/emissions.jl", "max_forks_repo_name": "Betristor/LTESOM", "max_forks_repo_head_hexsha": "ef972e96764254974de31b7bcbc1a6e63aee0ce0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5111111111, "max_line_length": 132, "alphanum_fraction": 0.7294713161, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24016287625726424}} {"text": "################################################################################\n#\n# IMPLEMENTATIONS OF DIFFERENT LATTICE MODIFICATION FUNCTIONS\n# (MOST OF THEM ALSO WORK FOR UNITCELLS)\n#\n# STRUCTURE OF THE FILE\n#\n# 1) CONNECTIONS ADDING REMOVING\n# - Add a new connection\n# - remove connections (based on indices)\n# - remove connections (based on strength)\n#\n# 2) SITES ADDING REMOVING\n# - add a new site\n# - remove a site (based on index)\n#\n# 3) CONNECTION STRENGTH MODIFICATION\n# - all connections\n# - mapping of strengths\n# - evaluate strengths\n# - optimize connections\n#\n# 4) REAL SPACE ROTATION / SCALING / SHIFTING\n# - Rotation around some axis\n# - Scaling along some axis\n# - Global (isotropic) scaling\n# - Global (isotropic) scaling to mean / minimum bond length\n# - Shifting along some axis\n# - Shifting along some lattice vector\n# - Shifting center of lattice to origin\n#\n# 5) LATTICE VECTOR OPTIMIZATION\n#\n################################################################################\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n################################################################################\n#\n# 1) CONNECTIONS ADDING REMOVING\n# - Add a new connection\n# - remove connections (based on indices)\n# - remove connections (based on strength)\n#\n################################################################################\n\n\n\n#-------------------------------------------------------------------------------\n#\n# Add connection to given unitcell / lattice objects\n#\n#-------------------------------------------------------------------------------\n\"\"\"\n addConnection!(unitcell::Unitcell, index_from::Int64, index_to::Int64, strength [, wrap=-1; overwrite::Bool=false])\n addConnection!(lattice::Lattice, index_from::Int64, index_to::Int64, strength [, wrap=-1; overwrite::Bool=false])\n\nFunction to add a connection to either a `Unitcell` object or a `Lattice` object.\nNecessary parameters include the indices of sites between which the connection takes place as well as the strength of the connection.\nAdditionally (in case of a unitcell or periodic boundaries), a wrap can be specified in terms of lattice vectors.\nIf no wrap is specified, the wrap will be chosen automatically as without wrapping around periodic boundaries.\n\nThe additional option `overwrite` specifies if one wants to simply add the connection\nor if one wants to first search if there is a connection that already satisfies the new connection (in which case nothing would be added).\n\nNOTE 1: This function always tries to add two connections, one going forward, one going backward.\n\nNOTE 2: This function modifies the given object and does not create a copy.\n\n\n# Examples\n\n```julia-repl\njulia> addConnection!(unitcell, 1, 3, \"tx\", (0,1))\n\n\njulia> addConnection!(lattice, 31, 27, \"tx\")\n\n```\n\"\"\"\nfunction addConnection!(unitcell::Unitcell, index_from::Int64, index_to::Int64, strength, wrap=-1; overwrite::Bool=false)\n\n # maybe default wrap\n if wrap == -1\n if length(unitcell.lattice_vectors) == 3\n wrap = (0,0,0)\n elseif length(unitcell.lattice_vectors) == 2\n wrap = (0,0)\n else\n wrap = (0)\n end\n end\n\n # construct the returning wrap\n if length(wrap) == 3\n wrap_return = (-wrap[1],-wrap[2],-wrap[3])\n elseif length(wrap) == 2\n wrap_return = (-wrap[1],-wrap[2])\n else\n wrap_return = (-wrap)\n end\n # construct the returning strength\n if typeof(strength) == Complex\n strength_return = deepcopy(conj(strength))\n else\n strength_return = deepcopy(strength)\n end\n\n # construct the connection as an array\n connection_1 = Any[index_from; index_to; strength; wrap]\n # construct the returning connection as an array\n connection_2 = Any[index_to; index_from; strength_return; wrap_return]\n\n # if not overwrite, check if the connection exists\n if !overwrite\n # report if found\n found_c1 = false\n found_c2 = false\n # check in all connections\n for c in unitcell.connections\n if Int(c[1]) == Int(connection_1[1]) && Int(c[2]) == Int(connection_1[2]) && c[3] == connection_1[3] && c[4] == connection_1[4]\n found_c1 = true\n end\n if Int(c[1]) == Int(connection_2[1]) && Int(c[2]) == Int(connection_2[2]) && c[3] == connection_2[3] && c[4] == connection_2[4]\n found_c2 = true\n end\n end\n # only add if not added already\n if !found_c1\n push!(unitcell.connections, connection_1);\n end\n if !found_c2\n push!(unitcell.connections, connection_2);\n end\n # otherwise, just add the connections\n else\n push!(unitcell.connections, connection_1);\n push!(unitcell.connections, connection_2);\n end\n\n # return nothing\n return nothing\nend\nfunction addConnection!(lattice::Lattice, index_from::Int64, index_to::Int64, strength, wrap=-1; overwrite::Bool=false)\n\n # maybe default wrap\n if wrap == -1\n if length(lattice.lattice_vectors) == 3\n wrap = (0,0,0)\n elseif length(lattice.lattice_vectors) == 2\n wrap = (0,0)\n else\n wrap = (0)\n end\n end\n\n # construct the returning wrap\n if length(wrap) == 3\n wrap_return = (-wrap[1],-wrap[2],-wrap[3])\n elseif length(wrap) == 2\n wrap_return = (-wrap[1],-wrap[2])\n else\n wrap_return = (-wrap)\n end\n # construct the returning strength\n if typeof(strength) == Complex\n strength_return = deepcopy(conj(strength))\n else\n strength_return = deepcopy(strength)\n end\n\n # construct the connection as an array\n connection_1 = Any[index_from; index_to; strength; wrap]\n # construct the returning connection as an array\n connection_2 = Any[index_to; index_from; strength_return; wrap_return]\n\n # if not overwrite, check if the connection exists\n if !overwrite\n # report if found\n found_c1 = false\n found_c2 = false\n # check in all connections\n for c in lattice.connections\n if Int(c[1]) == Int(connection_1[1]) && Int(c[2]) == Int(connection_1[2]) && c[3] == connection_1[3] && c[4] == connection_1[4]\n found_c1 = true\n end\n if Int(c[1]) == Int(connection_2[1]) && Int(c[2]) == Int(connection_2[2]) && c[3] == connection_2[3] && c[4] == connection_2[4]\n found_c2 = true\n end\n end\n # only add if not added already\n if !found_c1\n push!(lattice.connections, connection_1);\n end\n if !found_c2\n push!(lattice.connections, connection_2);\n end\n # otherwise, just add the connections\n else\n push!(lattice.connections, connection_1);\n push!(lattice.connections, connection_2);\n end\n\n # return nothing\n return nothing\nend\nexport addConnection!\n\n\n\n\n\n\n#-------------------------------------------------------------------------------\n#\n# Remove interactions with given strengths of the unitcell / lattice\n#\n#-------------------------------------------------------------------------------\n\"\"\"\n removeConnections!(unitcell::Unitcell, index_from::Int64, index_to::Int64 [, strength ])\n removeConnections!(lattice::Lattice, index_from::Int64, index_to::Int64 [, strength ])\n\nFunction to remove connections from either a `Unitcell` object or a `Lattice` object based on the sites that they connect.\nOptionally, one can pass a connection strength to also filter based on this strength. If no strength is passed, all connnections\nbetween the two sites will be removed.\n\n removeConnections!(unitcell::Unitcell [, strength])\n removeConnections!(lattice::Lattice [, strength])\n\nFunction to remove connections from either a `Unitcell` object or a `Lattice` object only based on the strength of connections.\nIf no strength is passed, all connnections with Float64 strength `0.0` will be removed.\n\nNOTE 1: This function always tries to delte both connections, one going forward, one going backward.\n\nNOTE 2: This function modifies the given object and does not create a copy.\n\n\n# Examples\n\n```julia-repl\njulia> removeConnections!(unitcell, 1, 3, \"tx\")\n\njulia> removeConnections!(unitcell, 1, 3)\n\njulia> removeConnections!(lattice, 23, 73)\n\njulia> removeConnections!(lattice, \"tx\")\n\n```\n\"\"\"\nfunction removeConnections!(lattice::Lattice, index_from::Int64, index_to::Int64, strength)\n # use the julia filter function to filter out all elements which have the strength passed and the fitting indices\n filter!(x->!(x[3]==strength && Int(x[1])==index_from && Int(x[2])==index_to) && !(x[3]==strength && Int(x[2])==index_from && Int(x[1])==index_to), lattice.connections)\n # return nothing\n return nothing\nend\nfunction removeConnections!(unitcell::Unitcell, index_from::Int64, index_to::Int64, strength)\n # use the julia filter function to filter out all elements which have the strength passed and the fitting indices\n filter!(x->!(x[3]==strength && Int(x[1])==index_from && Int(x[2])==index_to) && !(x[3]==strength && Int(x[2])==index_from && Int(x[1])==index_to), unitcell.connections)\n # return nothing\n return nothing\nend\nfunction removeConnections!(lattice::Lattice, index_from::Int64, index_to::Int64)\n # use the julia filter function to filter out all elements which have the fitting indices\n filter!(x->!(Int(x[1])==index_from && Int(x[2])==index_to) && !(Int(x[2])==index_from && Int(x[1])==index_to), lattice.connections)\n # return nothing\n return nothing\nend\nfunction removeConnections!(unitcell::Unitcell, index_from::Int64, index_to::Int64)\n # use the julia filter function to filter out all elements which have the fitting indices\n filter!(x->!(Int(x[1])==index_from && Int(x[2])==index_to) && !(Int(x[2])==index_from && Int(x[1])==index_to), unitcell.connections)\n # return nothing\n return nothing\nend\nfunction removeConnections!(lattice::Lattice, strength=0.0)\n # use the julia filter function to filter out all elements which have the strength passed\n filter!(x->x[3]!=strength, lattice.connections)\n # return nothing\n return nothing\nend\nfunction removeConnections!(unitcell::Unitcell, strength=0.0)\n # use the julia filter function to filter out all elements which have the strength passed\n filter!(x->x[3]!=strength, unitcell.connections)\n # return nothing\n return nothing\nend\n\nexport removeConnections!\n\n\n\n\n\n\n\n\n\n\n\n################################################################################\n#\n# 2) SITES ADDING REMOVING\n# - add a new site\n# - remove a site (based on index)\n#\n################################################################################\n\n\"\"\"\n addSite!(unitcell::Unitcell, position::Array{Float64,1})\n addSite!(lattice::Lattice, position::Array{Float64,1})\n\nFunction to add a site to either a `Unitcell` object or a `Lattice` object which is located at\nthe real space position `position`. The function returns the index of the newly added site for further use.\n\n\nNOTE 1: The newly added site is not connected to any other sites yet.\n\nNOTE 2: This function modifies the given object and does not create a copy.\n\n\n# Examples\n\n```julia-repl\njulia> addSite!(unitcell, Float64[0.0, 0.5])\n5\n\njulia> addSite!(lattice, Float64[0.0, 0.5, 1.0])\n187\n```\n\"\"\"\nfunction addSite!(lattice::Lattice, position::Array{Float64,1})\n # push the site into the positions list\n push!(lattice.positions, position)\n # return the site index\n return length(lattice.positions)\nend\nfunction addSite!(unitcell::Unitcell, position::Array{Float64,1})\n # push the site into the positions list\n push!(unitcell.basis, position)\n # return the site index\n return length(unitcell.basis)\nend\nexport addSite!\n\n\n\"\"\"\n removeSite!(unitcell::Unitcell, index::Int64)\n removeSite!(lattice::Lattice, index::Int64)\n\nFunction to remove a site from either a `Unitcell` object or a `Lattice` object with index `index`.\nThe function furhtermore removes all connections that are connected to the site and relabels all\nother connections as well to account for the index shift introduced by the removal.\n\nNOTE: This function modifies the given object and does not create a copy.\n\n\n# Examples\n\n```julia-repl\njulia> removeSite!(unitcell, 2)\n\njulia> removeSite!(lattice, 128)\n\n```\n\"\"\"\nfunction removeSite!(lattice::Lattice, index::Int64)\n # delete the element from the positions list\n deleteat!(lattice.positions, index)\n # delete all connections that touch the removed site\n deleteat!(lattice.connections, [c[1]==index || c[2]==index for c in lattice.connections])\n # now shift all indices in the connections array by 1\n for (i,c) in enumerate(lattice.connections)\n if Int(c[1]) > index\n c[1] = Int(c[1]) - 1\n end\n if Int(c[2]) > index\n c[2] = Int(c[2]) - 1\n end\n end\n # return nothing\n return nothing\nend\nfunction removeSite!(unitcell::Unitcell, index::Int64)\n # delete the element from the positions list\n deleteat!(unitcell.basis, index)\n # delete all connections that touch the removed site\n deleteat!(unitcell.connections, [c[1]==index || c[2]==index for c in unitcell.connections])\n # now shift all indices in the connections array by 1\n for (i,c) in enumerate(unitcell.connections)\n if Int(c[1]) > index\n c[1] = Int(c[1]) - 1\n end\n if Int(c[2]) > index\n c[2] = Int(c[2]) - 1\n end\n end\n # return nothing\n return nothing\nend\nexport removeSite!\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n################################################################################\n#\n# 3) CONNECTION STRENGTH MODIFICATION\n# - all connections\n# - mapping of strengths\n# - evaluate strengths\n# - optimize connections\n#\n################################################################################\n\n\n\n\n\n#-----------------------------------------------------------------------------------------------------------------------------\n#\n# Set / Map interaction strengths of the unitcell / lattice\n#\n#-----------------------------------------------------------------------------------------------------------------------------\n\"\"\"\n setAllInteractionStrengths!(unitcell::Unitcell, strength)\n setAllInteractionStrengths!(lattice::Lattice, strength)\n\nFunction to overwrite ALL connection strength values of either a `Unitcell` object or a `Lattice` object\nwith the value `strength`.\n\nNOTE: This function modifies the given object and does not create a copy.\n\n\n# Examples\n\n```julia-repl\njulia> setAllInteractionStrengths!(unitcell, \"tx\")\n\njulia> setAllInteractionStrengths!(lattice, 1.0)\n\n```\n\"\"\"\nfunction setAllInteractionStrengths!(unitcell::Unitcell, strength)\n # go through all connections and modify their strength\n for c in unitcell.connections\n c[3] = strength\n end\n # return nothing\n return nothing\nend\nfunction setAllInteractionStrengths!(lattice::Lattice, strength)\n # go through all connections and modify their strength\n for c in lattice.connections\n c[3] = strength\n end\n # return nothing\n return nothing\nend\nexport setAllInteractionStrengths!\n\n\n\n\n\n\"\"\"\n mapInteractionStrengths!(unitcell::Unitcell, mapping::Dict [; replace_in_strings::Bool=false, evaluate::Bool=false])\n mapInteractionStrengths!(lattice::Lattice, mapping::Dict [; replace_in_strings::Bool=false, evaluate::Bool=false])\n\nFunction to map connection strength values of either a `Unitcell` object or a `Lattice` object\nby replacing them along keys of a dictonary `mapping`.\n\nFurthermore, to be able to resolve strengths like `\"tx*ty\"` (`String` valued) to a `Float64` value one can use the following two steps:\n1) chosing `replace_in_strings=true` to also search for mapping keys in `String` connection strengths.\n2) chosing `evaluate=true` to evaluate every `String` connection strength by `eval(parse(.))` after all replacement has taken place.\n\nNOTE: This function modifies the given object and does not create a copy.\n\n\n# Examples\n\nExample mapping could read\n\n mapping = Dict(\"tx\"=>1.0, \"ty\"=>1.0, \"tz\"=>2.0)\n\nwhich modifies all `String` valued connection strengths `\"tx\"`, `\"ty\"` and `\"tz\"` to be `Float64` with values `1.0` and `2.0`\n\n```julia-repl\njulia> mapInteractionStrengths!(unitcell, mapping)\n\njulia> mapInteractionStrengths!(lattice, mapping, replace_in_strings=true)\n\n```\n\"\"\"\nfunction mapInteractionStrengths!(unitcell::Unitcell, mapping::Dict; replace_in_strings::Bool=false, evaluate::Bool=false)\n # get the old strengths\n old_strengths = keys(mapping)\n # iterate for replacement\n for old_strength in old_strengths\n # new strength is given by mapping\n new_strength = mapping[old_strength]\n # check all connections that are identical\n for c in unitcell.connections\n if c[3] == old_strength\n c[3] = new_strength\n end\n end\n # check for string replacement\n if replace_in_strings\n for c in unitcell.connections\n if typeof(c[3]) == String && contains(c[3], old_strength)\n c[3] = replace(c[3], old_strength, new_strength)\n end\n end\n end\n end\n # maybe even evaluate\n if evaluate\n for c in unitcell.connections\n if typeof(c[3]) == String\n c[3] = eval(parse(c[3]))\n end\n end\n end\n # return nothing\n return nothing\nend\nfunction mapInteractionStrengths!(lattice::Lattice, mapping::Dict; replace_in_strings::Bool=false, evaluate::Bool=false)\n # get the old strengths\n old_strengths = keys(mapping)\n # iterate for replacement\n for old_strength in old_strengths\n # new strength is given by mapping\n new_strength = mapping[old_strength]\n # check all connections that are identical\n for c in lattice.connections\n if c[3] == old_strength\n c[3] = new_strength\n end\n end\n # check for string replacement\n if replace_in_strings\n for c in lattice.connections\n if typeof(c[3]) == String && contains(c[3], old_strength)\n c[3] = replace(c[3], old_strength, new_strength)\n end\n end\n end\n end\n # maybe even evaluate\n if evaluate\n for c in lattice.connections\n if typeof(c[3]) == String\n c[3] = eval(parse(c[3]))\n end\n end\n end\n # return nothing\n return nothing\nend\nexport mapInteractionStrengths!\n\n\n\n\n\n\n\"\"\"\n evaluateInteractionStrengths!(unitcell::Unitcell [, parameters::Dict])\n evaluateInteractionStrengths!(lattice::Lattice [, parameters::Dict])\n\nFunction to evaluate connection strength values of either a `Unitcell` object or a `Lattice` object\nby first optionally replacing them along keys of a dictonary `parameters` and then calling `eval(parse(.))`.\n\nNOTE: This function modifies the given object and does not create a copy.\n\n\n# Examples\n\nExample parameters could read\n\n parameters = Dict(\"tx\"=>1.0, \"ty\"=>1.0, \"tz\"=>2.0)\n\nwhich modifies all `String` valued connection strengths `\"tx\"`, `\"ty\"` and `\"tz\"` to be `Float64` with values `1.0` and `2.0`\n\n```julia-repl\njulia> evaluateInteractionStrengths!(unitcell)\n\njulia> evaluateInteractionStrengths!(lattice, parameters)\n\n```\n\"\"\"\nfunction evaluateInteractionStrengths!(unitcell::Unitcell, parameters::Dict=Dict())\n # just call the mapping functions\n mapInteractionStrengths!(unitcell, parameters, replace_in_strings=true, evaluate=true)\nend\nfunction evaluateInteractionStrengths!(lattice::Lattice, parameters::Dict=Dict())\n # just call the mapping functions\n mapInteractionStrengths!(lattice, parameters, replace_in_strings=true, evaluate=true)\nend\nexport evaluateInteractionStrengths!\n\n\n\n\n\n\n#-----------------------------------------------------------------------------------------------------------------------------\n#\n# Optimize the lattice / unitcell by collapsing redundant connections into fewer connections and modify given object\n#\n#-----------------------------------------------------------------------------------------------------------------------------\n\n\"\"\"\n optimizeConnections!(unitcell::Unitcell)\n optimizeConnections!(lattice::Lattice)\n\nFunction to optimize connections of either a `Unitcell` object or a `Lattice` object\nby checking which ones can be compressed and put together.\n\nNOTE: This function modifies the given object and does not create a copy.\n\n\n# Examples\n\n```julia-repl\njulia> optimizeConnections!(unitcell)\n\n```\n\"\"\"\nfunction optimizeConnections!(lattice::Lattice)\n # build up new connections\n connections_new = Array{Any,1}[]\n # go through all old connections to check for redundant entries\n for c in lattice.connections\n # check if the connection already is present in the new list\n found = false\n for c_new in connections_new\n if c[1] == c_new[1] && c[2] == c_new[2] && c[4] == c_new[4]\n # found a redundent connection\n found = true\n # add connection strength\n if typeof(c[3]) == String || typeof(c_new[3]) == String\n c_new[3] = \"$(c_new[3])+$(c[3])\"\n else\n c_new[3] = c_new[3] + c[3]\n end\n # break the inner loop\n break\n end\n end\n # if not, add the current connection\n if !found\n push!(connections_new, c)\n end\n end\n # check if the connection strength is 0\n connections_new_2 = Array{Any,1}[]\n for c in connections_new\n # check if close to 0 connection strength\n if typeof(c[3]) == Float64 || typeof(c[3]) == Int64\n if abs(c[3]) > 1e-18\n push!(connections_new_2, c)\n else\n # do not push! c[3] too small!\n end\n elseif isnull(tryparse(Float64,c[3]))\n # not a float and cannot be parsed to float, just push in list as it is\n push!(connections_new_2, c)\n else\n # check if the strength is non-zero\n if abs(parse(Float64,c[3])) > 1e-18\n push!(connections_new_2, c)\n else\n # do not push! c[3] too small!\n end\n end\n end\n # overwrite the connections in the given lattice\n lattice.connections = connections_new_2\n # return nothing\n return nothing\nend\nfunction optimizeConnections!(unitcell::Unitcell)\n # build up new connections\n connections_new = Array{Any,1}[]\n # go through all old connections to check for redundant entries\n for c in unitcell.connections\n # check if the connection already is present in the new list\n found = false\n for c_new in connections_new\n if c[1] == c_new[1] && c[2] == c_new[2] && c[4] == c_new[4]\n # found a redundent connection\n found = true\n # add connection strength\n if typeof(c[3]) == String || typeof(c_new[3]) == String\n c_new[3] = \"$(c_new[3])+$(c[3])\"\n else\n c_new[3] = c_new[3] + c[3]\n end\n # break the inner loop\n break\n end\n end\n # if not, add the current connection\n if !found\n push!(connections_new, c)\n end\n end\n # check if the connection strength is 0\n connections_new_2 = Array{Any,1}[]\n for c in connections_new\n # check if close to 0 connection strength\n if typeof(c[3]) == Float64 || typeof(c[3]) == Int64\n if abs(c[3]) > 1e-18\n push!(connections_new_2, c)\n else\n # do not push! c[3] too small!\n end\n elseif isnull(tryparse(Float64,c[3]))\n # not a float and cannot be parsed to float, just push in list as it is\n push!(connections_new_2, c)\n else\n # check if the strength is non-zero\n if abs(parse(Float64,c[3])) > 1e-18\n push!(connections_new_2, c)\n else\n # do not push! c[3] too small!\n end\n end\n end\n # overwrite the connections in the given lattice\n unitcell.connections = connections_new_2\n # return nothing\n return nothing\nend\nexport optimizeConnections!\n\n\n\n\n\n\n\n################################################################################\n#\n# 4) REAL SPACE ROTATION / SCALING / SHIFTING\n# - Rotation around some axis\n# - Scaling along some axis\n# - Global (isotropic) scaling\n# - Global (isotropic) scaling to mean / minimum bond length\n# - Shifting along some axis\n# - Shifting along some lattice vector\n# - Shifting center of lattice to origin\n#\n################################################################################\n\n\n\n\n###################\n# ROTATION\n###################\n\n\n# ROTATION AROUND X AXIS\nfunction rotateAroundXAxis!(unitcell::Unitcell, angle::Float64)\n # rotate the lattice vectors\n for lv in unitcell.lattice_vectors\n # rotate and overwrite simulateously all components\n lv[2], lv[3] = cos(angle)*lv[2] + sin(angle)*lv[3] , -sin(angle)*lv[2] + cos(angle)*lv[3]\n end\n # rotate the basis sites\n for bs in unitcell.basis\n # rotate and overwrite simulateously all components\n bs[2], bs[3] = cos(angle)*bs[2] + sin(angle)*bs[3] , -sin(angle)*bs[2] + cos(angle)*bs[3]\n end\nend\nfunction rotateAroundXAxis!(lattice::Lattice, angle::Float64)\n # rotate the lattice vectors\n for lv in lattice.lattice_vectors\n # rotate and overwrite simulateously all components\n lv[2], lv[3] = cos(angle)*lv[2] + sin(angle)*lv[3] , -sin(angle)*lv[2] + cos(angle)*lv[3]\n end\n # rotate the basis sites\n for p in lattice.positions\n # rotate and overwrite simulateously all components\n p[2], p[3] = cos(angle)*p[2] + sin(angle)*p[3] , -sin(angle)*p[2] + cos(angle)*p[3]\n end\nend\nexport rotateAroundXAxis!\n\nfunction rotateAroundXAxisDeg!(unitcell::Unitcell, angle::Float64)\n rotateAroundXAxis!(unitcell, angle*pi/180.0)\nend\nfunction rotateAroundXAxisDeg!(lattice::Lattice, angle::Float64)\n rotateAroundXAxis!(lattice, angle*pi/180.0)\nend\nexport rotateAroundXAxisDeg!\n\n\n# ROTATION AROUND Y AXIS\nfunction rotateAroundYAxis!(unitcell::Unitcell, angle::Float64)\n # rotate the lattice vectors\n for lv in unitcell.lattice_vectors\n # rotate and overwrite simulateously all components\n lv[3], lv[1] = cos(angle)*lv[3] + sin(angle)*lv[1] , -sin(angle)*lv[3] + cos(angle)*lv[1]\n end\n # rotate the basis sites\n for bs in unitcell.basis\n # rotate and overwrite simulateously all components\n bs[3], bs[1] = cos(angle)*bs[3] + sin(angle)*bs[1] , -sin(angle)*bs[3] + cos(angle)*bs[1]\n end\nend\nfunction rotateAroundYAxis!(lattice::Lattice, angle::Float64)\n # rotate the lattice vectors\n for lv in lattice.lattice_vectors\n # rotate and overwrite simulateously all components\n lv[3], lv[1] = cos(angle)*lv[3] + sin(angle)*lv[1] , -sin(angle)*lv[3] + cos(angle)*lv[1]\n end\n # rotate the basis sites\n for p in lattice.positions\n # rotate and overwrite simulateously all components\n p[3], p[1] = cos(angle)*p[3] + sin(angle)*p[1] , -sin(angle)*p[3] + cos(angle)*p[1]\n end\nend\nexport rotateAroundYAxis!\n\nfunction rotateAroundYAxisDeg!(unitcell::Unitcell, angle::Float64)\n rotateAroundYAxis!(unitcell, angle*pi/180.0)\nend\nfunction rotateAroundYAxisDeg!(lattice::Lattice, angle::Float64)\n rotateAroundYAxis!(lattice, angle*pi/180.0)\nend\nexport rotateAroundYAxisDeg!\n\n\n# ROTATION AROUND Z AXIS\nfunction rotateAroundZAxis!(unitcell::Unitcell, angle::Float64)\n # rotate the lattice vectors\n for lv in unitcell.lattice_vectors\n # rotate and overwrite simulateously all components\n lv[1], lv[2] = cos(angle)*lv[1] + sin(angle)*lv[2] , -sin(angle)*lv[1] + cos(angle)*lv[2]\n end\n # rotate the basis sites\n for bs in unitcell.basis\n # rotate and overwrite simulateously all components\n bs[1], bs[2] = cos(angle)*bs[1] + sin(angle)*bs[2] , -sin(angle)*bs[1] + cos(angle)*bs[2]\n end\nend\nfunction rotateAroundZAxis!(lattice::Lattice, anglTODOe::Float64)\n # rotate the lattice vectors\n for lv in lattice.lattice_vectors\n # rotate and overwrite simulateously all components\n lv[1], lv[2] = cos(angle)*lv[1] + sin(angle)*lv[2] , -sin(angle)*lv[1] + cos(angle)*lv[2]\n end\n # rotate the basis sites\n for p in lattice.positions\n # rotate and overwrite simulateously all components\n p[1], p[2] = cos(angle)*p[1] + sin(angle)*p[2] , -sin(angle)*p[1] + cos(angle)*p[2]\n end\nend\nexport rotateAroundZAxis!\n\nfunction rotateAroundZAxisDeg!(unitcell::Unitcell, angle::Float64)\n rotateAroundZAxis!(unitcell, angle*pi/180.0)\nend\nfunction rotateAroundZAxisDeg!(lattice::Lattice, angle::Float64)\n rotateAroundZAxis!(lattice, angle*pi/180.0)\nend\nexport rotateAroundZAxisDeg!\n\n\n\n\n\n###################\n# SCALING\n###################\n\n# SCALING ALONG X AXIS\nfunction scaleAlongXAxis!(unitcell::Unitcell, factor::Float64)\n # scale all lattice vectors\n for l in unitcell.lattice_vectors\n l[1] *= factor\n end\n # scale all positions\n for p in unitcell.basis\n p[1] *= factor\n end\nend\nfunction scaleAlongXAxis!(lattice::Lattice, factor::Float64)\n # scale all lattice vectors\n for l in lattice.lattice_vectors\n l[1] *= factor\n end\n # scale all positions\n for p in lattice.positions\n p[1] *= factor\n end\nend\nexport scaleAlongXAxis!\n\n# SCALING ALONG Y AXIS\nfunction scaleAlongYAxis!(unitcell::Unitcell, factor::Float64)\n # scale all lattice vectors\n for l in unitcell.lattice_vectors\n l[2] *= factor\n end\n # scale all positions\n for p in unitcell.basis\n p[2] *= factor\n end\nend\nfunction scaleAlongYAxis!(lattice::Lattice, factor::Float64)\n # scale all lattice vectors\n for l in lattice.lattice_vectors\n l[2] *= factor\n end\n # scale all positions\n for p in lattice.positions\n p[2] *= factor\n end\nend\nexport scaleAlongYAxis!\n\n# SCALING ALONG Z AXIS\nfunction scaleAlongZAxis!(unitcell::Unitcell, factor::Float64)\n # scale all lattice vectors\n for l in unitcell.lattice_vectors\n l[3] *= factor\n end\n # scale all positions\n for p in unitcell.basis\n p[3] *= factor\n end\nend\nfunction scaleAlongZAxis!(lattice::Lattice, factor::Float64)\n # scale all lattice vectors\n for l in lattice.lattice_vectors\n l[3] *= factor\n end\n # scale all positions\n for p in lattice.positions\n p[3] *= factor\n end\nend\nexport scaleAlongZAxis!\n\n\n# SCALING ISOTROPIC\nfunction scaleIsotropic!(unitcell::Unitcell, factor::Float64)\n # scale all lattice vectors\n for l in unitcell.lattice_vectors\n l .*= factor\n end\n # scale all positions\n for p in unitcell.basis\n p .*= factor\n end\nend\nfunction scaleIsotropic!(lattice::Lattice, factor::Float64)\n # scale all lattice vectors\n for l in lattice.lattice_vectors\n l .*= factor\n end\n # scale all positions\n for p in lattice.positions\n p .*= factor\n end\nend\nexport scaleIsotropic!\n\n\n# SCALING TO MEAN BOND LENGTH\nfunction scaleToMeanBondLength!(unitcell::Unitcell, bond_length::Float64=1.0)\n # get all bond lengths\n bond_lengths = zeros(length(unitcell.connections))\n for i in 1:length(bond_lengths)\n # get the connection\n c = unitcell.connections[i]\n # get the connecting vector\n c_vector = unitcell.basis[Int(c[2])] .- unitcell.basis[Int(c[1])]\n for (j,l) in enumerate(unitcell.lattice_vectors)\n c_vector .+= l.*c[4][j]\n end\n # get how long it is\n bond_lengths[i] = sqrt(sum(c_vector.*c_vector))\n end\n # calculate the mean bond length\n mean_bond_length = mean(bond_lengths)\n # calculate how the scale factor looks like\n factor = bond_length / mean_bond_length\n # scale the object\n scaleIsotropic!(unitcell, factor)\nend\nfunction scaleToMeanBondLength!(lattice::Lattice, bond_length::Float64=1.0)\n # get all bond lengths\n bond_lengths = zeros(length(lattice.connections))\n for i in 1:length(bond_lengths)\n # get the connection\n c = lattice.connections[i]\n # get the connecting vector\n c_vector = lattice.positions[Int(c[2])] .- lattice.positions[Int(c[1])]\n for (j,l) in enumerate(lattice.lattice_vectors)\n c_vector .+= l.*c[4][j]\n end\n # get how long it is\n bond_lengths[i] = sqrt(sum(c_vector.*c_vector))\n end\n # calculate the mean bond length\n mean_bond_length = mean(bond_lengths)\n # calculate how the scale factor looks like\n factor = bond_length / mean_bond_length\n # scale the object\n scaleIsotropic!(lattice, factor)\nend\nexport scaleToMeanBondLength!\n\n# SCALING TO MINIMUM BOND LENGTH\nfunction scaleToMinimumBondLength!(unitcell::Unitcell, bond_length::Float64=1.0)\n # get all bond lengths\n bond_lengths = zeros(length(unitcell.connections))\n for i in 1:length(bond_lengths)\n # get the connection\n c = unitcell.connections[i]\n # get the connecting vector\n c_vector = unitcell.basis[Int(c[2])] .- unitcell.basis[Int(c[1])]\n for (j,l) in enumerate(unitcell.lattice_vectors)\n c_vector .+= l.*c[4][j]\n end\n # get how long it is\n bond_lengths[i] = sqrt(sum(c_vector.*c_vector))\n end\n # calculate the minimum bond length\n minimum_bond_length = minimum(bond_lengths)\n # calculate how the scale factor looks like\n factor = bond_length / minimum_bond_length\n # scale the object\n scaleIsotropic!(unitcell, factor)\nend\nfunction scaleToMinimumBondLength!(lattice::Lattice, bond_length::Float64=1.0)\n # get all bond lengths\n bond_lengths = zeros(length(lattice.connections))\n for i in 1:length(bond_lengths)\n # get the connection\n c = lattice.connections[i]\n # get the connecting vector\n c_vector = lattice.positions[Int(c[2])] .- lattice.positions[Int(c[1])]\n for (j,l) in enumerate(lattice.lattice_vectors)\n c_vector .+= l.*c[4][j]\n end\n # get how long it is\n bond_lengths[i] = sqrt(sum(c_vector.*c_vector))\n end\n # calculate the minimum bond length\n minimum_bond_length = minimum(bond_lengths)\n # calculate how the scale factor looks like\n factor = bond_length / minimum_bond_length\n # scale the object\n scaleIsotropic!(lattice, factor)\nend\nexport scaleToMinimumBondLength!\n\n\n\n\n\n###################\n# SHIFTING\n###################\n\n\n# SHIFT ALONG X AXIS\nfunction shiftAlongXAxis!(unitcell::Unitcell, offset::Float64)\n # shift all positions\n for p in unitcell.basis\n p[1] += offset\n end\nend\nfunction shiftAlongXAxis!(lattice::Lattice, offset::Float64)\n # shift all positions\n for p in lattice.positions\n p[1] += offset\n end\nend\nexport shiftAlongXAxis!\n\n# SHIFT ALONG Y AXIS\nfunction shiftAlongYAxis!(unitcell::Unitcell, offset::Float64)\n # shift all positions\n for p in unitcell.basis\n p[2] += offset\n end\nend\nfunction shiftAlongYAxis!(lattice::Lattice, offset::Float64)\n # shift all positions\n for p in lattice.positions\n p[2] += offset\n end\nend\nexport shiftAlongYAxis!\n\n# SHIFT ALONG Z AXIS\nfunction shiftAlongZAxis!(unitcell::Unitcell, offset::Float64)\n # shift all positions\n for p in unitcell.basis\n p[3] += offset\n end\nend\nfunction shiftAlongZAxis!(lattice::Lattice, offset::Float64)\n # shift all positions\n for p in lattice.positions\n p[3] += offset\n end\nend\nexport shiftAlongZAxis!\n\n\n# SHIFT BY VECTOR\nfunction shiftByVector!(unitcell::Unitcell, vector::Array{Float64,1})\n # shift all positions\n for p in unitcell.basis\n p .+= vector\n end\nend\nfunction shiftByVector!(lattice::Lattice, vector::Array{Float64,1})\n # shift all positions\n for p in lattice.positions\n p .+= vector\n end\nend\nexport shiftByVector!\n\n\n# SHIFT ALONG ANY LATTICE VECTOR\nfunction shiftAlongLatticeVector!(unitcell::Unitcell, lattice_vector::Int64, offset::Float64)\n # define a vector for shifting\n vector = unitcell.lattice_vectors[lattice_vector] .* (offset / sqrt(sum(unitcell.lattice_vectors[lattice_vector].*unitcell.lattice_vectors[lattice_vector])))\n # shift by that vector\n shiftByVector!(unitcell, vector)\nend\nfunction shiftAlongLatticeVector!(lattice::Lattice, lattice_vector::Int64, offset::Float64)\n # define a vector for shifting\n vector = lattice.lattice_vectors[lattice_vector] .* (offset / sqrt(sum(lattice.lattice_vectors[lattice_vector].*lattice.lattice_vectors[lattice_vector])))\n # shift by that vector\n shiftByVector!(lattice, vector)\nend\nexport shiftAlongLatticeVector!\n\n\n# SHIFT ALONG A1\nfunction shiftAlongA1!(unitcell::Unitcell, offset::Float64)\n # shift along the first lattice vector\n shiftAlongLatticeVector!(unitcell, 1, offset)\nend\nfunction shiftAlongA1!(lattice::Lattice, offset::Float64)\n # shift along the first lattice vector\n shiftAlongLatticeVector!(lattice, 1, offset)\nend\nexport shiftAlongA1!\n\n# SHIFT ALONG A2\nfunction shiftAlongA2!(unitcell::Unitcell, offset::Float64)\n # shift along the second lattice vector\n shiftAlongLatticeVector!(unitcell, 2, offset)\nend\nfunction shiftAlongA2!(lattice::Lattice, offset::Float64)\n # shift along the second lattice vector\n shiftAlongLatticeVector!(lattice, 2, offset)\nend\nexport shiftAlongA2!\n\n# SHIFT ALONG A3\nfunction shiftAlongA3!(unitcell::Unitcell, offset::Float64)\n # shift along the third lattice vector\n shiftAlongLatticeVector!(unitcell, 3, offset)\nend\nfunction shiftAlongA3!(lattice::Lattice, offset::Float64)\n # shift along the third lattice vector\n shiftAlongLatticeVector!(lattice, 3, offset)\nend\nexport shiftAlongA3!\n\n\n# SHIFT ALONG ANY LATTICE VECTOR (Relative)\nfunction shiftAlongLatticeVectorRelative!(unitcell::Unitcell, lattice_vector::Int64, offset::Float64)\n # define a vector for shifting\n vector = unitcell.lattice_vectors[lattice_vector] .* offset\n # shift by that vector\n shiftByVector!(unitcell, vector)\nend\nfunction shiftAlongLatticeVectorRelative!(lattice::Lattice, lattice_vector::Int64, offset::Float64)\n # define a vector for shifting\n vector = lattice.lattice_vectors[lattice_vector] .* offset\n # shift by that vector\n shiftByVector!(lattice, vector)\nend\nexport shiftAlongLatticeVectorRelative!\n\n\n# SHIFT ALONG A1 (Relative)\nfunction shiftAlongA1Relative!(unitcell::Unitcell, offset::Float64)\n # shift along the first lattice vector\n shiftAlongLatticeVectorRelative!(unitcell, 1, offset)\nend\nfunction shiftAlongA1Relative!(lattice::Lattice, offset::Float64)\n # shift along the first lattice vector\n shiftAlongLatticeVectorRelative!(lattice, 1, offset)\nend\nexport shiftAlongA1Relative!\n\n# SHIFT ALONG A2 (Relative)\nfunction shiftAlongA2Relative!(unitcell::Unitcell, offset::Float64)\n # shift along the second lattice vector\n shiftAlongLatticeVectorRelative!(unitcell, 2, offset)\nend\nfunction shiftAlongA2Relative!(lattice::Lattice, offset::Float64)\n # shift along the second lattice vector\n shiftAlongLatticeVectorRelative!(lattice, 2, offset)\nend\nexport shiftAlongA2Relative!\n\n# SHIFT ALONG A3 (Relative)\nfunction shiftAlongA3Relative!(unitcell::Unitcell, offset::Float64)\n # shift along the third lattice vector\n shiftAlongLatticeVectorRelative!(unitcell, 3, offset)\nend\nfunction shiftAlongA3Relative!(lattice::Lattice, offset::Float64)\n # shift along the third lattice vector\n shiftAlongLatticeVectorRelative!(lattice, 3, offset)\nend\nexport shiftAlongA3Relative!\n\n\n\n# SHIFT CENTER TO ORIGIN\nfunction shiftCenterToOrigin!(unitcell::Unitcell)\n # look for the central point\n center = unitcell.basis .* 0.0\n for p in unitcell.basis\n center .+= p\n end\n center ./= length(unitcell.basis)\n # shift by negative of that vector\n shiftByVector!(unitcell, center.*(-1))\nend\nfunction shiftCenterToOrigin!(lattice::Lattice)\n # look for the central point\n center = lattice.positions .* 0.0\n for p in lattice.positions\n center .+= p\n end\n center ./= length(lattice.positions)\n # shift by negative of that vector\n shiftByVector!(lattice, center.*(-1))\nend\nexport shiftCenterToOrigin!\n\n\n\n\n\n\n\n\n\n\n\n\n################################################################################\n#\n# 5) LATTICE VECTOR OPTIMIZATION\n#\n################################################################################\n\n# Function to optimize lattice vectors\nfunction optimizeLatticeVectors2D!(unitcell::Unitcell; verbose::Bool=false)\n # init the loop by assuming one refolded a vector\n refolded_one_vector = true\n # as long as one vector was refolded, repeat this loop\n while refolded_one_vector\n # init inside the loop by assuming one did not refold a vector\n refolded_one_vector = false\n # try a1\n if dot(unitcell.lattice_vectors[1],unitcell.lattice_vectors[1]) > dot(unitcell.lattice_vectors[1].-unitcell.lattice_vectors[2], unitcell.lattice_vectors[1].-unitcell.lattice_vectors[2])\n # print\n if verbose\n println(\"a1 --> a1 - a2\")\n end\n # change the lattice vector\n unitcell.lattice_vectors[1] = unitcell.lattice_vectors[1] .- unitcell.lattice_vectors[2]\n # change all connections\n for c in unitcell.connections\n if c[4][1] != 0\n c[4] = (c[4][1], c[4][2]+c[4][1])\n end\n end\n # did refold\n refolded_one_vector = true\n end\n if dot(unitcell.lattice_vectors[1],unitcell.lattice_vectors[1]) > dot(unitcell.lattice_vectors[1].+unitcell.lattice_vectors[2], unitcell.lattice_vectors[1].+unitcell.lattice_vectors[2])\n # print\n if verbose\n println(\"a1 --> a1 + a2\")\n end\n # change the lattice vector\n unitcell.lattice_vectors[1] = unitcell.lattice_vectors[1] .+ unitcell.lattice_vectors[2]\n # change all connections\n for c in unitcell.connections\n if c[4][1] != 0\n c[4] = (c[4][1], c[4][2]-c[4][1])\n end\n end\n # did refold\n refolded_one_vector = true\n end\n # try a2\n if dot(unitcell.lattice_vectors[2],unitcell.lattice_vectors[2]) > dot(unitcell.lattice_vectors[2].-unitcell.lattice_vectors[1], unitcell.lattice_vectors[2].-unitcell.lattice_vectors[1])\n # print\n if verbose\n println(\"a2 --> a2 - a1\")\n end\n # change the lattice vector\n unitcell.lattice_vectors[2] = unitcell.lattice_vectors[2] .- unitcell.lattice_vectors[1]\n # change all connections\n for c in unitcell.connections\n if c[4][2] != 0\n c[4] = (c[4][1]+c[4][2], c[4][2])\n end\n end\n # did refold\n refolded_one_vector = true\n end\n if dot(unitcell.lattice_vectors[2],unitcell.lattice_vectors[2]) > dot(unitcell.lattice_vectors[2].+unitcell.lattice_vectors[1], unitcell.lattice_vectors[2].+unitcell.lattice_vectors[1])\n # print\n if verbose\n println(\"a2 --> a2 + a1\")\n end\n # change the lattice vector\n unitcell.lattice_vectors[2] = unitcell.lattice_vectors[2] .+ unitcell.lattice_vectors[1]\n # change all connections\n for c in unitcell.connections\n if c[4][2] != 0\n c[4] = (c[4][1]-c[4][2], c[4][2])\n end\n end\n # did refold\n refolded_one_vector = true\n end\n end\nend\n\n# Function to optimize lattice vectors\nfunction optimizeLatticeVectors3D!(unitcell::Unitcell; verbose::Bool=false)\n # init the loop by assuming one refolded a vector\n refolded_one_vector = true\n # as long as one vector was refolded, repeat this loop\n while refolded_one_vector\n # init inside the loop by assuming one did not refold a vector\n refolded_one_vector = false\n # try all combinations of the remaining two lattice vectors\n for comb in Array{Int64,1}[[1,0], [-1,0], [0,1], [0,-1], [1,1], [1,-1], [-1,1], [-1,-1]]\n # try a1\n a1p = unitcell.lattice_vectors[1] .+ comb[1].*unitcell.lattice_vectors[2] .+ comb[2].*unitcell.lattice_vectors[3]\n # check if this is closer\n if dot(unitcell.lattice_vectors[1],unitcell.lattice_vectors[1]) > dot(a1p, a1p)\n # print\n if verbose\n println(\"a1 --> a1 + $(comb[1])*a2 + $(comb[2])*a3\")\n end\n # change the lattice vector\n unitcell.lattice_vectors[1] = a1p\n # change all connections\n for c in unitcell.connections\n c[4] = (c[4][1], c[4][2]-c[4][1]*comb[1], c[4][3]-c[4][1]*comb[2])\n end\n # did refold\n refolded_one_vector = true\n end\n # try a2\n a2p = unitcell.lattice_vectors[2] .+ comb[1].*unitcell.lattice_vectors[1] .+ comb[2].*unitcell.lattice_vectors[3]\n # check if this is closer\n if dot(unitcell.lattice_vectors[2],unitcell.lattice_vectors[2]) > dot(a2p, a2p)\n # print\n if verbose\n println(\"a2 --> a2 + $(comb[1])*a1 + $(comb[2])*a3\")\n end\n # change the lattice vector\n unitcell.lattice_vectors[2] = a2p\n # change all connections\n for c in unitcell.connections\n c[4] = (c[4][1]-c[4][2]*comb[1], c[4][2], c[4][3]-c[4][2]*comb[2])\n end\n # did refold\n refolded_one_vector = true\n end\n # try a3\n a3p = unitcell.lattice_vectors[3] .+ comb[1].*unitcell.lattice_vectors[1] .+ comb[2].*unitcell.lattice_vectors[2]\n # check if this is closer\n if dot(unitcell.lattice_vectors[3],unitcell.lattice_vectors[3]) > dot(a3p, a3p)\n # print\n if verbose\n println(\"a3 --> a3 + $(comb[1])*a1 + $(comb[2])*a2\")\n end\n # change the lattice vector\n unitcell.lattice_vectors[3] = a3p\n # change all connections\n for c in unitcell.connections\n c[4] = (c[4][1]-c[4][3]*comb[1], c[4][2]-c[4][3]*comb[2], c[4][3])\n end\n # did refold\n refolded_one_vector = true\n end\n end\n end\nend\n\n# general function\nfunction optimizeLatticeVectors!(unitcell::Unitcell; verbose::Bool=false)\n if length(unitcell.lattice_vectors) == 2\n return optimizeLatticeVectors2D!(unitcell, verbose=verbose)\n elseif length(unitcell.lattice_vectors) == 3\n return optimizeLatticeVectors3D!(unitcell, verbose=verbose)\n else\n # DO NOTHING\n end\nend\nexport optimizeLatticeVectors!\n", "meta": {"hexsha": "547223340cf429e88eaba760cb8dcf955e8090af", "size": 47684, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src_06/LatticePhysics_lattice_modification.jl", "max_stars_repo_name": "crstnbr/LatticePhysics.jl", "max_stars_repo_head_hexsha": "6ea9c4533bba973354a7fb96aadc4ab08aca8524", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-01-25T12:31:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T13:36:59.000Z", "max_issues_repo_path": "src_06/LatticePhysics_lattice_modification.jl", "max_issues_repo_name": "crstnbr/LatticePhysics.jl", "max_issues_repo_head_hexsha": "6ea9c4533bba973354a7fb96aadc4ab08aca8524", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-08-02T18:25:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-02T18:25:07.000Z", "max_forks_repo_path": "src_06/LatticePhysics_lattice_modification.jl", "max_forks_repo_name": "crstnbr/LatticePhysics.jl", "max_forks_repo_head_hexsha": "6ea9c4533bba973354a7fb96aadc4ab08aca8524", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-10-05T00:58:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-09T19:49:37.000Z", "avg_line_length": 32.8402203857, "max_line_length": 193, "alphanum_fraction": 0.622850432, "num_tokens": 12140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24016286993479338}} {"text": "# A Using Case:\n\"\"\"\nyao> nbits(4)\n\nyao> cc = begin\n 2 => X\n 3 => C, 1=>C, 4=>X\nend\n\nyao> nbits(6)\n\nyao> dc = begin\n subroutine(1,5,2,3) cc\n 3=>Rx(:θ) # symbolic input\nend\n\nyao> reg = bit\"000000\"\n\nyao> reg |> d\n\nyao> p(rintln) reg\n\nyao> p(rintln) c # print summary\n\nyao> s(how) reg\n\nyao> c(ode) s reg\n\nyao> m(easure!) [op] reg\n\nyao> reset!(reg, 0)\n\nyao> e(xpect) dc reg\n\nyao> e(xpect)' dc reg\n\nyao> f(idelity)' reg reg\n\nyao> i(nspect) c # show matrix\n\nyao> l(istvars) # list symbol table\n\nyao> q(uit)\n\"\"\"\n\nCmdTable = Dict(\n # query\n 'p'=>\"print\",\n 'i'=>\"inspect\",\n # compute\n 'e'=>\"expect\",\n 'f'=>\"fidelity\",\n 'r'=>\"reset\",\n 'm'=>\"measure\",\n # interactive command\n 'l'=>\"listvars\",\n 'h'=>\"help_repl\",\n)\n\nstruct YaoREPLState\n regs::Dict{Symbol,Any}\n blocks::Dict{Symbol,Any}\n parseinfo::YaoBlocks.ParseInfo\nend\nYaoREPLState() = YaoREPLState(Dict{Symbol,Any}(), Dict{Symbol,Any}(), YaoBlocks.ParseInfo(-1, \"\"))\n\nfunction _checkfunc(f)\n sf = string(f)\n if sf in values(CmdTable)\n return f\n elseif sf[end] == '!' && sf[1:end-1] in values(CmdTable)\n return f\n else\n error(\"Expression `$f` can not be parsed to a known function!\")\n end\nend\n\n\"\"\"\nexpand shortcuts.\n\"\"\"\nfunction yaorepl_parse(str)\n length(str) == 0 && return nothing\n str = strip(str, [' ', '\\n'])\n if haskey(CmdTable, str[1]) && (length(str) == 1 || str[2] in [' ', '!', '\\''])\n args = filter(x-> x!=\"\", split(str, ' '))\n func = get(CmdTable, args[1][1], \"noshortcut\")\n str = func*args[1][2:end]*'('*join(args[2:end], \", \")*')'\n end\n Meta.parse(str)\nend\n\nyaorepl_trans(ex, state) = @match ex begin\n :($x = zero_state($nbit, nbatch=$nbatch)) => :($x = zero_state($(_checkbit(nbit)), nbatch=$(_checkbatch(nbatch))))\n :($x = zero_state($nbit)) => :($x = zero_state($(_checkbit(nbit))))\n :($x = rand_state($nbit, nbatch=$nbatch)) => :($x = rand_state($(_checkbit(nbit)), nbatch=$(_checkbatch(nbatch))))\n :($x = rand_state($nbit)) => :($x = rand_state($(_checkbit(nbit))))\n :($x = [$(args...)]) => :($x = ArrayReg(ComplexF64[$(Float64.(args)...)]))\n :($x = @bit_str $line $val) => :($x = ArrayReg(@bit_str $(_checkbit(val))))\n :($x = $ex) => begin\n blk = YaoBlocks.parse_ex(ex, state.parseinfo)\n :($x = $blk)\n end\n :(expect($a, $b=>$c)) => :(expect($(_checkop(a)), $(_checkreg(b))=>$(_checkop(c))))\n :(expect'($a, $b=>$c)) => :(expect'($(_checkop(a)), $(_checkreg(b))=>$(_checkop(c))))\n :(expect($a, $b)) => :(expect($(_checkop(a)), $(_checkreg(b))))\n :(expect'($a, $b)) => :(expect'($(_checkop(a)), $(_checkreg(b))))\n :(fidelity($a=>$oa, $b=>$ob)) => :(fidelity($(_checkreg(a))=>$(_checkop(oa)), $(_checkreg(b))=>$(_checkop(ob))))\n :(fidelity'($a=>$oa, $b=>$ob)) => :(fidelity'($(_checkreg(a))=>$(_checkop(oa)), $(_checkreg(b))=>$(_checkop(ob))))\n :(fidelity($a, $b)) => :(fidelity($(_checkreg(a)), $(_checkreg(b))))\n :(fidelity'($a, $b)) => :(fidelity'($(_checkreg(a)), $(_checkreg(b))))\n :(measure($a)) => :(measure($(_checkreg(a))))\n :(measure($a, nshots=$nshots)) => :(measure($(_checkreg(a)), nshots=$(_checkshots(nshots))))\n :(measure($op, $a)) => :(measure($(_checkop(op)), $(_checkreg(a))))\n :(measure($op, $a, nshots=$nshots)) => :(measure($(_checkop(op)), $(_checkreg(a)), nshots=$(_checkshots(nshots))))\n :(measure!($a)) => :(measure!($(_checkreg(a))))\n :(measure!($op, $a)) => :(measure!($(_checkop(op)), $(_checkreg(a))))\n :(print($a)) => :(print2str($(_checkreg(a))))\n :(inspect($a)) => :(inspect2str($(_checkreg(a))))\n :($x |> $y) => :(apply!($x, $y))\n\n :(help_repl()) => :(help_repl())\n :(listvars()) => :(listvars($state))\n :(nbits($n)) => :(setnbits!($n, $state))\n :(nbits()) => :(getnbits($state))\n _ => error(\"Expression `$ex` can not be translated!\")\nend\n\nfunction yaorepl_execute(ex, state)\n @match ex begin\n :($x = $expr) => begin\n var = eval(expr)\n if var isa AbstractRegister\n state.regs[Symbol(x)] = var\n elseif var isa AbstractBlock\n state.blocks[Symbol(x)] = var\n else\n error(\"incorrect assignment with return value $var.\")\n end\n \"done\"\n end\n :($f($(args...))) => begin\n nargs = [query_state(state, arg) for arg in args]\n res = eval(:($(_checkfunc(f))($(nargs...))))\n if res isa AbstractString\n res\n elseif res isa Nothing\n \"done\"\n else\n io = IOBuffer()\n Base.show(io, \"text/plain\", res)\n String(take!(io))\n end\n end\n end\nend\n\nfunction query_state(state::YaoREPLState, arg)\n @match arg begin\n :($a => $b) => :($(query_state(state, a)) => $(query_state(state, b)))\n ::Symbol => begin\n if haskey(state.regs, arg)\n state.regs[arg]\n elseif haskey(state.blocks, arg)\n state.blocks[arg]\n else\n arg\n end\n end\n _ => arg\n end\nend\n\nfunction listvars(state)\n regstr = [\"$k ($(nqubits(v)))\" for (k,v) in state.regs]\n blkstr = [\"$k ($(nqubits(v)))\" for (k,v) in state.blocks]\n join([\"current nbits = $(state.parseinfo.nbit)\\n\", \"=== registers ===\", regstr..., \"\\n=== blocks ===\", blkstr...], \"\\n\")\nend\n\nfunction help_repl()\n\"\"\"Guide:\n=== Basic ===\nq: quit\nhelp_repl() | h: print this manual\nc cmd: show the julia code of an expression\nlistvars() | l: list defined register/block table\nnbits(n): set the number of qubits to `n` (used in defining a block)\nnbits(): show the number of qubits\n\n=== Define a Register ===\nreg = rand_state(n): random `n`-qubit state\nreg = zero_state(n): zero state\nreg = bit\"01011\": product state\n\n=== Operations ===\nexpect(op, reg): compute \nexpect'(op, reg[=>c]): compute ∂/∂reg and ∂/∂c\nfidelity(reg1, reg2): compute \nfidelity'(reg1[=>c1], reg2[=>c2]): compute ∂/∂reg1, ∂/∂c1 ...\nreg |> op: apply `op` on `reg`\nmeasure!([op, ]reg) | m! [op] reg: measure `op` inplace.\nmeasure([op, ]reg, [nshots=n]) | m! [op] reg [nshots=n]: measure `op` without collapsing `reg`.\n\n* Note: `n` is integer, `cmd` is command, `reg` is register, `op` is operator or gate (block).\"\"\"\nend\n\nfunction yaorepl_handler(str::AbstractString, state)\n if length(strip(str)) >=2 && strip(str)[1:2] == \"c \"\n string(yaorepl_trans(yaorepl_parse(str[3:end]), state))\n else\n yaorepl_execute(yaorepl_trans(yaorepl_parse(str), state), state)\n end\nend\n", "meta": {"hexsha": "345b0d0078e4690077666c32e237c217283dc588", "size": 6685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/repl/parse.jl", "max_stars_repo_name": "QuantumBFS/YaoExperiment.jl", "max_stars_repo_head_hexsha": "6a8f3f40c1b86eba14d87ddbfbe594a38bddabf8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-24T00:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-24T00:51:58.000Z", "max_issues_repo_path": "src/repl/parse.jl", "max_issues_repo_name": "QuantumBFS/YaoExperiment.jl", "max_issues_repo_head_hexsha": "6a8f3f40c1b86eba14d87ddbfbe594a38bddabf8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/repl/parse.jl", "max_forks_repo_name": "QuantumBFS/YaoExperiment.jl", "max_forks_repo_head_hexsha": "6a8f3f40c1b86eba14d87ddbfbe594a38bddabf8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-25T03:33:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:57:48.000Z", "avg_line_length": 31.3849765258, "max_line_length": 124, "alphanum_fraction": 0.5454001496, "num_tokens": 2178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.511716619597144, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2398879547560083}} {"text": "\"\"\"\nGenX: An Configurable Capacity Expansion Model\nCopyright (C) 2021, Massachusetts Institute of Technology\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\nA complete copy of the GNU General Public License v2 (GPLv2) is available\nin LICENSE.txt. Users uncompressing this from an archive may not have\nreceived this license file. If not, see .\n\"\"\"\n\n@doc raw\"\"\"\n\tconfigure_cplex(solver_settings_path::String)\n\nReads user-specified solver settings from cplex\\_settings.yml in the directory specified by the string solver\\_settings\\_path.\n\nReturns a MathOptInterface OptimizerWithAttributes CPLEX optimizer instance to be used in the GenX.generate_model() method.\n\nThe CPLEX optimizer instance is configured with the following default parameters if a user-specified parameter for each respective field is not provided:\n\n - CPX\\_PARAM\\_EPRHS = 1e-6 (Constraint (primal) feasibility tolerances. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/EpRHS.html)\n - CPX\\_PARAM\\_EPOPT = 1e-6 (Dual feasibility tolerances. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/EpOpt.html)\n - CPX\\_PARAM\\_AGGFILL = 10 (Allowed fill during presolve aggregation. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/AggFill.html)\n - CPX\\_PARAM\\_PREDUAL = 0 (Decides whether presolve should pass the primal or dual linear programming problem to the LP optimization algorithm. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/PreDual.html)\n - CPX\\_PARAM\\_TILIM = 1e+75\t(Limits total time solver. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/TiLim.html)\n - CPX\\_PARAM\\_EPGAP = 1e-4\t(Relative (p.u. of optimal) mixed integer optimality tolerance for MIP problems (ignored otherwise). See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/EpGap.html)\n - CPX\\_PARAM\\_LPMETHOD = 0 (Algorithm used to solve continuous models (including MIP root relaxation). See https://www.ibm.com/support/knowledgecenter/de/SSSA5P_12.7.0/ilog.odms.cplex.help/CPLEX/Parameters/topics/LPMETHOD.html)\n - CPX\\_PARAM\\_BAREPCOMP = 1e-8 (Barrier convergence tolerance (determines when barrier terminates). See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/BarEpComp.html)\n - CPX\\_PARAM\\_NUMERICALEMPHASIS = 0 (Numerical precision emphasis. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/NumericalEmphasis.html)\n - CPX\\_PARAM\\_BAROBJRNG = 1e+75 (Sets the maximum absolute value of the objective function. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/BarObjRng.html)\n - CPX\\_PARAM\\_SOLUTIONTYPE = 2 (Solution type for LP or QP. See https://www.ibm.com/support/knowledgecenter/hr/SSSA5P_12.8.0/ilog.odms.cplex.help/CPLEX/Parameters/topics/SolutionType.html)\n\n\"\"\"\nfunction configure_cplex(solver_settings_path::String)\n\n solver_settings = YAML.load(open(solver_settings_path))\n\n # Set solve to use CPLEX for MIP or LP problems\n # Optional setup parameters ############################################\n # Constraint (primal) feasibility tolerances. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/EpRHS.html\n FeasibilityTol = 1e-6\n if (haskey(solver_settings, \"Feasib_Tol\"))\n FeasibilityTol = solver_settings[\"Feasib_Tol\"]\n end\n\n # Dual feasibility tolerances. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/EpOpt.html\n OptimalityTol = 1e-6\n if (haskey(solver_settings, \"Optimal_Tol\"))\n OptimalityTol = solver_settings[\"Optimal_Tol\"]\n end\n\n # Allowed fill during presolve aggregation. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/AggFill.html\n AggFill = 10\n if (haskey(solver_settings, \"AggFill\"))\n AggFill = solver_settings[\"AggFill\"]\n end\n \n # Decides whether presolve should pass the primal or dual linear programming problem to the LP optimization algorithm. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/PreDual.html\n PreDual = 0\n if (haskey(solver_settings, \"PreDual\"))\n PreDual = solver_settings[\"PreDual\"]\n end\n\n # Limits total time solver. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/TiLim.html\n TimeLimit = 1e+75\n if (haskey(solver_settings, \"TimeLimit\"))\n TimeLimit = solver_settings[\"TimeLimit\"]\n end\n\n # Relative (p.u. of optimal) mixed integer optimality tolerance for MIP problems (ignored otherwise). See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/EpGap.html\n MIPGap = 1e-4\n if (haskey(solver_settings, \"MIPGap\"))\n MIPGap = solver_settings[\"MIPGap\"]\n end\n\n # Algorithm used to solve continuous models (including MIP root relaxation). See https://www.ibm.com/support/knowledgecenter/de/SSSA5P_12.7.0/ilog.odms.cplex.help/CPLEX/Parameters/topics/LPMETHOD.html\n Method = 0\n if (haskey(solver_settings, \"Method\"))\n Method = solver_settings[\"Method\"]\n end\n\n # Barrier convergence tolerance (determines when barrier terminates). See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/BarEpComp.html\n BarConvTol = 1e-8 \n if (haskey(solver_settings, \"BarConvTol\"))\n BarConvTol = solver_settings[\"BarConvTol\"]\n end\n\n # Numerical precision emphasis. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/NumericalEmphasis.html\n NumericFocus = 0 \n if (haskey(solver_settings, \"NumericFocus\"))\n NumericFocus = solver_settings[\"NumericFocus\"]\n end\n\n # Sets the maximum absolute value of the objective function. See https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.5.1/ilog.odms.cplex.help/CPLEX/Parameters/topics/BarObjRng.html\n BarObjRng = 1e+75 \n if (haskey(solver_settings, \"BarObjRng\"))\n BarObjRng = solver_settings[\"BarObjRng\"]\n end\n\n # Solution type for LP or QP. See https://www.ibm.com/support/knowledgecenter/hr/SSSA5P_12.8.0/ilog.odms.cplex.help/CPLEX/Parameters/topics/SolutionType.html\n SolutionType = 2 \n if (haskey(solver_settings, \"SolutionType\"))\n SolutionType = solver_settings[\"SolutionType\"]\n end\n ########################################################################\n\n OPTIMIZER = optimizer_with_attributes(\n CPLEX.Optimizer,\n \"CPX_PARAM_EPRHS\" => FeasibilityTol,\n \"CPX_PARAM_EPOPT\" => OptimalityTol,\n \"CPX_PARAM_AGGFILL\" => AggFill,\n \"CPX_PARAM_PREDUAL\" => PreDual,\n \"CPX_PARAM_TILIM\" => TimeLimit,\n \"CPX_PARAM_EPGAP\" => MIPGap,\n \"CPX_PARAM_LPMETHOD\" => Method,\n \"CPX_PARAM_BAREPCOMP\" => BarConvTol,\n \"CPX_PARAM_NUMERICALEMPHASIS\" => NumericFocus,\n \"CPX_PARAM_BAROBJRNG\" => BarObjRng,\n \"CPX_PARAM_SOLUTIONTYPE\" => SolutionType,\n )\n return OPTIMIZER\nend\n", "meta": {"hexsha": "f49f1205dc9b37cb2fb48a1632b740a53889cb01", "size": 7949, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/configure_solver/configure_cplex.jl", "max_stars_repo_name": "Betristor/LTESOM", "max_stars_repo_head_hexsha": "ef972e96764254974de31b7bcbc1a6e63aee0ce0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/configure_solver/configure_cplex.jl", "max_issues_repo_name": "Betristor/LTESOM", "max_issues_repo_head_hexsha": "ef972e96764254974de31b7bcbc1a6e63aee0ce0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/configure_solver/configure_cplex.jl", "max_forks_repo_name": "Betristor/LTESOM", "max_forks_repo_head_hexsha": "ef972e96764254974de31b7bcbc1a6e63aee0ce0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.1015625, "max_line_length": 268, "alphanum_fraction": 0.7470122028, "num_tokens": 2235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.23988794777431952}} {"text": "function add_flows(m::JuMP.AbstractModel, netinjection::BalanceNamedTuple, system_formulation::Type{S}, sys::PowerSystems.PowerSystem) where {S <: PM.AbstractDCPForm}\n\n fbr = m[:fbr]\n branch_name_index = m[:fbr].axes[1]\n time_index = m[:fbr].axes[2]\n\n for t in time_index, (ix,branch) in enumerate(branch_name_index)\n\n !isassigned(netinjection.var_active,sys.branches[ix].connectionpoints.from.number,t) ? netinjection.var_active[sys.branches[ix].connectionpoints.from.number,t] = -fbr[branch,t] : JuMP.add_to_expression!(netinjection.var_active[sys.branches[ix].connectionpoints.from.number,t],-fbr[branch,t])\n !isassigned(netinjection.var_active,sys.branches[ix].connectionpoints.to.number,t) ? netinjection.var_active[sys.branches[ix].connectionpoints.to.number,t] = fbr[branch,t] : JuMP.add_to_expression!(netinjection.var_active[sys.branches[ix].connectionpoints.to.number,t],fbr[branch,t])\n\n end\n\n\nend\n\nfunction add_flows(m::JuMP.AbstractModel, netinjection::BalanceNamedTuple, system_formulation::Type{S}, sys::PowerSystems.PowerSystem) where {S <: PM.AbstractDCPLLForm}\n\n fbr_fr = m[:fbr_fr]\n fbr_to = m[:fbr_to]\n time_index = m[:fbr_to].axes[2]\n branch_name_index = m[:fbr_fr].axes[1]\n\n for t in time_index, (ix,branch) in enumerate(branch_name_index)\n\n !isassigned(netinjection.var_active,sys.branches[ix].connectionpoints.from.number,t) ? netinjection.var_active[sys.branches[ix].connectionpoints.from.number,t] = -fbr_fr[branch,t] : JuMP.add_to_expression!(netinjection.var_active[sys.branches[ix].connectionpoints.from.number,t],-fbr_fr[branch,t])\n !isassigned(netinjection.var_active,sys.branches[ix].connectionpoints.to.number,t) ? netinjection.var_active[sys.branches[ix].connectionpoints.to.number,t] = fbr_to[branch,t] : JuMP.add_to_expression!(netinjection.var_active[sys.branches[ix].connectionpoints.to.number,t],fbr_to[branch,t])\n\n end\n\nend\n\nfunction nodalflowbalance(m::JuMP.AbstractModel, netinjection::BalanceNamedTuple, system_formulation::Type{S}, sys::PowerSystems.PowerSystem) where {S <: AbstractFlowForm}\n\n time_index = 1:sys.time_periods\n bus_name_index = [b.name for b in sys.buses]\n\n add_flows(m, netinjection, system_formulation, sys)\n\n pf_balance = JuMP.JuMPArray(Array{ConstraintRef}(undef,length(bus_name_index), sys.time_periods), bus_name_index, time_index)\n\n for t in time_index, (ix,bus) in enumerate(bus_name_index)\n\n isassigned(netinjection.var_active,ix, t) ? true : @error \"Islanded Bus in the system\"\n\n pf_balance[bus,t] = @constraint(m, netinjection.var_active[ix, t] == netinjection.timeseries_active[ix, t])\n\n end\n\n JuMP.register_object(m, :NodalFlowBalance_active, pf_balance)\n\nend\n\n\nfunction nodalflowbalance(m::JuMP.AbstractModel, netinjection::BalanceNamedTuple, system_formulation::Type{S}, sys::PowerSystems.PowerSystem) where {S <: AbstractDCPowerModel}\n\n time_index = 1:sys.time_periods\n bus_name_index = [b.name for b in sys.buses]\n\n PM_dict = pass_to_pm(sys, netinjection)\n\n for t in time_index, bus in sys.buses\n\n !isassigned(netinjection.var_active,bus.number,t) ? PM_dict[\"nw\"][\"$(t)\"][\"bus\"][\"$(bus.number)\"][\"pni\"] = -(netinjection.timeseries_active[bus.number, t]) : PM_dict[\"nw\"][\"$(t)\"][\"bus\"][\"$(bus.number)\"][\"pni\"] = JuMP.add_to_expression!(netinjection.var_active[bus.number,t],-(netinjection.timeseries_active[bus.number, t]))\n\n end\n\n m.ext[:PM_object] = PM_dict\n\nend\n\nfunction nodalflowbalance(m::JuMP.AbstractModel, netinjection::BalanceNamedTuple, system_formulation::Type{S}, sys::PowerSystems.PowerSystem) where {S <: AbstractACPowerModel}\n\n nodalflowbalance(m, netinjection, AbstractDCPowerModel, sys)\n\n PM_dict = m.ext[:PM_object]\n\n time_index = 1:sys.time_periods\n bus_name_index = [b.name for b in sys.buses]\n\n for t in time_index, bus in sys.buses\n\n !isassigned(netinjection.var_reactive,bus.number,t) ? PM_dict[\"nw\"][\"$(t)\"][\"bus\"][\"$(bus.number)\"][\"qni\"] = -(netinjection.timeseries_reactive[bus.number, t]) : PM_dict[\"nw\"][\"$(t)\"][\"bus\"][\"$(bus.number)\"][\"qni\"] = JuMP.add_to_expression!(netinjection.var_reactive[bus.number,t],-(netinjection.timeseries_reactive[bus.number, t]))\n\n end\n\n m.ext[:PM_object] = PM_dict\n\nend", "meta": {"hexsha": "eca50fb5fa6bfc88bc20dd539ffaff15e0066c02", "size": 4307, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/network_models/nodal_balance.jl", "max_stars_repo_name": "gitter-badger/PowerSimulations.jl", "max_stars_repo_head_hexsha": "608671297c4b813505aef4073932eae3d8875af6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/network_models/nodal_balance.jl", "max_issues_repo_name": "gitter-badger/PowerSimulations.jl", "max_issues_repo_head_hexsha": "608671297c4b813505aef4073932eae3d8875af6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/network_models/nodal_balance.jl", "max_forks_repo_name": "gitter-badger/PowerSimulations.jl", "max_forks_repo_head_hexsha": "608671297c4b813505aef4073932eae3d8875af6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.393258427, "max_line_length": 344, "alphanum_fraction": 0.7306710007, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23987421188575342}} {"text": "export fields\n\nadd_verbose_scope(:Fields)\nadd_assert_scope(:Fields)\n\nadd_verbose_scope(:FieldsNonFancy)\n\nmutable struct FieldsTower\n field::AnticNumberField\n generators_of_automorphisms::Vector{NfToNfMor}\n subfields::Vector{NfToNfMor}\n ramified_primes::Vector{fmpz}\n \n #Solvable embedding problems for the extension\n #They are here to improve the conductor computation\n has_info::Bool\n imgs_autos::Vector{Main.ForeignGAP.MPtr}\n auts_for_conductors::Vector{Main.ForeignGAP.MPtr}\n proj_ext::Main.ForeignGAP.MPtr\n \n function FieldsTower(K::AnticNumberField, auts::Vector{NfToNfMor}, subfields::Vector{NfToNfMor})\n z = new()\n z.field = K\n z.generators_of_automorphisms = auts\n z.subfields = subfields\n z.has_info = false\n return z\n end\n\nend\n\ninclude(\"./brauer.jl\")\ninclude(\"./merge.jl\")\ninclude(\"./abelian_layer.jl\")\ninclude(\"./read_write.jl\")\ninclude(\"./conductors.jl\")\n\nGeneric.degree(F::FieldsTower) = degree(F.field)\nHecke.maximal_order(F::FieldsTower) = maximal_order(F.field)\n\n\nfunction ramified_primes(F::FieldsTower)\n if !isdefined(F, :ramified_primes)\n f = factor(discriminant(maximal_order(F.field)))\n F.ramified_primes = collect(keys(f.fac))\n end\n return F.ramified_primes\nend\n\n###############################################################################\n#\n# From automorphisms to permutation groups\n#\n###############################################################################\n\nfunction Base.push!(G::AbstractAlgebra.Generic.geobucket{T}, p::T) where {T <: AbstractAlgebra.MPolyElem}\n R = parent(p)\n i = max(1, ndigits(length(p), base=4))\n l = length(G.buckets)\n if length(G.buckets) < i\n resize!(G.buckets, i)\n for j in (l + 1):i\n G.buckets[j] = zero(R)\n end\n end\n G.buckets[i] = addeq!(G.buckets[i], p)\n while i <= G.len\n if length(G.buckets[i]) >= 4^i\n G.buckets[i + 1] = addeq!(G.buckets[i + 1], G.buckets[i])\n G.buckets[i] = R()\n i += 1\n end\n break\n end\n if i == G.len + 1\n Base.push!(G.buckets, R())\n G.len += 1\n end\nend\n\nfunction permutation_group(G::Vector{Hecke.NfRelNSToNfRelNSMor{nf_elem}})\n permutations = permutation_group1(G)\n return _perm_to_gap_grp(permutations)\nend\n\n\nfunction permutations(G::Array{Hecke.NfToNfMor, 1})\n K = domain(G[1])\n n = length(G)\n dK = degree(K)\n d = numerator(discriminant(K.pol))\n p = 11\n while mod(d, p) == 0\n p = next_prime(p)\n end\n R = GF(p, cached = false)\n Rx, x = PolynomialRing(R, \"x\", cached = false)\n fmod = Rx(K.pol)\n\n\n pols = gfp_poly[x]\n gpol = Rx(G[1].prim_img)\n if gpol != x\n push!(pols, gpol)\n gpol = compose_mod(gpol, pols[2], fmod)\n while gpol != x\n push!(pols, gpol)\n gpol = compose_mod(gpol, pols[2], fmod)\n end\n end\n order = length(pols)\n\n for i in 2:n\n pi = Rx(G[i].prim_img)\n if !(pi in pols)\n previous_order = order\n order = order + 1\n push!(pols, pi)\n for j in 2:previous_order\n order = order + 1\n push!(pols, compose_mod(pols[j], pi, fmod))\n end\n if order == n\n break\n end\n rep_pos = previous_order + 1\n while rep_pos <= order\n for k in 1:i\n po = Rx(G[k].prim_img)\n att = compose_mod(pols[rep_pos], po, fmod)\n if !(att in pols)\n order = order + 1\n push!(pols, att)\n for j in 2:previous_order\n order = order + 1\n push!(pols, compose_mod(pols[j], att, fmod))\n end\n if order == dK\n break\n end\n end\n if order == dK\n break\n end\n end\n if order == dK\n break\n end\n rep_pos = rep_pos + previous_order\n end\n end\n end\n #Now, I have the images mod p\n Dcreation = Vector{Tuple{gfp_poly, Int}}(undef, length(pols))\n for i = 1:length(pols)\n Dcreation[i] = (pols[i], i)\n end\n permutations = Array{Array{Int, 1},1}(undef, n)\n for i = 1:n\n permutations[i] = Vector{Int}(undef, dK)\n end\n gen_pols = [Rx(x.prim_img) for x in G]\n D = Dict{gfp_poly, Int}(Dcreation)\n for s = 1:n\n for i = 1:length(pols)\n permutations[s][i] = D[Hecke.compose_mod(gen_pols[s], pols[i], fmod)]\n end\n end\n return permutations\nend\n\nfunction permutation_group(G::Array{Hecke.NfToNfMor, 1})\n return _perm_to_gap_grp(permutations(G))\nend\n\nfunction _from_autos_to_perm(G::Array{Hecke.NfToNfMor,1})\n \n K = domain(G[1])\n @assert degree(K) == length(G)\n n = length(G)\n #First, find a good prime\n p = 2\n d = numerator(discriminant(K.pol))\n while mod(d, p) == 0\n p = next_prime(p)\n end\n R = GF(p, cached = false)\n Rx, x = PolynomialRing(R, \"x\", cached = false)\n fmod = Rx(K.pol)\n pols = Vector{Tuple{gfp_poly, Int}}(undef, n)\n for i = 1:n\n pols[i] = (Rx(G[i].prim_img), i)\n end\n D = Dict{gfp_poly, Int}(pols)\n permutations = Array{Array{Int, 1},1}(undef, n)\n for s = 1:n\n perm = Array{Int, 1}(undef, n)\n for i = 1:n\n perm[i] = D[Hecke.compose_mod(pols[i][1], pols[s][1], fmod)]\n end\n permutations[s] = perm\n end\n return permutations\n \nend\n\nfunction _perm_to_gap_grp(perm::Array{Array{Int, 1},1})\n g = Main.ForeignGAP.MPtr[]\n for x in perm\n z = _perm_to_gap_perm(x)\n push!(g, z)\n end\n return GAP.Globals.Group(GAP.julia_to_gap(g)) \nend\n\nfunction _perm_to_gap_perm(x::Array{Int, 1})\n z = GAP.Globals.PermList(GAP.julia_to_gap(x))\n return z\nend\n\nfunction IdGroup(autos::Array{NfToNfMor, 1})\n G = permutation_group(autos)\n return GAP.Globals.IdGroup(G)\nend\n\n\n################################################################################\n#\n# final computation of the maximal order and automorphisms\n#\n################################################################################\n\nfunction _from_relative_to_abs_with_embedding(L::Hecke.NfRelNS{T}, autL::Array{Hecke.NfRelNSToNfRelNSMor{T}, 1}, use_simplify::Bool = true) where T\n\n S, mS = simple_extension(L)\n K, mK, MK = absolute_field(S, false)\n \n #First, we compute the maximal order of the absolute field.\n #We start from the maximal orders of the relative extension and of the base field.\n #FALSE: Since the computation of the relative maximal order is slow, I prefer to bring to the absolute field the elements\n # generating the equation order.\n pols = L.pol\n gL = gens(L)\n B = Array{nf_elem, 1}(undef, degree(K))\n B[1] = K(1)\n ind = total_degree(pols[1])\n genjj = mK\\(mS\\gL[1])\n for i = 2:ind\n B[i] = genjj*B[i-1]\n end\n for jj = 2:length(pols)\n genjj = mK\\(mS\\gL[jj])\n el = deepcopy(genjj)\n new_deg = total_degree(pols[jj])\n for i = 2:new_deg\n for j = 1:ind\n B[(i-1)* ind + j] = B[j]* el \n end\n mul!(el, el, genjj)\n end\n ind *= new_deg\n end\n\n #Now, I add the elements of the maximal order\n OB = maximal_order(base_field(S))\n for i = 1:degree(OB)\n el = MK(OB.basis_nf[i])\n for j = 1:ind\n B[(i-1)* ind + j] = B[j] * el \n end\n end\n @vprint :Fields 2 \"Product basis computed\\n\"\n #Now, we compute the maximal order. Then we simplify.\n #We simplify only if the degree of the field is lower than 30\n \n BasisMat = basis_matrix(B, FakeFmpqMat)\n @vtime :Fields 3 Hecke.hnf_modular_eldiv!(BasisMat.num, BasisMat.den, :lowerleft)\n NewBMat = FakeFmpqMat(BasisMat.num, BasisMat.den)\n @vtime :Fields 3 Ostart = NfAbsOrd(K, NewBMat)\n Ostart.index = divexact(NewBMat.den^degree(K), prod_diagonal(NewBMat.num))\n Ostart.gen_index = fmpq(Ostart.index)\n Ostart.disc = divexact(numerator(discriminant(K)), Ostart.index^2)\n ram_primes_rel = numerator(norm(discriminant(L)))\n ram_primes_down = Hecke.ramified_primes(OB)\n for p in ram_primes_down\n if isone(gcd(p, ram_primes_rel))\n push!(Ostart.primesofmaximality, p) \n end\n end\n @vtime :Fields 3 O1 = MaximalOrder(Ostart)\n O1.ismaximal = 1\n Hecke._set_maximal_order_of_nf(K, O1)\n if use_simplify\n @vtime :Fields 3 Ks, mKs = Hecke.simplify(K)\n #Now, we have to construct the maximal order of this field.\n #I compute the inverse of mKs\n @vtime :Fields 3 mKsI = find_inverse(mKs)\n if isdefined(O1, :lllO)\n lO = O1.lllO::NfOrd\n O2 = NfOrd(nf_elem[mKsI(x) for x in basis(lO, K, copy = false)], false)\n #O2.lllO = O2\n else\n O2 = NfOrd(nf_elem[mKsI(x) for x in basis(O1, K, copy = false)], false)\n end\n O2.ismaximal = 1\n @assert isdefined(O1, :disc)\n O2.disc = O1.disc\n O2.index = root(divexact(numerator(discriminant(Ks)), O2.disc), 2)\n @vtime :Fields 3 OLLL = lll(O2)\n Hecke._set_maximal_order_of_nf(Ks, OLLL)\n else\n Ks = K\n mKs = id_hom(K)\n mKsI = id_hom(K)\n end\n #I want also the embedding of the old field into the new one. \n #It is enough to find the image of the primitive element.\n k = base_field(S)\n a = MK(gen(k)) \n embed = NfToNfMor(k, Ks, mKsI(a))\n #@assert iszero(k.pol(img_a)) \n @vprint :Fields 3 \"MaximalOrder Computed. Now Automorphisms\\n\"\n #Now, the automorphisms.\n # I need both generators and the whole group. \n autos = Array{NfToNfMor, 1}(undef, length(autL))\n el = mS(mK(mKs.prim_img))\n el1 = mS(mK(gen(K)))\n for i=1:length(autL)\n #@assert iszero(K.pol(mK(mS\\(autL[i](el1)))))\n x = mKsI(mK\\(mS\\(autL[i](el))))\n #@assert Ks.pol(y) == 0\n autos[i] = Hecke.NfToNfMor(Ks, Ks, x)\n end\n #And the generators are done. Now the closure\n #@vtime :Fields 3 Hecke._set_automorphisms_nf(Ks, closure(autos, degree(Ks)))\n #No! I set the automorphisms only if I need them\n #Hecke._set_automorphisms_nf(Ks, autsKs)\n @vprint :Fields 2 \"Finished\\n\"\n #@assert codomain(embed) == Ks\n return Ks, autos, embed\nend \n\nfunction find_inverse(f::NfToNfMor)\n v = Vector{nf_elem}(undef, degree(domain(f)))\n v[1] = one(codomain(f))\n v[2] = f.prim_img\n for i = 3:degree(domain(f))\n v[i] = v[2]*v[i-1]\n end\n M = basis_matrix(v)\n w = zero_matrix(FlintQQ, 1, nrows(M))\n w[1, 2] = 1\n fl, s = can_solve(M, w, side = :left)\n @assert fl\n s1 = FakeFmpqMat(s)\n pre_img = elem_from_mat_row(domain(f), s1.num, 1, s1.den)\n return hom(codomain(f), domain(f), pre_img)\nend\n\nfunction find_inverse2(f::NfToNfMor)\n K = codomain(f)\n arr_prim_img = Array{nf_elem, 1}(undef, degree(K))\n arr_prim_img[1] = K(1)\n arr_prim_img[2] = f.prim_img\n for i = 3:degree(K)\n arr_prim_img[i] = arr_prim_img[i-1]*f.prim_img\n end\n M1 = inv(basis_matrix(arr_prim_img, FakeFmpqMat))\n return M1\nend\n\n\n###############################################################################\n#\n# Split Extensions\n#\n###############################################################################\n\nfunction _split_extension(G::Array{Hecke.NfToNfMor, 1}, mats::Array{Hecke.GrpAbFinGenMap, 1})\n \n gtype = map(Int, domain(mats[1]).snf)\n G1 = permutation_group(G)\n gensG1 = GAP.Globals.GeneratorsOfGroup(G1)\n A = GAP.Globals.AbelianGroup(GAP.julia_to_gap(gtype))\n gens = GAP.Globals.GeneratorsOfGroup(A)\n auts = Array{Main.ForeignGAP.MPtr, 1}(undef, length(mats))\n for i = 1:length(mats)\n images = Array{Main.ForeignGAP.MPtr, 1}(undef, length(gtype))\n for j = 1:length(gtype)\n g = GAP.Globals.Identity(A)\n for k = 1:length(gtype)\n if !iszero(mats[i].map[j,k])\n g *= gens[k]^Int(mats[i].map[j,k])\n end\n end\n images[j] = g\n end\n auts[i] = GAP.Globals.GroupHomomorphismByImages(A, A, gens, GAP.julia_to_gap(images))\n end \n AutGrp = GAP.Globals.Group(GAP.julia_to_gap(auts))\n mp = GAP.Globals.GroupHomomorphismByImages(G1, AutGrp, gensG1, GAP.julia_to_gap(auts))\n return GAP.Globals.SplitExtension(G1, mp, A)\n\nend\n\n###############################################################################\n#\n# Check group extension\n#\n###############################################################################\n\nfunction check_group_extension(TargetGroup::Main.ForeignGAP.MPtr, autos::Array{NfToNfMor, 1}, res_act::Array{GrpAbFinGenMap, 1})\n \n GS = domain(res_act[1])\n expo = Int(GS.snf[end])\n K = domain(autos[1])\n d = degree(K)\n com, uncom = ppio(expo, d)\n \n if com == 1 \n # I only need to check the split extension, since the second cohomology group is\n # trivial, regardless of the action\n H = _split_extension(autos, res_act)\n return GAP.Globals.IdGroup(H) == TargetGroup\n end\n \n if uncom == 1\n #Need a cohomological check. Only useful in the prime power case.\n return true\n end\n \n # I check the split extension related to only uncom\n #Now, I have to check if the split extension is isomorphic to IdH\n Qn, mQn = quo(GS, uncom, false)\n S1, mS1 = snf(Qn)\n new_res_act = Array{GrpAbFinGenMap, 1}(undef, length(res_act))\n for i = 1:length(res_act)\n Mat = mS1.map*mQn.imap*res_act[i].map*mQn.map*mS1.imap\n Hecke.reduce_mod_snf!(Mat, S1.snf)\n new_res_act[i] = hom(S1, S1, Mat)\n end\n H = _split_extension(autos, new_res_act)\n return GAP.Globals.IdGroup(H) == TargetGroup\n \nend\n\n\n###############################################################################\n#\n# Interface to find Fields\n#\n###############################################################################\n\nfunction field_extensions(list::Vector{FieldsTower}, bound::fmpz, IsoE1::Main.ForeignGAP.MPtr, l::Array{Int, 1}, only_real::Bool, simplify::Bool)\n\n grp_to_be_checked = Dict{Int, Main.ForeignGAP.MPtr}()\n d = degree(list[1])\n n = lcm(l)\n com, uncom = ppio(n, d)\n fac = factor(n)\n for (p, v) in fac\n grp_to_be_checked[Int(p)] = _construct_grp(IsoE1, Int(p)^v)\n end\n if uncom != 1\n IsoCheck = _construct_grp(IsoE1, uncom)\n else\n IsoCheck = IsoE1\n end\n final_list = FieldsTower[]\n for (j, x) in enumerate(list) \n @vprint :Fields 1 \"Field $(j)/$(length(list)): $(x.field.pol)\"\n @vprint :FieldsNonFancy 1 \"Field $(j)/$(length(list)): $(x.field.pol)\\n\"\n append!(final_list, field_extensions(x, bound, IsoCheck, l, only_real, grp_to_be_checked, IsoE1, simplify))\n end \n return final_list\n\nend\n\nfunction field_extensions(x::FieldsTower, bound::fmpz, IsoE1::Main.ForeignGAP.MPtr, l::Array{Int, 1}, only_real::Bool, grp_to_be_checked::Dict{Int, Main.ForeignGAP.MPtr}, IsoG::Main.ForeignGAP.MPtr, simplify::Bool)\n \n list_cfields = _abelian_normal_extensions(x, l, bound, IsoE1, only_real, IsoG)\n if isempty(list_cfields)\n @vprint :Fields 1 \"\\e[1F$(Hecke.set_cursor_col())$(Hecke.clear_to_eol())Number of new fields found: 0\\n\\n\"\n @vprint :FieldsNonFancy 1 \"Number of new fields found: 0\\n\"\n return Vector{FieldsTower}()\n end\n list = from_class_fields_to_fields(list_cfields, x.generators_of_automorphisms, grp_to_be_checked)\n @vprint :Fields 1 \"Computing maximal orders\"\n @vprint :FieldsNonFancy 1 \"Computing maximal orders\\n\"\n final_list = Vector{FieldsTower}(undef, length(list))\n for j = 1:length(list)\n fld, autos, embed = _from_relative_to_abs_with_embedding(list[j][1], list[j][2], simplify)\n previous_fields = Array{NfToNfMor, 1}(undef, length(x.subfields)+1)\n for s = 1:length(x.subfields)\n previous_fields[s] = x.subfields[s]\n end\n previous_fields[end] = embed \n final_list[j] = FieldsTower(fld, autos, previous_fields)\n end\n @vprint :Fields 1 \"$(Hecke.set_cursor_col())$(Hecke.clear_to_eol())\"\n @vprint :Fields 1 \"Number of new fields found: $(length(final_list))\\n\\n\"\n @vprint :FieldsNonFancy 1 \"Number of new fields found: $(length(final_list))\\n\"\n return final_list\n \nend\n\n###############################################################################\n#\n# Interface\n#\n###############################################################################\n\nfunction fields_direct_product(g1, g2, red, redfirst, absolute_bound; only_real = false)\n b1 = root(absolute_bound, g2[1])\n b2 = root(absolute_bound, g1[1])\n l2 = fields(g2[1], g2[2], b2, only_real = only_real)\n if isempty(l2)\n return FieldsTower[]\n end\n if g1 == g2\n return _merge(l2, l2, absolute_bound, red, redfirst)\n end\n l1 = fields(g1[1], g1[2], b1, only_real = only_real)\n if isempty(l1)\n return FieldsTower[]\n end\n return _merge(l1, l2, absolute_bound, red, redfirst)\nend\n\n\nfunction fields(a::Int, b::Int, absolute_bound::fmpz; using_direct_product::Bool = true, only_real::Bool = false, simplify::Bool = true)\n @assert absolute_bound > 0\n if a == 1\n @assert b == 1\n Qx, x = PolynomialRing(FlintQQ, \"x\", cached = false)\n K, a = NumberField(x-1, cached = false)\n g = NfToNfMor(K, K, K(1))\n return FieldsTower[FieldsTower(K, NfToNfMor[g], Array{NfToNfMor, 1}())]\n end\n G = GAP.Globals.SmallGroup(a, b)\n @assert GAP.Globals.IsSolvable(G)\n if using_direct_product\n g1, g2, red, redfirst = direct_product_decomposition(G, (a, b))\n if g2 != (1, 1) \n return fields_direct_product(g1, g2, red, redfirst, absolute_bound; only_real = false)\n end\n end\n @vprint :Fields 1 \"Doing Group ($a, $b) with bound $absolute_bound\\n\"\n @vprint :FieldsNonFancy 1 \"Doing Group ($a, $b) with bound $absolute_bound\\n\"\n L = GAP.Globals.DerivedSeries(G)\n lvl = _real_level(L)\n #First step by hand\n l = GAP.gap_to_julia(Vector{Int64}, GAP.Globals.AbelianInvariants(G))\n @vprint :Fields 1 \"contructing abelian extensions with invariants $l \\n\" \n @vprint :FieldsNonFancy 1 \"contructing abelian extensions with invariants $l \\n\" \n #@vtime :Fields 2 \n list = abelian_extensionsQQ(l, root(absolute_bound, div(a,prod(l))), (lvl > 1 || only_real))\n if isempty(list)\n return list\n end\n @vprint :Fields 1 \"First step completed\\n \\n\"\n @vprint :FieldsNonFancy 1 \"First step completed\\n \\n\"\n for i = 2:length(L)-1\n\n E1 = GAP.Globals.FactorGroup(L[1], L[i+1])\n l = GAP.gap_to_julia(Vector{Int64}, GAP.Globals.AbelianInvariants(L[i]))\n @vprint :Fields 1 \"contructing abelian extensions with invariants $l \\n\" \n @vprint :FieldsNonFancy 1 \"contructing abelian extensions with invariants $l \\n\" \n o = divexact(a, GAP.Globals.Size(E1))\n bound = root(absolute_bound, o)\n IsoE1 = GAP.Globals.IdGroup(E1)\n @vprint :Fields 1 \"Number of fields at the $i -th step: $(length(list)) \\n\"\n @vprint :FieldsNonFancy 1 \"Number of fields at the $i -th step: $(length(list)) \\n\"\n lG = snf(DiagonalGroup(l))[1]\n invariants = map(Int, lG.snf) \n onlyreal = (lvl > i || only_real)\n @vprint :Fields 1 \"Computing obstructions\\n\"\n @vprint :FieldsNonFancy 1 \"Computing obstructions\\n\"\n #@vtime :Fields 1 \n list = check_Brauer_obstruction(list, L, i, invariants)\n @vprint :Fields 1 \"Fields to check: $(length(list))\\n\\n\"\n @vprint :FieldsNonFancy 1 \"Fields to check: $(length(list))\\n\\n\"\n if isempty(list)\n return FieldsTower[]\n end\n simplify_i_th = true\n if i == length(L)-1 && simplify == false\n simplify_i_th = false\n end\n list = field_extensions(list, bound, IsoE1, invariants, onlyreal, simplify)\n @vprint :Fields 1 \"Step $i completed\\n\"\n @vprint :FieldsNonFancy 1 \"Step $i completed\\n\"\n if isempty(list)\n return FieldsTower[]\n end\n end\n return list\n \nend\n\nfunction fields(a::Int, b::Int, list::Vector{FieldsTower}, absolute_bound::fmpz; only_real::Bool = false, simplify::Bool = true)\n G = GAP.Globals.SmallGroup(a, b)\n return fields(list, G, absolute_bound, only_real = only_real, simplify = simplify)\nend\n\n\nfunction fields(list::Vector{FieldsTower}, G, absolute_bound::fmpz; only_real::Bool = false, simplify::Bool = true)\n L = GAP.Globals.DerivedSeries(G)\n lvl = _real_level(L)\n first = true\n for i = 2:length(L)-1\n G1 = GAP.Globals.FactorGroup(L[1], L[i])\n if first && GAP.Globals.Size(G1) != degree(list[1].field)\n continue\n end\n first = false\n E1 = GAP.Globals.FactorGroup(L[1], L[i+1])\n H1 = GAP.Globals.FactorGroup(L[i], L[i+1])\n l = GAP.gap_to_julia(Vector{Int64}, GAP.Globals.AbelianInvariants(H1))\n @vprint :Fields 1 \"contructing abelian extensions with invariants $l \\n\" \n @vprint :FieldsNonFancy 1 \"contructing abelian extensions with invariants $l \\n\" \n o = divexact(GAP.Globals.Size(G), GAP.Globals.Size(E1))\n bound = root(absolute_bound, o)\n IsoE1 = GAP.Globals.IdGroup(E1)\n @vprint :Fields 1 \"Number of fields at the $i -th step: $(length(list)) \\n\"\n @vprint :FieldsNonFancy 1 \"Number of fields at the $i -th step: $(length(list)) \\n\"\n lG = snf(DiagonalGroup(l))[1]\n invariants = map(Int, lG.snf) \n onlyreal = (lvl > i || only_real)\n #First, I search for obstruction.\n if iscyclic(lG) \n @vprint :Fields 1 \"Computing obstructions\\n\"\n @vprint :FieldsNonFancy 1 \"Computing obstructions\\n\"\n #@vtime :Fields 1 \n list = check_Brauer_obstruction(list, L, i, invariants[1])\n @vprint :Fields 1 \"Fields to check: $(length(list))\\n\\n\"\n @vprint :FieldsNonFancy 1 \"Fields to check: $(length(list))\\n\\n\"\n end\n if isempty(list)\n return FieldsTower[]\n end\n list = field_extensions(list, bound, IsoE1, invariants, onlyreal, simplify)\n @vprint :Fields 1 \"Step $i completed\\n\"\n @vprint :FieldsNonFancy 1 \"Step $i completed\\n\"\n if isempty(list)\n return FieldsTower[]\n end\n end\n return list\nend\n", "meta": {"hexsha": "7806ea8bcce83e7f00b5b4272090390cc2c70fff", "size": 20891, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FieldFactory/fields.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Hecke.jl-3e1990a7-5d81-5526-99ce-9ba3ff248f21", "max_stars_repo_head_hexsha": "7aaa4b05a5e24f6330c149bb20cb3d62621574a9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FieldFactory/fields.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Hecke.jl-3e1990a7-5d81-5526-99ce-9ba3ff248f21", "max_issues_repo_head_hexsha": "7aaa4b05a5e24f6330c149bb20cb3d62621574a9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FieldFactory/fields.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Hecke.jl-3e1990a7-5d81-5526-99ce-9ba3ff248f21", "max_forks_repo_head_hexsha": "7aaa4b05a5e24f6330c149bb20cb3d62621574a9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0906298003, "max_line_length": 214, "alphanum_fraction": 0.6292183237, "num_tokens": 6691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23986766542353896}} {"text": "module LagrangianParticleTracking\n\nexport LagrangianParticles, update_particle_properties!\n\nusing Adapt\nusing KernelAbstractions\nusing StructArrays\n\nusing Oceananigans.Grids\nusing Oceananigans.Architectures: device\nusing Oceananigans.Fields: interpolate, datatuple, compute!, location\n\nimport Base: size, length, show\n\nabstract type AbstractParticle end\n\nstruct Particle{T} <: AbstractParticle\n x :: T\n y :: T\n z :: T\nend\n\nstruct LagrangianParticles{P, R, T, D, Π}\n properties :: P\n restitution :: R\n tracked_fields :: T\n dynamics :: D\n parameters :: Π\nend\n\n@inline no_dynamics(args...) = nothing\n\n\"\"\"\n LagrangianParticles(; x, y, z, restitution=1.0, dynamics=no_dynamics, parameters=nothing)\n\nConstruct some `LagrangianParticles` that can be passed to a model. The particles will have initial locations\n`x`, `y`, and `z`. The coefficient of restitution for particle-wall collisions is specified by `restitution`.\n\n`dynamics` is a function of `(lagrangian_particles, model, Δt)` that is called prior to advecting particles.\n`parameters` can be accessed inside the `dynamics` function.\n\"\"\"\nfunction LagrangianParticles(; x, y, z, restitution=1.0, dynamics=no_dynamics, parameters=nothing)\n size(x) == size(y) == size(z) ||\n throw(ArgumentError(\"x, y, z must all have the same size!\"))\n\n (ndims(x) == 1 && ndims(y) == 1 && ndims(z) == 1) ||\n throw(ArgumentError(\"x, y, z must have dimension 1 but ndims=($(ndims(x)), $(ndims(y)), $(ndims(z)))\"))\n\n particles = StructArray{Particle}((x, y, z))\n\n return LagrangianParticles(particles; restitution, dynamics, parameters)\nend\n\n\"\"\"\n LagrangianParticles(particles::StructArray; restitution=1.0, tracked_fields::NamedTuple=NamedTuple(), dynamics=no_dynamics)\n\nConstruct some `LagrangianParticles` that can be passed to a model. The `particles` should be a `StructArray`\nand can contain custom fields. The coefficient of restitution for particle-wall collisions is specified by `restitution`.\n\nA number of `tracked_fields` may be passed in as a `NamedTuple` of fields. Each particle will track the value of each\nfield. Each tracked field must have a corresponding particle property. So if `T` is a tracked field, then `T` must also\nbe a custom particle property.\n\n`dynamics` is a function of `(lagrangian_particles, model, Δt)` that is called prior to advecting particles.\n`parameters` can be accessed inside the `dynamics` function.\n\"\"\"\nfunction LagrangianParticles(particles::StructArray; restitution=1.0, tracked_fields::NamedTuple=NamedTuple(),\n dynamics=no_dynamics, parameters=nothing)\n\n for (field_name, tracked_field) in pairs(tracked_fields)\n field_name in propertynames(particles) ||\n throw(ArgumentError(\"$field_name is a tracked field but $(eltype(particles)) has no $field_name field! \" *\n \"You might have to define your own particle type.\"))\n end\n\n return LagrangianParticles(particles, restitution, tracked_fields, dynamics, parameters)\nend\n\nsize(lagrangian_particles::LagrangianParticles) = size(lagrangian_particles.properties)\nlength(lagrangian_particles::LagrangianParticles) = length(lagrangian_particles.properties)\n\nfunction Base.show(io::IO, lagrangian_particles::LagrangianParticles)\n particles = lagrangian_particles.properties\n properties = propertynames(particles)\n fields = lagrangian_particles.tracked_fields\n print(io, \"$(length(particles)) Lagrangian particles with\\n\",\n \"├── $(length(properties)) properties: $properties\\n\",\n \"└── $(length(fields)) tracked fields: $(propertynames(fields))\")\nend\n\ninclude(\"update_particle_properties.jl\")\n\nend # module\n", "meta": {"hexsha": "ae392edc436d66bcb075239037fbf3a68293bd56", "size": 3709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LagrangianParticleTracking/LagrangianParticleTracking.jl", "max_stars_repo_name": "leea9524/Oceananigans.jl", "max_stars_repo_head_hexsha": "5e1448d14660e110edd8b28094d486bfe97c905b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 239, "max_stars_repo_stars_event_min_datetime": "2019-03-05T03:46:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T21:53:14.000Z", "max_issues_repo_path": "src/LagrangianParticleTracking/LagrangianParticleTracking.jl", "max_issues_repo_name": "leea9524/Oceananigans.jl", "max_issues_repo_head_hexsha": "5e1448d14660e110edd8b28094d486bfe97c905b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 654, "max_issues_repo_issues_event_min_datetime": "2019-03-02T02:20:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-02T00:13:53.000Z", "max_forks_repo_path": "src/LagrangianParticleTracking/LagrangianParticleTracking.jl", "max_forks_repo_name": "ali-ramadhan/OceanDispatch.jl", "max_forks_repo_head_hexsha": "65b8851d37052e90ca4a3e0c4a1c20398b0ee09a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2019-03-05T18:25:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T08:04:25.000Z", "avg_line_length": 39.4574468085, "max_line_length": 127, "alphanum_fraction": 0.7309247776, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2397125090510441}} {"text": "# functions for calculating node coordinates and metrics for curvilinear\n# meshes\n\n#------------------------------------------------------------------------------\n# allocators for curvilinear meshes\n\n\"\"\"\n Allocates mesh.vert_coords\n\"\"\"\nfunction allocateMeshCoordinateArray(mesh::PumiMeshDG{Tmsh}, sbp::AbstractSBP) where Tmsh\n\n num_coord_nodes = mesh.coord_numNodesPerElement\n\n if !isFieldDefined(mesh, :vert_coords)\n mesh.vert_coords = Array{Tmsh}(mesh.dim, num_coord_nodes, mesh.numEl)\n mesh.vert_coords_bar = Array{Tmsh}(mesh.dim, num_coord_nodes, mesh.numEl)\n else\n fill!(mesh.vert_coords, 0.0)\n end\n\n return nothing\nend\n\n\"\"\"\n Allocates the following fields of mesh:\n coords\n dxidx\n jac\n\n Also allocates the following fields with size zero (because they are not used):\n dxidx_face\n jac_face\n dxidx_bndry\n jac_bndry\n dxidx_sharedface\n jac_sharedface\n\"\"\"\nfunction allocateCurvilinearCoordinateAndMetricArrays(mesh::PumiMeshDG{Tmsh}, sbp::AbstractSBP) where Tmsh\n\n dim = mesh.dim\n sbpface = mesh.sbpface\n \n if !isFieldDefined(mesh, :coords, :dxidx, :jac)\n mesh.coords = zeros(Tmsh, mesh.dim, mesh.numNodesPerElement, mesh.numEl)\n mesh.dxidx = zeros(Tmsh, mesh.dim, mesh.dim, mesh.numNodesPerElement, mesh.numEl)\n mesh.jac = zeros(Tmsh, mesh.numNodesPerElement, mesh.numEl)\n\n mesh.dxidx_bar = zeros(mesh.dxidx)\n mesh.jac_bar = zeros(mesh.jac)\n\n # these arrays are not used for curvilinear meshes\n\n # interior faces\n mesh.dxidx_face = zeros(Tmsh, 0, 0, 0, 0)\n mesh.jac_face = zeros(Tmsh, 0, 0)\n\n mesh.dxidx_face_bar = zeros(mesh.dxidx_face)\n mesh.jac_face_bar = zeros(mesh.jac_face)\n\n # boundary faces\n mesh.dxidx_bndry = zeros(Tmsh, 0, 0, 0, 0)\n mesh.jac_bndry = zeros(Tmsh, 0, 0)\n\n mesh.dxidx_bndry_bar = zeros(mesh.dxidx_bndry)\n mesh.jac_bndry_bar = zeros(mesh.jac_bndry)\n\n # parallel shared faces\n mesh.dxidx_sharedface = Array{Array{Tmsh, 4}}(0)\n mesh.jac_sharedface = Array{Array{Tmsh, 2}}(0)\n\n mesh.dxidx_sharedface_bar = Array{Array{Tmsh, 4}}(0)\n mesh.jac_sharedface_bar = Array{Array{Tmsh, 2}}(0)\n else\n fill!(mesh.coords, 0.0)\n fill!(mesh.dxidx, 0.0)\n fill!(mesh.jac, 0.0)\n end\n\n\n return nothing\nend\n\n#------------------------------------------------------------------------------\n# curvilinear functions\n\n\"\"\"\n This function gets the coordinates that define the mesh \n (not the solution node coordinates) and puts them the mesh.vert_coords field\n of the mesh object. For each element, the ordering of the coordinates\n is verts, then edges, then faces, then regions. This function uses\n smart allocators to allocate the array if needed.\n\n Input:\n mesh: a DG mesh\n sbp: an SBP operators\n\"\"\"\nfunction getMeshCoordinates(mesh::PumiMeshDG{Tmsh}, sbp::AbstractSBP) where Tmsh\n\n allocateMeshCoordinateArray(mesh, sbp)\n\n coords_tmp = zeros(Float64, mesh.dim, mesh.coord_numNodesPerElement)\n for i=1:mesh.numEl\n el_i = mesh.elements[i]\n coords_i = sview(mesh.vert_coords, :, :, i)\n apf.getAllEntityCoords(mesh.m_ptr, el_i, coords_tmp)\n copy!(coords_i, coords_tmp)\n end\n\n return nothing\nend\n\n\"\"\"\n This function calculates the fields of the mesh that hold coordinates of the\n face nodes for boundaries, interfaces, and sharedfaces. This function uses\n smart allocators to allocate the arrays if needed\n\"\"\"\nfunction getFaceCoordinatesAndNormals(mesh::PumiMeshDG{Tmsh}, sbp::AbstractSBP) where Tmsh\n\n allocateFaceCoordinates(mesh)\n\n allocateNormals(mesh, sbp)\n\n if length(mesh.bndryfaces) > 0 # debugging: don't call if unneeded\n calcFaceCoordinatesAndNormals(mesh, sbp, mesh.bndryfaces, \n mesh.coords_bndry, mesh.nrm_bndry)\n end\n\n calcFaceCoordinatesAndNormals(mesh, sbp, mesh.interfaces, \n mesh.coords_interface, mesh.nrm_face)\n for i=1:mesh.npeers\n calcFaceCoordinatesAndNormals(mesh, sbp, mesh.bndries_local[i], \n mesh.coords_sharedface[i], mesh.nrm_sharedface[i])\n end\n\n return nothing\nend\n\n\"\"\"\n This function back propigates mesh.nrm_*_bar and mesh.coords_*_bar to\n mesh.vert_coords_bar. mesh.vert_coords_bar is updated (not overwritten)\n with the results.\n\"\"\"\nfunction getFaceCoordinatesAndNormals_rev(mesh::PumiMeshDG{Tmsh},\n sbp::AbstractSBP) where Tmsh\n if length(mesh.bndryfaces) > 0 # debugging: don't call if unneeded\n calcFaceCoordinatesAndNormals_rev(mesh, sbp, mesh.bndryfaces,\n mesh.coords_bndry,\n mesh.coords_bndry_bar,\n mesh.nrm_bndry,\n mesh.nrm_bndry_bar)\n end\n\n coords_face_bar = zeros(Tmsh, mesh.dim, mesh.numNodesPerFace, mesh.numInterfaces)\n calcFaceCoordinatesAndNormals_rev(mesh, sbp, mesh.interfaces, \n mesh.coords_interface, coords_face_bar,\n mesh.nrm_face, mesh.nrm_face_bar)\n\n for i=1:mesh.npeers\n coords_sharedface_bar = zeros(Tmsh, mesh.dim, mesh.numNodesPerFace, length(mesh.bndries_local[i]))\n calcFaceCoordinatesAndNormals_rev(mesh, sbp, mesh.bndries_local[i],\n mesh.coords_sharedface[i],\n coords_sharedface_bar, \n mesh.nrm_sharedface[i],\n mesh.nrm_sharedface_bar[i])\n end\n\n return nothing\nend\n\n\"\"\"\n This is the inner function used by getFaceCoordinatesandNormals. It\n gets the coordinates of the face nodes and their normal vectors for\n a given array of Interfaces/Boundaries\n\n Inputs:\n mesh: a DG mesh object\n faces: an array of Boundaries or Interfaces\n\n Inputs/Outputs\n coords_face: array Tdim x numNodesPerFace x length(faces)\n nrm_face: array, same size as coords_face\n\n Aliasing restrictions: none, although it would be weird if coords_face and\n nrm_face aliased\n\"\"\"\nfunction calcFaceCoordinatesAndNormals(\n mesh::PumiMeshDG{Tmsh}, sbp::AbstractSBP,\n faces::AbstractArray{I, 1}, \n coords_face::AbstractArray{Tmsh, 3}, \n nrm_face::AbstractArray{Tmsh, 3}) where {Tmsh, I <: Union{Boundary, Interface}}\n\n blocksize = 1000 # magic parameter: number of faces to do in a group\n nfaces = length(faces)\n\n # calculate number of blocks\n nblocks_full = div(nfaces, blocksize)\n nrem = nfaces % blocksize\n\n numNodesPerElement = mesh.coord_numNodesPerElement\n numNodesPerFace = mesh.coord_numNodesPerType[mesh.dim]\n\n # some temporary arrays\n down_faces = Array{Ptr{Void}}(12)\n coords_lag_face = Array{Tmsh}(mesh.dim, mesh.coord_numNodesPerFace, blocksize)\n\n # get the parametic coordinates of the face nodes\n face_xi = mesh.coord_facexi\n ref_verts = baryToXY(face_xi, mesh.sbpface.vtx)\n\n face_idx = 1 # index in faces array\n for block=1:nblocks_full\n start_idx = (block - 1)*blocksize + 1\n end_idx = block*blocksize\n coords_face_block = sview(coords_face, :, :, start_idx:end_idx)\n nrm_face_block = sview(nrm_face, :, :, start_idx:end_idx)\n\n # load up data for current block\n for i=1:blocksize\n el_i = getElementL(faces[face_idx])\n face_i = getFaceL(faces[face_idx])\n el_ptr = mesh.elements[el_i]\n\n coords_i = sview(coords_lag_face, :, :, i)\n getMeshFaceCoordinates(mesh, el_i, face_i, coords_i)\n face_idx += 1\n end\n\n\n # populate output array for current block\n calcFaceNormals!(mesh.sbpface, mesh.coord_order, ref_verts, coords_lag_face,\n coords_face_block, nrm_face_block)\n fill!(coords_lag_face, 0.0)\n\n fixOutwardNormal(mesh, sview(faces, start_idx:end_idx), nrm_face_block)\n end # end loop over full blocks\n\n # do remainder loop\n start_idx = nblocks_full*blocksize + 1\n end_idx = nfaces\n @assert end_idx - start_idx + 1 <= blocksize\n @assert end_idx - start_idx + 1 == nrem\n\n coords_face_block = sview(coords_face, :, :, start_idx:end_idx)\n nrm_face_block = sview(nrm_face, :, :, start_idx:end_idx)\n coords_lag_face_block = sview(coords_lag_face, :, :, 1:nrem)\n\n for i=1:nrem # loop over remaining faces\n el_i = getElementL(faces[face_idx])\n face_i = getFaceL(faces[face_idx])\n el_ptr = mesh.elements[el_i]\n\n coords_i = sview(coords_lag_face, :, :, i)\n getMeshFaceCoordinates(mesh, el_i, face_i, coords_i)\n face_idx += 1\n\n\n end\n\n calcFaceNormals!(mesh.sbpface, mesh.coord_order, ref_verts, \n coords_lag_face_block, coords_face_block, nrm_face_block)\n\n # make sure the normal vectors point outwards\n fixOutwardNormal(mesh, sview(faces, start_idx:end_idx), nrm_face_block)\n\n return nothing\nend\n\n\"\"\"\n Reverse mode of calcFaceCoordinatesAndNormals_rev, back propigates\n coords_face_bar and nrm_face_bar to mesh.vertcoords_bar.\n\n This function also recalculates coords_face and nrm_face in the course\n of doing the reverse mode.\n\"\"\"\nfunction calcFaceCoordinatesAndNormals_rev(\n mesh::PumiMeshDG{Tmsh}, sbp::AbstractSBP,\n faces::AbstractArray{I, 1},\n coords_face::AbstractArray{Tmsh, 3},\n coords_face_bar::AbstractArray{Tmsh, 3},\n nrm_face::AbstractArray{Tmsh, 3},\n nrm_face_bar::AbstractArray{Tmsh, 3}; print=false) where {Tmsh, I <: Union{Boundary, Interface}}\n\n blocksize = 1000 # magic parameter: number of faces to do in a group\n nfaces = length(faces)\n\n # calculate number of blocks\n nblocks_full = div(nfaces, blocksize)\n nrem = nfaces % blocksize\n\n numNodesPerElement = mesh.coord_numNodesPerElement\n numNodesPerFace = mesh.coord_numNodesPerType[mesh.dim]\n\n # some temporary arrays\n down_faces = Array{Ptr{Void}}(12)\n coords_lag_face = Array{Tmsh}(mesh.dim, mesh.coord_numNodesPerFace, blocksize)\n coords_lag_face_bar = zeros(coords_lag_face)\n\n # get the parametic coordinates of the face nodes\n face_xi = mesh.coord_facexi\n ref_verts = baryToXY(face_xi, mesh.sbpface.vtx)\n\n for block=1:nblocks_full\n start_idx = (block - 1)*blocksize + 1\n end_idx = block*blocksize\n faces_block = sview(faces, start_idx:end_idx)\n coords_face_block = sview(coords_face, :, :, start_idx:end_idx)\n coords_face_bar_block = sview(coords_face_bar, :, :, start_idx:end_idx)\n nrm_face_block = sview(nrm_face, :, :, start_idx:end_idx)\n nrm_face_bar_block = sview(nrm_face_bar, :, :, start_idx:end_idx)\n\n # load up data for current block\n for i=1:blocksize\n el_i = getElementL(faces_block[i])\n face_i = getFaceL(faces_block[i])\n el_ptr = mesh.elements[el_i]\n\n coords_i = sview(coords_lag_face, :, :, i)\n getMeshFaceCoordinates(mesh, el_i, face_i, coords_i)\n end\n\n\n # forward sweep\n # need the *original* face normals for fix_outward_normal, so recalculate\n # them here\n calcFaceNormals!(mesh.sbpface, mesh.coord_order, ref_verts, coords_lag_face,\n coords_face_block, nrm_face_block)\n\n # reverse sweep\n fixOutwardNormal_rev(mesh, sview(faces, start_idx:end_idx), nrm_face_block,\n nrm_face_bar_block)\n\n fill!(coords_lag_face_bar, 0.0)\n calcFaceNormals_rev!(mesh.sbpface, mesh.coord_order, ref_verts,\n coords_lag_face, coords_lag_face_bar,\n coords_face_bar_block, nrm_face_bar_block)\n\n #TODO: unecessary?\n fill!(coords_lag_face, 0.0)\n\n for i=1:blocksize\n el_i = getElementL(faces_block[i])\n face_i = getFaceL(faces_block[i])\n el_ptr = mesh.elements[el_i]\n\n coords_bar_i = sview(coords_lag_face_bar, :, :, i)\n getMeshFaceCoordinates_rev(mesh, el_i, face_i, coords_bar_i)\n end\n end # end loop over full blocks\n\n # do remainder loop\n start_idx = nblocks_full*blocksize + 1\n end_idx = nfaces\n @assert end_idx - start_idx + 1 <= blocksize\n @assert end_idx - start_idx + 1 == nrem\n\n faces_block = sview(faces, start_idx:end_idx)\n coords_face_block = sview(coords_face, :, :, start_idx:end_idx)\n coords_face_bar_block = sview(coords_face_bar, :, :, start_idx:end_idx)\n nrm_face_block = sview(nrm_face, :, :, start_idx:end_idx)\n nrm_face_bar_block = sview(nrm_face_bar, :, :, start_idx:end_idx)\n coords_lag_face_block = sview(coords_lag_face, :, :, 1:nrem)\n coords_lag_face_bar_block = sview(coords_lag_face_bar, :, :, 1:nrem)\n\n \n for i=1:nrem # loop over remaining faces\n el_i = getElementL(faces_block[i])\n face_i = getFaceL(faces_block[i])\n\n coords_i = sview(coords_lag_face, :, :, i)\n getMeshFaceCoordinates(mesh, el_i, face_i, coords_i)\n end\n\n # forward sweep\n # we need to use the *original* face normals, not the already reversed\n # ones for fixOutwardNormal_rev\n calcFaceNormals!(mesh.sbpface, mesh.coord_order, ref_verts, \n coords_lag_face_block, coords_face_block, nrm_face_block)\n\n # reverse sweep\n fixOutwardNormal_rev(mesh, sview(faces, start_idx:end_idx), nrm_face_block,\n nrm_face_bar_block)\n\n fill!(coords_lag_face_bar, 0.0)\n\n calcFaceNormals_rev!(mesh.sbpface, mesh.coord_order, ref_verts, \n coords_lag_face_block, coords_lag_face_bar_block,\n coords_face_bar_block, nrm_face_bar_block)\n\n for i=1:nrem\n el_i = getElementL(faces_block[i])\n face_i = getFaceL(faces_block[i])\n\n coords_bar_i = sview(coords_lag_face_bar_block, :, :, i)\n getMeshFaceCoordinates_rev(mesh, el_i, face_i, coords_bar_i)\n end\n\n return nothing\nend\n\n\n\n\"\"\"\n This function check to make sure each face normal vector is oriented\n outwards, and flips it if needed.\n\n Inputs:\n mesh\n faces: array of Boundary of Interfaces to check for normal orientation\n\n Inputs/Outputs:\n nrm_face: array of size mesh.dim x mesh.numNodesPerFace x length(faces)\n containing the normal vector at each node of each face.\n Updated in place to make normal vector point outward\n\"\"\"\nfunction fixOutwardNormal(mesh, \nfaces::AbstractArray{I, 1},\nnrm_face::AbstractArray{Tmsh, 3}) where {I <: Union{Boundary, Interface}, Tmsh}\n\n\n nfaces = length(faces)\n should_flip_node = Array{Bool}(mesh.numNodesPerFace)\n for i=1:nfaces\n is_inward_normal(mesh, faces[i], sview(nrm_face, :, :, i), should_flip_node)\n\n for j=1:mesh.numNodesPerFace\n if should_flip_node[j]\n for p=1:mesh.dim\n nrm_face[p, j, i] = -nrm_face[p, j, i]\n end\n end\n end # end j\n\n end # end loop i\n\n return nothing\nend\n\n\"\"\"\n Reverse mode of fixOutwardNormal, reverses the primal normal vectors.\n On entry nrm_face should have the normal vectors as calculated by\n SBP. On exit, they will point outwards.\n\n Inputs:\n mesh\n faces\n\n Inputs/Outputs:\n nrm_face\n nrm_face_bar: adjoint part of nrm_face\n\"\"\"\nfunction fixOutwardNormal_rev(mesh,\n faces::AbstractArray{I, 1},\n nrm_face::AbstractArray{Tmsh, 3},\n nrm_face_bar::AbstractArray{Tmsh, 3}) where {Tmsh, I <: Union{Boundary, Interface}}\n\n nfaces = length(faces)\n should_flip_node = Array{Bool}(mesh.numNodesPerFace)\n for i=1:nfaces\n is_inward_normal(mesh, faces[i], sview(nrm_face, :, :, i), should_flip_node)\n\n for j=1:mesh.numNodesPerFace\n if should_flip_node[j]\n for p=1:mesh.dim\n nrm_face_bar[p, j, i] = -nrm_face_bar[p, j, i]\n nrm_face[p, j, i] = -nrm_face[p, j, i]\n end\n end\n end # end j\n\n end # end loop i\n\n return nothing\nend\n\n\n\n\"\"\"\n Check if the normal vector on each node of a face is pointing inward\n\n The algorithm determines orientation by comparing the normal vector against\n the vector along an edge of the simplex (from the vertex not on the face to\n the vertex on the face). For highly skewed elements, using different\n vertices on the face to compute the vector can give different results, so\n only the vector with the largest magnitude dot product with the normal vector\n is considered.\n\n Inputs:\n mesh: the mesh\n iface: either a Boundary or an Interface\n nrm_face: mesh.dim x mesh.numNodesPerFace array containing the normal\n vectors for each face node\n\n Inputs/Outputs:\n should_flip_node: an Bool array of length numNodesPerFace specifying whether\n the normal vector at each node is pointing inward\n\"\"\"\nfunction is_inward_normal(mesh, iface::Union{Boundary, Interface},\n nrm_face::AbstractMatrix{Tmsh},\n should_flip_node::AbstractVector{Bool}) where Tmsh\n\n tmp = zeros(3) # temporary vector to hold coordinates\n topo = mesh.topo\n numVertPerElement = mesh.numTypePerElement[1]\n numVertPerFace = numVertPerElement - 1\n\n # temporary arrays\n# el_verts = Array{Ptr{Void}}(numVertPerElement)\n other_vert_coords = zeros(Tmsh, mesh.dim)\n# face_verts = Array{Ptr{Void}}(numVertPerElement - 1)\n face_vert_coords = zeros(Tmsh, mesh.dim, numVertPerFace)\n\n elnum = getElementL(iface)\n facenum_local = getFaceL(iface)\n\n# el_i = mesh.elements[elnum]\n# apf.getDownward(mesh.m_ptr, el_i, 0, el_verts)\n\n for j=1:numVertPerFace\n v_j = topo.face_verts[j, facenum_local]\n\n for p=1:mesh.dim\n face_vert_coords[p, j] = mesh.vert_coords[p, v_j, elnum]\n end\n end\n\n # get the vert not on the face\n other_vert = 0\n for j=1:numVertPerElement\n if !(j in sview(topo.face_verts, :, facenum_local))\n other_vert = j\n end\n end\n\n for p=1:mesh.dim\n other_vert_coords[p] = mesh.vert_coords[p, other_vert, elnum]\n end\n # check that the face normal is in the opposite direction as the\n # vectors from a vertex on the face to the vertex not on the face\n\n # in some cases the normal vector can be nearly orthoogonal to vertex\n # vectors, so use the one with the greatest magnitude dot product\n should_flip = false\n max_mag = 0.0 # maximum dot product\n for j=1:mesh.numNodesPerFace\n outward_count = 0 # count number of calculations that showed outward\n for k=1:numVertPerFace\n val = zero(Tmsh)\n for p=1:mesh.dim\n r1_p = other_vert_coords[p] - face_vert_coords[p, k]\n val += nrm_face[p, j]*r1_p # accumulate dot product\n end\n \n if abs(val) > max_mag\n max_mag = abs(val)\n # flip if the value is greater than 0\n should_flip = real(val) > 0\n #=\n if val < 0\n should_flip = false\n else \n should_flip = true\n end # end if\n =#\n\n end \n end # end k\n\n should_flip_node[j] = should_flip\n end # end loop j\n\n return nothing\nend\n\n\n\n\n\"\"\"\n This function calculates the node coordinates, scaled mapping jacobian, and\n mapping jacobian determinant for a curvilinear mesh and stores them to\n the fields of the mesh object. This function uses smart allocators to\n allocate the arrays if needed\n\n Inputs:\n mesh: a DG mesh object\n sbp: an SBP operator\n\"\"\"\nfunction getCurvilinearCoordinatesAndMetrics(mesh::PumiMeshDG{Tmsh}, \n sbp::AbstractSBP) where Tmsh\n\n allocateCurvilinearCoordinateAndMetricArrays(mesh, sbp)\n\n ref_vtx = baryToXY(mesh.coord_xi, sbp.vtx)\n# if mesh.dim == 2\n# calcMappingJacobian!(sbp, mesh.coord_order, ref_vtx, mesh.vert_coords, \n# mesh.coords, mesh.dxidx, mesh.jac)\n# else # need to calculate Eone\n\n # block format\n blocksize = 1000 # number of elements per block\n nblocks_full = div(mesh.numEl, blocksize)\n nrem = mesh.numEl % blocksize\n\n Eone = zeros(Tmsh, mesh.numNodesPerElement, mesh.dim, blocksize)\n\n for block=1:nblocks_full\n start_idx = (block - 1)*blocksize + 1\n end_idx = block*blocksize\n element_range = start_idx:end_idx\n \n getCurvilinearMetricsAndCoordinates_inner(mesh, sbp, element_range, Eone)\n \n end # end loop over blocks\n\n if nrem != 0\n # remainder block\n start_idx = nblocks_full*blocksize + 1\n end_idx = mesh.numEl\n @assert end_idx - start_idx + 1 <= blocksize\n @assert end_idx - start_idx + 1 == nrem\n\n element_range = start_idx:end_idx\n\n # make sure dimensions of Eone is correct (number of elements might be\n # less than before)\n Eone_rem = sview(Eone, :, :, 1:nrem)\n\n getCurvilinearMetricsAndCoordinates_inner(mesh, sbp, element_range, Eone_rem)\n end\n# end # end if dim == 2\n\n return nothing\nend\n\n\"\"\"\n Back propigate dxidx to mesh.vert_coords and mesh.nrm. See the primal method\n for details.\n\n Inputs:\n mesh: vert_coords_bar, nrm_face_bar, nrm_bndry_bar, nrm_sharedface are\n updated with the results\n sbp:\n\"\"\"\nfunction getCurvilinearCoordinatesAndMetrics_rev(mesh::PumiMeshDG{Tmsh},\n sbp::AbstractSBP) where Tmsh\n\n # we have to compute E1_bar for both 2d and 3D\n blocksize = 1000 # number of elements per block\n nblocks_full = div(mesh.numEl, blocksize)\n nrem = mesh.numEl % blocksize\n\n Eone_bar = zeros(Tmsh, mesh.numNodesPerElement, mesh.dim, blocksize)\n\n for block=1:nblocks_full\n start_idx = (block - 1)*blocksize + 1\n end_idx = block*blocksize\n element_range = start_idx:end_idx\n\n fill!(Eone_bar, 0.0)\n getCurvilinearMetricsAndCoordinates_inner_rev(mesh, sbp, element_range,\n Eone_bar)\n end\n\n if nrem != 0\n # remainder block\n start_idx = nblocks_full*blocksize + 1\n end_idx = mesh.numEl\n @assert end_idx - start_idx + 1 <= blocksize\n @assert end_idx - start_idx + 1 == nrem\n\n element_range = start_idx:end_idx\n\n # make sure dimensions of Eone is correct (number of elements might be\n # less than before)\n Eone_bar_rem = sview(Eone_bar, :, :, 1:nrem)\n\n fill!(Eone_bar_rem, 0.0)\n getCurvilinearMetricsAndCoordinates_inner_rev(mesh, sbp, element_range,\n Eone_bar_rem)\n end\n\n return Eone_bar\nend\n\n\n\"\"\"\n This function calculates the metrics and coordinates for one block of \n elements. Used by getCurvilinearMetricsAndCoordinates\n\"\"\"\nfunction getCurvilinearMetricsAndCoordinates_inner(mesh, sbp, \n element_range::UnitRange, Eone::AbstractArray{T, 3}) where T\n\n # calculate Eone for current range\n\n vert_coords_block = sview(mesh.vert_coords, :, :, element_range)\n coords_block = sview(mesh.coords, :, :, element_range)\n dxidx_block = sview(mesh.dxidx, :, :, :, element_range)\n jac_block = sview(mesh.jac, :, element_range)\n ref_vtx = baryToXY(mesh.coord_xi, sbp.vtx)\n\n calcEone(mesh, sbp, element_range, Eone)\n\n #=\n println(\"checking Eone\")\n for el=1:size(Eone, 3)\n println(\"el = \", el)\n println(\"Eone = \\n\", Eone[:, :, el])\n for d=1:mesh.dim\n println(\" d = \", d)\n val = abs(sum(Eone[:, d, el]))\n println(\" val = \", val)\n @assert val < 1e-6\n end\n end\n =#\n\n#= \n println(\"sbp.numnodes = \", sbp.numnodes)\n println(\"size(coords) = \", size(coords_block))\n println(\"size(dxidx) = \", size(dxidx_block))\n println(\"size(jac) = \", size(jac_block))\n println(\"size(Eone) = \", size(Eone))\n=# \n calcMappingJacobian!(sbp, mesh.coord_order, ref_vtx, vert_coords_block, \n coords_block, dxidx_block, jac_block, Eone)\n\n fill!(Eone, 0.0)\n return nothing\nend\n\n\"\"\"\n This function calculates the metrics and coordinates for one block of \n elements. Used by getCurvilinearMetricsAndCoordinates\n\"\"\"\nfunction getCurvilinearMetricsAndCoordinates_inner_rev(mesh, sbp, \n element_range::UnitRange, Eone_bar::AbstractArray{T, 3}) where T\n\n\n vert_coords_block = sview(mesh.vert_coords, :, :, element_range)\n # we don't allow perturbing mesh coordinate directly (yet)\n coords_bar_block = zeros(T, mesh.dim, mesh.numNodesPerElement, length(element_range))\n dxidx_block = sview(mesh.dxidx, :, :, :, element_range)\n dxidx_bar_block = sview(mesh.dxidx_bar, :, :, :, element_range)\n# jac_block = sview(mesh.jac, :, element_range)\n jac_bar_block = sview(mesh.jac_bar, :, element_range)\n #@assert vecnorm(jac_bar_block) < 1e-13 # this is currently broken in SBP\n\n # outputs\n vert_coords_bar_block = sview(mesh.vert_coords_bar, :, :, element_range)\n fill!(Eone_bar, 0.0)\n\n ref_vtx = baryToXY(mesh.coord_xi, sbp.vtx)\n\n # back propigate dxidx to vert_coords, E1\n calcMappingJacobian_rev!(sbp, mesh.coord_order, ref_vtx, vert_coords_block, \n vert_coords_bar_block, coords_bar_block,\n dxidx_bar_block, jac_bar_block, Eone_bar)\n\n # back propigate E1 to the face normals\n calcEone_rev(mesh, sbp, element_range, Eone_bar)\n\n return nothing\nend\n\nfunction calcEone(mesh::PumiMeshDG{Tmsh}, sbp, element_range, \n Eone::AbstractArray{Tmsh, 3}) where Tmsh\n\n # search interfaces and bndryfaces\n\n first_el = element_range[1]\n last_el = element_range[end]\n\n offset = first_el - 1\n\n # R times vector of ones\n # the permutation doesn't matter because it is being multiplied by a constant\n # vector.\n # also R1 = 1 by definition\n Rone = ones(Float64, mesh.numNodesPerFace)\n# Rone = vec(sum(mesh.sbpface.interp.', 2))\n sbpface = mesh.sbpface\n tmp = zeros(Tmsh, length(Rone))\n nrmL = zeros(Tmsh, mesh.dim, sbpface.numnodes)\n\n # accumulate E1 for a given element\n Eone_el = zeros(Tmsh, size(sbpface.perm, 1), mesh.dim)\n\n for i=1:mesh.numInterfaces\n iface_i = mesh.interfaces[i]\n\n if iface_i.elementL >= first_el && iface_i.elementL <= last_el\n elnum = iface_i.elementL\n facenum_local = iface_i.faceL\n nrm = sview(mesh.nrm_face, :, :, i)\n\n # call inner functions\n calcEoneElement(sbpface, nrm, Rone, tmp, Eone_el)\n assembleEone(sbpface, elnum - offset, facenum_local, Eone_el, Eone)\n\n end\n\n if iface_i.elementR >= first_el && iface_i.elementR <= last_el\n # do same as above, negating and permuting nrm\n elnum = iface_i.elementR\n facenum_local = iface_i.faceR\n orient = iface_i.orient\n for j=1:sbpface.numnodes\n for d=1:mesh.dim\n nrmL[d, j] = -mesh.nrm_face[d, sbpface.nbrperm[j, orient], i]\n end\n end\n \n calcEoneElement(sbpface, nrmL, Rone, tmp, Eone_el)\n assembleEone(sbpface, elnum - offset, facenum_local, Eone_el, Eone)\n end # end if/else\n\n end # end loop over interfaces\n\n for i=1:mesh.numBoundaryFaces\n bface_i = mesh.bndryfaces[i]\n\n if bface_i.element >= first_el && bface_i.element <= last_el\n elnum = bface_i.element\n facenum_local = bface_i.face\n nrm = sview(mesh.nrm_bndry, :, :, i)\n\n # call inner functions\n calcEoneElement(sbpface, nrm, Rone, tmp, Eone_el)\n assembleEone(sbpface, elnum - offset, facenum_local, Eone_el, Eone)\n end\n end # end loop over boundary faces\n\n # check shared faces\n for peer=1:mesh.npeers\n bndryfaces_peer = mesh.bndries_local[peer]\n nrm_peer = mesh.nrm_sharedface[peer]\n for i=1:mesh.peer_face_counts[peer]\n bface_i = bndryfaces_peer[i]\n\n if bface_i.element >= first_el && bface_i.element <= last_el\n elnum = bface_i.element\n facenum_local = bface_i.face\n nrm = sview(nrm_peer, :, :, i)\n\n calcEoneElement(sbpface, nrm, Rone, tmp, Eone_el)\n assembleEone(sbpface, elnum - offset, facenum_local, Eone_el, Eone)\n end\n end\n end\n\n\n\n return nothing\nend\n\n\"\"\"\n Back propigates Eone_bar to the various normal vectors stored in the\n mesh objects (bndry, face, sharedface)\n\n Inputs:\n mesh: mesh.nrm_face_bar, mesh.nrm_bndry_bar, mesh.nrm_sharedface_bar are\n updated\n sbp\n element range: range of elements to compute\n Eone_bar: the adjoint part of Eone, see the primal method for details\n\"\"\"\nfunction calcEone_rev(mesh::PumiMeshDG{Tmsh}, sbp, element_range, \n Eone_bar::AbstractArray{Tmsh, 3}) where Tmsh\n\n # search interfaces and bndryfaces\n\n first_el = element_range[1]\n last_el = element_range[end]\n\n offset = first_el - 1\n\n # R times vector of ones\n # the permutation doesn't matter because it is being multiplied by a constant\n # vector.\n # also R1 = 1 by def.inition\n Rone = ones(Float64, mesh.numNodesPerFace)\n# Rone = vec(sum(mesh.sbpface.interp.', 2))\n sbpface = mesh.sbpface\n tmp = zeros(Rone)\n nrmL_bar = zeros(Tmsh, mesh.dim, sbpface.numnodes)\n\n # accumulate E1 for a given element\n Eone_el_bar = zeros(Tmsh, size(sbpface.perm, 1), mesh.dim)\n\n for i=1:mesh.numInterfaces\n iface_i = mesh.interfaces[i]\n\n if iface_i.elementL >= first_el && iface_i.elementL <= last_el\n elnum = iface_i.elementL\n facenum_local = iface_i.faceL\n nrm_bar = sview(mesh.nrm_face_bar, :, :, i)\n\n # call inner functions\n fill!(Eone_el_bar, 0.0)\n assembleEone_rev(sbpface, elnum - offset, facenum_local, Eone_el_bar,\n Eone_bar)\n calcEoneElement_rev(sbpface, nrm_bar, Rone, tmp, Eone_el_bar)\n\n end\n\n if iface_i.elementR >= first_el && iface_i.elementR <= last_el\n # do same as above, negating and permuting nrm\n elnum = iface_i.elementR\n facenum_local = iface_i.faceR\n orient = iface_i.orient\n\n fill!(Eone_el_bar, 0.0)\n fill!(nrmL_bar, 0.0)\n assembleEone_rev(sbpface, elnum - offset, facenum_local, Eone_el_bar,\n Eone_bar)\n calcEoneElement_rev(sbpface, nrmL_bar, Rone, tmp, Eone_el_bar)\n\n for j=1:sbpface.numnodes\n for d=1:mesh.dim\n mesh.nrm_face_bar[d, sbpface.nbrperm[j, orient], i] -= nrmL_bar[d, j]\n end\n end\n \n end # end if/else\n\n end # end loop over interfaces\n\n for i=1:mesh.numBoundaryFaces\n bface_i = mesh.bndryfaces[i]\n\n if bface_i.element >= first_el && bface_i.element <= last_el\n elnum = bface_i.element\n facenum_local = bface_i.face\n nrm_bar = sview(mesh.nrm_bndry_bar, :, :, i)\n\n # call inner functions\n fill!(Eone_el_bar, 0.0)\n assembleEone_rev(sbpface, elnum - offset, facenum_local, Eone_el_bar, \n Eone_bar)\n calcEoneElement_rev(sbpface, nrm_bar, Rone, tmp, Eone_el_bar)\n end\n end # end loop over boundary faces\n\n # check shared faces\n for peer=1:mesh.npeers\n bndryfaces_peer = mesh.bndries_local[peer]\n nrm_peer_bar = mesh.nrm_sharedface_bar[peer]\n for i=1:mesh.peer_face_counts[peer]\n bface_i = bndryfaces_peer[i]\n\n if bface_i.element >= first_el && bface_i.element <= last_el\n elnum = bface_i.element\n facenum_local = bface_i.face\n nrm_bar = sview(nrm_peer_bar, :, :, i)\n\n fill!(Eone_el_bar, 0.0)\n assembleEone_rev(sbpface, elnum - offset, facenum_local, Eone_el_bar,\n Eone_bar)\n calcEoneElement_rev(sbpface, nrm_bar, Rone, tmp, Eone_el_bar)\n end\n end\n end\n\n return nothing\nend\n\n\n\n\"\"\"\n Calculates E1 for a given interface. Used by calcEone.\n\n Actually what it computes is:\n (R^T)*N*B*R*P*1\n\n Note that there should be a factor of P^T on the left. That factor is\n applied in assembleEone().\n\n Inputs:\n sbpface: an AbstractFace\n nrm: the normal vectors for each node of the face, dim x numFaceNodes\n Rone: the interpolation operator R times the vector of ones\n tmp: a temporary vector of length numFaceNodes, overwritten\n\n Inputs/Outputs:\n Eone_el: sbp.stencilsize x dim matrix to be populated with the E\n contribution for this face. Overwritten.\n\n\"\"\"\nfunction calcEoneElement(sbpface::AbstractFace, nrm::AbstractMatrix, \n Rone::AbstractVector, tmp::AbstractVector, \n Eone_el::AbstractMatrix)\n\n dim = size(Eone_el, 2)\n numFaceNodes = length(Rone)\n for d=1:dim\n for i=1:numFaceNodes\n tmp[i] = Rone[i]*nrm[d, i]*sbpface.wface[i]\n end\n\n Eone_dim = sview(Eone_el, :, d)\n smallmatvec!(sbpface.interp, tmp, Eone_dim)\n end\n\n return nothing\nend\n\n\"\"\"\n This methods works for SparseFaces (ex. diagonlE operators).\n It takes in all the same arguments as the other method for compatability\n but does not need them\n\"\"\"\nfunction calcEoneElement(sbpface::SparseFace, nrm::AbstractMatrix, \n Rone::AbstractVector, tmp::AbstractVector, \n Eone_el::AbstractMatrix)\n\n dim = size(Eone_el, 2)\n numFaceNodes = length(Rone)\n for d=1:dim\n for i=1:numFaceNodes\n Eone_el[i, d] = Rone[i]*nrm[d, i]*sbpface.wface[i]\n end\n end\n\n return nothing\nend\n\n\n# back propigate Eone_el_bar to nrm_bar\n\"\"\"\n This function uses reverse mode to back-propigate Eone_el_bar to nrm_bar\n\n Input:\n sbpface: an AbstractFace\n Rone: the interpolation operator R times a vector of ones\n tmp: a temporary vector, overwritten\n Eone_el_bar: the adjoint part of E1\n\n Inputs/Outputs:\n nrm_bar: the adjoint part of the scaled face normal vector in x-y space\n updated with the contribution from this function\n\n\"\"\"\nfunction calcEoneElement_rev(sbpface::AbstractFace,\n nrm_bar::AbstractMatrix,\n Rone::AbstractVector, tmp_bar::AbstractVector, \n Eone_el_bar::AbstractMatrix)\n\n dim = size(Eone_el_bar, 2)\n numFaceNodes = length(Rone)\n\n for d=1:dim\n # this function is linear, so no need for a forward sweep\n\n # reverse sweep\n Eone_dim_bar = sview(Eone_el_bar, :, d)\n # only back propigate to tmp_bar (sbpface.interp is unimportant)\n fill!(tmp_bar, 0.0)\n smallmatvec_revv!(sbpface.interp, tmp_bar, Eone_dim_bar)\n\n for i=1:numFaceNodes\n nrm_bar[d, i] += tmp_bar[i]*Rone[i]*sbpface.wface[i]\n end\n end\n\n return nothing\nend\n\n\"\"\"\n This method works for SparseFace sbp face objects.\n\"\"\"\nfunction calcEoneElement_rev(sbpface::SparseFace,\n nrm_bar::AbstractMatrix,\n Rone::AbstractVector, tmp_bar::AbstractVector, \n Eone_el_bar::AbstractMatrix)\n\n dim = size(Eone_el_bar, 2)\n numFaceNodes = length(Rone)\n\n for d=1:dim\n for i=1:numFaceNodes\n nrm_bar[d, i] += Eone_el_bar[i, d]*Rone[i]*sbpface.wface[i]\n end\n end\n\n return nothing\nend\n\n\n\n\n\n\"\"\"\n Takes an Eone_el matrix from calcEoneElement and assemble it into the big\n Eone.\n\n Inputs:\n sbpface: an SBP face\n elnum: the element index of Eone to put the values into. Note that if\n Eone is for the entire mesh, then this is the element number. If\n Eone is for a range of elements, then elnum is the index of the\n element within the range.\n Eone_el: the E1 contribution of an element\n\n Inputs/Output\n Eone: a numNodesPerElement x dim x blocksize array to store E1 for a\n range of elements, updated with the new contribution\n\"\"\"\nfunction assembleEone(sbpface::AbstractFace, elnum::Integer, \n facenum_local::Integer, Eone_el::AbstractMatrix{Tmsh}, \n Eone::AbstractArray{Tmsh, 3}) where Tmsh\n\n dim = size(Eone, 2)\n for d=1:dim\n for i=1:size(sbpface.perm, 1)\n p_i = sbpface.perm[i, facenum_local]\n Eone[p_i, d, elnum] += Eone_el[i, d]\n end\n end\n\n return nothing\nend\n\n\"\"\"\n Back propigates Eone_bar to Eone_el_bar.\n\n Inputs:\n sbpface: an AbstractFace\n elnum: the element number\n facenum_local: the local number of the face that Eone_el is calculated for\n Eone_bar: the adjoint part\n\n Inputs/Outputs:\n Eone_el_bar: the adjoint part\n\"\"\"\nfunction assembleEone_rev(sbpface::AbstractFace, elnum::Integer, \n facenum_local::Integer,\n Eone_el_bar::AbstractMatrix{Tmsh},\n Eone_bar::AbstractArray{Tmsh, 3}) where Tmsh\n\n dim = size(Eone_bar, 2)\n for d=1:dim # TODO: switch loops: turn an indexed store into a strided store\n for i=1:size(sbpface.perm, 1)\n p_i = sbpface.perm[i, facenum_local]\n # reverse mode step\n Eone_el_bar[i, d] += Eone_bar[p_i, d, elnum]\n end\n end\n\n return nothing\nend\n\n\n# get the coordinates of the nodes on a given face (in the coordinate field, not\n# the solution field)\n# this only works up to second order, and uses the ElementTopology to figure\n# out the orientation of the edge\n# elnum is the global element number\n# facenum is the local face number\n\"\"\"\n This function gets the coordinates of the coordinate field nodes of the\n face of an element, in the orientation specified by mesh.topo. This only\n works up to second order. It uses the SBP element topology to determine\n the ordering of the nodes. I guess this makes sense because calcFaceNormals\n is an SBP function and requires its definition of the vertices that define the\n face. Because ref_vtx is passed into calcFaceNormals, it should be ok to \n use the Pumi definition of the coordinates of the reference nodes (precisely\n because we use the SBP definition of which vertices define the face, the\n face node coordinates are relative to those vertices).\n \n Inputs:\n mesh: a 2D mesh\n elnum: the global element number\n facenum: the local face number\n\n Inputs/Outputs:\n coords: array to be populated with the coordinates, Tdim x \n number of coordinate nodes on a face (2 for linear 2D, \n 3 for quadratic 2D)\n\"\"\"\nfunction getMeshFaceCoordinates(mesh::PumiMesh2DG, elnum::Integer,\n facenum::Integer, \n coords::AbstractMatrix)\n\n# coords = a 2 x number of nodes on the face array to be populated with the\n# coordinates\n\n topo = mesh.topo\n\n # equivalent to topo.face_verts[:, facenum]\n v1_idx = topo.face_verts[1, facenum]\n v2_idx = topo.face_verts[2, facenum]\n\n coords[1, 1] = mesh.vert_coords[1, v1_idx, elnum]\n coords[2, 1] = mesh.vert_coords[2, v1_idx, elnum]\n\n coords[1, 2] = mesh.vert_coords[1, v2_idx, elnum]\n coords[2, 2] = mesh.vert_coords[2, v2_idx, elnum]\n\n if mesh.coord_numNodesPerType[2] > 0\n edge_idx = 3 + topo.face_edges[1, facenum]\n coords[1, 3] = mesh.vert_coords[1, edge_idx, elnum]\n coords[2, 3] = mesh.vert_coords[2, edge_idx, elnum]\n end\n\n return nothing\nend\n\n\"\"\"\n This function is the reverse mode of getMeshFaceCoordinates\n This function stores the adjoint part of the vert_coords to mesh.vert_coords\n\n 2nd order coordinate fields only.\n\n This function *accumulates* into mesh.vertcoords_bar.\n\n Inputs\n mesh::PumiMesh2DG\n elnum: the element number\n facenum: the local face number\n coords_bar: the adjoint part of the coordinate field for the given face,\n 2 x coord_numNodesPerFace.\n The data should be ordered vertices, then mid edge nodes.\n\"\"\"\nfunction getMeshFaceCoordinates_rev(mesh::PumiMesh2DG, elnum::Integer,\n facenum::Integer, \n coords_bar::AbstractMatrix)\n\n# vertmap = mesh.topo_pumi.face_verts\n topo = mesh.topo_pumi\n\n # equivalent to topo.face_verts[:, facenum]\n v1_idx = topo.face_verts[1, facenum]\n v2_idx = topo.face_verts[2, facenum]\n\n mesh.vert_coords_bar[1, v1_idx, elnum] += coords_bar[1, 1]\n mesh.vert_coords_bar[2, v1_idx, elnum] += coords_bar[2, 1]\n\n mesh.vert_coords_bar[1, v2_idx, elnum] += coords_bar[1, 2]\n mesh.vert_coords_bar[2, v2_idx, elnum] += coords_bar[2, 2]\n\n if mesh.coord_numNodesPerType[2] > 0\n edge_idx = facenum + 3 # for simplex elements\n mesh.vert_coords_bar[1, edge_idx, elnum] += coords_bar[1, 3]\n mesh.vert_coords_bar[2, edge_idx, elnum] += coords_bar[2, 3]\n end\n\n\n return nothing\nend\n\n\nfunction getMeshFaceCoordinates(mesh::PumiMesh3DG, elnum::Integer,\n facenum::Integer, coords::AbstractMatrix)\n\n topo = mesh.topo\n # get the face vertices\n face_vert_idx = sview(topo.face_verts, :, facenum)\n\n for i=1:3 # 3 vertices per face\n for j=1:3 # 3 coordinates at each vertex\n coords[j, i] = mesh.vert_coords[j, face_vert_idx[i], elnum]\n end\n end\n\n if mesh.coord_numNodesPerType[2] > 0\n for i=1:3 # 3 edges per face\n edge_idx = topo.face_edges[i, facenum] + 4 # 4 = numVerts\n for j=1:3 # 3 coordinates per face\n coords[j, 3 + i] = mesh.vert_coords[j, edge_idx, elnum]\n end\n end\n\n end\n\n return nothing\nend\n\n\"\"\"\n Similar to the 2d method.\n\n coords_bar should be ordered vertices, edge nodes, then face nodes\n\"\"\"\nfunction getMeshFaceCoordinates_rev(mesh::PumiMesh3DG, elnum::Integer,\n facenum::Integer, \n coords_bar::AbstractMatrix)\n\n# vertmap = mesh.topo.face_verts\n topo = mesh.topo\n \n # get the face vertices\n face_vert_idx = sview(topo.face_verts, :, facenum)\n\n for i=1:3 # 3 vertices per face\n for j=1:3 # 3 coordinates at each vertex\n mesh.vert_coords_bar[j, face_vert_idx[i], elnum] += coords_bar[j, i]\n end\n end\n\n if mesh.coord_numNodesPerType[2] > 0\n offset = 3 + (facenum - 1)*3 # 3 vertices + 1 edge node per face\n\n for i=1:3 # 3 edges per face\n edge_idx = topo.face_edges[i, facenum] + 4 # 4 = numVerts\n for j=1:3 # 3 coordinates per face\n mesh.vert_coords_bar[j, edge_idx, elnum] += coords_bar[j, 3 + i] # 3 verts\n end\n end\n\n end\n\n\n return nothing\nend\n", "meta": {"hexsha": "c4d0768510dab155d435e3cd0b10301539c3fe6d", "size": 41033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metrics_curvilinear.jl", "max_stars_repo_name": "OptimalDesignLab/PumiInterface.jl", "max_stars_repo_head_hexsha": "ca2cfe4cdb35958921ffc3748387772db4406901", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-10T18:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T06:16:59.000Z", "max_issues_repo_path": "src/metrics_curvilinear.jl", "max_issues_repo_name": "OptimalDesignLab/PumiInterface.jl", "max_issues_repo_head_hexsha": "ca2cfe4cdb35958921ffc3748387772db4406901", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2015-09-30T16:29:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-04T21:47:17.000Z", "max_forks_repo_path": "src/metrics_curvilinear.jl", "max_forks_repo_name": "OptimalDesignLab/PumiInterface.jl", "max_forks_repo_head_hexsha": "ca2cfe4cdb35958921ffc3748387772db4406901", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2513328256, "max_line_length": 162, "alphanum_fraction": 0.6701679136, "num_tokens": 11545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23966798115040908}} {"text": "module FEIterators\n\nusing StaticArrays\nusing MeshCore\nusing MeshCore: nshapes, indextype, nrelations, nentities, IncRel, shapedesc\nusing MeshSteward: Mesh, baseincrel, increl\nusing ..RefShapes: manifdim, manifdimv\nusing ..FElements: refshape, nfeatofdim\nimport ..FElements: jacjac\nusing ..FESpaces.FEFields: FEField, ndofsperterm\nusing ..FESpaces: FESpace, doftype\nimport ..FESpaces: ndofsperel\nusing ..QPIterators: QPIterator, bfungradpar\n\n#= TODO is it more natural to have access to the geometry from the font element space or from the iterator? =#\n\n\"\"\"\n FEIterator{FES, IR, G, IT, T, V, IR0, IR1, IR2, IR3, F0, F1, F2, F3}\n\nType of finite element iterator. Parameterized with the types of\n- `FES`: finite element space,\n- `IR`: base incidence relation of the mesh, \n- `G`: type of the geometry attribute, \n- `IT`: type of integer indices, such as the numbers of nodes and degrees of freedom, \n- `T`: type of the degree of freedom value (real double, complex float, ... ), \n- `V`: `Val` representation of the manifold dimension of the base relation elements, \n- `IR0`, `IR1`, `IR2`, `IR3`: types of incidence relations with which degrees\n of freedom are associated in the finite element space, for each of the\n manifolds dimensions 0, 1, 2, 3, \n- `F0`, `F1`, `F2`, `F3`: types of fields with which degrees\n of freedom are associated in the finite element space, for each of the\n manifolds dimensions 0, 1, 2, 3.\n\"\"\"\nstruct FEIterator{FES, IR, G, IT, T, V, IR0, IR1, IR2, IR3, F0, F1, F2, F3}\n fesp::FES\n _bir::IR\n _geom::G\n _dofs::Vector{IT}\n _dofvals::Vector{T}\n _entmdim::Vector{IT}\n _dofcomp::Vector{IT}\n _nodes::Vector{IT}\n _irs0::Union{Nothing, IR0}\n _irs1::Union{Nothing, IR1}\n _irs2::Union{Nothing, IR2}\n _irs3::Union{Nothing, IR3}\n _fld0::Union{Nothing, F0}\n _fld1::Union{Nothing, F1}\n _fld2::Union{Nothing, F2}\n _fld3::Union{Nothing, F3}\n _manifdimv::V\n _state::Vector{IT}\n \n function FEIterator(fesp::FES) where {FES}\n _bir = baseincrel(fesp.mesh)\n _geom = MeshCore.attribute(_bir.right, \"geom\")\n _dofs = zeros(Int64, ndofsperel(fesp))\n _dofvals = zeros(doftype(fesp), ndofsperel(fesp))\n _entmdim = zeros(Int64, ndofsperel(fesp))\n _dofcomp = zeros(Int64, ndofsperel(fesp))\n _nodes = zeros(Int64, nfeatofdim(fesp.fe, 0)) \n _fld0 = nothing\n _fld1 = nothing\n _fld2 = nothing\n _fld3 = nothing\n _irs0 = nothing\n _irs1 = nothing\n _irs2 = nothing\n _irs3 = nothing\n 0 in keys(fesp._irsfields) && (_irs0 = fesp._irsfields[0][1]; _fld0 = fesp._irsfields[0][2])\n 1 in keys(fesp._irsfields) && (_irs1 = fesp._irsfields[1][1]; _fld1 = fesp._irsfields[1][2])\n 2 in keys(fesp._irsfields) && (_irs2 = fesp._irsfields[2][1]; _fld2 = fesp._irsfields[2][2])\n 3 in keys(fesp._irsfields) && (_irs3 = fesp._irsfields[3][1]; _fld3 = fesp._irsfields[3][2])\n _manifdimv = Val(manifdim(refshape(fesp.fe)))\n p = 1\n _irs0 != nothing && (p = _init_e_d!(_entmdim, _dofcomp, p, _irs0, _fld0))\n _irs1 != nothing && (p = _init_e_d!(_entmdim, _dofcomp, p, _irs1, _fld1))\n _irs2 != nothing && (p = _init_e_d!(_entmdim, _dofcomp, p, _irs2, _fld2))\n _irs3 != nothing && (p = _init_e_d!(_entmdim, _dofcomp, p, _irs3, _fld3))\n return new{FES, typeof(_bir), typeof(_geom), eltype(_dofs), doftype(fesp), typeof(_manifdimv), typeof(_irs0), typeof(_irs1), typeof(_irs2), typeof(_irs3), typeof(_fld0), typeof(_fld1), typeof(_fld2), typeof(_fld3)}(fesp, _bir, _geom, _dofs, _dofvals, _entmdim, _dofcomp, _nodes, _irs0, _irs1, _irs2, _irs3, _fld0, _fld1, _fld2, _fld3, _manifdimv, [0])\n end\nend\n\n\"\"\"\n Base.iterate(it::FEIterator, state = 1)\n\nAdvance the iterator to the next entity.\n\nThe nodes of the finite element are cached, as is a vector of all the degrees\nof freedom represented on the element.\n\"\"\"\nfunction Base.iterate(it::FEIterator, state = 1)\n if state > nrelations(it._bir)\n return nothing\n else\n return (_update!(it, state), state+1)\n end\nend\n\n\"\"\"\n Base.length(it::FEIterator) \n\nNumber of elements represented by this iterator.\n\"\"\"\nBase.length(it::FEIterator) = nrelations(it._bir)\n\n\"\"\"\n ndofsperel(it::FEIterator)\n\nRetrieve the number of degrees of freedom per element.\n\"\"\"\nndofsperel(it::FEIterator) = ndofsperel(it.fesp)\n\n\"\"\"\n eldofs(it::FEIterator)\n\nRetrieve the vector of the element degrees of freedom\n\"\"\"\neldofs(it::FEIterator) = it._dofs\n\n\"\"\"\n elnodes(it::FEIterator)\n\nRetrieve the vector of the nodes of the element.\n\"\"\"\nelnodes(it::FEIterator) = it._nodes\n\n\"\"\"\n eldofentmdims(it::FEIterator)\n\nRetrieve the vector of the entity dimensions for each element degree of freedom.\n\nEach degree of freedom is associated with some entity of the finite element:\nvertices, edges, faces, and so on. This vector records the dimension of the\nmanifold entity with which each degree of freedom is associated.\n\"\"\"\neldofentmdims(it::FEIterator) = it._entmdim\n\n\"\"\"\n eldofcomps(it::FEIterator)\n\nRetrieve the vector of the component numbers for each element degree of freedom.\n\nIf multiple copies of the finite element are referenced in the finite element\nspace, each copy is referred to as component.\n\"\"\"\neldofcomps(it::FEIterator) = it._dofcomp\n\nfunction _init_e_d!(mdim, dofcomp, p, ir, fl)\n ndpt = ndofsperterm(fl)\n for k in 1:nentities(ir, 1)\n for i in 1:ndpt\n mdim[p] = MeshCore.manifdim(shapedesc(ir.right))\n dofcomp[p] = i\n p = p + 1\n end\n end\n return p\nend\n\nfunction _storedofs!(d, p, e, ir, fl)\n ndpt = ndofsperterm(fl)\n for k in 1:nentities(ir, e)\n gk = ir[e, k]\n for i in 1:ndpt\n d[p] = fl.dofnums[gk][i]\n p = p + 1\n end\n end\n return p\nend\n\nfunction _storedofvals!(d, p, e, ir, fl)\n ndpt = ndofsperterm(fl)\n for k in 1:nentities(ir, e)\n gk = ir[e, k]\n for i in 1:ndpt\n d[p] = fl.dofvals[gk][i]\n p = p + 1\n end\n end\n return p\nend\n\nfunction _update!(it::FEIterator, state)\n it._state[1] = state\n copyto!(it._nodes, it._bir[state])\n p = 1\n it._irs0 != nothing && (p = _storedofs!(it._dofs, p, state, it._irs0, it._fld0))\n it._irs1 != nothing && (p = _storedofs!(it._dofs, p, state, it._irs1, it._fld1))\n it._irs2 != nothing && (p = _storedofs!(it._dofs, p, state, it._irs2, it._fld2))\n it._irs3 != nothing && (p = _storedofs!(it._dofs, p, state, it._irs3, it._fld3))\n return it\nend\n\n\"\"\"\n eldofvals(it::FEIterator)\n\nProvide access to vector of element degrees of freedom.\n\"\"\"\nfunction eldofvals(it::FEIterator)\n p = 1\n it._irs0 != nothing && (p = _storedofvals!(it._dofvals, p, it._state[1], it._irs0, it._fld0))\n it._irs1 != nothing && (p = _storedofvals!(it._dofvals, p, it._state[1], it._irs1, it._fld1))\n it._irs2 != nothing && (p = _storedofvals!(it._dofvals, p, it._state[1], it._irs2, it._fld2))\n it._irs3 != nothing && (p = _storedofvals!(it._dofvals, p, it._state[1], it._irs3, it._fld3))\n return it._dofvals\nend\n\n\"\"\"\n jacjac(it::FEIterator, qpit::QPIterator)\n\nCompute the Jacobian matrix and the Jacobian determinant.\n\nThe finite element iterator cooperates with the quadrature point iterator here\nto compute the Jacobian at the current integration point.\n\"\"\"\nfunction jacjac(it::FEIterator, qpit::QPIterator)\n return jacjac(it.fesp.fe, it._geom, it._nodes, qpit._geomscalbfungrad_ps[qpit._pt])\nend\n\n\"\"\"\n location(it::FEIterator, qpit::QPIterator)\n\nCalculate the location of the quadrature point.\n\"\"\"\nfunction location(it::FEIterator, qpit::QPIterator)\n n = it._nodes[1]\n loc = it._geom[n] * qpit._geomscalbfuns[qpit._pt][1]\n for i in 2:length(it._nodes)\n n = it._nodes[i]\n loc += it._geom[n] * qpit._geomscalbfuns[qpit._pt][i]\n end\n return loc\nend\n\nend\n", "meta": {"hexsha": "dcf7d794885a225b405e7cf09c797ec2674737e8", "size": 7891, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FEIterators.jl", "max_stars_repo_name": "PetrKryslUCSD/Elfem.jl", "max_stars_repo_head_hexsha": "4bbd57db0541dd08c181936110f4753c2d6079d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-05-17T21:30:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:06:50.000Z", "max_issues_repo_path": "src/FEIterators.jl", "max_issues_repo_name": "PetrKryslUCSD/Elfem.jl", "max_issues_repo_head_hexsha": "4bbd57db0541dd08c181936110f4753c2d6079d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-07-15T02:11:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T01:26:23.000Z", "max_forks_repo_path": "src/FEIterators.jl", "max_forks_repo_name": "PetrKryslUCSD/Elfem.jl", "max_forks_repo_head_hexsha": "4bbd57db0541dd08c181936110f4753c2d6079d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1554621849, "max_line_length": 359, "alphanum_fraction": 0.6613863896, "num_tokens": 2603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23966798115040905}} {"text": "#gnum-division.jl\n#division algorithms between unums, ubounds and gnums.\n\n#=\n\ndoc\"\"\"\n `div!(::Unum, ::Gnum)` divides a unum BY a gnum. the gnum will be altered as\n a result. This function may also alter the unum by appending g-flags into the\n flags section. Returns a reference to the gnum to allow chaining.\n\"\"\"\nfunction div!{ESS,FSS}(a::Unum{ESS,FSS}, b::Gnum{ESS,FSS})\n #make sure our ignore_sides parameters are set.\n clear_ignore_sides!(b)\n #go ahead and set \"g-flags\" on the value a.\n set_g_flags!(a)\n\n #ascertain the result sign. Note that all division algorithms are\n #sign-agnostic and return positive-definite results.\n result_sign::UInt16 = @signof(a) $ @signof(b.lower)\n\n #perform hard override checks on the multiply.\n __check_div_hard_override!(a, b)\n\n #flip sides?\n\n #test sidedness and trampoline to the appropriate procedure.\n #is_onesided(b) ? div_onesided!(a, b) : div_twosided!(a, b)\n\n (result_sign != 0) && additive_inverse!(b)\nend\n=#\n#=\ndoc\"\"\"\n `mul!(::Ubound, ::Gnum)` multiplies a ubound INTO a gnum.\n the gnum will be altered as a result. This function may also alter the ubound\n by appending g-flags into the flags section of the constituent unums. Returns\n a reference to the gnum to allow chaining.\n\"\"\"\nfunction mul!{ESS,FSS}(a::Ubound{ESS,FSS}, b::Gnum{ESS,FSS})\n throw(ArgumentError(\"not implemented yet.\"))\nend\n\ndoc\"\"\"\n `mul!(a::Gnum, b::Gnum)` multiplies a gnum `a` INTO a gnum `b`.\n the *second* gnum will be altered as a result. Following at&t assembly syntax,\n the result is on the right hand side (this is the equivalent of b \\*= a ).\n Returns a reference to the gnum to allow chaining.\n\"\"\"\nfunction mul!{ESS,FSS}(a::Gnum{ESS,FSS}, b::Gnum{ESS,FSS})\n throw(ArgumentError(\"not implemented yet.\"))\nend\n\n################################################################################\n## onesided/twosided multiplies.\n\ndoc\"\"\"\n `mul_onesided!(::Unum, ::Gnum)` performs a multiplication of a unum a into\n a unum b, where the starting gnum is one-sided. This function does not check\n that the passed parameters match this description.\n\"\"\"\nfunction mul_onesided!{ESS,FSS}(a::Unum{ESS,FSS}, b::Gnum{ESS,FSS})\n #all procedures in onesided multiply presume that a is positive.\n\n if is_zero(b, LOWER_UNUM)\n ignore_side!(b, LOWER_UNUM)\n elseif is_inf(b, LOWER_UNUM)\n b.lower.flags &= ~UNUM_SIGN_MASK\n ignore_side!(b, LOWER_UNUM)\n elseif should_calculate(b, LOWER_UNUM) && is_unit(b.lower)\n copy_unum!(a, b.lower)\n #overwrite the sign; this will be re-xored later.\n b.lower.flags &= ~UNUM_SIGN_MASK\n ignore_side!(b, LOWER_UNUM)\n elseif is_mmr(a)\n should_calculate(b, LOWER_UNUM) && mmr_onesided_mult!(b)\n elseif is_sss(a)\n should_calculate(b, LOWER_UNUM) && sss_onesided_mult!(b)\n end\n\n #check for the gnum value being mmr or sss.\n if should_calculate(b, LOWER_UNUM)\n if is_mmr(b, LOWER_UNUM)\n copy_unum!(a, b.lower)\n mmr_onesided_mult!(b)\n elseif is_sss(b, LOWER_UNUM)\n copy_unum!(a, b.lower)\n sss_onesided_mult!(b)\n end\n end\n\n #we have exhausted all of the special cases, so just do the multiplication.\n should_calculate(b, LOWER_UNUM) && (__multiply!(a, b, LOWER_UNUM, UPPER_UNUM))\n #swap parity if a was negative.\n\n #return the gnum.\n b\nend\n\ndoc\"\"\"\n `mul_twosided!(::Unum, ::Gnum)` performs a multiplication of a unum a into\n a unum b, where the starting gnum is one-sided. This function does not check\n that the passed parameters match this description.\n\"\"\"\nfunction mul_twosided!{ESS,FSS}(a::Unum{ESS,FSS}, b::Gnum{ESS,FSS})\n throw(ArgumentError(\"twosided mults not implemented yet\"))\nend\n=#\n#=\ndoc\"\"\"\n `__transits_zero(::Gnum)` checks to see if a Gnum has a negative-definite left\n and a positive-definite right. This is useful for division because such a gnum\n will throw an error.\n\"\"\"\nfunction __transits_zero{ESS,FSS}(b::Gnum{ESS,FSS})\n #onesided gnums cannot transit zero\n return is_twosided(b) & is_negative(b.lower) & is_positive(b.upper) & !(is_zero(b, LOWER_UNUM)) & !(is_zero(b, UPPER_UNUM))\nend\n\n################################################################################\n## shortcut division, for special values.\n\ndoc\"\"\"\n `__check_div_hard_override!(::Unum, ::Gnum)` checks to see if the terms in\n the divisor or the dividend trigger a \"hard override\". These values are,\n in cascading precedence:\n\n nan (dividend, divisor) -> outputs nan.\n value that transits zero (divisor) -> outputs nan.\n\"\"\"\nfunction __check_div_hard_override!{ESS,FSS}(a::Utype{ESS,FSS}, b::Gnum{ESS,FSS})\n ############################################\n # analysis of division with NaNs.\n # if our dividend is nan, then set the product to nan.\n is_nan(a) && (@scratch_this_operation!(b); return)\n is_nan(b) && (ignore_both_sides!(b); return)\n\n ############################################\n # check for values that transit zero\n __transits_zero(b) && (@scratch_this_operation!(b); return)\nend\n\n#checking for values in the dividend which trigger override.\nfunction __check_div_dividend_override!{ESS,FSS}(a::Unum{ESS,FSS}, b::Gnum{ESS,FSS})\n ############################################\n # analysis of division with infs\n # inf / anything becomes inf, except inf, which becomes NaN.\n\n if (is_g_inf(a))\n #infinity can't multiply times just zero, either\n should_calculate(b, LOWER_UNUM) && is_inf(b, LOWER_UNUM) && (@scratch_this_operation!(b))\n should_calculate(b, UPPER_UNUM) && is_inf(b, UPPER_UNUM) && (@scratch_this_operation!(b))\n #set the lower side to infinity, then ignore further calculations, and make it onesided\n inf!(b, z16, LOWER_UNUM); ignore_side!(b, LOWER_UNUM); set_onesided!(b)\n end\n\n ############################################\n # analysis of division with zeros\n # zero divided by anything becomes zero.\n # n.b. this does not check twosided unums, because that has already been checked.\n if is_g_zero(a)\n zero!(b, LOWER_UNUM)\n set_onesided!(b)\n ignore_side!(b, LOWER_UNUM)\n end\nend\n\nfunction __check_div_divisor_override!{ESS,FSS}(a::Unum{ESS,FSS}, b::Gnum{ESS,FSS})\n #anything / inf is zero, but make sure the zero gets placed in the lower unum.\n if should_calculate(b, LOWER_UNUM) && is_inf(b, LOWER_UNUM)\n zero!(b, LOWER_UNUM)\n ignore_side!(b, LOWER_UNUM); set_onesided!(b)\n end\n if should_calculate(b, UPPER_UNUM) && is_inf(b, UPPER_UNUM)\n #move the value of the lower unum into the upper segment and then do the calculation.\n #note tthat using this implies that the upper unum is active, s o we don't need to\n #set this to onesided.\n copy_unum_with_gflags!(b.lower, b.upper)\n zero!(b, LOWER_UNUM)\n ignore_side!(b, LOWER_UNUM)\n end\nend\n\n\ndoc\"\"\"\n `sss_onesided_mult!(::Gnum)` multiplies a onesided Gnum times an sss.\n the lower value of the Gnum contains the value to be multiplied. The upper\n value will contain the result value.\n\"\"\"\nfunction sss_onesided_mult!{ESS,FSS}(b::Gnum{ESS,FSS})\n #if the magnitude is more than one, then we multiply the value of b times\n #smallsubnormal.\n if is_magnitude_less_than_one(b.lower)\n sss!(b, z16, LOWER_UNUM)\n ignore_side!(b, LOWER_UNUM)\n else\n #we're going to have a two-valued solution, so alias the inner and outer values.\n set_twosided!(b)\n #first, make the upper part small_exact.\n small_exact!(b.upper, z16)\n __outward_exact!(b.lower)\n #do the multiplication\n __multiply!(b.lower, b, UPPER_UNUM, DISCARD_SECONDARY)\n #check to see if we need to retrace.\n is_exact(b.upper) && __inward_ulp!(b.upper)\n #set the lower unum to be small subnormal.\n sss!(b, z16, LOWER_UNUM)\n #finished with calculations.\n ignore_both_sides!(b)\n end\nend\n\ndoc\"\"\" `mmr_onesided_mult!(::Gnum)` multiplies a onesided Gnum times an mmr.\"\"\"\nfunction mmr_onesided_mult!{ESS,FSS}(b::Gnum{ESS,FSS})\n if is_magnitude_less_than_one(b.lower)\n #we're going to have a two-valued solution, so alias the inner and outer values.\n set_twosided!(b)\n #first, make the buffer big_exact.\n big_exact!(b.buffer, z16)\n #multiply the buffer times the value in the lower unum, overwriting it.\n __multiply!(b.buffer, b, LOWER_UNUM, DISCARD_SECONDARY)\n #check to see if we need to retrace.\n is_exact(b.lower) && make_ulp!(b.lower)\n #make the upper side mmr.\n mmr!(b, z16, UPPER_UNUM)\n ignore_both_sides!(b)\n else\n #then everything stays mmr.\n mmr!(b, z16, LOWER_UNUM)\n ignore_side!(b, LOWER_UNUM)\n end\nend\n=#\n#=\n################################################################################\n## actual algorithmic multiplication\n\ndoc\"\"\"\n `Unums.__multiply!(::Unum, ::Gnum, ::Type{Val}, ::Type{Val})`\n performs the algorithmic multiplication of an unum into one side of the gnum.\n Because a unum muliplication times another unum must always be on the same\n side of zero, this procedure ignores sign, always returning a positive value.\n\n The *primary result* is the result of the exact multiplication between the two\n values; the *secondary result* is the result of multiplying the ulp values.\n\n The first value parameter contains the side that contains the multiplicand:\n this may be UPPER_GNUM, LOWER_GNUM, or BUFFER.\n\n The second value parameter contains a directive that determines what to do\n when the value is inexact. If this is UPPER_GNUM, LOWER_GNUM, or BUFFER, then\n the secondary result is stored in the respective destination. This destination\n cannot be identical to the first value parameter.\n\n You may also specify DISCARD_PRIMARY or DISCARD_SECONDARY as the directives,\n which will discard the primary or secondary results.\n\"\"\"\n@gen_code function __multiply!{ESS,FSS,side,directive}(a::Unum{ESS,FSS}, b::Gnum{ESS,FSS}, ::Type{Val{side}}, ::Type{Val{directive}})\n max_exp = max_exponent(ESS)\n sml_exp = min_exponent(ESS, FSS)\n min_exp = min_exponent(ESS)\n mesize = max_esize(ESS)\n mfsize = max_fsize(FSS)\n\n (side == directive) && throw(ArgumentError(\"multiply algorithm cannot send an ulp result to the same side as source\"))\n\n @code quote\n a_exp::Int64 = decode_exp(a)\n b_exp::Int64 = decode_exp(b.$side)\n a_dev::UInt64 = is_exp_zero(a) * o64\n b_dev::UInt64 = is_exp_zero(b.$side) * o64\n\n #make the result positive\n b.scratchpad.flags &= ~UNUM_SIGN_MASK\n\n scratchpad_exp::Int64 = a_exp + b_exp + a_dev + b_dev\n\n #preliminary comparisons that will stop us from performing unnecessary steps.\n (scratchpad_exp > $max_exp + 1) && (@preserve_sflags b mmr!(b, z16, Val{side}); return)\n (scratchpad_exp < $sml_exp - 2) && (@preserve_sflags b sss!(b, z16, Val{side}); return)\n end\n\n if FSS < 6\n #fss < 6 can perform a multiplication within the existing 64-bit integer width.\n @code :(b.scratchpad.fraction = __chunk_mult_small(a.fraction, b.$side.fraction))\n elseif FSS == 6\n #fss = 6 requires access to the scratchpad array.\n @code :(nan!(b); return)\n else\n @code :(nan!(b); return)\n end\n\n @code quote\n\n #fraction multiplication: where va is \"virtual bit\" that is 1 for normals or 0 for subnormals.\n # va + a\n # vb + b\n # va*vb + vb * a + va * b + ab\n #\n carry::UInt64 = o64 - (a_dev | b_dev) #if either a or b are subnormal, the carry is zero.\n #note that adding the fractions back in has a cross-multiplied effect.\n (b_dev == 0) && (carry = __carried_add_frac!(carry, a, b.scratchpad))\n (a_dev == 0) && (carry = __carried_add_frac!(carry, b.$side, b.scratchpad))\n\n #next, do carry analysis. carry can be 0, 1, 2, or 3 at the most.\n if (carry == 0)\n #shift over the fraction as far as we need to.\n shift::Int64 = leading_zeros(b.scratchpad.fraction) + 1\n #check if we're zero.\n is_frac_zero(b.scratchpad) && (sss!(b, z16, Val{side}); return)\n __leftshift_frac!(b.scratchpad, shift)\n #adjust the exponent.\n scratchpad_exp -= shift\n (scratchpad_exp < $sml_exp) && (sss!(b, z16, Val{side}); return)\n if (scratchpad_exp < $min_exp)\n #calculate the leftshift.\n shift = $min_exp - scratchpad_exp\n __rightshift_frac_with_underflow_check!(b.scratchpad, shift)\n set_frac_bit!(b.scratchpad, shift)\n b.scratchpad.esize = $mesize\n b.scratchpad.exponent = 0\n else\n (b.scratchpad.esize, b.scratchpad.exponent) = encode_exp(scratchpad_exp)\n carry = 1\n end\n elseif (carry == 1)\n if scratchpad_exp > $max_exp\n @preserve_sflags b (mmr!(b, z16, Val{side}); return)\n end\n (b.scratchpad.esize, b.scratchpad.exponent) = encode_exp(scratchpad_exp)\n else\n (scratchpad_exp += 1)\n if scratchpad_exp > $max_exp\n @preserve_sflags b (mmr!(b, z16, Val{side}); return)\n else\n #shift things over by one since we went up in size.\n __rightshift_frac_with_underflow_check!(b.scratchpad, 1)\n #carry from the carry over into the fraction.\n (carry == 3) && set_frac_top!(b.scratchpad)\n #re-encode the exponent.\n (b.scratchpad.esize, b.scratchpad.exponent) = encode_exp(scratchpad_exp)\n end\n #set the carry to one\n carry = 1\n end\n end\n\n #if we're instructed to discard the secondary value, then simply copy over\n #the values, and we're done.\n (directive == :discard_secondary) && (@code :(copy_unum_with_gflags!(b.scratchpad, b.$side); return); @goto __mult_end)\n #assign the destination for the secondary varibale.\n sdest = (directive == :discard_primary) ? side : directive\n #this code ge\n retrace_code1 = (directive == :discard_primary) ? :(nothing) : :(carry = __tandem_copy_add_frac!(carry, b.$side, b.scratchpad, a.fsize))\n retrace_code2 = (directive == :discard_primary) ? :(nothing) : :(copy_unum!(b.scratchpad, b.$side))\n needs_twosided = (sdest == :upper) ? (:(set_twosided!(b))) : :(nothing)\n #if we're writing to the lower side, then be prepared to collapse an mmr into a onesided.\n mmr_collapse = (side == :lower) && !(directive == :discard_primary) ? :(set_onesided!(b)) : :(nothing)\n\n @code quote\n #if both sides were exact, the result is fairly simple. Just copy the scratchpad results\n #on over to the destination side, we don't have to do anything further.\n\n is_exact(a) && is_exact(b.$side) && (copy_unum_with_gflags!(b.scratchpad, b.$side); return)\n $needs_twosided\n\n #the scratchpad needs to be exact, but as a temporary shim we need to make\n #it an ulp to assess if the result is mmr.\n make_ulp!(b.scratchpad)\n is_mmr(b.scratchpad) && ($mmr_collapse; mmr!(b, z16, Val{side}); return)\n make_exact!(b.scratchpad)\n\n# println(\"a: \", bits(a))\n# println(\"1) scr: \", bits(b.scratchpad), \" carry: \", carry)\n\n #from here on out we engage the heuristic algorithm. The 'direct' algorithm\n #would be to do two multiplications, but it is possible to save on that\n #calculation. The algorithm is as follows:\n # we're going to do the multiplication X1 * X2\n # X1 = (2^P1)(F1) (+) (2^(P1-U1))\n # X2 = (2^P2)(F2) (+) (2^(P2-U2))\n # X1 * X2 = 2^(P1P2)(F1F2 (+) (2^-U1)F2 + (2^-U2)F1 + 2^(-U1-U2))\n # where x (+) a ≡ x + (0, a)\n\n #copy the scratchpad back, and add into the scratchpad b.$side.fraction >> a.fsize\n (is_ulp(a)) ? $retrace_code1 : $retrace_code2\n\n\n# println(\"2) scr: \", bits(b.scratchpad), \" carry: \", carry)\n #add into the scratchpad a.fraction >> b.$side.fsize\n (is_ulp(b.$side)) && (carry = __add_frac_with_shift!(carry, a, b.scratchpad, b.$side.fsize))\n #check to make sure the far value isn't exact; move it inward if so.\n\n #tentatively make the fsize the maximum\n b.$side.fsize = $mfsize\n\n #resolve the scratchpad's carry\n __carry_resolve!(carry, b.scratchpad, Val{true})\n\n is_exact(b.scratchpad) && __inward_ulp!(b.scratchpad)\n\n #move the scratchpad back to the destination\n copy_unum!(b.scratchpad, b.$sdest)\n end\n\n @label __mult_end\nend\n=#\n", "meta": {"hexsha": "685db56cbbd52089cd89b24efca2ffd3fedf3ffd", "size": 15809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gnum/gnum-division.jl", "max_stars_repo_name": "REX-Computing/unumjl", "max_stars_repo_head_hexsha": "5441eecd983943dcc5f2ad737b3f2144b3ed12e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2015-11-09T22:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T19:59:29.000Z", "max_issues_repo_path": "src/gnum/gnum-division.jl", "max_issues_repo_name": "REX-Computing/unumjl", "max_issues_repo_head_hexsha": "5441eecd983943dcc5f2ad737b3f2144b3ed12e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2015-10-29T23:56:10.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-17T08:57:28.000Z", "max_forks_repo_path": "src/gnum/gnum-division.jl", "max_forks_repo_name": "REX-Computing/unumjl", "max_forks_repo_head_hexsha": "5441eecd983943dcc5f2ad737b3f2144b3ed12e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2015-10-27T00:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-25T22:12:17.000Z", "avg_line_length": 38.7475490196, "max_line_length": 138, "alphanum_fraction": 0.6730976026, "num_tokens": 4642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23966798115040905}} {"text": "abstract type _AbstractFunction end\n\n\"\"\"\n _Operation\n\nAn enum representing different node types in a symbolic expression graph.\n\n * `_OP_COEFFICIENT`: a numerical `Float64`\n * `_OP_VARIABLE`: a decision variable\n * `_OP_OPERATION`: a function call\n * `_OP_INTEGER_EXPONENT`: a special case for handling integer polynomials such\n as `x^2`, since the `2.0` is usually structural rather than a coefficient\n that differs between expressions.\n\"\"\"\n@enum(\n _Operation,\n _OP_COEFFICIENT,\n _OP_VARIABLE,\n _OP_OPERATION,\n _OP_INTEGER_EXPONENT,\n)\n\n\"\"\"\n _Node\n\nA type to represent a node in the symbolic expression graph.\n\n!!! warning\n `_Node`s can only be used in conjunction with `_Function`.\n\n`_Node` has the following fields:\n\n * `.head::_Operation`: this describes the node type\n * `.hash::UInt64`: a hash of the expression tree rooted at this node. See the\n Fast hashing section for more details.\n * `.index::Int` : interpretation depends on `.head`. If head is:\n * `_OP_COEFFICIENT`, the index into `f.data`\n * `_OP_VARIABLE`, the index into `f.ordered_variables`\n * `_OP_INTEGER_EXPONENT`, the integer exponent `children[1]^index`\n * `.operation::Symbol` : the symbolic name of the function call, if `.head` is\n `_OP_OPERATION`, otherwise this can be ignored.\n * `.children::Union{Nothing,Vector{_Node}}` : a vector of children of the node,\n if `.head` is `_OP_OPERATION`, otherwise `nothing`.\n\n## Fast hashing\n\nThe expression graph is structured as a Merkle tree (a.k.a. a hash tree). That\nis, each node contains a field `.hash`, which is the hash of the node's\noperation with the hash of its children. Since children are also nodes, hashing\na child is an O(1) lookup of `child.hash`. Moreover, two expressions are\nstructurally identical if the have the same hash when converted into `_Node`\nform.\n\n## Other considerations\n\nThrough experience, the representation of the symbolic expression graph is not\nthe bottleneck in a nonlinear optimization model. Therefore, we choose the\nsomewhat inefficient storage rpresentation of\n`children::Union{Nothing,Vector{_Node}}` for the list of children. This results\nin a GC tracked object for each node that has children. If memory issues are\nidentified in future, changing how we represent the expression graph is one\npromising avenue of investigation.\n\"\"\"\nstruct _Node\n head::_Operation\n hash::UInt\n index::Int\n operation::Symbol\n children::Union{Nothing,Vector{_Node}}\n\n function _Node(f::_AbstractFunction, coefficient::Float64)\n # Store the coefficient\n push!(f.data, coefficient)\n # Compute the hash of the node. Because all coefficients are alike, this\n # is just the hash of `_OP_COEFFICIENT`.\n h = hash(_OP_COEFFICIENT)\n # Index is the length of `f.data` when we need to look it up again.\n index = length(f.data)\n return new(_OP_COEFFICIENT, h, index, :NONE, nothing)\n end\n function _Node(f::_AbstractFunction, variable::MOI.VariableIndex)\n # We need to convert the variable to the order in which it will appear\n # in .ordered_variables. Currently, the order is stored in\n # `f.variables`...\n lookup = f.variables::Dict{MOI.VariableIndex,Int}\n # And if the variable hasn't been seen yet, add a new index\n index = get!(lookup, variable, length(lookup) + 1)\n # The hash of this node depends on the variable and it's position in\n # ordered_variables.\n h = hash(_OP_VARIABLE, hash(index))\n return new(_OP_VARIABLE, h, index, :NONE, nothing)\n end\n function _Node(::_AbstractFunction, operation::Symbol, children::_Node...)\n # Okay, a function call. The hash depends on the operation and the\n # children.\n h = hash(operation, _hash(children...))\n return new(_OP_OPERATION, h, 0, operation, collect(children))\n end\n # Special cased performance optimization: x^N where N::Int is a common\n # operation that would otherwise get re-written to x[i]^p[j]. Doing so\n # disables a lot of potential optimizations, so it's worth special-casing\n # this. Other operations aren't as important.\n function _Node(::_AbstractFunction, ::typeof(^), x::_Node, N::Int)\n # The hash depends on ^, as well as the child node `x` and the\n # exponent `N`\n h = hash(_OP_INTEGER_EXPONENT, hash(_hash(x), hash(N)))\n return new(_OP_INTEGER_EXPONENT, h, N, :^, [x])\n end\nend\n\n# The hash of a child is an O(1) lookup\n_hash(child::_Node) = child.hash\n\n# Recursively has nodes together\n_hash(a::_Node, args::_Node...) = hash(a.hash, _hash(args...))\n\n\"\"\"\n _Function(expr::Expr)\n\nThis function parses the Julia expression `expr` into a `_Function`.\n\n`_Function` has the following fields:\n\n * `ordered_variables`: a vector containing the `.value` indices of each\n variable in the order that they are discovered in the expression tree.\n * `coefficients::Vector{Float64}`: a vector to store the numerical input values\n of `x`.\n * `data::Vector{Float64}`: the list of numerical coefficients that appear in\n `expr`\n * `expr::_Node`: the symbolic representation of `expr`.\n\nFor more information on how to interpret the fields, see `_Node`.\n\"\"\"\nmutable struct _Function <: _AbstractFunction\n ordered_variables::Vector{Int}\n coefficients::Vector{Float64}\n data::Vector{Float64}\n expr::_Node\n # A field that is only used when constructing the _Function\n variables::Union{Nothing,Dict{MOI.VariableIndex,Int}}\n function _Function(expr::Expr)\n f = new()\n f.variables = Dict{MOI.VariableIndex,Int}()\n f.data = Float64[]\n f.expr = _Node(f, expr)\n f.coefficients = zeros(length(f.variables))\n f.ordered_variables = zeros(Int, length(f.variables))\n for (k, v) in f.variables\n f.ordered_variables[v] = k.value\n end\n f.variables = nothing\n return f\n end\nend\n\n_is_integer(::Any) = false\n_is_integer(x::Real) = Base.isinteger(x)\n\n\"\"\"\n _Node(f::_Function, expr::Expr)\n\nParse `expr` into `f` and return a `_Node`.\n\n!!! warning\n This function gets called recursively.\n\"\"\"\nfunction _Node(f::_Function, expr::Expr)\n if isexpr(expr, :call)\n # Performance optimization: most calls will be unary or binary\n # operators. Therefore, we can specialize an if-statement to handle the\n # common cases without needing to splat.\n if length(expr.args) == 2\n return _Node(f, expr.args[1], _Node(f, expr.args[2]))\n elseif length(expr.args) == 3\n # Special cased performance optimization for _OP_INTEGER_EXPONENT\n if expr.args[1] == :^ && _is_integer(expr.args[3])\n return _Node(f, ^, _Node(f, expr.args[2]), Int(expr.args[3]))\n end\n return _Node(\n f,\n expr.args[1],\n _Node(f, expr.args[2]),\n _Node(f, expr.args[3]),\n )\n else\n nodes = (_Node(f, expr.args[i]) for i in 2:length(expr.args))\n return _Node(f, expr.args[1], nodes...)\n end\n else\n @assert isexpr(expr, :ref)\n @assert expr.args[1] == :x\n return _Node(f, expr.args[2])\n end\nend\n\nstruct _SymbolicsFunction{F,G,H}\n f::F\n ∇f::G\n ∇²f::H\n g::Vector{Float64}\n H::Vector{Float64}\n H_structure::Vector{Tuple{Int,Int}}\nend\n\n\"\"\"\n _expr_to_symbolics(expr::_Node, p, x)\n\nConvert a `_Node` into a `Symbolics.jl` expression via operator overloading.\n\"\"\"\nfunction _expr_to_symbolics(expr::_Node, p, x)\n if expr.head == _OP_COEFFICIENT\n return p[expr.index]\n elseif expr.head == _OP_VARIABLE\n return x[expr.index]\n elseif expr.head == _OP_OPERATION\n # TODO(odow): improve this lookup of expr.operation to function.\n f = getfield(Base, expr.operation)\n return f((_expr_to_symbolics(c, p, x) for c in expr.children)...)\n else\n @assert expr.head == _OP_INTEGER_EXPONENT\n return _expr_to_symbolics(expr.children[1], p, x)^expr.index\n end\nend\n\nfunction _SymbolicsFunction(f::_Function, features::Vector{Symbol})\n d, n = length(f.data), length(f.ordered_variables)\n Symbolics.@variables(p[1:d], x[1:n])\n p, x = collect(p), collect(x)\n f_expr = _expr_to_symbolics(f.expr, p, x)\n f = Symbolics.build_function(f_expr, p, x; expression = Val{false})\n if :Jac in features || :Grad in features\n ∇f_expr = Symbolics.gradient(f_expr, x)\n _, g! = Symbolics.build_function(∇f_expr, p, x; expression = Val{false})\n g_cache = zeros(length(x))\n else\n g!, g_cache = nothing, Float64[]\n end\n if :Hess in features\n ∇²f_expr_square = Symbolics.sparsejacobian(∇f_expr, x)\n # ∇²f_expr_square is sparse but it is also symmetrical. MathOptInterface\n # needs only the lower-triangular (technically, it doesn't matter which\n # triangle, but let's choose the lower-triangular for simplicity).\n I, J, V = SparseArrays.findnz(∇²f_expr_square)\n # Rather than using a SparseArray as storage, convert to MOI's\n # ((i, j), v) datastructure. This simplifies\n # `hessian_lagrangian_structure` calls later.\n ∇²f_expr = [V[i] for i in 1:length(I) if I[i] >= J[i]]\n ∇²f_structure = [(I[i], J[i]) for i in 1:length(I) if I[i] >= J[i]]\n _, h! =\n Symbolics.build_function(∇²f_expr, p, x; expression = Val{false})\n h_cache = zeros(length(∇²f_structure))\n else\n h!, h_cache, ∇²f_structure = nothing, Float64[], Tuple{Int,Int}[]\n end\n return _SymbolicsFunction(f, g!, h!, g_cache, h_cache, ∇²f_structure)\nend\n\n\"\"\"\n AbstractNonlinearOracleBackend\n\nAn abstract type to help dispatch on different implementations of the function\nevaluations.\n\"\"\"\nabstract type AbstractNonlinearOracleBackend end\n\n\"\"\"\n DefaultBackend() <: AbstractNonlinearOracleBackend\n\nA simple implementation that loops over the different constraints.\n\"\"\"\nstruct DefaultBackend <: AbstractNonlinearOracleBackend end\n\nmutable struct _NonlinearOracle{B} <: MOI.AbstractNLPEvaluator\n backend::B\n objective::Union{Nothing,_Function}\n constraints::Vector{_Function}\n symbolic_functions::Dict{UInt,_SymbolicsFunction}\n hessian_sparsity_map::Vector{Int}\n eval_objective_timer::Float64\n eval_objective_gradient_timer::Float64\n eval_constraint_timer::Float64\n eval_constraint_jacobian_timer::Float64\n eval_hessian_lagrangian_timer::Float64\n function _NonlinearOracle(backend::B, objective, constraints) where {B}\n return new{B}(\n backend,\n objective,\n constraints,\n Dict{UInt,_SymbolicsFunction}(),\n Int[],\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n )\n end\nend\n\nfunction MOI.initialize(\n ::_NonlinearOracle,\n ::AbstractNonlinearOracleBackend,\n ::Vector{Symbol},\n)\n return\nend\n\nfunction MOI.initialize(oracle::_NonlinearOracle, features::Vector{Symbol})\n oracle.eval_constraint_timer = 0.0\n oracle.eval_constraint_jacobian_timer = 0.0\n oracle.eval_hessian_lagrangian_timer = 0.0\n hashes = map(f -> f.expr.hash, oracle.constraints)\n for h in unique(hashes)\n f = oracle.constraints[findfirst(isequal(h), hashes)]\n oracle.symbolic_functions[h] = _SymbolicsFunction(f, features)\n end\n if oracle.objective !== nothing\n f = oracle.objective\n h = f.expr.hash\n if !haskey(oracle.symbolic_functions, h)\n oracle.symbolic_functions[h] = _SymbolicsFunction(f, features)\n end\n end\n MOI.initialize(oracle, oracle.backend, features)\n return\nend\n\nMOI.features_available(::_NonlinearOracle) = [:Grad, :Jac, :Hess]\n\nfunction _update_coefficients(f::_Function, x::AbstractVector{Float64})\n for (i, v) in enumerate(f.ordered_variables)\n @inbounds f.coefficients[i] = x[v]\n end\n return\nend\n\nfunction _eval_function(\n oracle::_NonlinearOracle,\n func::_Function,\n x::AbstractVector{Float64},\n)\n _update_coefficients(func, x)\n @inbounds f = oracle.symbolic_functions[func.expr.hash]\n return f.f(func.data, func.coefficients)::Float64\nend\n\nfunction _eval_gradient(\n oracle::_NonlinearOracle,\n func::_Function,\n x::AbstractVector{Float64},\n)\n _update_coefficients(func, x)\n @inbounds f = oracle.symbolic_functions[func.expr.hash]\n f.∇f(f.g, func.data, func.coefficients)\n return f.g\nend\n\nfunction _eval_hessian(\n oracle::_NonlinearOracle,\n func::_Function,\n x::AbstractVector{Float64},\n)\n _update_coefficients(func, x)\n @inbounds f = oracle.symbolic_functions[func.expr.hash]\n f.∇²f(f.H, func.data, func.coefficients)\n return f.H\nend\n\nfunction MOI.eval_objective(\n oracle::_NonlinearOracle,\n x::AbstractVector{Float64},\n)\n start = time()\n @assert oracle.objective !== nothing\n objective_value = _eval_function(oracle, oracle.objective, x)\n oracle.eval_objective_timer += time() - start\n return objective_value\nend\n\nfunction MOI.eval_objective_gradient(\n oracle::_NonlinearOracle,\n g::AbstractVector{Float64},\n x::AbstractVector{Float64},\n)\n start = time()\n @assert oracle.objective !== nothing\n ∇f = _eval_gradient(oracle, oracle.objective, x)\n fill!(g, 0.0)\n for (i, v) in enumerate(oracle.objective.ordered_variables)\n @inbounds g[v] = ∇f[i]\n end\n oracle.eval_objective_gradient_timer += time() - start\n return\nend\n\nfunction MOI.eval_constraint(\n oracle::_NonlinearOracle,\n g::AbstractVector{Float64},\n x::AbstractVector{Float64},\n)\n start = time()\n for (row, c) in enumerate(oracle.constraints)\n g[row] = _eval_function(oracle, c, x)\n end\n oracle.eval_constraint_timer += time() - start\n return\nend\n\nfunction MOI.jacobian_structure(oracle::_NonlinearOracle)\n structure = Tuple{Int,Int}[]\n for (row, c) in enumerate(oracle.constraints)\n for col in c.ordered_variables\n push!(structure, (row, col))\n end\n end\n return structure\nend\n\nfunction MOI.eval_constraint_jacobian(\n oracle::_NonlinearOracle,\n J::AbstractVector{Float64},\n x::AbstractVector{Float64},\n)\n start = time()\n k = 1\n for c in oracle.constraints\n g = _eval_gradient(oracle, c, x)\n for gi in g\n J[k] = gi\n k += 1\n end\n end\n oracle.eval_constraint_jacobian_timer += time() - start\n return\nend\n\nfunction _hessian_lagrangian_structure(\n ::Vector{Tuple{Int,Int}},\n ::_NonlinearOracle,\n ::Any,\n ::Nothing,\n)\n return\nend\n\nfunction _hessian_lagrangian_structure(\n structure::Vector{Tuple{Int,Int}},\n oracle::_NonlinearOracle,\n map::Dict{Tuple{Int,Int},Int},\n c::_Function,\n)\n f = oracle.symbolic_functions[c.expr.hash]\n for (i, j) in f.H_structure\n row, col = c.ordered_variables[i], c.ordered_variables[j]\n row_col = row >= col ? (row, col) : (col, row)\n index = get(map, row_col, nothing)\n if index === nothing\n push!(structure, row_col)\n map[row_col] = length(structure)\n push!(oracle.hessian_sparsity_map, length(structure))\n else\n push!(oracle.hessian_sparsity_map, index::Int)\n end\n end\n return\nend\n\nfunction MOI.hessian_lagrangian_structure(oracle::_NonlinearOracle)\n structure = Tuple{Int,Int}[]\n map = Dict{Tuple{Int,Int},Int}()\n _hessian_lagrangian_structure(structure, oracle, map, oracle.objective)\n for c in oracle.constraints\n _hessian_lagrangian_structure(structure, oracle, map, c)\n end\n return structure\nend\n\nfunction MOI.eval_hessian_lagrangian(\n oracle::_NonlinearOracle,\n H::AbstractVector{Float64},\n x::AbstractVector{Float64},\n σ::Float64,\n μ::AbstractVector{Float64},\n)\n fill!(H, 0.0)\n start = time()\n k = 1\n if oracle.objective !== nothing && !iszero(σ)\n h = _eval_hessian(oracle, oracle.objective, x)\n for (i, hi) in enumerate(h)\n @inbounds H[oracle.hessian_sparsity_map[i]] += σ * hi\n end\n k += length(h)\n end\n for (μi, constraint) in zip(μ, oracle.constraints)\n if iszero(μi)\n continue\n end\n h = _eval_hessian(oracle, constraint, x)\n for nzval in h\n @inbounds H[oracle.hessian_sparsity_map[k]] += μi * nzval\n k += 1\n end\n end\n oracle.eval_hessian_lagrangian_timer += time() - start\n return\nend\n\nfunction _nonlinear_constraint(expr::Expr)\n lower, upper, body = -Inf, Inf, :()\n if isexpr(expr, :call, 3)\n if expr.args[1] == :(>=)\n lower, upper, body = expr.args[1], expr.args[5], expr.args[3]\n elseif expr.args[1] == :(<=)\n lower, upper, body = -Inf, expr.args[3], expr.args[2]\n else\n @assert expr.args[1] == :(==)\n lower, upper, body = expr.args[3], expr.args[3], expr.args[2]\n end\n else\n @assert isexpr(expr, :comparison, 5)\n lower, upper, body = expr.args[1], expr.args[5], expr.args[3]\n end\n return _Function(body), MOI.NLPBoundsPair(lower, upper)\nend\n\n\"\"\"\n _nlp_block_data(\n d::MOI.AbstractNLPEvaluator;\n backend::AbstractNonlinearOracleBackend,\n )\n\nConvert an AbstractNLPEvaluator into a SymbolicAD instance of MOI.NLPBlockData.\n\"\"\"\nfunction _nlp_block_data(\n d::MOI.AbstractNLPEvaluator;\n backend::AbstractNonlinearOracleBackend,\n)\n MOI.initialize(d, [:ExprGraph])\n objective = d.has_nlobj ? _Function(MOI.objective_expr(d)) : nothing\n n = length(d.constraints)\n functions = Vector{_Function}(undef, n)\n bounds = Vector{MOI.NLPBoundsPair}(undef, n)\n for i in 1:n\n f, bound = _nonlinear_constraint(MOI.constraint_expr(d, i))\n functions[i], bounds[i] = f, bound\n end\n oracle = _NonlinearOracle(backend, objective, functions)\n return MOI.NLPBlockData(bounds, oracle, d.has_nlobj)\nend\n\n###\n### ThreadedBackend\n###\n\nstruct _ConstraintOffset\n index::Int\n ∇f_offset::Int\n ∇²f_offset::Int\nend\n\nstruct ThreadedBackend <: AbstractNonlinearOracleBackend\n offsets::Vector{Vector{_ConstraintOffset}}\n ThreadedBackend() = new(Vector{_ConstraintOffset}[])\nend\n\nfunction MOI.initialize(\n oracle::_NonlinearOracle,\n backend::ThreadedBackend,\n ::Vector{Symbol},\n)\n obj_hess_offset = 0\n if oracle.objective !== nothing\n h = oracle.objective.expr.hash\n obj_hess_offset = length(oracle.symbolic_functions[h].H)\n end\n offsets = Dict{UInt,Vector{_ConstraintOffset}}(\n h => _ConstraintOffset[] for h in keys(oracle.symbolic_functions)\n )\n index, ∇f_offset, ∇²f_offset = 1, 1, obj_hess_offset + 1\n for f in oracle.constraints\n push!(\n offsets[f.expr.hash],\n _ConstraintOffset(index, ∇f_offset, ∇²f_offset),\n )\n index += 1\n symbolic_function = oracle.symbolic_functions[f.expr.hash]\n ∇f_offset += length(symbolic_function.g)\n ∇²f_offset += length(symbolic_function.H)\n end\n for v in values(offsets)\n push!(backend.offsets, v)\n end\n return\nend\n\nfunction MOI.eval_constraint(\n oracle::_NonlinearOracle{ThreadedBackend},\n g::AbstractVector{Float64},\n x::AbstractVector{Float64},\n)\n start = time()\n Threads.@threads for offsets in oracle.backend.offsets\n for c in offsets\n func = oracle.constraints[c.index]\n @inbounds g[c.index] = _eval_function(oracle, func, x)\n end\n end\n oracle.eval_constraint_timer += time() - start\n return\nend\n\nfunction MOI.eval_constraint_jacobian(\n oracle::_NonlinearOracle{ThreadedBackend},\n J::AbstractVector{Float64},\n x::AbstractVector{Float64},\n)\n start = time()\n Threads.@threads for offset in oracle.backend.offsets\n for c in offset\n func = oracle.constraints[c.index]\n g = _eval_gradient(oracle, func, x)\n for i in 1:length(g)\n @inbounds J[c.∇f_offset+i-1] = g[i]\n end\n end\n end\n oracle.eval_constraint_jacobian_timer += time() - start\n return\nend\n\nfunction _hessian_lagrangian_structure(\n structure::Vector{Tuple{Int,Int}},\n oracle::_NonlinearOracle{ThreadedBackend},\n ::Dict{Tuple{Int,Int},Int},\n c::_Function,\n)\n f = oracle.symbolic_functions[c.expr.hash]\n for (i, j) in f.H_structure\n row, col = c.ordered_variables[i], c.ordered_variables[j]\n push!(structure, row >= col ? (row, col) : (col, row))\n end\n return\nend\n\nfunction MOI.eval_hessian_lagrangian(\n oracle::_NonlinearOracle{ThreadedBackend},\n H::AbstractVector{Float64},\n x::AbstractVector{Float64},\n σ::Float64,\n μ::AbstractVector{Float64},\n)\n fill!(H, 0.0)\n start = time()\n hessian_offset = 0\n if oracle.objective !== nothing && !iszero(σ)\n h = _eval_hessian(oracle, oracle.objective, x)\n for i in 1:length(h)\n H[i] = σ * h[i]\n end\n hessian_offset += length(h)\n end\n Threads.@threads for offset in oracle.backend.offsets\n for c in offset\n if iszero(μ[c.index])\n continue\n end\n func = oracle.constraints[c.index]\n h = _eval_hessian(oracle, func, x)\n for i in 1:length(h)\n @inbounds H[c.∇²f_offset+i-1] = μ[c.index] * h[i]\n end\n end\n end\n oracle.eval_hessian_lagrangian_timer += time() - start\n return\nend\n\n###\n### JuMP integration\n###\n\nfunction _to_expr(\n nlp_data::JuMP._NLPData,\n data::JuMP._NonlinearExprData,\n subexpressions::Vector{Expr},\n)\n tree = Any[]\n for node in data.nd\n expr = if node.nodetype == JuMP._Derivatives.CALL\n Expr(:call, JuMP._Derivatives.operators[node.index])\n elseif node.nodetype == JuMP._Derivatives.CALLUNIVAR\n Expr(:call, JuMP._Derivatives.univariate_operators[node.index])\n elseif node.nodetype == JuMP._Derivatives.SUBEXPRESSION\n subexpressions[node.index]\n elseif node.nodetype == JuMP._Derivatives.MOIVARIABLE\n MOI.VariableIndex(node.index)\n elseif node.nodetype == JuMP._Derivatives.PARAMETER\n nlp_data.nlparamvalues[node.index]\n else\n @assert node.nodetype == JuMP._Derivatives.VALUE\n data.const_values[node.index]\n end\n if 1 <= node.parent <= length(tree)\n push!(tree[node.parent].args, expr)\n end\n push!(tree, expr)\n end\n return tree[1]\nend\n\n_to_expr(::JuMP._NLPData, ::Nothing, ::Vector{Expr}) = nothing\n\nfunction _nlp_block_data(\n model::JuMP.Model;\n backend::AbstractNonlinearOracleBackend,\n)\n return _nlp_block_data(model.nlp_data; backend = backend)\nend\n\nfunction _nlp_block_data(\n nlp_data::JuMP._NLPData;\n backend::AbstractNonlinearOracleBackend,\n)\n subexpressions = map(nlp_data.nlexpr) do expr\n return _to_expr(nlp_data, expr, Expr[])::Expr\n end\n nlobj = _to_expr(nlp_data, nlp_data.nlobj, subexpressions)\n objective = nlobj === nothing ? nothing : _Function(nlobj)\n functions = map(nlp_data.nlconstr) do c\n return _Function(_to_expr(nlp_data, c.terms, subexpressions))\n end\n return MOI.NLPBlockData(\n [MOI.NLPBoundsPair(c.lb, c.ub) for c in nlp_data.nlconstr],\n _NonlinearOracle(backend, objective, functions),\n objective !== nothing,\n )\nend\n\nfunction optimize_hook(\n model::JuMP.Model;\n backend::AbstractNonlinearOracleBackend = DefaultBackend(),\n)\n nlp_block = _nlp_block_data(model; backend = backend)\n nlp_data = model.nlp_data\n model.nlp_data = nothing\n MOI.set(model, MOI.NLPBlock(), nlp_block)\n JuMP.optimize!(model; ignore_optimize_hook = true)\n model.nlp_data = nlp_data\n return\nend\n", "meta": {"hexsha": "78f016c72e5e673d54cf1785db73692d61af41a9", "size": 23774, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinear_oracle.jl", "max_stars_repo_name": "odow/SymbolicAD.jl", "max_stars_repo_head_hexsha": "bae8b1e042841b80fef5606b71e13e1d30255df2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2022-03-18T06:42:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:58:31.000Z", "max_issues_repo_path": "src/nonlinear_oracle.jl", "max_issues_repo_name": "odow/SymbolicAD.jl", "max_issues_repo_head_hexsha": "bae8b1e042841b80fef5606b71e13e1d30255df2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-03-29T19:45:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T08:28:25.000Z", "max_forks_repo_path": "src/nonlinear_oracle.jl", "max_forks_repo_name": "odow/SymbolicAD.jl", "max_forks_repo_head_hexsha": "bae8b1e042841b80fef5606b71e13e1d30255df2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6143617021, "max_line_length": 80, "alphanum_fraction": 0.6569782115, "num_tokens": 6259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23966798115040902}} {"text": "parse_float(x) = parse(Float64, x)\n\nfunction run_lblrtm(work_dir::String, ν_s::Float64, ν_e::Float64)::Tuple{Array{Float64,1},Array{Float64,1}}\n ν_s -= 25\n ν_e += 25\n\n @info \"Entering $(pwd()) ...\"\n cd(work_dir)\n @info \"Entered.\"\n\n @info \"Checking system links...\"\n requirements = [\"lblrtm\", \"TAPE3\"]\n for link in requirements\n @assert(islink(link) || isfile(link), \"$link does not exist.\")\n end\n @info \"System links OK.\"\n\n @info \"Removing last run's files...\"\n rm(\"TAPE5\", force=true)\n rm(\"TAPE6\", force=true)\n rm(\"TAPE7\", force=true)\n rm(\"TAPE8\", force=true)\n rm(\"TAPE10\", force=true)\n @info \"Removed.\"\n\n IHIRAC = 1\n ILBLF4 = 2\n ICNTNM = 1\n IAERSL = 1\n IEMIT = 1\n ISCAN = 0\n IFILTR = 0\n IPLOT = 0\n ITEST = 0\n IATM = 1\n IMRG = 0\n ILAS = 0\n IOD = 1\n IXSECT = 0\n NPTS = 80\n ISOTPL = 0\n IBRD = 0\n\n SAMPLE = 4\n DVSET = 0.0 # Spectral resolution for calculation\n ALFAL0 = 0.04\n AVMASS = 36.0\n DPTMIN = 0.0002\n DPTFAC = 0.001\n IFNFLG = 0\n DVOUT = 0.1 # Spectral resolution for output\n \n TBOUND = 300.0 # Boundary temperature\n SREMIS = 1.0 # Emissivity coefficient - Rand 0\n\n MODEL = 6 # U.S.Standard\n ITYPE = 2\n IBMAX = 0\n ZERO = 0\n NOPRNT = 0\n\n H1 = 100.0\n H2 = 0.0\n ANGLE = 180.0\n @info \"Writing TAPE5...\"\n open(\"TAPE5\", \"w\") do tape5\n write(tape5, \"\\$ LBLRTM INPUT\\n\") # Record 1.1\n write(tape5, \" HI=$IHIRAC F4=$ILBLF4 CN=$ICNTNM AE=$IAERSL EM=$IEMIT SC=$ISCAN FI=$IFILTR PL=$IPLOT TS=$ITEST AM=$IATM MG=$IMRG LA=$ILAS OD=$IOD XS=$IXSECT 00 00\\n\") # Record 1.2\n write(tape5, @sprintf(\"%10.3f%10.3f%10.3f%10.3f%10.3f%10.3f%10.3f%10.3f%5d%10.3f\\n\", ν_s, ν_e, SAMPLE, DVSET, ALFAL0, AVMASS, DPTMIN, DPTFAC, IFNFLG, DVOUT)) # Record 1.3\n write(tape5, @sprintf(\"%10.3f%10.3f\\n\", TBOUND, SREMIS)) # Record 1.4\n write(tape5, @sprintf(\"%5d%5d%5d%5d%5d\\n\", MODEL, ITYPE, IBMAX, ZERO, NOPRNT)) # Record 3.1\n write(tape5, @sprintf(\"%10.3f%10.3f%10.3f\\n\", H1, H2, ANGLE)) # Record 3.2\n write(tape5, \"\\n\") # Record 3.3A\n write(tape5, \"\\n\") # Record 4.1\n write(tape5, \"-1.\\n\")\n write(tape5, @sprintf(\n\"\"\"\n\\$ Transfer to ASCII plotting data\n HI=0 F4=0 CN=0 AE=0 EM=0 SC=0 FI=0 PL=1 TS=0 AM=0 MG=0 LA=0 MS=0 XS=0 0 0\n# Plot title not used\n%10.3f%10.3f 10.2000 100.0000 5 0 12 0 1.000 0 0 0\n 0.0000 1.2000 7.0200 0.2000 4 0 1 1 0 0 0 3 27\n%10.3f%10.3f 10.2000 100.0000 5 0 12 0 1.000 0 0 0\n 0.0000 1.2000 7.0200 0.2000 4 0 1 1 1 0 0 3 28\n-1.\n\"\"\", ν_s, ν_e, ν_s, ν_e))\n end\n @info \"TAPE5 OK.\"\n\n # Run LBLRTM\n @info \"Running LBLRTM...\"\n @time run(`./lblrtm`)\n @info \"LBLRTM completed.\"\n\n # Collect result\n @info \"Collecting result...\"\n wavenumber = []\n brightness_temperature = []\n open(\"TAPE28\") do io\n see_header = false\n see_data = false\n for line in eachline(io)\n if !see_header\n if findfirst(\"WAVENUMBER\", line) ≠ nothing\n see_header = true\n end\n elseif !see_data\n see_data = true\n else\n wb, bt = map(parse_float, split(strip(line), r\"\\s+\"))\n append!(wavenumber, wb)\n append!(brightness_temperature, bt)\n end\n end\n end\n @info \"Results collected.\"\n\n return (wavenumber, brightness_temperature)\nend", "meta": {"hexsha": "0666a2deb17d07d9ed561904a7033652f451c47b", "size": 3566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/run_lblrtm.jl", "max_stars_repo_name": "lucifer1004/LBLRTM.jl", "max_stars_repo_head_hexsha": "23611861b4c94bbf726867f32f98599c42a607c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/run_lblrtm.jl", "max_issues_repo_name": "lucifer1004/LBLRTM.jl", "max_issues_repo_head_hexsha": "23611861b4c94bbf726867f32f98599c42a607c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-09-19T00:52:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-29T08:59:22.000Z", "max_forks_repo_path": "src/run_lblrtm.jl", "max_forks_repo_name": "lucifer1004/LBLRTM.jl", "max_forks_repo_head_hexsha": "23611861b4c94bbf726867f32f98599c42a607c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9663865546, "max_line_length": 190, "alphanum_fraction": 0.5443073472, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23966797489595806}} {"text": "# Driver functions for the integrators.\n\nstruct MolecularDynamicsParameters\n \"Centroid friction (1 / ps).\"\n gamma0::Float64\n \"Time step (ps).\"\n dt::Float64\n \"Total duration (ps).\"\n duration::Float64\nend\n\n\"\"\"\n num_steps(mdp::MolecularDynamicsParameters)\n\nNumber of molecular dynamics steps for `mdp`.\n\"\"\"\nnum_steps(mdp::MolecularDynamicsParameters) = ceil(Int, mdp.duration / mdp.dt)\n\n\nfunction run_constrained_equilibration(\n model_T::Type{<:WaterModel}, int_T::Type{<:Integrator}, N::Int,\n T::Float64, R::Float64, P::Int, mdp_equil::MolecularDynamicsParameters;\n qs_init::Maybe{Vector{Float64}}=nothing, output_skip::Int=100)\n is_constrained(int_T) || error(\"Integrator is not constrained.\")\n\n # Number of atoms in each water molecule.\n A = 3\n # Number of spatial dimensions.\n D = 3\n\n if !isnothing(qs_init)\n s = State(P, D, A, N; qs_init)\n else\n s = State(P, D, A, N; R)\n end\n\n model = model_T(N)\n fc = ForceContainer(P, D, A, N)\n int_equil = int_T(model, R, mdp_equil.dt, beta(T), mdp_equil.gamma0, fc, s)\n\n for i in 1:num_steps(mdp_equil)\n step!(s, int_equil)\n\n i % output_skip == 0 || continue\n\n time = i * mdp_equil.dt\n E = energy(int_equil, s)\n E_K = pop!(E, \"kinetic\")\n E_Vspring = pop!(E, \"spring\")\n E_Vmodel = pop!(E, \"model\")\n isempty(E) || error(\"Unexpected energy contribution.\")\n E_total = E_K + E_Vspring + E_Vmodel\n T = get_temperature(int_equil)\n\n println(\"$(time) $(E_K) $(E_Vspring) $(E_Vmodel) $(E_total) $(T)\")\n end\n\n s\nend\n\nfunction run_constrained_production(\n model_T::Type{<:WaterModel}, int_T::Type{<:Integrator}, N::Int,\n T::Float64, R::Float64, P::Int, mdp_equil::MolecularDynamicsParameters,\n mdp_prod::MolecularDynamicsParameters;\n qs_init::Maybe{Vector{Float64}}=nothing, aux_output::IO=stderr)\n is_constrained(int_T) || error(\"Integrator is not constrained.\")\n\n # Number of atoms in each water molecule.\n A = 3\n # Number of spatial dimensions.\n D = 3\n\n # Number of molecular dynamics steps for equilibration.\n N_equil = num_steps(mdp_equil)\n # Number of molecular dynamics steps for production.\n N_prod = num_steps(mdp_prod)\n\n if !isnothing(qs_init)\n s = State(P, D, A, N; qs_init)\n else\n s = State(P, D, A, N; R)\n end\n\n model = model_T(N)\n fc = ForceContainer(P, D, A, N)\n int_equil = int_T(model, R, mdp_equil.dt, beta(T), mdp_equil.gamma0, fc, s)\n int_prod = int_T(model, R, mdp_prod.dt, beta(T), mdp_prod.gamma0, fc, s)\n\n meter_equil = Progress(N_equil, output=aux_output)\n\n for _ in ProgressWrapper(1:N_equil, meter_equil)\n step!(s, int_equil)\n end\n\n constraints = Array{Float64}(undef, N_prod)\n E_Ks = Array{Float64}(undef, N_prod)\n E_Vsprings = Array{Float64}(undef, N_prod)\n E_Vmodels = Array{Float64}(undef, N_prod)\n E_totals = Array{Float64}(undef, N_prod)\n temperatures = Array{Float64}(undef, N_prod)\n\n forces1 = Array{Float64}(undef, N_prod)\n forces2 = Array{Float64}(undef, N_prod)\n\n estim1 = estimator1(R, beta(T), int_prod, s)\n estim2 = estimator2(R, beta(T), int_prod, s)\n\n meter = Progress(N_prod, output=aux_output)\n\n for i in ProgressWrapper(1:N_prod, meter)\n step!(s, int_prod)\n\n constraints[i] = com_r(CN1, CN2, CJ, s)\n E = energy(int_prod, s)\n E_Ks[i] = pop!(E, \"kinetic\")\n E_Vsprings[i] = pop!(E, \"spring\")\n E_Vmodels[i] = pop!(E, \"model\")\n isempty(E) || error(\"Unexpected energy contribution.\")\n E_totals[i] = E_Ks[i] + E_Vsprings[i] + E_Vmodels[i]\n temperatures[i] = get_temperature(int_prod)\n\n forces1[i] = estim1()\n forces2[i] = estim2()\n end\n\n data_table = []\n\n for (label, data) in [(\"xi (nm)\", constraints),\n (\"K (kJ / mol)\", E_Ks),\n (\"Vspring (kJ / mol)\", E_Vsprings),\n (\"Vmodel (kJ / mol)\", E_Vmodels),\n (\"E (kJ / mol)\", E_totals),\n (\"T (K)\", temperatures),\n (\"est1 (1 / nm)\", forces1),\n (\"est2 (1 / nm)\", forces2)]\n data_mean, data_stderr, data_actime = aggregate(mdp_prod.dt, data)\n push!(data_table, [label, data_mean, data_stderr, data_actime])\n end\n\n pretty_table(aux_output, permutedims(hcat(data_table...)),\n [\"\", \"Value\", \"Error\", \"Autocorrelation time (ps)\"])\n\n s, aggregate(mdp_prod.dt, forces1), aggregate(mdp_prod.dt, forces2)\nend\n\n\nfunction run_restrained_equilibration(\n model_T::Type{<:WaterModel}, int_T::Type{<:Integrator}, N::Int,\n T::Float64, R::Float64, P::Int, mdp_equil::MolecularDynamicsParameters,\n bias_force_constant::Float64; qs_init::Maybe{Vector{Float64}}=nothing,\n output_skip::Int=100)\n is_constrained(int_T) && error(\"Integrator is constrained.\")\n\n # Number of atoms in each water molecule.\n A = 3\n # Number of spatial dimensions.\n D = 3\n\n if !isnothing(qs_init)\n s = State(P, D, A, N; qs_init)\n else\n s = State(P, D, A, N; R)\n end\n\n bias = HarmonicRestraint(bias_force_constant, R, CN1, CN2, CJ)\n model = model_T(N)\n fc = ForceContainer(P, D, A, N)\n int_equil = int_T(model, mdp_equil.dt, beta(T), mdp_equil.gamma0, fc, s;\n extra_forces=Dict(\"bias\" => [bias]))\n\n for i in 1:num_steps(mdp_equil)\n step!(s, int_equil)\n\n i % output_skip == 0 || continue\n\n time = i * mdp_equil.dt\n xi = com_r(CN1, CN2, CJ, s)\n E = energy(int_equil, s)\n E_K = pop!(E, \"kinetic\")\n E_Vspring = pop!(E, \"spring\")\n E_Vmodel = pop!(E, \"model\")\n E_Vbias = pop!(E, \"bias\")\n isempty(E) || error(\"Unexpected energy contribution.\")\n E_total = E_K + E_Vspring + E_Vmodel + E_Vbias\n T = get_temperature(int_equil)\n\n print(\"$(time) $(xi) $(E_K) $(E_Vspring) $(E_Vmodel) $(E_Vbias) \")\n println(\"$(E_total) $(T)\")\n end\n\n s\nend\n\nfunction run_restrained_production(\n model_T::Type{<:WaterModel}, int_T::Type{<:Integrator}, N::Int,\n T::Float64, R::Float64, P::Int, mdp_equil::MolecularDynamicsParameters,\n mdp_prod::MolecularDynamicsParameters, bias_force_constant::Float64;\n qs_init::Maybe{Vector{Float64}}=nothing, output_skip::Int=100)\n is_constrained(int_T) && error(\"Integrator is constrained.\")\n\n # Number of atoms in each water molecule.\n A = 3\n # Number of spatial dimensions.\n D = 3\n\n # Number of molecular dynamics steps for equilibration.\n N_equil = num_steps(mdp_equil)\n # Number of molecular dynamics steps for production.\n N_prod = num_steps(mdp_prod)\n\n if !isnothing(qs_init)\n s = State(P, D, A, N; qs_init)\n else\n s = State(P, D, A, N; R)\n end\n\n bias = HarmonicRestraint(bias_force_constant, R, CN1, CN2, CJ)\n model = model_T(N)\n fc = ForceContainer(P, D, A, N)\n int_equil = int_T(model, mdp_equil.dt, beta(T), mdp_equil.gamma0, fc, s;\n extra_forces=Dict(\"bias\" => [bias]))\n int_prod = int_T(model, mdp_prod.dt, beta(T), mdp_prod.gamma0, fc, s;\n extra_forces=Dict(\"bias\" => [bias]))\n\n for _ in 1:N_equil\n step!(s, int_equil)\n end\n\n for i in 1:N_prod\n step!(s, int_prod)\n\n i % output_skip == 0 || continue\n\n println(com_r(CN1, CN2, CJ, s))\n end\n\n s\nend\n", "meta": {"hexsha": "5dac06872f6714d49802a8dd6d2c70aa7a412019", "size": 7527, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/run.jl", "max_stars_repo_name": "0/WaterMeanMeanForce.jl", "max_stars_repo_head_hexsha": "a10068ecce6456bc57215cce8e60cd6976cae608", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/run.jl", "max_issues_repo_name": "0/WaterMeanMeanForce.jl", "max_issues_repo_head_hexsha": "a10068ecce6456bc57215cce8e60cd6976cae608", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/run.jl", "max_forks_repo_name": "0/WaterMeanMeanForce.jl", "max_forks_repo_head_hexsha": "a10068ecce6456bc57215cce8e60cd6976cae608", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4937238494, "max_line_length": 79, "alphanum_fraction": 0.6019662548, "num_tokens": 2238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.23960216046857674}} {"text": "# This file is a part of Julia. License is MIT: https://julialang.org/license\n\nmodule FieldValues\n\nusing ...VersionWeights\n\nexport FieldValue, Field, validmax, secondmax\n\n# FieldValue is a hierarchical numeric type with 5 levels.\n# When summing two FieldValues, the levels are summed independently.\n# When comparing them, lower levels take precedence.\n# The levels are used as such:\n# l0 : for hard constraints (dependencies and requirements)\n# l1 : for favoring higher versions of the explicitly required\n# packages\n# l2 : for favoring higher versions of all other packages\n# l3 : for favoring uninstallation of non-needed packages\n#\nstruct FieldValue\n l0::Int64\n l1::VersionWeight\n l2::VersionWeight\n l3::Int64\n FieldValue(l0::Integer = 0,\n l1::VersionWeight = zero(VersionWeight),\n l2::VersionWeight = zero(VersionWeight),\n l3::Integer = 0) = new(l0, l1, l2, l3)\nend\n\n# This isn't nice, but it's for debugging only anyway\nfunction Base.show(io::IO, a::FieldValue)\n print(io, a.l0)\n a == FieldValue(a.l0) && return\n print(io, \".\", a.l1)\n a == FieldValue(a.l0, a.l1) && return\n print(io, \".\", a.l2)\n a == FieldValue(a.l0, a.l1, a.l2) && return\n print(io, \".\", a.l3)\n return\nend\n\nconst Field = Vector{FieldValue}\n\nBase.zero(::Type{FieldValue}) = FieldValue()\n\nBase.typemin(::Type{FieldValue}) = (x=typemin(Int64); y=typemin(VersionWeight); FieldValue(x, y, y, x))\n\nBase.:-(a::FieldValue, b::FieldValue) = FieldValue(a.l0-b.l0, a.l1-b.l1, a.l2-b.l2, a.l3-b.l3)\nBase.:+(a::FieldValue, b::FieldValue) = FieldValue(a.l0+b.l0, a.l1+b.l1, a.l2+b.l2, a.l3+b.l3)\n\nfunction Base.isless(a::FieldValue, b::FieldValue)\n a.l0 < b.l0 && return true\n a.l0 > b.l0 && return false\n c = cmp(a.l1, b.l1)\n c < 0 && return true\n c > 0 && return false\n c = cmp(a.l2, b.l2)\n c < 0 && return true\n c > 0 && return false\n a.l3 < b.l3 && return true\n return false\nend\n\nBase.:(==)(a::FieldValue, b::FieldValue) =\n a.l0 == b.l0 && a.l1 == b.l1 && a.l2 == b.l2 && a.l3 == b.l3\n\nBase.abs(a::FieldValue) = FieldValue(abs(a.l0), abs(a.l1), abs(a.l2), abs(a.l3))\n\nBase.copy(a::FieldValue) = FieldValue(a.l0, copy(a.l1), copy(a.l2), a.l3)\n\n# if the maximum field has l0 < 0, it means that\n# some hard constraint is being violated\nvalidmax(a::FieldValue) = a.l0 >= 0\n\n# like usual indmax, but favors the highest indices\n# in case of a tie\nfunction Base.indmax(f::Field)\n m = typemin(FieldValue)\n mi = 0\n for j = length(f):-1:1\n if f[j] > m\n m = f[j]\n mi = j\n end\n end\n @assert mi != 0\n return mi\nend\n\n# secondmax returns the (normalized) value of the second maximum in a\n# field. It's used to determine the most polarized field.\nfunction secondmax(f::Field, msk::BitVector = trues(length(f)))\n m = typemin(FieldValue)\n m2 = typemin(FieldValue)\n for i = 1:length(f)\n msk[i] || continue\n a = f[i]\n if a > m\n m2 = m\n m = a\n elseif a > m2\n m2 = a\n end\n end\n return m2 - m\nend\n\n# Support broadcasting like a scalar by default\nBase.Broadcast.broadcastable(a::FieldValue) = Ref(a)\n\nend\n", "meta": {"hexsha": "7bfa49551392d7ad3ddb95039437d774099ce043", "size": 3205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "stdlib/Pkg3/src/resolve/FieldValues.jl", "max_stars_repo_name": "djsegal/julia-fork", "max_stars_repo_head_hexsha": "dd3d14e5e7d24985cba6185e2d07a62ee9943d4e", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-28T14:58:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:20:14.000Z", "max_issues_repo_path": "stdlib/Pkg3/src/resolve/FieldValues.jl", "max_issues_repo_name": "djsegal/julia-fork", "max_issues_repo_head_hexsha": "dd3d14e5e7d24985cba6185e2d07a62ee9943d4e", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stdlib/Pkg3/src/resolve/FieldValues.jl", "max_forks_repo_name": "djsegal/julia-fork", "max_forks_repo_head_hexsha": "dd3d14e5e7d24985cba6185e2d07a62ee9943d4e", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6160714286, "max_line_length": 103, "alphanum_fraction": 0.6230889236, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23959216141852563}} {"text": "module Enzyme\n\nexport Forward, Reverse\nexport Const, Active, Duplicated, DuplicatedNoNeed, BatchDuplicated, BatchDuplicatedNoNeed\nexport autodiff, jacobian, gradient, gradient!\nexport markType, batch_size, onehot, chunkedonehot\n\nusing LinearAlgebra\n\n# Independent code, must be loaded before \"compiler.jl\"\ninclude(\"pmap.jl\")\n\nusing Adapt\n\n\"\"\"\n abstract type Annotation{T}\n\nAbstract type for [`autodiff`](@ref) function argument wrappers like\n[`Const`](@ref), [`Active`](@ref) and [`Duplicated`](@ref).\n\"\"\"\nabstract type Annotation{T} end\nBase.eltype(::Type{<:Annotation{T}}) where T = T\n\n\"\"\"\n Const(x)\n\nMark a function argument `x` of [`autodiff`](@ref) as constant,\nEnzyme will not auto-differentiate in respect `Const` arguments.\n\"\"\"\nstruct Const{T} <: Annotation{T}\n val::T\nend\nAdapt.adapt_structure(to, x::Const) = Const(adapt(to, x.val))\n\n# To deal with Const(Int) and prevent it to go to `Const{DataType}(T)`\nConst(::Type{T}) where T = Const{Type{T}}(T)\n\n\"\"\"\n Active(x)\n\nMark a function argument `x` of [`autodiff`](@ref) as active,\nEnzyme will auto-differentiate in respect `Active` arguments.\n\n!!! note\n\n Enzyme gradients with respect to integer values are zero.\n [`Active`](@ref) will automatically convert plain integers to floating\n point values, but cannot do so for integer values in tuples and structs.\n\"\"\"\nstruct Active{T} <: Annotation{T}\n val::T\nend\nAdapt.adapt_structure(to, x::Active) = Active(adapt(to, x.val))\n\nActive(i::Integer) = Active(float(i))\n\n\"\"\"\n Duplicated(x, ∂f_∂x)\n\nMark a function argument `x` of [`autodiff`](@ref) as duplicated, Enzyme will\nauto-differentiate in respect to such arguments, with `dx` acting as an\naccumulator for gradients (so ``\\\\partial f / \\\\partial x`` will be *added to*)\n`∂f_∂x`.\n\"\"\"\nstruct Duplicated{T} <: Annotation{T}\n val::T\n dval::T\nend\nAdapt.adapt_structure(to, x::Duplicated) = Duplicated(adapt(to, x.val), adapt(to, x.dval))\n\n\"\"\"\n DuplicatedNoNeed(x, ∂f_∂x)\n\nLike [`Duplicated`](@ref), except also specifies that Enzyme may avoid computing\nthe original result and only compute the derivative values.\n\"\"\"\nstruct DuplicatedNoNeed{T} <: Annotation{T}\n val::T\n dval::T\nend\nAdapt.adapt_structure(to, x::DuplicatedNoNeed) = DuplicatedNoNeed(adapt(to, x.val), adapt(to, x.dval))\n\n\"\"\"\n BatchDuplicated(x, ∂f_∂xs)\n\nLike [`Duplicated`](@ref), except contains several shadows to compute derivatives\nfor all at once. Argument `∂f_∂xs` should be a tuple of the several values of type `x`.\n\"\"\"\nstruct BatchDuplicated{T,N} <: Annotation{T}\n val::T\n dval::NTuple{N,T}\nend\nAdapt.adapt_structure(to, x::BatchDuplicated) = BatchDuplicated(adapt(to, x.val), adapt(to, x.dval))\n\n\"\"\"\n BatchDuplicatedNoNeed(x, ∂f_∂xs)\n\nLike [`DuplicatedNoNeed`](@ref), except contains several shadows to compute derivatives\nfor all at once. Argument `∂f_∂xs` should be a tuple of the several values of type `x`.\n\"\"\"\nstruct BatchDuplicatedNoNeed{T,N} <: Annotation{T}\n val::T\n dval::NTuple{N,T}\nend\nbatch_size(::BatchDuplicated{T,N}) where {T,N} = N\nbatch_size(::BatchDuplicatedNoNeed{T,N}) where {T,N} = N\nAdapt.adapt_structure(to, x::BatchDuplicatedNoNeed) = BatchDuplicatedNoNeed(adapt(to, x.val), adapt(to, x.dval))\n\n\"\"\"\n abstract type Mode\n\nAbstract type for what differentiation mode will be used.\n\"\"\"\nabstract type Mode end\n\n\"\"\"\n struct Reverse <: Mode\n\nReverse mode differentiation\n\"\"\"\nstruct ReverseMode <: Mode\nend\nconst Reverse = ReverseMode()\nguess_activity(::Type{T}, ::ReverseMode) where T = guess_activity(T)\n\n\"\"\"\n struct Forward <: Mode\n\nForward mode differentiation\n\"\"\"\nstruct ForwardMode <: Mode\nend\nconst Forward = ForwardMode()\nguess_activity(::Type{T}, ::ForwardMode) where T = guess_activity(T, API.DEM_ForwardMode)\n\nimport LLVM\ninclude(\"api.jl\")\n\n@inline function guess_activity(::Type{T}, Mode::API.CDerivativeMode=API.DEM_ReverseModeCombined) where {T}\n return Const{T}\nend\n@inline function guess_activity(::Type{T}, Mode::API.CDerivativeMode=API.DEM_ReverseModeCombined) where {T<:AbstractFloat}\n if Mode == API.DEM_ForwardMode\n return DuplicatedNoNeed{T}\n else\n return Active{T}\n end\nend\n@inline function guess_activity(::Type{T}, Mode::API.CDerivativeMode=API.DEM_ReverseModeCombined) where {T<:Complex{<:AbstractFloat}}\n if Mode == API.DEM_ForwardMode\n return DuplicatedNoNeed{T}\n else\n return Active{T}\n end\nend\n\n@inline function guess_activity(::Type{T}, Mode::API.CDerivativeMode=API.DEM_ReverseModeCombined) where {T<:AbstractArray}\n if Mode == API.DEM_ForwardMode\n return DuplicatedNoNeed{T}\n else\n return Duplicated{T}\n end\nend\n\n\ninclude(\"logic.jl\")\ninclude(\"typeanalysis.jl\")\ninclude(\"typetree.jl\")\ninclude(\"utils.jl\")\ninclude(\"compiler.jl\")\n\nimport .Compiler: CompilationException\n\n# @inline annotate() = ()\n# @inline annotate(arg::A, args::Vararg{Any, N}) where {A<:Annotation, N} = (arg, annotate(args...)...)\n# @inline annotate(arg, args::Vararg{Any, N}) where N = (Const(arg), annotate(args...)...)\n\n@inline function annotate(args::Vararg{Any, N}) where N\n ntuple(Val(N)) do i\n Base.@_inline_meta\n arg = @inbounds args[i]\n if arg isa Annotation\n return arg\n else\n return Const(arg)\n end\n end\nend\n\n@inline function same_or_one(args::Vararg{Any, N}) where N\n current = -1\n for arg in args\n if arg isa BatchDuplicated\n if current == -1\n current = batch_size(arg)\n else\n @assert current == batch_size(arg)\n end\n elseif arg isa BatchDuplicatedNoNeed\n if current == -1\n current = batch_size(arg)\n else\n @assert current == batch_size(arg)\n end\n end\n end\n\n if current == -1\n current = 1\n end\n\n return current\nend\n\n\"\"\"\n autodiff(::ReverseMode, f, Activity, args...)\n\nAuto-differentiate function `f` at arguments `args` using reverse mode.\n\nLimitations:\n\n* `f` may only return a `Real` (of a built-in/primitive type) or `nothing`,\n not an array, struct, `BigFloat`, etc. To handle vector-valued return\n types, use a mutating `f!` that returns `nothing` and stores it's return\n value in one of the arguments, which must be wrapped in a\n [`Duplicated`](@ref).\n\n`args` may be numbers, arrays, structs of numbers, structs of arrays and so\non. Enzyme will only differentiate in respect to arguments that are wrapped\nin an [`Active`](@ref) (for immutable arguments like primitive types and\nstructs thereof) or [`Duplicated`](@ref) (for mutable arguments like arrays,\n`Ref`s and structs thereof). Non-annotated arguments will automatically be\ntreated as [`Const`](@ref).\n\n`Activity` is the Activity of the return value, it may be `Const` or `Active`.\n\nExample:\n\n```jldoctest\na = 4.2\nb = [2.2, 3.3]; ∂f_∂b = zero(b)\nc = 55; d = 9\n\nf(a, b, c, d) = a * √(b[1]^2 + b[2]^2) + c^2 * d^2\n∂f_∂a, ∂f_∂d = autodiff(Reverse, f, Active, Active(a), Duplicated(b, ∂f_∂b), c, Active(d))\n\n# output\n\n(3.966106403010388, 54450.0)\n```\n\nhere, `autodiff` returns a tuple\n``(\\\\partial f/\\\\partial a, \\\\partial f/\\\\partial d)``,\nwhile ``\\\\partial f/\\\\partial b`` will be *added to* `∂f_∂b` (but not returned).\n`c` will be treated as `Const(c)`.\n\n!!! note\n\n Enzyme gradients with respect to integer values are zero.\n [`Active`](@ref) will automatically convert plain integers to floating\n point values, but cannot do so for integer values in tuples and structs.\n\"\"\"\n@inline function autodiff(::ReverseMode, f::F, ::Type{A}, args...) where {F, A<:Annotation}\n args′ = annotate(args...)\n tt′ = Tuple{map(Core.Typeof, args′)...}\n width = Val(same_or_one(args...))\n if A <: Active\n tt = Tuple{map(T->eltype(Core.Typeof(T)), args′)...}\n rt = Core.Compiler.return_type(f, tt)\n if !allocatedinline(rt)\n forward, adjoint = Enzyme.Compiler.thunk(f, #=df=#nothing, Duplicated{rt}, tt′, #=Split=# Val(API.DEM_ReverseModeGradient), width, #=ModifiedBetween=#Val(false))\n res = forward(args′...)\n @assert length(res) == 2\n tape = res[1]\n if res[2] isa Base.RefValue\n res[2][] += one(eltype(typeof(res[2])))\n else\n res[2] += one(eltype(typeof(res[2])))\n end\n return adjoint(args′..., tape)\n end\n elseif A <: Duplicated || A<: DuplicatedNoNeed || A <: BatchDuplicated || A<: BatchDuplicatedNoNeed\n throw(ErrorException(\"Duplicated Returns not yet handled\"))\n end\n thunk = Enzyme.Compiler.thunk(f, #=df=#nothing, A, tt′, #=Split=# Val(API.DEM_ReverseModeCombined), width)\n if A <: Active\n tt = Tuple{map(T->eltype(Core.Typeof(T)), args′)...}\n rt = eltype(Compiler.return_type(thunk))\n args′ = (args′..., one(rt))\n end\n thunk(args′...)\nend\n\n@inline function autodiff(::ReverseMode, dupf::Duplicated{F}, ::Type{A}, args...) where {F, A<:Annotation}\n args′ = annotate(args...)\n tt′ = Tuple{map(Core.Typeof, args′)...}\n width = Val(same_or_one(args...))\n thunk = Enzyme.Compiler.thunk(#=f=#dupf.val, #=df=#dupf.dval, A, tt′, #=Split=# Val(API.DEM_ReverseModeCombined), width)\n if A <: Active\n rt = eltype(Compiler.return_type(thunk))\n args′ = (args′..., one(rt))\n end\n thunk(args′...)\nend\n\n\n\"\"\"\n autodiff(mode::Mode, f, args...)\n autodiff(f, mode::Mode, args...)\n\nLike [`autodiff`](@ref) but will try to guess the activity of the return value.\n\"\"\"\n@inline function autodiff(mode::Mode, f::F, args...) where {F}\n args′ = annotate(args...)\n tt′ = Tuple{map(Core.Typeof, args′)...}\n tt = Tuple{map(T->eltype(Core.Typeof(T)), args′)...}\n rt = Core.Compiler.return_type(f, tt)\n A = guess_activity(rt, mode)\n autodiff(mode, f, A, args′...)\nend\n\n@inline function autodiff(mode::Mode, dupf::Duplicated{F}, args...) where {F}\n args′ = annotate(args...)\n tt′ = Tuple{map(Core.Typeof, args′)...}\n tt = Tuple{map(T->eltype(Core.Typeof(T)), args′)...}\n rt = Core.Compiler.return_type(dupf.val, tt)\n A = guess_activity(rt, mode)\n autodiff(mode, dupf, A, args′...)\nend\n\n\"\"\"\n autodiff(::ForwardMode, f, Activity, args...)\n\nAuto-differentiate function `f` at arguments `args` using forward mode.\n\n`args` may be numbers, arrays, structs of numbers, structs of arrays and so\non. Enzyme will only differentiate in respect to arguments that are wrapped\nin a [`Duplicated`](@ref) or similar argument. Non-annotated arguments will\nautomatically be treated as [`Const`](@ref). Unlike reverse mode in\n[`autodiff`](@ref), [`Active`](@ref) arguments are not allowed here, since\nall \n\n`Activity` is the Activity of the return value, it may be:\n* `Const` if the return is not to be differentiated with respect to\n* `Duplicated`, if the return is being differentiated with respect to and\n both the original value and the derivative return are desired\n* `DuplicatedNoNeed`, if the return is being differentiated with respect to\n and only the derivative return is desired.\n\nExample returning both original return and derivative:\n\n```jldoctest\na = 4.2\nb = [2.2, 3.3]; ∂f_∂b = zero(b)\nc = 55; d = 9\n\nf(x) = x*x\nres, ∂f_∂x = autodiff(Forward, f, Duplicated, Duplicated(3.14, 1.0))\n\n# output\n\n(9.8596, 6.28)\n```\n\nExample returning just the derivative:\n\n```jldoctest\na = 4.2\nb = [2.2, 3.3]; ∂f_∂b = zero(b)\nc = 55; d = 9\n\nf(x) = x*x\n∂f_∂x = autodiff(Forward, f, DuplicatedNoNeed, Duplicated(3.14, 1.0))\n\n# output\n\n(6.28,)\n```\n\"\"\"\n@inline function autodiff(::ForwardMode, f::F, ::Type{A}, args...) where {F, A<:Annotation}\n args′ = annotate(args...)\n tt′ = Tuple{map(Core.Typeof, args′)...}\n width = Val(same_or_one(args...))\n if A <: Active\n throw(ErrorException(\"Active Returns not allowed in forward mode\"))\n end\n ReturnPrimal = Val(A <: Duplicated || A <: BatchDuplicated)\n thunk = Enzyme.Compiler.thunk(f, #=df=#nothing, A, tt′, #=Mode=# Val(API.DEM_ForwardMode), width,\n #=ModifiedBetween=#Val(false), ReturnPrimal)\n thunk(args′...)\nend\n\n@inline function autodiff(::ForwardMode, dupf::Duplicated{F}, ::Type{A}, args...) where {F, A<:Annotation}\n args′ = annotate(args...)\n tt′ = Tuple{map(Core.Typeof, args′)...}\n width = Val(same_or_one(args...))\n if A <: Active\n throw(ErrorException(\"Active Returns not allowed in forward mode\"))\n end\n ReturnPrimal = Val(A <: Duplicated || A <: BatchDuplicated)\n thunk = Enzyme.Compiler.thunk(#=f=#dupf.val, #=df=#dupf.dval, A, tt′, #=Mode=# Val(API.DEM_ForwardMode), width, #=ModifiedBetween=#Val(false), ReturnPrimal)\n thunk(args′...)\nend\n\n\n# Compat\n@deprecate fwddiff(f::F, ::Type{A}, args...) where {F, A<:Annotation} autodiff(Forward, f, A, args...)\n@deprecate fwddiff(f::F, args...) where {F} autodiff(Forward, f, args...)\n\n# Compat\n@inline autodiff(f::F, ::Type{A}, args...) where {F, A<:Annotation} = autodiff(Reverse, f, A, args...)\n@inline autodiff(f::F, args...) where {F} = autodiff(Reverse, f, args...)\n\n# F as first arg for `do` syntax\n@inline autodiff(dupf::Duplicated{F}, mode::Mode, ::Type{A}, args...) where {F,A<:Annotation} = autodiff(mode, dupf, A, args...)\n@inline autodiff(f::F, mode::Mode, ::Type{A}, args...) where {F,A<:Annotation} = autodiff(mode, f, A, args...)\n@inline autodiff(dupf::Duplicated{F}, mode::Mode, args...) where {F} = autodiff(mode, dupf, args...)\n@inline autodiff(f::F, mode::Mode, args...) where {F} = autodiff(mode, f, args...)\n\n\"\"\"\n autodiff_deferred(f, Activity, args...)\n\nSame as [`autodiff`](@ref) but uses deferred compilation to support usage in GPU\ncode, as well as high-order differentiation.\n\"\"\"\n@inline function autodiff_deferred(f::F, ::Type{A}, args...) where {F, A<:Annotation}\n args′ = annotate(args...)\n tt′ = Tuple{map(Core.Typeof, args′)...}\n width = Val(same_or_one(args...))\n if A isa UnionAll\n tt = Tuple{map(T->eltype(Core.Typeof(T)), args′)...}\n rt = Core.Compiler.return_type(f, tt)\n rt = A{rt}\n else\n @assert A isa DataType\n rt = A\n end\n\n if eltype(rt) == Union{}\n error(\"Return type inferred to be Union{}. Giving up.\")\n end\n\n ReturnPrimal = Val(false)\n ptr = Compiler.deferred_codegen(f, Val(tt′), Val(rt), #=dupClosure=#Val(false), Val(API.DEM_ReverseModeCombined), width, #=ModifiedBetween=#Val(false), ReturnPrimal)\n thunk = Compiler.CombinedAdjointThunk{F, rt, tt′, typeof(width), Nothing, ReturnPrimal}(f, ptr, #=df=#nothing)\n if rt <: Active\n args′ = (args′..., one(eltype(rt)))\n elseif A <: Duplicated || A<: DuplicatedNoNeed || A <: BatchDuplicated || A<: BatchDuplicatedNoNeed\n throw(ErrorException(\"Duplicated Returns not yet handled\"))\n end\n thunk(args′...)\nend\n\n\"\"\"\n autodiff_deferred(f, args...)\n\nLike [`autodiff_deferred`](@ref) but will try to guess the activity of the return value.\n\"\"\"\n@inline function autodiff_deferred(f::F, args...) where {F}\n args′ = annotate(args...)\n tt′ = Tuple{map(Core.Typeof, args′)...}\n tt = Tuple{map(T->eltype(Core.Typeof(T)), args′)...}\n rt = Core.Compiler.return_type(f, tt)\n rt = guess_activity(rt)\n autodiff_deferred(f, rt, args′...) \nend\n\n\"\"\"\n fwddiff_deferred(f, Activity, args...)\n\nSame as `autodiff(::ForwardMode, ...)` but uses deferred compilation to support usage in GPU\ncode, as well as high-order differentiation.\n\"\"\"\n@inline function fwddiff_deferred(f::F, ::Type{A}, args...) where {F, A<:Annotation}\n args′ = annotate(args...)\n tt′ = Tuple{map(Core.Typeof, args′)...}\n width = Val(same_or_one(args...))\n if A isa UnionAll\n tt = Tuple{map(T->eltype(Core.Typeof(T)), args′)...}\n rt = Core.Compiler.return_type(f, tt)\n rt = A{rt}\n else\n @assert A isa DataType\n rt = A\n end\n\n if eltype(rt) == Union{}\n error(\"Return type inferred to be Union{}. Giving up.\")\n end\n\n if A <: Active\n throw(ErrorException(\"Active Returns not allowed in forward mode\"))\n end\n\n ReturnPrimal = Val(A <: Duplicated || A <: BatchDuplicated)\n ptr = Compiler.deferred_codegen(f, Val(tt′), Val(rt), #=dupClosure=#Val(false), Val(API.DEM_ForwardMode), width, #=ModifiedBetween=#Val(false), ReturnPrimal)\n thunk = Compiler.ForwardModeThunk{F, rt, tt′, typeof(width), Nothing, ReturnPrimal}(f, ptr, #=df=#nothing)\n thunk(args′...)\nend\n\n\"\"\"\n fwddiff_deferred(f, args...)\n\nLike [`fwddiff_deferred`](@ref) but will try to guess the activity of the return value.\n\"\"\"\n@inline function fwddiff_deferred(f::F, args...) where {F}\n args′ = annotate(args...)\n tt = Tuple{map(T->eltype(Core.Typeof(T)), args′)...}\n rt = Core.Compiler.return_type(f, tt)\n rt = guess_activity(rt, API.DEM_ForwardMode)\n fwddiff_deferred(f, rt, args′...)\nend\n\n# White lie, should be `Core.LLVMPtr{Cvoid, 0}` but that's not supported by ccallable\nBase.@ccallable function __enzyme_float(x::Ptr{Cvoid})::Cvoid\n return nothing\nend\n\nBase.@ccallable function __enzyme_double(x::Ptr{Cvoid})::Cvoid\n return nothing\nend\n\n@inline function markType(::Type{T}, ptr::Ptr{Cvoid}) where T\n markType(Base.unsafe_convert(Ptr{T}, ptr))\nend\n\n@inline function markType(data::Array{T}) where T\n GC.@preserve data markType(pointer(data))\nend\n\n# TODO(WM): We record the type of a single index here, we could give it a range\n@inline function markType(data::SubArray)\n GC.@preserve data markType(pointer(data))\nend\n\n@inline function markType(data::Ptr{Float32})\n Base.llvmcall((\"declare void @__enzyme_float(i8* nocapture) nounwind define void @c(i64 %q) nounwind alwaysinline { %p = inttoptr i64 %q to i8* call void @__enzyme_float(i8* %p) ret void }\", \"c\"), Cvoid, Tuple{Ptr{Float32}}, data)\n nothing\nend\n\n@inline function markType(data::Ptr{Float64})\n Base.llvmcall((\"declare void @__enzyme_double(i8* nocapture) nounwind define void @c(i64 %q) nounwind alwaysinline { %p = inttoptr i64 %q to i8* call void @__enzyme_double(i8* %p) ret void }\", \"c\"), Cvoid, Tuple{Ptr{Float64}}, data)\n nothing\nend\n\n@inline function onehot(x, start=1, endl=length(x))\n ntuple(Val(endl-start+1)) do i\n Base.@_inline_meta\n res = similar(x)\n for idx in 1:length(x)\n @inbounds res[idx] = (i + start - 1== idx) ? 1.0 : 0.0\n end\n return res\n end\nend\n\n@inline function onehot(x::NTuple{N, T}, start=1, endl=N) where {T, N}\n ntuple(Val(endl-start+1)) do i\n Base.@_inline_meta\n ntuple(N) do idx\n Base.@_inline_meta\n return (i + start - 1 == idx) ? 1.0 : 0.0\n end\n end\nend\n\n\"\"\"\n gradient(::ReverseMode, f, x)\n\nCompute the gradient of an array-input function `f` using reverse mode.\nThis will allocate and return new array with the gradient result.\n\nExample:\n\n```jldoctest\nf(x) = x[1]*x[2]\n\ngrad = gradient(Reverse, f, [2.0, 3.0])\n\n# output\n\n2-element Vector{Float64}:\n 3.0\n 2.0\n```\n\"\"\"\n@inline function gradient(::ReverseMode, f, x)\n dx = zero(x)\n autodiff(Reverse, f, Duplicated(x, dx))\n dx\nend\n\n\n\"\"\"\n gradient!(::ReverseMode, dx, f, x)\n\nCompute the gradient of an array-input function `f` using reverse mode,\nstoring the derivative result in an existing array `dx`.\n\nExample:\n\n```jldoctest\nf(x) = x[1]*x[2]\n\ndx = [0.0, 0.0]\ngradient!(Reverse, dx, f, [2.0, 3.0])\n\n# output\n\n2-element Vector{Float64}:\n 3.0\n 2.0\n```\n\"\"\"\n@inline function gradient!(::ReverseMode, dx, f, x)\n dx .= 0\n autodiff(Reverse, f, Duplicated(x, dx))\n dx\nend\n\n\"\"\"\n gradient(::ForwardMode, f, x; shadow=onehot(x))\n\nCompute the gradient of an array-input function `f` using forward mode. The\noptional keyword argument `shadow` is a vector of one-hot vectors of type `x`\nwhich are used to forward-propagate into the return. For performance reasons,\nthis should be computed once, outside the call to `gradient`, rather than\nwithin this call.\n\nExample:\n\n```jldoctest\nf(x) = x[1]*x[2]\n\ngrad = gradient(Forward, f, [2.0, 3.0])\n\n# output\n\n(3.0, 2.0)\n```\n\"\"\"\n@inline function gradient(::ForwardMode, f, x; shadow=onehot(x))\n only(autodiff(Forward, f, BatchDuplicatedNoNeed, BatchDuplicated(x, shadow)))\nend\n\n@inline function chunkedonehot(x, ::Val{chunk}) where chunk\n sz = length(x)\n num = ((sz + chunk - 1) ÷ chunk)\n ntuple(Val(num)) do i\n Base.@_inline_meta\n onehot(x, (i-1)*chunk+1, i == num ? sz : (i*chunk) )\n end\nend\n\n@inline tupleconcat(x) = x\n@inline tupleconcat(x, y) = (x..., y...)\n@inline tupleconcat(x, y, z...) = (x..., tupleconcat(y, z...)...)\n\n\"\"\"\n gradient(::ForwardMode, f, x, ::Val{chunk}; shadow=onehot(x))\n\nCompute the gradient of an array-input function `f` using vector forward mode.\nLike [`gradient`](@ref), except it uses a chunk size of `chunk` to compute\n`chunk` derivatives in a single call.\n\nExample:\n\n```jldoctest\nf(x) = x[1]*x[2]\n\ngrad = gradient(Forward, f, [2.0, 3.0], Val(2))\n\n# output\n\n(3.0, 2.0)\n```\n\"\"\"\n@inline function gradient(::ForwardMode, f, x, ::Val{chunk}; shadow=chunkedonehot(x, Val(chunk))) where chunk\n tmp = ntuple(length(shadow)) do i\n autodiff(Forward, f, BatchDuplicatedNoNeed, BatchDuplicated(x, shadow[i]))[1]\n end\n tupleconcat(tmp...)\nend\n\n@inline function gradient(::ForwardMode, f, x, ::Val{1}; shadow=onehot(x))\n ntuple(length(shadow)) do i\n autodiff(Forward, f, DuplicatedNoNeed, Duplicated(x, shadow[i]))[1]\n end\nend\n\n\"\"\"\n jacobian(::ForwardMode, f, x; shadow=onehot(x))\n jacobian(::ForwardMode, f, x, ::Val{chunk}; shadow=onehot(x))\n\nCompute the jacobian of an array-input function `f` using (potentially vector)\nforward mode. This is a simple rename of the [`gradient`](@ref) function,\nand all relevant arguments apply here.\n\nExample:\n\n```jldoctest\nf(x) = [x[1]*x[2], x[2]]\n\ngrad = jacobian(Forward, f, [2.0, 3.0])\n\n# output\n\n2×2 Matrix{Float64}:\n 3.0 2.0\n 0.0 1.0\n```\n\"\"\"\n@inline function jacobian(::ForwardMode, args...; kwargs...)\n cols = gradient(Forward, args...; kwargs...)\n reduce(hcat, cols)\nend\n\n\"\"\"\n jacobian(::ReverseMode, f, x, ::Val{num_outs}, ::Val{chunk})\n\nCompute the jacobian of an array-input function `f` using (potentially vector)\nreverse mode. The `chunk` argument denotes the chunk size to use and `num_outs`\ndenotes the number of outputs `f` will return in an array.\n\nExample:\n\n```jldoctest\nf(x) = [x[1]*x[2], x[2]]\n\ngrad = jacobian(Reverse, f, [2.0, 3.0], Val(2))\n\n# output\n\n2×2 Matrix{Float64}:\n 3.0 2.0\n 0.0 1.0\n```\n\"\"\"\n@inline function jacobian(::ReverseMode, f, x, n_outs::Val{n_out_val}, ::Val{chunk}) where {chunk, n_out_val}\n num = ((n_out_val + chunk - 1) ÷ chunk)\n\n tt′ = Tuple{BatchDuplicated{Core.Typeof(x), chunk}}\n tt = Tuple{Core.Typeof(x)}\n rt = Core.Compiler.return_type(f, tt)\n primal, adjoint = Enzyme.Compiler.thunk(f, #=df=#nothing, BatchDuplicatedNoNeed{rt}, tt′, #=Split=# Val(API.DEM_ReverseModeGradient), #=width=#Val(chunk), #=ModifiedBetween=#Val(false))\n \n if num * chunk == n_out_val\n last_size = chunk\n primal2, adjoint2 = primal, adjoint\n else\n last_size = n_out_val - (num-1)*chunk\n tt′ = Tuple{BatchDuplicated{Core.Typeof(x), last_size}}\n primal2, adjoint2 = Enzyme.Compiler.thunk(f, #=df=#nothing, BatchDuplicatedNoNeed{rt}, tt′, #=Split=# Val(API.DEM_ReverseModeGradient), #=width=#Val(last_size), #=ModifiedBetween=#Val(false))\n end\n\n tmp = ntuple(num) do i\n Base.@_inline_meta\n dx = ntuple(i == num ? last_size : chunk) do idx\n Base.@_inline_meta\n zero(x)\n end\n res = (i == num ? primal2 : primal)(BatchDuplicated(x, dx))\n tape = res[1]\n j = 0\n for shadow in res[2]\n j += 1\n @inbounds shadow[(i-1)*chunk+j] += one(eltype(typeof(shadow)))\n end\n (i == num ? adjoint2 : adjoint)(BatchDuplicated(x, dx), tape)\n return dx\n end\n rows = tupleconcat(tmp...)\n mapreduce(LinearAlgebra.adjoint, vcat, rows)\nend\n\n@inline function jacobian(::ReverseMode, f, x, n_outs::Val{n_out_val}, ::Val{1} = Val(1)) where {n_out_val}\n tt′ = Tuple{Duplicated{Core.Typeof(x)}}\n tt = Tuple{Core.Typeof(x)}\n rt = Core.Compiler.return_type(f, tt)\n primal, adjoint = Enzyme.Compiler.thunk(f, #=df=#nothing, DuplicatedNoNeed{rt}, tt′, #=Split=# Val(API.DEM_ReverseModeGradient), #=width=#Val(1), #=ModifiedBetween=#Val(false))\n rows = ntuple(n_outs) do i\n Base.@_inline_meta\n dx = zero(x)\n res = primal(Duplicated(x, dx))\n tape = res[1]\n @inbounds res[2][i] += one(eltype(typeof(res[2])))\n adjoint(Duplicated(x, dx), tape)\n return dx\n end\n mapreduce(LinearAlgebra.adjoint, vcat, rows)\nend\n\n\nend # module\n", "meta": {"hexsha": "965e6f70c984aa87f3e3fc41da40de423f2f161a", "size": 24677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Enzyme.jl", "max_stars_repo_name": "EnzymeAD/Enzyme.jl", "max_stars_repo_head_hexsha": "d48e1f3287a7f062f173a062b246477fe6a2fe3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2022-02-06T21:35:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T21:55:28.000Z", "max_issues_repo_path": "src/Enzyme.jl", "max_issues_repo_name": "EnzymeAD/Enzyme.jl", "max_issues_repo_head_hexsha": "d48e1f3287a7f062f173a062b246477fe6a2fe3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2022-02-07T02:00:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T02:59:31.000Z", "max_forks_repo_path": "src/Enzyme.jl", "max_forks_repo_name": "EnzymeAD/Enzyme.jl", "max_forks_repo_head_hexsha": "d48e1f3287a7f062f173a062b246477fe6a2fe3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-08T22:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T08:17:47.000Z", "avg_line_length": 31.0402515723, "max_line_length": 236, "alphanum_fraction": 0.6473639421, "num_tokens": 7376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23950804663043068}} {"text": "include(\"./load_csv.jl\")\n\n# Specify model parameters and/or initial values to optimize\nfunction get_search_index()::Tuple{Array{Int64,1},Array{Int64,1}}\n # parameters\n search_idx_params::Vector{Int} = [\n C.kf1,\n C.kr1,\n C.kf2,\n C.kr2,\n C.kf3,\n C.kr3,\n C.kf4,\n C.kr4,\n C.kf5,\n C.kr5,\n C.kf6,\n C.kr6,\n C.kf7,\n C.kr7,\n C.kf8,\n C.kr8,\n C.kf9,\n C.kr9,\n C.kf10,\n C.kr10,\n C.kf11,\n C.kr11,\n C.kf12,\n C.kr12,\n C.kf13,\n C.kr13,\n C.kf14,\n C.kr14,\n C.kf15,\n C.kr15,\n C.kf16,\n C.kr16,\n C.kf17,\n C.kr17,\n C.kf18,\n C.kr18,\n C.kf19,\n C.kr19,\n C.kf20,\n C.kr20,\n C.kf21,\n C.kr21,\n C.kf22,\n C.kr22,\n C.kf23,\n C.kr23,\n C.kf24,\n C.kr24,\n C.kf25,\n C.kr25,\n C.kf26,\n C.kr26,\n C.kf27,\n C.kr27,\n C.kf28,\n C.kr28,\n C.kf29,\n C.kr29,\n C.kf30,\n C.kr30,\n C.kf31,\n C.kr31,\n C.kf32,\n C.kr32,\n C.kf33,\n C.kr33,\n C.kf34,\n C.kr34,\n C.kf35,\n C.kr35,\n C.kf36,\n C.kr36,\n C.kf37,\n C.kr37,\n C.kf38,\n C.kr38,\n # C.kf39,\n # C.kr39,\n # C.kf40,\n # C.kr40,\n # C.kf41,\n # C.kr41,\n # C.kf42,\n # C.kr42,\n # C.kf43,\n # C.kr43,\n C.kf44,\n # C.kr44,\n # C.kf45,\n # C.kr45,\n # C.kf46,\n # C.kr46,\n # C.kf47,\n # C.kr47,\n # C.kf48,\n # C.kr48,\n # C.kf49,\n # C.kr49,\n C.kf50,\n C.kr50,\n # C.kf51,\n # C.kr51,\n # C.kf52,\n # C.kr52,\n # C.kf53,\n # C.kr53,\n # C.kf54,\n # C.kr54,\n # C.kf55,\n # C.kr55,\n C.kf56,\n # C.kr56,\n # C.kf57,\n # C.kr57,\n # C.kf58,\n # C.kr58,\n # C.kf59,\n # C.kr59,\n # C.kf60,\n # C.kr60,\n # C.kf61,\n # C.kr61,\n C.kf62,\n C.kr62,\n # C.kf63,\n # C.kr63,\n # C.kf64,\n # C.kr64,\n # C.kf65,\n # C.kr65,\n # C.kf66,\n # C.kr66,\n # C.kf67,\n # C.kr67,\n # C.kf68,\n # C.kr68,\n # C.kf69,\n # C.kr69,\n # C.kf70,\n # C.kr70,\n # C.kf71,\n # C.kr71,\n # C.kf72,\n # C.kr72,\n # C.kf73,\n # C.kr73,\n C.kf74,\n C.kr74,\n # C.kf75,\n # C.kr75,\n # C.kf76,\n # C.kr76,\n # C.kf77,\n # C.kr77,\n # C.kf78,\n # C.kr78,\n # C.kf79,\n # C.kr79,\n # C.kf80,\n # C.kr80,\n # C.kf81,\n # C.kr81,\n # C.kf82,\n # C.kr82,\n # C.kf83,\n # C.kr83,\n # C.kf84,\n # C.kr84,\n # C.kf85,\n # C.kr85,\n C.kf86,\n C.kr86,\n # C.kf87,\n # C.kr87,\n # C.kf88,\n # C.kr88,\n # C.kf89,\n # C.kr89,\n # C.kf90,\n # C.kr90,\n # C.kf91,\n # C.kr91,\n # C.kf92,\n # C.kr92,\n # C.kf93,\n # C.kr93,\n # C.kf94,\n # C.kr94,\n # C.kf95,\n # C.kr95,\n # C.kf96,\n # C.kr96,\n # C.kf97,\n # C.kr97,\n C.kf98,\n # C.kr98,\n # C.kf99,\n # C.kr99,\n # C.kf100,\n # C.kr100,\n # C.kf101,\n # C.kr101,\n # C.kf102,\n # C.kr102,\n # C.kf103,\n # C.kr103,\n # C.kf104,\n # C.kr104,\n # C.kf105,\n # C.kr105,\n # C.kf106,\n # C.kr106,\n # C.kf107,\n # C.kr107,\n # C.kf108,\n # C.kr108,\n # C.kf109,\n # C.kr109,\n C.V110,\n C.K110,\n C.V111,\n C.K111,\n C.V112,\n C.K112,\n C.V113,\n C.K113,\n C.V114,\n C.K114,\n C.V115,\n C.K115,\n C.V116,\n C.K116,\n C.V117,\n C.K117,\n C.V118,\n C.K118,\n C.V119,\n C.K119,\n C.V120,\n C.K120,\n C.V121,\n C.K121,\n C.kf122,\n # C.kr122,\n # C.kf123,\n # C.kr123,\n # C.kf124,\n # C.kr124,\n # C.kf125,\n # C.kr125,\n # C.kf126,\n # C.kr126,\n # C.kf127,\n # C.kr127,\n # C.kf128,\n # C.kr128,\n # C.kf129,\n # C.kr129,\n # C.kf130,\n # C.kr130,\n # C.kf131,\n # C.kr131,\n # C.kf132,\n # C.kr132,\n # C.kf133,\n # C.kr133,\n # C.kf134,\n # C.kr134,\n C.kf135,\n C.kr135,\n # C.kf136,\n # C.kr136,\n # C.kf137,\n # C.kr137,\n # C.kf138,\n # C.kr138,\n # C.kf139,\n # C.kr139,\n # C.kf140,\n # C.kr140,\n # C.kf141,\n # C.kr141,\n # C.kf142,\n # C.kr142,\n # C.kf143,\n # C.kr143,\n # C.kf144,\n # C.kr144,\n # C.kf145,\n # C.kr145,\n # C.kf146,\n # C.kr146,\n # C.kf147,\n # C.kr147,\n C.kf148,\n # C.kr148,\n # C.kf149,\n # C.kr149,\n # C.kf150,\n # C.kr150,\n # C.kf151,\n # C.kr151,\n # C.kf152,\n # C.kr152,\n # C.kf153,\n # C.kr153,\n # C.kf154,\n # C.kr154,\n # C.kf155,\n # C.kr155,\n # C.kf156,\n # C.kr156,\n # C.kf157,\n # C.kr157,\n # C.kf158,\n # C.kr158,\n # C.kf159,\n # C.kr159,\n # C.kf160,\n # C.kr160,\n C.kf161,\n C.kr161,\n # C.kf162,\n # C.kr162,\n # C.kf163,\n # C.kr163,\n # C.kf164,\n # C.kr164,\n # C.kf165,\n # C.kr165,\n # C.kf166,\n # C.kr166,\n # C.kf167,\n # C.kr167,\n # C.kf168,\n # C.kr168,\n # C.kf169,\n # C.kr169,\n # C.kf170,\n # C.kr170,\n # C.kf171,\n # C.kr171,\n # C.kf172,\n # C.kr172,\n # C.kf173,\n # C.kr173,\n C.kf174,\n C.kr174,\n # C.kf175,\n # C.kr175,\n # C.kf176,\n # C.kr176,\n # C.kf177,\n # C.kr177,\n # C.kf178,\n # C.kr178,\n # C.kf179,\n # C.kr179,\n # C.kf180,\n # C.kr180,\n # C.kf181,\n # C.kr181,\n # C.kf182,\n # C.kr182,\n # C.kf183,\n # C.kr183,\n # C.kf184,\n # C.kr184,\n # C.kf185,\n # C.kr185,\n # C.kf186,\n # C.kr186,\n # C.kf187,\n # C.kr187,\n # C.kf188,\n # C.kr188,\n # C.kf189,\n # C.kr189,\n # C.kf190,\n # C.kr190,\n # C.kf191,\n # C.kr191,\n # C.kf192,\n # C.kr192,\n C.kf193,\n # C.kr193,\n # C.kf194,\n # C.kr194,\n # C.kf195,\n # C.kr195,\n # C.kf196,\n # C.kr196,\n # C.kf197,\n # C.kr197,\n # C.kf198,\n # C.kr198,\n # C.kf199,\n # C.kr199,\n # C.kf200,\n # C.kr200,\n # C.kf201,\n # C.kr201,\n # C.kf202,\n # C.kr202,\n # C.kf203,\n # C.kr203,\n # C.kf204,\n # C.kr204,\n # C.kf205,\n # C.kr205,\n # C.kf206,\n # C.kr206,\n # C.kf207,\n # C.kr207,\n # C.kf208,\n # C.kr208,\n # C.kf209,\n # C.kr209,\n # C.kf210,\n # C.kr210,\n # C.kf211,\n # C.kr211,\n C.kf212,\n C.kr212,\n # C.kf213,\n # C.kr213,\n # C.kf214,\n # C.kr214,\n # C.kf215,\n # C.kr215,\n # C.kf216,\n # C.kr216,\n # C.kf217,\n # C.kr217,\n # C.kf218,\n # C.kr218,\n # C.kf219,\n # C.kr219,\n # C.kf220,\n # C.kr220,\n # C.kf221,\n # C.kr221,\n # C.kf222,\n # C.kr222,\n # C.kf223,\n # C.kr223,\n # C.kf224,\n # C.kr224,\n C.kf225,\n C.kr225,\n # C.kf226,\n # C.kr226,\n # C.kf227,\n # C.kr227,\n # C.kf228,\n # C.kr228,\n # C.kf229,\n # C.kr229,\n # C.kf230,\n # C.kr230,\n # C.kf231,\n # C.kr231,\n # C.kf232,\n # C.kr232,\n # C.kf233,\n # C.kr233,\n # C.kf234,\n # C.kr234,\n # C.kf235,\n # C.kr235,\n # C.kf236,\n # C.kr236,\n # C.kf237,\n # C.kr237,\n # C.kf238,\n # C.kr238,\n # C.kf239,\n # C.kr239,\n # C.kf240,\n # C.kr240,\n # C.kf241,\n # C.kr241,\n C.kf242,\n # C.kr242,\n # C.kf243,\n # C.kr243,\n # C.kf244,\n # C.kr244,\n # C.kf245,\n # C.kr245,\n # C.kf246,\n # C.kr246,\n # C.kf247,\n # C.kr247,\n # C.kf248,\n # C.kr248,\n # C.kf249,\n # C.kr249,\n # C.kf250,\n # C.kr250,\n # C.kf251,\n # C.kr251,\n # C.kf252,\n # C.kr252,\n # C.kf253,\n # C.kr253,\n # C.kf254,\n # C.kr254,\n # C.kf255,\n # C.kr255,\n # C.kf256,\n # C.kr256,\n # C.kf257,\n # C.kr257,\n # C.kf258,\n # C.kr258,\n C.kf259,\n C.kr259,\n C.V260,\n C.K260,\n C.V261,\n C.K261,\n C.V262,\n C.K262,\n C.V263,\n C.K263,\n C.V264,\n C.K264,\n C.V265,\n C.K265,\n C.V266,\n C.K266,\n C.kf267,\n C.kf268,\n # C.kf269,\n # C.kf270,\n # C.kf271,\n # C.kf272,\n # C.kf273,\n # C.kf274,\n # C.kf275,\n # C.kf276,\n # C.kf277,\n # C.kf278,\n # C.kf279,\n # C.kf280,\n # C.kf281,\n # C.kf282,\n # C.kf283,\n # C.kf284,\n # C.kf285,\n # C.kf286,\n # C.kf287,\n # C.kf288,\n # C.kf289,\n # C.kf290,\n C.V291,\n C.K291,\n # C.n291,\n C.kf292,\n # C.kr292,\n C.kf293,\n C.kf294,\n C.V295,\n C.K295,\n C.kf296,\n C.kf297,\n C.kf298,\n C.kr298,\n C.kf299,\n C.kr299,\n C.kf300,\n C.kr300,\n C.kf301,\n C.kr301,\n C.kf302,\n C.kr302,\n # C.kf303,\n # C.kr303,\n # C.kf304,\n # C.kr304,\n # C.kf305,\n # C.kr305,\n # C.kf306,\n # C.kr306,\n # C.kf307,\n # C.kr307,\n C.V308,\n C.K308,\n C.V309,\n C.K309,\n C.V310,\n C.K310,\n # C.n310,\n C.KF310,\n # C.nF310,\n C.kf311,\n # C.kr311,\n C.kf312,\n C.kf313,\n C.V314,\n C.K314,\n C.V315,\n C.K315,\n C.V316,\n C.K316,\n C.V317,\n C.K317,\n C.kf318,\n C.kf319,\n #\n C.w_EGFR,\n C.w_ERBB2,\n C.w_ERBB3,\n C.w_ERBB4,\n #\n C.w_GRB2,\n #\n C.w_SHC1,\n C.w_SHC2,\n C.w_SHC3,\n C.w_SHC4,\n #\n C.w_RASA1,\n C.w_RASA2,\n C.w_RASA3,\n #\n C.w_PIK3CA,\n C.w_PIK3CB,\n C.w_PIK3CD,\n C.w_PIK3CG,\n #\n C.w_PTEN,\n #\n C.w_SOS1,\n C.w_SOS2,\n #\n C.w_GAB1,\n #\n C.w_HRAS,\n C.w_KRAS,\n C.w_NRAS,\n #\n C.w_ARAF,\n C.w_BRAF,\n C.w_RAF1,\n #\n C.w_MAP2K1,\n C.w_MAP2K2,\n #\n C.w_MAPK1,\n C.w_MAPK3,\n #\n C.w_AKT1,\n C.w_AKT2,\n #\n C.w_PTPN1,\n #\n C.w_GSK3B,\n #\n C.w_DUSP5,\n C.w_DUSP6,\n C.w_DUSP7,\n #\n C.w_MYC,\n ]\n\n # initial values\n search_idx_initials::Vector{Int} = [\n V.PIP2\n ]\n\n return search_idx_params, search_idx_initials\nend\n\n\nfunction get_search_region()::Matrix{Float64}\n p::Vector{Float64} = param_values()\n u0::Vector{Float64} = initial_values()\n\n search_idx::Tuple{Array{Int64,1},Array{Int64,1}} = get_search_index()\n search_param::Vector{Float64} = init_search_param(search_idx, p, u0)\n\n search_rgn::Matrix{Float64} = zeros(2, length(p) + length(u0))\n\n # Default: 0.1 ~ 10x\n for (i, j) in enumerate(search_idx[1])\n search_rgn[1,j] = 1e-4 # lower bound\n search_rgn[2,j] = 1e+5 # upper bound\n end\n\n # Default: 0.5 ~ 2x\n for (i, j) in enumerate(search_idx[2])\n search_rgn[1,j + length(p)] = search_param[i + length(search_idx[1])] * 1 # lower bound\n search_rgn[2,j + length(p)] = search_param[i + length(search_idx[1])] * 1000 # upper bound\n end\n\n # search_rgn[:, C.param_name] = [lower_bound, upper_bound]\n # search_rgn[:, V.var_name+length(p)] = [lower_bound, upper_bound]\n\n for input_layer in [\n C.kf1,\n C.kr1,\n C.kf2,\n C.kr2,\n C.kf3,\n C.kr3,\n C.kf4,\n C.kr4,\n C.kf5,\n C.kr5,\n C.kf6,\n C.kr6,\n C.kf7,\n C.kr7,\n C.kf8,\n C.kr8,\n C.kf9,\n C.kr9,\n ]\n search_rgn[:, input_layer] = [1e-2, 1e+2]\n end\n\n for receptor_phosphorylation in [\n C.kf10,\n C.kr10,\n C.kf11,\n C.kr11,\n C.kf12,\n C.kr12,\n C.kf13,\n C.kr13,\n C.kf14,\n C.kr14,\n C.kf15,\n C.kr15,\n ]\n search_rgn[:, receptor_phosphorylation] = [1e-2, 1e+2]\n end\n\n for recepotor_adaptor in [\n C.kf16,\n C.kr16,\n C.kf17,\n C.kr17,\n C.kf18,\n C.kr18,\n C.kf19,\n C.kr19,\n C.kf20,\n C.kr20,\n C.kf21,\n C.kr21,\n C.kf22,\n C.kr22,\n C.kf23,\n C.kr23,\n C.kf24,\n C.kr24,\n C.kf25,\n C.kr25,\n C.kf26,\n C.kr26,\n C.kf27,\n C.kr27,\n C.kf28,\n C.kr28,\n C.kf29,\n C.kr29,\n C.kf30,\n C.kr30,\n C.kf31,\n C.kr31,\n C.kf32,\n C.kr32,\n C.kf33,\n C.kr33,\n C.kf34,\n C.kr34,\n C.kf35,\n C.kr35,\n C.kf36,\n C.kr36,\n C.kf37,\n C.kr37,\n ]\n search_rgn[:, recepotor_adaptor] = [1e-4, 1e+2]\n end\n\n for degradation in [\n C.kf267,\n C.kf268,\n C.kf294,\n C.kf296,\n C.kf297,\n C.kf312,\n C.kf318,\n C.kf319,\n ]\n search_rgn[:, degradation] = [1e-4, 1e+0]\n end\n\n for EC50 in [\n C.K110,\n C.K111,\n C.K112,\n C.K113,\n C.K114,\n C.K115,\n C.K116,\n C.K117,\n C.K118,\n C.K119,\n C.K120,\n C.K121,\n C.K260,\n C.K261,\n C.K262,\n C.K263,\n C.K264,\n C.K265,\n C.K266,\n C.K291,\n C.K295,\n C.K308,\n C.K309,\n C.K310,\n C.K314,\n C.K315,\n C.K316,\n C.K317,\n ]\n search_rgn[:, EC50] = [1e+0, 1e+4]\n end\n\n search_rgn[:, C.w_EGFR] = [0.01, 100]\n search_rgn[:, C.w_ERBB2] = [0.01, 100]\n search_rgn[:, C.w_ERBB3] = [0.01, 100]\n search_rgn[:, C.w_ERBB4] = [0.01, 100]\n #\n search_rgn[:, C.w_GRB2] = [0.01, 100]\n #\n search_rgn[:, C.w_SHC1] = [0.01, 100]\n search_rgn[:, C.w_SHC2] = [0.01, 100]\n search_rgn[:, C.w_SHC3] = [0.01, 100]\n search_rgn[:, C.w_SHC4] = [0.01, 100]\n #\n search_rgn[:, C.w_RASA1] = [0.01, 100]\n search_rgn[:, C.w_RASA2] = [0.01, 100]\n search_rgn[:, C.w_RASA3] = [0.01, 100]\n #\n search_rgn[:, C.w_PIK3CA] = [0.01, 100]\n search_rgn[:, C.w_PIK3CB] = [0.01, 100]\n search_rgn[:, C.w_PIK3CD] = [0.01, 100]\n search_rgn[:, C.w_PIK3CG] = [0.01, 100]\n #\n search_rgn[:, C.w_PTEN] = [0.01, 100]\n #\n search_rgn[:, C.w_SOS1] = [0.01, 100]\n search_rgn[:, C.w_SOS2] = [0.01, 100]\n #\n search_rgn[:, C.w_GAB1] = [0.01, 100]\n #\n search_rgn[:, C.w_HRAS] = [0.01, 100]\n search_rgn[:, C.w_KRAS] = [0.01, 100]\n search_rgn[:, C.w_NRAS] = [0.01, 100]\n #\n search_rgn[:, C.w_ARAF] = [0.01, 100]\n search_rgn[:, C.w_BRAF] = [0.01, 100]\n search_rgn[:, C.w_RAF1] = [0.01, 100]\n #\n search_rgn[:, C.w_MAP2K1] = [0.01, 100]\n search_rgn[:, C.w_MAP2K2] = [0.01, 100]\n #\n search_rgn[:, C.w_MAPK1] = [0.01, 100]\n search_rgn[:, C.w_MAPK3] = [0.01, 100]\n #\n search_rgn[:, C.w_AKT1] = [0.01, 100]\n search_rgn[:, C.w_AKT2] = [0.01, 100]\n #\n # search_rgn[:, C.w_RPS6KA1] = [0.01, 100]\n # search_rgn[:, C.w_RPS6KA2] = [0.01, 100]\n # search_rgn[:, C.w_RPS6KA3] = [0.01, 100]\n # search_rgn[:, C.w_RPS6KA6] = [0.01, 100]\n #\n # search_rgn[:, C.w_PPP2CA] = [0.01, 100]\n # search_rgn[:, C.w_PPP2CB] = [0.01, 100]\n #\n search_rgn[:, C.w_PTPN1] = [0.01, 100]\n #\n # search_rgn[:, C.w_CREB1] = [0.01, 100]\n #\n # search_rgn[:, C.w_ELK1] = [0.01, 100]\n #\n search_rgn[:, C.w_GSK3B] = [0.01, 100]\n #\n search_rgn[:, C.w_DUSP5] = [0.01, 100]\n search_rgn[:, C.w_DUSP6] = [0.01, 100]\n search_rgn[:, C.w_DUSP7] = [0.01, 100]\n #\n # search_rgn[:, C.w_FOS] = [0.01, 100]\n #\n search_rgn[:, C.w_MYC] = [0.01, 100]\n \n\n search_rgn = conv_lin2log!(search_rgn, search_idx)\n\n return search_rgn\nend\n\n\nfunction update_param(indiv::Vector{Float64})::Tuple{Array{Float64,1},Array{Float64,1}}\n p::Vector{Float64} = param_values()\n u0::Vector{Float64} = initial_values()\n\n search_idx::Tuple{Array{Int64,1},Array{Int64,1}} = get_search_index()\n\n for (i, j) in enumerate(search_idx[1])\n @inbounds p[j] = indiv[i]\n end\n for (i, j) in enumerate(search_idx[2])\n @inbounds u0[j] = indiv[i + length(search_idx[1])]\n end\n\n (p, u0) = individualize!(p, u0, \"MCF7_BREAST\")\n\n # constraints --------------------------------------------------------------\n p[C.kf39] = p[C.kf38]\n p[C.kr39] = p[C.kr38]\n p[C.kf40] = p[C.kf38]\n p[C.kr40] = p[C.kr38]\n p[C.kf41] = p[C.kf38]\n p[C.kr41] = p[C.kr38]\n p[C.kf42] = p[C.kf38]\n p[C.kr42] = p[C.kr38]\n p[C.kf43] = p[C.kf38]\n p[C.kr43] = p[C.kr38]\n p[C.kf45] = p[C.kf44]\n p[C.kr45] = p[C.kr44]\n p[C.kf46] = p[C.kf44]\n p[C.kr46] = p[C.kr44]\n p[C.kf47] = p[C.kf44]\n p[C.kr47] = p[C.kr44]\n p[C.kf48] = p[C.kf44]\n p[C.kr48] = p[C.kr44]\n p[C.kf49] = p[C.kf44]\n p[C.kr49] = p[C.kr44]\n p[C.kf51] = p[C.kf50]\n p[C.kr51] = p[C.kr50]\n p[C.kf52] = p[C.kf50]\n p[C.kr52] = p[C.kr50]\n p[C.kf53] = p[C.kf50]\n p[C.kr53] = p[C.kr50]\n p[C.kf54] = p[C.kf50]\n p[C.kr54] = p[C.kr50]\n p[C.kf55] = p[C.kf50]\n p[C.kr55] = p[C.kr50]\n p[C.kf57] = p[C.kf56]\n p[C.kr57] = p[C.kr56]\n p[C.kf58] = p[C.kf56]\n p[C.kr58] = p[C.kr56]\n p[C.kf59] = p[C.kf56]\n p[C.kr59] = p[C.kr56]\n p[C.kf60] = p[C.kf56]\n p[C.kr60] = p[C.kr56]\n p[C.kf61] = p[C.kf56]\n p[C.kr61] = p[C.kr56]\n p[C.kf63] = p[C.kf62]\n p[C.kr63] = p[C.kr62]\n p[C.kf64] = p[C.kf62]\n p[C.kr64] = p[C.kr62]\n p[C.kf65] = p[C.kf62]\n p[C.kr65] = p[C.kr62]\n p[C.kf66] = p[C.kf62]\n p[C.kr66] = p[C.kr62]\n p[C.kf67] = p[C.kf62]\n p[C.kr67] = p[C.kr62]\n p[C.kf68] = p[C.kf62]\n p[C.kr68] = p[C.kr62]\n p[C.kf69] = p[C.kf62]\n p[C.kr69] = p[C.kr62]\n p[C.kf70] = p[C.kf62]\n p[C.kr70] = p[C.kr62]\n p[C.kf71] = p[C.kf62]\n p[C.kr71] = p[C.kr62]\n p[C.kf72] = p[C.kf62]\n p[C.kr72] = p[C.kr62]\n p[C.kf73] = p[C.kf62]\n p[C.kr73] = p[C.kr62]\n p[C.kf75] = p[C.kf74]\n p[C.kr75] = p[C.kr74]\n p[C.kf76] = p[C.kf74]\n p[C.kr76] = p[C.kr74]\n p[C.kf77] = p[C.kf74]\n p[C.kr77] = p[C.kr74]\n p[C.kf78] = p[C.kf74]\n p[C.kr78] = p[C.kr74]\n p[C.kf79] = p[C.kf74]\n p[C.kr79] = p[C.kr74]\n p[C.kf80] = p[C.kf74]\n p[C.kr80] = p[C.kr74]\n p[C.kf81] = p[C.kf74]\n p[C.kr81] = p[C.kr74]\n p[C.kf82] = p[C.kf74]\n p[C.kr82] = p[C.kr74]\n p[C.kf83] = p[C.kf74]\n p[C.kr83] = p[C.kr74]\n p[C.kf84] = p[C.kf74]\n p[C.kr84] = p[C.kr74]\n p[C.kf85] = p[C.kf74]\n p[C.kr85] = p[C.kr74]\n p[C.kf87] = p[C.kf86]\n p[C.kr87] = p[C.kr86]\n p[C.kf88] = p[C.kf86]\n p[C.kr88] = p[C.kr86]\n p[C.kf89] = p[C.kf86]\n p[C.kr89] = p[C.kr86]\n p[C.kf90] = p[C.kf86]\n p[C.kr90] = p[C.kr86]\n p[C.kf91] = p[C.kf86]\n p[C.kr91] = p[C.kr86]\n p[C.kf92] = p[C.kf86]\n p[C.kr92] = p[C.kr86]\n p[C.kf93] = p[C.kf86]\n p[C.kr93] = p[C.kr86]\n p[C.kf94] = p[C.kf86]\n p[C.kr94] = p[C.kr86]\n p[C.kf95] = p[C.kf86]\n p[C.kr95] = p[C.kr86]\n p[C.kf96] = p[C.kf86]\n p[C.kr96] = p[C.kr86]\n p[C.kf97] = p[C.kf86]\n p[C.kr97] = p[C.kr86]\n p[C.kf99] = p[C.kf98]\n p[C.kr99] = p[C.kr98]\n p[C.kf100] = p[C.kf98]\n p[C.kr100] = p[C.kr98]\n p[C.kf101] = p[C.kf98]\n p[C.kr101] = p[C.kr98]\n p[C.kf102] = p[C.kf98]\n p[C.kr102] = p[C.kr98]\n p[C.kf103] = p[C.kf98]\n p[C.kr103] = p[C.kr98]\n p[C.kf104] = p[C.kf98]\n p[C.kr104] = p[C.kr98]\n p[C.kf105] = p[C.kf98]\n p[C.kr105] = p[C.kr98]\n p[C.kf106] = p[C.kf98]\n p[C.kr106] = p[C.kr98]\n p[C.kf107] = p[C.kf98]\n p[C.kr107] = p[C.kr98]\n p[C.kf108] = p[C.kf98]\n p[C.kr108] = p[C.kr98]\n p[C.kf109] = p[C.kf98]\n p[C.kr109] = p[C.kr98]\n p[C.kf123] = p[C.kf122]\n p[C.kr123] = p[C.kr122]\n p[C.kf124] = p[C.kf122]\n p[C.kr124] = p[C.kr122]\n p[C.kf125] = p[C.kf122]\n p[C.kr125] = p[C.kr122]\n p[C.kf126] = p[C.kf122]\n p[C.kr126] = p[C.kr122]\n p[C.kf127] = p[C.kf122]\n p[C.kr127] = p[C.kr122]\n p[C.kf128] = p[C.kf122]\n p[C.kr128] = p[C.kr122]\n p[C.kf129] = p[C.kf122]\n p[C.kr129] = p[C.kr122]\n p[C.kf130] = p[C.kf122]\n p[C.kr130] = p[C.kr122]\n p[C.kf131] = p[C.kf122]\n p[C.kr131] = p[C.kr122]\n p[C.kf132] = p[C.kf122]\n p[C.kr132] = p[C.kr122]\n p[C.kf133] = p[C.kf122]\n p[C.kr133] = p[C.kr122]\n p[C.kf134] = p[C.kf122]\n p[C.kr134] = p[C.kr122]\n p[C.kf136] = p[C.kf135]\n p[C.kr136] = p[C.kr135]\n p[C.kf137] = p[C.kf135]\n p[C.kr137] = p[C.kr135]\n p[C.kf138] = p[C.kf135]\n p[C.kr138] = p[C.kr135]\n p[C.kf139] = p[C.kf135]\n p[C.kr139] = p[C.kr135]\n p[C.kf140] = p[C.kf135]\n p[C.kr140] = p[C.kr135]\n p[C.kf141] = p[C.kf135]\n p[C.kr141] = p[C.kr135]\n p[C.kf142] = p[C.kf135]\n p[C.kr142] = p[C.kr135]\n p[C.kf143] = p[C.kf135]\n p[C.kr143] = p[C.kr135]\n p[C.kf144] = p[C.kf135]\n p[C.kr144] = p[C.kr135]\n p[C.kf145] = p[C.kf135]\n p[C.kr145] = p[C.kr135]\n p[C.kf146] = p[C.kf135]\n p[C.kr146] = p[C.kr135]\n p[C.kf147] = p[C.kf135]\n p[C.kr147] = p[C.kr135]\n p[C.kf149] = p[C.kf148]\n p[C.kr149] = p[C.kr148]\n p[C.kf150] = p[C.kf148]\n p[C.kr150] = p[C.kr148]\n p[C.kf151] = p[C.kf148]\n p[C.kr151] = p[C.kr148]\n p[C.kf152] = p[C.kf148]\n p[C.kr152] = p[C.kr148]\n p[C.kf153] = p[C.kf148]\n p[C.kr153] = p[C.kr148]\n p[C.kf154] = p[C.kf148]\n p[C.kr154] = p[C.kr148]\n p[C.kf155] = p[C.kf148]\n p[C.kr155] = p[C.kr148]\n p[C.kf156] = p[C.kf148]\n p[C.kr156] = p[C.kr148]\n p[C.kf157] = p[C.kf148]\n p[C.kr157] = p[C.kr148]\n p[C.kf158] = p[C.kf148]\n p[C.kr158] = p[C.kr148]\n p[C.kf159] = p[C.kf148]\n p[C.kr159] = p[C.kr148]\n p[C.kf160] = p[C.kf148]\n p[C.kr160] = p[C.kr148]\n p[C.kf162] = p[C.kf161]\n p[C.kr162] = p[C.kr161]\n p[C.kf163] = p[C.kf161]\n p[C.kr163] = p[C.kr161]\n p[C.kf164] = p[C.kf161]\n p[C.kr164] = p[C.kr161]\n p[C.kf165] = p[C.kf161]\n p[C.kr165] = p[C.kr161]\n p[C.kf166] = p[C.kf161]\n p[C.kr166] = p[C.kr161]\n p[C.kf167] = p[C.kf161]\n p[C.kr167] = p[C.kr161]\n p[C.kf168] = p[C.kf161]\n p[C.kr168] = p[C.kr161]\n p[C.kf169] = p[C.kf161]\n p[C.kr169] = p[C.kr161]\n p[C.kf170] = p[C.kf161]\n p[C.kr170] = p[C.kr161]\n p[C.kf171] = p[C.kf161]\n p[C.kr171] = p[C.kr161]\n p[C.kf172] = p[C.kf161]\n p[C.kr172] = p[C.kr161]\n p[C.kf173] = p[C.kf161]\n p[C.kr173] = p[C.kr161]\n p[C.kf175] = p[C.kf174]\n p[C.kr175] = p[C.kr174]\n p[C.kf176] = p[C.kf174]\n p[C.kr176] = p[C.kr174]\n p[C.kf177] = p[C.kf174]\n p[C.kr177] = p[C.kr174]\n p[C.kf178] = p[C.kf174]\n p[C.kr178] = p[C.kr174]\n p[C.kf179] = p[C.kf174]\n p[C.kr179] = p[C.kr174]\n p[C.kf180] = p[C.kf174]\n p[C.kr180] = p[C.kr174]\n p[C.kf181] = p[C.kf174]\n p[C.kr181] = p[C.kr174]\n p[C.kf182] = p[C.kf174]\n p[C.kr182] = p[C.kr174]\n p[C.kf183] = p[C.kf174]\n p[C.kr183] = p[C.kr174]\n p[C.kf184] = p[C.kf174]\n p[C.kr184] = p[C.kr174]\n p[C.kf185] = p[C.kf174]\n p[C.kr185] = p[C.kr174]\n p[C.kf186] = p[C.kf174]\n p[C.kr186] = p[C.kr174]\n p[C.kf187] = p[C.kf174]\n p[C.kr187] = p[C.kr174]\n p[C.kf188] = p[C.kf174]\n p[C.kr188] = p[C.kr174]\n p[C.kf189] = p[C.kf174]\n p[C.kr189] = p[C.kr174]\n p[C.kf190] = p[C.kf174]\n p[C.kr190] = p[C.kr174]\n p[C.kf191] = p[C.kf174]\n p[C.kr191] = p[C.kr174]\n p[C.kf192] = p[C.kf174]\n p[C.kr192] = p[C.kr174]\n p[C.kf194] = p[C.kf193]\n p[C.kr194] = p[C.kr193]\n p[C.kf195] = p[C.kf193]\n p[C.kr195] = p[C.kr193]\n p[C.kf196] = p[C.kf193]\n p[C.kr196] = p[C.kr193]\n p[C.kf197] = p[C.kf193]\n p[C.kr197] = p[C.kr193]\n p[C.kf198] = p[C.kf193]\n p[C.kr198] = p[C.kr193]\n p[C.kf199] = p[C.kf193]\n p[C.kr199] = p[C.kr193]\n p[C.kf200] = p[C.kf193]\n p[C.kr200] = p[C.kr193]\n p[C.kf201] = p[C.kf193]\n p[C.kr201] = p[C.kr193]\n p[C.kf202] = p[C.kf193]\n p[C.kr202] = p[C.kr193]\n p[C.kf203] = p[C.kf193]\n p[C.kr203] = p[C.kr193]\n p[C.kf204] = p[C.kf193]\n p[C.kr204] = p[C.kr193]\n p[C.kf205] = p[C.kf193]\n p[C.kr205] = p[C.kr193]\n p[C.kf206] = p[C.kf193]\n p[C.kr206] = p[C.kr193]\n p[C.kf207] = p[C.kf193]\n p[C.kr207] = p[C.kr193]\n p[C.kf208] = p[C.kf193]\n p[C.kr208] = p[C.kr193]\n p[C.kf209] = p[C.kf193]\n p[C.kr209] = p[C.kr193]\n p[C.kf210] = p[C.kf193]\n p[C.kr210] = p[C.kr193]\n p[C.kf211] = p[C.kf193]\n p[C.kr211] = p[C.kr193]\n p[C.kf213] = p[C.kf212]\n p[C.kr213] = p[C.kr212]\n p[C.kf214] = p[C.kf212]\n p[C.kr214] = p[C.kr212]\n p[C.kf215] = p[C.kf212]\n p[C.kr215] = p[C.kr212]\n p[C.kf216] = p[C.kf212]\n p[C.kr216] = p[C.kr212]\n p[C.kf217] = p[C.kf212]\n p[C.kr217] = p[C.kr212]\n p[C.kf218] = p[C.kf212]\n p[C.kr218] = p[C.kr212]\n p[C.kf219] = p[C.kf212]\n p[C.kr219] = p[C.kr212]\n p[C.kf220] = p[C.kf212]\n p[C.kr220] = p[C.kr212]\n p[C.kf221] = p[C.kf212]\n p[C.kr221] = p[C.kr212]\n p[C.kf222] = p[C.kf212]\n p[C.kr222] = p[C.kr212]\n p[C.kf223] = p[C.kf212]\n p[C.kr223] = p[C.kr212]\n p[C.kf224] = p[C.kf212]\n p[C.kr224] = p[C.kr212]\n p[C.kf226] = p[C.kf225]\n p[C.kr226] = p[C.kr225]\n p[C.kf227] = p[C.kf225]\n p[C.kr227] = p[C.kr225]\n p[C.kf228] = p[C.kf225]\n p[C.kr228] = p[C.kr225]\n p[C.kf229] = p[C.kf225]\n p[C.kr229] = p[C.kr225]\n p[C.kf230] = p[C.kf225]\n p[C.kr230] = p[C.kr225]\n p[C.kf231] = p[C.kf225]\n p[C.kr231] = p[C.kr225]\n p[C.kf232] = p[C.kf225]\n p[C.kr232] = p[C.kr225]\n p[C.kf233] = p[C.kf225]\n p[C.kr233] = p[C.kr225]\n p[C.kf234] = p[C.kf225]\n p[C.kr234] = p[C.kr225]\n p[C.kf235] = p[C.kf225]\n p[C.kr235] = p[C.kr225]\n p[C.kf236] = p[C.kf225]\n p[C.kr236] = p[C.kr225]\n p[C.kf237] = p[C.kf225]\n p[C.kr237] = p[C.kr225]\n p[C.kf238] = p[C.kf225]\n p[C.kr238] = p[C.kr225]\n p[C.kf239] = p[C.kf225]\n p[C.kr239] = p[C.kr225]\n p[C.kf240] = p[C.kf225]\n p[C.kr240] = p[C.kr225]\n p[C.kf241] = p[C.kf225]\n p[C.kr241] = p[C.kr225]\n p[C.kf243] = p[C.kf242]\n p[C.kr243] = p[C.kr242]\n p[C.kf244] = p[C.kf242]\n p[C.kr244] = p[C.kr242]\n p[C.kf245] = p[C.kf242]\n p[C.kr245] = p[C.kr242]\n p[C.kf246] = p[C.kf242]\n p[C.kr246] = p[C.kr242]\n p[C.kf247] = p[C.kf242]\n p[C.kr247] = p[C.kr242]\n p[C.kf248] = p[C.kf242]\n p[C.kr248] = p[C.kr242]\n p[C.kf249] = p[C.kf242]\n p[C.kr249] = p[C.kr242]\n p[C.kf250] = p[C.kf242]\n p[C.kr250] = p[C.kr242]\n p[C.kf251] = p[C.kf242]\n p[C.kr251] = p[C.kr242]\n p[C.kf252] = p[C.kf242]\n p[C.kr252] = p[C.kr242]\n p[C.kf253] = p[C.kf242]\n p[C.kr253] = p[C.kr242]\n p[C.kf254] = p[C.kf242]\n p[C.kr254] = p[C.kr242]\n p[C.kf255] = p[C.kf242]\n p[C.kr255] = p[C.kr242]\n p[C.kf256] = p[C.kf242]\n p[C.kr256] = p[C.kr242]\n p[C.kf257] = p[C.kf242]\n p[C.kr257] = p[C.kr242]\n p[C.kf258] = p[C.kf242]\n p[C.kr258] = p[C.kr242]\n p[C.kf269] = p[C.kf268]\n p[C.kf270] = p[C.kf268]\n p[C.kf271] = p[C.kf268]\n p[C.kf272] = p[C.kf268]\n p[C.kf273] = p[C.kf268]\n p[C.kf274] = p[C.kf268]\n p[C.kf275] = p[C.kf268]\n p[C.kf276] = p[C.kf268]\n p[C.kf277] = p[C.kf268]\n p[C.kf278] = p[C.kf268]\n p[C.kf279] = p[C.kf268]\n p[C.kf280] = p[C.kf268]\n p[C.kf281] = p[C.kf268]\n p[C.kf282] = p[C.kf268]\n p[C.kf283] = p[C.kf268]\n p[C.kf284] = p[C.kf268]\n p[C.kf285] = p[C.kf268]\n p[C.kf286] = p[C.kf268]\n p[C.kf287] = p[C.kf268]\n p[C.kf288] = p[C.kf268]\n p[C.kf289] = p[C.kf268]\n p[C.kf290] = p[C.kf268]\n p[C.kf303] = p[C.kf298]\n p[C.kr303] = p[C.kr298]\n p[C.kf304] = p[C.kf299]\n p[C.kr304] = p[C.kr299]\n p[C.kf305] = p[C.kf300]\n p[C.kr305] = p[C.kr300]\n p[C.kf306] = p[C.kf301]\n p[C.kr306] = p[C.kr301]\n p[C.kf307] = p[C.kf302]\n p[C.kr307] = p[C.kr302]\n # --------------------------------------------------------------------------\n\n return p, u0\nend\n\n\nfunction decode_gene2val(indiv_gene::Vector{Float64})::Vector{Float64}\n search_rgn::Matrix{Float64} = get_search_region()\n indiv::Vector{Float64} = zeros(length(indiv_gene))\n\n for i in eachindex(indiv_gene)\n indiv[i] = 10^(\n indiv_gene[i] * (\n search_rgn[2,i] - search_rgn[1,i]\n ) + search_rgn[1,i]\n )\n end\n\n return round.(indiv, sigdigits=7)\nend\n\n\nfunction encode_val2gene(indiv::Vector{Float64})\n search_rgn::Matrix{Float64} = get_search_region()\n indiv_gene::Vector{Float64} = zeros(length(indiv))\n\n for i in eachindex(indiv)\n indiv_gene[i] = (\n log10(indiv[i]) - search_rgn[1,i]\n ) / (\n search_rgn[2,i] - search_rgn[1,i]\n )\n end\n\n return indiv_gene\nend\n\n\nfunction encode_bestIndivVal2randGene(\n idx::Int64,\n best_indiv::Vector{Float64},\n p0_bounds::Vector{Float64})::Float64\n search_rgn::Matrix{Float64} = get_search_region()\n rand_gene::Float64 = (\n log10(\n best_indiv[idx] * 10^(\n rand() * log10(p0_bounds[2] / p0_bounds[1]) + log10(p0_bounds[1])\n )\n ) - search_rgn[1,idx]\n ) / (\n search_rgn[2,idx] - search_rgn[1,idx]\n )\n return rand_gene\nend\n\n\nfunction init_search_param(\n search_idx::Tuple{Array{Int64,1},Array{Int64,1}},\n p::Vector{Float64},\n u0::Vector{Float64})::Vector{Float64}\n duplicate::Vector{String} = []\n if length(search_idx[1]) != length(unique(search_idx[1]))\n for idx in findall([count(x -> x == i, search_idx[1])\n for i in unique(search_idx[1])] .!= 1)\n push!(duplicate, C.NAMES[search_idx[1][idx]])\n end\n error(\n \"Duplicate parameters (C.): $duplicate\"\n )\n elseif length(search_idx[2]) != length(unique(search_idx[2]))\n for idx in findall([count(x -> x == i, search_idx[2])\n for i in unique(search_idx[2])] .!= 1)\n push!(duplicate, V.NAMES[search_idx[2][idx]])\n end\n error(\n \"Duplicate species (V.): $duplicate\"\n )\n end\n search_param = zeros(\n length(search_idx[1]) + length(search_idx[2])\n )\n for (i, j) in enumerate(search_idx[1])\n @inbounds search_param[i] = p[j]\n end\n for (i, j) in enumerate(search_idx[2])\n @inbounds search_param[i + length(search_idx[1])] = u0[j]\n end\n\n if any(x -> x == 0.0, search_param)\n msg::String = \"search_param must not contain zero.\"\n for idx in search_idx[1]\n if p[idx] == 0.0\n error(\n @sprintf(\n \"`C.%s` in search_idx_params: \", C.NAMES[idx]\n ) * msg\n )\n end\n end\n for idx in search_idx[2]\n if u0[idx] == 0.0\n error(\n @sprintf(\n \"`V.%s` in search_idx_initials: \", V.NAMES[idx]\n ) * msg\n )\n end\n end\n end\n\n return search_param\nend\n\n\nfunction conv_lin2log!(\n search_rgn::Matrix{Float64},\n search_idx::Tuple{Array{Int64,1},Array{Int64,1}})::Matrix{Float64}\n for i = 1:size(search_rgn, 2)\n if minimum(search_rgn[:,i]) < 0.0\n msg = \"search_rgn[lower_bound,upper_bound] must be positive.\\n\"\n if i <= C.NUM\n error(@sprintf(\"`C.%s` \", C.NAMES[i]) * msg)\n else\n error(@sprintf(\"`V.%s` \", V.NAMES[i - C.NUM]) * msg)\n end\n elseif minimum(search_rgn[:,i]) == 0.0 && maximum(search_rgn[:,i]) != 0.0\n msg = \"lower_bound must be larger than 0.\\n\"\n if i <= C.NUM\n error(@sprintf(\"`C.%s` \", C.NAMES[i]) * msg)\n else\n error(@sprintf(\"`V.%s` \", V.NAMES[i - C.NUM]) * msg)\n end\n elseif search_rgn[2,i] - search_rgn[1,i] < 0.0\n msg = \"lower_bound must be smaller than upper_bound.\\n\"\n if i <= C.NUM\n error(@sprintf(\"`C.%s` \", C.NAMES[i]) * msg)\n else\n error(@sprintf(\"`V.%s` \", V.NAMES[i - C.NUM]) * msg)\n end\n end\n end\n\n nonzero_idx::Vector{Int} = []\n for i = 1:size(search_rgn, 2)\n if search_rgn[:,i] != [0.0,0.0]\n push!(nonzero_idx, i)\n end\n end\n difference::Vector{Int} = collect(\n symdiff(\n Set(nonzero_idx),\n Set(append!(search_idx[1], C.NUM .+ search_idx[2]))\n )\n )\n if length(difference) > 0\n for idx in difference\n if idx <= C.NUM\n println(@sprintf(\"`C.%s`\", C.NAMES[Int(idx)]))\n else\n println(@sprintf(\"`V.%s`\", V.NAMES[Int(idx) - C.NUM]))\n end\n end\n error(\n \"Set these search_params in both search_idx and search_rgn.\"\n )\n end\n\n search_rgn = search_rgn[:,nonzero_idx]\n\n return log10.(search_rgn)\nend", "meta": {"hexsha": "3507709e97089f81ef17c08c6ee3347a0e16c8f4", "size": 34697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "training/erbb_network_jl/set_search_param.jl", "max_stars_repo_name": "pasmopy/breast_cancer", "max_stars_repo_head_hexsha": "ec25b16844d7321ca00c7cbbd8c49c314e6da13b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-10-02T03:48:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T04:20:46.000Z", "max_issues_repo_path": "training/erbb_network_jl/set_search_param.jl", "max_issues_repo_name": "pasmopy/breast_cancer", "max_issues_repo_head_hexsha": "ec25b16844d7321ca00c7cbbd8c49c314e6da13b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-18T13:53:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T13:53:18.000Z", "max_forks_repo_path": "training/erbb_network_jl/set_search_param.jl", "max_forks_repo_name": "pasmopy/breast_cancer", "max_forks_repo_head_hexsha": "ec25b16844d7321ca00c7cbbd8c49c314e6da13b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8269736842, "max_line_length": 99, "alphanum_fraction": 0.4317952561, "num_tokens": 13281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2392746666303752}} {"text": "export HCatMatrix\n\nimmutable HCatMatrix{T,S<:AbstractMatrix,V<:AbstractMatrix} <:AbstractMatrix{T}\n left::S\n right::V\nend\n\nfunction HCatMatrix(left::AbstractMatrix, right::AbstractMatrix)\n size(left, 1) == size(right, 1) ||\n error(DimensionMismatch(\"left and right must have same first dimension\"))\n HCatMatrix{Base.promote_eltype(left, right),typeof(left),typeof(right)}(left, right)\nend\n\nBase.size(A::HCatMatrix) = (size(A.left, 1), size(A.left, 2)+size(A.right, 2))\nBase.getindex(X::HCatMatrix, i1::Integer) =\n i1 <= length(X.left) ? X.left[i1] : X.right[i1-length(X.left)]\nBase.getindex(X::HCatMatrix, i1::Integer, i2::Integer) =\n i2 <= size(X.left, 2) ? X.left[i1, i2] : X.right[i1, i2-size(X.left, 2)]\n\nfunction Base.A_mul_B!(out::DenseVector, A::HCatMatrix, b::DenseVector)\n size(A, 1) == length(out) && size(A, 2) == length(b) ||\n throw(DimensionMismatch(\"A has size $(size(A)), b has length $(length(b)), C has length $(length(out))\"))\n b1 = sub(b, 1:size(A.left, 2))\n b2 = sub(b, size(A.left, 2)+1:size(A.left, 2)+size(A.right, 2))\n if isa(A.left, DenseMatrix) && eltype(A.left) <: Base.LinAlg.BlasFloat\n A_mul_B!(out, A.right, b2)\n BLAS.gemv!('N', 1.0, A.left, b1, 1.0, out)\n else\n A_mul_B!(out, A.left, b1)\n broadcast!(+, out, out, A.right*b2)\n end\n out\nend\n\nfor fn in (:Ac_mul_B, :At_mul_B)\n fn! = symbol(string(fn, '!'))\n @eval begin\n function Base.$fn!(out::DenseMatrix, A::HCatMatrix, B::HCatMatrix)\n size(out, 1) == size(A, 2) && size(A, 1) == size(B, 1) && size(out, 2) == size(B, 2) ||\n throw(DimensionMismatch(\"A has size $(size(A)), B has size $(size(B)), C has size $(size(out))\"))\n A1 = A.left\n A2 = A.right\n B1 = B.left\n B2 = B.right\n $fn!(sub(out, 1:size(A1, 2), 1:size(B1, 2)), A1, B1)\n A1B2 = sub(out, 1:size(A1, 2), size(B1, 2)+1:size(B1, 2)+size(B2, 2))\n A2B1 = sub(out, size(A1, 2)+1:size(A1, 2)+size(A2, 2), 1:size(B1, 2))\n $fn!(A1B2, A1, B2)\n if A === B\n ctranspose!(A2B1, A1B2)\n else\n $fn!(A2B1, A2, B1)\n end\n $fn!(sub(out, size(A1, 2)+1:size(A1, 2)+size(A2, 2),\n size(B1, 2)+1:size(B1, 2)+size(B2, 2)), A2, B2)\n out\n end\n\n function Base.$fn!(out::DenseVector, A::HCatMatrix, b::DenseVector)\n length(out) == size(A, 2) && size(A, 1) == size(b, 1) ||\n throw(DimensionMismatch(\"A has size $(size(A)), b has length $(length(b)), C has size $(size(out))\"))\n A1 = A.left\n A2 = A.right\n $fn!(sub(out, 1:size(A1, 2)), A.left, b)\n $fn!(sub(out, size(A1, 2)+1:size(A1, 2)+size(A2, 2)), A.right, b)\n out\n end\n\n function Base.$fn!(out::DenseMatrix, A::HCatMatrix, B::DenseMatrix)\n size(out, 1) == size(A, 2) && size(A, 1) == size(B, 1) && size(out, 2) == size(B, 2) ||\n throw(DimensionMismatch(\"A has size $(size(A)), B has size $(size(B)), C has size $(size(out))\"))\n A1 = A.left\n A2 = A.right\n $fn!(sub(out, 1:size(A1, 2), 1:size(B, 2)), A.left, B)\n $fn!(sub(out, size(A1, 2)+1:size(A1, 2)+size(A2, 2), 1:size(B, 2)), A.right, B)\n out\n end\n\n Base.$fn(X::HCatMatrix, Y::Union{HCatMatrix, DenseMatrix}) =\n $fn!(Array(promote_type(eltype(X), eltype(Y)), size(X, 2), size(Y, 2)), X, Y)\n Base.$fn(X::HCatMatrix, Y::DenseVector) =\n $fn!(Array(promote_type(eltype(X), eltype(Y)), size(X, 2)), X, Y)\n end\nend\n\nfunction Base.scale!(out::HCatMatrix, s::DenseVector, X::HCatMatrix)\n scale!(out.left, s, X.left)\n scale!(out.right, s, X.right)\n out\nend\n\nBase.copy{T,S,V}(X::HCatMatrix{T,S,V}) = HCatMatrix{T,S,V}(copy(X.left), copy(X.right))\n\nfunction weightmul!(out::AbstractMatrix, X::HCatMatrix, w::AbstractVector)\n X1 = X.left\n X2 = X.right\n length(w) == size(X, 1) || throw(DimensionMismatch(\"X has size $(size(X)) but w has length $(length(w))\"))\n size(out, 1) == size(out, 2) == size(X, 2) ||\n throw(DimensionMismatch(\"X has $(size(X, 2)) columns but output has size $(size(out))\"))\n weightmul!(sub(out, 1:size(X1, 2), 1:size(X1, 2)), X1, w)\n blk = sub(out, 1:size(X1, 2), size(X1, 2)+1:size(X1, 2)+size(X2, 2))\n Ac_mul_B!(blk, X1, scale(w, X2))\n ctranspose!(sub(out, size(X1, 2)+1:size(X1, 2)+size(X2, 2), 1:size(X1, 2)), blk)\n weightmul!(sub(out, size(X1, 2)+1:size(X1, 2)+size(X2, 2),\n size(X1, 2)+1:size(X1, 2)+size(X2, 2)), X2, w)\n out\nend\n", "meta": {"hexsha": "2cb640138669878c04f0565b7f60a60110a70ed4", "size": 4682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HCatMatrix.jl", "max_stars_repo_name": "simonster/SpikeGLM.jl", "max_stars_repo_head_hexsha": "bfee0f2cb3650fd8fb906cd8e1b02a4507ba7c6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-01T21:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-03T12:13:09.000Z", "max_issues_repo_path": "src/HCatMatrix.jl", "max_issues_repo_name": "simonster/SpikeGLM.jl", "max_issues_repo_head_hexsha": "bfee0f2cb3650fd8fb906cd8e1b02a4507ba7c6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HCatMatrix.jl", "max_forks_repo_name": "simonster/SpikeGLM.jl", "max_forks_repo_head_hexsha": "bfee0f2cb3650fd8fb906cd8e1b02a4507ba7c6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3518518519, "max_line_length": 117, "alphanum_fraction": 0.5422896198, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.23927465983345292}} {"text": "using Pkg; Pkg.activate(pwd())\r\nusing Revise\r\nusing Test, LinearAlgebra, Random, Statistics\r\nusing FileIO, JLD2\r\ndir = pwd()\r\ninclude(joinpath(dir, \"src\\\\ops_utility.jl\"))\r\ninclude(joinpath(dir, \"src\\\\ops_build.jl\"))\r\ninclude(joinpath(dir, \"src\\\\ops_methods.jl\"))\r\ninclude(joinpath(dir, \"src\\\\cfrops_solve.jl\"))\r\ninclude(joinpath(dir, \"src\\\\dcfrops_solve.jl\"))\r\ninclude(joinpath(dir, \"src\\\\optops_solve.jl\"))\r\ninclude(joinpath(dir, \"src\\\\ops_results.jl\"))\r\n\r\n\r\n##########################################################\r\n# build sequence-form reward\r\n# CAUTION: takes 1 hr+ to build sequence-form reward for 10 city default\r\nncity = 10\r\ng = AirDefenseGame(ncity, 6, 3, 4, 4, 2, 2)\r\nA, An, na_stage = build_action(g)\r\nni, ni1, ni2, ni_stage = build_info(g)\r\nns1, ns2, ns1_stage, ns2_stage = build_nseq(g, na_stage, ni_stage)\r\nΣ, seqn, seqactions = build_Σset(g, A, ns1, ns2)\r\n(U, z), uh_time = @timed build_utility_hist(g, A, An)\r\nreward_exp2, runtime2, nalloc, gc_time, misc = @timed build_utility_seq(g, gs, seqn, seqactions, expected = true)\r\n\r\ndir = pwd()\r\nfn = joinpath(dir, \"data\\\\vars_opt_rewardfunction_expected_15city_temp.jld2\")\r\n# @save fn g U z reward_exp Σ seqn seqactions runtime nalloc\r\n@show runtime\r\n# # load(fn)\r\n\r\ngs = GameSet(g)\r\ngos = GameOptSet(gs, reward_exp)\r\n(status, u_ne, r_ne, t_solve), t_total = @timed lp_nash(gos)\r\nlp_best_response(gos, r_ne, fixedplayer = 2)\r\n\r\n##########################################################\r\n# Data-biased response and robust best response\r\ng = AirDefenseGame(10,\r\n reshape([0.03674972063074833,0.7471235124528937,0.8006182686839263,0.1134119509104532,0.3720810993450727,0.6452465195265953,0.9927983579441313,0.8545575129265128,0.29473362663716407,0.9808676508834953,0.6242283949611096,0.6173536676330247,0.4739652533798455,0.6677615345281047,0.6338233451643072,0.8231268712815414,0.011816562466650193,0.048514560425303443,0.7974455234366102,0.22065505430418475], 10, 2),\r\n [0.47973468500756566,0.1596483573101528,0.7116043145363229,0.969005005082471,0.7139100481289631,0.4747849042596852,0.5066187533113924,0.7074385618615113,0.21009348198668265,0.29520436695319363],\r\n 0.3,\r\n 6,\r\n 3,\r\n 4,\r\n 4,\r\n 2,\r\n 2,\r\n 0.9,\r\n 0.8,\r\n 0.7,\r\n 0.2,\r\n [1, 3, 4, 5, 8, 9])\r\ngs = GameSet(g)\r\nA, An, na_stage = build_action(g)\r\nni, ni1, ni2, ni_stage = build_info(g)\r\nns1, ns2, ns1_stage, ns2_stage = build_nseq(g, na_stage, ni_stage)\r\nΣ, seqn, seqactions = build_Σset(g, A, ns1, ns2)\r\n(U, z), uh_time = @timed build_utility_hist(g, A, An)\r\n(reward_exp, reward_complete), runtime, _, _, _ = @timed build_utility_seq(g, gs, (ns1, ns2), seqn, seqactions, expected = true)\r\n\r\ndir = pwd()\r\nfn = joinpath(dir, \"data\\\\vars_opt_rewardfunction_expected_15city_flipped_temp.jld2\")\r\n# @save fn g U z reward_exp Σ seqn seqactions runtime\r\n@show runtime\r\n# load(fn)\r\n\r\ndir = pwd()\r\ninclude(joinpath(dir, \"src\\\\dbr_cfrops_solve.jl\"))\r\nusing Plots; gr()\r\nutemp, rtemp, stemp, σtemp = cfr(1_000, g, gs)\r\nσfix = copy(σtemp)\r\npdbr = vcat(fill(0.95, gs.ni_stage[3]), fill(0.0, gs.ni_stage[5]), fill(0.85, gs.ni_stage[6]))\r\nfn = \"data\\\\vars_cfr_dbr_attackerfixed_temp.jld2\"\r\n# @save joinpath(dir, fn) σfix pdbr\r\n\r\nT = 3_000\r\n\r\n# NE for g\r\nucfr, _, _, σcfr = cfr(T, g, gs)\r\nmean(ucfr)\r\nplot(cumsum(ucfr) ./ collect(1:T))\r\n\r\n# NE for g using cfr_dbr (PConf = 0 and σfix = arbitrary)\r\nu2, _, _, σ2 = cfr_dbr(T, g, gs, zeros(length(pdbr)), σcfr .* 100)\r\nmean(u2)\r\nall(sum(i) ≈ 1 for i in σ2)\r\n\r\n# NE for g using cfr_dbr (PConf = 1 and σfix = σNE)\r\nu3, _, _, _ = cfr_dbr(T, g, gs, ones(length(pdbr)), σcfr)\r\nmean(u3)\r\n\r\n# calculate defender's robust CFR BR to σfix at 100% confidence\r\n# this matches lp_best_response (at least sometimes...)\r\nT = 3000\r\nu1, _, _, _ = cfr_dbr(T, g, gs, ones(length(pdbr)), σfix)\r\nmean(u1)\r\nplot(cumsum(u1) ./ collect(1:T))\r\n\r\n# calculate defender's BR to σfix\r\ngos = GameOptSet(g, gs, reward_exp)\r\nstatus_br, u_br, r_br = lp_best_response(gos, real_strat(σfix, gs, gos)[2], fixedplayer = 2)\r\nu_br\r\n\r\nstatus_brne, u_brne, r_brne = lp_best_response(gos, real_strat(σcfr, gs, gos)[2], fixedplayer = 2)\r\nu_brne\r\n\r\nst_ne, u_ne, r_ne, t_ne = lp_nash(gos, 5 * 60)\r\nu_ne\r\n\r\nstatus_brne, u_brne, r_brne = lp_best_response(gos, r_ne, fixedplayer = 2)\r\nu_brne\r\n\r\nT = 20_000\r\nucfr, _, _, σcfr = cfr(T, g, gs)\r\nmean(ucfr)\r\nstatus_brne, u_brne_1, r_brne = lp_best_response(gos, real_strat(σcfr, gs, gos)[2], fixedplayer = 2)\r\nu_brne_1\r\nstatus_brne, u_brne_2, r_brne = lp_best_response(gos, real_strat(σcfr, gs, gos)[1], fixedplayer = 1)\r\nu_brne_2\r\n\r\n# calculate defender's robust CFR BR to σfix at pdbr% confidence\r\nu, _, _, _ = cfr_dbr(T, g, gs, pdbr, σfix)\r\nmean(u)\r\nplot(cumsum(u) ./ collect(1:T))\r\n\r\n\r\n# calculate defender's exact robust BR to σfix\r\n# TBD - need to code up robust BR...from overleaf\r\n\r\n##########################################################\r\n# deprecate once GameOptSet constructor works\r\n# build AirDefenseGame, GameSet, and GameOptSet for both optimization and CFR\r\ng = AirDefenseGame()\r\ngs = GameSet(g)\r\nA, An, na_stage = build_action(g)\r\nni, ni1, ni2, ni_stage = build_info(g)\r\nns1, ns2, ns1_stage, ns2_stage = build_nseq(g, na_stage, ni_stage)\r\nΣ, seqn, seqactions = build_Σset(g, A, ns1, ns2)\r\nIset, (I1set, I2set), (seqI1, seqI2), (nextseqI1, nextseqI2) = build_Iset(g, A, na_stage, ns1_stage, ns2_stage, ni1, ni2, ns1, ns2)\r\n# load expensive reward function\r\nfn = joinpath(dir, \"data\\\\vars_opt_rewardfunction.jld2\")\r\n@load fn reward\r\nfn2 = joinpath(dir, \"data\\\\vars_opt_rewardfunction_expected.jld2\")\r\n@load fn2 reward_exp\r\n# Next line defaults to expected reward\r\ngos = GameOptSet(ns1, ns2, ni1, ni2, ns1_stage, ns2_stage, reward_exp,\r\n gs.na_stage, gs.sensors, seqI1, seqI2, nextseqI1, nextseqI2)\r\n\r\n\r\n##########################################################\r\n# CFR\r\nRandom.seed!(579843)\r\n# g = AirDefenseGame(0.95)\r\n# gamesize(AirDefenseGame(15,8,5,8,8,3,3))\r\n# g = AirDefenseGame(13,6,4,6,6,3,3)\r\n# gamesize(g)\r\n# gamesize(AirDefenseGame())\r\n# g = AirDefenseGame(10,8,4,8,8,3,3)\r\ng = AirDefenseGame()\r\n\r\n\r\ng = AirDefenseGame(10,\r\n reshape([0.03674972063074833,0.7471235124528937,0.8006182686839263,0.1134119509104532,0.3720810993450727,0.6452465195265953,0.9927983579441313,0.8545575129265128,0.29473362663716407,0.9808676508834953,0.6242283949611096,0.6173536676330247,0.4739652533798455,0.6677615345281047,0.6338233451643072,0.8231268712815414,0.011816562466650193,0.048514560425303443,0.7974455234366102,0.22065505430418475], 10, 2),\r\n [0.47973468500756566,0.1596483573101528,0.7116043145363229,0.969005005082471,0.7139100481289631,0.4747849042596852,0.5066187533113924,0.7074385618615113,0.21009348198668265,0.29520436695319363],\r\n 0.3,\r\n 6,\r\n 3,\r\n 4,\r\n 4,\r\n 2,\r\n 2,\r\n 0.9,\r\n 0.8,\r\n 0.7,\r\n 0.2,\r\n [1, 3, 4, 5, 8, 9])\r\ngs = GameSet(g)\r\n# gos = GameOptSet(gs, reward_exp)\r\nT = 5_000\r\n@time u, r, s, σ = cfr(T, g, gs) # 45 ms => 45 sec per 1k iterations\r\nmean(u)\r\n\r\n@time u1, r, s, σ, σ1, converged, iter = dcfr_full(g, gs, iterlimit = T)\r\nmean(u1)\r\n\r\n# psc = 0.55, pac = 0.8, T = 5_000: utility = -1.2374797\r\n# psc = 0.95, pac = 0.8, T = 5_000: utility = -1.2249\r\n\r\n##########################################################\r\n# CFR Stopping Rule and Step size\r\nusing Plots; gr()\r\nusing Distributed\r\nnprocs() == 1 && addprocs()\r\n@everywhere using Pkg\r\n@everywhere Pkg.activate(pwd())\r\n@everywhere(using Revise, BenchmarkTools, Printf, ProgressMeter, FileIO, JLD2)\r\n@everywhere(using Random, LinearAlgebra, Statistics, Distances, IterTools, DataFrames, DataFramesMeta)\r\n@everywhere(using StaticArrays, SparseArrays)\r\n@everywhere(using JuMP, Clp)\r\n@everywhere(using Clp: ClpCInterface)\r\n@everywhere dir = pwd()\r\n@everywhere include(joinpath(dir, \"src\\\\ops_utility.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_build.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_methods.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\cfrops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\dcfrops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\optops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_results.jl\"))\r\n\r\nRandom.seed!(579843)\r\ng = AirDefenseGame(10,\r\n reshape([0.03674972063074833,0.7471235124528937,0.8006182686839263,0.1134119509104532,0.3720810993450727,0.6452465195265953,0.9927983579441313,0.8545575129265128,0.29473362663716407,0.9808676508834953,0.6242283949611096,0.6173536676330247,0.4739652533798455,0.6677615345281047,0.6338233451643072,0.8231268712815414,0.011816562466650193,0.048514560425303443,0.7974455234366102,0.22065505430418475], 10, 2),\r\n [0.47973468500756566,0.1596483573101528,0.7116043145363229,0.969005005082471,0.7139100481289631,0.4747849042596852,0.5066187533113924,0.7074385618615113,0.21009348198668265,0.29520436695319363],\r\n 0.3,\r\n 6,\r\n 3,\r\n 4,\r\n 4,\r\n 2,\r\n 2,\r\n 0.9,\r\n 0.8,\r\n 0.7,\r\n 0.2,\r\n [1, 3, 4, 5, 8, 9])\r\ngs = GameSet(g)\r\n# @load joinpath(dir, \"data\\\\vars_opt_rewardfunction_expected.jld2\") reward_exp\r\n# gos = GameOptSet(gs, reward_exp)\r\n\r\n# @time u, r, s, σ, σ1, converged = cfr_stoprule(5, g, gs, tolerance = 5e-5)\r\n# mean(u)\r\n# um = cumsum(u) ./ collect(1:length(u))\r\n# status, u_br, r_br = lp_best_response(gos, real_strat(σ, gs, gos)[1], fixedplayer = 1)\r\n# plot(1:length(um), um, xlim = (0,1000))\r\n# ud, rd, sd, σd, σ1d, converged_d = dcfr_full(g, gs, timelimit = 2, tol = 5e-5,\r\n# α = 1.5, β = 0.5, γ = 2.0, discounted = true)\r\n# non-discounted: mean(ud) = -1.245077\r\n# @show mean(ud)\r\n# umd = cumsum(ud) ./ collect(1:length(ud))\r\n# plot!(1:length(umd), umd)\r\n# plot(1:length(ud), ud)\r\n# statusd, u_brd, r_brd = lp_best_response(gos, real_strat(σd, gs, gos)[1], fixedplayer = 1)\r\n# rerr(-u_brd, -1.2595387377)\r\n\r\n#\r\n# alphas = [0.0, 0.0, 0.0, 0.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 1.5]\r\n# betas = [-8.0, -8.0, 8.0, 8.0, -8.0, -8.0, 8.0, 8.0, 8.0, -8.0, 0.5]\r\n# gammas = [0.0, 8.0, 0.0, 8.0, 0.0, 8.0, 0.0, 8.0, 0.0, 2.0, 2.0]\r\nreps = 50\r\nalphas = repeat([8.0, 8.0, 1.5], inner = reps)\r\nbetas = repeat([8.0, -8.0, 0.5], inner = reps)\r\ngammas = repeat([0.0, 2.0, 2.0], inner = reps)\r\ndoe_discount = DataFrame(alpha = alphas, beta = betas, gamma = gammas)\r\nresults = pmap((a,b,c) -> dcfr_full(g, gs, timelimit = 10, tol = 5e-5,\r\n α = a, β = b, γ = c, discounted = true), alphas, betas, gammas)\r\nnsteps = 12_000\r\nums = [cumsum(r[1]) ./ collect(1:length(r[1])) for r in results]\r\nums_means = [[mean(ums[i][j] for i = (k * reps + 1):((k + 1) * reps)) for j in 1:nsteps] for k in 0:2]\r\nums_stds = [[std(ums[i][j] for i = (k * reps + 1):((k + 1) * reps)) for j in 1:nsteps] for k in 0:2]\r\n# us = [r[1] for r in results]\r\n# us_means = [[mean(us[i][j] for i = (k * reps + 1):((k + 1) * reps)) for j in 1:nsteps] for k in 0:2]\r\n# us_stds = [[std(us[i][j] for i = (k * reps + 1):((k + 1) * reps)) for j in 1:nsteps] for k in 0:2]\r\npcolors = [:steelblue, :tomato, :mediumseagreen]\r\npstyles = [:solid, :dash, :dashdot]\r\nfig = plot(xlabel = \"Iterations\", ylabel = \"Defender Utility\",\r\n xlims = (0, nsteps), ylims = (-1.27, -1.2))\r\n# fig = plot(xlabel = \"Iterations\", ylabel = \"Defender Utility\",\r\n# xlims = (0, 2_000), ylims = (-1.5, -0.5))\r\nfor i in 1:3\r\n plot!(fig, 1:nsteps, ums_means[i], ribbon = 2.009 * ums_stds[i] ./ sqrt(reps), fillalpha = 0.2, linecolor = pcolors[i],\r\n label = string(alphas[i*reps], \", \", betas[i*reps], \", \", gammas[i*reps]),\r\n linestyle = pstyles[i])\r\n # plot!(fig, 1:nsteps, us_means[i], alpha = 0.5, seriestype = :line,\r\n # color = pcolors[i])\r\n # plot!(fig, 1:nsteps, ums_means[i] .- ums_stds[i], linecolor = pcolors[i], linestyle = :dot)\r\n # plot!(fig, 1:nsteps, ums_means[i] .+ ums_stds[i], linecolor = pcolors[i], linestyle = :dot)\r\nend\r\nplot!(fig, 1:nsteps, fill(-1.2595387377, nsteps), label = \"Nash Equilibrium\",\r\n linestyle = :dot, color = :black)\r\n\r\ndir = pwd()\r\nfn = joinpath(dir, \"data\\\\plot_stepsize_v4_temp.pdf\")\r\n# savefig(fn)\r\nfn = joinpath(dir, \"data\\\\vars_stepsize_fig_temp.jld2\")\r\n# @save fn results reps g doe_discount\r\n\r\n##########################################################\r\n# CFR DOE\r\nusing Pkg; Pkg.activate(pwd())\r\nusing Distributed, SharedArrays, Statistics, Dates\r\nusing CSV\r\n# using Plots; gr()\r\nnprocs() == 1 && addprocs()\r\n@everywhere using Pkg\r\n@everywhere Pkg.activate(pwd())\r\n@everywhere(using Revise, BenchmarkTools, Printf, ProgressMeter, FileIO, JLD2)\r\n@everywhere(using Random, LinearAlgebra, Statistics, Distances, IterTools, DataFrames, DataFramesMeta)\r\n@everywhere(using StaticArrays, SparseArrays)\r\n@everywhere(using JuMP, Clp)\r\n@everywhere(using Clp: ClpCInterface)\r\n@everywhere dir = pwd()\r\n@everywhere include(joinpath(dir, \"src\\\\ops_utility.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_build.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_methods.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\cfrops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\dcfrops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\optops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_results.jl\"))\r\n\r\n# see scratch for screening design and RSM design\r\n@everywhere function build_design(fn::String)\r\n factor_names = [\"pp\", \"psc\", \"pdc\",\r\n \"alpha\", \"beta\", \"gamma\"]\r\n col_types = [Float64, Float64, Float64,\r\n Float64, Float64, Float64]\r\n const_names = [\"radius\", \"pac\",\r\n \"ncity\", \"ndp\", \"nap\",\r\n \"ndpdc\", \"ndpac\", \"ndc\", \"nac\"]\r\n const_types = [Float64, Float64,\r\n Int64, Int64, Int64,\r\n Int64, Int64, Int64, Int64]\r\n const_values = [0.3, 0.2,\r\n 13, 6, 4,\r\n 6, 6, 3, 3]\r\n design = CSV.read(joinpath(dir, fn), types = col_types)\r\n rename!(design, old => new for (old, new) = zip(names(design), Symbol.(factor_names)))\r\n l, w = size(design)\r\n for i in 1:2\r\n design[Symbol(const_names[i])] = fill(const_values[i], l)\r\n end\r\n for i in 3:length(const_names)\r\n design[Symbol(const_names[i])] = fill(Int64(const_values[i]), l)\r\n end\r\n return design\r\nend\r\n\r\n@everywhere function build_constants(design)\r\n nruns = size(design, 1)\r\n Xmax = rand(maximum(design.ncity), 2)\r\n vmax = rand(maximum(design.ncity))\r\n Xs = [Xmax[1:nc, :] for nc in design.ncity]\r\n vs = [vmax[1:nc] for nc in design.ncity]\r\n iadstable = Vector{Any}[]\r\n for nc in unique(design.ncity), nndp in unique(design.ndp)\r\n push!(iadstable, [nc, nndp, sort!(sample(1:nc, nndp, replace = false))])\r\n end\r\n iadss = [iadstable[findfirst(x -> x[1] == design.ncity[i] && x[2] == design.ndp[i],\r\n iadstable)][3] for i in 1:nruns]\r\n return Xs, vs, iadss\r\nend\r\n\r\n@everywhere function build_doegames(design, Xs, vs, iadss)\r\n nruns = size(design, 1)\r\n gvec = Array{AirDefenseGame}(undef, nruns)\r\n gsvec = Array{GameSet}(undef, nruns)\r\n nnodevec = Array{String}(undef, nruns)\r\n for i in 1:nruns\r\n ncity = design.ncity[i][1]\r\n radius = design.radius[i][1]\r\n ndp = design.ndp[i][1]\r\n nap = design.nap[i][1]\r\n ndpdc = design.ndpdc[i][1]\r\n ndpac = design.ndpac[i][1]\r\n ndc = design.ndc[i][1]\r\n nac = design.nac[i][1]\r\n pp = design.pp[i][1]\r\n psc = design.psc[i][1]\r\n pdc = design.pdc[i][1]\r\n pac = design.pac[i][1]\r\n a = design.alpha[i][1]\r\n b = design.beta[i][1]\r\n c = design.gamma[i][1]\r\n gvec[i] = AirDefenseGame(ncity, Xs[i], vs[i], radius, ndp, nap, ndpdc, ndpac, ndc, nac,\r\n pp, psc, pdc, pac, iadss[i])\r\n gsvec[i] = GameSet(gvec[i])\r\n nnodevec[i] = gamesize(gvec[i])[4]\r\n end\r\n return gvec, gsvec, nnodevec\r\nend\r\n\r\n@everywhere function calc_run(df_row, g, gs, runnum)\r\n a = df_row.alpha[1]\r\n b = df_row.beta[1]\r\n c = df_row.gamma[1]\r\n println(\"----------- Start Run $runnum -----------\")\r\n (u, _, _, _, _, converged, iter), runtime = @timed dcfr_full(g, gs,\r\n iterlimit = 100_000, timelimit = 240, tol = 5e-5,\r\n α = a, β = b, γ = c, discounted = true)\r\n println(\"------##### End Run $runnum #####------\")\r\n return mean(u), converged, iter, runtime\r\nend\r\n\r\n# design = build_design(\"data\\\\design_frac_207.csv\")\r\ndesign = build_design(\"data\\\\design_frac_207_augment.csv\")\r\nnruns = size(design, 1)\r\nXs, vs, iadss = build_constants(design)\r\ngvec, gsvec, nnodevec = build_doegames(design, Xs, vs, iadss)\r\nparse.(Float64, nnodevec) |> findmax\r\n\r\nresults_doe, t_doe = @timed pmap(x -> calc_run(design[x, :], gvec[x], gsvec[x], x), 1:nruns)\r\nfn = joinpath(dir, \"data\\\\results_doe_frac207augment_temp.jld2\")\r\n# @save fn results_doe, t_doe, gvec\r\n\r\ndfr = hcat(design, DataFrame(utility = [ri[1] for ri in results_doe],\r\n converged = [ri[2] for ri in results_doe],\r\n iterations = [ri[3] for ri in results_doe],\r\n time = [ri[4] for ri in results_doe]))\r\n\r\n# CSV.write(joinpath(dir, \"data\\\\results_doe_frac207augment_temp.csv\"), dfr)\r\n\r\n##########################################################\r\n# CFR Large\r\n\r\nusing Pkg; Pkg.activate(pwd())\r\nusing Revise\r\nusing Distributed, SharedArrays, Statistics, Dates\r\nusing CSV\r\n# using Plots; gr()\r\nnprocs() == 1 && addprocs()\r\n@everywhere using Pkg\r\n@everywhere Pkg.activate(pwd())\r\n@everywhere(using Revise, BenchmarkTools, Printf, ProgressMeter, FileIO, JLD2)\r\n@everywhere(using Random, LinearAlgebra, StatsBase, Distances, IterTools, DataFrames, DataFramesMeta)\r\n@everywhere(using StaticArrays, SparseArrays)\r\n@everywhere(using JuMP, Clp)\r\n@everywhere(using Clp: ClpCInterface)\r\n@everywhere dir = pwd()\r\n@everywhere include(joinpath(dir, \"src\\\\ops_utility.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_build.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_methods.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\cfrops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\dcfrops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\optops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_results.jl\"))\r\n\r\n# collect and load reward function data\r\n@everywhere function collect_sizedata_seqreward(ncity, tlim)\r\n g = AirDefenseGame(ncity, 6, 3, 4, 4, 2, 2)\r\n gs = GameSet(g)\r\n A, An, na_stage = build_action(g)\r\n ni, ni1, ni2, ni_stage = build_info(g)\r\n ns1, ns2, ns1_stage, ns2_stage = build_nseq(g, na_stage, ni_stage)\r\n Σ, seqn, seqactions = build_Σset(g, A, ns1, ns2)\r\n U, z = build_utility_hist(g, A, An)\r\n (reward_exp, completed), runtime = @timed build_utility_seq(g, gs, (ns1, ns2), seqn, seqactions,\r\n expected = true, timelimit = tlim)\r\n return g, U, z, reward_exp, completed, Σ, seqn, seqactions, runtime\r\nend\r\nRandom.seed!(579843)\r\nncities = [7, 8, 9, 10, 11, 12, 13, 14, 15] # number of cities (all other game params fixed)\r\nn = length(ncities)\r\nprintln(\"Start Time: $(now())\")\r\nresults = pmap((a, b) -> collect_sizedata_seqreward(a, b), ncities, fill(12 * 60, length(ncities)))\r\ndirlocal = \"C:\\\\Users\\\\AKeith\\\\JuliaProjectsLocal\\\\StrategyGamesLocal\"\r\nfnlocal = joinpath(dirlocal, \"data\\\\vars_opt_rewardfunction_expected_7to15city_temp.jld2\")\r\n# # @save fnlocal results\r\n# fn = joinpath(dir, \"data\\\\vars_opt_rewardfunction_expected_7to15city_temp.jld2\") # 12 hr time limit\r\n# # @save fn results\r\n# @load joinpath(dirlocal, \"data\\\\vars_opt_rewardfunction_expected_7to15city.jld2\") results # approx 5 min\r\ngvec = [ri[1] for ri in results]\r\ngsvec = GameSet.(gvec)\r\ngosvec = [GameOptSet(gvec[i], gsvec[i], rexps[i]) for i in 1:n]\r\nrexps = [ri[4] for ri in results]\r\ngsizes = [gamesize(gi)[4] for gi in gvec]\r\nseqsizes = [size(ri[7][1])[1] * size(ri[7][2])[1] for ri in results]\r\nstatuses = [ri[5] for ri in results]\r\nruntimes = [ri[end] for ri in results] ./ (60 * 60) # in hours\r\n\r\n# collect and load LP\r\nunes = SharedArray{Float64}(n)\r\ntnes = SharedArray{Float64}(n)\r\nstatusnes = SharedArray{Bool}(n)\r\nprintln(\"LP NE start time for $n city sizes: $(now())\")\r\n@distributed for i in 1:n\r\n g = gvec[i]\r\n gs = gsvec[i]\r\n gos = gosvec[i]\r\n maxseconds = 10 * 60\r\n (status_ne, u_ne, r_ne, t_solve), t_ne = @timed lp_nash(gos, maxseconds)\r\n unes[i] = u_ne\r\n tnes[i] = t_ne\r\n (status_ne == :Optimal) && (statusnes[i] = true)\r\nend\r\nfn = joinpath(dir, \"results_size_lpne_7to15city_10min_temp.jld2\")\r\n# @save fn unes tnes statusnes\r\n# @load joinpath(dir, \"results_size_lpne_15city_10min.jld2\") unes tnes statusnes\r\n\r\n# collect and load CFR\r\n@everywhere function collect_sizedata_cfr(g::AirDefenseGame, gs::GameSet)\r\n (u, r, s, σ, σs, converged), runtime = @timed dcfr_full(g, gs, timelimit = 10, tol = 5e-5, α = 1.5, β = 0.0, γ = 2.0, discounted = false)\r\n return u, r, s, σ, σs, converged, runtime\r\nend\r\nRandom.seed!(748685)\r\ncfr_params = Dict(\"timelimit\" => 10, \"tol\" => 5e-5, \"α\" => 1.5, \"β\" => 0.0, \"γ\" => 2.0, \"discounted\" => false)\r\nprintln(\"Start Time: $(now())\")\r\nresults_cfr = pmap((a, b) -> collect_sizedata_cfr(a, b), gvec, gsvec)\r\nfn = joinpath(dir, \"data\\\\results_size_cfr_7to15city_10min_temp.jld2\")\r\n# @save fn results_cfr gvec cfr_params\r\n# @load joinpath(dir, \"data\\\\results_size_cfr_15city_5min.jld2\") results ncities T\r\nucfrs = [ri[1] for ri in results_cfr]\r\numcfrs = [cumsum(ri[1]) ./ collect(1:length(ri[1])) for ri in results_cfr]\r\numeancfrs = [mean(ri[1]) for ri in results_cfr]\r\ntcfrs = [ri[7] for ri in results_cfr]\r\nσcfrs = [ri[4] for ri in results_cfr]\r\nconvergecfrs = [ri[6] for ri in results_cfr]\r\n\r\n# collect and load best responses\r\n@everywhere fbr(g, gs, gos, σ) = lp_best_response(gos, real_strat(σ, gs, gos)[1], fixedplayer = 1)\r\nresults_br = pmap(fbr, gvec, gsvec, gosvec, σcfrs) # status_br, u_br, r_br\r\nfn = joinpath(dir, \"data\\\\results_size_br_7to15city_10min_temp.jld2\")\r\n# @save fn results_br gvec\r\nubrs = [-1 * ri[2] for ri in results_br]\r\nuexploits = rerr.(ubrs, unes)\r\n\r\n# make size summary data frame\r\ndf_size = DataFrame(ncity = ncities, nnodes = gsizes, nseqcombos = seqsizes,\r\n rewardtime = runtimes, rewardcomplete = statuses,\r\n lptime = tnes, lputility = unes, lpstatus = statusnes,\r\n cfrtime = tcfrs, cfrutility = umeancfrs, cfrconverged = convergecfrs,\r\n brutility = ubrs, exploitability = uexploits)\r\n# CSV.write(joinpath(dir, \"data\\\\results_size_7to15_temp.csv\"), df_size)\r\n\r\n\r\n# plots\r\nusing DataFrames, DataFramesMeta\r\n\r\ndfr = DataFrame(ncity = Int64[], iter = Int64[], utility = Float64[], um = Float64[], converged = Bool[], runtime = Float64[])\r\nfor i in eachindex(us)\r\n for j in eachindex(us[i])\r\n push!(dfr, [ncities[i], j, us[i][j], ums[i][j]])\r\n end\r\nend\r\n\r\ndfx = @linq dfr |>\r\n where(:ncity .== 10) |>\r\n select(:iter, :um)\r\n\r\nfig = plot(dfx[:iter], dfx[:um], xlabel = \"Iterations\", ylabel = \"Defender Utility\")\r\nfor city in ncities\r\n dfi = @linq dfr |>\r\n where(:ncity .== city) |>\r\n select(:iter, :um)\r\n plot!(fig, dfi[:iter], dfi[:um], label = \"|M|=$city\")\r\nend\r\nfig\r\n\r\n\r\n\r\n\r\n\r\n######################################################################################\r\n# Analyze default scenario\r\n# Output: Defender utility by iteration plot, relative exploitability by iteration plot\r\ninclude(joinpath(dir, \"src\\\\optops_solve.jl\"))\r\nusing Plots; gr()\r\nRandom.seed!(579843)\r\ng = AirDefenseGame()\r\ngs = GameSet(g)\r\n@load joinpath(dir, \"data\\\\vars_opt_rewardfunction_expected.jld2\") reward_exp\r\ngos = GameOptSet(g, gs, reward_exp)\r\nT = 1_000\r\n@time u, r, s, σ, u_br = cfr_exploit(T, g, gs, gos)\r\n(status, u_ne, r1_ne, r2_ne, t_solve), t_total = @timed lp_nash(gos)\r\nprintln(\"Status: $status, Obj Value: $u_ne, Solve Time: $t_solve, Build Time: $(t_total - t_solve)\")\r\n\r\n@show u_ne # -1.2595387377\r\num = cumsum(u) ./ collect(1:T) # incremental utility\r\nu_rerr = rerr.(u_br, u_ne) # relative error calc of br to ne\r\n\r\n# title = \"Defensive utility raw\"\r\nplot(1:T, um, legend = false, ylims = (-1.26, -1.2),\r\n ylabel = \"Defender Utility\", xlabel = \"Iterations\")\r\n\r\n# title = \"CFR approximate relative error\"\r\nplot(1:T, [rerr.(um, u_true)] * 100, legend = false, ylims = (0.0,15),\r\n ylabel = \"Relative Error (%)\", xlabel = \"Iterations\")\r\n\r\n# title = \"CFR exploitability\"\r\nplot(T ÷ 10:T ÷ 10:T, u_rerr * 100, legend = false, ylims = (0.0,2),\r\n seriestype = :line, markerstrokealpha = 0,\r\n ylabel = \"Exploitability (% Nash Equilibrium Utility)\", xlabel = \"Iterations\")\r\nplot!(T ÷ 10:T ÷ 10:T, u_rerr * 100, seriestype = :scatter, markerstrokealpha = 0,\r\n markercolor = :steelblue)\r\nplot!(1:T, fill(0.5, T), linecolor = :red)\r\nannotate!(T, 0.6, text(\"0.5% Exploitability\", 10, :red, :right))\r\ndir = pwd()\r\nfn = joinpath(dir, \"data\\\\plot_default_temp.pdf\")\r\n# savefig(fn)\r\n\r\nfunction h_mle(σ, g, gs; chance_ind = [1,1,0,1,0,0])\r\n h = SVector(0, 0, 0, 0, 0, 0)\r\n depth = 1\r\n for i = 1:6\r\n if getplayer(depth) == 3\r\n h = setindex(h, chance_ind[depth], depth)\r\n depth += 1\r\n else\r\n maxval, maxind = findmax(σ[infoset(h, depth, g, gs)])\r\n h = setindex(h, maxind, depth)\r\n depth += 1\r\n end\r\n end\r\n h\r\nend\r\n\r\nfunction getutility(h, U, z)\r\n U[findfirst(x -> x == h, z)]\r\nend\r\n\r\ng = AirDefenseGame()\r\ngs = GameSet(g)\r\nU, z = build_utility_hist(g, gs.A, gs.An)\r\nh1 = h_mle(σ, g, gs, chance_ind = [1,1,0,4,0,0])\r\nh3 = SVector(1, 1, 1, 4, 1, 1)\r\ndp3 = getlaydown(h3, g, coverage(g), gs.A)\r\nplot_laydown(dp3)\r\ndp1 = getlaydown(h1, g, coverage(g), gs.A)\r\nplot_laydown(dp1)\r\ndir = pwd()\r\nfn = joinpath(dir, \"data\\\\plot_default_[1,1,1,1,6,39].pdf\")\r\nsavefig(fn)\r\nh2 = h_mle(σ, g, gs, chance_ind = [1,1,0,4,0,0])\r\ndp2 = getlaydown(h2, g, coverage(g), gs.A)\r\nplot_laydown(dp2)\r\ngetutility(h1, U, z)\r\ngetutility(h2, U, z) # this should be higher since we have cyber sa\r\n\r\n######################################################\r\n# Distributed Pdetect investigation\r\n\r\nusing Distributed, Statistics, Plots\r\ngr()\r\naddprocs(10); nprocs()\r\n@everywhere using Pkg\r\n@everywhere Pkg.activate(pwd())\r\n@everywhere(using Revise, BenchmarkTools, Printf, ProgressMeter, FileIO, JLD2)\r\n@everywhere(using Random, LinearAlgebra, StatsBase, Distances, IterTools, DataFrames, DataFramesMeta)\r\n@everywhere(using StaticArrays, SparseArrays)\r\n@everywhere(using JuMP, Clp)\r\n@everywhere(using Clp: ClpCInterface)\r\n@everywhere dir = pwd()\r\n@everywhere include(joinpath(dir, \"src\\\\ops_utility.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_build.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_methods.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\cfrops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\dcfrops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\optops_solve.jl\"))\r\n@everywhere include(joinpath(dir, \"src\\\\ops_results.jl\"))\r\n\r\n\r\n@everywhere function sensor_eval(p::Float64)\r\n Random.seed!(579843)\r\n g = AirDefenseGame(p)\r\n gs = GameSet(g)\r\n (u, r, s, σ, σs, converged), runtime = @timed dcfr_full(g, gs, timelimit = 10,\r\n tol = 5e-5, discounted = false)\r\n return u, σ, converged, runtime\r\nend\r\n\r\nps = 0.5:0.05:1.0\r\nresults = pmap(sensor_eval, ps)\r\nus = [mean(r[1]) for r in results]\r\nplot(ps, us, xlabel = \"Probability of Detection\", ylabel = \"Defender Utility\",\r\n legend = false, seriestype = :line)\r\nplot!(ps, us, seriestype = :scatter, markerstrokealpha = 0, markercolor = :steelblue)\r\ndir = pwd()\r\nfn = joinpath(dir, \"data\\\\plot_pdetect_stoprule_temp.pdf\")\r\n# savefig(fn)\r\n\r\nrmprocs(getindex(procs(), procs() .> 1))\r\n\r\ngtoy = AirDefenseGame(2, [1.0 1;2 1], [1.0, 1], 0.2, 2, 1, 2, 2, 1, 1, 0.9, 0.99, 0.7, 0.8, [1,2])\r\ngstoy = GameSet(gtoy)\r\nT = 15_000\r\n(utoy, r, s, σtoy), t_cfr = @timed cfr(T, gtoy, gstoy)\r\nmean(utoy)\r\nc1 = [chance(4, i, gtoy, gstoy) for i in 1:2]\r\ns1 = σtoy[infoset(SVector(1,1,1,1,0,0), 5, gtoy, gstoy)]\r\ns2 = σtoy[infoset(SVector(1,1,1,2,0,0), 5, gtoy, gstoy)]\r\nplot_laydown(getlaydown(SVector(1,1,1,1,2,1), gtoy, coverage(gtoy), gstoy.A))\r\nleafutility(SVector(1,1,1,1,1,1), 1, 1.0, 1.0, gtoy, gstoy)\r\nleafutility(SVector(1,1,1,1,2,1), 1, 1.0, 1.0, gtoy, gstoy)\r\nsh1 = h_mle(σtoy, gtoy, gstoy, chance_ind = [1,1,0,1,0,0])\r\nsh2 = h_mle(σtoy, gtoy, gstoy, chance_ind = [1,1,0,2,0,0])\r\n\r\ngtoy = AirDefenseGame(2, [1.0 1;2 1], [1.0, 1], 0.2, 2, 1, 2, 2, 1, 1, 0.9, 0.5, 0.7, 0.8, [1,2])\r\ngstoy = GameSet(gtoy)\r\nT = 15_000\r\n(utoy, r, s, σtoy), t_cfr = @timed cfr(T, gtoy, gstoy)\r\nmean(utoy)\r\nc1 = [chance(4, i, gtoy, gstoy) for i in 1:2]\r\ns1 = σtoy[infoset(SVector(1,1,1,1,0,0), 5, gtoy, gstoy)]\r\ns2 = σtoy[infoset(SVector(1,1,1,2,0,0), 5, gtoy, gstoy)]\r\nplot_laydown(getlaydown(SVector(1,1,1,1,2,1), gtoy, coverage(gtoy), gstoy.A))\r\nleafutility(SVector(1,1,1,1,1,1), 1, 1.0, 1.0, gtoy, gstoy)\r\nleafutility(SVector(1,1,1,1,2,1), 1, 1.0, 1.0, gtoy, gstoy)\r\nsh1 = h_mle(σtoy, gtoy, gstoy, chance_ind = [1,1,0,1,0,0])\r\nsh2 = h_mle(σtoy, gtoy, gstoy, chance_ind = [1,1,0,2,0,0])\r\n\r\ng1 = AirDefenseGame(0.5)\r\ngs1 = GameSet(g1)\r\n@show c1 = [chance(4, i, g1, gs1) for i in 1:4]\r\nleafutility(SVector(1,1,1,4,1,1), 1, 1.0, 1.0, g1, gs1)\r\nleafutility(SVector(1,1,1,4,6,1), 1, 1.0, 1.0, g1, gs1)\r\nT = 15_000\r\n(u1, r, s, σ1), t_cfr = @timed cfr(T, g1, gs1)\r\nmean(u1)\r\ns11 = σ1[infoset(SVector(1,1,1,1,0,0), 5, g1, gs9)]\r\ns12 = σ1[infoset(SVector(1,1,1,4,0,0), 5, g1, gs9)]\r\ns1h1 = h_mle(σ1, g1, gs1, chance_ind = [1,1,0,1,0,0])\r\ns1h2 = h_mle(σ1, g1, gs1, chance_ind = [1,1,0,4,0,0])\r\n\r\ng9 = AirDefenseGame(0.99)\r\ngs9 = GameSet(g9)\r\n@show c9 = [chance(4, i, g9, gs9) for i in 1:4]\r\nleafutility(SVector(1,1,1,4,1,1), 1, 1.0, 1.0, g9, gs9)\r\nleafutility(SVector(1,1,1,4,6,1), 1, 1.0, 1.0, g9, gs9)\r\nT = 15_000\r\n(u9, r, s, σ9), t_cfr = @timed cfr(T, g9, gs9)\r\nmean(u9)\r\ns9h1 = h_mle(σ9, g9, gs9, chance_ind = [1,1,0,1,0,0])\r\ns9h2 = h_mle(σ9, g9, gs9, chance_ind = [1,1,0,4,0,0])\r\n\r\n\r\nsensor_eval(0.1, 10)\r\nsensor_eval(0.9, 10)\r\n\r\nfunction sensor_eval_toy(p::Float64, T::Int64)\r\n Random.seed!(579843)\r\n g = AirDefenseGame(2, [1.0 1;2 1], [1.0, 1], 0.2, 2, 1, 2, 2, 1, 1, 0.9, p, 0.7, 0.8, [1,2])\r\n @show g.v\r\n gs = GameSet(g)\r\n (u, r, s, σ), t_cfr = @timed cfr(T, g, gs)\r\n return u, r, s, σ, t_cfr\r\nend\r\n\r\nps = 0.55:0.05:0.95\r\nevals = [mean(sensor_eval_toy(p, 15000)[1]) for p in ps]\r\n\r\nT = 15_000\r\nresults = pmap((a, b) -> sensor_eval(a, b), ps, fill(T, length(ps)))\r\nus = [mean(r[1]) for r in results]\r\nplot(ps, us, xlabel = \"Probability of Detection\", ylabel = \"Defender Utility\")\r\n", "meta": {"hexsha": "a1d10f2ea9e7708b3ce5bd34948b04b459f6f336", "size": 30580, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cfrops_collect.jl", "max_stars_repo_name": "ajkeith/Cyber-Air-Defense", "max_stars_repo_head_hexsha": "856b833e7c6cbfe389b2ec1b21edb5d6e6ee97e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-09-25T16:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:21:35.000Z", "max_issues_repo_path": "src/cfrops_collect.jl", "max_issues_repo_name": "ajkeith/Cyber-Air-Defense", "max_issues_repo_head_hexsha": "856b833e7c6cbfe389b2ec1b21edb5d6e6ee97e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-08T14:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T00:42:16.000Z", "max_forks_repo_path": "src/cfrops_collect.jl", "max_forks_repo_name": "ajkeith/CFR_ICADS", "max_forks_repo_head_hexsha": "856b833e7c6cbfe389b2ec1b21edb5d6e6ee97e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-25T16:52:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T16:52:02.000Z", "avg_line_length": 40.9919571046, "max_line_length": 414, "alphanum_fraction": 0.6321451929, "num_tokens": 11029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2392746598334529}} {"text": "import Base: divgcd, numerator, denominator, string, show, ==, hastypemax,\n iszero, isone, <, <=, cmp, widen, promote_rule, isinteger, BigFloat,\n +, -, *, /, //, ^, inv, div, fld, cld, trunc, floor, ceil, round, rem, mod,\n read, write, sign, signbit, typemax, typemin, copysign, flipsign,\n abs, fma, gcd, gcdx, lcm, decompose, power_by_squaring, big\n\nimport Base.GMP: ClongMax, CulongMax, CdoubleMax\n\n\nconst ClongSmall = Clong === Int64 ? Union{Int8,Int16,Int32} : Union{Int8,Int16}\nconst CulongSmall = Culong === UInt64 ? Union{UInt8,UInt16,UInt32} : Union{UInt8,UInt16}\n\n## Construction\n\nBigRational(x::BigRational) = x\n\nBigRational(x::Clong) = MPQ.set_si(x, one(Culong))\nBigRational(x::ClongSmall) = BigRational(Clong(x))\nBigRational(x::Culong) = MPQ.set_ui(x, one(Culong))\nBigRational(x::CulongSmall) = BigRational(Culong(x))\nBigRational(x::BigInt) = MPQ.set_z(x)\nBigRational(x::Bool) = MPQ.set_si(Int(x), one(Culong))\nBigRational(x::Integer) = BigRational(BigInt(x))\n\nBigRational(x::Rational) = MPQ.set_den!(BigRational(numerator(x)), denominator(x))\n\nfunction BigRational(x::Clong, y::Culong)\n g = gcd(unsigned(abs(x)), y)\n num = div(x, g)\n den = div(y, g)\n MPQ.set_si(num, den)\nend\nBigRational(x::ClongMax, y::CulongMax) = BigRational(Clong(x), Culong(y))\nfunction BigRational(x::ClongSmall, y::ClongMax)\n num = flipsign(Clong(x), y)\n den = unsigned(abs(y))\n BigRational(num, den)\nend\nfunction BigRational(x::Clong, y::ClongSmall)\n BigRational(unsigned(abs(x)), flipsign(Clong(y),x))\nend\nfunction BigRational(x::Clong, y::Clong)\n if y < 0\n if x < 0\n BigRational(unsigned(-x), unsigned(-y))\n else\n BigRational(-x, unsigned(-y))\n end\n else\n BigRational(x, unsigned(y))\n end\nend\n\nfunction BigRational(x::Culong, y::Culong)\n num, den = divgcd(x, y)\n MPQ.set_ui(num, den)\nend\nBigRational(x::CulongMax, y::CulongMax) = BigRational(Culong(x), Culong(y))\nfunction BigRational(x::CulongSmall, y::ClongMax)\n y < 0 && return BigRational(-(x%Clong), unsigned(-y))\n BigRational(x, unsigned(y))\nend\nfunction BigRational(x::Culong, y::ClongMax)\n if y < 0\n if x <= typemax(Int)\n BigRational(-(x%Clong), unsigned(-y))\n else\n MPQ.inv!(BigRational(y, x))\n end\n else\n BigRational(x, unsigned(y))\n end\nend\n\nfunction BigRational(x::Integer, y::Bool)\n y ? BigRational(x) : MPQ.set_si(Clong(sign(x)), Base.Checked.checked_div(y, x)%Culong)\nend\nfunction BigRational(x::Bool, y::Integer)\n if !(x && iszero(y))\n if x\n MPQ.inv!(BigRational(y))\n else\n MPQ.set_si(0, 1)\n end\n else\n MPQ.set_si(1, 0)\n end\nend\nfunction BigRational(x::Bool, y::Bool)\n y ? BigRational(x) : MPQ.set_si(1, Base.Checked.checked_div(y, x)%UInt)\nend\n\nfunction BigRational(x::Integer, y::Integer)\n iszero(y) && return MPQ.set_si(Clong(sign(x)), 0)\n MPQ.canonicalize!(MPQ.set_den!(BigRational(x), BigInt(y)))\nend\n\nfunction BigRational(x::Cdouble)\n isnan(x) && throw(InexactError(:BigRational, BigRational, x))\n isinf(x) && return MPQ.set_si(Clong(sign(x)), 0)\n MPQ.set_d(x)\nend\nBigRational(x::CdoubleMax) = BigRational(Cdouble(x))\nfunction BigRational(x::AbstractFloat)\n BigRational(rationalize(BigInt, BigFloat(x)))\nend\n\n\n## Rational functions\n\nnumerator(x::BigRational) = MPQ.get_num(x)\ndenominator(x::BigRational) = MPQ.get_den(x)\n# numerator(x::BigRational) = unsafe_load(Ptr{BigInt}(pointer_from_objref(x)), 1)\n# denominator(x::BigRational) = unsafe_load(Ptr{BigInt}(pointer_from_objref(x)), 2)\n\n@static if VERSION >= v\"1.5.0-rc1\"\n Rational{BigInt}(x::BigRational) = Base.unsafe_rational(BigInt, numerator(x), denominator(x))\n function Rational{T}(x::BigRational) where {T <: Integer}\n Base.unsafe_rational(convert(T, numerator(x)), convert(T, denominator(x)))\n end\nelse\n Rational{BigInt}(x::BigRational) = Rational{BigInt}(numerator(x), denominator(x))\n function Rational{T}(x::BigRational) where {T <: Integer}\n Rational{T}(convert(T, numerator(x)), convert(T, denominator(x)))\n end\nend\nRational(x::BigRational) = Rational{BigInt}(x)\n\nisinteger(x::BigRational) = isone(denominator(x))\n\n## Conversions and promotions\n\n@static if VERSION >= v\"1.1.0-rc1\"\n function BigFloat(x::BigRational, r::Base.MPFR.MPFRRoundingMode=Base.MPFR.ROUNDING_MODE[]; precision::Integer=Base.MPFR.DEFAULT_PRECISION[])\n Base.MPFR.setprecision(BigFloat, precision) do\n Base.MPFR.setrounding_raw(BigFloat, r) do\n BigFloat(numerator(x)) / BigFloat(denominator(x))\n end\n end\n end\nelse\n BigFloat(x::BigRational) = BigFloat(numerator(x)) / BigFloat(denominator(x))\nend\nfunction (::Type{T})(x::BigRational) where T<:AbstractFloat\n convert(T, convert(T, numerator(x)) / convert(T, denominator(x)))\nend\n\nBool(x::BigRational) = iszero(x) ? false : isone(x) ? true :\n throw(InexactError(:Bool, Bool, x)) # to resolve ambiguity\nfunction (::Type{T})(x::BigRational) where {T<:Integer}\n isinteger(x) ? convert(T, numerator(x)) : throw(InexactError(nameof(T), T, x))\nend\n\npromote_rule(::Type{BigRational}, ::Union{Type{<:Integer},Type{<:Rational}}) = BigRational\npromote_rule(::Type{BigRational}, ::Type{<:AbstractFloat}) = BigFloat\n\n\n## Comparisons\n\nfor (op1, op2) in ((:(==), :iszero), (:cmp, :sign))\n @eval begin\n $op1(x::BigRational, y::Rational{<:CulongMax}) = $op2(MPQ.cmp_ui(x, numerator(y), denominator(y)))\n $op1(x::BigRational, y::Rational{<:ClongMax}) = $op2(MPQ.cmp_si(x, numerator(y), denominator(y)))\n $op1(x::BigRational, y::ClongMax) = $op2(MPQ.cmp_si(x, Clong(y), one(Culong)))\n $op1(x::BigRational, y::CulongMax) = $op2(MPQ.cmp_ui(x, Culong(y), one(Culong)))\n $op1(x::BigRational, y::BigInt) = $op2(MPQ.cmp_z(x, y))\n $op1(x::BigRational, y::Bool) = $op1(x, Clong(y))\n $op1(x::BigRational, y::Integer) = $op1(x, BigInt(y))\n end\nend\n\n==(x::BigRational, y::BigRational) = MPQ.equal(x, y)\nfunction ==(x::BigRational, y::Rational)\n numerator(x) == numerator(y) && denominator(x) == denominator(y)\nend\n==(x::Union{Rational,Integer}, y::BigRational) = y == x\ncmp(x::BigRational, y::BigRational) = sign(MPQ.cmp(x, y))\ncmp(x::BigRational, y::Rational{BigInt}) = cmp(x, BigRational(y))\nfunction cmp(x::BigRational, y::Rational)\n cmp(denominator(y) * numerator(x), denominator(x) * numerator(y))\nend\n\ncmp(x::BigRational, y::Real) = cmp(numerator(x), y*denominator(x))\ncmp(y::Union{Rational,Real}, x::BigRational) = -cmp(x, y)\n\niszero(x::BigRational) = iszero(x.num_size)\nisone(x::BigRational) = isone(numerator(x)) && isone(denominator(x))\n\nfor op in (:(<), :(<=))\n for (T1, T2) in ((:BigRational, :Real), (:Real, :BigRational), (:BigRational, :BigRational))\n @eval $op(x::$T1, y::$T2) = isnan(x) ? false : isnan(y) ? false : ($op)(cmp(x,y), 0)\n end\nend\n\n\n## Arithmetic operations\n\n-(x::BigRational) = MPQ.neg(x)\n\nfor (op, gop) in ((:+, :add), (:-, :sub), (:*, :mul), (:/, :div), (://, :div))\n gop! = Symbol(gop, :!)\n @eval begin\n $op(x::BigRational, y::BigRational) = MPQ.$gop(x, y)\n function $op(x::BigRational, y::Union{Integer,Rational})\n z = BigRational(y) # z !== y by construction because !(y isa BigRational)\n MPQ.$gop!(z, x, z)\n end\n function $op(x::Union{Integer,Rational}, y::BigRational)\n z = BigRational(x) # z !== x by construction because !(x isa BigRational)\n MPQ.$gop!(z, z, y)\n end\n end\nend\n\n^(x::Number, y::BigRational) = x^(float(y))\n^(::Irrational{:ℯ}, x::BigRational) = exp(x) # to avoid ambiguity\n^(x::T, y::BigRational) where {T<:AbstractFloat} = x^convert(T,y)\n^(z::Complex{T}, p::BigRational) where {T<:Real} = z^convert(typeof(one(T)^p), p)\n^(z::Complex{BigRational}, n::Bool) = n ? z : one(z) # to resolve ambiguity\nfunction ^(z::Complex{BigRational}, n::Integer)\n n >= 0 ? Base.power_by_squaring(z, n) : power_by_squaring(inv(z), -n)\nend\n# All previous functions on ^ are taken from base/rational.jl\n\nfunction power_by_squaring(x::BigRational, p::Integer)\n if p <= 2\n if p == 1\n return x\n elseif p == 0\n return one(BigRational)\n elseif p == 2\n return x*x\n elseif p == -1\n return inv(x)\n else\n return power_by_squaring(inv(x), -p)\n end\n end\n t = trailing_zeros(p) + 1\n p >>= t\n z = MPQ.set(x)\n while (t -= 1) > 0\n MPQ.mul!(z, z)\n end\n y = MPQ.set(z)\n while p > 0\n t = trailing_zeros(p) + 1\n p >>= t\n while (t -= 1) >= 0\n MPQ.mul!(z, z)\n end\n MPQ.mul!(y, z)\n end\n return y\nend\n\ninv(x::BigRational) = MPQ.inv(x)\n\n# The next few functions might need to be optimized\nfor op in (:rem, :mod)\n @eval begin\n function $op(x::BigRational, y::Integer)\n den = denominator(x)\n BigRational($op(numerator(x), den * y), den)\n end\n function $op(x::Integer, y::BigRational)\n den = denominator(y)\n BigRational($op(x * den, numerator(y)), den)\n end\n end\n for (T1, T2) in ((:Rational, :BigRational), (:BigRational, :Rational), (:BigRational, :BigRational))\n @eval begin\n function $op(x::$T1, y::$T2)\n den = denominator(x)\n xd, yd = divgcd(den, denominator(y))\n BigRational($op(numerator(x)*yd, numerator(y)*xd), den*yd)\n end\n end\n end\nend\n\nconst nmissingtype = VERSION >= v\"1.3.0-rc1\" ? Base.nonmissingtype_checked : Base.nonmissingtype\n@static if VERSION >= v\"1.4.0-rc1\"\n\n function div(x::BigRational, y::Integer, r::RoundingMode)\n xn, yn = divgcd(numerator(x), y)\n div(xn, denominator(x) * yn, r)\n end\n function div(x::Integer, y::BigRational, r::RoundingMode)\n xn, yn = divgcd(x, numerator(y))\n div(xn * denominator(y), yn, r)\n end\n function round(::Type{T}, x::BigRational, r::RoundingMode=RoundNearest) where T\n if iszero(denominator(x)) && !(T <: Integer)\n return convert(T, Rational{Int32}(sign(numerator(x)), 0))\n end\n convert(T, div(numerator(x), denominator(x), r))\n end\n for (T1, T2) in ((:Rational, :BigRational), (:BigRational, :Rational), (:BigRational, :BigRational))\n @eval begin\n function div(x::$T1, y::$T2, r::RoundingMode)\n xn, yn = divgcd(numerator(x), numerator(y))\n xd, yd = divgcd(denominator(x), denominator(y))\n div(xn * yd, xd * yn, r)\n end\n end\n end\n for (S, T) in ((BigRational, Integer), (Integer, BigRational), (BigRational, BigRational))\n @eval begin\n div(x::$S, y::$T) = div(x, y, RoundToZero)\n fld(x::$S, y::$T) = div(x, y, RoundDown)\n cld(x::$S, y::$T) = div(x, y, RoundUp)\n end\n end\n\nelse\n\n function round(::Type{T}, x::BigRational, ::RoundingMode{:ToZero}) where T\n convert(T, div(numerator(x), denominator(x)))\n end\n function round(::Type{T}, x::BigRational, ::RoundingMode{:Down}) where T\n convert(T, fld(numerator(x), denominator(x)))\n end\n function round(::Type{T}, x::BigRational, ::RoundingMode{:Up}) where T\n convert(T, cld(numerator(x), denominator(x)))\n end\n function round(::Type{T}, x::BigRational, ::RoundingMode{:Nearest}) where T\n if T <: Integer\n if iszero(denominator(x))\n throw(DivideError())\n end\n elseif iszero(denominator(x))\n return convert(T, Rational{Int32}(sign(numerator(x)), 0))\n end\n q,r = divrem(numerator(x), denominator(x))\n s = q\n if abs(r) >= abs((denominator(x)-copysign(BigInt(4), numerator(x))+one(BigInt)+iseven(q))>>1 + copysign(BigInt(2), numerator(x)))\n s += copysign(one(BigInt), numerator(x))\n end\n convert(T, s)\n end\n function round(::Type{T}, x::BigRational) where T\n round(T, x, RoundNearest)\n end\n for S in (:(RoundingMode{:Up}), :(RoundingMode{:Down}), :(RoundingMode{:ToZero}), :(RoundingMode{:Nearest}))\n @eval begin\n function round(::Type{T}, x::BigRational, r::$S) where {T>:Missing}\n round(nmissingtype(T), x, r)\n end # to avoid ambiguities\n end\n end\n\n for op in (:div, :fld, :cld)\n @eval begin\n function $op(x::BigRational, y::Integer)\n xn, yn = divgcd(numerator(x), y)\n $op(xn, denominator(x) * yn)\n end\n function $op(x::Integer, y::BigRational)\n xn, yn = divgcd(x, numerator(y))\n $op(xn * denominator(y), yn)\n end\n end\n for (T1, T2) in ((:Rational, :BigRational), (:BigRational, :Rational), (:BigRational, :BigRational))\n @eval begin\n function $op(x::$T1, y::$T2)\n xn, yn = divgcd(numerator(x), numerator(y))\n xd, yd = divgcd(denominator(x), denominator(y))\n $op(xn * yd, xd * yn)\n end\n end\n end\n end\n\nend\n\ntrunc(::Type{T}, x::BigRational) where {T} = round(T, x, RoundToZero)\nfloor(::Type{T}, x::BigRational) where {T} = round(T, x, RoundDown)\nceil(::Type{T}, x::BigRational) where {T} = round(T, x, RoundUp)\n\nfor f in (:ceil, :floor, :trunc)\n @eval begin\n $f(::Type{T}, x::BigRational) where {T>:Missing} = $f(nmissingtype(T), x)\n end # to avoid ambiguity\nend\nfunction round(::Type{T}, x::BigRational, r::RoundingMode) where {T>:Missing}\n round(nmissingtype(T), x, r)\nend # to avoid ambiguities\nfunction round(::Type{T}, x::BigRational) where {T>:Missing}\n round(T, x, RoundNearest)\nend # to avoid ambiguities\nround(x::BigRational, r::RoundingMode=RoundNearest) = round(BigRational, x, r)\n\n\nfunction gcd(x::BigRational, y::BigRational)\n BigRational(gcd(numerator(x), numerator(y)), lcm(denominator(x), denominator(y)))\nend\nfunction lcm(x::BigRational, y::BigRational)\n BigRational(lcm(numerator(x), numerator(y)), gcd(denominator(x), denominator(y)))\nend\nfunction gcdx(x::BigRational, y::BigRational)\n c = gcd(x, y)\n num = numerator(c)\n den = denominator(c)\n if iszero(num)\n a, b = one(BigInt), zero(BigInt)\n elseif iszero(den)\n a = ifelse(iszero(denominator(x)), one(BigInt), den)\n b = ifelse(iszero(denominator(y)), one(BigInt), den)\n else\n _, a, b = gcdx(div(numerator(x), num) * div(den, denominator(x)),\n div(numerator(y), num) * div(den, denominator(y)))\n end\n c, a, b\nend\n\n\nsign(x::BigRational) = sign(numerator(x))\nsignbit(x::BigRational) = signbit(numerator(x))\n\ncopysign(x::BigRational, y::Real) = signbit(x) == signbit(y) ? x : -x\nflipsign(x::BigRational, y::Real) = signbit(y) ? -x : x\n@static if VERSION < v\"1.2.0-rc1\"\n copysign(x::BigRational, y::Unsigned) = abs(x)\n flipsign(x::BigRational, y::Unsigned) = x\nend\n\nabs(x::BigRational) = MPQ.abs(x)\n\n\n## IO operations\n\nfunction string(x::BigRational; base::Integer = 10, pad::Integer = 1)\n string(BigRational, '(' * string(numerator(x); base=base, pad=pad) * ',' *\n string(denominator(x); base=base, pad=pad) * ')')\nend\nfunction show(io::IO, x::BigRational)\n if get(io, :typeinfo, Any) == BigRational\n print(io, numerator(x), \"//\", denominator(x))\n else\n print(io, string(x))\n end\nend\n\nfunction read(io::IO, ::Type{BigRational})\n num = read(s, BigInt)\n den = read(s, BigInt)\n BigRational(num, den)\nend\nfunction write(io::IO, x::BigRational)\n write(io, numerator(x), denominator(x))\nend\n\n\n## Other functions\n\nwiden(::Type{BigRational}) = BigRational\n\nbig(::Type{BigRational}) = BigRational\nbig(x::BigRational) = x\n\nhastypemax(::Type{BigRational}) = true\ntypemax(::Type{BigRational}) = BigRational(1,0)\ntypemin(::Type{BigRational}) = BigRational(-1,0)\n\ndecompose(x::BigRational) = numerator(x), 0, denominator(x)\n\nfunction fma(x::BigRational, y::BigRational, z::BigRational)\n MPQ.add!(MPQ.mul(x, y), z)\nend\n\nfunction Base.deepcopy_internal(x::BigRational, stackdict::IdDict)\n if haskey(stackdict, x)\n return stackdict[x]\n end\n y = MPQ.set(x)\n stackdict[x] = y\n return y\nend\n", "meta": {"hexsha": "3f15d9e3e771a2aa2f0e2d28cebf37801d893f8d", "size": 16369, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "Liozou/BigRationals.jl", "max_stars_repo_head_hexsha": "8ca8c58c55f565693db6706209861e8c078493b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "Liozou/BigRationals.jl", "max_issues_repo_head_hexsha": "8ca8c58c55f565693db6706209861e8c078493b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "Liozou/BigRationals.jl", "max_forks_repo_head_hexsha": "8ca8c58c55f565693db6706209861e8c078493b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1020833333, "max_line_length": 144, "alphanum_fraction": 0.6050461238, "num_tokens": 5163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23914545451109062}} {"text": "\n# This file is part of Similitude.jl\n# It is licensed under the MIT license\n# Similitude Copyright (C) 2022 Michael Reed\n# _ _ _\n# | | | | | |\n# ___| |__ __ _| | ___ __ __ ___ ____ _| | __ _\n# / __| '_ \\ / _` | |/ / '__/ _` \\ \\ / / _` | |/ _` |\n# | (__| | | | (_| | <| | | (_| |\\ V / (_| | | (_| |\n# \\___|_| |_|\\__,_|_|\\_\\_| \\__,_| \\_/ \\__,_|_|\\__,_|\n#\n# https://github.com/chakravala\n# https://crucialflow.com\n\nexport AbelianGroup, Dimension, 𝟙, normal\nexport UnitSystems, Quantity, Group, LogGroup, ExpGroup\nexport universe, Universe, unitname, normal, logdb, expdb, dB\n\nfor i ∈ 1:dims\n @eval export $(Symbol(isq[i]))\nend\n\nfor unit ∈ Dimensionless\n @eval @pure $unit(C::Coupling) = UnitSystems.$unit(C)\n @eval @pure $unit(U::UnitSystem) = UnitSystems.$unit(universe(U))\nend\n\nfor u ∈ (Constants...,Physics...)\n u∉(:permeability,:gaussgravitation) && @eval const $u = UnitSystems.$u(SI)\nend\n\nconst hyperfine = SI2019(ΔνCs,inv(T))\nconst hubble = Hubble(𝟏,inv(T))\nconst cosmological = 𝟑*ΩΛ*(hubble/lightspeed(Hubble))^2\nconst eddington = Cosmological(𝟏,M)(QCD)\nconst solarmass = IAU(𝟏,M)\nconst earthmass = Metric(GME/G,M)(IAU)\nconst jupitermass = Metric(GMJ/G,M)(IAU)\nconst lunarmass = earthmass/μE☾\nconst gforce = English(𝟏,specificforce)\nconst atmosphere = Metric(atm,pressure)\nconst loschmidt = atmosphere(SI2019)/SI2019(T₀,Θ)/boltzmann(SI2019)\nconst amagat = loschmidt(SI2019)/avogadro(SI2019)\nconst wienwavelength = planck(SI)*lightspeed(SI)/boltzmann(SI)/Constant(4.965114231744276303)\nconst wienfrequency = Constant(2.821439372122078893)*boltzmann(SI)/planck(SI)\n@pure (::typeof(loschmidt))(U::UnitSystem,P=atmosphere(U),T=SI2019(T₀,Θ)(U)) = U(P,pressure)/U(T,Θ)/boltzmann(U)\n@pure mechanicalheat(U::UnitSystem) = molargas(U)*U(normal(calorie(Metric)/molargas(Metric)),Θ*N)\n\n# angle\n\n#const radian = MetricEngineering(𝟏,A)\nconst spatian = MetricSpatian(𝟏,A)\nconst steradian = MetricEngineering(𝟏,solidangle)\nconst degree = MetricDegree(𝟏,A)\nconst squaredegree = MetricDegree(𝟏,solidangle)\nconst gradian = MetricGradian(𝟏,A)\nconst bradian = MetricEngineering(τ/𝟐^8,A)\nconst arcminute = MetricArcminute(𝟏,A)\nconst arcsecond = MetricArcsecond(𝟏,A)\n\n# length\n\nconst meter = Metric(𝟏,L)\nconst angstrom = hecto*pico*meter\nconst inch = IPS(𝟏,L)\n#const rackunit = foot*𝟕/𝟐^4/𝟑\nconst foot = English(𝟏,L)\nconst surveyfoot = Survey(𝟏,L)\nconst yard = 𝟑*foot\nconst mile = English(𝟐^5*𝟑*𝟓*𝟏𝟏,L)\nconst statutemile = Survey(𝟐^5*𝟑*𝟓*𝟏𝟏,L)\nconst earthradius = sqrt(earthmass(Metric)*gravitation(Metric)/gforce(Metric))\nconst greatcircle = τ*earthradius\nconst earthmeter = Meridian(𝟏,L)\nconst nauticalmile = Nautical(𝟏,L)\nconst admiraltymile = English(𝟐^6*𝟓*𝟏𝟗,L)\nconst meridianmile = Metric(𝟐^4*𝟓^5/𝟑^3,L)\nconst astronomicalunit = IAU(𝟏,L)\nconst lunardistance = IAUE(𝟏,L)(IAU)\nconst jupiterdistance = IAUJ(𝟏,L)(IAU)\nconst parsec = astronomicalunit*(𝟐^7*𝟑^4*𝟓^3/τ)\n\n#time\n\nconst second = Metric(𝟏,T)\nconst minute = (𝟐^2*𝟑*𝟓)*second\nconst hour = (𝟐^2*𝟑*𝟓)*minute\nconst day = IAU(𝟏,T)\nconst year = IAU(aⱼ,T)\nconst lightyear = year*lightspeed(IAU)\nconst radarmile = 𝟐*nauticalmile(Metric)/lightspeed(Metric)\nconst gaussgravitation = sqrt(normal(gravitation(IAU)))*radian(IAU)/day(IAU)\nconst gaussianyear = turn(IAU)/gaussgravitation\nconst siderealyear = gaussianyear/√(solarmass+earthmass+lunarmass).v\nconst gaussianmonth = τ/sqrt(normal(gravitation(IAUE)))*day\nconst siderealmonth = gaussianmonth/normal(sqrt(earthmass(IAUE)+lunarmass(IAUE)))\nconst synodicmonth = inv(inv(siderealmonth(IAU))-inv(siderealyear(IAU)))\nconst jovianyear = τ*sqrt(normal(jupiterdistance^3/solarmass/gravitation(IAU)))*day/normal(sqrt(solarmass+jupitermass))\n\n# area\n\nconst barn = Metric((𝟐*𝟓)^-28,area)\nconst hectare = Metric(hecto*hecto,area)\nconst acre = MPH(𝟐^-7/𝟓,area)(English)\nconst surveyacre = Survey(𝟐^3*𝟑^2*𝟓*𝟏𝟏^2,area)\n#const township = 𝟐^9*𝟑^2*𝟓*surveyacre\n#const footballfield = English(𝟐^8*𝟑^2*𝟓^2,area)\n\n# volume\n\nconst gallon = IPS(𝟑*𝟕*𝟏𝟏,volume)\nconst liter = Metric(milli,volume)\nconst quart = gallon/𝟐^2\nconst pint = quart/𝟐\nconst cup = pint/𝟐\nconst fluidounce = cup/𝟐^3\nconst teaspoon = 𝟓*milli*liter\nconst tablespoon = 𝟑*teaspoon\n#const oilbarrel = 𝟐*𝟑*𝟕*gallon\n\n# speed\n\nconst bubnoff = meter(Metric)/year(Metric)\nconst ips = IPS(𝟏,speed)\nconst fps = British(𝟏,speed)\nconst fpm = foot(British)/minute(British)\nconst ms = Metric(𝟏,speed)\nconst kmh = kilo*meter/hour\nconst mph = MPH(𝟏,speed)\nconst knot = Nautical(𝟏,speed)\nconst mps = mile(MPH)/second(MPH)\n\n# mass\n\nconst gram = Metric(milli,M)\nconst earthgram = Meridian(milli,M)\nconst kilogram = Metric(𝟏,M)\nconst tonne = Metric(kilo,M)\nconst ton = English(𝟐*kilo,M)\nconst pound = English(𝟏,M)\nconst ounce = English(𝟐^-4,M)\nconst grain = milli*pound/𝟕\nconst slug = British(𝟏,M)\nconst slinch = IPS(𝟏,M)\nconst hyl = GravitationalMetric(𝟏,M)\n\n# force\n\nconst dyne = Gauss(𝟏,force)\nconst newton = Metric(𝟏,force)\nconst poundal = FPS(𝟏,force)\nconst kilopond = MetricEngineering(𝟏,force)\nconst poundforce = English(𝟏,F)\n\n# pressure\n\nconst psi = IPS(𝟏,pressure)\nconst bar = Metric(hecto*kilo,pressure)\nconst barye = Gauss(𝟏,pressure)\nconst pascal = Metric(𝟏,pressure)\nconst technicalatmosphere = kilopond/(centi*meter(ME))^2\nconst inchmercury = Metric(inv(inHg),pressure)\nconst torr = Metric(atm/𝟐^3/𝟓/𝟏𝟗,pressure)\n\n# energy\n\nconst erg = Gauss(𝟏,energy)\nconst joule = Metric(𝟏,energy)\nconst footpound = poundforce*foot\nconst meancalorie = InternationalMean(𝟐^2*𝟓*𝟑^2/𝟒𝟑,energy)(Metric)\nconst kilocalorie = International(𝟐^5*𝟓^4*𝟑^2/𝟒𝟑,energy)(Metric)\nconst calorie = kilocalorie*milli\nconst earthcalorie = mechanicalheat(Meridian)\nconst thermalunit = mechanicalheat(English)\nconst tontnt = giga*calorie(Metric)\nconst gasgallon = 𝟐*𝟑*𝟏𝟗*kilo*thermalunit(Metric)\n\n# power\n\nconst watt = Metric(𝟏,power)\nconst horsepower = British(𝟐*𝟓^2*𝟏𝟏,power)\nconst horsepowerwatt = British(𝟐^4*𝟑^3/𝟓*τ,power)\nconst horsepowermetric = GM(𝟑*𝟓^2,power)\nconst tonsrefrigeration = thermalunit(Metric)/Metric(𝟑/𝟐/𝟓,T)\nconst boilerhorsepower = Constant(1339)/Metric(𝟐^4*𝟑^2,T)*thermalunit(Metric)\nconst electricalhorsepower = Metric(Constant(746),power)\n\n# electromagnetic\n\nconst coulomb = Metric(𝟏,Q)\nconst ampere = Metric(𝟏,current)\nconst volt = Metric(𝟏,electricpotential)\nconst henry = Metric(𝟏,inductance)\nconst ohm = Metric(𝟏,resistance)\nconst siemens = Metric(𝟏,conductance)\nconst farad = Metric(𝟏,capacitance)\nconst weber = Metric(𝟏,magneticflux)\nconst tesla = Metric(𝟏,magneticfluxdensity)\nconst statcoulomb = ESU(𝟏,Q)\nconst statampere = ESU(𝟏,current)\nconst statvolt = ESU(𝟏,electricpotential)\nconst stathenry = ESU(𝟏,inductance)\nconst statohm = ESU(𝟏,resistance)\nconst statmho = ESU(𝟏,conductance)\nconst statfarad = ESU(𝟏,capacitance)\nconst statweber = ESU(𝟏,magneticflux)\nconst stattesla = ESU(𝟏,magneticfluxdensity)\nconst abcoulomb = EMU(𝟏,Q)\nconst abampere = EMU(𝟏,current)\nconst abvolt = EMU(𝟏,electricpotential)\nconst abhenry = EMU(𝟏,inductance)\nconst abohm = EMU(𝟏,resistance)\nconst abmho = EMU(𝟏,conductance)\nconst abfarad = EMU(𝟏,capacitance)\nconst maxwell = EMU(𝟏,magneticflux)\nconst gauss = EMU(𝟏,magneticfluxdensity)\nconst oersted = EMU(𝟏,magneticfield)\nconst gilbert = EMU(𝟏/𝟐/τ,current/A)\nconst earthcoulomb = Meridian(𝟏,Q)\nconst electronvolt = elementarycharge(SI2019)*SI2019(𝟏,electricpotential)\n\n# temperature\n\n#const freezing = Metric(T₀-milli,Θ)\nconst boiling = Metric(T₀+Constant(99.9839),Θ)\nconst sealevel = Metric(T₀+𝟑*𝟓,Θ)\nconst kelvin = Metric(𝟏,Θ)\nconst celsius = Metric(T₀,Θ)\nconst rankine = English(𝟏,Θ)\nconst fahrenheit = English(Constant(459.67),Θ)\n#const delisle = Metric(𝟐/𝟑,Θ)\n#const reaumur = Metric(𝟓/𝟐^2,Θ)\n\n# mole\n\nconst mole = Metric(𝟏,N)\nconst earthmole = Meridian(𝟏,N)\nconst poundmole = English(𝟏,N)\nconst slugmole = British(𝟏,N)\nconst slinchmole = IPS(𝟏,N)\n\n# photometric\n\nconst lumen = Metric(𝟏,luminousflux)\nconst candela = Metric(𝟏,luminousintensity)\nconst lux = Metric(𝟏,illuminance)\nconst phot = Gauss(𝟏,illuminance)\nconst footcandle = English(𝟏,illuminance)\nconst nit = Metric(𝟏,luminance)\nconst apostilb = Metric(𝟐/τ,luminance)\nconst stilb = Gauss(𝟏,luminance)\nconst lambert = Gauss(𝟐/τ,luminance)\nconst footlambert = English(𝟐/τ,luminance)\nconst bril = centi*nano*lambert\nconst talbot = Metric(𝟏,luminousenergy)\nconst lumerg = Gauss(centi^2*milli,luminousenergy)\nconst rayleigh = Metric(deka*giga,photonirradiance)\nconst flick = Metric(deka*giga,radiance/L)\n\n@pure neper(U::UnitSystem) = U(𝟏,log(𝟙))\n@pure bel(U::UnitSystem) = U(𝟏,log10(𝟙))\n@pure decibel(U::UnitSystem) = U(𝟏,dB(𝟙))\nconst hertz = inv(second(Metric))\nconst apm = inv(minute(Metric))\nconst rpm = turn(Metric)/minute(Metric)\n#const rpd = turn(Metric)/day(Metric)\nconst galileo = Gauss(𝟏,specificforce)\nconst eotvos = Gauss(nano,specificforce/L)\nconst poise = Gauss(𝟏,viscosity)\nconst reyn = IPS(𝟏,viscosity)\nconst diopter = Metric(𝟏,angularwavenumber)\nconst kayser = Gauss(𝟏,wavenumber)\nconst darcy = Gauss(milli/atm,area)\nconst stokes = Gauss(𝟏,diffusivity)\nconst katal = Metric(𝟏,catalysis)\nconst mpge = mile(Metric)/gasgallon(Metric)\nconst curie = Constant(37)*giga*hertz\nconst sievert = Metric(𝟏,energy/M)\n#const rem = centi*sievert\nconst roentgen = ESU(𝟏,chargedensity)(Metric)/Metric(Constant(1.293),density)\nconst rayl = Metric(𝟏,specificimpedance)\nconst langley = calorie(Metric)/(centi*meter(Metric))^2\nconst jansky = Metric((𝟐*𝟓)^-26,fluence)\nconst solarflux = hecto*hecto*jansky\n\nfor CAL ∈ (:calₜₕ,:cal₄,:cal₁₀,:cal₂₀,:calₘ,:calᵢₜ)\n KCAL = Symbol(:k,CAL)\n @eval const $CAL = SI(UnitSystems.$CAL,energy)\n @eval const $KCAL = SI(UnitSystems.$KCAL,energy)\nend\n\n#const H0 = hubble\n\nevaldim(::typeof(angle)) = A\nevaldim(::typeof(length)) = L\nevaldim(::typeof(time)) = T\nevaldim(::typeof(molarmass)) = M/N\nevaldim(::typeof(luminousefficacy)) = T*J/F/L\nevaldim(::typeof(UnitSystems.solidangle)) = A^2\nevaldim(unit::Dimension) = unit\nevaldim(unit::Symbol) = evaldim(eval(unit))\nevaldim(unit::Symbol,U) = evaldim(evaldim(unit),U)\nevaldim(unit,U) = normal(U)(unit)\n\n(::typeof(molarmass))(U::UnitSystem,S::UnitSystem) = (M/N)(U,S)\n(::typeof(luminousefficacy))(U::UnitSystem,S::UnitSystem) = (T*J/F/L)(U,S)\n\ndimlist(text,dim) = \"$text : [$(evaldim(dim))], [$(evaldim(dim,British))], [$(evaldim(dim,Metric))], [$(evaldim(dim,EMU))], [$(evaldim(dim,ESU))]\"\ndimlist(U) = join(dimtext(normal(U)) == isq ? isodim.(Ref(U),usq) : unitdim.(Ref(U),usq), \", \")\nisodim(U,D) = (UD = U(D); D==UD ? \"$D\" : \"$D=$UD\")\nunitdim(U,D) = (io = IOBuffer(); showgroup(io,U(D),U); \"$D=$(String(take!(io)))\")\n\nconvertext(unit,fun) = \"\"\"\n```Julia\n$(dimlist(unit,unit))\n$unit(U::UnitSystem,S::UnitSystem) = $fun\n$unit(v::Real,U::UnitSystem,S::UnitSystem) = v/$unit(U,S)\n$(evaldim(unit)(Unified))\n```\n\"\"\"\n\n@pure unitsym(x) = :nonstandard\n@pure unitsym(::typeof(𝟙)) = :dimensionless\n@pure unitsym(::typeof(A)) = :angle\nfor unit ∈ Convert\n if unit ∉ (:length,:time,:angle,:molarmass,:luminousefficacy)\n @eval @pure unitsym(::typeof($(eval(unit)))) = $(QuoteNode(unit))\n else\n @eval @pure unitsym(::typeof($(evaldim(unit)))) = $(QuoteNode(unit))\n end\nend\n\nfunction unitext(unit,text)\n dim = Dimension(eval(unit))\n sym = unitsym(dim)\n return \"\"\"\n```Julia\n$unit(U::UnitSystem) = $text\n$(dimlist(sym,dim))\n$(eval(unit)(Unified))\n```\n\"\"\"\nend\n\nsystext(sys,text) = \"\"\"\n```Julia\n$sys = $text\n$(dimlist(eval(sys)))\n```\n\"\"\"\n\n# 1,2,3,4, 5, 6, 7, 8,9,10,11\n#kB,ħ,𝘤,μ₀,mₑ,Mᵤ,Kcd,A,λ,αL,g₀\n# F,M,L,T, Q, Θ, N, J,A,R, C\n\nfunction (u::typeof(normal(MetricEngineering)))(d::Group)\n Group(Values(d.v[1],d.v[2],d.v[3],d.v[4],d.v[5],d.v[6],d.v[7],d.v[8],d.v[9],0,0))\nend\nfunction (u::typeof(normal(GravitationalMetric)))(d::Group)\n Group(Values(d.v[1]+d.v[2],0,d.v[3]-d.v[2],d.v[4]+2(d.v[2]),d.v[5],d.v[6],d.v[7],d.v[8],0,0,0))\nend\nfunction (u::typeof(normal(Metric)))(d::Group)\n Group(Values(0,d.v[1]+d.v[2],d.v[1]+d.v[3],d.v[4]-2(d.v[1]),d.v[5],d.v[6],d.v[7],d.v[8],0,0,0))\nend\nfunction (u::typeof(normal(MetricDegree)))(d::Group)\n Group(Values(0,d.v[1]+d.v[2],d.v[1]+d.v[3],d.v[4]-2(d.v[1]),d.v[5],d.v[6],d.v[7],d.v[8],d.v[9],0,0))\nend\n#=function (u::typeof(normal(Astronomical)))(d::Group)\n Group(Values(d.v[1],0,d.v[3]+3d.v[2],d.v[4]-2d.v[2],d.v[5],d.v[6],d.v[7],d.v[8],d.v[9],0,0))\nend=#\n\nfunction (u::typeof(normal(Gauss)))(d::Group{<:Integer})\n Group(Values(0,d.v[1]+d.v[2]+d.v[5]//2,d.v[1]+d.v[3]+(3//2)*d.v[5]+d.v[11],d.v[4]-2(d.v[1])-d.v[5]-d.v[11],0,d.v[6],d.v[7],d.v[8],0,0,0))\nend\nfunction (u::typeof(normal(ESU)))(d::Group{<:Integer})\n Group(Values(0,d.v[1]+d.v[2]+d.v[5]//2,d.v[1]+d.v[3]+(3//2)*d.v[5],d.v[4]-2(d.v[1])-d.v[5],0,d.v[6],d.v[7],d.v[8],0,0,0))\nend\nfunction (u::typeof(normal(EMU)))(d::Group{<:Integer})\n Group(Values(0,d.v[1]+d.v[2]+d.v[5]//2,d.v[1]+d.v[3]+d.v[5]//2,d.v[4]-2(d.v[1]),0,d.v[6],d.v[7],d.v[8],0,0,0))\nend\n\nfunction (u::typeof(normal(Gauss)))(d::Group)\n Group(Values(0,d.v[1]+d.v[2]+d.v[5]/2,d.v[1]+d.v[3]+(3/2)*d.v[5]+d.v[11],d.v[4]-2(d.v[1])-d.v[5]-d.v[11],0,d.v[6],d.v[7],d.v[8],0,0,0))\nend\nfunction (u::typeof(normal(ESU)))(d::Group)\n Group(Values(0,d.v[1]+d.v[2]+d.v[5]/2,d.v[1]+d.v[3]+(3/2)*d.v[5],d.v[4]-2(d.v[1])-d.v[5],0,d.v[6],d.v[7],d.v[8],0,0,0))\nend\nfunction (u::typeof(normal(EMU)))(d::Group)\n Group(Values(0,d.v[1]+d.v[2]+d.v[5]/2,d.v[1]+d.v[3]+d.v[5]/2,d.v[4]-2(d.v[1]),0,d.v[6],d.v[7],d.v[8],0,d.v[10],0))\nend\n\nfunction (u::typeof(normal(Stoney)))(d::Group)\n Group(Values(0,d.v[1]+d.v[2]+d.v[6]+d.v[7],0,d.v[3]+d.v[4]-d.v[1],d.v[5],0,0,d.v[8],0,0,0))\nend\nfunction (u::typeof(normal(Electronic)))(d::Group)\n Group(Values(0,0,0,d.v[3]+d.v[4]-d.v[1]-d.v[8],d.v[5],0,0,0,0,0,0))\nend\nfunction (u::typeof(normal(QCDoriginal)))(d::Group)\n Group(Values(0,d.v[2]+d.v[6]+d.v[7]+2(d.v[1]+d.v[8])-d.v[3]-d.v[4],0,0,d.v[5],0,0,0,0,0,0))\nend\nfunction (u::typeof(normal(Planck)))(d::Group)\n Group(Values(0,d.v[2]+d.v[6]+d.v[7]+2(d.v[1]+d.v[8])-d.v[3]-d.v[4],0,0,0,0,0,0,0,0,0))\nend\nfunction (u::typeof(normal(PlanckGauss)))(d::Group)\n Group(Values(0,d.v[2]+d.v[6]+d.v[7]+2(d.v[1]+d.v[8])-d.v[3]-d.v[4],0,0,d.v[5],0,0,0,0,0,0))\nend\nfunction (u::typeof(normal(Natural)))(d::Group)\n Group(Values(0,0,0,0,0,0,0,0,0,0,0))\nend\nfunction (u::typeof(normal(NaturalGauss)))(d::Group)\n Group(Values(0,0,0,0,d.v[5],0,0,0,0,0,0))\nend\n\nfunction (u::typeof(normal(Rydberg)))(d::Group)\n Group(Values(0,d.v[1]+d.v[2]+d.v[7],d.v[1]+d.v[3],d.v[4]-d.v[6]+2(d.v[8]-d.v[1]),d.v[5],0,0,0,0,0,0))\nend\nfunction (u::typeof(normal(Hartree)))(d::Group)\n Group(Values(0,0,d.v[3]+2(d.v[4]-d.v[6])-3(d.v[1])-4(d.v[8]),0,d.v[5],0,0,0,0,0,0))\nend\nfunction (u::typeof(normal(Hubble)))(d::Group)\n Group(Values(0,0,0,d.v[3]+d.v[4]-d.v[1]-d.v[8],d.v[5],0,0,0,0,0,0))\nend\nfunction (u::typeof(normal(Cosmological)))(d::Group)\n Group(Values(0,d.v[1]+d.v[2]+d.v[6]+d.v[7],0,d.v[3]+d.v[4]-d.v[1],d.v[5],0,0,d.v[8],0,0,0))\nend\nfunction (u::typeof(normal(CosmologicalQuantum)))(d::Group)\n Group(Values(0,d.v[2]+d.v[6]+d.v[7]+2(d.v[1]+d.v[8])-d.v[3]-d.v[4],0,0,d.v[5],0,0,0,0,0,0))\nend\n\nexport @unitdim, @unitgroup\n\n\"\"\"\n @unitgroup(U::UnitSystem,S::UnitSystem) -> (u::typeof(normal(U)))(d::Group) = normal(S)(d)\n\nImplements `Group` homomorphism for `U` in terms of existing specification from `S`.\n\"\"\"\nmacro unitgroup(U,S)\n :((u::typeof(normal($U)))(d::Group) = normal($S)(d))\nend\n\n#=@unitgroup SI2019 Metric\n@unitgroup SI1976 Metric\n@unitgroup Conventional Metric\n@unitgroup CODATA Metric\n@unitgroup International Metric\n@unitgroup InternationalMean Metric\n@unitgroup MTS Metric\n@unitgroup KKH Metric\n@unitgroup MPH Metric\n@unitgroup Nautical Metric\n@unitgroup Meridian Metric\n@unitgroup FFF Metric\n@unitgroup IAU Metric\n@unitgroup IAUE Metric\n@unitgroup IAUJ Metric=#\n\n@unitgroup MetricTurn MetricDegree\n@unitgroup MetricSpatian MetricDegree\n@unitgroup MetricGradian MetricDegree\n@unitgroup MetricArcminute MetricDegree\n@unitgroup MetricArcsecond MetricDegree\n@unitgroup LorentzHeaviside Gauss\n#@unitgroup Thomson EMU\n#@unitgroup Kennelly EMU\n@unitgroup Schrodinger Rydberg\n@unitgroup QCD Planck\n@unitgroup QCDGauss PlanckGauss\n#@unitgroup Cosmological Hubble\n\n#@unitgroup SI2019Engineering MetricEngineering\n#@unitgroup MeridianEngineering MetricEngineering\n#@unitgroup GravitationalSI2019 GravitationalMetric\n#@unitgroup GravitationalMeridian GravitationalMetric\n@unitgroup British GravitationalMetric\n@unitgroup English MetricEngineering\n@unitgroup Survey MetricEngineering\n@unitgroup IPS GravitationalMetric\n\n\"\"\"\n @unitdim(U::UnitSystem,F,M,L,T,Q,Θ,N,J=\"lm\",A=\"rad\")\n\nSpecify the `print` output for each base `Dimension` of `U::UnitSystem` with `String` input arguments `force`, `mass`, `length`, `time`, `charge`, `temperature`, `molaramount`, `luminousflux`, `angle`.\n```Julia\n@unitdim Gauss \"gf\" \"g\" \"cm\" \"s\" \"C\" \"K\" \"mol\"\n@unitdim Metric \"kgf\" \"kg\" \"m\" \"s\" \"C\" \"K\" \"mol\"\n@unitdim British \"lb\" \"slug\" \"ft\" \"s\" \"C\" \"°R\" \"slug-mol\"\n@unitdim IPS \"lb\" \"slinch\" \"in\" \"s\" \"C\" \"°R\" \"slinch-mol\"\n@unitdim FPS \"pdl\" \"lb\" \"ft\" \"s\" \"C\" \"°R\" \"lb-mol\"\n@unitdim English \"lbf\" \"lbm\" \"ft\" \"s\" \"C\" \"°R\" \"lb-mol\"\n@unitdim IAU☉ \"M☉f\" \"M☉\" \"au\" \"D\" \"C\" \"K\" \"mol\"\n```\nThese standard examples are some of the built-in defaults.\n\"\"\"\nmacro unitdim(U,F,M,L,T,Q,Θ,N,J=\"lm\",A=\"rad\",R=\"\",C=\"\")\n :(dimtext(::typeof(normal($U))) = Values($F,$M,$L,$T,$Q,$Θ,$N,$J,$A,$R,$C))\nend\n\n@unitdim Metric \"kgf\" \"kg\" \"m\" \"s\" \"C\" \"K\" \"mol\"\n@unitdim Meridian \"kegf\" \"keg\" \"em\" \"s\" \"eC\" \"K\" \"eg-mol\"\n@unitdim MetricTurn \"kgf\" \"kg\" \"m\" \"s\" \"C\" \"K\" \"mol\" \"lm\" \"τ\"\n@unitdim MetricSpatian \"kgf\" \"kg\" \"m\" \"s\" \"C\" \"K\" \"mol\" \"lm\" \"ς\"\n@unitdim MetricGradian \"kgf\" \"kg\" \"m\" \"s\" \"C\" \"K\" \"mol\" \"lm\" \"gon\"\n@unitdim MetricDegree \"kgf\" \"kg\" \"m\" \"s\" \"C\" \"K\" \"mol\" \"lm\" \"deg\"\n@unitdim MetricArcminute \"kgf\" \"kg\" \"m\" \"s\" \"C\" \"K\" \"mol\" \"lm\" \"amin\"\n@unitdim MetricArcsecond \"kgf\" \"kg\" \"m\" \"s\" \"C\" \"K\" \"mol\" \"lm\" \"asec\"\n@unitdim British \"lb\" \"slug\" \"ft\" \"s\" \"C\" \"°R\" \"slug-mol\"\n@unitdim English \"lbf\" \"lbm\" \"ft\" \"s\" \"C\" \"°R\" \"lb-mol\"\n@unitdim IPS \"lb\" \"slinch\" \"in\" \"s\" \"C\" \"°R\" \"slinch-mol\"\n@unitdim FPS \"pdl\" \"lb\" \"ft\" \"s\" \"C\" \"°R\" \"lb-mol\"\n@unitdim Gauss \"gf\" \"g\" \"cm\" \"s\" \"_\" \"K\" \"mol\"\n@unitdim IAU☉ \"M☉f\" \"M☉\" \"au\" \"D\" \"C\" \"K\" \"mol\"\n@unitdim IAUE \"MEf\" \"ME\" \"LD\" \"D\" \"C\" \"K\" \"mol\"\n@unitdim IAUJ \"MJf\" \"MJ\" \"JD\" \"D\" \"C\" \"K\" \"mol\"\n@unitdim MTS \"tf\" \"t\" \"m\" \"s\" \"C\" \"K\" \"mol\"\n@unitdim KKH \"kgf\" \"kg\" \"km\" \"h\" \"C\" \"K\" \"mol\"\n@unitdim MPH \"lbf\" \"lb\" \"mi\" \"h\" \"C\" \"°R\" \"lb-mol\"\n@unitdim Nautical \"kegf\" \"keg\" \"nm\" \"h\" \"eC\" \"K\" \"eg-mol\"\n@unitdim FFF \"firf\" \"fir\" \"fur\" \"ftn\" \"Inf\" \"°R\" \"fir-mol\"\n@unitdim Hartree \"F\" \"M\" \"a₀\" \"T\" \"𝘦\" \"Θ\" \"N\" \"J\"\n@unitdim QCDoriginal \"F\" \"mₚ\" \"L\" \"T\" \"𝘦\" \"Θ\" \"N\" \"J\"\n@unitdim QCD \"F\" \"mₚ\" \"L\" \"T\" \"Q\" \"Θ\" \"N\" \"J\"\n@unitdim QCDGauss \"F\" \"mₚ\" \"L\" \"T\" \"𝘦ₙ\" \"Θ\" \"N\" \"J\"\n@unitdim PlanckGauss \"F\" \"mP\" \"L\" \"T\" \"𝘦ₙ\" \"Θ\" \"N\" \"J\"\n@unitdim NaturalGauss \"F\" \"T\" \"L\" \"T\" \"𝘦ₙ\" \"Θ\" \"N\" \"J\"\n\n\"\"\"\n @unitdim(U::UnitSystem,S::UnitSystem) -> dimtext(::typeof(normal(U))) = dimtext(normal(S))\n\nSpecify the `print` output for each base `Dimension` of `U` upon prior existing `S` data.\n```Julia\n@unitdim EMU Gauss\n@unitdim ESU Gauss\n@unitdim LorentzHeaviside Gauss\n@unitdim SI2019 Metric\n@unitdim SI1976 Metric\n@unitdim CODATA Metric\n@unitdim Conventional Metric\n@unitdim International Metric\n@unitdim InternationalMean Metric\n@unitdim Survey English\n```\nThese standard examples are some of the built-in defaults.\n\"\"\"\nmacro unitdim(U,S)\n :(dimtext(::typeof(normal($U))) = dimtext(normal($S)))\nend\n\n@unitdim SI2019 Metric\n@unitdim SI1976 Metric\n@unitdim CODATA Metric\n@unitdim Conventional Metric\n@unitdim International Metric\n@unitdim InternationalMean Metric\n@unitdim MetricEngineering Metric\n@unitdim GravitationalMetric Metric\n#@unitdim SI2019Engineering MetricEngineering\n#@unitdim GravitationalSI2019 GravitationalMetric\n#@unitdim MeridianEngineering Meridian\n#@unitdim GravitationalMeridian Meridian\n@unitdim Survey English\n@unitdim EMU Gauss\n@unitdim ESU Gauss\n@unitdim LorentzHeaviside Gauss\n#@unitdim Thomson Gauss\n#@unitdim Kennelly Metric\n\n\"\"\"\n @unitdim(D,U,S) -> showgroup(io::IO,::typeof(U(D)),::typeof(normal(U))) = print(io,S)\n\nSpecify the `print` output `S::String` for derived `D::Dimension` in `U::UnitSystem`.\n```Julia\n@unitdim magneticflux Gauss \"Mx\"\n@unitdim magneticfluxdensity Gauss \"G\"\n@unitdim magneticfield Gauss \"Oe\"\n@unitdim frequency Metric \"Hz\"\n@unitdim force Metric \"N\"\n@unitdim pressure Metric \"Pa\"\n@unitdim energy Metric \"J\"\n@unitdim power Metric \"W\"\n@unitdim mass British \"slug\"\n@unitdim force FPS \"pdl\"\n```\nThese standard examples are some of the built-in defaults.\n\"\"\"\nmacro unitdim(D, U, S)\n :(showgroup(io::IO,::typeof($U($D)),::typeof(normal($U))) = print(io,$S))\nend\n\nfor U ∈ (:MetricEngineering,:GravitationalMetric)\n @eval begin\n @unitdim frequency $U \"Hz\"\n @unitdim frequencydrift $U \"Hz⋅s⁻¹\"\n @unitdim photonirradiance $U \"Hz⋅m⁻²\"\n @unitdim illuminance $U \"lx\"\n @unitdim luminousexposure $U \"lx⋅s\"\n showgroup(io::IO,::typeof(luminance),::typeof(normal($U))) = print(io,\"nt\")\n end\nend\nfor U ∈ (:MetricEngineering,:English,:Survey)\n @eval @unitdim specificforce $U \"g₀\"\nend\nfor U ∈ (:Metric, :SI2019, :CODATA, :Conventional, :International, :InternationalMean, :MetricTurn, :MetricSpatian, :MetricGradian, :MetricDegree, :MetricArcminute, :MetricArcsecond)\n @eval begin\n @unitdim frequency $U \"Hz\"\n @unitdim frequencydrift $U \"Hz⋅s⁻¹\"\n @unitdim photonirradiance $U \"Hz⋅m⁻²\"\n @unitdim force $U \"N\"\n @unitdim inv(force) $U \"N⁻¹\"\n @unitdim pressure $U \"Pa\"\n @unitdim compressibility $U \"Pa⁻¹\"\n @unitdim energy $U \"J\"\n @unitdim inv(energy) $U \"J⁻¹\"\n @unitdim power $U \"W\"\n @unitdim inv(power) $U \"W⁻¹\"\n\n @unitdim electricpotential $U \"V\"\n @unitdim inv(electricpotential) $U \"V⁻¹\"\n @unitdim capacitance $U \"F\"\n @unitdim inv(capacitance) $U \"F⁻¹\"\n @unitdim resistance $U \"Ω\"\n @unitdim conductance $U \"S\"\n @unitdim magneticflux $U \"Wb\"\n @unitdim inv(magneticflux) $U \"Hz⋅V⁻¹\"\n @unitdim magneticfluxdensity $U \"T\"\n @unitdim inv(magneticfluxdensity) $U \"T⁻¹\"\n @unitdim permeance $U \"H\"\n @unitdim reluctance $U \"H⁻¹\"\n\n @unitdim catalysis $U \"kat\"\n @unitdim molarenergy $U \"J⋅mol⁻¹\"\n @unitdim molarentropy $U \"J⋅K⁻¹mol⁻¹\"\n\n @unitdim luminousflux/power $U \"lm⋅W⁻¹\"\n @unitdim power/luminousflux $U \"W⋅lm⁻¹\"\n @unitdim illuminance $U \"lx\"\n @unitdim luminousexposure $U \"lx⋅s\"\n\n @unitdim action*speed $U \"J⋅m\"\n @unitdim impulse $U \"N⋅s\"\n @unitdim yank $U \"N⋅s⁻¹\"\n @unitdim fluence $U \"N⋅m⁻¹\"\n @unitdim compliance $U \"m⋅N⁻¹\"\n\n @unitdim viscosity $U \"Pa⋅s\"\n @unitdim irradiance $U \"W⋅m⁻²\"\n @unitdim inv(irradiance) $U \"W⁻¹m²\"\n @unitdim powerdensity $U \"W⋅m⁻³\"\n @unitdim spectralexposure $U \"J⋅m⁻²⋅Hz⁻¹\"\n @unitdim irradiance/Θ^4 $U \"W⋅m⁻²K⁻⁴\"\n @unitdim pressure/Θ^4 $U \"J⋅m⁻³K⁻⁴\"\n @unitdim 𝟙/T/Θ $U \"Hz⋅K⁻¹\"\n @unitdim entropy/Q $U \"V⋅K⁻¹\"\n @unitdim entropy $U \"J⋅K⁻¹\"\n @unitdim specificentropy $U \"J⋅K⁻¹kg⁻¹\"\n @unitdim specificenergy $U \"J⋅kg⁻¹\"\n @unitdim thermalconductivity $U \"W⋅m⁻¹K⁻¹\"\n @unitdim thermalconductance $U \"W⋅K⁻¹\"\n @unitdim thermalresistance $U \"K⋅W⁻¹\"\n @unitdim thermalresistivity $U \"K⋅m⋅W⁻¹\"\n @unitdim molarconductivity $U \"S⋅m²mol⁻¹\"\n\n @unitdim electricpotential/M $U \"V⋅kg⁻¹\"\n @unitdim electricflux $U \"V⋅m\"\n @unitdim electricfield $U \"V⋅m⁻¹\"\n @unitdim permittivity $U \"F⋅m⁻¹\"\n @unitdim inv(permittivity) $U \"m⋅F⁻¹\"\n @unitdim permeability $U \"H⋅m⁻¹\"\n @unitdim inv(permeability) $U \"m⋅H⁻¹\"\n @unitdim resistivity $U \"Ω⋅m\"\n @unitdim conductivity $U \"S⋅m⁻¹\"\n @unitdim vectorpotential $U \"Wb⋅m⁻¹\"\n @unitdim magneticmoment $U \"Wb⋅m\"\n @unitdim mobility $U \"m²s⁻¹V⁻¹\"\n end\nend\nfor U ∈ (:Metric, :SI2019, :CODATA, :Conventional, :International, :InternationalMean)\n @eval begin\n @unitdim luminousintensity $U \"cd\"\n showgroup(io::IO,::typeof(luminance),::typeof(normal($U))) = print(io,\"nt\")\n @unitdim angularmomentum $U \"J⋅s\"\n @unitdim magneticdipolemoment $U \"J⋅T⁻¹\"\n end\nend\nfor U ∈ (:MetricTurn,:MetricSpatian,:MetricDegree,:MetricGradian,:MetricArcminute,:MetricArcsecond)\n let u = dimtext(normal(eval(U)))[9]\n @eval begin\n @unitdim angularmomentum $U $(\"J⋅s⋅$(u)⁻¹\")\n @unitdim magneticdipolemoment $U $(\"J⋅T⁻¹⋅$(u)⁻¹\")\n @unitdim photonintensity $U $(\"Hz⋅$(u)⁻²\")\n @unitdim photonradiance $U $(\"Hz⋅m⁻²⋅$(u)⁻²\")\n @unitdim radiance $U $(\"W⋅m⁻²⋅$(u)⁻²\")\n @unitdim radiance*T $U $(\"W⋅m⁻²⋅$(u)⁻²⋅Hz⁻¹\")\n @unitdim radiance/L $U $(\"W⋅m⁻³⋅$(u)⁻²\")\n @unitdim radiantintensity $U \"W⋅$(u)⁻²\"\n @unitdim radiantintensity*T $U $(\"W⋅$(u)⁻²⋅Hz⁻¹\")\n @unitdim radiantintensity/L $U $(\"W⋅$(u)⁻²⋅m⁻¹\")\n end\n end\nend\n\n@unitdim frequency Meridian \"Hz\"\n@unitdim frequencydrift Meridian \"Hz⋅s⁻¹\"\n@unitdim photonirradiance Meridian \"Hz⋅m⁻²\"\n@unitdim force Meridian \"eN\"\n@unitdim inv(force) Meridian \"eN⁻¹\"\n@unitdim pressure Meridian \"ePa\"\n@unitdim compressibility Meridian \"ePa⁻¹\"\n@unitdim energy Meridian \"eJ\"\n@unitdim inv(energy) Meridian \"eJ⁻¹\"\n@unitdim power Meridian \"eW\"\n@unitdim inv(power) Meridian \"eW⁻¹\"\n\n@unitdim electricpotential Meridian \"eV\"\n@unitdim inv(electricpotential) Meridian \"eV⁻¹\"\n@unitdim capacitance Meridian \"eF\"\n@unitdim inv(capacitance) Meridian \"eF⁻¹\"\n@unitdim resistance Meridian \"eΩ\"\n@unitdim conductance Meridian \"eS\"\n@unitdim magneticflux Meridian \"eWb\"\n@unitdim inv(magneticflux) Meridian \"Hz⋅eV⁻¹\"\n@unitdim magneticfluxdensity Meridian \"eT\"\n@unitdim inv(magneticfluxdensity) Meridian \"eT⁻¹\"\n@unitdim permeance Meridian \"eH\"\n@unitdim reluctance Meridian \"eH⁻¹\"\n\n@unitdim catalysis Meridian \"ekat\"\n@unitdim molarenergy Meridian \"eJ⋅eg-mol⁻¹\"\n@unitdim molarentropy Meridian \"eJ⋅K⁻¹eg-mol⁻¹\"\n\n@unitdim luminousflux/power Meridian \"lm⋅eW⁻¹\"\n@unitdim luminousintensity Meridian \"cd\"\n@unitdim illuminance Meridian \"elx\"\n@unitdim luminousexposure Meridian \"lx⋅s\"\nshowgroup(io::IO,::typeof(luminance),::typeof(normal(Meridian))) = print(io,\"ent\")\n\n@unitdim impulse Meridian \"eN⋅s\"\n@unitdim angularmomentum Meridian \"eJ⋅s\"\n@unitdim action*speed Meridian \"eJ⋅em\"\n@unitdim yank Meridian \"eN⋅s⁻¹\"\n@unitdim fluence Meridian \"eN⋅em⁻¹\"\n@unitdim compliance Meridian \"em⋅eN⁻¹\"\n\n@unitdim viscosity Meridian \"ePa⋅s\"\n@unitdim irradiance Meridian \"eW⋅em⁻²\"\n@unitdim inv(irradiance) Meridian \"eW⁻¹em²\"\n@unitdim powerdensity Meridian \"eW⋅m⁻³\"\n@unitdim spectralexposure Meridian \"eJ⋅em⁻²⋅Hz⁻¹\"\n@unitdim irradiance/Θ^4 Meridian \"eW⋅em⁻²K⁻⁴\"\n@unitdim pressure/Θ^4 Meridian \"eJ⋅em⁻³K⁻⁴\"\n@unitdim 𝟙/T/Θ Meridian \"Hz⋅K⁻¹\"\n@unitdim entropy/Q Meridian \"eV⋅K⁻¹\"\n@unitdim entropy Meridian \"eJ⋅K⁻¹\"\n@unitdim specificentropy Meridian \"eJ⋅K⁻¹keg⁻¹\"\n@unitdim specificenergy Meridian \"eJ⋅keg⁻¹\"\n@unitdim thermalconductivity Meridian \"eW⋅em⁻¹K⁻¹\"\n@unitdim thermalresistance Meridian \"K⋅eW⁻¹\"\n@unitdim thermalresistivity Meridian \"K⋅em⋅eW⁻¹\"\n@unitdim molarconductivity Meridian \"eS⋅em²eg-mol⁻¹\"\n\n@unitdim electricpotential/M Meridian \"eV⋅kg⁻¹\"\n@unitdim action*speed/Q Meridian \"eV⋅em\"\n@unitdim electricfield Meridian \"eV⋅em⁻¹\"\n@unitdim permittivity Meridian \"eF⋅em⁻¹\"\n@unitdim inv(permittivity) Meridian \"em⋅eF⁻¹\"\n@unitdim permeability Meridian \"eH⋅em⁻¹\"\n@unitdim inv(permeability) Meridian \"em⋅eH⁻¹\"\n@unitdim resistivity Meridian \"eΩ⋅em\"\n@unitdim conductivity Meridian \"eS⋅em⁻¹\"\n@unitdim magneticdipolemoment Meridian \"eJ⋅eT⁻¹\"\n@unitdim vectorpotential Meridian \"eWb⋅em⁻¹\"\n@unitdim magneticmoment Meridian \"eWb⋅em\"\n@unitdim mobility Meridian \"em²s⁻¹eV⁻¹\"\n\nfor U ∈ (:Gauss, :EMU, :ESU, :LorentzHeaviside)\n @eval begin\n @unitdim volume $U \"mL\"\n @unitdim numberdensity $U \"mL⁻¹\"\n @unitdim frequency $U \"Hz\"\n @unitdim photonirradiance $U \"Hz⋅m⁻²\"\n @unitdim force $U \"dyn\"\n @unitdim inv(force) $U \"dyn⁻¹\"\n @unitdim specificforce $U \"gal\"\n @unitdim specificforce/L $U \"gal⋅cm⁻¹\"\n @unitdim pressure $U \"Ba\"\n @unitdim compressibility $U \"Ba⁻¹\"\n @unitdim energy $U \"erg\"\n @unitdim inv(energy) $U \"erg⁻¹\"\n @unitdim power $U \"erg⋅s⁻¹\"\n @unitdim inv(power) $U \"s⋅erg⁻¹\"\n\n @unitdim catalysis $U \"kat\"\n @unitdim molarenergy $U \"erg⋅mol⁻¹\"\n @unitdim molarentropy $U \"erg⋅K⁻¹mol⁻¹\"\n\n @unitdim luminousflux/power $U \"lm⋅s⋅erg⁻¹\"\n @unitdim power/luminousflux $U \"erg⋅s⁻¹lm⁻¹\"\n @unitdim luminousintensity $U \"cd\"\n @unitdim illuminance $U \"ph\"\n showgroup(io::IO,::typeof(luminance),::typeof(normal($U))) = print(io,\"sb\")\n\n @unitdim angularmomentum $U \"erg⋅s\"\n @unitdim action*speed $U \"erg⋅cm\"\n @unitdim fluence $U \"dyn⋅cm⁻¹\"\n @unitdim compliance $U \"cm⋅dyn⁻¹\"\n @unitdim impulse $U \"dyn⋅s\"\n @unitdim yank $U \"dyn⋅s⁻¹\"\n\n @unitdim viscosity $U \"P\"\n @unitdim diffusivity $U \"St\"\n @unitdim irradiance $U \"erg⋅s⁻¹cm⁻²\"\n @unitdim inv(irradiance) $U \"erg⁻¹s⋅cm²\"\n @unitdim powerdensity $U \"erg⋅s⁻¹mL⁻¹\"\n @unitdim spectralexposure $U \"erg⋅cm⁻²⋅Hz⁻¹\"\n @unitdim irradiance/Θ^4 $U \"erg⋅s⁻¹cm⁻²K⁻⁴\"\n @unitdim pressure/Θ^4 $U \"Ba⋅K⁻⁴\"\n @unitdim 𝟙/T/Θ $U \"Hz⋅K⁻¹\"\n @unitdim entropy $U \"erg⋅K⁻¹\"\n @unitdim specificentropy $U \"erg⋅K⁻¹g⁻¹\"\n @unitdim specificenergy $U \"erg⋅g⁻¹\"\n @unitdim thermalconductance $U \"erg⋅s⁻¹K⁻¹\"\n @unitdim thermalresistance $U \"K⋅s⋅erg⁻¹\"\n @unitdim thermalconductivity $U \"erg⋅s⁻¹cm⁻¹K⁻¹\"\n @unitdim thermalresistivity $U \"K⋅cm⋅s⋅erg⁻¹\"\n end\nend\n\n#@unitdim current EMU \"Bi\"\n@unitdim magneticflux EMU \"Mx\"\n@unitdim magneticfluxdensity EMU \"G\"\n#@unitdim magneticfield EMU \"Oe\"\n#@unitdim reluctance EMU \"Bi⋅Mx⁻¹\"\n@unitdim magneticdipolemoment EMU \"erg⋅G⁻¹\"\n@unitdim vectorpotential EMU \"Mx⋅cm⁻¹\"\n#@unitdim magneticmoment EMU \"Mx⋅cm\"\n#@unitdim polestrength EMU \"pole\"\n\n#@unitdim charge Gauss \"Fr\"\n@unitdim magneticflux Gauss \"Mx\"\n@unitdim magneticfluxdensity Gauss \"G\"\n#@unitdim magneticfield Gauss \"Oe\"\n#@unitdim reluctance Gauss \"Fr⋅s⁻¹Mx⁻¹\"\n@unitdim magneticdipolemoment Gauss \"erg⋅G⁻¹\"\n@unitdim vectorpotential Gauss \"Mx⋅cm⁻¹\"\n#@unitdim magneticmoment Gauss \"Mx⋅cm\"\n\n@unitdim force MTS \"sn\"\n@unitdim inv(force) MTS \"sn⁻¹\"\n@unitdim pressure MTS \"pz\"\n@unitdim compressibility MTS \"pz⁻¹\"\n\n@unitdim mass GravitationalMetric \"hyl\"\n@unitdim mass British \"slug\"\n@unitdim mass IPS \"slinch\"\n@unitdim molarmass GravitationalMetric \"hyl⋅mol⁻¹\"\n@unitdim molarmass British \"slug⋅slug-mol⁻¹\"\n@unitdim molarmass IPS \"slinch-slinch-mol⁻¹\"\n@unitdim force FPS \"pdl\"\n@unitdim pressure FPS \"pdl⋅ft⁻²\"\n@unitdim density British \"slug⋅ft⁻³\"\n@unitdim density IPS \"slinch⋅in⁻³\"\n@unitdim density GravitationalMetric \"hyl⋅m⁻³\"\n\n@unitdim L Rydberg \"a₀\"\n@unitdim inv(L) Rydberg \"a₀⁻¹\"\n@unitdim area Rydberg \"a₀²\"\n@unitdim fuelefficiency Rydberg \"a₀⁻²\"\n@unitdim volume Rydberg \"a₀³\"\n@unitdim numberdensity Rydberg \"a₀⁻³\"\n@unitdim Q Electronic \"𝘦\"\n@unitdim Q Stoney \"𝘦\"\n@unitdim Q Schrodinger \"𝘦\"\n@unitdim Q CosmologicalQuantum \"𝘦ₙ\"\n@unitdim inv(Q) Electronic \"𝘦⁼¹\"\n@unitdim inv(Q) Stoney \"𝘦⁼¹\"\n@unitdim inv(Q) Schrodinger \"𝘦⁼¹\"\n@unitdim inv(Q) CosmologicalQuantum \"𝘦ₙ⁼¹\"\n@unitdim Q^2 Electronic \"𝘦²\"\n@unitdim Q^2 Stoney \"𝘦²\"\n@unitdim Q^2 Schrodinger \"𝘦²\"\n@unitdim Q^2 CosmologicalQuantum \"𝘦ₙ²\"\n@unitdim inv(Q^2) Electronic \"𝘦⁼²\"\n@unitdim inv(Q^2) Stoney \"𝘦⁼²\"\n@unitdim inv(Q^2) Schrodinger \"𝘦⁼²\"\n@unitdim inv(Q^2) CosmologicalQuantum \"𝘦ₙ⁼²\"\n\nfor U ∈ (:FPS,:IPS,:British,:English,:Survey)\n @eval begin\n @unitdim frequency $U \"Hz\"\n @unitdim frequencydrift $U \"Hz⋅s⁻¹\"\n @unitdim 𝟙/T/Θ $U \"Hz⋅°R⁻¹\"\n end\nend\nfor U ∈ (:FPS,:British,:English,:Survey)\n @eval begin\n @unitdim luminousintensity $U \"cd\"\n @unitdim illuminance $U \"fc\"\n end\nend\n\n@doc \"\"\"\n$(convertext(:length,\"planck(U,S)/mass(U,S)/speed(U,S)\"))\n\nExtent of one-dimensional shape or `length` (m), unit conversion factor.\n\n```Julia\njulia> L(CGS,Metric) # m⋅cm⁻¹\n$(L(CGS,Metric))\n\njulia> L(IAU,Metric) # m⋅au⁻¹\n$(L(IAU,Metric))\n\njulia> L(English,Metric) # m⋅ft⁻¹\n$(L(English,Metric))\n\njulia> L(EnglishUS,English) # ft⋅ftUS⁻¹\n$(L(EnglishUS,English))\n\njulia> L(PlanckGauss,Metric) # m⋅ℓP⁻¹\n$(L(PlanckGauss,Metric))\n```\n\"\"\" L, ft, ftUS\n\n@doc \"\"\"\n$(convertext(:time,\"length(U,S)/speed(U,S)\"))\n\nDimension along which events are ordered or `T` (s), unit conversion factor.\n\n```Julia\njulia> T(MPH,Metric) # s⋅h⁻¹\n$(T(MPH,Metric))\n\njulia> T(IAU,Metric) # s⋅D⁻¹\n$(T(IAU,Metric))\n\njulia> T(Hubble,Metric)\n$(T(Hubble,Metric))\n```\n\"\"\" T\n\n@doc \"\"\"\n neper(U::UnitSystem) = U(𝟏,log(𝟙))\n\nLogarithmic unit expressing the ratio of a dimensional quanty.\n```Julia\njulia> neper(Metric)\n$(neper(Metric))\n\njulia> exp(neper(Metric))\n$(exp(neper(Metric)))\n```\n\"\"\" neper\n\n@doc \"\"\"\n bel(U::UnitSystem) = U(𝟏,log10(𝟙))\n\nLogarithmic unit expressing the ratio of a dimensional quanty.\n```Julia\njulia> bel(Metric)\n$(bel(Metric))\n\njulia> exp10(bel(Metric))\n$(exp10(bel(Metric)))\n```\n\"\"\" bel\n\n@doc \"\"\"\n decibel(U::UnitSystem) = U(𝟏,logdb(𝟙))\n\nLogarithmic unit expressing the ratio of a dimensional quanty.\n```Julia\njulia> decibel(Metric)\n$(decibel(Metric))\n\njulia> expdb(decibel(Metric))\n$(expdb(decibel(Metric)))\n```\n\"\"\" decibel\n", "meta": {"hexsha": "c0ffc166a02c1b973d5642de9113f7d67c3af4b6", "size": 33325, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derived.jl", "max_stars_repo_name": "chakravala/Similitude.jl", "max_stars_repo_head_hexsha": "d92144f13958bf5c27103806e9b89e2af61f2147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-29T10:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:03:19.000Z", "max_issues_repo_path": "src/derived.jl", "max_issues_repo_name": "chakravala/Similitude.jl", "max_issues_repo_head_hexsha": "d92144f13958bf5c27103806e9b89e2af61f2147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/derived.jl", "max_forks_repo_name": "chakravala/Similitude.jl", "max_forks_repo_head_hexsha": "d92144f13958bf5c27103806e9b89e2af61f2147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0746421268, "max_line_length": 201, "alphanum_fraction": 0.6680570143, "num_tokens": 13497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.23913813457254143}} {"text": "##### multi dimensional advection\n##### For incompressible model only\n##### calculate tendencies in x direction\n@kernel function calc_Gcˣ_kernel!(Gc, c, u, g::AbstractGrid, ΔT)\n i, j, k = @index(Global, NTuple)\n ### offset index for halo points\n ii = i + g.Hx\n jj = j + g.Hy\n kk = k + g.Hz\n @inbounds Gc[ii, jj, kk] = adv_flux_x(ii, jj, kk, g, u, c, ΔT)\nend\nfunction calc_Gcsˣ!(Gcs, nut, u, g::AbstractGrid, ΔT, arch::Architecture)\n kernel! = calc_Gcˣ_kernel!(device(arch), (16,16), (g.Nx, g.Ny, g.Nz))\n barrier = Event(device(arch))\n events = []\n for name in nut_names\n event = kernel!(Gcs[name].data, nut[name].data, u, g, ΔT, dependencies=barrier)\n push!(events,event)\n end\n wait(device(arch), MultiEvent(Tuple(events)))\n return nothing\nend\n\n##### calculate tendencies in y direction\n@kernel function calc_Gcʸ_kernel!(Gc, c, v, g::AbstractGrid, ΔT)\n i, j, k = @index(Global, NTuple)\n ### offset index for halo points\n ii = i + g.Hx\n jj = j + g.Hy\n kk = k + g.Hz\n @inbounds Gc[ii, jj, kk] = adv_flux_y(ii, jj, kk, g, v, c, ΔT)\nend\nfunction calc_Gcsʸ!(Gcs, nut, v, g::AbstractGrid, ΔT, arch::Architecture)\n kernel! = calc_Gcʸ_kernel!(device(arch), (16,16), (g.Nx, g.Ny, g.Nz))\n barrier = Event(device(arch))\n events = []\n for name in nut_names\n event = kernel!(Gcs[name].data, nut[name].data, v, g, ΔT, dependencies=barrier)\n push!(events,event)\n end\n wait(device(arch), MultiEvent(Tuple(events)))\n return nothing\nend\n\n##### calculate tendencies in z direction\n@kernel function calc_Gcᶻ_kernel!(Gc, c, w, g::AbstractGrid, ΔT)\n i, j, k = @index(Global, NTuple)\n ### offset index for halo points\n ii = i + g.Hx\n jj = j + g.Hy\n kk = k + g.Hz\n @inbounds Gc[ii, jj, kk] = adv_flux_z(ii, jj, kk, g, w, c, ΔT)\nend\nfunction calc_Gcsᶻ!(Gcs, nut, w, g::AbstractGrid, ΔT, arch::Architecture)\n kernel! = calc_Gcᶻ_kernel!(device(arch), (16,16), (g.Nx, g.Ny, g.Nz))\n barrier = Event(device(arch))\n events = []\n for name in nut_names\n event = kernel!(Gcs[name].data, nut[name].data, w, g, ΔT, dependencies=barrier)\n push!(events,event)\n end\n wait(device(arch), MultiEvent(Tuple(events)))\n return nothing\nend\n\n##### apply the tendency in x direction to tracer c\n@kernel function multi_dim_x_kernel!(ctemp, Gc, c, u, g::AbstractGrid, ΔT)\n i, j, k = @index(Global, NTuple)\n ### offset index for halo points\n ii = i + g.Hx\n jj = j + g.Hy\n kk = k + g.Hz\n @inbounds ctemp[ii, jj, kk] -= ΔT / volume(ii, jj, kk, g) * (δx⁺(ii, jj, kk, Gc, g) - c[ii, jj, kk] * δx⁺(ii, jj, kk, g, Trans_x, u))\nend\nfunction multi_dim_x!(nut_temp, Gcs, nut, u, g::AbstractGrid, ΔT, arch::Architecture)\n kernel! = multi_dim_x_kernel!(device(arch), (16,16), (g.Nx, g.Ny, g.Nz))\n barrier = Event(device(arch))\n events = []\n for name in nut_names\n event = kernel!(nut_temp[name].data, Gcs[name].data, nut[name].data, u, g, ΔT, dependencies=barrier)\n push!(events,event)\n end\n wait(device(arch), MultiEvent(Tuple(events)))\n return nothing\nend\n\n##### apply the tendency in y direction to tracer c\n@kernel function multi_dim_y_kernel!(ctemp, Gc, c, v, g::AbstractGrid, ΔT)\n i, j, k = @index(Global, NTuple)\n ### offset index for halo points\n ii = i + g.Hx\n jj = j + g.Hy\n kk = k + g.Hz\n @inbounds ctemp[ii, jj, kk] -= ΔT / volume(ii, jj, kk, g) * (δy⁺(ii, jj, kk, Gc, g) - c[ii, jj, kk] * δy⁺(ii, jj, kk, g, Trans_y, v ))\nend\nfunction multi_dim_y!(nut_temp, Gcs, nut, v, g::AbstractGrid, ΔT, arch::Architecture)\n kernel! = multi_dim_y_kernel!(device(arch), (16,16), (g.Nx, g.Ny, g.Nz))\n barrier = Event(device(arch))\n events = []\n for name in nut_names\n event = kernel!(nut_temp[name].data, Gcs[name].data, nut[name].data, v, g, ΔT, dependencies=barrier)\n push!(events,event)\n end\n wait(device(arch), MultiEvent(Tuple(events)))\n return nothing\nend\n\n##### apply the tendency in z direction to tracer c\n@kernel function multi_dim_z_kernel!(ctemp, Gc, c, w, g::AbstractGrid, ΔT)\n i, j, k = @index(Global, NTuple)\n ### offset index for halo points\n ii = i + g.Hx\n jj = j + g.Hy\n kk = k + g.Hz\n @inbounds ctemp[ii, jj, kk] -= ΔT / volume(ii, jj, kk, g) * (δz⁺(ii, jj, kk, Gc, g) - c[ii, jj, kk] * δz⁺(ii, jj, kk, g, Trans_z, w ))\nend\nfunction multi_dim_z!(nut_temp, Gcs, nut, w, g::AbstractGrid, ΔT, arch::Architecture)\n kernel! = multi_dim_z_kernel!(device(arch), (16,16), (g.Nx, g.Ny, g.Nz))\n barrier = Event(device(arch))\n events = []\n for name in nut_names\n event = kernel!(nut_temp[name].data, Gcs[name].data, nut[name].data, w, g, ΔT, dependencies=barrier)\n push!(events,event)\n end\n wait(device(arch), MultiEvent(Tuple(events)))\n return nothing\nend\n\nfunction calc_nut_tendency!(a, b, c, ΔT)\n for name in nut_names\n @inbounds a[name].data .= b[name].data .- c[name].data\n end\nend\n\nfunction nut_advection!(nut, nut_temp, Gcs, vel, g::AbstractGrid, ΔT, arch::Architecture)\n for name in nut_names\n @inbounds nut_temp[name].data .= nut[name].data\n end\n ##### x direction\n calc_Gcsˣ!(Gcs, nut_temp, vel.u.data, g, ΔT, arch)\n fill_halo_Gcs!(Gcs, g)\n multi_dim_x!(nut_temp, Gcs, nut, vel.u.data, g, ΔT, arch)\n fill_halo_nut!(nut_temp, g)\n\n ##### y direction\n calc_Gcsʸ!(Gcs, nut_temp, vel.v.data, g, ΔT, arch)\n fill_halo_Gcs!(Gcs, g)\n multi_dim_y!(nut_temp, Gcs, nut, vel.v.data, g, ΔT, arch)\n fill_halo_nut!(nut_temp, g)\n\n ##### z direction\n calc_Gcsᶻ!(Gcs, nut_temp, vel.w.data, g, ΔT, arch)\n fill_halo_Gcs!(Gcs, g)\n multi_dim_z!(nut_temp, Gcs, nut, vel.w.data, g, ΔT, arch)\n fill_halo_nut!(nut_temp, g)\n\n calc_nut_tendency!(Gcs, nut_temp, nut, ΔT)\n\nend", "meta": {"hexsha": "bfa6129a31a950bffea83cbbb683dfb6ef936889", "size": 5792, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Biogeochemistry/Advection/multi_dim_adv.jl", "max_stars_repo_name": "zhenwu0728/PlanktonIndividuals.jl", "max_stars_repo_head_hexsha": "aa2edffcab3b38ae1d7f188bc421ed8e01ac9ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-03-14T08:48:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-08T19:35:57.000Z", "max_issues_repo_path": "src/Biogeochemistry/Advection/multi_dim_adv.jl", "max_issues_repo_name": "zhenwu0728/PlanktonIndividuals.jl", "max_issues_repo_head_hexsha": "aa2edffcab3b38ae1d7f188bc421ed8e01ac9ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-03-13T19:27:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-06T19:54:00.000Z", "max_forks_repo_path": "src/Biogeochemistry/Advection/multi_dim_adv.jl", "max_forks_repo_name": "zhenwu0728/PlanktonIndividuals.jl", "max_forks_repo_head_hexsha": "aa2edffcab3b38ae1d7f188bc421ed8e01ac9ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-11T21:23:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T21:23:27.000Z", "avg_line_length": 36.427672956, "max_line_length": 138, "alphanum_fraction": 0.6222375691, "num_tokens": 1997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.63341024983754, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.23913812934726528}} {"text": "import ModelingToolkit\nimport ModelingToolkit: build_function, substitute\nimport Catalyst\nimport Catalyst: ReactionSystem\nusing StaticArrays\nimport Base.show\nusing Setfield\n\nstruct ReactionSet\n rates::Vector{Float64}\n rstoich::Vector{Vector{Pair{Int64,Int64}}}\n nstoich::Vector{Vector{Pair{Int64,Int64}}}\n nspecies::Int\nend\n\nabstract type AbstractJumpRateAggregatorAlgorithm end\n\nstruct GillespieDirect <: AbstractJumpRateAggregatorAlgorithm end\n\nstruct DepGraphDirect <: AbstractJumpRateAggregatorAlgorithm end\n\nabstract type AbstractJumpRateAggregator end\n\nstruct DirectAggregator{U} <: AbstractJumpRateAggregator\n \"the sum of all reaction rates\"\n sumrate::Float64\n\n \"a vector of the current reaction rates\"\n rates::Vector{Float64}\n\n \"sum of group propensities\"\n gsums::Vector{Float64}\n\n \"maps reaction indices to group indices\"\n ridtogroup::U\n\n \"time span for aggregation\"\n tspan::Tuple{Float64,Float64}\n\n \"time of last recorded reaction\"\n tprev::Float64\n\n \"accumulated log-probability\"\n weight::Float64\nend\n\nfunction build_aggregator(alg::GillespieDirect, reactions::ReactionSet, ridtogroup, tspan=(0.0, Inf64))\n ngroups = maximum(ridtogroup)\n nreactions = length(reactions.rates)\n DirectAggregator(0.0, zeros(nreactions), zeros(ngroups), ridtogroup, tspan, tspan[1], 0.0)\nend\n\nstruct DepGraphAggregator{U,DepGraph} <: AbstractJumpRateAggregator\n \"the sum of all reaction rates\"\n sumrate::Float64\n\n \"a vector of the current reaction rates\"\n rates::Vector{Float64}\n\n \"sum of group propensities\"\n gsums::Vector{Float64}\n\n \"maps reaction indices to group indices\"\n ridtogroup::U\n\n \"time span for aggregation\"\n tspan::Tuple{Float64,Float64}\n\n \"time of last recorded reaction\"\n tprev::Float64\n\n \"accumulated log-probability\"\n weight::Float64\n\n \"dependency graph\"\n depgraph::DepGraph\n\n \"previously executed reaction\"\n prev_reaction::Int\nend\n\nfunction build_aggregator(alg::DepGraphDirect, reactions::ReactionSet, ridtogroup, tspan=(0.0, Inf64))\n ngroups = maximum(ridtogroup)\n nreactions = length(reactions.rates)\n depgraph = make_depgraph(reactions)\n DepGraphAggregator(0.0, zeros(nreactions), zeros(ngroups), ridtogroup, tspan, tspan[1], 0.0, depgraph, 0)\nend\n\nfunction initialize_aggregator(agg::AbstractJumpRateAggregator; tspan=(0.0, Inf64))\n agg = @set agg.tspan = tspan\n agg = @set agg.tprev = tspan[1]\n agg = @set agg.weight = 0.0\n agg = @set agg.sumrate = 0.0\n agg.rates .= 0.0\n agg.gsums .= 0.0\n agg\nend\n\nfunction initialize_aggregator(agg::DepGraphAggregator; tspan=(0.0, Inf64))\n agg = @set agg.tspan = tspan\n agg = @set agg.tprev = tspan[1]\n agg = @set agg.weight = 0.0\n agg = @set agg.sumrate = 0.0\n agg = @set agg.prev_reaction = 0\n agg.rates .= 0.0\n agg.gsums .= 0.0\n agg\nend\n\nfunction ReactionSet(js::ModelingToolkit.JumpSystem, p)\n parammap = map(Pair, ModelingToolkit.parameters(js), p)\n statetoid = Dict(ModelingToolkit.value(state) => i for (i, state) in enumerate(ModelingToolkit.states(js)))\n\n rates = Float64[]\n rstoich_vec = Vector{Pair{Int64,Int64}}[]\n nstoich_vec = Vector{Pair{Int64,Int64}}[]\n\n for eq in ModelingToolkit.equations(js)\n rate = ModelingToolkit.value(ModelingToolkit.substitute(eq.scaled_rates, parammap))\n rstoich = sort!([statetoid[ModelingToolkit.value(spec)] => stoich for (spec, stoich) in eq.reactant_stoch])\n nstoich = sort!([statetoid[ModelingToolkit.value(spec)] => stoich for (spec, stoich) in eq.net_stoch])\n\n push!(rates, rate)\n push!(rstoich_vec, rstoich)\n push!(nstoich_vec, nstoich)\n end\n\n ReactionSet(rates, rstoich_vec, nstoich_vec, length(ModelingToolkit.states(js)))\nend\n\nfunction species_to_dependent_reaction_map(reactions::ReactionSet)\n nspecies = reactions.nspecies\n # map from a species to reactions that depend on it\n spec_to_dep_rxs = [Vector{Int}() for n = 1:nspecies]\n for (rx, complex) in enumerate(reactions.rstoich)\n for (spec, stoch) in complex\n push!(spec_to_dep_rxs[spec], rx)\n end\n end\n\n foreach(s -> unique!(sort!(s)), spec_to_dep_rxs)\n spec_to_dep_rxs\nend\n\nfunction make_depgraph(reactions::ReactionSet)\n nreactions = length(reactions.rates)\n spec_to_dep_rxs = species_to_dependent_reaction_map(reactions)\n\n # create map from rx to reactions depending on it\n dep_graph = [Vector{Int}() for n = 1:nreactions]\n for rx in 1:nreactions\n # rx changes spec, hence rxs depending on spec depend on rx\n for (spec, stoch) in reactions.nstoich[rx]\n for dependent_rx in spec_to_dep_rxs[spec]\n push!(dep_graph[rx], dependent_rx)\n end\n end\n end\n\n foreach(deps -> unique!(sort!(deps)), dep_graph)\n dep_graph\nend\n\nstruct TrajectoryDistribution{A}\n reactions::ReactionSet\n aggregator::A\nend\n\nfunction TrajectoryDistribution(reactions::ReactionSet, alg::AbstractJumpRateAggregatorAlgorithm, ridtogroup=1:length(reactions.rates))\n agg = build_aggregator(alg, reactions, ridtogroup)\n TrajectoryDistribution(reactions, agg)\nend\n\ndistribution(rn::ReactionSystem, p; update_map=1:Catalyst.numreactions(rn), alg=GillespieDirect()) = TrajectoryDistribution(ReactionSet(convert(ModelingToolkit.JumpSystem, rn), p), alg, update_map)\n\n@fastmath function Distributions.logpdf(dist::TrajectoryDistribution, trajectory)::Float64\n traj_iter = trajectory_iterator(trajectory)\n tprev = 0.0\n result = 0.0\n agg = initialize_aggregator(dist.aggregator)\n for (u, t, i) in traj_iter\n agg = update_rates(agg, (u, t, i), dist.reactions)\n\n dt = t - tprev\n result -= dt * agg.sumrate\n if i != 0\n @inbounds gid = agg.ridtogroup[i]\n gid != 0 && @inbounds result += log(agg.gsums[gid])\n end\n\n tprev = t\n end\n\n result\nend\n\n@fastmath function fold_logpdf(dist::TrajectoryDistribution, agg::AbstractJumpRateAggregator, (u, t, i))\n agg = update_rates(agg, (u, t, i), dist.reactions)\n dt = t - agg.tprev\n log_jump_prob = 0.0\n if i != 0\n @inbounds gid = agg.ridtogroup[i]\n gid != 0 && @inbounds log_jump_prob = log(agg.gsums[gid])\n end\n log_surv_prob = -dt * agg.sumrate\n agg = @set agg.weight = agg.weight + log_surv_prob + log_jump_prob\n agg = @set agg.tprev = t\nend\n\nfunction step_energy(dist::TrajectoryDistribution, agg::AbstractJumpRateAggregator, (u, t, i))\n if t <= agg.tspan[1]\n return agg\n end\n if t > agg.tspan[2]\n if agg.tprev >= agg.tspan[2]\n return agg\n end\n fold_logpdf(dist, agg, (u, agg.tspan[2], 0))\n else\n fold_logpdf(dist, agg, (u, t, i))\n end\nend\n\nfunction trajectory_energy(dist::TrajectoryDistribution, traj; tspan=(0.0, Inf64))\n agg = initialize_aggregator(dist.aggregator, tspan=tspan)\n traj_iter = trajectory_iterator(traj)\n agg = Base.foldl((acc, x) -> step_energy(dist, acc, x), traj_iter; init=agg)\n agg.weight\nend\n\nfunction cumulative_logpdf!(result::AbstractVector, dist::TrajectoryDistribution, traj, dtimes::AbstractVector)\n tspan = (first(dtimes), last(dtimes))\n agg = initialize_aggregator(dist.aggregator, tspan=tspan)\n result[1] = zero(eltype(result))\n traj_iter = trajectory_iterator(traj)\n result_agg, k = Base.foldl(traj_iter; init=(agg, 1)) do (agg, k), (u, t, i)\n if t <= agg.tspan[1]\n return agg, k\n end\n\n t = min(t, agg.tspan[2])\n agg = update_rates(agg, (u, t, i), dist.reactions)\n\n tprev = agg.tprev\n while k <= length(dtimes) && dtimes[k] < t\n result[k] -= (dtimes[k] - tprev) * agg.sumrate\n tprev = dtimes[k]\n k += 1\n result[k] = result[k-1]\n end\n result[k] -= (t - tprev) * agg.sumrate\n\n log_jump_prob = 0.0\n if i != 0\n @inbounds gid = agg.ridtogroup[i]\n gid != 0 && @inbounds log_jump_prob = log(agg.gsums[gid])\n end\n result[k] += log_jump_prob\n\n agg = @set agg.weight = agg.weight - (t - agg.tprev) * agg.sumrate + log_jump_prob\n agg = @set agg.tprev = t\n agg, k\n end\n\n result\nend\n\ncumulative_logpdf(dist::TrajectoryDistribution, trajectory, dtimes::AbstractVector) = cumulative_logpdf!(zeros(length(dtimes)), dist, trajectory, dtimes)\n\n\n@inline @fastmath function evalrxrate(speciesvec::AbstractVector{T}, rxidx::Int64, rs::ReactionSet) where {T}\n val = Float64(1.0)\n @inbounds for specstoch in rs.rstoich[rxidx]\n @inbounds specpop = speciesvec[specstoch[1]]\n val *= Float64(specpop)\n @inbounds for k = 2:specstoch[2]\n specpop -= one(specpop)\n val *= Float64(specpop)\n end\n end\n\n @inbounds val * rs.rates[rxidx]\nend\n\n@inline function update_reaction_rate!(aggregator::AbstractJumpRateAggregator, u::AbstractVector, reactions, rx::Int)\n @inbounds gid = aggregator.ridtogroup[rx]\n if gid != 0\n rate = evalrxrate(u, rx, reactions)\n @inbounds aggregator.gsums[gid] += -aggregator.rates[rx] + rate\n @inbounds aggregator.rates[rx] = rate\n end\nend\n\n@fastmath function update_rates(aggregator::DirectAggregator, (u, t, i), reactions::ReactionSet)\n for rx in eachindex(reactions.rates)\n update_reaction_rate!(aggregator, u, reactions, rx)\n end\n aggregator = @set aggregator.sumrate = sum(aggregator.gsums)\nend\n\n@fastmath function update_rates(aggregator::DepGraphAggregator, (u, t, i), reactions::ReactionSet)\n if aggregator.prev_reaction == 0\n for rx in eachindex(reactions.rates)\n update_reaction_rate!(aggregator, u, reactions, rx)\n end\n else\n @inbounds for rx in aggregator.depgraph[aggregator.prev_reaction]\n update_reaction_rate!(aggregator, u, reactions, rx)\n end\n end\n aggregator = @set aggregator.sumrate = sum(aggregator.gsums)\n aggregator = @set aggregator.prev_reaction = i\nend\n", "meta": {"hexsha": "7a07c37b5529185ef4d46d84a00b9a4cb1b086c8", "size": 10010, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/trajectories/distribution.jl", "max_stars_repo_name": "manuel-rhdt/PWS.jl", "max_stars_repo_head_hexsha": "9ca9fc8964027926a3776ffc44e8783280ce5399", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/trajectories/distribution.jl", "max_issues_repo_name": "manuel-rhdt/PWS.jl", "max_issues_repo_head_hexsha": "9ca9fc8964027926a3776ffc44e8783280ce5399", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-17T15:15:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T15:15:39.000Z", "max_forks_repo_path": "src/trajectories/distribution.jl", "max_forks_repo_name": "manuel-rhdt/PWS.jl", "max_forks_repo_head_hexsha": "9ca9fc8964027926a3776ffc44e8783280ce5399", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8789808917, "max_line_length": 197, "alphanum_fraction": 0.6771228771, "num_tokens": 2840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.23903422866138607}} {"text": "@with_kw mutable struct Domain{FT}\n # Something CUDA\n max_streams::IndexT\n streams::Nothing\n\n # Elem-centered\n matElemlist::VD{IndexT} # material indexset\n nodelist::VD{IndexT} # elemToNode connectivity\n\n lxim::VD{IndexT} # element connectivity through face g\n lxip::VD{IndexT}\n letam::VD{IndexT}\n letap::VD{IndexT}\n lzetam::VD{IndexT}\n lzetap::VD{IndexT}\n\n elemBC::VD{Int} # elem face symm/free-surf flag g\n\n e::VD{FT} # energy g\n d_e::VD{FT} # change in energy g\n\n p::VD{FT} # pressure g\n\n q::VD{FT} # q g\n ql::VD{FT} # linear term for q g\n qq::VD{FT} # quadratic term for q g\n\n v::VD{FT} # relative volume g\n\n volo::VD{FT} # reference volume g\n delv::VD{FT} # m_vnew - m_v g\n vdov::VD{FT} # volume derivative over volume g\n\n arealg::VD{FT} # char length of an element g\n\n ss::VD{FT} # \"sound speed\" g\n\n elemMass::VD{FT} # mass g\n\n # TODO: Not making distinction between pointers to arrays down here\n\n vnew::VD{FT} # new relative volume -- temporary g\n\n delv_xi::VD{FT} # velocity gradient -- temporary g\n delv_eta::VD{FT}\n delv_zeta::VD{FT}\n\n delx_xi::VD{FT} # coordinate gradient -- temporary g\n delx_eta::VD{FT}\n delx_zeta::VD{FT}\n\n dxx::VD{FT} # principal strains -- temporary g\n dyy::VD{FT}\n dzz::VD{FT}\n\n # Node-centered g\n\n x::VD{FT} # coordinates g\n y::VD{FT}\n z::VD{FT}\n\n xd::VD{FT} # velocities g\n yd::VD{FT}\n zd::VD{FT}\n\n xdd::VD{FT} # accelerations g\n ydd::VD{FT}\n zdd::VD{FT}\n\n\n fx::VD{FT} # forces g\n fy::VD{FT}\n fz::VD{FT}\n\n dfx::VD{FT} # AD of the forces g\n dfy::VD{FT}\n dfz::VD{FT}\n\n nodalMass::VD{FT} # mass g\n h_nodalMass::Vector{FT} # mass - host g\n\n # device pointers for comms g\n # TODO: Not sure how to store the pointers or if even necessary\n # Real_t *d_delv_xi # velocity gradient -- temporary g\n # Real_t *d_delv_eta\n # Real_t *d_delv_zeta\n\n # Real_t *d_x # coordinates g\n # Real_t *d_y\n # Real_t *d_z\n\n # Real_t *d_xd # velocities g\n # Real_t *d_yd\n # Real_t *d_zd\n\n # Real_t *d_fx # forces g\n # Real_t *d_fy\n # Real_t *d_fz\n # Boundary nodesets\n\n symmX::VD{IndexT} # symmetry plane nodesets\n symmY::VD{IndexT}\n symmZ::VD{IndexT}\n\n nodeElemCount::VD{Int}\n nodeElemStart::VD{Int}\n nodeElemCornerList::VD{IndexT}\n\n # Parameters\n\n dtfixed::FT # fixed time increment g\n deltatimemultlb::FT\n deltatimemultub::FT\n stoptime::FT # end time for simulation g\n dtmax::FT # maximum allowable time increment g\n cycle::Int # iteration count for simulation g\n\n dthydro_h::FT # hydro time constraint g\n d_dthydro_h::FT # AD change of the hydro time constraint g\n dtcourant_h::FT # courant time constraint g\n d_dtcourant_h::FT # AD of the courant time constraint g\n bad_q_h::IndexT # flag to indicate Q error g\n bad_vol_h::IndexT # flag to indicate volume error g\n\n # cuda Events to indicate completion of certain kernels\n # TODO Will check later how this works with KA\n # cudaEvent_t time_constraint_computed;\n time_h::FT # current time g\n deltatime_h::FT # variable time increment g\n\n u_cut::FT # velocity tolerance g\n hgcoef::FT # hourglass control g\n qstop::FT # excessive q indicator g\n monoq_max_slope::FT\n monoq_limiter_mult::FT\n e_cut::FT # energy tolerance g\n p_cut::FT # pressure tolerance g\n ss4o3::FT\n q_cut::FT # q tolerance g\n v_cut::FT # relative volume tolerance g\n qlc_monoq::FT # linear term coef for q g\n qqc_monoq::FT # quadratic term coef for q g\n qqc::FT\n eosvmax::FT\n eosvmin::FT\n pmin::FT # pressure floor g\n emin::FT # energy floor g\n dvovmax::FT # maximum allowable volume change g\n refdens::FT # reference density g\n\n m_colLoc::IndexT\n m_rowLoc::IndexT\n m_planeLoc::IndexT\n m_tp::IndexT\n sizeX::IndexT\n sizeY::IndexT\n sizeZ::IndexT\n maxPlaneSize::IndexT\n maxEdgeSize::IndexT\n\n numElem::IndexT\n # padded_numElem::IndexT\n\n numNode::IndexT\n # padded_numNode::IndexT\n\n numSymmX::IndexT\n numSymmY::IndexT\n numSymmZ::IndexT\n\n octantCorner::IndexT\n\n # Region information\n numReg::Int # number of regions (def:11)\n balance::Int # Load balance between regions of a domain (def: 1)\n cost::Int # imbalance cost (def: 1)\n regElemSize::Vector{Int} # Size of region sets\n regCSR::VD{Int} # records the begining and end of each region\n regReps::VD{Int} # records the rep number per region\n regNumList::VD{IndexT} # Region number per domain element\n regElemlist::VD{IndexT} # region indexset\n regSorted::VD{IndexT} # keeps index of sorted regions\n\n\n # MPI-Related additional data\n\n # TODO I think we can handle this differently\n\n # IndexT m_numRanks;\n # IndexT& numRanks() { return m_numRanks ; }\n\n\n # # Used in setup\n # IndexT m_rowMin, m_rowMax;\n # IndexT m_colMin, m_colMax;\n # IndexT m_planeMin, m_planeMax ;\n\n # # Communication Work space\n # Real_t *commDataSend ;\n # Real_t *commDataRecv ;\n\n # Real_t *d_commDataSend ;\n # Real_t *d_commDataRecv ;\n\n # # Maximum number of block neighbors\n # MPI_Request recvRequest[26] ; # 6 faces + 12 edges + 8 corners\n # MPI_Request sendRequest[26] ; # 6 faces + 12 edges + 8 corners\nend\n", "meta": {"hexsha": "c28a9c7b344049aeca7a4899ab9ea8d90a26f1e2", "size": 6078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/types.jl", "max_stars_repo_name": "vchuravy/LULESH.jl", "max_stars_repo_head_hexsha": "9674cf178e6d78ee11ee1b2e3befbe8cc933cf5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/types.jl", "max_issues_repo_name": "vchuravy/LULESH.jl", "max_issues_repo_head_hexsha": "9674cf178e6d78ee11ee1b2e3befbe8cc933cf5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types.jl", "max_forks_repo_name": "vchuravy/LULESH.jl", "max_forks_repo_head_hexsha": "9674cf178e6d78ee11ee1b2e3befbe8cc933cf5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0813397129, "max_line_length": 87, "alphanum_fraction": 0.5661401777, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2390342231773309}} {"text": "#!/usr/bin/julia\n#\n# Plotting functions.\n#\nusing RecipesBase;\nusing Plots: @layout, grid;\n#using IJulia; # Required to prevent plotting window opening and crashing.\n\nexport check_path, gen_filename, format_plot_title_variable,\n GeneralPlotOptions, LanczosPlotOptions, SplitStepPlotOptions, SimPlot;\n\n\"\"\"\nImplementations contain mainly boolean objects specifying what should be\nincluded within plots.\n\nAll implementations should at least implement all the properties of\n`GeneralPlotOptions`.\n\nSee also: [`GeneralPlotOptions`](@ref).\n\"\"\"\nabstract type PlotOptions end;\n\n\"Plotting options for a simulation agnostic plot\"\nstruct GeneralPlotOptions <: PlotOptions\n \"\"\"\n If the real and imaginary parts of the wave function should be plotted in\n addition to the absolute square value.\n \"\"\"\n components::Bool;\n\n \"\"\"\n If the value of the wave function is less than the value of this property at\n the start or end of the plot range, then they will not be plotted.\n \"\"\"\n extremaϵ::Number;\n\nend\nGeneralPlotOptions(;components::Bool=false, extremaϵ::Number=0.1) =\n GeneralPlotOptions(components, extremaϵ);\n\n\"Plotting options for split step simulations.\"\nstruct SplitStepPlotOptions <: PlotOptions\n components::Bool;\n extremaϵ::Number;\nend\nSplitStepPlotOptions(;components::Bool=false, extremaϵ::Number=0.1) =\n SplitStepPlotOptions(components, extremaϵ);\n\n\"Plotting options for Lanczos simulations.\"\nstruct LanczosPlotOptions <: PlotOptions\n components::Bool;\n extremaϵ::Number;\n \"Plot basis functions.\"\n basis::Bool;\n \"Plot eigenfunctions of the reduced Hamiltonian.\"\n eigenfct::Bool;\nend\n\nabstract type PlotType end;\nstruct SimPlot<:PlotType end;\n\n\"\"\"\n check_path(path::String)\n\nCheck the path given exists and create it if it does not.\n\"\"\"\nfunction check_path(path::String)\n if (!ispath(path))\n mkpath(path)\n end\nend\n\n# Parameters common to all simulation methods.\nfunction gen_filename(p::SimParams, grid::UniformGrid{S,1}) where S\n return string(real(p.Δt) == 0 ? \"ti\" : \"td\",\n round(typeof(grid.Δ), grid.Δ, sigdigits=4), \"d\",\n round(typeof(grid.max), grid.max, sigdigits=4), \"mx\",\n round(typeof(p.Δt), abs(p.Δt), sigdigits=4), \"dt-\", p.steps, \"s\");\nend\n# Simulation variation method.\nfunction gen_filename(var::Vararg{SimVariation})\n name = string();\n\n # Iterate through simulation variations and append parameters to filename.\n for i ∈ var\n if i isa AdaptiveΔt\n name *= string(\"-\", round(i.ϵmax, sigdigits=4), \"emx\",\n round(i.ϵmin, sigdigits=4), \"emn\",\n round(i.Δtdown, sigdigits=4), \"tdn\",\n round(i.Δtup, sigdigits=4), \"tup\", \n round(i.Δtmax, sigdigits=4), \"tmx\",\n round(i.Δtmin, sigdigits=4), \"tmn\", \n i.maxeval, \"mxev\");\n if i.maxevallimit != nothing\n name *= string(i.maxevallimit, \"mxevlm\");\n end\n elseif i isa ConvergenceVariation\n name *= string(\"-\", i.ϵ, \"ecnv\");\n end\n end\n\n return name;\nend\n# Common plotting options.\nfunction gen_filename(plt::PlotOptions)\n if plt.components\n return string(\"pcmpnt\");\n end\n return string();\nend\n# Simulation specific methods.\nfunction gen_filename(sim::Lanczos, plt::LanczosPlotOptions)\n name = string(\"-sil-\", sim.basisno, \"b\", sim.basissteps, \"bs-\" );\n\n if plt.basis name *= string(\"pb\"); end\n if plt.eigenfct name *= string(\"pefct\"); end\n \n name *= gen_filename(plt);\n\n return name;\nend\nfunction gen_filename(sim::SplitStep, plt::SplitStepPlotOptions)\n name = string(\"-ss-\");\n\n name *= gen_filename(plt);\n\n return name\nend\n\"\"\"\n gen_filename(p::SimParams, grid::UniformGrid{S,1},\n sim::SimMethod, plt::PlotOptions,\n var::Union{Vararg{SimVariation},Nothing}=nothing) where S\n\nGenerate an appropriate filename reflecting the parameters used in the\nsimulation.\n\"\"\"\nfunction gen_filename(p::SimParams, grid::UniformGrid{S,1},\n sim::SimMethod, plt::PlotOptions,\n var::Vararg{Union{Nothing,SimVariation}}=nothing) where S\n name = gen_filename(p, grid);\n name *= gen_filename(sim, plt);\n if (var[1] != nothing) name *= gen_filename(var...); end\n\n return name;\nend\n\n\"\"\"\n format_plot_title_variable(variable::Number, decimalplaces::Integer)\n\nFormat `variable` with a fixed number of decimal places given by `decimalplaces`\nsuch that it is in a suitable format to be printed in a GIF frame.\n\"\"\"\nfunction format_plot_title_variable(variable::Unitful.Quantity, decimalplaces::Integer)\n return string(format_plot_title_variable(ustrip(variable), decimalplaces),\n \" \", unit(variable));\nend\nfunction format_plot_title_variable(variable::Number, decimalplaces::Integer)\n # Determine number of digits before the decimal place.\n predecimal = findfirst(\".\", string(variable));\n if predecimal === nothing predecimal = length(string(variable));\n else predecimal = predecimal[1]-1 end\n\n return string(rpad(round(variable, digits=decimalplaces),\n predecimal+decimalplaces+1, '0'));\nend\n\n\"\"\"\n get_effective_minmax(v::AbstractVector, ϵ::Float64=0.1)\n\nReturn the minimum and maximum indices of `v` below and above which the value of\n`v` does not exceed `ϵ`.\n\"\"\"\nfunction get_effective_minmax(v::AbstractVector, ϵ::Number=0.1)\n len = length(v);\n min = 1;\n max = len;\n # Find the first and last indices of v where v > ϵ.\n for i ∈ 1:len\n if abs(v[i]) > ϵ\n min = i;\n break;\n end;\n end\n for i ∈ len:-1:1\n if abs(v[i]) > ϵ\n max = i;\n break;\n end\n end\n\n return (min, max);\nend\nfunction get_effective_minmax(v::Vararg{AbstractVector}; ϵ=0.1)\n len = length(v);\n mins = Vector{Int}(undef, len);\n maxs = Vector{Int}(undef, len);\n\n for i ∈ 1:len\n (mins[i], maxs[i]) = get_effective_minmax(v[i], ϵ);\n end\n\n return (mins, maxs);\nend\n\"\"\"\n get_effective_minmax(m::AbstractMatrix, ϵ::Number=0.1)\n\nTreat the columns of the matrix `m` as vectors.\n\"\"\"\nfunction get_effective_minmax(m::AbstractMatrix, ϵ::Number=0.1)\n numv = size(m)[2];\n mins = Vector{Int}(undef, numv);\n maxs = Vector{Int}(undef, numv);\n\n for i ∈ 1:numv\n (mins[i], maxs[i]) = get_effective_minmax(m[:,i], ϵ);\n end\n\n return (mins, maxs);\nend\n\n\"\"\"\n get_global_effective_minmax(v::Vararg{AbstractVector}; ϵ=0.1)\n\nReturns the maximum and minimum values found by the respective\n`get_effective_minmax()` function.\n\nSee also: [`get_effective_minmax`](@ref)\n\"\"\"\nfunction get_global_effective_minmax(v::Vararg{AbstractVector}; ϵ=0.1)\n (xmins, xmaxs) = get_effective_minmax(v..., ϵ=ϵ);\n return (minimum(xmins), maximum(xmaxs));\nend\nfunction get_global_effective_minmax(m::AbstractMatrix, ϵ::Number=0.1)\n (xmins, xmaxs) = get_effective_minmax(m, ϵ);\n return (minimum(xmins), maximum(xmaxs));\nend\n\n\"\"\"\n get_ranged_minmax(min::Int, max::Int, v::Vararg{AbstractVector})\n\nFind the minimum and maximum of the `v` in the index range `min:max`.\n\nNote: values of the `v` should be real to allow size comparison.\n\"\"\"\nfunction get_ranged_minmax(min::Int, max::Int, v::Vararg{AbstractVector})\n ymin = 0.0;\n ymax = 0.0;\n for i ∈ 2:numψ\n w = v[i][xmin:xmax];\n t = minimum(w);\n if (t < ymin || i == 1) ymin = t; end\n t = maxmum(w);\n if (t > ymmax || i ==1) ymax = t; end\n end\n\n return (ymin, ymax);\nend\n\n\"\"\"\n subscript(i::Integer)\n\nGenerate a string with a subscript number `i`. From Stack Overflow user\nimprobable https://stackoverflow.com/a/46709534.\n\"\"\"\nsubscript(i::Integer) = i<0 ? error(\"$i is negative\") : join('₀'+d for d in reverse(digits(i)));\n\n\"\"\"\n generate_wavefunction_labels(num::Int)\n\nGenerate labels to identify `num` wave functions.\n\"\"\"\nfunction generate_wavefunction_labels(num::Int)\n labels = Vector{String}(undef, num);\n if (num == 1) labels[1] = \"|ψ|²\";\n else\n for i ∈ 1:num labels[i] = string(\"|ψ\", subscript(i), \"|²\"); end\n end\n return reshape(labels, 1, num);\nend\n\n\"Set appropriate axis labels\"\n@recipe function f(::Type{O}, x::Vector, y::Array) where\n {T,N,S<:ConfigurationSpace,O<:WaveObject{T,N,S,1}}\n xguide --> \"r\";\n yguide --> \"Probability density\";\n (x, y)\nend\n@recipe function f(::Type{O}, x::Vector, y::Array) where\n {T,N,S<:MomentumSpace,O<:WaveObject{T,N,S,1}}\n xguide --> \"k\";\n yguide --> \"Probability density\";\n (x, y)\nend\n\n\"\"\"\n vectors_to_matrix(v::Tuple{Vararg{Vector}}, min::Int=1, max::Int=0)\n\nConstruct a matrix from the vectors `v` between the indices `min` and `max`.\n\"\"\"\nfunction vectors_to_matrix(v::Tuple{Vararg{AbstractVector}}, min::Int=1, max::Int=0)\n num = length(v);\n if (max == 0) max = num; end\n\n m = Matrix{Number}(undef, max - min + 1, num);\n for i ∈ 1:num m[:,i] = abs2.(v[i][min:max]); end\n\n return m;\nend\n\n\"Plot absolute square of wave function across relevant range.\"\n@recipe function f(grid::Grid1D, ψ::Vararg{WaveFunction{T,1}};\n opts=GeneralPlotOptions()) where T\n (opts, grid, ψ...);\nend\n# Keyword arguments are not dispatched properly in the recipe chain,\n# so define this alternative order of the arguments to implement the function.\n# 2020/12/01\n@recipe function f(opts::PlotOptions, grid::Grid1D,\n ψ::Vararg{WaveFunction{T,1}}) where T\n label --> generate_wavefunction_labels(length(ψ));\n\n (min, max) = get_global_effective_minmax(ψ..., ϵ=opts.extremaϵ);\n\n (typeof(ψ[1]), grid[min:max], vectors_to_matrix(ψ, min, max));\nend\n\n\"\"\"\nPlot potential function and absolute square of wave function across interesting\nwave function range.\n\"\"\"\n@recipe function f(grid::Grid1D, H::SeparableHamiltonian,\n ψ::Vararg{WaveFunction{T,1}};\n opts=GeneralPlotOptions()) where T\n (opts, grid, H, ψ...);\nend\n# Workaround for same issue as above.\n@recipe function f(opts::PlotOptions, grid::Grid1D, H::SeparableHamiltonian,\n ψ::Vararg{WaveFunction{T,1}}) where T\n label --> hcat([\"Potential\"], generate_wavefunction_labels(length(ψ)));\n\n (min, max) = get_global_effective_minmax(ψ..., ϵ=opts.extremaϵ);\n\n (typeof(ψ[1]), grid[min:max], hcat(real.(H.V[min:max]),\n vectors_to_matrix(ψ, min, max)));\nend\n\n\"\"\"\nPlot absolute square of wave function components of wave matrix across relevant\nrange.\n\"\"\"\n@recipe function f(grid::G, ϕ::WaveMatrix{T,S,G},\n opts::PlotOptions=GeneralPlotOptions()) where {T,S,G}\n label --> generate_wavefunction_labels(size(ϕ)[2]);\n\n (min, max) = get_global_effective_minmax(ϕ, opts.extremaϵ);\n\n (typeof(ϕ), grid[min:max], abs2.(ϕ[min:max,:]))\nend\n\n\"\"\"\nPlot potential function and absolute square of wave function components of wave\nmatrix across relevant range.\n\"\"\"\n@recipe function f(grid::G, H::SeparableHamiltonian, ϕ::WaveMatrix{T,S,G},\n opts::PlotOptions=GeneralPlotOptions()) where {T,S,G}\n label --> hcat([\"Potential\"], generate_wavefunction_labels(size(ϕ)[2]));\n\n (min, max) = get_global_effective_minmax(ϕ, opts.extremaϵ);\n\n (typeof(ϕ), grid[min:max], hcat(real.(H.V[min:max]),\n abs2.(ϕ[min:max,:])))\nend\n\n\"Plot potential functions included in the passed Hamiltonians.\"\n@recipe function f(grid::Grid1D, H::Vararg{SeparableHamiltonian})\n potentials = Vector{Vector{real(eltype(H[1]))}}(undef, length(H));\n for i ∈ 1:length(H) potentials[i] = real.(H[i].V); end\n (grid, potentials)\nend\n\n\"Plot real and imaginary parts of wave functions alongside main plot.\"\n@recipe function f(p::SimPlot, opts::PlotOptions, g::G, ψ::WaveFunction{T,1,S,G},\n H::Union{SeparableHamiltonian,Nothing}=nothing) where {T,S,G}\n size := (800, 450);\n dpi := 300;\n\n if opts.components\n #layout := @layout [ a{0.6w} grid(2,1) ]\n layout := @layout [ a{0.5w} b ]\n\n @series begin\n subplot := 2;\n title := \"Wave function decomposition\";\n ylims := (-1,1);\n realψ = real.(ψ);\n (remin, remax) = get_effective_minmax(realψ, opts.extremaϵ);\n imagψ = imag.(ψ);\n (immin, immax) = get_effective_minmax(imagψ, opts.extremaϵ);\n min = Base.min(immin, remin);\n max = Base.max(immax, remax);\n label := hcat([\"Re(ψ)\"], [\"Im(ψ)\"]);\n (g[min:max], hcat(realψ[min:max], imagψ[min:max]))\n end\n # Allow negative y values on subplots.\n #=\n try\n subylims = ylims();\n if subylims[1] >= 0\n subylims = (-subylims[2], subylims[2]);\n end\n catch\n end=#\n\n #=@series begin\n subplot := 2;\n title := \"Re(ψ)\";\n ylims := (-1,1);\n realψ = real.(ψ);\n (min, max) = get_effective_minmax(realψ, opts.extremaϵ);\n (g[min:max], realψ[min:max])\n end\n \n @series begin\n subplot := 3;\n title := \"Im(ψ)\";\n ylims := (-1,1);\n imagψ = imag.(ψ);\n (min, max) = get_effective_minmax(imagψ, opts.extremaϵ);\n (g[min:max], imagψ[min:max])\n end=#\n end\n\n @series begin\n subplot := 1;\n if (H === nothing) return (opts, g, ψ);\n else return (opts, g, H, ψ); end\n end\nend\n\n\"Plot Krylov basis and reduced Hamiltonian eigenfunctions from Lanczos method.\"\n@recipe function f(p::SimPlot, opts::LanczosPlotOptions, g::G, ψ::WaveFunction{T,1,S,G},\n Φ::KrylovBasis{T,S,G}, H::Union{SeparableHamiltonian,Nothing}=nothing) where {T,S,G}\n if opts.components && opts.basis && opts.eigenfct\n layout := @layout [ a{0.7w} grid(2,1); grid(1,2){0.4h}]\n size := (1400, 750);\n elseif !opts.components && opts.basis && opts.eigenfct\n layout := @layout [ a; grid(1,2)]\n size := (1400, 750);\n elseif !opts.components && !opts.basis && !opts.eigenfct\n size := (1400, 750);\n elseif opts.components && !opts.basis && !opts.eigenfct\n layout := @layout [ a{0.6w} grid(2,1) ]\n size := (1400, 750);\n else\n error(\"the requested plotting format has not yet been implemented.\");\n end\n\n if opts.components\n @series begin\n subplot := 2;\n title := \"Re(ψ)\";\n ylims := (-1,1);\n realψ = real.(ψ);\n (min, max) = get_effective_minmax(realψ, opts.extremaϵ);\n (g[min:max], realψ[min:max])\n end\n @series begin\n subplot := 3;\n title := \"Im(ψ)\";\n ylims := (-1,1);\n imagψ = imag.(ψ);\n (min, max) = get_effective_minmax(imagψ, opts.extremaϵ);\n (g[min:max], imagψ[min:max])\n end\n end\n if opts.basis && opts.eigenfct\n # Plot basis functions.\n @series begin\n if !opts.components subplot := 2;\n else subplot := 4; end\n title := \"Krylov Basis\"\n (g, Φ, opts)\n end\n\n # Plot eigenfunctions.\n @series begin\n if !opts.components subplot := 3;\n else subplot := 5; end\n\n # Label the eigenstates by their energies.\n len = length(Φ.λ);\n labels = Vector{String}(undef, len)\n for i ∈ 1:len labels[i] = string(\"|ψ|² where E = \", round(Φ.λ[i], sigdigits=4)); end\n label := reshape(labels, 1, len);\n\n title := \"Reduced Hamiltonian Eigenstates\"\n (g, KrylovBasis{T,S,G}(Φ*Φ.v, Φ.λ, Φ.v, Φ.Δ), opts)\n end\n end\n\n @series begin\n subplot := 1;\n if (H === nothing) return (opts, g, ψ);\n else return (opts, g, H, ψ); end\n end\nend\n", "meta": {"hexsha": "16e60fee0ba3d4d48ce6ee98db10d104cefb851c", "size": 15033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plot.jl", "max_stars_repo_name": "sw104/QuantumSimulation.jl", "max_stars_repo_head_hexsha": "cb35059dd07d39fcfc869f635cd8d2418b6b7b59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plot.jl", "max_issues_repo_name": "sw104/QuantumSimulation.jl", "max_issues_repo_head_hexsha": "cb35059dd07d39fcfc869f635cd8d2418b6b7b59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plot.jl", "max_forks_repo_name": "sw104/QuantumSimulation.jl", "max_forks_repo_head_hexsha": "cb35059dd07d39fcfc869f635cd8d2418b6b7b59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.650887574, "max_line_length": 103, "alphanum_fraction": 0.6445819198, "num_tokens": 4439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23901246861003952}} {"text": "#=\nThis file is auto-generated. Do not edit.\n=#\n\"\"\"\n mutable struct AVRTypeI <: AVR\n Ka::Float64\n Ke::Float64\n Kf::Float64\n Ta::Float64\n Te::Float64\n Tf::Float64\n Tr::Float64\n Vr_max::Float64\n Vr_min::Float64\n Ae::Float64\n Be::Float64\n V_ref::Float64\n ext::Dict{String, Any}\n states::Vector{Symbol}\n n_states::Int64\n internal::InfrastructureSystemsInternal\n end\n\nParameters of an Automatic Voltage Regulator Type I - Resembles IEEE Type DC1\n\n# Arguments\n- `Ka::Float64`: Amplifier Gain, validation range: (0, nothing)\n- `Ke::Float64`: Field circuit integral deviation, validation range: (0, nothing)\n- `Kf::Float64`: Stabilizer Gain in s * pu/pu, validation range: (0, nothing)\n- `Ta::Float64`: Amplifier Time Constant in s, validation range: (0, nothing)\n- `Te::Float64`: Field Circuit Time Constant in s, validation range: (0, nothing)\n- `Tf::Float64`: Stabilizer Time Constant in s, validation range: (0, nothing)\n- `Tr::Float64`: Voltage Measurement Time Constant in s, validation range: (0, nothing)\n- `Vr_max::Float64`: Maximum regulator voltage in pu, validation range: (0, nothing)\n- `Vr_min::Float64`: Minimum regulator voltage in pu, validation range: (0, nothing)\n- `Ae::Float64`: 1st ceiling coefficient, validation range: (0, nothing)\n- `Be::Float64`: 2nd ceiling coefficient, validation range: (0, nothing)\n- `V_ref::Float64`: Reference Voltage Set-point, validation range: (0, nothing)\n- `ext::Dict{String, Any}`\n- `states::Vector{Symbol}`\n- `n_states::Int64`\n- `internal::InfrastructureSystemsInternal`: power system internal reference, do not modify\n\"\"\"\nmutable struct AVRTypeI <: AVR\n \"Amplifier Gain\"\n Ka::Float64\n \"Field circuit integral deviation\"\n Ke::Float64\n \"Stabilizer Gain in s * pu/pu\"\n Kf::Float64\n \"Amplifier Time Constant in s\"\n Ta::Float64\n \"Field Circuit Time Constant in s\"\n Te::Float64\n \"Stabilizer Time Constant in s\"\n Tf::Float64\n \"Voltage Measurement Time Constant in s\"\n Tr::Float64\n \"Maximum regulator voltage in pu\"\n Vr_max::Float64\n \"Minimum regulator voltage in pu\"\n Vr_min::Float64\n \"1st ceiling coefficient\"\n Ae::Float64\n \"2nd ceiling coefficient\"\n Be::Float64\n \"Reference Voltage Set-point\"\n V_ref::Float64\n ext::Dict{String, Any}\n states::Vector{Symbol}\n n_states::Int64\n \"power system internal reference, do not modify\"\n internal::InfrastructureSystemsInternal\nend\n\nfunction AVRTypeI(Ka, Ke, Kf, Ta, Te, Tf, Tr, Vr_max, Vr_min, Ae, Be, V_ref=1.0, ext=Dict{String, Any}(), )\n AVRTypeI(Ka, Ke, Kf, Ta, Te, Tf, Tr, Vr_max, Vr_min, Ae, Be, V_ref, ext, [:Vf, :Vr1, :Vr2, :Vm], 4, InfrastructureSystemsInternal(), )\nend\n\nfunction AVRTypeI(; Ka, Ke, Kf, Ta, Te, Tf, Tr, Vr_max, Vr_min, Ae, Be, V_ref=1.0, ext=Dict{String, Any}(), )\n AVRTypeI(Ka, Ke, Kf, Ta, Te, Tf, Tr, Vr_max, Vr_min, Ae, Be, V_ref, ext, )\nend\n\n# Constructor for demo purposes; non-functional.\nfunction AVRTypeI(::Nothing)\n AVRTypeI(;\n Ka=0,\n Ke=0,\n Kf=0,\n Ta=0,\n Te=0,\n Tf=0,\n Tr=0,\n Vr_max=0,\n Vr_min=0,\n Ae=0,\n Be=0,\n V_ref=0,\n ext=Dict{String, Any}(),\n )\nend\n\n\"\"\"Get AVRTypeI Ka.\"\"\"\nget_Ka(value::AVRTypeI) = value.Ka\n\"\"\"Get AVRTypeI Ke.\"\"\"\nget_Ke(value::AVRTypeI) = value.Ke\n\"\"\"Get AVRTypeI Kf.\"\"\"\nget_Kf(value::AVRTypeI) = value.Kf\n\"\"\"Get AVRTypeI Ta.\"\"\"\nget_Ta(value::AVRTypeI) = value.Ta\n\"\"\"Get AVRTypeI Te.\"\"\"\nget_Te(value::AVRTypeI) = value.Te\n\"\"\"Get AVRTypeI Tf.\"\"\"\nget_Tf(value::AVRTypeI) = value.Tf\n\"\"\"Get AVRTypeI Tr.\"\"\"\nget_Tr(value::AVRTypeI) = value.Tr\n\"\"\"Get AVRTypeI Vr_max.\"\"\"\nget_Vr_max(value::AVRTypeI) = value.Vr_max\n\"\"\"Get AVRTypeI Vr_min.\"\"\"\nget_Vr_min(value::AVRTypeI) = value.Vr_min\n\"\"\"Get AVRTypeI Ae.\"\"\"\nget_Ae(value::AVRTypeI) = value.Ae\n\"\"\"Get AVRTypeI Be.\"\"\"\nget_Be(value::AVRTypeI) = value.Be\n\"\"\"Get AVRTypeI V_ref.\"\"\"\nget_V_ref(value::AVRTypeI) = value.V_ref\n\"\"\"Get AVRTypeI ext.\"\"\"\nget_ext(value::AVRTypeI) = value.ext\n\"\"\"Get AVRTypeI states.\"\"\"\nget_states(value::AVRTypeI) = value.states\n\"\"\"Get AVRTypeI n_states.\"\"\"\nget_n_states(value::AVRTypeI) = value.n_states\n\"\"\"Get AVRTypeI internal.\"\"\"\nget_internal(value::AVRTypeI) = value.internal\n\n\"\"\"Set AVRTypeI Ka.\"\"\"\nset_Ka!(value::AVRTypeI, val::Float64) = value.Ka = val\n\"\"\"Set AVRTypeI Ke.\"\"\"\nset_Ke!(value::AVRTypeI, val::Float64) = value.Ke = val\n\"\"\"Set AVRTypeI Kf.\"\"\"\nset_Kf!(value::AVRTypeI, val::Float64) = value.Kf = val\n\"\"\"Set AVRTypeI Ta.\"\"\"\nset_Ta!(value::AVRTypeI, val::Float64) = value.Ta = val\n\"\"\"Set AVRTypeI Te.\"\"\"\nset_Te!(value::AVRTypeI, val::Float64) = value.Te = val\n\"\"\"Set AVRTypeI Tf.\"\"\"\nset_Tf!(value::AVRTypeI, val::Float64) = value.Tf = val\n\"\"\"Set AVRTypeI Tr.\"\"\"\nset_Tr!(value::AVRTypeI, val::Float64) = value.Tr = val\n\"\"\"Set AVRTypeI Vr_max.\"\"\"\nset_Vr_max!(value::AVRTypeI, val::Float64) = value.Vr_max = val\n\"\"\"Set AVRTypeI Vr_min.\"\"\"\nset_Vr_min!(value::AVRTypeI, val::Float64) = value.Vr_min = val\n\"\"\"Set AVRTypeI Ae.\"\"\"\nset_Ae!(value::AVRTypeI, val::Float64) = value.Ae = val\n\"\"\"Set AVRTypeI Be.\"\"\"\nset_Be!(value::AVRTypeI, val::Float64) = value.Be = val\n\"\"\"Set AVRTypeI V_ref.\"\"\"\nset_V_ref!(value::AVRTypeI, val::Float64) = value.V_ref = val\n\"\"\"Set AVRTypeI ext.\"\"\"\nset_ext!(value::AVRTypeI, val::Dict{String, Any}) = value.ext = val\n\"\"\"Set AVRTypeI states.\"\"\"\nset_states!(value::AVRTypeI, val::Vector{Symbol}) = value.states = val\n\"\"\"Set AVRTypeI n_states.\"\"\"\nset_n_states!(value::AVRTypeI, val::Int64) = value.n_states = val\n\"\"\"Set AVRTypeI internal.\"\"\"\nset_internal!(value::AVRTypeI, val::InfrastructureSystemsInternal) = value.internal = val\n", "meta": {"hexsha": "3ce76b14f97a6fd51493bc4e35a7a0ba5d2db112", "size": 5679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/generated/AVRTypeI.jl", "max_stars_repo_name": "Nongchao/PowerSystems.jl", "max_stars_repo_head_hexsha": "0d7e74e71dc8957e3bf5f27846ec22d22ece7172", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-29T04:22:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-29T04:22:46.000Z", "max_issues_repo_path": "src/models/generated/AVRTypeI.jl", "max_issues_repo_name": "Nongchao/PowerSystems.jl", "max_issues_repo_head_hexsha": "0d7e74e71dc8957e3bf5f27846ec22d22ece7172", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/generated/AVRTypeI.jl", "max_forks_repo_name": "Nongchao/PowerSystems.jl", "max_forks_repo_head_hexsha": "0d7e74e71dc8957e3bf5f27846ec22d22ece7172", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8035714286, "max_line_length": 138, "alphanum_fraction": 0.6643775313, "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.2389800188821294}} {"text": "\"\"\"\nCalculate value, gradient, and hessian of the variational ELBO.\n\"\"\"\nmodule DeterministicVI\n\nusing Base.Threads: threadid, nthreads\n\nimport ..Config\nusing ..BivariateNormals: BivariateNormalDerivatives, BvnComponent,\n GalaxySigmaDerivs, get_bvn_cov, eval_bvn_pdf!,\n get_bvn_derivs!, transform_bvn_derivs!\nusing ..Model\nusing ..Model: SkyPatch, BvnBundle, populate_fsm!\nimport ..Celeste: Const, @aliasscope, @unroll_loop\nimport ..Infer\nusing ..SensitiveFloats\nimport ..Log\nusing ..Transform\nimport DataFrames\nimport Optim\nimport ForwardDiff.Dual\nusing StaticArrays\nimport Base: convert\n\nexport ElboArgs, generic_init_source, catalog_init_source, init_sources,\n VariationalParams, elbo, ElboIntermediateVariables\n\nfunction init_thread_pool!(pool::Vector, create)\n if length(pool) != Base.Threads.nthreads()\n empty!(pool)\n for i = 1:Base.Threads.nthreads()\n push!(pool, create())\n end\n end\nend\n\n\"\"\"\nReturn a default-initialized VariationalParams instance.\n\"\"\"\nfunction generic_init_source(init_pos::Vector{Float64})\n ret = Vector{Float64}(length(CanonicalParams))\n ret[ids.is_star] = 0.5\n ret[ids.pos] = init_pos\n ret[ids.flux_loc] = log(2.0)\n ret[ids.flux_scale] = 1e-3\n ret[ids.gal_fracdev] = 0.5\n ret[ids.gal_ab] = 0.5\n ret[ids.gal_angle] = 0.0\n ret[ids.gal_scale] = 1.0\n ret[ids.k] = 1.0 / size(ids.k, 1)\n ret[ids.color_mean] = 0.0\n ret[ids.color_var] = 1e-2\n ret\nend\n\n\n\"\"\"\nReturn VariationalParams instance initialized form a catalog entry\n\"\"\"\nfunction catalog_init_source(ce::CatalogEntry; max_gal_scale=Inf)\n # TODO: sync this up with the transform bounds\n ret = generic_init_source(ce.pos)\n\n # TODO: don't do this thresholding for background sources,\n # just for sources that are being optimized\n ret[ids.is_star[1]] = ce.is_star ? 0.8: 0.2\n ret[ids.is_star[2]] = ce.is_star ? 0.2: 0.8\n\n ret[ids.flux_loc[1]] = log(max(0.1, ce.star_fluxes[3]))\n ret[ids.flux_loc[2]] = log(max(0.1, ce.gal_fluxes[3]))\n\n function get_color(color_var, color_mean)\n color_var > 0 && color_mean > 0 ? min(max(log(color_var / color_mean), -9.), 9.) :\n color_var > 0 && color_mean <= 0 ? 3.0 :\n color_var <= 0 && color_mean > 0 ? -3.0 : 0.0\n end\n\n function get_colors(raw_fluxes)\n [get_color(raw_fluxes[c+1], raw_fluxes[c]) for c in 1:4]\n end\n\n ret[ids.color_mean[:, 1]] = get_colors(ce.star_fluxes)\n ret[ids.color_mean[:, 2]] = get_colors(ce.gal_fluxes)\n\n ret[ids.gal_fracdev] = min(max(ce.gal_frac_dev, 0.015), 0.985)\n\n ret[ids.gal_ab] = ce.is_star ? .8 : min(max(ce.gal_ab, 0.015), 0.985)\n ret[ids.gal_angle] = ce.gal_angle\n ret[ids.gal_scale] = ce.is_star ? 0.2 : min(max_gal_scale, max(ce.gal_scale, 0.2))\n\n ret\nend\n\n\nfunction init_sources(target_sources::Vector{Int}, catalog::Vector{CatalogEntry})\n ret = Vector{Vector{Float64}}(length(catalog))\n for s in 1:length(catalog)\n ret[s] = catalog_init_source(catalog[s])\n end\n for s in target_sources\n ret[s][:] = generic_init_source(catalog[s].pos)\n end\n ret\nend\n\n\ninclude(\"deterministic_vi/elbo_args.jl\")\ninclude(\"deterministic_vi/elbo_kl.jl\")\ninclude(\"deterministic_vi/source_brightness.jl\")\ninclude(\"deterministic_vi/elbo_objective.jl\")\ninclude(\"deterministic_vi/ConstraintTransforms.jl\")\ninclude(\"deterministic_vi/ElboMaximize.jl\")\n\n\n\"\"\"\nInfers one light source. This routine is intended to be called in parallel,\nonce per target light source.\n\nArguments:\n images: a collection of astronomical images\n neighbors: the other light sources near `entry`\n entry: the source to infer\n\"\"\"\nfunction infer_source(config::Config,\n images::Vector{Image},\n neighbors::Vector{CatalogEntry},\n entry::CatalogEntry)\n if length(neighbors) > 100\n msg = string(\"object at RA, Dec = $(entry.pos) has an excessive\",\n \"number ($(length(neighbors))) of neighbors\")\n Log.warn(msg)\n end\n\n # It's a bit inefficient to call the next 5 lines every time we optimize_f.\n # But, as long as runtime is dominated by the call to maximize!, that\n # isn't a big deal.\n cat_local = vcat([entry], neighbors)\n vp = init_sources([1], cat_local)\n patches = Infer.get_sky_patches(images, cat_local)\n Infer.load_active_pixels!(config, images, patches)\n\n ea = ElboArgs(images, patches, [1])\n f_evals, max_f, max_x, nm_result = ElboMaximize.maximize!(ea, vp)\n return vp[1]\nend\n\n# legacy wrapper\nfunction infer_source(images::Vector{Image},\n neighbors::Vector{CatalogEntry},\n entry::CatalogEntry)\n infer_source(Config(), images, neighbors, entry)\nend\n\nend\n", "meta": {"hexsha": "ba47beab0c86c14274be6586162829dba2d78555", "size": 4801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DeterministicVI.jl", "max_stars_repo_name": "giordano/Celeste.jl", "max_stars_repo_head_hexsha": "2353019d3a737129364b5fa88220e37be07eebea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DeterministicVI.jl", "max_issues_repo_name": "giordano/Celeste.jl", "max_issues_repo_head_hexsha": "2353019d3a737129364b5fa88220e37be07eebea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DeterministicVI.jl", "max_forks_repo_name": "giordano/Celeste.jl", "max_forks_repo_head_hexsha": "2353019d3a737129364b5fa88220e37be07eebea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9741935484, "max_line_length": 90, "alphanum_fraction": 0.6704853156, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23895338462622037}} {"text": "# low-level interface, meaning works with vectors and matrices, not data frames and estimation objects\n\n\"Structure to store test results\"\nstruct BootTestResult{T}\n stat::T; stattype::String\n p::T; padj::T\n reps::Int64; repsfeas::Int64\n nbootclust::Int64\n dof::Int64; dof_r::T\n plot::Union{Nothing, NamedTuple{(:X, :p), Tuple{Tuple{Vararg{Vector{T}, N} where N},Vector{T}}}}\n peak::Union{Nothing, NamedTuple{(:X, :p), Tuple{Vector{T}, T}}}\n ci::Union{Nothing, Matrix{T}}\n dist::Matrix{T}\n b::Vector{T}\n V::Matrix{T}\n auxweights::Union{Nothing,Matrix{T}}\n # M::StrBootTest\nend\n\n\"Return test statistic\"\nteststat(o::BootTestResult) = o.stat\n\n\"Return numerator of test statistic\"\nstatnumer(o::BootTestResult) = o.b\n\n\"Return denominator of test statistic\"\nstatvar(o::BootTestResult) = o.V\n\n\"\"\"Return type of test statistic: \"t\", \"z\", \"F\", or \"χ²\" \"\"\"\nstattype(o::BootTestResult) = o.stattype\n\n\"Return p value\"\np(o::BootTestResult) = o.p\n\n\"Return p value after multiple-hypothesis adjustment, if any\"\npadj(o::BootTestResult) = o.padj\n\n\"Return requested number of replications\"\nreps(o::BootTestResult) = o.reps\n\n\"Return actual number of replications, subject to enumeration of Rademacher draws\"\nrepsfeas(o::BootTestResult) = o.repsfeas\n\n\"Return number of bootstrapping clusters in test\"\nnbootclust(o::BootTestResult) = o.nbootclust\n\n\"Return degrees of freedom of test\"\ndof(o::BootTestResult) = o.dof\n\n\"Return residual degrees of freedom of test\"\ndof_r(o::BootTestResult) = o.dof_r\n\n\"\"\"\nReturn data for confidence plot of test.\nReturn value is a 2-tuple with named entries `X` and `p` holding\nthe confidence sampling locations and p values respectively. `X` is in turn\na 1- or 2-tuple of vectors of sampling coordinates for each \ndimension of the tested hypothesis.\n\"\"\"\nplotpoints(o::BootTestResult) = o.plot\n\n\"Return parameter value with peak p value in test\"\npeak(o::BootTestResult) = o.peak\n\n\"Return confidence interval matrix from test, one row per disjoint piece\"\nci(o::BootTestResult) = o.ci\n\n\"Return bootstrap distribution of statistic or statistic numerator in bootstrap test\"\ndist(o::BootTestResult) = o.dist\n\n\"Return auxilliary weight matrix for wild bootstrap\"\nauxweights(o::BootTestResult) = o.auxweights\n\nstrint(x) = iszero(mod(x,1)) ? \"$(Int64(x))\" : \"$x\"\nfunction Base.show(io::IO, o::BootTestResult{T}) where T\n\ts = stattype(o) * ( iszero(dof_r(o)) ? isone(dof(o)) ? \" \" : \"(\" * strint(dof(o)) * \")\" : # z, χ²\n\t isone(dof(o)) ? \"(\" * strint(dof_r(o)) * \")\" : \"(\" * strint(dof(o)) * \", \" * strint(dof_r(o)) * \")\" ) # t, F\n\tPrintf.@printf(io, \"%s = %6.4f\\n\", s, teststat(o))\n\tPrintf.@printf(io, \"p%s = %6.4f\\n\", repeat(\" \", length(s)-1), p(o))\n\tisdefined(o, :ci) && !isnothing(o.ci) && length(o.ci)>0 && print(io, \"CI\" * repeat(\" \", length(s)-2) * \" = $(round.(ci(o); sigdigits=4))\\n\")\nend\n\n# single entry point with arguments already converted to standardized types, to allow a smaller set of precompile() calls(?)\nfunction __wildboottest(\n\tR::Matrix{T},\n\tr::Vector{T};\n\tresp::VecOrMat{T},\n\tpredexog::Matrix{T},\n\tpredendog::Matrix{T},\n\tinst::Matrix{T},\n\tR1::Matrix{T},\n\tr1::Vector{T},\n\tclustid::Matrix{Int64},\n\tnbootclustvar::Int64,\n\tnerrclustvar::Int64,\n\tissorted::Bool,\n\thetrobust::Bool,\n\tnfe::Int64,\n\tfeid::VecOrMat{Int64},\n\tfedfadj::Int64,\n\tobswt::VecOrMat{T},\n\tfweights::Bool,\n\tmaxmatsize::Float16,\n\tptype::Symbol,\n\tbootstrapc::Bool,\n\tliml::Bool,\n\tfuller::T,\n\tkappa::T,\n\tarubin::Bool,\n\tsmall::Bool,\n\tclusteradj::Bool,\n\tclustermin::Bool,\n\tscorebs::Bool,\n\treps::Int64,\n\timposenull::Bool,\n\tauxwttype::Symbol,\n\trng::AbstractRNG,\n\tlevel::T,\n\trtol::T,\n\tmadjtype::Symbol,\n\tnH0::Int16,\n\tml::Bool,\n\tscores::Matrix{T},\n\tbeta::Vector{T},\n\tA::Symmetric{T,Matrix{T}},\n\tgridmin::VecOrMat{T},\n\tgridmax::VecOrMat{T},\n\tgridpoints::VecOrMat{T},\n\tdiststat::Symbol,\n\tgetci::Bool,\n\tgetplot::Bool,\n\tgetauxweights::Bool) where T\n\n\tM = StrBootTest{T}(R, r, R1, r1, resp, predexog, predendog, inst, obswt, fweights, liml, fuller, kappa, arubin,\n\t reps, auxwttype, rng, maxmatsize, ptype, imposenull, scorebs, !bootstrapc, clustid, nbootclustvar, nerrclustvar, issorted, hetrobust, small, clusteradj, clustermin,\n\t nfe, feid, fedfadj, level, rtol, madjtype, nH0, ml, beta, A, scores, getplot,\n\t gridmin, gridmax, gridpoints)\n\n\tif getplot || (level<1 && getci)\n\t\tplot!(M)\n\t\tplot = getplot & isdefined(M, :plotX) ? (X=Tuple(M.plotX), p=M.plotY) : nothing\n\t\tpeak = M.peak\n\t\tci = level<1 & getci ? M.ci : nothing\n\telse\n\t\tci = plot = peak = nothing\n\tend\n\t\n\tpadj = getp(M) # trigger main (re)computation\n\n\tBootTestResult{T}(getstat(M),\n\t isone(nrows(R)) ? (small ? \"t\" : \"z\") : (small ? \"F\" : \"χ²\"),\n\t M.p, padj, M.B, M.BFeas, M.N✻, M.dof, M.dof_r, plot, peak, ci,\n\t getdist(M, diststat),\n\t getb(M), getV(M),\n\t getauxweights && reps>0 ? getv(M) : nothing #=, M=#)\nend\n\nvecconvert(T::DataType, X) = Vector(isa(X, AbstractArray) ? vec( eltype(X)==T ? X : T.(X)) : X)\nmatconvert(T::DataType, X) = Matrix(isa(X, AbstractArray) ? reshape(eltype(X)==T ? X : T.(X), size(X,1), size(X,2)) : X)\n\nfunction _wildboottest(T::DataType,\n\t\t\t\t\t R::AbstractVecOrMat,\n\t\t\t\t\t\tr::AbstractVecOrMat;\n\t\t\t\t\t resp::AbstractVecOrMat{<:Real},\n\t\t\t\t\t predexog::AbstractVecOrMat{<:Real}=zeros(T,0,0),\n\t\t\t\t\t predendog::AbstractVecOrMat{<:Real}=zeros(T,0,0),\n\t\t\t\t\t inst::AbstractVecOrMat{<:Real}=zeros(T,0,0),\n\t\t\t\t\t R1::AbstractVecOrMat=zeros(T,0,0),\n\t\t\t\t\t\tr1::AbstractVecOrMat=zeros(T,0),\n\t\t\t\t\t hetrobust::Bool=true,\n\t\t\t\t\t clustid::AbstractVecOrMat{<:Integer}=zeros(Int,0,0), # bootstrap-only clust vars, then boot&err clust vars, then err-only clust vars\n\t\t\t\t\t nbootclustvar::Integer=ncols(clustid),\n\t\t\t\t\t nerrclustvar::Integer=nbootclustvar,\n\t\t\t\t\t\tissorted::Bool=false,\n\t\t\t\t\t\tnfe::Integer=0,\n\t\t\t\t\t feid::AbstractVecOrMat{<:Integer}=Int8[],\n\t\t\t\t\t fedfadj::Integer=length(feid)>0 ? -1 : 0,\n\t\t\t\t\t obswt::AbstractVecOrMat{<:Real}=T[],\n\t\t\t\t\t fweights::Bool=false,\n\t\t\t\t\t maxmatsize::Number=0,\n\t\t\t\t\t ptype::Symbol=:symmetric,\n\t\t\t\t\t bootstrapc::Bool=false,\n\t\t\t\t\t liml::Bool=false,\n\t\t\t\t\t fuller::Number=0,\n\t\t\t\t\t kappa::Number=NaN,\n\t\t\t\t\t arubin::Bool=false,\n\t\t\t\t\t small::Bool=true,\n\t\t\t\t\t\tclusteradj::Bool=small,\n\t\t\t\t\t\tclustermin::Bool=false,\n\t\t\t\t\t scorebs::Bool=false,\n\t\t\t\t\t reps::Integer=999,\n\t\t\t\t\t imposenull::Bool=true,\n\t\t\t\t\t auxwttype::Symbol=:rademacher,\n\t\t\t\t\t rng::AbstractRNG=MersenneTwister(),\n\t\t\t\t\t level::Number=.95,\n\t\t\t\t\t rtol::Number=1e-6,\n\t\t\t\t\t madjtype::Symbol=:none,\n\t\t\t\t\t nH0::Integer=1,\n\t\t\t\t\t ml::Bool=false,\n\t\t\t\t\t scores::AbstractVecOrMat=Matrix{Float32}(undef,0,0),\n\t\t\t\t\t beta::AbstractVecOrMat=T[],\n\t\t\t\t\t A::AbstractMatrix=zeros(T,0,0),\n\t\t\t\t\t gridmin::Union{VecOrMat{S},VecOrMat{Union{S,Missing}}} where S<:Number = T[],\n\t\t\t\t\t gridmax::Union{VecOrMat{S},VecOrMat{Union{S,Missing}}} where S<:Number = T[],\n\t\t\t\t\t gridpoints::Union{VecOrMat{S},VecOrMat{Union{S,Missing}}} where S<:Number = Int64[],\n\t\t\t\t\t diststat::Symbol=:none,\n\t\t\t\t\t getci::Bool=true,\n\t\t\t\t\t getplot::Bool=getci,\n\t\t\t\t\t getauxweights::Bool=false)\n\n\tnrows(R)>2 && (getplot = getci = false)\n\n\t@assert any(auxwttype .== (:rademacher, :mammen, :webb, :gamma, :normal)) \"auxwttype shoud be :rademacher, :mammen, :webb, :gamma, or :normal\"\n\t@assert any(ptype .==(:symmetric, :equaltail, :lower, :upper)) \"ptype should be :symmetric, :equaltail, :lower, or :upper\"\n\t@assert any(madjtype .== (:none, :bonferroni, :sidak)) \"madjtype should be :none, :bonferroni, or :sidak\"\n\t@assert any(diststat .== (:none, :t, :numer))\n\t@assert ml || ncols(resp)==1 \"resp should have one column\"\n @assert (length(predexog)==0 || nrows(predexog)==nrows(resp)) && \n\t (length(predendog)==0 || nrows(predendog)==nrows(resp)) &&\n\t\t\t\t\t(length(inst)==0 || nrows(inst)==nrows(resp)) \"All data vectors/matrices must have same height\"\n\t@assert ncols(inst) >= ncols(predendog) \"Model has fewer instruments than instrumented variables\"\n @assert length(feid)==0 || nrows(feid)==nrows(resp) \"feid vector must have same height as data matrices\"\n\t@assert ncols(feid)≤1 \"feid should have one column\"\n @assert length(clustid)==0 || nrows(clustid)==nrows(resp) \"clustid must have same height as data matrices\"\n @assert nrows(obswt)==0 || nrows(obswt)==nrows(resp) \"obswt must have same height as data matrices\"\n\t@assert ncols(obswt)≤1 \"obswt must have one column\"\n @assert nrows(R)==nrows(r) \"R and r must have same height\"\n @assert (ncols(R) == (ml ? nrows(beta) : ncols(predexog)+ncols(predendog)) && isone(ncols(r))) \"Wrong number of columns in null specification\"\n @assert nrows(R1)==nrows(r1) \"R₁ and r₁ must have same height\"\n @assert length(R1)==0 || ncols(R1)==ncols(predexog)+ncols(predendog) \"Wrong number of columns in model constraint specification\"\n\t@assert ncols(r)==1 \"r should have one column\"\n\t@assert length(R1)==0 || ncols(r1)==1 \"r1 should have one column\"\n @assert nbootclustvar ≤ ncols(clustid) \"nbootclustvar > width of clustid\"\n @assert nerrclustvar ≤ ncols(clustid) \"nerrclustvar > width of clustid\"\n @assert reps ≥ 0 \"reps < 0\"\n @assert level ≥ 0. && level≤1. \"level must be in the range [0,1]\"\n @assert rtol > 0. \"rtol ≤ 0\"\n @assert nH0 > 0 \"nH0 ≤ 0\"\n\t@assert !liml || (ncols(predendog)>0 && ncols(inst)>0) \"For liml, non-empty predendog and inst arguments are needed\"\n\t@assert fuller==0 || (ncols(predendog)>0 && ncols(inst)>0) \"For Fuller liml, non-empty predendog and inst arguments are needed\"\n\t@assert iszero(ncols(predendog)) || ncols(inst)>0 \"predendog provided without inst\"\n\t@assert !arubin || ncols(predendog)>0 \"Anderson-Rubin test requested but predendog not provided\"\n\n\tif getplot || getci\n\t\t@assert iszero(length(gridmin )) || length(gridmin )==nrows(R) \"Length of gridmin doesn't match number of hypotheses being jointly tested\"\n\t\t@assert iszero(length(gridmax )) || length(gridmax )==nrows(R) \"Length of gridmax doesn't match number of hypotheses being jointly tested\"\n\t\t@assert iszero(length(gridpoints)) || length(gridpoints)==nrows(R) \"Length of gridpoints doesn't match number of hypotheses being jointly tested\"\n\t\t@assert iszero(length(gridmin )) || ncols(gridmin) ==1 \"gridmin should have one column\"\n\t\t@assert iszero(length(gridmax )) || ncols(gridmax) ==1 \"gridmax should have one column\"\n\t\t@assert iszero(length(gridpoints)) || ncols(gridpoints)==1 \"gridpoints should have one column\"\n\tend\n\n\t_gridmin = Vector{T}(undef, length(gridmin))\n\t_gridmax = Vector{T}(undef, length(gridmax))\n\t_gridpoints = Vector{T}(undef, length(gridpoints))\n\tfor i ∈ 1:length(gridmin) # cumbersome loops because map() and list comprehensions mess up type inference(?!)\n\t\t_gridmin[i] = T(ismissing(gridmin[i]) ? NaN : gridmin[i])\n\tend\n\tfor i ∈ 1:length(gridmax)\n\t\t_gridmax[i] = T(ismissing(gridmax[i]) ? NaN : gridmax[i])\n\tend\n\tfor i ∈ 1:length(gridpoints)\n\t\t_gridpoints[i] = T(ismissing(gridpoints[i]) ? NaN : gridpoints[i])\n\tend\n\n\t__wildboottest(\n\t\tmatconvert(T,R),\n\t\tvecconvert(T,r);\n\t\tresp=vecconvert(T,resp),\n\t\tpredexog=matconvert(T,predexog),\n\t\tpredendog=matconvert(T,predendog),\n\t\tinst=matconvert(T,inst),\n\t\tR1=matconvert(T,R1),\n\t\tr1=vecconvert(T,r1),\n\t\tclustid=matconvert(Int64,clustid),\n\t\tnbootclustvar=Int64(nbootclustvar),\n\t\tnerrclustvar=Int64(nerrclustvar),\n\t\tissorted,\n\t\thetrobust,\n\t\tnfe,\n\t\tfeid=vecconvert(Int64,feid),\n\t\tfedfadj,\n\t\tobswt=vecconvert(T,obswt),\n\t\tfweights,\n\t\tmaxmatsize=Float16(maxmatsize),\n\t\tptype,\n\t\tbootstrapc,\n\t\tliml,\n\t\tfuller=T(fuller),\n\t\tkappa=T(kappa),\n\t\tarubin,\n\t\tsmall,\n\t\tclusteradj,\n\t\tclustermin,\n\t\tscorebs,\n\t\treps=Int64(reps),\n\t\timposenull,\n\t\tauxwttype,\n\t\trng,\n\t\tlevel=T(level),\n\t\trtol=T(rtol),\n\t\tmadjtype,\n\t\tnH0=Int16(nH0),\n\t\tml,\n\t\tscores=matconvert(T,scores),\n\t\tbeta=vecconvert(T,beta),\n\t\tA=Symmetric(matconvert(T,A)),\n\t\tgridmin=_gridmin,\n\t\tgridmax=_gridmax,\n\t\tgridpoints=_gridpoints,\n\t\tdiststat,\n\t\tgetci,\n\t\tgetplot,\n\t\tgetauxweights)\nend\n\n_wildboottest(T::DataType, R, r::Number; kwargs...) = _wildboottest(T, R, [r]; kwargs...)\n_wildboottest(T::DataType, R::UniformScaling{Bool}, r; kwargs...) = _wildboottest(T, diagm(fill(T(R.λ),nrows(r))), r; kwargs...)\n_wildboottest(R::Union{UniformScaling{Bool},AbstractVecOrMat}, r::Union{Number,AbstractVecOrMat}; kwargs...) = _wildboottest(Float64, R, r; kwargs...)\n\n\n\"\"\"\nwildboottest([T::DataType=Float64,] R::AbstractMatrix, r::AbstractVector; \n resp, ) -> WildBootTests.BootTestResult\n\nFunction to perform wild-bootstrap-based hypothesis test\n\n# Positional arguments\n* `T::DataType`: data type for inputs, results, and computations: Float32 or Float64 (default)\n* `R::AbstractMatrix` and `r::AbstractVector`: required matrix and vector expressing the null Rβ=r; see notes below\n\n# Required keyword argument\n* `resp::AbstractVector`: response/dependent variable (y or y₁ in Roodman et al. (2019))\n\n# Optional keyword arguments\n* `predexog::AbstractVecOrMat`: exogenous predictors, including constant term, if any (X/X₁)\n* `predendog::AbstractVecOrMat`: endogenous predictors (Y₂)\n* `inst::AbstractVecOrMat`: instruments (X₂)\n* `R1::AbstractMatrix` and `r1::AbstractVector`: model constraints; same format as for `R` and `r`\n* `clustid::AbstractVecOrMat{<:Integer}`: data vector/matrix of error and bootstrapping cluster identifiers; see Notes \n* `nbootclustvar::Integer=1`: number of bootstrap-clustering variables\n* `nerrclustvar::Integer=nbootclustvar`: number of error-clustering variables\n* `issorted:Bool=false`: time-saving flag: data matrices are already sort by column types 2, then 3, then 1 (see notes)\n* `hetrobust::Bool=true`: true unless errors are treated as iid\n* `nfe::Integer=0`: number of fixed-effect groups; if 0 yet `feid` is provided, will be computed\n* `feid::AbstractVector{<:Integer}`: data vector for one-way fixed effect group identifier\n* `fedfadj::Integer=nfe`: degrees of freedom that fixed effects (if any) consume\n* `obswt::AbstractVector=[]`: observation weight vector; default is equal weighting\n* `fweights::Bool=false`: true for frequency weights\n* `maxmatsize::Number`: maximum size of auxilliary weight matrix (v), in gigabytes\n* `ptype::Symbol=:symmetric`: p value type (`:symmetric`, `:equaltail`, `:lower`, `:upper`)\n* `bootstrapc::Bool=false`: true to request bootstrap-c instead of bootstrap-t\n* `liml::Bool=false`: true for LIML or Fuller LIML\n* `fuller::Number`: Fuller LIML factor\n* `kappa::Number`: fixed κ for _k_-class estimation\n* `arubin::Bool=false`: true for Anderson-Rubin test\n* `small::Bool=true`: true to multiply test statistics by G/(G-1) × N/(N-k), where G, N, k are number of clusters, observations, and predictors\n* `clusteradj::Bool=true`: false to drop G/(G-1) factor\n* `clustermin::Bool=false``: for multiway clustering, true to base G/(G-1) factor for all clusterings ]on the smallest G across clusterings\n* `scorebs::Bool=false`: true for score bootstrap instead of wild bootstrap\n* `reps::Integer=999`: number of bootstrap replications; `reps` = 0 requests classical Rao (or Wald) test if `imposenull` = `true` (or `false`)\n* `imposenull::Bool=true`: true to impose null\n* `auxwttype::Symbol=:rademacher`: auxilliary weight type (`:rademacher`, `:mammen`, `:webb`, `:normal`, `:gamma`)\n* `rng::AbstractRNG=MersenneTwister()`: randon number generator\n* `level::Number=.95`: significance level (0-1)\n* `rtol::Number=1e-6`: tolerance for ci bound determination\n* `madjtype::Symbol=:none`: multiple hypothesis adjustment (`none`, `:bonferroni`, `:sidak`)\n* `nH0::Integer=1`: number of hypotheses tested, including one being tested now\n* `ml::Bool=false`: true for (nonlinear) ML estimation\n* `scores::AbstractVecOrMat`: for ML, pre-computed scores\n* `beta::AbstractVector`: for ML, parameter estimates\n* `A::AbstractMatrix`: for ML, covariance estimates\n* `gridmin`: vector of graph lower bounds; max length 2, `missing`/`NaN` entries ask wildboottest() to choose\n* `gridmax`: vector of graph upper bounds; `missing`/`NaN` entries ask wildboottest() to choose\n* `gridpoints`: vector of number of sampling points; `missing`/`NaN` entries ask wildboottest() to choose\n* `diststat::Symbole=:none`: `:t` to save bootstrap distribution of t/z/F/χ² statistics; `:numer` to save numerators thereof\n* `getci::Bool=true`: whether to return confidence interval\n* `getplot::Bool=getci`: whether to generate plot data\n* `getauxweights::Bool=false`: whether to save auxilliary weight matrix (v)\n\n# Notes\n`T`, `ptype`, `auxwttype`, `madjtype`, and `diststat` may also be strings. Examples: `\"Float32\"` and `\"webb\"`.\n\nThe columns of `R` in the statement of the null should correspond to those of the matrix [`predexog` `predendog`],\nwhere `predendog` is non-empty only in regressions with instruments. \n\nOrder the columns of `clustid` this way:\n1. Variables only used to define bootstrapping clusters, as in the subcluster bootstrap.\n2. Variables used to define both bootstrapping and error clusters.\n3. Variables only used to define error clusters.\n`nbootclustvar` is then the number of columns of type 1 or 2; `nerrclustvar` is the number of columns of type 2 or 3. Typically `clustid` is a single column of type 2. \n\n`wildboottest()` does not handle missing data values: all data and identifier matrices must \nbe restricted to the estimation sample.\n\n\"\"\"\nwildboottest( R, r; kwargs...) = _wildboottest( R, r; Dict(a.first => isa(a.second, AbstractString) ? Meta.parse(a.second) : a.second for a ∈ kwargs)...)\nwildboottest(T, R, r; kwargs...) = _wildboottest(isa(T, AbstractString) ? eval(Meta.parse(T)) : T, R, r; Dict(a.first => isa(a.second, AbstractString) ? Meta.parse(a.second) : a.second for a ∈ kwargs)...)\n", "meta": {"hexsha": "aa99e53fd7f2ea21baa721bd1e58d5b146737edf", "size": 17678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interface.jl", "max_stars_repo_name": "droodman/WildBootTests.jl", "max_stars_repo_head_hexsha": "91a68dfbfbe4cfe6f495acd14b90bce00c42f336", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-12-12T16:53:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T22:20:17.000Z", "max_issues_repo_path": "src/interface.jl", "max_issues_repo_name": "droodman/WildBootTests.jl", "max_issues_repo_head_hexsha": "91a68dfbfbe4cfe6f495acd14b90bce00c42f336", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-11-30T23:53:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T04:20:00.000Z", "max_forks_repo_path": "src/interface.jl", "max_forks_repo_name": "droodman/WildBootTests.jl", "max_forks_repo_head_hexsha": "91a68dfbfbe4cfe6f495acd14b90bce00c42f336", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.305764411, "max_line_length": 204, "alphanum_fraction": 0.6874646453, "num_tokens": 5407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.23872157975280645}} {"text": "using AtomsBase\n# Key functionality to integrate DFTK and AtomsBase\n\nfunction construct_system(lattice::AbstractMatrix, atoms::Vector, positions::Vector, magnetic_moments::Vector)\n @assert length(atoms) == length(positions)\n @assert isempty(magnetic_moments) || length(magnetic_moments) == length(atoms)\n atomsbase_atoms = map(enumerate(atoms)) do (i, element)\n kwargs = Dict{Symbol, Any}(:potential => element, )\n if !isempty(magnetic_moments)\n kwargs[:magnetic_moment] = normalize_magnetic_moment(magnetic_moments[i])\n end\n if element isa ElementPsp\n kwargs[:pseudopotential] = element.psp.identifier\n end\n\n position = lattice * positions[i] * u\"bohr\"\n if atomic_symbol(element) == :X # dummy element ... should solve this upstream\n Atom(:X, position; atomic_symbol=:X, atomic_number=0, atomic_mass=0u\"u\", kwargs...)\n else\n Atom(atomic_symbol(element), position; kwargs...)\n end\n end\n periodic_system(atomsbase_atoms, collect(eachcol(lattice)) * u\"bohr\")\nend\n\nfunction parse_system(system::AbstractSystem{D}) where {D}\n if !all(periodicity(system))\n error(\"DFTK only supports calculations with periodic boundary conditions.\")\n end\n\n # Parse abstract system and return data required to construct model\n mtx = austrip.(reduce(hcat, bounding_box(system)))\n T = eltype(mtx)\n lattice = zeros(T, 3, 3)\n lattice[1:D, 1:D] .= mtx\n\n # Cache for instantiated pseudopotentials. This is done to ensure that identical\n # atoms are indistinguishable in memory, which is used in the Model constructor\n # to deduce the atom_groups.\n cached_pspelements = Dict{String, ElementPsp}()\n atoms = map(system) do atom\n if hasproperty(atom, :potential)\n atom.potential\n elseif hasproperty(atom, :pseudopotential)\n get!(cached_pspelements, atom.pseudopotential) do\n ElementPsp(atomic_symbol(atom); psp=load_psp(atom.pseudopotential))\n end\n else\n ElementCoulomb(atomic_symbol(atom))\n end\n end\n\n positions = map(system) do atom\n coordinate = zeros(T, 3)\n coordinate[1:D] = lattice[1:D, 1:D] \\ T.(austrip.(position(atom)))\n Vec3{T}(coordinate)\n end\n\n magnetic_moments = map(system) do atom\n hasproperty(atom, :magnetic_moment) || return nothing\n getproperty(atom, :magnetic_moment)\n end\n if all(m -> isnothing(m) || iszero(m) || isempty(m), magnetic_moments)\n empty!(magnetic_moments)\n else\n magnetic_moments = normalize_magnetic_moment.(magnetic_moments)\n end\n\n # TODO Use system to determine n_electrons\n\n (; lattice, atoms, positions, magnetic_moments)\nend\n\n\nfunction _call_with_system(f, system::AbstractSystem, args...; kwargs...)\n @assert !(:magnetic_moments in keys(kwargs))\n parsed = parse_system(system)\n f(parsed.lattice, parsed.atoms, parsed.positions, args...;\n parsed.magnetic_moments, kwargs...)\nend\n\n\n\"\"\"\n Model(system::AbstractSystem; kwargs...)\n\nAtomsBase-compatible Model constructor. Sets structural information (`atoms`, `positions`,\n`lattice`, `n_electrons` etc.) from the passed `system`.\n\"\"\"\nModel(system::AbstractSystem; kwargs...) = _call_with_system(Model, system; kwargs...)\n\n\n# Generate equivalent functions for AtomsBase\nfor fun in (:model_atomic, :model_DFT, :model_LDA, :model_PBE, :model_SCAN)\n @eval function $fun(system::AbstractSystem, args...; kwargs...)\n _call_with_system($fun, system, args...; kwargs...)\n end\nend\n\n\n# Extra methods to AtomsBase functions for DFTK data structures\n\"\"\"\n atomic_system(model::DFTK.Model, magnetic_moments=[])\n\nConstruct an AtomsBase atomic system from a DFTK model and associated magnetic moments.\n\"\"\"\nfunction AtomsBase.atomic_system(model::Model, magnetic_moments=[])\n construct_system(model.lattice, model.atoms, model.positions, magnetic_moments)\nend\n\n\"\"\"\n periodic_system(model::DFTK.Model, magnetic_moments=[])\n\nConstruct an AtomsBase atomic system from a DFTK model and associated magnetic moments.\n\"\"\"\nfunction AtomsBase.periodic_system(model::Model, magnetic_moments=[])\n atomic_system(model, magnetic_moments)\nend\n\nAtomsBase.chemical_formula(model::Model) = chemical_formula(atomic_symbol.(model.atoms))\n", "meta": {"hexsha": "35c2b1e9a9e0dfc62ac7b385fa7801752c365edd", "size": 4330, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/external/atomsbase.jl", "max_stars_repo_name": "epolack/DFTK.jl", "max_stars_repo_head_hexsha": "7256a356c9870aee350fbf181f10de8f4d83f592", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-05-16T13:05:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-05T13:56:46.000Z", "max_issues_repo_path": "src/external/atomsbase.jl", "max_issues_repo_name": "epolack/DFTK.jl", "max_issues_repo_head_hexsha": "7256a356c9870aee350fbf181f10de8f4d83f592", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2019-06-14T08:08:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-09T13:46:54.000Z", "max_forks_repo_path": "src/external/atomsbase.jl", "max_forks_repo_name": "epolack/DFTK.jl", "max_forks_repo_head_hexsha": "7256a356c9870aee350fbf181f10de8f4d83f592", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-19T07:38:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T09:48:05.000Z", "avg_line_length": 36.0833333333, "max_line_length": 110, "alphanum_fraction": 0.6963048499, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.23846090906360976}} {"text": "__precompile__(true)\n\nmodule ColorVectorSpace\n\nusing ColorTypes, FixedPointNumbers, Compat\n\nimport Base: ==, +, -, *, /, .+, .-, .*, ./, ^, .^, <, ~\nimport Base: abs, abs2, clamp, convert, copy, div, eps, isfinite, isinf,\n isnan, isless, length, mapreduce, norm, one, promote_array_type,\n promote_op, promote_rule, zero, trunc, floor, round, ceil, bswap,\n mod, rem, atan2, hypot, max, min, varm, real, histrange\n\nif VERSION < v\"0.5.0-dev\"\n import Base.nan\nelse\n export nan\nend\n\n# The unaryOps\nimport Base: conj, sin, cos, tan, sinh, cosh, tanh,\n asin, acos, atan, asinh, acosh, atanh,\n sec, csc, cot, asec, acsc, acot,\n sech, csch, coth, asech, acsch, acoth,\n sinc, cosc, cosd, cotd, cscd, secd,\n sind, tand, acosd, acotd, acscd, asecd,\n asind, atand, rad2deg, deg2rad,\n log, log2, log10, log1p, exponent, exp,\n exp2, expm1, cbrt, sqrt, erf,\n erfc, erfcx, erfi, dawson,\n significand, lgamma,\n gamma, lfact, frexp, modf, airy, airyai,\n airyprime, airyaiprime, airybi, airybiprime,\n besselj0, besselj1, bessely0, bessely1,\n eta, zeta, digamma\n\ntypealias AbstractGray{T} Color{T,1}\ntypealias TransparentRGB{C<:AbstractRGB,T} TransparentColor{C,T,4}\ntypealias TransparentGray{C<:AbstractGray,T} TransparentColor{C,T,2}\ntypealias TransparentRGBFloat{C<:AbstractRGB,T<:AbstractFloat} TransparentColor{C,T,4}\ntypealias TransparentGrayFloat{C<:AbstractGray,T<:AbstractFloat} TransparentColor{C,T,2}\ntypealias TransparentRGBUFixed{C<:AbstractRGB,T<:UFixed} TransparentColor{C,T,4}\ntypealias TransparentGrayUFixed{C<:AbstractGray,T<:UFixed} TransparentColor{C,T,2}\n\ntypealias MathTypes{T,C} Union{AbstractRGB{T},TransparentRGB{C,T},AbstractGray{T},TransparentGray{C,T}}\n\n# convert(RGB{Float32}, NaN) doesn't and shouldn't work, so we need to reintroduce nan\nif VERSION >= v\"0.5.0-dev\"\n nan{T<:AbstractFloat}(::Type{T}) = convert(T, NaN)\nend\nnan{C<:MathTypes}(::Type{C}) = _nan(eltype(C), C)\n_nan{T<:AbstractFloat,C<:AbstractGray}(::Type{T}, ::Type{C}) = (x = convert(T, NaN); C(x))\n_nan{T<:AbstractFloat,C<:TransparentGray}(::Type{T}, ::Type{C}) = (x = convert(T, NaN); C(x,x))\n_nan{T<:AbstractFloat,C<:AbstractRGB}(::Type{T}, ::Type{C}) = (x = convert(T, NaN); C(x,x,x))\n_nan{T<:AbstractFloat,C<:TransparentRGB}(::Type{T}, ::Type{C}) = (x = convert(T, NaN); C(x,x,x,x))\n\n## Generic algorithms\nmapreduce(f, op::Base.ShortCircuiting, a::MathTypes) = f(a) # ambiguity\nmapreduce(f, op, a::MathTypes) = f(a)\n\nfor f in (:trunc, :floor, :round, :ceil, :eps, :bswap)\n @eval $f{T}(g::Gray{T}) = Gray{T}($f(gray(g)))\n @eval Compat.@dep_vectorize_1arg Gray $f\nend\neps{T}(::Type{Gray{T}}) = Gray(eps(T))\nCompat.@dep_vectorize_1arg AbstractGray isfinite\nCompat.@dep_vectorize_1arg AbstractGray isinf\nCompat.@dep_vectorize_1arg AbstractGray isnan\nCompat.@dep_vectorize_1arg AbstractGray abs\nCompat.@dep_vectorize_1arg AbstractGray abs2\nfor f in (:trunc, :floor, :round, :ceil)\n @eval $f{T<:Integer}(::Type{T}, g::Gray) = Gray{T}($f(T, gray(g)))\nend\n\nfor f in (:mod, :rem, :mod1)\n @eval $f(x::Gray, m::Gray) = Gray($f(gray(x), gray(m)))\nend\n\n# Real values are treated like grays\nColorTypes.gray(x::Real) = x\n\n# Return types for arithmetic operations\nmultype{A,B}(::Type{A}, ::Type{B}) = coltype(typeof(zero(A)*zero(B)))\nsumtype{A,B}(::Type{A}, ::Type{B}) = coltype(typeof(zero(A)+zero(B)))\ndivtype{A,B}(::Type{A}, ::Type{B}) = coltype(typeof(zero(A)/zero(B)))\npowtype{A,B}(::Type{A}, ::Type{B}) = coltype(typeof(zero(A)^zero(B)))\nmultype(a::Colorant, b::Colorant) = multype(eltype(a),eltype(b))\nsumtype(a::Colorant, b::Colorant) = sumtype(eltype(a),eltype(b))\ndivtype(a::Colorant, b::Colorant) = divtype(eltype(a),eltype(b))\npowtype(a::Colorant, b::Colorant) = powtype(eltype(a),eltype(b))\n\ncoltype{T<:Fractional}(::Type{T}) = T\ncoltype{T}(::Type{T}) = Float64\n\n# Scalar binary RGB operations require the same RGB type for each element,\n# otherwise we don't know which to return\ncolor_rettype{A<:AbstractRGB,B<:AbstractRGB}(::Type{A}, ::Type{B}) = _color_rettype(base_colorant_type(A), base_colorant_type(B))\ncolor_rettype{A<:AbstractGray,B<:AbstractGray}(::Type{A}, ::Type{B}) = _color_rettype(base_colorant_type(A), base_colorant_type(B))\ncolor_rettype{A<:TransparentRGB,B<:TransparentRGB}(::Type{A}, ::Type{B}) = _color_rettype(base_colorant_type(A), base_colorant_type(B))\ncolor_rettype{A<:TransparentGray,B<:TransparentGray}(::Type{A}, ::Type{B}) = _color_rettype(base_colorant_type(A), base_colorant_type(B))\n_color_rettype{A<:Colorant,B<:Colorant}(::Type{A}, ::Type{B}) = error(\"binary operation with $A and $B, return type is ambiguous\")\n_color_rettype{C<:Colorant}(::Type{C}, ::Type{C}) = C\n\ncolor_rettype(c1::Colorant, c2::Colorant) = color_rettype(typeof(c1), typeof(c2))\n\n## Math on Colors. These implementations encourage inlining and,\n## for the case of UFixed types, nearly halve the number of multiplications (for RGB)\n\n# Scalar RGB\ncopy(c::AbstractRGB) = c\n(*)(f::Real, c::AbstractRGB) = base_colorant_type(c){multype(typeof(f),eltype(c))}(f*red(c), f*green(c), f*blue(c))\n(*)(f::Real, c::TransparentRGB) = base_colorant_type(c){multype(typeof(f),eltype(c))}(f*red(c), f*green(c), f*blue(c), f*alpha(c))\nfunction (*){T<:UFixed}(f::Real, c::AbstractRGB{T})\n fs = f*(1/reinterpret(one(T)))\n base_colorant_type(c){multype(typeof(f),T)}(fs*reinterpret(red(c)), fs*reinterpret(green(c)), fs*reinterpret(blue(c)))\nend\nfunction (*){T<:UFixed}(f::UFixed, c::AbstractRGB{T})\n fs = reinterpret(f)*(1/widen(reinterpret(one(T)))^2)\n base_colorant_type(c){multype(typeof(f),T)}(fs*reinterpret(red(c)), fs*reinterpret(green(c)), fs*reinterpret(blue(c)))\nend\nfunction (/){T<:UFixed}(c::AbstractRGB{T}, f::Real)\n fs = (one(f)/reinterpret(one(T)))/f\n base_colorant_type(c){divtype(typeof(f),T)}(fs*reinterpret(red(c)), fs*reinterpret(green(c)), fs*reinterpret(blue(c)))\nend\nfunction (/){T<:UFixed}(c::AbstractRGB{T}, f::Integer)\n fs = (1/reinterpret(one(T)))/f\n base_colorant_type(c){divtype(typeof(f),T)}(fs*reinterpret(red(c)), fs*reinterpret(green(c)), fs*reinterpret(blue(c)))\nend\n(+){S,T}(a::AbstractRGB{S}, b::AbstractRGB{T}) = color_rettype(a, b){sumtype(S,T)}(red(a)+red(b), green(a)+green(b), blue(a)+blue(b))\n(-){S,T}(a::AbstractRGB{S}, b::AbstractRGB{T}) = color_rettype(a, b){sumtype(S,T)}(red(a)-red(b), green(a)-green(b), blue(a)-blue(b))\n(+)(a::TransparentRGB, b::TransparentRGB) =\n color_rettype(a, b){sumtype(a,b)}(red(a)+red(b), green(a)+green(b), blue(a)+blue(b), alpha(a)+alpha(b))\n(-)(a::TransparentRGB, b::TransparentRGB) =\n color_rettype(a, b){sumtype(a,b)}(red(a)-red(b), green(a)-green(b), blue(a)-blue(b), alpha(a)-alpha(b))\n(*)(c::AbstractRGB, f::Real) = (*)(f, c)\n(*)(c::TransparentRGB, f::Real) = (*)(f, c)\n(.*)(f::Real, c::AbstractRGB) = (*)(f, c)\n(.*)(f::Real, c::TransparentRGB) = (*)(f, c)\n(.*)(c::AbstractRGB, f::Real) = (*)(f, c)\n(.*)(c::TransparentRGB, f::Real) = (*)(f, c)\n(/)(c::AbstractRGB, f::Real) = (one(f)/f)*c\n(/)(c::TransparentRGB, f::Real) = (one(f)/f)*c\n(/)(c::AbstractRGB, f::Integer) = (one(eltype(c))/f)*c\n(/)(c::TransparentRGB, f::Integer) = (one(eltype(c))/f)*c\n(./)(c::AbstractRGB, f::Real) = (/)(c, f)\n(./)(c::TransparentRGB, f::Real) = (/)(c, f)\n\nisfinite{T<:UFixed}(c::Colorant{T}) = true\nisfinite{T<:AbstractFloat}(c::AbstractRGB{T}) = isfinite(red(c)) && isfinite(green(c)) && isfinite(blue(c))\nisfinite(c::TransparentRGBFloat) = isfinite(red(c)) && isfinite(green(c)) && isfinite(blue(c)) && isfinite(alpha(c))\nisnan{T<:UFixed}(c::Colorant{T}) = false\nisnan{T<:AbstractFloat}(c::AbstractRGB{T}) = isnan(red(c)) || isnan(green(c)) || isnan(blue(c))\nisnan(c::TransparentRGBFloat) = isnan(red(c)) || isnan(green(c)) || isnan(blue(c)) || isnan(alpha(c))\nisinf{T<:UFixed}(c::Colorant{T}) = false\nisinf{T<:AbstractFloat}(c::AbstractRGB{T}) = isinf(red(c)) || isinf(green(c)) || isinf(blue(c))\nisinf(c::TransparentRGBFloat) = isinf(red(c)) || isinf(green(c)) || isinf(blue(c)) || isinf(alpha(c))\nabs(c::AbstractRGB) = abs(red(c))+abs(green(c))+abs(blue(c)) # should this have a different name?\nabs{T<:UFixed}(c::AbstractRGB{T}) = Float32(red(c))+Float32(green(c))+Float32(blue(c)) # should this have a different name?\nabs(c::TransparentRGB) = abs(red(c))+abs(green(c))+abs(blue(c))+abs(alpha(c)) # should this have a different name?\nabs{T<:UFixed}(c::TransparentRGB{T}) = Float32(red(c))+Float32(green(c))+Float32(blue(c))+Float32(alpha(c)) # should this have a different name?\nabs2(c::AbstractRGB) = red(c)^2+green(c)^2+blue(c)^2\nabs2{T<:UFixed}(c::AbstractRGB{T}) = Float32(red(c))^2+Float32(green(c))^2+Float32(blue(c))^2\nabs2(c::TransparentRGB) = (ret = abs2(color(c)); ret + convert(typeof(ret), alpha(c))^2)\nnorm(c::AbstractRGB) = sqrt(abs2(c))\nnorm(c::TransparentRGB) = sqrt(abs2(c))\n\none{C<:AbstractRGB}(::Type{C}) = C(1,1,1)\none{C<:TransparentRGB}(::Type{C}) = C(1,1,1,1)\nzero{C<:AbstractRGB}(::Type{C}) = C(0,0,0)\nzero{C<:TransparentRGB}(::Type{C}) = C(0,0,0,0)\nzero{C<:YCbCr}(::Type{C}) = C(0,0,0)\nzero{C<:HSV}(::Type{C}) = C(0,0,0)\none(p::Colorant) = one(typeof(p))\nzero(p::Colorant) = zero(typeof(p))\n\n# Arrays\n(+){CV<:AbstractRGB}(A::AbstractArray{CV}, b::AbstractRGB) = (.+)(A, b)\n(+){CV<:AbstractRGB}(b::AbstractRGB, A::AbstractArray{CV}) = (.+)(b, A)\n(-){CV<:AbstractRGB}(A::AbstractArray{CV}, b::AbstractRGB) = (.-)(A, b)\n(-){CV<:AbstractRGB}(b::AbstractRGB, A::AbstractArray{CV}) = (.-)(b, A)\n(*){T<:Number}(A::AbstractArray{T}, b::AbstractRGB) = A.*b\n(*){T<:Number}(b::AbstractRGB, A::AbstractArray{T}) = A.*b\n(.+){C<:AbstractRGB}(A::AbstractArray{C}, b::AbstractRGB) = plus(A, b)\n(.+){C<:AbstractRGB}(b::AbstractRGB, A::AbstractArray{C}) = plus(b, A)\n(.-){C<:AbstractRGB}(A::AbstractArray{C}, b::AbstractRGB) = minus(A, b)\n(.-){C<:AbstractRGB}(b::AbstractRGB, A::AbstractArray{C}) = minus(b, A)\n(.*){T<:Number}(A::AbstractArray{T}, b::AbstractRGB) = mul(A, b)\n(.*){T<:Number}(b::AbstractRGB, A::AbstractArray{T}) = mul(b, A)\n\n(+){CV<:TransparentRGB}(A::AbstractArray{CV}, b::TransparentRGB) = (.+)(A, b)\n(+){CV<:TransparentRGB}(b::TransparentRGB, A::AbstractArray{CV}) = (.+)(b, A)\n(-){CV<:TransparentRGB}(A::AbstractArray{CV}, b::TransparentRGB) = (.-)(A, b)\n(-){CV<:TransparentRGB}(b::TransparentRGB, A::AbstractArray{CV}) = (.-)(b, A)\n(*){T<:Number}(A::AbstractArray{T}, b::TransparentRGB) = A.*b\n(*){T<:Number}(b::TransparentRGB, A::AbstractArray{T}) = A.*b\n(.+){C<:TransparentRGB}(A::AbstractArray{C}, b::TransparentRGB) = plus(A, b)\n(.+){C<:TransparentRGB}(b::TransparentRGB, A::AbstractArray{C}) = plus(b, A)\n(.-){C<:TransparentRGB}(A::AbstractArray{C}, b::TransparentRGB) = minus(A, b)\n(.-){C<:TransparentRGB}(b::TransparentRGB, A::AbstractArray{C}) = minus(b, A)\n(.*){T<:Number}(A::AbstractArray{T}, b::TransparentRGB) = mul(A, b)\n(.*){T<:Number}(b::TransparentRGB, A::AbstractArray{T}) = mul(b, A)\n\n# Scalar Gray\ncopy(c::AbstractGray) = c\nconst unaryOps = (:~, :conj, :abs,\n :sin, :cos, :tan, :sinh, :cosh, :tanh,\n :asin, :acos, :atan, :asinh, :acosh, :atanh,\n :sec, :csc, :cot, :asec, :acsc, :acot,\n :sech, :csch, :coth, :asech, :acsch, :acoth,\n :sinc, :cosc, :cosd, :cotd, :cscd, :secd,\n :sind, :tand, :acosd, :acotd, :acscd, :asecd,\n :asind, :atand, :rad2deg, :deg2rad,\n :log, :log2, :log10, :log1p, :exponent, :exp,\n :exp2, :expm1, :cbrt, :sqrt, :erf,\n :erfc, :erfcx, :erfi, :dawson,\n :significand, :lgamma,\n :gamma, :lfact, :frexp, :modf, :airy, :airyai,\n :airyprime, :airyaiprime, :airybi, :airybiprime,\n :besselj0, :besselj1, :bessely0, :bessely1,\n :eta, :zeta, :digamma)\nfor op in unaryOps\n @eval ($op)(c::AbstractGray) = $op(gray(c))\nend\n\n(*)(f::Real, c::AbstractGray) = base_colorant_type(c){multype(typeof(f),eltype(c))}(f*gray(c))\n(*)(f::Real, c::TransparentGray) = base_colorant_type(c){multype(typeof(f),eltype(c))}(f*gray(c), f*alpha(c))\n(*)(c::AbstractGray, f::Real) = (*)(f, c)\n(.*)(f::Real, c::AbstractGray) = (*)(f, c)\n(.*)(c::AbstractGray, f::Real) = (*)(f, c)\n(*)(c::TransparentGray, f::Real) = (*)(f, c)\n(.*)(f::Real, c::TransparentGray) = (*)(f, c)\n(.*)(c::TransparentGray, f::Real) = (*)(f, c)\n(/)(c::AbstractGray, f::Real) = (one(f)/f)*c\n(/)(n::Number, c::AbstractGray) = n/gray(c)\n(/)(c::TransparentGray, f::Real) = (one(f)/f)*c\n(/)(c::AbstractGray, f::Integer) = (one(eltype(c))/f)*c\n(/)(c::TransparentGray, f::Integer) = (one(eltype(c))/f)*c\n(./)(c::AbstractGray, f::Real) = c/f\n(./)(n::Number, c::AbstractGray) = n/gray(c)\n(./)(c::TransparentGray, f::Real) = c/f\n(+){S,T}(a::AbstractGray{S}, b::AbstractGray{T}) = color_rettype(a,b){sumtype(S,T)}(gray(a)+gray(b))\n(+)(a::TransparentGray, b::TransparentGray) = color_rettype(a,b){sumtype(eltype(a),eltype(b))}(gray(a)+gray(b),alpha(a)+alpha(b))\n(-){S,T}(a::AbstractGray{S}, b::AbstractGray{T}) = color_rettype(a,b){sumtype(S,T)}(gray(a)-gray(b))\n(-)(a::TransparentGray, b::TransparentGray) = color_rettype(a,b){sumtype(eltype(a),eltype(b))}(gray(a)-gray(b),alpha(a)-alpha(b))\n(*){S,T}(a::AbstractGray{S}, b::AbstractGray{T}) = color_rettype(a,b){multype(S,T)}(gray(a)*gray(b))\n(^){S}(a::AbstractGray{S}, b::Integer) = base_colorant_type(a){powtype(S,Int)}(gray(a)^convert(Int,b))\n(^){S}(a::AbstractGray{S}, b::Real) = base_colorant_type(a){powtype(S,typeof(b))}(gray(a)^b)\n(.^){S}(a::AbstractGray{S}, b) = a^b\n(+)(c::AbstractGray) = c\n(+)(c::TransparentGray) = c\n(-)(c::AbstractGray) = typeof(c)(-gray(c))\n(-)(c::TransparentGray) = typeof(c)(-gray(c),-alpha(c))\n(/)(a::AbstractGray, b::AbstractGray) = gray(a)/gray(b)\ndiv(a::AbstractGray, b::AbstractGray) = div(gray(a), gray(b))\n(+)(a::AbstractGray, b::Number) = gray(a)+b\n(-)(a::AbstractGray, b::Number) = gray(a)-b\n(+)(a::Number, b::AbstractGray) = a+gray(b)\n(-)(a::Number, b::AbstractGray) = a-gray(b)\n(.+)(a::AbstractGray, b::Number) = gray(a)+b\n(.-)(a::AbstractGray, b::Number) = gray(a)-b\n(.+)(a::Number, b::AbstractGray) = a+gray(b)\n(.-)(a::Number, b::AbstractGray) = a-gray(b)\nmax{T<:AbstractGray}(a::T, b::T) = T(max(gray(a),gray(b)))\nmax(a::AbstractGray, b::AbstractGray) = max(promote(a,b)...)\nmax(a::Number, b::AbstractGray) = max(promote(a,b)...)\nmax(a::AbstractGray, b::Number) = max(promote(a,b)...)\nmin{T<:AbstractGray}(a::T, b::T) = T(min(gray(a),gray(b)))\nmin(a::AbstractGray, b::AbstractGray) = min(promote(a,b)...)\nmin(a::Number, b::AbstractGray) = min(promote(a,b)...)\nmin(a::AbstractGray, b::Number) = min(promote(a,b)...)\n\nisfinite{T<:AbstractFloat}(c::AbstractGray{T}) = isfinite(gray(c))\nisfinite(c::TransparentGrayFloat) = isfinite(gray(c)) && isfinite(alpha(c))\nisnan{T<:AbstractFloat}(c::AbstractGray{T}) = isnan(gray(c))\nisnan(c::TransparentGrayFloat) = isnan(gray(c)) && isnan(alpha(c))\nisinf{T<:AbstractFloat}(c::AbstractGray{T}) = isinf(gray(c))\nisinf(c::TransparentGrayFloat) = isinf(gray(c)) && isnan(alpha(c))\nnorm(c::AbstractGray) = abs(gray(c))\nabs(c::TransparentGray) = abs(gray(c))+abs(alpha(c)) # should this have a different name?\nabs(c::TransparentGrayUFixed) = Float32(gray(c)) + Float32(alpha(c)) # should this have a different name?\nabs2(c::AbstractGray) = gray(c)^2\nabs2{T<:UFixed}(c::AbstractGray{T}) = Float32(gray(c))^2\nabs2(c::TransparentGray) = gray(c)^2+alpha(c)^2\nabs2(c::TransparentGrayUFixed) = Float32(gray(c))^2 + Float32(alpha(c))^2\natan2(x::Gray, y::Gray) = atan2(convert(Real, x), convert(Real, y))\nhypot(x::Gray, y::Gray) = hypot(convert(Real, x), convert(Real, y))\nnorm(c::TransparentGray) = sqrt(abs2(c))\n\n(<)(g1::AbstractGray, g2::AbstractGray) = gray(g1) < gray(g2)\n(<)(c::AbstractGray, r::Real) = gray(c) < r\n(<)(r::Real, c::AbstractGray) = r < gray(c)\nisless(g1::AbstractGray, g2::AbstractGray) = isless(gray(g1), gray(g2))\nisless(c::AbstractGray, r::Real) = isless(gray(c), r)\nisless(r::Real, c::AbstractGray) = isless(r, gray(c))\nBase.isapprox(x::AbstractGray, y::AbstractGray; kwargs...) = isapprox(gray(x), gray(y); kwargs...)\nBase.isapprox(x::TransparentGray, y::TransparentGray; kwargs...) = isapprox(gray(x), gray(y); kwargs...) && isapprox(alpha(x), alpha(y); kwargs...)\nBase.isapprox(x::AbstractRGB, y::AbstractRGB; kwargs...) = isapprox(red(x), red(y); kwargs...) && isapprox(green(x), green(y); kwargs...) && isapprox(blue(x), blue(y); kwargs...)\nBase.isapprox(x::TransparentRGB, y::TransparentRGB; kwargs...) = isapprox(alpha(x), alpha(y); kwargs...) && isapprox(red(x), red(y); kwargs...) && isapprox(green(x), green(y); kwargs...) && isapprox(blue(x), blue(y); kwargs...)\n\nfunction Base.isapprox{Cx<:MathTypes,Cy<:MathTypes}(x::AbstractArray{Cx},\n y::AbstractArray{Cy};\n rtol::Real=Base.rtoldefault(eltype(Cx),eltype(Cy)),\n atol::Real=0,\n norm::Function=vecnorm)\n d = norm(x - y)\n if isfinite(d)\n return d <= atol + rtol*max(norm(x), norm(y))\n else\n # Fall back to a component-wise approximate comparison\n return all(ab -> isapprox(ab[1], ab[2]; rtol=rtol, atol=atol), zip(x, y))\n end\nend\n\nzero{C<:TransparentGray}(::Type{C}) = C(0,0)\nzero{C<:Gray}(::Type{C}) = C(0)\none{C<:TransparentGray}(::Type{C}) = C(1,1)\none{C<:Gray}(::Type{C}) = C(1)\n\n # Arrays\n(+){CV<:AbstractGray}(A::AbstractArray{CV}, b::AbstractGray) = (.+)(A, b)\n(+){CV<:AbstractGray}(b::AbstractGray, A::AbstractArray{CV}) = (.+)(b, A)\n(-){CV<:AbstractGray}(A::AbstractArray{CV}, b::AbstractGray) = (.-)(A, b)\n(-){CV<:AbstractGray}(b::AbstractGray, A::AbstractArray{CV}) = (.-)(b, A)\n(*){T<:Number}(A::AbstractArray{T}, b::AbstractGray) = A.*b\n(*){T<:Number}(b::AbstractGray, A::AbstractArray{T}) = A.*b\n(/){C<:AbstractGray}(A::AbstractArray{C}, b::AbstractGray) = A./b\n(.+){C<:AbstractGray}(A::AbstractArray{C}, b::AbstractGray) = plus(A, b)\n(.+){C<:AbstractGray}(b::AbstractGray, A::AbstractArray{C}) = plus(b, A)\n(.-){C<:AbstractGray}(A::AbstractArray{C}, b::AbstractGray) = minus(A, b)\n(.-){C<:AbstractGray}(b::AbstractGray, A::AbstractArray{C}) = minus(b, A)\n(.*){T<:Number}(A::AbstractArray{T}, b::AbstractGray) = mul(A, b)\n(.*){T<:Number}(b::AbstractGray, A::AbstractArray{T}) = mul(b, A)\n(./){C<:AbstractGray}(A::AbstractArray{C}, b::AbstractGray) = divd(A, b)\n\nCompat.@dep_vectorize_2arg Gray max\nCompat.@dep_vectorize_2arg Gray min\nfor f in (:min, :max)\n @eval begin\n @deprecate($f{T<:Gray}(x::Number, y::AbstractArray{T}),\n @compat $f.(x, y))\n @deprecate($f{T<:Gray}(x::AbstractArray{T}, y::Number),\n @compat $f.(x, y))\n end\nend\n\n(+){CV<:TransparentGray}(A::AbstractArray{CV}, b::TransparentGray) = (.+)(A, b)\n(+){CV<:TransparentGray}(b::TransparentGray, A::AbstractArray{CV}) = (.+)(b, A)\n(-){CV<:TransparentGray}(A::AbstractArray{CV}, b::TransparentGray) = (.-)(A, b)\n(-){CV<:TransparentGray}(b::TransparentGray, A::AbstractArray{CV}) = (.-)(b, A)\n(*){T<:Number}(A::AbstractArray{T}, b::TransparentGray) = A.*b\n(*){T<:Number}(b::TransparentGray, A::AbstractArray{T}) = A.*b\n(.+){C<:TransparentGray}(A::AbstractArray{C}, b::TransparentGray) = plus(A, b)\n(.+){C<:TransparentGray}(b::TransparentGray, A::AbstractArray{C}) = plus(b, A)\n(.-){C<:TransparentGray}(A::AbstractArray{C}, b::TransparentGray) = minus(A, b)\n(.-){C<:TransparentGray}(b::TransparentGray, A::AbstractArray{C}) = minus(b, A)\n(.*){T<:Number}(A::AbstractArray{T}, b::TransparentGray) = mul(A, b)\n(.*){T<:Number}(b::TransparentGray, A::AbstractArray{T}) = mul(b, A)\n\nvarm{C<:AbstractGray}(v::AbstractArray{C}, s::AbstractGray; corrected::Bool=true) =\n varm(map(gray,v),gray(s); corrected=corrected)\nreal{C<:AbstractGray}(::Type{C}) = real(eltype(C))\n\n# Called plus/minus instead of plus/sub because `sub` already has a meaning!\nfunction plus(A::AbstractArray, b::Colorant)\n bT = convert(eltype(A), b)\n out = similar(A)\n plus!(out, A, bT)\nend\nplus(b::Colorant, A::AbstractArray) = plus(A, b)\nfunction minus(A::AbstractArray, b::Colorant)\n bT = convert(eltype(A), b)\n out = similar(A)\n minus!(out, A, bT)\nend\nfunction minus(b::Colorant, A::AbstractArray)\n bT = convert(eltype(A), b)\n out = similar(A)\n minus!(out, bT, A)\nend\nfunction mul{T<:Number}(A::AbstractArray{T}, b::Colorant)\n bT = typeof(b*one(T))\n out = similar(A, bT)\n mul!(out, A, b)\nend\nmul{T<:Number}(b::Colorant, A::AbstractArray{T}) = mul(A, b)\nfunction divd{C<:AbstractGray}(A::AbstractArray{C}, b::AbstractGray)\n bT = typeof(zero(C)/b)\n out = similar(A, bT)\n div!(out, A, b)\nend\n\nfor (func, op) in ((:plus!, :+),\n (:minus!, :-),\n (:mul!, :*),\n (:div!, :/))\n @eval begin\n function $func{T,N}(out, A::AbstractArray{T,N}, b)\n Rout, RA = eachindex(out), eachindex(A)\n if Rout == RA\n for I in RA\n @inbounds out[I] = $op(A[I], b)\n end\n else\n for (Iout, IA) in zip(Rout, RA)\n @inbounds out[Iout] = $op(A[IA], b)\n end\n end\n out\n end\n end\nend\n\n# This needs separate implementation because we can take -b of unsigned types\nfunction minus!{T,N}(out, b::Colorant, A::AbstractArray{T,N})\n Rout, RA = eachindex(out), eachindex(A)\n if Rout == RA\n for I in RA\n @inbounds out[I] = b - A[I]\n end\n else\n for (Iout, IA) in zip(Rout, RA)\n @inbounds out[Iout] = b - A[IA]\n end\n end\n out\nend\n\n#histrange for Gray type\nBase.histrange{T}(v::AbstractArray{Gray{T}}, n::Integer) = histrange(convert(Array{Float32}, map(gray, v)), n)\n\n# Promotions for reductions\nif VERSION < v\"0.5.0-dev+3701\"\n Base.r_promote{T<:FixedPoint}(::Base.AddFun, c::MathTypes{T}) = convert(base_colorant_type(typeof(c)){Float64}, c)\n Base.r_promote{T<:FixedPoint}(::Base.MulFun, c::MathTypes{T}) = convert(base_colorant_type(typeof(c)){Float64}, c)\nelse\n Base.r_promote{T<:FixedPoint}(::typeof(+), c::MathTypes{T}) = convert(base_colorant_type(typeof(c)){Float64}, c)\n Base.r_promote{T<:FixedPoint}(::typeof(*), c::MathTypes{T}) = convert(base_colorant_type(typeof(c)){Float64}, c)\nend\n\n# To help type inference\npromote_array_type{T<:Real,C<:MathTypes}(F, ::Type{T}, ::Type{C}) = base_colorant_type(C){Base.promote_array_type(F, T, eltype(C))}\npromote_op{C<:MathTypes,T<:Real}(F, ::Type{C}, ::Type{T}) = typeof(F(zero(C), zero(T)))\npromote_op{C<:MathTypes,T<:Real}(F, ::Type{T}, ::Type{C}) = typeof(F(zero(T), zero(C)))\npromote_rule{C1<:Colorant,C2<:Colorant}(::Type{C1}, ::Type{C2}) = color_rettype(C1,C2){promote_type(eltype(C1), eltype(C2))}\npromote_rule{T<:Real,C<:AbstractGray}(::Type{T}, ::Type{C}) = promote_type(T, eltype(C))\n\n@deprecate sumsq abs2\n\nend\n", "meta": {"hexsha": "6b47b5d4b067a1190a29ce4577c3324bc6c5d91d", "size": 23020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ColorVectorSpace.jl", "max_stars_repo_name": "JuliaPackageMirrors/ColorVectorSpace.jl", "max_stars_repo_head_hexsha": "3cf570992317ba47782d9274e34a2eb4a89ada2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ColorVectorSpace.jl", "max_issues_repo_name": "JuliaPackageMirrors/ColorVectorSpace.jl", "max_issues_repo_head_hexsha": "3cf570992317ba47782d9274e34a2eb4a89ada2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ColorVectorSpace.jl", "max_forks_repo_name": "JuliaPackageMirrors/ColorVectorSpace.jl", "max_forks_repo_head_hexsha": "3cf570992317ba47782d9274e34a2eb4a89ada2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.2694877506, "max_line_length": 227, "alphanum_fraction": 0.6223718506, "num_tokens": 7813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23833124840630765}} {"text": "############################################################################################\n\"\"\"\n$(SIGNATURES)\nReturn kernel that is used for jittering.\n\n# Examples\n```julia\n```\n\n\"\"\"\nfunction jitterkernel(particles::SMCParticles, iter::Int64)\n return particles.kernel[iter]\nend\n\n############################################################################################\n\"\"\"\n$(SIGNATURES)\nResample particle ancestors, shuffle current particles and rejuvenate θ.\n\n# Examples\n```julia\n```\n\n\"\"\"\nfunction resample!(\n _rng::Random.AbstractRNG,\n particles::SMCParticles,\n tune::SMCTune,\n data::D,\n temperature::F\n) where {D, F<:AbstractFloat}\n ## Set resample back to false from previous iteration\n init!(tune.resample, false)\n ## Compute ESS\n ESS = BaytesCore.computeESS(particles.weights)\n resampled = BaytesCore.issmaller(ESS, tune.chains.Nchains * tune.chains.threshold)\n if resampled\n ## Record in tuning for diagnostics and propagation step\n init!(tune.resample, true)\n ## Resample ancestors ~ buffer already contain normalized weights from computeESS(weights) call\n resample!(\n _rng,\n tune.resample.method,\n particles.buffer.parameter.index,\n tune.iter.current,\n particles.weights.buffer,\n tune.chains.Nchains,\n )\n ## Equal weight normalized weights for next iteration memory\n Base.fill!(particles.weights.ℓweightsₙ, log(1.0 / tune.chains.Nchains))\n ## Reshuffle θ and rejuvenation particles - can be done inplace via buffer\n #!NOTE: Also set cumulative particle weights smc.buffer.weights back to correct position\n BaytesCore.shuffle!(particles.buffer.parameter, particles.kernel, particles.model, particles.buffer.cumweights)\n ## Rejuvenate Particles\n jitter!(_rng, particles, tune, data, temperature)\n ## Reweight ℓweights used for tempering so have correct index and temperature for next iteration\n reweight!(_rng, particles, tune, data, temperature)\n end\n return ESS, resampled\nend\n\n############################################################################################\n\"\"\"\n$(SIGNATURES)\nJitter θ particles with given kernels. This is performed in 2 stages:\n1. kernel is updated with new data and shuffled particles, then one proposal step is performed.\n2. If more than one jitterstep has to be performed, previous results might be captured depending on the kernel.\n\n# Examples\n```julia\n```\n\n\"\"\"\nfunction jitter!(_rng::Random.AbstractRNG, particles::SMCParticles, tune::SMCTune, data::D, temperature::F) where {D, F<:AbstractFloat}\n ## Make first jitter step, update for new data and shuffled parameter\n Base.Threads.@threads for iter in eachindex(particles.kernel)\n ## Propose new parameter\n _, particles.buffer.jitterdiagnostics[iter] = propose!(\n _rng,\n jitterkernel(particles, iter),\n particles.model[iter],\n data,\n temperature,\n BaytesCore.UpdateTrue()\n )\n #!NOTE: has to be in loop for scoping rules\n particles.buffer.predictions[iter] = BaytesCore.get_prediction(\n particles.buffer.jitterdiagnostics[iter]\n )\n end\n # Calculate Correlation between old and new θ particles\n compute_ρ!(particles.buffer.correlation, particles.buffer.parameter.result, particles.kernel)\n # Check if jittering can be stopped\n jitter = BaytesCore.jitter!(tune.jitter, tune.jitterfun(particles.buffer.correlation.ρ))\n ## If more than one jitterstep has to be performed, previous results might be captured depending on the kernel.\n #!NOTE buffer.parameter.result.θᵤ at correct place because jitter! only happens after shuffle!\n while jitter\n ## Jitter Particles\n Base.Threads.@threads for iter in eachindex(particles.kernel)\n ## Propose new parameter\n #!TODO: This is only true in the first call though, if more than 1 step jittered, MCMC only kernels could be set to UpdateFalse()\n _, particles.buffer.jitterdiagnostics[iter] = propose!(\n _rng,\n jitterkernel(particles, iter),\n particles.model[iter],\n data,\n temperature,\n tune.capture\n )\n #!NOTE: has to be in loop for scoping rules\n particles.buffer.predictions[iter] = BaytesCore.get_prediction(\n particles.buffer.jitterdiagnostics[iter]\n )\n end\n ## Calculate Correlation between old and new θ particles\n compute_ρ!(particles.buffer.correlation, particles.buffer.parameter.result, particles.kernel)\n ## Check if jittering can be stopped\n jitter = jitter!(tune.jitter, tune.jitterfun(particles.buffer.correlation.ρ))\n end\n return nothing\nend\n\n############################################################################################\n\"\"\"\n$(SIGNATURES)\nPropagate data forward over time. If (latent) data has to be extended, need to overload this function for specific smc kernel.\n\n# Examples\n```julia\n```\n\n\"\"\"\nfunction propagate!(_rng::Random.AbstractRNG, particles::SMCParticles, tune::SMCTune, data::D, temperature::F) where {D, F<:AbstractFloat}\n return nothing\nend\n\n############################################################################################\n\"\"\"\n$(SIGNATURES)\nPredict new data for each smc particle.\n\n# Examples\n```julia\n```\n\n\"\"\"\nfunction predict!(_rng::Random.AbstractRNG, particles::SMCParticles, tune::SMCTune, data::D, temperature::F) where {D, F<:AbstractFloat}\n ## Propagate series forward with recent particle\n for iter in eachindex(particles.model)\n ## Predict new data point\n particles.buffer.predictions[iter] = predict(\n _rng,\n particles.kernel[iter],\n Objective(particles.model[iter], data, tune.tagged, temperature)\n )\n end\n #!NOTE: Here, particles.buffer.jitterdiagnostics will not be updated, and for SMCDiagnostics, last available jitterdiagnostics are provided.\n return nothing\nend\n\n############################################################################################\n\"\"\"\n$(SIGNATURES)\nCompute new cumulative and incremental particle weights.\n\n# Examples\n```julia\n```\n\n\"\"\"\nfunction weight!(\n _rng::Random.AbstractRNG,\n particles::SMCParticles,\n tune::SMCTune,\n data::D,\n temperature::F\n) where {D, F<:AbstractFloat}\n ## Compute incremental weight for resampling step, and cumulative weight for i) next iteration and ii) temperature adjustment\n @inbounds for iter in eachindex(particles.weights.ℓweights)\n objective = Objective(particles.model[iter], data, tune.tagged, temperature)\n #!NOTE: particles.buffer.cumweights is cumulative weight at previous iteration, accounting for jittering step.\n particles.buffer.cumweights[iter], particles.weights.ℓweights[iter] = SMCweight(\n _rng,\n objective, particles.kernel[iter],\n particles.buffer.cumweights[iter]\n )\n end\n BaytesFilters.normalize!(particles.weights)\n return nothing\nend\n\n############################################################################################\n\"\"\"\n$(SIGNATURES)\nCompute cumulative and incremental weight of objective at time/iteration t, given weight at t-1.\nIncremental weight will be used as particle weight for resampling.\nCumulative weight will be used to adapt temperature.\n\nIf temperature is constant, this function can be overloaded with your ModelName if incremental weight can be computed independent of previous weight,\nwhich speeds up computation. `cumweightsₜ` is not needed in this case.\n\n# Examples\n```julia\n```\n\n\"\"\"\nfunction SMCweight(_rng::Random.AbstractRNG, objective::Objective, algorithm, cumweightsₜ₋₁)\n cumweightsₜ = objective.temperature * objective(objective.model.val)\n #!NOTE: cumweightsₜ₋₁ already has correct temperature at t-1\n return cumweightsₜ, cumweightsₜ - cumweightsₜ₋₁\nend\n\n############################################################################################\n\"\"\"\n$(SIGNATURES)\nCompute new cumulative particle weights, accounting for jittering steps. This is only needed for\nnext iteration's weight calculation, and will not adjust current incremental and normalized weight.\n\n# Examples\n```julia\n```\n\n\"\"\"\nfunction reweight!(\n _rng::Random.AbstractRNG,\n particles::SMCParticles,\n tune::SMCTune,\n data::D,\n temperature::F\n) where {D, F<:AbstractFloat}\n ## Compute incremental weight for resampling step, and cumulative weight for i) next iteration and ii) temperature adjustment\n @inbounds for iter in eachindex(particles.weights.ℓweights)\n objective = Objective(particles.model[iter], data, tune.tagged, temperature)\n #!NOTE: particles.buffer.cumweights is cumulative weight at previous iteration, accounting for jittering step.\n particles.buffer.cumweights[iter], _ = SMCreweight(\n _rng,\n objective,\n particles.kernel[iter],\n particles.buffer.cumweights[iter]\n )\n end\n return nothing\nend\n\n############################################################################################\n\"\"\"\n$(SIGNATURES)\nComputes particle weights after jiterring step. Defaults to `SMCweight` function.\n\n# Examples\n```julia\n```\n\n\"\"\"\nfunction SMCreweight(_rng::Random.AbstractRNG, objective::Objective, algorithm, cumweightsₜ₋₁)\n return SMCweight(_rng, objective, algorithm, cumweightsₜ₋₁)\nend\n\n############################################################################################\n# Export\nexport\n resample!,\n jitter!,\n propagate!,\n weight!,\n reweight!,\n SMCweight,\n SMCreweight\n", "meta": {"hexsha": "b8c0afcf58eb42a619c6fdbd972f4dd7a36e74fc", "size": 9766, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Core/trajectories.jl", "max_stars_repo_name": "paschermayr/BaytesSMC.jl", "max_stars_repo_head_hexsha": "a0ff1b6a582271bfebeefd1b6ebc884171f464e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/trajectories.jl", "max_issues_repo_name": "paschermayr/BaytesSMC.jl", "max_issues_repo_head_hexsha": "a0ff1b6a582271bfebeefd1b6ebc884171f464e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-10T16:39:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T18:06:48.000Z", "max_forks_repo_path": "src/Core/trajectories.jl", "max_forks_repo_name": "paschermayr/BaytesSMC.jl", "max_forks_repo_head_hexsha": "a0ff1b6a582271bfebeefd1b6ebc884171f464e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3048327138, "max_line_length": 149, "alphanum_fraction": 0.6277902929, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23833123661849287}} {"text": "# type\nmutable struct DQMCStack{GreensEltype<:Number, HoppingEltype<:Number} <: AbstractDQMCStack\n eye_flv::Matrix{Float64}\n eye_full::Matrix{Float64}\n ones_vec::Vector{Float64}\n\n u_stack::Array{GreensEltype, 3}\n d_stack::Matrix{Float64}\n t_stack::Array{GreensEltype, 3}\n\n Ul::Matrix{GreensEltype}\n Ur::Matrix{GreensEltype}\n Dl::Vector{Float64}\n Dr::Vector{Float64}\n Tl::Matrix{GreensEltype}\n Tr::Matrix{GreensEltype}\n\n greens::Matrix{GreensEltype}\n greens_temp::Matrix{GreensEltype}\n log_det::Float64 # contains logdet of greens_{mc.p.slices+1} === greens_1\n # after we calculated a fresh greens in propagate()\n\n U::Matrix{GreensEltype}\n D::Vector{Float64}\n T::Matrix{GreensEltype}\n tmp::Matrix{GreensEltype}\n\n ranges::Array{UnitRange, 1}\n n_elements::Int\n current_slice::Int # running internally over 0:mc.p.slices+1, where 0 and mc.p.slices+1 are artifcial to prepare next sweep direction.\n direction::Int\n\n # # -------- Global update backup\n # gb_u_stack::Array{GreensEltype, 3}\n # gb_d_stack::Matrix{Float64}\n # gb_t_stack::Array{GreensEltype, 3}\n\n # gb_greens::Matrix{GreensEltype}\n # gb_log_det::Float64\n\n # gb_conf::Array{Float64, 3}\n # # --------\n\n\n # preallocated, reused arrays\n curr_U::Matrix{GreensEltype}\n eV::Matrix{GreensEltype}\n\n # hopping matrices\n hopping_matrix_exp::Matrix{HoppingEltype} # mu included\n hopping_matrix_exp_inv::Matrix{HoppingEltype} # mu included\n\n # checkerboard hopping matrices\n checkerboard::Matrix{Int} # src, trg, bondid\n groups::Vector{UnitRange}\n n_groups::Int\n chkr_hop_half::Vector{SparseMatrixCSC{HoppingEltype, Int64}}\n chkr_hop_half_inv::Vector{SparseMatrixCSC{HoppingEltype, Int64}}\n chkr_hop_half_dagger::Vector{SparseMatrixCSC{HoppingEltype, Int64}}\n chkr_hop::Vector{SparseMatrixCSC{HoppingEltype, Int64}} # without prefactor 0.5 in matrix exponentials\n chkr_hop_inv::Vector{SparseMatrixCSC{HoppingEltype, Int64}}\n chkr_hop_dagger::Vector{SparseMatrixCSC{HoppingEltype, Int64}}\n chkr_mu_half::SparseMatrixCSC{HoppingEltype, Int64}\n chkr_mu_half_inv::SparseMatrixCSC{HoppingEltype, Int64}\n chkr_mu::SparseMatrixCSC{HoppingEltype, Int64}\n chkr_mu_inv::SparseMatrixCSC{HoppingEltype, Int64}\n\n\n DQMCStack{GreensEltype, HoppingEltype}() where {GreensEltype<:Number, HoppingEltype<:Number} = begin\n # @assert isleaftype(GreensEltype);\n # @assert isleaftype(HoppingEltype);\n @assert isconcretetype(GreensEltype);\n @assert isconcretetype(HoppingEltype);\n new()\n end\nend\n\n# type helpers\ngeltype(::Type{DQMCStack{G,H}}) where {G,H} = G\nheltype(::Type{DQMCStack{G,H}}) where {G,H} = H\ngeltype(mc::DQMC{M, CB, CT, S}) where {M, CB, CT, S} = geltype(S)\nheltype(mc::DQMC{M, CB, CT, S}) where {M, CB, CT, S} = heltype(S)\n\n# type initialization\nfunction initialize_stack(mc::DQMC)\n GreensEltype = geltype(mc)\n HoppingEltype = heltype(mc)\n N = mc.model.l.sites\n flv = mc.model.flv\n\n mc.s.eye_flv = Matrix{Float64}(I, flv,flv)\n mc.s.eye_full = Matrix{Float64}(I, flv*N,flv*N)\n mc.s.ones_vec = ones(flv*N)\n\n mc.s.n_elements = convert(Int, mc.p.slices / mc.p.safe_mult) + 1\n\n mc.s.u_stack = zeros(GreensEltype, flv*N, flv*N, mc.s.n_elements)\n mc.s.d_stack = zeros(Float64, flv*N, mc.s.n_elements)\n mc.s.t_stack = zeros(GreensEltype, flv*N, flv*N, mc.s.n_elements)\n\n mc.s.greens = zeros(GreensEltype, flv*N, flv*N)\n mc.s.greens_temp = zeros(GreensEltype, flv*N, flv*N)\n\n mc.s.Ul = Matrix{GreensEltype}(I, flv*N, flv*N)\n mc.s.Ur = Matrix{GreensEltype}(I, flv*N, flv*N)\n mc.s.Tl = Matrix{GreensEltype}(I, flv*N, flv*N)\n mc.s.Tr = Matrix{GreensEltype}(I, flv*N, flv*N)\n mc.s.Dl = ones(Float64, flv*N)\n mc.s.Dr = ones(Float64, flv*N)\n\n mc.s.U = zeros(GreensEltype, flv*N, flv*N)\n mc.s.D = zeros(Float64, flv*N)\n mc.s.T = zeros(GreensEltype, flv*N, flv*N)\n mc.s.tmp = zeros(GreensEltype, flv*N, flv*N)\n\n\n # # Global update backup\n # mc.s.gb_u_stack = zero(mc.s.u_stack)\n # mc.s.gb_d_stack = zero(mc.s.d_stack)\n # mc.s.gb_t_stack = zero(mc.s.t_stack)\n # mc.s.gb_greens = zero(mc.s.greens)\n # mc.s.gb_log_det = 0.\n # mc.s.gb_conf = zero(mc.conf)\n\n mc.s.ranges = UnitRange[]\n\n for i in 1:mc.s.n_elements - 1\n push!(mc.s.ranges, 1 + (i - 1) * mc.p.safe_mult:i * mc.p.safe_mult)\n end\n\n mc.s.curr_U = zero(mc.s.U)\n mc.s.eV = zeros(GreensEltype, flv*N, flv*N)\n\n # mc.s.hopping_matrix_exp = zeros(HoppingEltype, flv*N, flv*N)\n # mc.s.hopping_matrix_exp_inv = zeros(HoppingEltype, flv*N, flv*N)\n nothing\nend\n\n# hopping\nfunction init_hopping_matrices(mc::DQMC{M,CB}, m::Model) where {M, CB<:Checkerboard}\n init_hopping_matrix_exp(mc, m)\n CB <: CheckerboardTrue && init_checkerboard_matrices(mc, m)\n nothing\nend\nfunction init_hopping_matrix_exp(mc::DQMC, m::Model)\n N = m.l.sites\n flv = m.flv\n dtau = mc.p.delta_tau\n\n T = hopping_matrix(mc, m)\n size(T) == (flv*N, flv*N) || error(\"Hopping matrix should have size \"*\n \"$((flv*N, flv*N)) but has size $(size(T)) .\")\n mc.s.hopping_matrix_exp = exp(-0.5 * dtau * T)\n mc.s.hopping_matrix_exp_inv = exp(0.5 * dtau * T)\n nothing\nend\n\n# checkerboard\nrem_eff_zeros!(X::AbstractArray) = map!(e -> abs.(e)<1e-15 ? zero(e) : e,X,X)\nfunction init_checkerboard_matrices(mc::DQMC, m::Model)\n s = mc.s\n l = m.l\n flv = m.flv\n H = heltype(mc)\n N = m.l.sites\n dtau = mc.p.delta_tau\n mu = m.mu\n\n s.checkerboard, s.groups, s.n_groups = build_checkerboard(l)\n n_grps = s.n_groups\n cb = s.checkerboard\n\n T = reshape(hopping_matrix(mc, m), (N, flv, N, flv))\n\n s.chkr_hop_half = Vector{SparseMatrixCSC{H, Int}}(undef, n_grps)\n s.chkr_hop_half_inv = Vector{SparseMatrixCSC{H, Int}}(undef, n_grps)\n s.chkr_hop = Vector{SparseMatrixCSC{H, Int}}(undef, n_grps)\n s.chkr_hop_inv = Vector{SparseMatrixCSC{H, Int}}(undef, n_grps)\n\n for (g, gr) in enumerate(s.groups)\n Tg = zeros(H, N, flv, N, flv)\n for i in gr\n src, trg = cb[1:2,i]\n for f1 in 1:flv, f2 in 1:flv\n Tg[trg, f1, src, f2] = T[trg, f1, src, f2]\n end\n end\n\n Tgg = reshape(Tg, (N*flv, N*flv))\n s.chkr_hop_half[g] = sparse(rem_eff_zeros!(exp(-0.5 * dtau * Tgg)))\n s.chkr_hop_half_inv[g] = sparse(rem_eff_zeros!(exp(0.5 * dtau * Tgg)))\n s.chkr_hop[g] = sparse(rem_eff_zeros!(exp(- dtau * Tgg)))\n s.chkr_hop_inv[g] = sparse(rem_eff_zeros!(exp(dtau * Tgg)))\n end\n\n s.chkr_hop_half_dagger = adjoint.(s.chkr_hop_half)\n s.chkr_hop_dagger = adjoint.(s.chkr_hop)\n\n mus = diag(reshape(T, (N*flv, N*flv)))\n s.chkr_mu_half = spdiagm(0 => exp.(-0.5 * dtau * mus))\n s.chkr_mu_half_inv = spdiagm(0 => exp.(0.5 * dtau * mus))\n s.chkr_mu = spdiagm(0 => exp.(-dtau * mus))\n s.chkr_mu_inv = spdiagm(0 => exp.(dtau * mus))\n\n # hop_mat_exp_chkr = foldl(*,s.chkr_hop_half) * sqrt.(s.chkr_mu)\n # r = effreldiff(s.hopping_matrix_exp,hop_mat_exp_chkr)\n # r[find(x->x==zero(x),hop_mat_exp_chkr)] = 0.\n # println(\"Checkerboard - Exact ≈ \", round(maximum(absdiff(s.hopping_matrix_exp,hop_mat_exp_chkr)), 4))\n nothing\nend\n\n# stack construction\n\"\"\"\nBuild stack from scratch.\n\"\"\"\nfunction build_stack(mc::DQMC)\n mc.s.u_stack[:, :, 1] = mc.s.eye_full\n mc.s.d_stack[:, 1] = mc.s.ones_vec\n mc.s.t_stack[:, :, 1] = mc.s.eye_full\n\n @inbounds for i in 1:length(mc.s.ranges)\n add_slice_sequence_left(mc, i)\n end\n\n mc.s.current_slice = mc.p.slices + 1\n mc.s.direction = -1\n\n nothing\nend\n\"\"\"\nUpdates stack[idx+1] based on stack[idx]\n\"\"\"\nfunction add_slice_sequence_left(mc::DQMC, idx::Int)\n copyto!(mc.s.curr_U, mc.s.u_stack[:, :, idx])\n\n # println(\"Adding slice seq left $idx = \", mc.s.ranges[idx])\n for slice in mc.s.ranges[idx]\n multiply_slice_matrix_left!(mc, mc.model, slice, mc.s.curr_U)\n end\n\n mc.s.curr_U *= spdiagm(0 => mc.s.d_stack[:, idx])\n mc.s.u_stack[:, :, idx + 1], mc.s.d_stack[:, idx + 1], T = udt(mc.s.curr_U)\n mc.s.t_stack[:, :, idx + 1] = T * mc.s.t_stack[:, :, idx]\nend\n\"\"\"\nUpdates stack[idx] based on stack[idx+1]\n\"\"\"\nfunction add_slice_sequence_right(mc::DQMC, idx::Int)\n copyto!(mc.s.curr_U, mc.s.u_stack[:, :, idx + 1])\n\n for slice in reverse(mc.s.ranges[idx])\n multiply_daggered_slice_matrix_left!(mc, mc.model, slice, mc.s.curr_U)\n end\n\n mc.s.curr_U *= spdiagm(0 => mc.s.d_stack[:, idx + 1])\n mc.s.u_stack[:, :, idx], mc.s.d_stack[:, idx], T = udt(mc.s.curr_U)\n mc.s.t_stack[:, :, idx] = T * mc.s.t_stack[:, :, idx + 1]\nend\n\n# Green's function calculation\n\"\"\"\nCalculates G(slice) using mc.s.Ur,mc.s.Dr,mc.s.Tr=B(slice)' ... B(M)' and\nmc.s.Ul,mc.s.Dl,mc.s.Tl=B(slice-1) ... B(1)\n\"\"\"\nfunction calculate_greens(mc::DQMC)\n # U, D, T = udt(mc.s.greens) after this\n mc.s.U, mc.s.D, mc.s.T = udt_inv_one_plus(\n UDT(mc.s.Ul, mc.s.Dl, mc.s.Tl),\n UDT(mc.s.Ur, mc.s.Dr, mc.s.Tr),\n tmp = mc.s.U, tmp2 = mc.s.T, tmp3 = mc.s.tmp,\n internaluse = true\n )\n mul!(mc.s.tmp, mc.s.U, Diagonal(mc.s.D))\n mul!(mc.s.greens, mc.s.tmp, mc.s.T)\n mc.s.greens\nend\n\n\"\"\"\nOnly reasonable immediately after calculate_greens()!\n\"\"\"\nfunction calculate_logdet(mc::DQMC)\n mc.s.log_det = real(\n log(complex(det(mc.s.U))) +\n sum(log.(mc.s.D)) +\n log(complex(det(mc.s.T)))\n )\n # mc.s.log_det = real(logdet(mc.s.U) + sum(log.(mc.s.D)) + logdet(mc.s.T))\nend\n\n# Green's function propagation\n@inline function wrap_greens!(mc::DQMC, gf::Matrix, curr_slice::Int, direction::Int)\n if direction == -1\n multiply_slice_matrix_inv_left!(mc, mc.model, curr_slice - 1, gf)\n multiply_slice_matrix_right!(mc, mc.model, curr_slice - 1, gf)\n else\n multiply_slice_matrix_left!(mc, mc.model, curr_slice, gf)\n multiply_slice_matrix_inv_right!(mc, mc.model, curr_slice, gf)\n end\n nothing\nend\n# @inline function wrap_greens(mc::DQMC, gf::Matrix,slice::Int,direction::Int)\n# temp = copy(gf)\n# wrap_greens!(mc, temp, slice, direction)\n# return temp\n# end\nfunction propagate(mc::DQMC)\n if mc.s.direction == 1\n if mod(mc.s.current_slice, mc.p.safe_mult) == 0\n mc.s.current_slice +=1 # slice we are going to\n if mc.s.current_slice == 1\n mc.s.Ur[:, :], mc.s.Dr[:], mc.s.Tr[:, :] = mc.s.u_stack[:, :, 1], mc.s.d_stack[:, 1], mc.s.t_stack[:, :, 1]\n mc.s.u_stack[:, :, 1] = mc.s.eye_full\n mc.s.d_stack[:, 1] = mc.s.ones_vec\n mc.s.t_stack[:, :, 1] = mc.s.eye_full\n mc.s.Ul[:,:], mc.s.Dl[:], mc.s.Tl[:,:] = mc.s.u_stack[:, :, 1], mc.s.d_stack[:, 1], mc.s.t_stack[:, :, 1]\n\n calculate_greens(mc) # greens_1 ( === greens_{m+1} )\n calculate_logdet(mc)\n\n elseif 1 < mc.s.current_slice <= mc.p.slices\n idx = Int((mc.s.current_slice - 1)/mc.p.safe_mult)\n\n mc.s.Ur[:, :], mc.s.Dr[:], mc.s.Tr[:, :] = mc.s.u_stack[:, :, idx+1], mc.s.d_stack[:, idx+1], mc.s.t_stack[:, :, idx+1]\n add_slice_sequence_left(mc, idx)\n mc.s.Ul[:,:], mc.s.Dl[:], mc.s.Tl[:,:] = mc.s.u_stack[:, :, idx+1], mc.s.d_stack[:, idx+1], mc.s.t_stack[:, :, idx+1]\n\n if mc.p.all_checks\n mc.s.greens_temp = copy(mc.s.greens)\n end\n\n wrap_greens!(mc, mc.s.greens_temp, mc.s.current_slice - 1, 1)\n\n calculate_greens(mc) # greens_{slice we are propagating to}\n\n if mc.p.all_checks\n greensdiff = maximum(abs.(mc.s.greens_temp - mc.s.greens)) # OPT: could probably be optimized through explicit loop\n if greensdiff > 1e-7\n @printf(\"->%d \\t+1 Propagation instability\\t %.1e\\n\", mc.s.current_slice, greensdiff)\n end\n end\n\n else # we are going to mc.p.slices+1\n idx = mc.s.n_elements - 1\n add_slice_sequence_left(mc, idx)\n mc.s.direction = -1\n mc.s.current_slice = mc.p.slices+1 # redundant\n propagate(mc)\n end\n\n else\n # Wrapping\n wrap_greens!(mc, mc.s.greens, mc.s.current_slice, 1)\n mc.s.current_slice += 1\n end\n\n else # mc.s.direction == -1\n if mod(mc.s.current_slice-1, mc.p.safe_mult) == 0\n mc.s.current_slice -= 1 # slice we are going to\n if mc.s.current_slice == mc.p.slices\n mc.s.Ul[:, :], mc.s.Dl[:], mc.s.Tl[:, :] = mc.s.u_stack[:, :, end], mc.s.d_stack[:, end], mc.s.t_stack[:, :, end]\n mc.s.u_stack[:, :, end] = mc.s.eye_full\n mc.s.d_stack[:, end] = mc.s.ones_vec\n mc.s.t_stack[:, :, end] = mc.s.eye_full\n mc.s.Ur[:,:], mc.s.Dr[:], mc.s.Tr[:,:] = mc.s.u_stack[:, :, end], mc.s.d_stack[:, end], mc.s.t_stack[:, :, end]\n\n calculate_greens(mc) # greens_{mc.p.slices+1} === greens_1\n calculate_logdet(mc) # calculate logdet for potential global update\n\n # wrap to greens_{mc.p.slices}\n wrap_greens!(mc, mc.s.greens, mc.s.current_slice + 1, -1)\n\n elseif 0 < mc.s.current_slice < mc.p.slices\n idx = Int(mc.s.current_slice / mc.p.safe_mult) + 1\n mc.s.Ul[:, :], mc.s.Dl[:], mc.s.Tl[:, :] = mc.s.u_stack[:, :, idx], mc.s.d_stack[:, idx], mc.s.t_stack[:, :, idx]\n add_slice_sequence_right(mc, idx)\n mc.s.Ur[:,:], mc.s.Dr[:], mc.s.Tr[:,:] = mc.s.u_stack[:, :, idx], mc.s.d_stack[:, idx], mc.s.t_stack[:, :, idx]\n\n if mc.p.all_checks\n mc.s.greens_temp = copy(mc.s.greens)\n end\n\n calculate_greens(mc)\n\n if mc.p.all_checks\n greensdiff = maximum(abs.(mc.s.greens_temp - mc.s.greens)) # OPT: could probably be optimized through explicit loop\n if greensdiff > 1e-7\n @printf(\"->%d \\t-1 Propagation instability\\t %.1e\\n\", mc.s.current_slice, greensdiff)\n end\n end\n\n wrap_greens!(mc, mc.s.greens, mc.s.current_slice + 1, -1)\n\n else # we are going to 0\n idx = 1\n add_slice_sequence_right(mc, idx)\n mc.s.direction = 1\n mc.s.current_slice = 0 # redundant\n propagate(mc)\n end\n\n else\n # Wrapping\n wrap_greens!(mc, mc.s.greens, mc.s.current_slice, -1)\n mc.s.current_slice -= 1\n end\n end\n nothing\nend\n", "meta": {"hexsha": "ed00f18b0daf1de33316996450584cfd5ec15251", "size": 13741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/flavors/DQMC/stack.jl", "max_stars_repo_name": "yosefcap/MC", "max_stars_repo_head_hexsha": "a862d85762b2b17a91b5deec6d1938f3438ac521", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/flavors/DQMC/stack.jl", "max_issues_repo_name": "yosefcap/MC", "max_issues_repo_head_hexsha": "a862d85762b2b17a91b5deec6d1938f3438ac521", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/flavors/DQMC/stack.jl", "max_forks_repo_name": "yosefcap/MC", "max_forks_repo_head_hexsha": "a862d85762b2b17a91b5deec6d1938f3438ac521", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5965770171, "max_line_length": 136, "alphanum_fraction": 0.6356888145, "num_tokens": 4700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2381704124172608}} {"text": "# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# Description\n# ==============================================================================\n#\n# Tests related to ECI to ECI transformations using satellite state vector.\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# References\n# ==============================================================================\n#\n# [1] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications.\n# Microcosm Press, Hawthorn, CA, USA.\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n# Get the current EOP Data.\n#\n# TODO: The EOP data obtained from IERS website does not match the values in the\n# examples in [1]. However, this should be enough, because 1) the individual\n# functions at the low level are tested using the same values of [1], and 2) the\n# difference is smaller than 30 cm.\n\neop_iau1980 = read_iers_eop(\"./eop_IAU1980.txt\", Val(:IAU1980))\neop_iau2000a = read_iers_eop(\"./eop_IAU2000A.txt\", Val(:IAU2000A))\n\n# File: ./src/transformations/sv_eci_to_eci.jl\n# ============================================\n\n################################################################################\n# IAU-76/FK5\n################################################################################\n\n# Functions: sv_eci_to_eci\n# ------------------------\n\n# The rotations functions were already heavily tested on `eci_to_eci.jl` file.\n# Hence, here we will do only some minor testing involving the following\n# transformations:\n#\n# GCRF <=> J2000 (FK5)\n# MOD <=> TOD (FK5)\n# GCRF <=> CIRS (IAU2006)\n\n# GCRF <=> J2000\n# ==============\n\n################################################################################\n# Test Results\n################################################################################\n#\n# Scenario 01\n# ===========\n#\n# Example 3-15: Performing IAU-76/FK5 reduction.\n#\n# According to this example and Table 3-6, using:\n#\n# UTC = April 6, 2004, 07:51:28.386009\n# r_gcrf = 5102.50895790 i + 6123.01140070 j + 6378.13692820 k [km]\n# v_gcrf = -4.7432201570 i + 0.7905364970 j + 5.5337557270 k [km/s]\n#\n# one gets:\n#\n# r_j2000 = 5102.50960000 i + 6123.01152000 j + 6378.13630000 k [km]\n# v_j2000 = -4.7432196000 i + 0.7905366000 j + 5.5337561900 k [km/s]\n#\n################################################################################\n\n@testset \"Function sv_eci_to_eci GCRF <=> J2000\" begin\n JD_UTC = date_to_jd(2004, 4, 6, 7, 51, 28.386009)\n\n ## GCRF => J2000\n ## =============\n\n r_gcrf = [5102.50895790; 6123.01140070; 6378.13692820]\n v_gcrf = [-4.7432201570; 0.7905364970; 5.5337557270]\n sv_gcrf = orbsv(JD_UTC, r_gcrf, v_gcrf)\n sv_j2000 = sv_eci_to_eci(sv_gcrf, GCRF(), J2000(), JD_UTC, eop_iau1980)\n\n @test sv_j2000.t === JD_UTC\n\n @test sv_j2000.r[1] ≈ +5102.50960000 atol=1e-4\n @test sv_j2000.r[2] ≈ +6123.01152000 atol=1e-4\n @test sv_j2000.r[3] ≈ +6378.13630000 atol=1e-4\n\n @test sv_j2000.v[1] ≈ -4.7432196000 atol=1e-7\n @test sv_j2000.v[2] ≈ +0.7905366000 atol=1e-7\n @test sv_j2000.v[3] ≈ +5.5337561900 atol=1e-7\n\n ## J2000 => GCRF\n ## =============\n\n r_j2000 = [5102.50960000; 6123.01152000; 6378.13630000]\n v_j2000 = [-4.7432196000; 0.7905366000; 5.5337561900]\n sv_j2000 = orbsv(JD_UTC, r_j2000, v_j2000)\n sv_gcrf = sv_eci_to_eci(sv_j2000, J2000(), GCRF(), JD_UTC, eop_iau1980)\n\n @test sv_gcrf.t === JD_UTC\n\n @test sv_gcrf.r[1] ≈ +5102.50895790 atol=1e-4\n @test sv_gcrf.r[2] ≈ +6123.01140070 atol=1e-4\n @test sv_gcrf.r[3] ≈ +6378.13692820 atol=1e-4\n\n @test sv_gcrf.v[1] ≈ -4.7432201570 atol=1e-7\n @test sv_gcrf.v[2] ≈ +0.7905364970 atol=1e-7\n @test sv_gcrf.v[3] ≈ +5.5337557270 atol=1e-7\n\nend\n\n# MOD <=> TOD\n# ============\n\n################################################################################\n# Test Results\n################################################################################\n#\n# Scenario 01\n# ===========\n#\n# Example 3-15: Performing IAU-76/FK5 reduction.\n#\n# According to this example and Table 3-6, using:\n#\n# UTC = April 6, 2004, 07:51:28.386009\n# r_mod = 5094.02837450 i + 6127.87081640 j + 6380.24851640 k [km]\n# v_mod = -4.7462630520 i + 0.7860140450 j + 5.5317905620 k [km/s]\n#\n# one gets:\n#\n# r_tod = 5094.51620300 i + 6127.36527840 j + 6380.34453270 k [km]\n# v_tod = -4.7460883850 i + 0.7860783240 j + 5.5319312880 k [km/s]\n#\n################################################################################\n\n@testset \"Function sv_eci_to_eci MOD <=> TOD\" begin\n JD_UTC = date_to_jd(2004, 4, 6, 7, 51, 28.386009)\n\n ## MOD => TOD\n ## ===========\n\n r_mod = [5094.02837450; 6127.87081640; 6380.24851640]\n v_mod = [-4.7462630520; 0.7860140450; 5.5317905620]\n sv_mod = orbsv(JD_UTC, r_mod, v_mod)\n sv_tod = sv_eci_to_eci(sv_mod, MOD(), JD_UTC, TOD(), JD_UTC, eop_iau1980)\n\n @test sv_tod.t === JD_UTC\n\n @test sv_tod.r[1] ≈ +5094.51620300 atol=1e-4\n @test sv_tod.r[2] ≈ +6127.36527840 atol=1e-4\n @test sv_tod.r[3] ≈ +6380.34453270 atol=1e-4\n\n @test sv_tod.v[1] ≈ -4.7460883850 atol=1e-7\n @test sv_tod.v[2] ≈ +0.7860783240 atol=1e-7\n @test sv_tod.v[3] ≈ +5.5319312880 atol=1e-7\n\n ## TOD => MOD\n ## ===========\n\n r_tod = [5094.51620300; 6127.36527840; 6380.34453270]\n v_tod = [-4.7460883850; 0.7860783240; 5.5319312880]\n sv_tod = orbsv(JD_UTC, r_tod, v_tod)\n sv_mod = sv_eci_to_eci(sv_tod, TOD(), JD_UTC, MOD(), JD_UTC, eop_iau1980)\n\n @test sv_mod.t === JD_UTC\n\n @test sv_mod.r[1] ≈ +5094.02837450 atol=1e-4\n @test sv_mod.r[2] ≈ +6127.87081640 atol=1e-4\n @test sv_mod.r[3] ≈ +6380.24851640 atol=1e-4\n\n @test sv_mod.v[1] ≈ -4.7462630520 atol=1e-7\n @test sv_mod.v[2] ≈ +0.7860140450 atol=1e-7\n @test sv_mod.v[3] ≈ +5.5317905620 atol=1e-7\n\nend\n\n################################################################################\n# IAU-2006/2010\n################################################################################\n\n## GCRF <=> CIRS\n## =============\n\n################################################################################\n# Test Results\n################################################################################\n#\n# Scenario 01\n# ===========\n#\n# Example 3-14: Performing an IAU-2000 reduction [1, p. 220]\n#\n# According to this example and Table 3-6, using:\n#\n# NOTE: It seems that the results in the Example 3-14 is computed **without**\n# the `dX` and `dY` corrections, whereas in the Table 3-6 they are computed\n# **with** the corrections.\n#\n# UTC = April 6, 2004, 07:51:28.386009\n# r_cirs = -5100.01840470 i + 6122.78636480 j + 6380.34453270 k [km]\n# v_cirs = -4.7453803300 i - 0.7903414530 j + 5.5319312880 k [km/s]\n#\n# one gets the following (this is the result in Table 3-6):\n#\n# r_gcrf = 5102.50895290 i + 6123.01139910 j + 6378.13693380 k [km]\n# v_gcrf = -4.7432201610 i + 0.7905364950 j + 5.5337557240 k [km/s]\n#\n################################################################################\n\n@testset \"Function sv_eci_to_eci GCRF <=> CIRS\" begin\n JD_UTC = date_to_jd(2004, 4, 6, 7, 51, 28.386009)\n\n ## GCRF => CIRS\n ## ===========\n\n r_gcrf = [5102.50895290; 6123.01139910; 6378.13693380]\n v_gcrf = [-4.7432201610; 0.7905364950; 5.5337557240]\n sv_gcrf = orbsv(JD_UTC, r_gcrf, v_gcrf)\n sv_cirs = sv_eci_to_eci(sv_gcrf, GCRF(), CIRS(), JD_UTC, eop_iau2000a)\n\n @test sv_cirs.t === JD_UTC\n\n @test sv_cirs.r[1] ≈ +5100.01840470 atol=1e-4\n @test sv_cirs.r[2] ≈ +6122.78636480 atol=1e-4\n @test sv_cirs.r[3] ≈ +6380.34453270 atol=1e-4\n\n @test sv_cirs.v[1] ≈ -4.7453803300 atol=1e-7\n @test sv_cirs.v[2] ≈ +0.7903414530 atol=1e-7\n @test sv_cirs.v[3] ≈ +5.5319312880 atol=1e-7\n\n ## CIRS => GCRF\n ## ===========\n\n r_cirs = [+5100.01840470; +6122.78636480; +6380.34453270]\n v_cirs = [-4.7453803300; +0.7903414530; +5.5319312880]\n sv_cirs = orbsv(JD_UTC, r_cirs, v_cirs)\n sv_gcrf = sv_eci_to_eci(sv_cirs, CIRS(), GCRF(), JD_UTC, eop_iau2000a)\n\n @test sv_gcrf.t === JD_UTC\n\n @test sv_gcrf.r[1] ≈ +5102.50895290 atol=1e-4\n @test sv_gcrf.r[2] ≈ +6123.01139910 atol=1e-4\n @test sv_gcrf.r[3] ≈ +6378.13693380 atol=1e-4\n\n @test sv_gcrf.v[1] ≈ -4.7432201610 atol=1e-7\n @test sv_gcrf.v[2] ≈ +0.7905364950 atol=1e-7\n @test sv_gcrf.v[3] ≈ +5.5337557240 atol=1e-7\n\nend\n", "meta": {"hexsha": "67b67eb5d71c6e298088c13c824ba0d1ee008f07", "size": 8645, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/transformations/sv_eci_to_eci.jl", "max_stars_repo_name": "disberd/SatelliteToolbox.jl", "max_stars_repo_head_hexsha": "441470938af978e9d5653a9c4b36ccc107023960", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 157, "max_stars_repo_stars_event_min_datetime": "2018-06-19T21:11:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:24:41.000Z", "max_issues_repo_path": "test/transformations/sv_eci_to_eci.jl", "max_issues_repo_name": "disberd/SatelliteToolbox.jl", "max_issues_repo_head_hexsha": "441470938af978e9d5653a9c4b36ccc107023960", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71, "max_issues_repo_issues_event_min_datetime": "2018-06-18T20:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T21:33:20.000Z", "max_forks_repo_path": "test/transformations/sv_eci_to_eci.jl", "max_forks_repo_name": "disberd/SatelliteToolbox.jl", "max_forks_repo_head_hexsha": "441470938af978e9d5653a9c4b36ccc107023960", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2018-10-02T02:42:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T20:36:51.000Z", "avg_line_length": 34.4422310757, "max_line_length": 80, "alphanum_fraction": 0.5044534413, "num_tokens": 3270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2380574420636893}} {"text": "# TernaryLayer and TernaryMERA types, and methods thereof.\n# To be `included` in MERAKit.jl.\n\n\"\"\"\n TernaryLayer{ST, ET, Tan} <: SimpleLayer\n\nThe type for layers of a ternary MERA.\n\nEach layer consists of two tensors, a 2-to-2 disentangler, often called `u`, and a 3-to-1\nisometry, often called `w`.\n\nThe type parameters are `ST` for space type, e.g. `ComplexSpace` or `SU2Space`; `ET` for\nelement type, e.g. `Complex{Float64}`; and `Tan` for whether this layer is a tangent layer\nor not. If `Tan = false`, the layer in question is an actual MERA layer. If `Tan = true` it\nconsists, instead of the actual tensors, of Stiefel/Grassmann tangent vectors of these\ntensors.\n\n`TernaryLayer` implements the iteration interface, returning first the disentangler, then\nthe isometry.\n\nIndex numbering convention is as follows, where the physical indices are at the bottom:\nDisentangler:\n```\n 3│ 4│\n ┌┴─────┴┐\n │ u │\n └┬─────┬┘\n 1│ 2│\n```\n\nIsometry:\n```\n 4│\n ┌───┴───┐\n │ w │\n └┬──┬──┬┘\n 1│ 2│ 3│\n```\n\"\"\"\nstruct TernaryLayer{ST, ET, Tan} <: SimpleLayer\n # Even though the types are here marked as any, they are restricted to be specific,\n # concrete types dependent on ST, ET and Tan, both in the constructor and in\n # getproperty.\n disentangler::Any\n isometry::Any\n\n function TernaryLayer{ST, ET, Tan}(disentangler, isometry) where {ST, ET, Tan}\n DisType = disentangler_type(ST, ET, Tan)\n IsoType = ternaryisometry_type(ST, ET, Tan)\n disconv = convert(DisType, disentangler)::DisType\n isoconv = convert(IsoType, isometry)::IsoType\n return new{ST, ET, Tan}(disconv, isoconv)\n end\nend\n\nfunction TernaryLayer(disentangler::DisType, isometry::IsoType) where {\n ST,\n DisType <: AbstractTensorMap{ST, 2, 2},\n IsoType <: AbstractTensorMap{ST, 3, 1}\n}\n ET = eltype(DisType)\n @assert eltype(IsoType) === ET\n return TernaryLayer{ST, ET, false}(disentangler, isometry)\nend\n\nfunction TernaryLayer(disentangler::DisTanType, isometry::IsoTanType) where {\n ST,\n DisType <: AbstractTensorMap{ST, 2, 2},\n IsoType <: AbstractTensorMap{ST, 3, 1},\n DisTanType <: Stiefel.StiefelTangent{DisType},\n IsoTanType <: Grassmann.GrassmannTangent{IsoType},\n}\n ET = eltype(DisType)\n @assert eltype(IsoType) === ET\n return TernaryLayer{ST, ET, true}(disentangler, isometry)\nend\n\nfunction Base.getproperty(l::TernaryLayer{ST, ET, Tan}, sym::Symbol) where {ST, ET, Tan}\n if sym === :disentangler\n T = disentangler_type(ST, ET, Tan)\n elseif sym === :isometry\n T = ternaryisometry_type(ST, ET, Tan)\n else\n T = Any\n end\n return getfield(l, sym)::T\nend\n\n\"\"\"\n TernaryMERA{N}\n\nA ternary MERA is a MERA consisting of `TernaryLayer`s.\n\"\"\"\nTernaryMERA{N} = GenericMERA{N, T, O} where {T <: TernaryLayer, O}\nlayertype(::Type{TernaryMERA}) = TernaryLayer\n#Base.show(io::IO, ::Type{TernaryMERA}) = print(io, \"TernaryMERA\")\n#Base.show(io::IO, ::Type{TernaryMERA{N}}) where {N} = print(io, \"TernaryMERA{($N)}\")\n\n# Implement the iteration and indexing interfaces.\n# See simplelayer.jl for details.\n_tuple(layer::TernaryLayer) = (layer.disentangler, layer.isometry)\n\nfunction operatortype(::Type{TernaryLayer{ST, ET, false}}) where {ST, ET}\n return tensormaptype(ST, 2, 2, ET)\nend\noperatortype(::Type{TernaryLayer{ST, ET, true}}) where {ST, ET} = Nothing\n\nTensorKit.spacetype(::Type{TernaryLayer{ST, ET, Tan}}) where {ST, ET, Tan} = ST\n\nscalefactor(::Type{<:TernaryLayer}) = 3\n\ncausal_cone_width(::Type{<:TernaryLayer}) = 2\n\nBase.eltype(::Type{TernaryLayer{ST, ET, Tan}}) where {ST, ET, Tan} = ET\n\noutputspace(layer::TernaryLayer) = space(layer.disentangler, 1)\ninputspace(layer::TernaryLayer) = space(layer.isometry, 4)'\ninternalspace(layer::TernaryLayer) = space(layer.isometry, 1)\ninternalspace(m::TernaryMERA, depth) = internalspace(getlayer(m, depth))\n\nfunction expand_inputspace(layer::TernaryLayer, V_new)\n u, w = layer\n w = pad_with_zeros_to(w, 4 => V_new')\n return TernaryLayer(u, w)\nend\n\nfunction expand_outputspace(layer::TernaryLayer, V_new)\n u, w = layer\n u = pad_with_zeros_to(u, 1 => V_new, 2 => V_new)\n w = pad_with_zeros_to(w, 2 => V_new)\n return TernaryLayer(u, w)\nend\n\nfunction expand_internalspace(layer::TernaryLayer, V_new)\n u, w = layer\n u = pad_with_zeros_to(u, 3 => V_new', 4 => V_new')\n w = pad_with_zeros_to(w, 1 => V_new, 3 => V_new)\n return TernaryLayer(u, w)\nend\n\nfunction randomlayer(\n ::Type{TernaryLayer}, ::Type{T}, Vin, Vout, Vint = Vout; random_disentangler = false\n) where {T}\n w = randomisometry(T, Vint ⊗ Vout ⊗ Vint, Vin)\n u = initialize_disentangler(T, Vout, Vint, random_disentangler)\n return TernaryLayer(u, w)\nend\n\nfunction ascending_fixedpoint(layer::TernaryLayer)\n width = causal_cone_width(layer)\n Vtotal = ⊗(ntuple(n->inputspace(layer), Val(width))...)\n return id(storagetype(operatortype(layer)), Vtotal)\nend\n\nfunction scalingoperator_initialguess(l::TernaryLayer, irreps...)\n width = causal_cone_width(l)\n V = inputspace(l)\n interlayer_space = ⊗(ntuple(n->V, Val(width))...)\n outspace = interlayer_space\n inspace = interlayer_space\n for irrep in irreps\n inspace = inspace ⊗ spacetype(V)(irrep => 1)\n end\n typ = eltype(l)\n t = TensorMap(randn, typ, outspace ← inspace)\n return t\nend\n\nfunction gradient(layer::TernaryLayer, env::TernaryLayer; metric = :euclidean)\n u, w = layer\n uenv, wenv = env\n # The environment is the partial derivative. We need to turn that into a tangent vector\n # of the Stiefel manifold point u or w.\n # The factor of two is from the partial_x + i partial_y derivative of the cost function,\n # and how it depends on both v and v^dagger.\n ugrad = Stiefel.project!(2*uenv, u; metric = metric)\n wgrad = Grassmann.project!(2*wenv, w)\n return TernaryLayer(ugrad, wgrad)\nend\n\nfunction precondition_tangent(layer::TernaryLayer, tan::TernaryLayer, rho)\n u, w = layer\n utan, wtan = tan\n @planar rho_wl[-1; -11] := rho[-1 1; -11 1]\n @planar rho_wr[-1; -11] := rho[1 -1; 1 -11]\n rho_w = (rho_wl + rho_wr) / 2.0\n @planar(\n rho_u[-1 -2; -11 -12] :=\n w'[12; 1 2 -11] * w'[22; -12 3 4] *\n rho[11 21; 12 22] *\n w[1 2 -1; 11] * w[-2 3 4; 21]\n )\n utan_prec = precondition_tangent(utan, rho_u)\n wtan_prec = precondition_tangent(wtan, rho_w)\n return TernaryLayer(utan_prec, wtan_prec)\nend\n\n# # # Invariants\n\nfunction space_invar_intralayer(layer::TernaryLayer)\n u, w = layer\n matching_bonds = (\n (space(u, 3)', space(w, 3)),\n (space(u, 4)', space(w, 1)),\n )\n allmatch = all(pair -> ==(pair...), matching_bonds)\n # Check that the dimensions are such that isometricity can hold.\n allmatch &= all((u, w)) do v\n codom, dom = fuse(codomain(v)), fuse(domain(v))\n infimum(dom, codom) == dom\n end\n return allmatch\nend\n\nfunction space_invar_interlayer(layer::TernaryLayer, next_layer::TernaryLayer)\n u, w = layer.disentangler, layer.isometry\n unext, wnext = next_layer.disentangler, next_layer.isometry\n matching_bonds = (\n (space(w, 4)', space(unext, 1)),\n (space(w, 4)', space(unext, 2)),\n (space(w, 4)', space(wnext, 2)),\n )\n allmatch = all(pair -> ==(pair...), matching_bonds)\n return allmatch\nend\n\n# # # Ascending and descending superoperators\n\n# TODO Fix this to work with anyons.\n#\"\"\"\n#Return the ascending superoperator of the one site in the middle of the isometries in a\n#TernaryMERA, as a TensorMap. Unlike most ascending superoperators, this one is actually\n#affordable to construct as a full tensor.\n#\"\"\"\n#ascending_superop_onesite(m::TernaryMERA) = ascending_superop_onesite(getlayer(m, Inf))\n#\n#function ascending_superop_onesite(layer::TernaryLayer)\n# w = layer.isometry\n# @planar superop[-1 -2; -11 -12] := w'[-11; 1 -1 2] * w[1 -2 2; -12]\n# return superop\n#end\n\nconst TernaryOperator{S} = AbstractTensorMap{S, 2, 2}\nconst ChargedTernaryOperator{S} = AbstractTensorMap{S, 2, 3}\nconst DoubleChargedTernaryOperator{S} = AbstractTensorMap{S, 2, 4}\n\nfunction ascend(\n op::Union{TernaryOperator, ChargedTernaryOperator, DoubleChargedTernaryOperator},\n layer::TernaryLayer\n) where {S1}\n u, w = layer\n l = ascend_left(op, layer)\n r = ascend_right(op, layer)\n m = ascend_mid(op, layer)\n scaled_op = (l+r+m)/3\n return scaled_op\nend\n\nfunction ascend(op::SquareTensorMap{1}, layer::TernaryLayer)\n return ascend(expand_support(op, causal_cone_width(TernaryLayer)), layer)\nend\n\n# TODO Think about how to best remove the code duplication of having the separate methods\n# for ordinary, charged, and double charged operators. Note also that there's a mix of using\n# @tensor and @planar.\nfunction ascend_left(op::ChargedTernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @tensor(\n scaled_op[-100 -200; -300 -400 -1000] :=\n w[51 52 53; -300] * w[54 11 12; -400] *\n u[41 42; 53 54] *\n op[31 32; 52 41 -1000] *\n u'[21 55; 32 42] *\n w'[-100; 51 31 21] * w'[-200; 55 11 12]\n )\n return scaled_op\nend\n\nfunction ascend_right(op::ChargedTernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @tensor(\n scaled_op[-100 -200; -300 -400 -1000] :=\n w[11 12 65; -300] * w[63 61 62; -400] *\n u[51 52; 65 63] *\n op[31 41; 52 61 -1000] *\n u'[64 21; 51 31] *\n w'[-100; 11 12 64] * w'[-200; 21 41 62]\n )\n return scaled_op\nend\n\nfunction ascend_mid(op::ChargedTernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 6X^6\n @tensor(\n scaled_op[-100 -200; -300 -400 -1000] :=\n w[31 32 41; -300] * w[51 21 22; -400] *\n u[1 2; 41 51] *\n op[11 12; 1 2 -1000] *\n u'[42 52; 11 12] *\n w'[-100; 31 32 42] * w'[-200; 52 21 22]\n )\n return scaled_op\nend\n\nfunction ascend_left(op::TernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n scaled_op[-100 -200; -300 -400] :=\n w[51 52 53; -300] * w[54 11 12; -400] *\n u[41 42; 53 54] *\n op[31 32; 52 41] *\n u'[21 55; 32 42] *\n w'[-100; 51 31 21] * w'[-200; 55 11 12]\n )\n return scaled_op\nend\n\nfunction ascend_right(op::TernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n scaled_op[-100 -200; -300 -400] :=\n w[11 12 65; -300] * w[63 61 62; -400] *\n u[51 52; 65 63] *\n op[31 41; 52 61] *\n u'[64 21; 51 31] *\n w'[-100; 11 12 64] * w'[-200; 21 41 62]\n )\n return scaled_op\nend\n\nfunction ascend_mid(op::TernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 6X^6\n @planar(\n scaled_op[-100 -200; -300 -400] :=\n w[31 32 41; -300] * w[51 21 22; -400] *\n u[1 2; 41 51] *\n op[11 12; 1 2] *\n u'[42 52; 11 12] *\n w'[-100; 31 32 42] * w'[-200; 52 21 22]\n )\n return scaled_op\nend\n\nfunction ascend_left(op::DoubleChargedTernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n temp1[-1 -2 -3 -4; -11 -12 -13 -14] :=\n op[31 32; -1 -11 -12 -13] *\n u'[21 -4; 32 -14] *\n w'[-3; -2 31 21]\n )\n temp2 = braid(temp1, (11, 12, 13, 14, 15, 1, 100, 16), (1, 2, 3, 7, 6, 4), (5, 8))\n @planar(\n temp3[-100 -1000 -2000 -200; -300 -400] :=\n w[51 52 53; -300] * w[54 11 12; -400] *\n u[41 42; 53 54] *\n temp2[52 51 -100 -1000 -2000 55; 41 42] *\n w'[-200; 55 11 12]\n )\n scaled_op = braid(temp3, (11, 100, 1, 12, 13, 14), (1, 4), (5, 6, 3, 2))\n return scaled_op\nend\n\nfunction ascend_right(op::DoubleChargedTernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n temp1[-1 -2 -3 -4 -5 -6; -11 -12] :=\n op[31 41; -12 -6 -5 -4] *\n u'[-1 21; -11 31] *\n w'[-2; 21 41 -3]\n )\n temp2 = braid(temp1, (11, 12, 13, 100, 1, 14, 15, 16), (1, 2, 4, 5, 3, 6), (7, 8))\n @planar(\n temp3[-100 -200 -1000 -2000; -300 -400] :=\n w[11 12 65; -300] * w[63 61 62; -400] *\n u[51 52; 65 63] *\n temp2[64 -200 -1000 -2000 62 61; 51 52] *\n w'[-100; 11 12 64]\n )\n scaled_op = braid(temp3, (11, 12, 100, 1, 13, 14), (1, 2), (5, 6, 4, 3))\n return scaled_op\nend\n\nfunction ascend_mid(op::DoubleChargedTernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 6X^6\n @planar(\n temp1[-1 -2; -3 -4 -5 -6] :=\n u[1 2; -3 -4] *\n op[11 12; 1 2 -5 -6] *\n u'[-1 -2; 11 12]\n )\n temp2 = braid(temp1, (11, 12, 13, 14, 1, 100), (1, 6, 5, 2), (3, 4))\n @planar(\n temp3[-100 -1000 -2000 -200; -300 -400] :=\n w[31 32 41; -300] * w[51 21 22; -400] *\n temp2[42 -1000 -2000 52; 41 51] *\n w'[-100; 31 32 42] * w'[-200; 52 21 22]\n )\n scaled_op = braid(temp3, (11, 100, 1, 12, 13, 14), (1, 4), (5, 6, 3, 2))\n return scaled_op\nend\n\nfunction descend_left(rho::TernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n scaled_rho[-100 -200; -300 -400] :=\n u'[61 62; -400 63] *\n w'[51; 52 -300 61] * w'[21; 62 11 12] *\n rho[42 22; 51 21] *\n w[52 -100 41; 42] * w[31 11 12; 22] *\n u[-200 63; 41 31]\n )\n return scaled_rho\nend\n\nfunction descend_right(rho::TernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n scaled_rho[-100 -200; -300 -400] :=\n u'[62 61; 63 -300] *\n w'[21; 11 12 62] * w'[51; 61 -400 52] *\n rho[22 42; 21 51] *\n w[11 12 41; 22] * w[31 -200 52; 42] *\n u[63 -100; 41 31]\n )\n return scaled_rho\nend\n\nfunction descend_mid(rho::TernaryOperator, layer::TernaryLayer)\n u, w = layer\n # Cost: 6X^6\n @planar(\n scaled_rho[-100 -200; -300 -400] :=\n u'[61 62; -300 -400] *\n w'[21; 11 12 61] * w'[41; 62 31 32] *\n rho[22 42; 21 41] *\n w[11 12 51; 22] * w[52 31 32; 42] *\n u[-100 -200; 51 52]\n )\n return scaled_rho\nend\n\nfunction descend(rho::TernaryOperator, layer::TernaryLayer)\n u, w = layer\n l = descend_left(rho, layer)\n r = descend_right(rho, layer)\n m = descend_mid(rho, layer)\n scaled_rho = (l+r+m)/3\n return scaled_rho\nend\n\n# # # Optimization\n\nfunction environment(op, layer::TernaryLayer, rho; vary_disentanglers = true)\n if vary_disentanglers\n env_u = environment_disentangler(op, layer, rho)\n else\n # The adjoint is just for type stability.\n env_u = zero(layer.disentangler')'\n end\n env_w = environment_isometry(op, layer, rho)\n return TernaryLayer(env_u, env_w)\nend\n\nfunction minimize_expectation_ev(\n layer::TernaryLayer, env::TernaryLayer; vary_disentanglers = true\n)\n u = if vary_disentanglers\n projectisometric(env.disentangler; alg = Polar())\n else\n layer.disentangler\n end\n w = projectisometric(env.isometry; alg = Polar())\n return TernaryLayer(u, w)\nend\n\nfunction environment_disentangler(h::TernaryOperator, layer, rho)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n env1[-1 -2; -3 -4] :=\n rho[31 21; 63 22] *\n w[61 51 41; 31] * w[42 11 12; 21] *\n u[52 -2; 41 42] *\n h[62 -1; 51 52] *\n w'[63; 61 62 -3] * w'[22; -4 11 12]\n )\n\n # Cost: 6X^6\n @planar(\n env2[-1 -2; -3 -4] :=\n rho[41 51; 42 52] *\n w[21 22 61; 41] * w[62 31 32; 51] *\n u[11 12; 61 62] *\n h[-1 -2; 11 12] *\n w'[42; 21 22 -3] * w'[52; -4 31 32]\n )\n\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n env3[-1 -2; -3 -4] :=\n rho[21 31; 22 63] *\n w[12 11 42; 21] * w[41 51 61; 31] *\n u[-1 52; 42 41] *\n h[-2 62; 52 51] *\n w'[22; 12 11 -3] * w'[63; -4 62 61]\n )\n\n env = (env1 + env2 + env3)/3\n return env\nend\n\nfunction environment_isometry(h::TernaryOperator, layer, rho)\n u, w = layer\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n env1[-1 -2 -3; -4] :=\n rho[81 84; 82 -4] *\n w[62 41 31; 81] * w[83 -2 -3; 84] *\n u[42 52; 31 83] *\n h[61 51; 41 42] *\n u'[63 -1; 51 52] *\n w'[82; 62 61 63]\n )\n\n # Cost: 6X^6\n @planar(\n env2[-1 -2 -3; -4] :=\n rho[41 62; 42 -4] *\n w[11 12 52; 41] * w[61 -2 -3; 62] *\n u[31 32; 52 61] *\n h[21 22; 31 32] *\n u'[51 -1; 21 22] *\n w'[42; 11 12 51]\n )\n\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n env3[-1 -2 -3; -4] :=\n rho[31 33; 32 -4] *\n w[21 11 51; 31] * w[41 61 -3; 33] *\n u[72 62; 51 41] *\n h[71 -2; 62 61] *\n u'[73 -1; 72 71] *\n w'[32; 21 11 73]\n )\n\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n env4[-1 -2 -3; -4] :=\n rho[33 31; -4 32] *\n w[-1 61 41; 33] * w[51 11 21; 31] *\n u[62 72; 41 51] *\n h[-2 71; 61 62] *\n u'[-3 73; 71 72] *\n w'[32; 73 11 21]\n )\n\n # Cost: 6X^6\n @planar(\n env5[-1 -2 -3; -4] :=\n rho[62 41; -4 42] *\n w[-1 -2 61; 62] * w[52 12 11; 41] *\n u[32 31; 61 52] *\n h[22 21; 32 31] *\n u'[-3 51; 22 21] *\n w'[42; 51 12 11]\n )\n\n # Cost: 2X^8 + 2X^7 + 2X^6\n @planar(\n env6[-1 -2 -3; -4] :=\n rho[84 81; -4 82] *\n w[-1 -2 83; 84] * w[31 41 62; 81] *\n u[52 42; 83 31] *\n h[51 61; 42 41] *\n u'[-3 63; 52 51] *\n w'[82; 63 61 62]\n )\n\n env = (env1 + env2 + env3 + env4 + env5 + env6)/3\n return env\nend\n", "meta": {"hexsha": "e1bc5882c55aa6e3293e617959586140d29bac23", "size": 17614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ternarylayer.jl", "max_stars_repo_name": "mhauru/MERA.jl", "max_stars_repo_head_hexsha": "ace2f92eac2fb782d2f24a3e7f5123b1f104510e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2020-01-24T22:08:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-08T02:00:30.000Z", "max_issues_repo_path": "src/ternarylayer.jl", "max_issues_repo_name": "Jutho/MERAKit.jl", "max_issues_repo_head_hexsha": "d10174eec7322cecd79166085b320f64d0e84355", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ternarylayer.jl", "max_forks_repo_name": "Jutho/MERAKit.jl", "max_forks_repo_head_hexsha": "d10174eec7322cecd79166085b320f64d0e84355", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-14T09:48:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T10:53:19.000Z", "avg_line_length": 29.6033613445, "max_line_length": 92, "alphanum_fraction": 0.5784603157, "num_tokens": 6757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23802685338731044}} {"text": "export iauAtco13\n\"\"\"\nICRS RA,Dec to observed place. The caller supplies UTC, site\ncoordinates, ambient air conditions and observing wavelength.\n\nSOFA models are used for the Earth ephemeris, bias-precession-\nnutation, Earth orientation and refraction.\n\nThis function is part of the International Astronomical Union's\nSOFA (Standards of Fundamental Astronomy) software collection.\n\nStatus: support function.\n\nGiven:\n rc,dc double ICRS right ascension at J2000.0 (radians, Note 1)\n pr double RA proper motion (radians/year; Note 2)\n pd double Dec proper motion (radians/year)\n px double parallax (arcsec)\n rv double radial velocity (km/s, +ve if receding)\n utc1 double UTC as a 2-part...\n utc2 double ...quasi Julian Date (Notes 3-4)\n dut1 double UT1-UTC (seconds, Note 5)\n elong double longitude (radians, east +ve, Note 6)\n phi double latitude (geodetic, radians, Note 6)\n hm double height above ellipsoid (m, geodetic, Notes 6,8)\n xp,yp double polar motion coordinates (radians, Note 7)\n phpa double pressure at the observer (hPa = mB, Note 8)\n tc double ambient temperature at the observer (deg C)\n rh double relative humidity at the observer (range 0-1)\n wl double wavelength (micrometers, Note 9)\n\nReturned:\n aob double* observed azimuth (radians: N=0,E=90)\n zob double* observed zenith distance (radians)\n hob double* observed hour angle (radians)\n dob double* observed declination (radians)\n rob double* observed right ascension (CIO-based, radians)\n eo double* equation of the origins (ERA-GST)\n\nReturned (function value):\n int status: +1 = dubious year (Note 4)\n 0 = OK\n -1 = unacceptable date\n\nNotes:\n\n 1. Star data for an epoch other than J2000.0 (for example from the\n Hipparcos catalog, which has an epoch of J1991.25) will require\n a preliminary call to iauPmsafe before use.\n\n 2. The proper motion in RA is dRA/dt rather than cos(Dec)*dRA/dt.\n\n 3. utc1+utc2 is quasi Julian Date (see Note 2), apportioned in any\n convenient way between the two arguments, for example where utc1\n is the Julian Day Number and utc2 is the fraction of a day.\n\n However, JD cannot unambiguously represent UTC during a leap\n second unless special measures are taken. The convention in the\n present function is that the JD day represents UTC days whether\n the length is 86399, 86400 or 86401 SI seconds.\n\n Applications should use the function iauDtf2d to convert from\n calendar date and time of day into 2-part quasi Julian Date, as\n it implements the leap-second-ambiguity convention just\n described.\n\n 4. The warning status \"dubious year\" flags UTCs that predate the\n introduction of the time scale or that are too far in the\n future to be trusted. See iauDat for further details.\n\n 5. UT1-UTC is tabulated in IERS bulletins. It increases by exactly\n one second at the end of each positive UTC leap second,\n introduced in order to keep UT1-UTC within +/- 0.9s. n.b. This\n practice is under review, and in the future UT1-UTC may grow\n essentially without limit.\n\n 6. The geographical coordinates are with respect to the WGS84\n reference ellipsoid. TAKE CARE WITH THE LONGITUDE SIGN: the\n longitude required by the present function is east-positive\n (i.e. right-handed), in accordance with geographical convention.\n\n 7. The polar motion xp,yp can be obtained from IERS bulletins. The\n values are the coordinates (in radians) of the Celestial\n Intermediate Pole with respect to the International Terrestrial\n Reference System (see IERS Conventions 2003), measured along the\n meridians 0 and 90 deg west respectively. For many\n applications, xp and yp can be set to zero.\n\n 8. If hm, the height above the ellipsoid of the observing station\n in meters, is not known but phpa, the pressure in hPa (=mB),\n is available, an adequate estimate of hm can be obtained from\n the expression\n\n hm = -29.3 * tsl * log ( phpa / 1013.25 );\n\n where tsl is the approximate sea-level air temperature in K\n (See Astrophysical Quantities, C.W.Allen, 3rd edition, section\n 52). Similarly, if the pressure phpa is not known, it can be\n estimated from the height of the observing station, hm, as\n follows:\n\n phpa = 1013.25 * exp ( -hm / ( 29.3 * tsl ) );\n\n Note, however, that the refraction is nearly proportional to\n the pressure and that an accurate phpa value is important for\n precise work.\n\n 9. The argument wl specifies the observing wavelength in\n micrometers. The transition from optical to radio is assumed to\n occur at 100 micrometers (about 3000 GHz).\n\n 10. The accuracy of the result is limited by the corrections for\n refraction, which use a simple A*tan(z) + B*tan^3(z) model.\n Providing the meteorological parameters are known accurately and\n there are no gross local effects, the predicted observed\n coordinates should be within 0.05 arcsec (optical) or 1 arcsec\n (radio) for a zenith distance of less than 70 degrees, better\n than 30 arcsec (optical or radio) at 85 degrees and better\n than 20 arcmin (optical) or 30 arcmin (radio) at the horizon.\n\n Without refraction, the complementary functions iauAtco13 and\n iauAtoc13 are self-consistent to better than 1 microarcsecond\n all over the celestial sphere. With refraction included,\n consistency falls off at high zenith distances, but is still\n better than 0.05 arcsec at 85 degrees.\n\n 11. \"Observed\" Az,ZD means the position that would be seen by a\n perfect geodetically aligned theodolite. (Zenith distance is\n used rather than altitude in order to reflect the fact that no\n allowance is made for depression of the horizon.) This is\n related to the observed HA,Dec via the standard rotation, using\n the geodetic latitude (corrected for polar motion), while the\n observed HA and RA are related simply through the Earth rotation\n angle and the site longitude. \"Observed\" RA,Dec or HA,Dec thus\n means the position that would be seen by a perfect equatorial\n with its polar axis aligned to the Earth's axis of rotation.\n\n 12. It is advisable to take great care with units, as even unlikely\n values of the input parameters are accepted and processed in\n accordance with the models used.\n\nCalled:\n iauApco13 astrometry parameters, ICRS-observed, 2013\n iauAtciq quick ICRS to CIRS\n iauAtioq quick CIRS to observed\n\nThis revision: 2016 February 2\n\nSOFA release 2018-01-30\n\nCopyright (C) 2018 IAU SOFA Board. See notes at end.\n\"\"\"\n# int iauAtco13(double rc, double dc,\n# double pr, double pd, double px, double rv,\n# double utc1, double utc2, double dut1,\n# double elong, double phi, double hm, double xp, double yp,\n# double phpa, double tc, double rh, double wl,\n# double *aob, double *zob, double *hob,\n# double *dob, double *rob, double *eo)\n\nfunction iauAtco13(rc::Real, dc::Real, pr::Real, pd::Real, \n px::Real, rv::Real, utc1::Real, utc2::Real, \n dut1::Real, elong::Real, phi::Real, hm::Real, \n xp::Real, yp::Real, phpa::Real, tc::Real, \n rh::Real, wl::Real)\n\n # Allocate return values\n ref_aob = Ref{Float64}(0.0)\n ref_zob = Ref{Float64}(0.0)\n ref_hob = Ref{Float64}(0.0)\n ref_dob = Ref{Float64}(0.0)\n ref_rob = Ref{Float64}(0.0)\n ref_eo = Ref{Float64}(0.0)\n\n status = ccall((:iauAtco13, libsofa_c), Cint, \n (Cdouble, Cdouble, Cdouble, Cdouble,\n Cdouble, Cdouble, Cdouble, Cdouble,\n Cdouble, Cdouble, Cdouble, Cdouble,\n Cdouble, Cdouble, Cdouble, Cdouble,\n Cdouble, Cdouble, \n Ref{Cdouble}, Ref{Cdouble}, Ref{Cdouble},\n Ref{Cdouble}, Ref{Cdouble}, Ref{Cdouble}), \n convert(Float64, rc), convert(Float64, dc), \n convert(Float64, pr), convert(Float64, pd), \n convert(Float64, px), convert(Float64, rv), \n convert(Float64, utc1), convert(Float64, utc2), \n convert(Float64, dut1), convert(Float64, elong), \n convert(Float64, phi), convert(Float64, hm), \n convert(Float64, xp), convert(Float64, yp), \n convert(Float64, phpa), convert(Float64, tc), \n convert(Float64, rh), convert(Float64, wl),\n ref_aob, ref_zob, ref_hob, ref_dob, ref_rob, ref_eo)\n\n return status, ref_aob[], ref_zob[], ref_hob[], ref_dob[], ref_rob[], ref_eo[]\nend", "meta": {"hexsha": "f228845cf5de8b4472039e4ddf29310ff297cfe0", "size": 8648, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atco13.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_stars_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-12-11T05:19:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T03:10:26.000Z", "max_issues_repo_path": "src/atco13.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_issues_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-02T00:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T06:42:23.000Z", "max_forks_repo_path": "src/atco13.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_forks_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:41:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:41:12.000Z", "avg_line_length": 44.3487179487, "max_line_length": 81, "alphanum_fraction": 0.6862858464, "num_tokens": 2371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.3557748866829643, "lm_q1q2_score": 0.23797079883796723}} {"text": "\n\n## return copy of `a` with midi channel changed to `v`\nfunction channel(v::Int, a::Atom)\n\t@assert 1 <= v <= 16\n\tif in(:cha,fieldnames(typeof(a)))\n\t\ta = deepcopy(a)\n\t\ta.cha = v\n\tend\n\ta\nend\n\n\n## return copy of `a` with duration and offset multiplied by `v`\nfunction dilate(v::Rat, a::Atom)\n\t@assert v > 0\n\tif in(:dur,fieldnames(typeof(a)))\n\t\ta = deepcopy(a)\n\t\ta.ofs *= v\n\t\ta.dur *= v\n\tend\n\ta\nend\n\n\n## return copy of `a` with `v` added to offset\nfunction sshift(v::Rat, a::Atom)\n\ta = deepcopy(a)\n\ta.ofs += v\n\ta\nend\n\n\n## return copy of `a` with velocity mutiplied by `v`\nfunction accel(v::Float64, a::Atom)\n\t@assert 0 < v\n\tif in(:vel,fieldnames(typeof(a)))\n\t\ta = deepcopy(a)\n\t\ta.vel *= v\n\tend\n\ta\nend\n\n\n## return copy of `a` with `v` added to note inteval value\nfunction transl(v::Int, a::Atom)\n\tif in(:itv,fieldnames(typeof(a)))\n\t\ta = deepcopy(a)\n\t\ta.itv += v \n\tend\n\ta\nend\n\n\n## return copy of `a` with `v` added to note octave value\nfunction octave(v::Int, a::Atom)\n\tif in(:ocv,fieldnames(typeof(a)))\n\t\ta = deepcopy(a)\n\t\ta.ocv = v\n\tend\n\ta\nend\n\n\n## return copy of `a` with note scale changed to `v`\nfunction sscale(v::Scales.Scale, a::Atom)\n\tif in(:sca,fieldnames(typeof(a)))\n\t\ta = deepcopy(a)\n\t\ta.sca = v\n\tend\n\ta\nend\n\n\n## tests if atom default fields have valid values\nfunction atomTest(a::Atom)\n\tif in(:cha,fieldnames(typeof(a))) ; @assert 1 <= a.cha <= 16 ; end\n\tif isa(a,Duratom)\n\t\tif in(:dur,fieldnames(typeof(a))) ; @assert 0 < a.dur ; end\n\telse\n\t\tif in(:dur,fieldnames(typeof(a))) ; @assert 0 <= a.dur ; end\n\tend\n\tif in(:ocv,fieldnames(typeof(a))) ; @assert 1 <= a.ocv <= 5 ; end\n\tif in(:vel,fieldnames(typeof(a))) ; @assert 0 < a.vel ; end\n\ta\nend\n\n\n## play a note (on and off midi events)\ntype Note <: Duratom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tcha::Int\t\t\t# channel\n\titv::Int\t\t\t# interval value\n\tocv::Int\t\t\t# octave\n\tvel::Float64\t\t# velocity\n\tsca::Scales.Scale\t# scale\n\n\tNote(ofs,dur,cha,itv,ocv,vel,sca) = atomTest(new(ofs,dur,cha,itv,ocv,vel,sca))\nend\n\n\n## select instrument bank\ntype BankSel <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tcha::Int\t\t\t# channel\n\tbank::Int\t\t\t# bank number\n\t\n\tBankSel(ofs,cha,bank) = ( @assert 0<=bank<=16383 ; atomTest(new(ofs,0//1,cha,bank)) )\nend\n\n\n## select instrument program\ntype ProgSel <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tcha::Int\t\t\t# channel\n\tprog::Int\t\t\t# program\n\n\tProgSel(ofs,cha,prog) = ( @assert 0<=prog<=127 ; atomTest(new(ofs,0//1,cha,prog)) )\nend\n\n\n## set channel volume\ntype VolSet <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tcha::Int\t\t\t# channel\n\tvol::Float64\t\t# volume [0,1]\n\n\tVolSet(ofs,cha,vol) = ( @assert 0<=vol<=1 ; atomTest(new(ofs,0//1,cha,vol)) )\nend\n\n\n## pitch wheel bend\ntype PitchWheel <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tcha::Int\t\t\t# channel\n\tval::Int\t\t\t# value {0..2^14-1}\n\n\tPitchWheel(ofs,cha,val) = ( @assert 0<=val<=16383 ; atomTest(new(ofs,0//1,cha,val)) )\nend\n\n\n## channel aftertouch\ntype ChanAfter <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tcha::Int\t\t\t# channel\n\tval::Int\t\t\t# value {0..127}\n\n\tChanAfter(ofs,cha,val) = ( @assert 0<=val<=127 ; atomTest(new(ofs,0//1,cha,val)) )\nend\n\n\n## channel contol 7bit\ntype Control7 <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tcha::Int\t\t\t# channel\n\tnum::Int\t\t\t# control number {64..127}\n\tval::Int\t\t\t# control value {0..127}\n\n\tControl7(ofs,cha,num,val) = ( @assert 0<=val<=127 && 64<=num<=127 ; atomTest(new(ofs,0//1,cha,num,val)) )\nend\n\n\n## channel contol 14bit\ntype Control14 <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tcha::Int\t\t\t# channel\n\tnum::Int\t\t\t# control number {0..31}\n\tval::Int\t\t\t# control value {0..2^14-1}\n\n\tControl14(ofs,cha,num,val) = ( @assert 0<=val<=16383 && 0<=num<=31 ; atomTest(new(ofs,0//1,cha,num,val)) )\nend\n\n\n## track marker\ntype Marker <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tname::AbstractString\t# marker name\n\n\tMarker(ofs,name) = ( @assert length(name) > 0 ; atomTest(new(ofs,0//1,name)) )\nend\n\n\n## set track time signature\ntype TimeSignature <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tnum::Int\t\t\t# numerator\n\tden::Int\t\t\t# denominator as logarithm of 2\n\tclocks::Int\t\t\t# divisions per quarter note\n\tsub::Int\t\t\t# subdivisions\n\n\tTimeSignature(ofs,num,den,clocks,sub) = ( @assert 1<=num<=32 && 0<=den<=6 && 1<=clocks<64 && 1<=sub<64 ; atomTest(new(ofs,0//1,num,den,clocks,sub)) )\nend\n\n\n## track tempo\ntype Tempo <: Atom\n\tofs::Rat\t\t\t# offset\n\tdur::Rat\t\t\t# duration\n\tbpm::Int\t\t\t# beats per minute\n\n\tTempo(ofs,bpm) = ( @assert 12<=bpm<=1728 ; atomTest(new(ofs,0//1,bpm)) )\nend\n\n\n## functions for writing Atoms to a MidiTrack; uses Jumidi functions; returns a's end time in MidiTrack ticks\n\nfunction toTrack!(mt::MidiTrack, a::Note)\n\tt1 = timm(mt,a.ofs) ; t2 = t1 + tim(mt,a.dur) ; @assert t1 < t2-1\n\tve = ftoi7(a.vel) ; pch::Int = Scales.getPitch(a.sca,a.ocv,a.itv) ; @assert 0 <= pch < 128\n\tnoteOn!(mt,a.ofs,a.cha,pch,ve)\n\tnoteOff!(mt,a.ofs+a.dur,a.cha,pch,ve)\n\tt2\nend\n\ntoTrack!(mt::MidiTrack, a::BankSel) = bankSel!(mt,a.ofs,a.cha,a.bank)\n\ntoTrack!(mt::MidiTrack, a::ProgSel) = progSel!(mt,a.ofs,a.cha,a.prog)\n\ntoTrack!(mt::MidiTrack, a::VolSet) = control14!(mt,a.ofs,a.cha,7,ftoi14(a.vol))\n\ntoTrack!(mt::MidiTrack, a::PitchWheel) = pitchWheel!(mt,a.ofs,a.cha,a.val)\n\ntoTrack!(mt::MidiTrack, a::ChanAfter) = chanAfter!(mt,a.ofs,a.cha,a.val)\n\ntoTrack!(mt::MidiTrack, a::Control7) = control7!(mt,a.ofs,a.cha,a.num,a.val)\n\ntoTrack!(mt::MidiTrack, a::Control14) = control14!(mt,a.ofs,a.cha,a.num,a.val)\n\ntoTrack!(mt::MidiTrack, a::Marker) = trackMarker!(mt,a.ofs,a.name)\n\ntoTrack!(mt::MidiTrack, a::TimeSignature) = timeSigSet!(mt,a.ofs,a.num,a.den,a.clocks,a.sub)\n\ntoTrack!(mt::MidiTrack, a::Tempo) = tempoSet!(mt,a.ofs,a.bpm)\n\n\nfunction Base.isequal(x::Atom, y::Atom)\n\tif typeof(x) != typeof(y) ; return false ; end\n\tfor t in fieldnames(typeof(x))\n\t\tv1 = getfield(x,t)\n\t\tv2 = getfield(y,t)\n\t\tif !isequal(v1,v2) ; return false ; end\n\tend\n\ttrue\nend\n\n\n\n\n\n\n", "meta": {"hexsha": "2a97e1ef2fcd4cad9a8b57ba1114ab7324f2746e", "size": 5897, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atoms.jl", "max_stars_repo_name": "GerhardVisser/SirenSeq.jl", "max_stars_repo_head_hexsha": "a401fe533d7f4687241f1b6d5e06d426beb16672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/atoms.jl", "max_issues_repo_name": "GerhardVisser/SirenSeq.jl", "max_issues_repo_head_hexsha": "a401fe533d7f4687241f1b6d5e06d426beb16672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-10-05T11:33:53.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-11T22:03:58.000Z", "max_forks_repo_path": "src/atoms.jl", "max_forks_repo_name": "GerhardVisser/SirenSeq.jl", "max_forks_repo_head_hexsha": "a401fe533d7f4687241f1b6d5e06d426beb16672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5938697318, "max_line_length": 150, "alphanum_fraction": 0.6428692556, "num_tokens": 2179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.23771550287121515}} {"text": "using JuMP; using NCDatasets; using AxisArrays; using CalliopeJuMP.Util;\n\n\nfunction load_conversion_plus_constraints(model_dict)\n sets = model_dict[\"sets\"]\n constraint_dict = Dict()\n\n constraint_dict[\"balance_conversion_plus_primary_constraint\"] = (\n build_constraint(\n [\"loc_techs_balance_conversion_plus_primary_constraint\",\n \"timesteps\"], \"balance_conversion_plus_primary\", model_dict\n )\n )\n\n constraint_dict[\"carrier_production_max_conversion_plus_constraint\"] = (\n build_constraint(\n [\"loc_techs_carrier_production_max_conversion_plus_constraint\",\n \"timesteps\"], \"carrier_production_max_conversion_plus\", model_dict\n )\n )\n\n if haskey(sets, \"loc_techs_carrier_production_min_conversion_plus_constraint\")\n constraint_dict[\"carrier_production_min_conversion_plus_constraint\"] = (\n build_constraint(\n [\"loc_techs_carrier_production_min_conversion_plus_constraint\",\n \"timesteps\"], \"carrier_production_min_conversion_plus\", model_dict\n )\n )\n end\n\n if haskey(sets, \"loc_techs_cost_var_conversion_plus_constraint\")\n constraint_dict[\"cost_var_conversion_plus_constraint\"] = (\n build_constraint(\n [\"costs\", \"loc_techs_cost_var_conversion_plus_constraint\", \"timesteps\"],\n \"cost_var_conversion_plus\", model_dict\n )\n )\n end\n\n if haskey(sets, \"loc_techs_balance_conversion_plus_in_2_constraint\")\n constraint_dict[\"balance_conversion_plus_in_2_constraint\"] = (\n build_constraint(\n [\"loc_techs_balance_conversion_plus_in_2_constraint\", \"timesteps\"],\n \"balance_conversion_plus_tiers\", model_dict, tier=\"in_2\"\n )\n )\n end\n\n if haskey(sets, \"loc_techs_balance_conversion_plus_in_3_constraint\")\n constraint_dict[\"balance_conversion_plus_in_3_constraint\"] = (\n build_constraint(\n [\"loc_techs_balance_conversion_plus_in_3_constraint\", \"timesteps\"],\n \"balance_conversion_plus_tiers\", model_dict, tier=\"in_3\"\n )\n )\n end\n\n if haskey(sets, \"loc_techs_balance_conversion_plus_out_2_constraint\")\n constraint_dict[\"balance_conversion_plus_out_2_constraint\"] = (\n build_constraint(\n [\"loc_techs_balance_conversion_plus_out_2_constraint\", \"timesteps\"],\n \"balance_conversion_plus_tiers\", model_dict, tier=\"out_2\"\n )\n )\n end\n\n if haskey(sets, \"loc_techs_balance_conversion_plus_out_3_constraint\")\n constraint_dict[\"balance_conversion_plus_out_3_constraint\"] = (\n build_constraint(\n [\"loc_techs_balance_conversion_plus_out_3_constraint\", \"timesteps\"],\n \"balance_conversion_plus_tiers\", model_dict, tier=\"out_3\"\n )\n )\n end\n\n return constraint_dict\nend\n\n\nfunction balance_conversion_plus_primary_constraint_rule(backend_model, set_indices, model_dict)\n \"\"\"\n Balance energy carrier consumption and production for carrier_in and carrier_out\n \"\"\"\n loc_tech, timestep = set_indices\n variables = model_dict[\"variables\"]\n parameters = model_dict[\"parameters\"]\n\n loc_tech_carriers_out = split_comma_list(\n parameters[\"lookup_loc_techs_conversion_plus\"][loc_tech, \"out\"]\n )\n loc_tech_carriers_in = split_comma_list(\n parameters[\"lookup_loc_techs_conversion_plus\"][loc_tech, \"in\"]\n )\n\n energy_eff = get_param(model_dict, \"energy_eff\", [loc_tech], timestep)\n\n carrier_prod = sum(\n variables[\"carrier_prod\"][loc_tech_carrier, timestep] /\n get_param(model_dict, \"carrier_ratios\", [loc_tech_carrier, \"out\"])\n for loc_tech_carrier in loc_tech_carriers_out\n )\n carrier_con = sum(\n variables[\"carrier_con\"][loc_tech_carrier, timestep] *\n get_param(model_dict, \"carrier_ratios\", [loc_tech_carrier, \"in\"])\n for loc_tech_carrier in loc_tech_carriers_in\n )\n\n return @constraint(backend_model, carrier_prod == -1 * carrier_con * energy_eff)\nend\n\n\nfunction carrier_production_max_conversion_plus_constraint_rule(backend_model, set_indices, model_dict)\n \"\"\"\n Set maximum conversion_plus carrier production.\n \"\"\"\n loc_tech, timestep = set_indices\n variables = model_dict[\"variables\"]\n parameters = model_dict[\"parameters\"]\n\n timestep_resolution = model_dict[\"parameters\"][\"timestep_resolution\"][timestep]\n loc_tech_carriers_out = split_comma_list(\n parameters[\"lookup_loc_techs_conversion_plus\"][loc_tech, \"out\"]\n )\n\n carrier_prod = sum(variables[\"carrier_prod\"][loc_tech_carrier, timestep]\n for loc_tech_carrier in loc_tech_carriers_out)\n\n return @constraint(backend_model, carrier_prod <= timestep_resolution * variables[\"energy_cap\"][loc_tech])\nend\n\n\nfunction carrier_production_min_conversion_plus_constraint_rule(backend_model, set_indices, model_dict)\n \"\"\"\n Set minimum conversion_plus carrier production.\n \"\"\"\n loc_tech, timestep = set_indices\n variables = model_dict[\"variables\"]\n parameters = model_dict[\"parameters\"]\n\n timestep_resolution = model_dict[\"parameters\"][\"timestep_resolution\"][timestep]\n min_use = get_param(model_dict, \"energy_cap_min_use\", [loc_tech], timestep)\n\n loc_tech_carriers_out = split_comma_list(\n parameters[\"lookup_loc_techs_conversion_plus\"][loc_tech, \"out\"]\n )\n\n carrier_prod = sum(variables[\"carrier_prod\"][loc_tech_carrier, timestep]\n for loc_tech_carrier in loc_tech_carriers_out)\n\n return @constraint(backend_model, carrier_prod >=\n timestep_resolution * variables[\"energy_cap\"][loc_tech] * min_use\n )\nend\n\n\nfunction cost_var_conversion_plus_constraint_rule(backend_model, set_indices, model_dict)\n \"\"\"\n Add time-varying conversion_plus technology costs\n \"\"\"\n cost, loc_tech, timestep = set_indices\n variables = model_dict[\"variables\"]\n parameters = model_dict[\"parameters\"]\n sets = model_dict[\"sets\"]\n expressions = model_dict[\"expressions\"]\n\n weight = parameters[\"timestep_weights\"][timestep]\n\n loc_tech_carrier = parameters[\"lookup_primary_loc_tech_carriers\"][loc_tech]\n\n var_cost = 0\n\n if loc_tech_carrier in sets[\"loc_tech_carriers_prod\"]\n cost_om_prod = get_param(model_dict, \"cost_om_prod\", [loc_tech, cost], timestep)\n if cost_om_prod > 0\n var_cost += (\n cost_om_prod * weight *\n variables[\"carrier_prod\"][loc_tech_carrier, timestep]\n )\n end\n end\n\n if loc_tech_carrier in sets[\"loc_tech_carriers_con\"]\n cost_om_con = get_param(model_dict, \"cost_om_con\", [loc_tech, cost], timestep)\n if cost_om_con > 0\n var_cost += (\n cost_om_con * weight *\n variables[\"carrier_con\"][loc_tech_carrier, timestep]\n )\n end\n end\n\n expressions[\"cost_var_rhs\"][cost, loc_tech, timestep] = var_cost\n\n return @constraint(backend_model,\n variables[\"cost_var\"][cost, loc_tech, timestep]\n == expressions[\"cost_var_rhs\"][cost, loc_tech, timestep]\n )\nend\n\n\nfunction balance_conversion_plus_tiers_constraint_rule(backend_model, set_indices, model_dict, tier)\n \"\"\"\n Force all carrier_in_2/carrier_in_3 and carrier_out_2/carrier_out_3 to follow\n carrier_in and carrier_out (respectively).\n \"\"\"\n loc_tech, timestep = set_indices\n parameters = model_dict[\"parameters\"]\n primary_tier, decision_variable = get_conversion_plus_io(model_dict, tier)\n\n loc_tech_carriers_1 = split_comma_list(\n parameters[\"lookup_loc_techs_conversion_plus\"][loc_tech, primary_tier]\n )\n loc_tech_carriers_2 = split_comma_list(\n parameters[\"lookup_loc_techs_conversion_plus\"][loc_tech, tier]\n )\n\n c_1 = sum(decision_variable[loc_tech_carrier, timestep]\n / get_param(model_dict, \"carrier_ratios\", [loc_tech_carrier, primary_tier])\n for loc_tech_carrier in loc_tech_carriers_1)\n c_2 = sum(decision_variable[loc_tech_carrier, timestep]\n / get_param(model_dict, \"carrier_ratios\", [loc_tech_carrier, tier])\n for loc_tech_carrier in loc_tech_carriers_2)\n c_min = parameters[\"carrier_ratios_min\"][loc_tech, tier]\n\n return @constraint(backend_model, c_1 * c_min == c_2)\nend", "meta": {"hexsha": "05a231d935d8479dc85fa7f56a7e4ee3bb9ec7e9", "size": 8361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/constraints/conversion_plus.jl", "max_stars_repo_name": "calliope-project/CalliopeJuMP", "max_stars_repo_head_hexsha": "958ae502ffd2a305c8bdef4a9e6e15e0d21466cd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-09-03T19:16:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-12T11:43:51.000Z", "max_issues_repo_path": "src/constraints/conversion_plus.jl", "max_issues_repo_name": "calliope-project/CalliopeJuMP", "max_issues_repo_head_hexsha": "958ae502ffd2a305c8bdef4a9e6e15e0d21466cd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/constraints/conversion_plus.jl", "max_forks_repo_name": "calliope-project/CalliopeJuMP", "max_forks_repo_head_hexsha": "958ae502ffd2a305c8bdef4a9e6e15e0d21466cd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9955752212, "max_line_length": 110, "alphanum_fraction": 0.7021887334, "num_tokens": 1918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23765613952648726}} {"text": "function king_in_check(board::Bitboard, color::String=\"white\")\n if color == \"white\"\n if board.K & board.black_attacks == EMPTY\n return false\n end\n else\n if board.k & board.white_attacks == EMPTY\n return false\n end\n end\n return kingtrace(board, color)\nend\n\n\nfunction square_in_check(board::Bitboard, ui::UInt64, color::String=\"white\")\n if color == \"white\"\n if ui & board.a[1] != EMPTY\n return true\n end\n if ui & board.a[2] != EMPTY\n return true\n end\n if ui & board.a[4] != EMPTY || ui & board.a[3] != EMPTY\n squares, edges = orthogonal_attack(board.taken, ui)\n for rook in board.r\n if rook in edges\n return true\n end\n end\n for queen in board.q\n if queen in edges\n return true\n end\n end\n end\n if ui & board.a[5] != EMPTY || ui & board.a[3] != EMPTY\n squares, edges = cross_attack(board.taken, ui)\n for bishop in board.b\n if bishop in edges\n return true\n end\n end\n for queen in board.q\n if queen in edges\n return true\n end\n end\n end\n return false\n else\n if ui & board.A[1] != EMPTY\n return true\n end\n if ui & board.A[2] != EMPTY\n return true\n end\n if ui & board.A[4] != EMPTY || ui & board.A[3] != EMPTY\n squares, edges = orthogonal_attack(board.taken, ui)\n for rook in board.R\n if rook in edges\n return true\n end\n end\n for queen in board.Q\n if queen in edges\n return true\n end\n end\n end\n if ui & board.A[5] != EMPTY || ui & board.A[3] != EMPTY\n squares, edges = cross_attack(board.taken, ui)\n for bishop in board.B\n if bishop in edges\n return true\n end\n end\n for queen in board.Q\n if queen in edges\n return true\n end\n end\n end\n return false\n end\nend\n\n\nfunction kingtrace(board::Bitboard, color::String=\"white\")\n if color == \"white\"\n return square_in_check(board, board.K, color)\n else\n return square_in_check(board, board.k, color)\n end\nend\n\n\nfunction check_mate(board::Bitboard, color::String=\"white\")\n if color == \"white\"\n king = board.K\n else\n king = board.k\n end\n\n if length(get_current_king_valid(board, color)) != 0\n return false\n else\n if length(get_all_valid_moves(board, color)) == 0\n return true\n else\n return false\n end\n end\nend\n", "meta": {"hexsha": "637f0a92fafeb5b20ee37e40ef8457ef2b28edfd", "size": 2996, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/check.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Bobby.jl-bd34264e-e812-11e8-1ee8-bfb20fea2fb4", "max_stars_repo_head_hexsha": "9814a1d987fcf64e61b1626395e6e221a09b6004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/check.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Bobby.jl-bd34264e-e812-11e8-1ee8-bfb20fea2fb4", "max_issues_repo_head_hexsha": "9814a1d987fcf64e61b1626395e6e221a09b6004", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/check.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Bobby.jl-bd34264e-e812-11e8-1ee8-bfb20fea2fb4", "max_forks_repo_head_hexsha": "9814a1d987fcf64e61b1626395e6e221a09b6004", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2807017544, "max_line_length": 76, "alphanum_fraction": 0.4729639519, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23752217100941891}} {"text": "################################################################################\n# Use the Julia-PerpleX interface to run the same isobaric Perplex calculation\n# with different solution models to compare results\n\n## --- Import some useful packages\n using StatGeochem\n using Plots; gr();\n using Statistics, DelimitedFiles, SpecialFunctions\n\n\n## --- Configure\n\n # Absolute paths to perplex resources\n perplexdir = joinpath(resourcepath,\"perplex-stable\")\n scratchdir = \"./scratch/\" # Location of directory to store output files\n\n # Attempt to install perplex, if not already extant\n if !isfile(joinpath(perplexdir,\"vertex\"))\n # Make sure resourcepath exists\n run(`mkdir -p $resourcepath`)\n\n # Download Perplex v6.8.7 -- known to work with interface used here\n file = download(\"https://storage.googleapis.com/statgeochem/perplex-stable-6.8.7.zip\", joinpath(resourcepath,\"perplex-stable.zip\"))\n\n # # For a more updated perplex version, also try\n # file = download(\"https://petrol.natur.cuni.cz/~ondro/perplex-sources-stable.zip\", joinpath(resourcepath,\"perplex-stable.zip\"))\n\n run(`unzip -u $file -d $resourcepath`) # Extract\n system(\"cd $perplexdir; make\") # Compile\n end\n\n## --- # # # # # # # # # # # # # Initial composition # # # # # # # # # # # # # #\n ## McDonough Pyrolite\n #elements = [ \"SIO2\", \"TIO2\", \"AL2O3\", \"FEO\", \"MNO\", \"MGO\", \"CAO\", \"NA2O\", \"K2O\", \"H2O\", \"CO2\",]\n #composition = [45.1242, 0.2005, 4.4623, 8.0723, 0.1354, 37.9043, 3.5598, 0.3610, 0.0291, 0.1511, 0.0440,]\n\n ## Kelemen (2014) primitive continental basalt. H2O and CO2 are guesses\n #elements = [ \"SIO2\", \"TIO2\", \"AL2O3\", \"FEO\", \"MNO\", \"MGO\", \"CAO\", \"NA2O\", \"K2O\", \"H2O\", \"CO2\",]\n #composition = [50.0956, 0.9564, 15.3224, 8.5103, 0.1659, 9.2520, 9.6912, 2.5472, 0.8588, 2.0000, 0.6000,]\n\n # Kelemen (2014) primitive continental basalt excluding Mn and Ti since most melt models can\"t handle them..\n elements = [ \"SIO2\", \"AL2O3\", \"FEO\", \"MGO\", \"CAO\", \"NA2O\", \"K2O\", \"H2O\", \"CO2\",]\n composition = [50.0956, 15.3224, 8.5103, 9.2520, 9.6912, 2.5472, 0.8588, 2.0000, 0.6000,]\n\n ## Average Archean basalt (EarthChem data)\n #elements = [ \"SIO2\", \"TIO2\", \"AL2O3\", \"FEO\", \"MNO\", \"MGO\", \"CAO\", \"NA2O\", \"K2O\", \"H2O\", \"CO2\",]\n #composition = [49.2054, 0.8401, 12.0551, 11.4018, 0.2198, 12.3997, 9.3113, 1.6549, 0.4630, 1.8935, 0.5555,]\n\n## --- # # # # # # # # # # # Some solution model options # # # # # # # # # # # #\n # Emphasis on phases from Green (2016) -- developed for metabasites, includes what is probably the best (and most expensive) amphibole model. Use with hp11ver.dat\n G_solution_phases = \"Augite(G)\\nOpx(JH)\\ncAmph(G)\\noAmph(DP)\\nO(JH)\\nSp(JH)\\nGrt(JH)\\nfeldspar_B\\nMica(W)\\nBio(TCC)\\nChl(W)\\nCtd(W)\\nCrd(W)\\nSa(WP)\\nSt(W)\\nIlm(WPH)\\nAtg(PN)\\nT\\nB\\nF\\nDo(HP)\\nScap\\nChum\\nNeph(FB)\\n\"\n G_excludes =\"ged\\nfanth\\ngl\\n\"\n\n # Emphasis on phases from White (2014) -- developed for metapelites. Use with hp11ver.dat\n W_solution_phases = \"Omph(HP)\\nOpx(W)\\ncAmph(DP)\\noAmph(DP)\\nO(JH)\\nSp(JH)\\nGt(W)\\nfeldspar_B\\nMica(W)\\nBi(W)\\nChl(W)\\nCtd(W)\\nCrd(W)\\nSa(WP)\\nSt(W) \\nIlm(WPH)\\nAtg(PN)\\nT\\nB\\nF\\nDo(HP)\\nScap\\nChum\\nPu(M)\\n\"\n W_excludes = \"andr\\nts\\nparg\\ngl\\nged\\nfanth\\n\"\n\n # Emphasis on phases from Jennings and Holland (2015) -- developed for mantle melting. Use with hp11ver.dat\n JH_solution_phases = \"Cpx(JH)\\nOpx(JH)\\ncAmph(DP)\\noAmph(DP)\\nO(JH)\\nSp(JH)\\nGrt(JH)\\nfeldspar_B\\nMica(W)\\nBio(TCC)\\nChl(W)\\nCtd(W)\\nCrd(W)\\nSa(WP)\\nSt(W)\\nIlm(WPH)\\nAtg(PN)\\nT\\nB\\nF\\nDo(HP)\\nScap\\nChum\\nNeph(FB)\\n\"\n JH_excludes = \"ts\\nparg\\ngl\\nged\\nfanth\\n\"\n\n # Emphasis on phases from Holland and Powell -- all phases can be used with hp02ver.dat.\n HP_solution_phases = \"Omph(HP)\\nOpx(HP)\\nGlTrTsPg\\nAnth\\nO(HP)\\nSp(HP)\\nGt(HP)\\nfeldspar_B\\nMica(CF)\\nBio(TCC)\\nChl(HP)\\nCtd(HP)\\nSapp(HP)\\nSt(HP)\\nIlHm(A)\\nDo(HP)\\nT\\nB\\nF\\n\"\n HP_excludes = \"\";\n\n## --- Prepare for plotting\n\n h0 = plot(xlabel=\"T (C)\", ylabel=\"Melt percent\")\n\n## --- # # # # # # # # # # melt(G) + G_solution_phases # # # # # # # # # # # # #\n\n # Input parameters\n P = 10000 # bar\n T_range = [500+273.15, 1500+273.15]\n idx = 1\n print(\"\\nmelt(G) + G_solution_phases\\n\")\n @time perplex_configure_isobar(perplexdir, scratchdir, composition, elements, P, T_range, dataset=\"hp11ver.dat\", solution_phases=\"melt(G)\\n\"*G_solution_phases, excludes=G_excludes, index=idx)\n\n # Query the full isobar -- results returned as elementified dictionary\n T_range_inc = [floor(Int,T_range[1])+1, ceil(Int,T_range[2])-1]\n npoints = T_range_inc[2] - T_range_inc[1] + 1\n bulk = perplex_query_system(perplexdir, scratchdir, index=idx) # Get system data for all temperatures. Set include_fluid = \"n\" to get solid+melt only\n modes = perplex_query_modes(perplexdir, scratchdir, index=idx) # || phase modes\n melt = perplex_query_phase(perplexdir, scratchdir, \"melt(G)\", index=idx) # || melt data\n\n # Create dictionary to hold solid composition and fill it using what we know from system and melt\n solid = Dict()\n solid[\"wt_pct\"] = 100 .- melt[\"wt_pct\"]\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n solid[e] = (bulk[e] .- (melt[e] .* melt[\"wt_pct\"]/100)) ./ (solid[\"wt_pct\"]/100)\n end\n\n # Add results to melt % vs temperature figure\n plot!(h0, melt[\"T(K)\"] .- 273.15, melt[\"wt_pct\"], label=\"melt(G) + G\")\n\n # Plot melt composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in melt\", title=\"melt(G) + G_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], melt[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box)\n savefig(h,\"Perplex_MeltTest_G.pdf\")\n\n # Plot solid composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in solid\", title=\"melt(G) + G_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], solid[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box, legend=:topleft)\n savefig(h,\"Perplex_SolidTest_G.pdf\")\n\n## --- # # # # # # # # # # melt(G) + W_solution_phases # # # # # # # # # # # # #\n\n # Input parameters\n P = 10000 # bar\n T_range = [500+273.15, 1500+273.15]\n idx = 2\n print(\"\\nmelt(G) + W_solution_phases\\n\")\n @time perplex_configure_isobar(perplexdir, scratchdir, composition, elements, P, T_range, dataset=\"hp11ver.dat\", solution_phases=\"melt(G)\\n\"*W_solution_phases, excludes=W_excludes, index=idx)\n\n # Query the full isobar -- results returned as elementified dictionary\n T_range_inc = [floor(Int,T_range[1])+1, ceil(Int,T_range[2])-1]\n npoints = T_range_inc[2] - T_range_inc[1] + 1\n bulk = perplex_query_system(perplexdir, scratchdir, index=idx) # Get system data for all temperatures. Set include_fluid = \"n\" to get solid+melt only\n modes = perplex_query_system(perplexdir, scratchdir, index=idx) # || phase modes\n melt = perplex_query_phase(perplexdir, scratchdir, \"melt(G)\", index=idx) # || melt data\n\n # Create dictionary to hold solid composition and fill it using what we know from system and melt\n solid = Dict()\n solid[\"wt_pct\"] = 100 .- melt[\"wt_pct\"]\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n solid[e] = (bulk[e] - (melt[e] .* melt[\"wt_pct\"]/100)) ./ (solid[\"wt_pct\"]/100)\n end\n\n # Add results to melt % vs temperature figure\n plot!(h0, melt[\"T(K)\"] .- 273.15, melt[\"wt_pct\"], label=\"melt(G) + W\")\n\n # Plot melt composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in melt\", title=\"melt(G) + W_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], melt[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box)\n savefig(h,\"Perplex_MeltTest_G_W.pdf\")\n\n # Plot solid composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in solid\", title=\"melt(G) + W_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], solid[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box, legend=:topleft)\n savefig(h,\"Perplex_SolidTest_G_W.pdf\")\n\n\n## --- # # # # # # # # # # melt(G) +JH_solution_phases # # # # # # # # # # # # #\n\n # Input parameters\n P = 10000 # bar\n T_range = [500+273.15, 1500+273.15]\n idx = 3\n print(\"\\nmelt(G) + JH_solution_phases\\n\")\n @time perplex_configure_isobar(perplexdir, scratchdir, composition, elements, P, T_range, dataset=\"hp11ver.dat\", solution_phases=\"melt(G)\\n\"*JH_solution_phases, excludes=JH_excludes, index=idx)\n\n # Query the full isobar -- results returned as elementified dictionary\n T_range_inc = [floor(Int,T_range[1])+1, ceil(Int,T_range[2])-1]\n npoints = T_range_inc[2] - T_range_inc[1] + 1\n bulk = perplex_query_system(perplexdir, scratchdir, index=idx) # Get system data for all temperatures. Set include_fluid = \"n\" to get solid+melt only\n modes = perplex_query_modes(perplexdir, scratchdir, index=idx) # || phase modes\n melt = perplex_query_phase(perplexdir, scratchdir, \"melt(G)\", index=idx) # || melt data\n\n # Create dictionary to hold solid composition and fill it using what we know from system and melt\n solid = Dict()\n solid[\"wt_pct\"] = 100 .- melt[\"wt_pct\"]\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n solid[e] = (bulk[e] - (melt[e] .* melt[\"wt_pct\"]/100)) ./ (solid[\"wt_pct\"]/100)\n end\n\n # Add results to melt % vs temperature figure\n plot!(h0, melt[\"T(K)\"] .- 273.15, melt[\"wt_pct\"], label=\"melt(G) + JH\")\n\n # Plot melt composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in melt\", title=\"melt(G) + JH_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], melt[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box)\n savefig(h,\"Perplex_MeltTest_G_JH.pdf\")\n\n # Plot solid composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in solid\", title=\"melt(G) + JH_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], solid[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box, legend=:topleft)\n savefig(h,\"Perplex_SolidTest_G_JH.pdf\")\n\n## --- # # # # # # # # # # pMELTS(G) +HP_solution_phases # # # # # # # # # # # #\n\n # Input parameters\n P = 10000 # bar\n T_range = [500+273.15, 1500+273.15]\n idx = 4\n print(\"\\npMELTS(G) + JH_solution_phases\\n\")\n @time perplex_configure_isobar(perplexdir, scratchdir, composition, elements, P, T_range, dataset=\"hp02ver.dat\", solution_phases=\"pMELTS(G)\\n\"*JH_solution_phases, excludes=JH_excludes, index=idx)\n\n # Query the full isobar -- results returned as elementified dictionary\n T_range_inc = [floor(Int,T_range[1])+1, ceil(Int,T_range[2])-1]\n npoints = T_range_inc[2] - T_range_inc[1] + 1\n bulk = perplex_query_system(perplexdir, scratchdir, index=idx) # Get system data for all temperatures. Set include_fluid = \"n\" to get solid+melt only\n modes = perplex_query_modes(perplexdir, scratchdir, index=idx) # || phase modes\n melt = perplex_query_phase(perplexdir, scratchdir, \"pMELTS(G)\", index=idx) # || melt data\n\n # Create dictionary to hold solid composition and fill it using what we know from system and melt\n solid = Dict()\n solid[\"wt_pct\"] = 100 .- melt[\"wt_pct\"]\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n solid[e] = (bulk[e] - (melt[e] .* melt[\"wt_pct\"]/100)) ./ (solid[\"wt_pct\"]/100)\n end\n\n # Add results to melt % vs temperature figure\n plot!(h0, melt[\"T(K)\"] .- 273.15, melt[\"wt_pct\"], label=\"pMELTS(G) + JH\")\n\n # Plot melt composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in melt\", title=\"pMELTS(G) + JH_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], melt[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box)\n savefig(h,\"Perplex_MeltTest_pMELTS_JH.pdf\")\n\n # Plot solid composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in solid\", title=\"pMELTS(G) + JH_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], solid[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box, legend=:topleft)\n savefig(h,\"Perplex_SolidTest_pMELTS_JH.pdf\")\n\n## --- # # # # # # # # # # # melt(W) + W_solution_phases # # # # # # # # # # # #\n\n # Input parameters\n P = 10000 # bar\n T_range = [500+273.15, 1500+273.15]\n idx = 5\n print(\"\\nmelt(W) + W_solution_phases\\n\")\n @time perplex_configure_isobar(perplexdir, scratchdir, composition, elements, P, T_range, dataset=\"hp11ver.dat\", solution_phases=\"melt(W)\\n\"*W_solution_phases, excludes=W_excludes, index=idx)\n\n # Query the full isobar -- results returned as elementified dictionary\n T_range_inc = [floor(Int,T_range[1])+1, ceil(Int,T_range[2])-1]\n npoints = T_range_inc[2] - T_range_inc[1] + 1\n bulk = perplex_query_system(perplexdir, scratchdir, index=idx) # Get system data for all temperatures. Set include_fluid = \"n\" to get solid+melt only\n modes = perplex_query_modes(perplexdir, scratchdir, index=idx) # || phase modes\n melt = perplex_query_phase(perplexdir, scratchdir, \"melt(W)\", index=idx) # || melt data\n\n # Create dictionary to hold solid composition and fill it using what we know from system and melt\n solid = Dict()\n solid[\"wt_pct\"] = 100 .- melt[\"wt_pct\"]\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n solid[e] = (bulk[e] - (melt[e] .* melt[\"wt_pct\"]/100)) ./ (solid[\"wt_pct\"]/100)\n end\n\n # Add results to melt % vs temperature figure\n plot!(h0, melt[\"T(K)\"] .- 273.15, melt[\"wt_pct\"], label=\"melt(W) + W\")\n\n # Plot melt composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in melt\", title=\"melt(W) + W_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], melt[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box)\n savefig(h,\"Perplex_MeltTest_W.pdf\")\n\n # Plot solid composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in solid\", title=\"melt(W) + W_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], solid[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box, legend=:topleft)\n savefig(h,\"Perplex_SolidTest_W.pdf\")\n\n## --- # # # # # # # # # # melt(W) + G_solution_phases # # # # # # # # # # # # #\n\n # Input parameters\n P = 10000 # bar\n T_range = [500+273.15, 1500+273.15]\n idx = 6\n print(\"\\nmelt(W) + G_solution_phases\\n\")\n @time perplex_configure_isobar(perplexdir, scratchdir, composition, elements, P, T_range, dataset=\"hp11ver.dat\", solution_phases=\"melt(W)\\n\"*G_solution_phases, excludes=G_excludes, index=idx)\n\n # Query the full isobar -- results returned as elementified dictionary\n T_range_inc = [floor(Int,T_range[1])+1, ceil(Int,T_range[2])-1]\n npoints = T_range_inc[2] - T_range_inc[1] + 1\n bulk = perplex_query_system(perplexdir, scratchdir, index=idx) # Get system data for all temperatures. Set include_fluid = \"n\" to get solid+melt only\n modes = perplex_query_modes(perplexdir, scratchdir, index=idx) # || phase modes\n melt = perplex_query_phase(perplexdir, scratchdir, \"melt(W)\", index=idx) # || melt data\n\n # Create dictionary to hold solid composition and fill it using what we know from system and melt\n solid = Dict()\n solid[\"wt_pct\"] = 100 .- melt[\"wt_pct\"]\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n solid[e] = (bulk[e] - (melt[e] .* melt[\"wt_pct\"]/100)) ./ (solid[\"wt_pct\"]/100)\n end\n\n # Add results to melt % vs temperature figure\n plot!(h0, melt[\"T(K)\"] .- 273.15, melt[\"wt_pct\"], label=\"melt(W) + G\")\n\n # Plot melt composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in melt\", title=\"melt(W) + G_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], melt[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box)\n savefig(h,\"Perplex_MeltTest_W_G.pdf\")\n\n # Plot solid composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in solid\", title=\"melt(W) + G_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], solid[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box, legend=:topleft)\n savefig(h,\"Perplex_SolidTest_W_G.pdf\")\n\n## --- # # # # # # # # # # # melt(W) +JH_solution_phases # # # # # # # # # # # #\n\n # Input parameters\n P = 10000 # bar\n T_range = [500+273.15, 1500+273.15]\n idx = 7\n print(\"\\nmelt(W) + JH_solution_phases\\n\")\n @time perplex_configure_isobar(perplexdir, scratchdir, composition, elements, P, T_range, dataset=\"hp11ver.dat\", solution_phases=\"melt(W)\\n\"*JH_solution_phases, excludes=JH_excludes, index=idx)\n\n # Query the full isobar -- results returned as elementified dictionary\n T_range_inc = [floor(Int,T_range[1])+1, ceil(Int,T_range[2])-1]\n npoints = T_range_inc[2] - T_range_inc[1] + 1\n bulk = perplex_query_system(perplexdir, scratchdir, index=idx) # Get system data for all temperatures. Set include_fluid = \"n\" to get solid+melt only\n modes = perplex_query_modes(perplexdir, scratchdir, index=idx) # || phase modes\n melt = perplex_query_phase(perplexdir, scratchdir, \"melt(W)\", index=idx) # || melt data\n\n # Create dictionary to hold solid composition and fill it using what we know from system and melt\n solid = Dict()\n solid[\"wt_pct\"] = 100 .- melt[\"wt_pct\"]\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n solid[e] = (bulk[e] - (melt[e] .* melt[\"wt_pct\"]/100)) ./ (solid[\"wt_pct\"]/100)\n end\n\n # Add results to melt % vs temperature figure\n plot!(h0, melt[\"T(K)\"] .- 273.15, melt[\"wt_pct\"], label=\"melt(W) + JH\")\n\n # Plot melt composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in melt\", title=\"melt(W) + JH_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], melt[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box)\n savefig(h,\"Perplex_MeltTest_W_JH.pdf\")\n\n # Plot solid composition as a function of melt percent\n h = plot(xlabel=\"Percent melt\", ylabel=\"Wt. % in solid\", title=\"melt(W) + JH_solution_phases, $P bar\")\n for e in [\"SIO2\",\"AL2O3\",\"FEO\",\"MGO\",\"CAO\",\"NA2O\",\"K2O\"]\n plot!(h, melt[\"wt_pct\"], solid[e], label=e)\n end\n plot!(h,fg_color_legend=:white, framestyle=:box, legend=:topleft)\n savefig(h,\"Perplex_SolidTest_W_JH.pdf\")\n\n## --- Format melt comparison\n\n plot!(h0,fg_color_legend=:white,legend=:topleft)\n display(h0)\n savefig(h0,\"Perplex_T-F_comparison.pdf\")\n\n## --- End of File\n", "meta": {"hexsha": "bb901e1a3c4ec35c914a2bc2dc12296d315feae4", "size": 19643, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/PerplexSolutionModelComparison.jl", "max_stars_repo_name": "brenhinkeller/StatGeochem.jl", "max_stars_repo_head_hexsha": "43c6ee9d6ffd49c2aac78083c3ae4640663e23d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-11-08T20:09:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T01:19:41.000Z", "max_issues_repo_path": "examples/PerplexSolutionModelComparison.jl", "max_issues_repo_name": "brenhinkeller/StatGeochem.jl", "max_issues_repo_head_hexsha": "43c6ee9d6ffd49c2aac78083c3ae4640663e23d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-05-04T05:34:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T06:23:42.000Z", "max_forks_repo_path": "examples/PerplexSolutionModelComparison.jl", "max_forks_repo_name": "brenhinkeller/StatGeochem.jl", "max_forks_repo_head_hexsha": "43c6ee9d6ffd49c2aac78083c3ae4640663e23d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-10-03T17:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T20:57:44.000Z", "avg_line_length": 52.8037634409, "max_line_length": 219, "alphanum_fraction": 0.6343735682, "num_tokens": 6606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23752217100941891}} {"text": "function nextline(pf::IO, c::Char)\n eof(pf) && return \"-1\"\n s = \"\\0\"\n while s[1] != c\n eof(pf) && return \"-1\"\n s = chomp(readline(pf))\n end\n return s\nend\n\n@doc \"\"\"\n H, R = uwpf(pf[, v])\n\nRead UW-format seismic pick file `pf` into SeisHdr object `H`, with seismic\nsource description (focal mechanism) returned in SeisSrc object `R`.\n\n uwpf!(W, pf[, v::Integer=KW.v])\n\nRead UW-format seismic pick info from pickfile `f` into SeisEvent object `W`.\nOverwrites W.source and W.hdr with pickfile information. Keyword `v` controls\nverbosity.\n\n!!! caution\n\n Reader has no safety check to guarantee that `pf` is from the same event.\n\n\"\"\" uwpf\nfunction uwpf(pickfile::String; v::Integer=KW.v)\n # Initialize variables that will fill SeisHdr structure\n D = Dict{String, Any}()\n MAG = -5.0f0\n ID = \"\"\n OT = zero(Float64)\n loc = zeros(Float64, 12)\n sig = \"\"\n locflags = Array{Char, 1}(undef,8)\n R = SeisSrc()\n fill!(locflags, '0')\n\n # Read begins\n pf = open(pickfile, \"r\")\n\n # ========================================================================\n # Acard line\n A = nextline(pf, 'A')\n (v > 1) && println(stdout, A)\n c = 0\n if length(A) == 75 || length(A) == 12\n y = zero(Int8)\n c = 1900\n else\n y = Int8(2)\n end\n D[\"type\"] = getindex(A, 2)\n\n # ACard indices\n #\n # Crosson's notes:\n # Type, Year, Month, Day, Hour, Min, Sec, LatDeg, NS, Latmin*100, LongDeg, EW, Lonmin*100, Depth, Fix, Magnitude, Numsta, numphase, Gap, Mindelta, RMS, ERR, Q1, Q2, Velmodel\n # ATYYYYMMDDHHMM SS.SS LLNMMMM LLLWMMMM DD.DD* M.M NN/0NN GGG DD R.RR EE.EQQ VV\n # AF200206291436 4.79 45N2009 121W4118 6.20* 4.5 41/041 37 9 0.27 0.1BB O0\n #\n # Sec,Lat,Lon,Dep,Fix,Mag,Nst,Nph,Gap, d0,RMS,ERR, Q, mod\n si = Int8[13, 19, 27, 36, 42, 43, 47, 51, 54, 58, 61, 66, 71, 74] .+ y\n ei = Int8[18, 26, 35, 41, 42, 46, 49, 53, 57, 60, 65, 70, 72, 75] .+ y\n L = length(si)\n\n # Parse reset of Acard line\n ah = Array{String,1}(undef, L)\n for i = 1:L\n setindex!(ah, getindex(A, getindex(si, i):getindex(ei, i)), i)\n end\n v > 2 && println(\"ah = \", ah)\n\n # origin time, event depth, and magnitude\n OT = d2u(DateTime(string(parse(Int64, A[3:4+y]) + c)*A[5+y:12+y],\n \"yyyymmddHHMM\")) + parse(Float64, getindex(ah, 1))\n evla = getindex(ah, 2)\n evlo = getindex(ah, 3)\n loc[3] = parse(Float64, getindex(ah, 4)) # depth :dep\n locflags[3] = (getindex(ah, 5) == \"F\") ? '1' : '0'\n MAG = parse(Float32, getindex(ah, 6))\n nst = parse(Int64, getindex(ah, 7))\n D[\"numpha\"] = parse(Int64, getindex(ah, 8))\n loc[10] = parse(Float64, getindex(ah, 9)) # gap :gap\n loc[11] = parse(Float64, getindex(ah, 10)) # min distance :dmin\n loc[9] = parse(Float64, getindex(ah, 11)) # rms pick error :rms\n loc[8] = parse(Float64, getindex(ah, 12)) # standard error :se\n D[\"qual\"] = getindex(ah, 13)\n D[\"vmod\"] = getindex(ah, 14)\n\n # Convert lat and lon to decimal degrees\n loc[1] = (parse(Float64, evla[1:3]) +\n parse(Float64, evla[5:6])/60.0 +\n parse(Float64, evla[7:8])/6000.0) * (evla[4] == 'S' ? -1.0 : 1.0)\n loc[2] = (parse(Float64, evlo[1:4]) +\n parse(Float64, evlo[6:7])/60.0 +\n parse(Float64, evlo[8:9])/6000.0) * (evlo[5] == 'W' ? -1.0 : 1.0)\n\n # ========================================================================\n # Error line\n seekstart(pf)\n eline = nextline(pf, 'E')\n if eline != \"-1\"\n # E O0 0.27 0.022 0.281 0.281 141.30 38 Z 0.05 0.05 0.11 0.01 4.50 0.000.03\n # Effectively: 10x MeanRMS SDabout0 SDaboutMean SSWRES NDFR FIXXYZT SDx SDy SDz SDt Mag 5x MeanUncert\n # 10x f6.3 f6.3 f6.3 f8.2 i4 a4 f5.2 f5.2 f5.2 f5.2 f5.2 5x f4.2\n eline_keys = String[\"MeanRMS\", \"SDabout0\", \"SDaboutMean\", \"SSWRES\", \"NDFR\", \"FIXXYZT\", \"SDx\", \"SDy\", \"SDz\", \"SDt\", \"Mag\", \"MeanUncert\"]\n si = Int8[ 11, 17, 23, 29, 37, 42, 46, 51, 56, 61, 66, 76]\n ei = Int8[ 16, 22, 28, 36, 40, 45, 50, 55, 60, 65, 70, 79]\n j = 0\n\n while j < length(eline_keys)\n j = j + 1\n a = getindex(si, j)\n b = getindex(ei, j)\n s = getindex(eline, a:b)\n if j == 6\n (s[1] == 'X') && (locflags[1] = '1')\n (s[2] == 'Y') && (locflags[2] = '1')\n (s[3] == 'Z') && (locflags[3] = '1')\n (s[4] == 'T') && (locflags[4] = '1')\n elseif j == 7\n loc[4] = parse(Float64, s)\n elseif j == 8\n loc[5] = parse(Float64, s)\n elseif j == 9\n loc[6] = parse(Float64, s)\n elseif j == 10\n if s != \"*****\"\n loc[7] = parse(Float64, s)\n end\n elseif !isempty(s)\n k = getindex(eline_keys, j)\n D[k] = parse(j == 5 ? Int32 : Float32, s)\n end\n end\n sig = \"1σ\"\n end\n LOC = EQLoc(loc..., nst, parse(UInt8, join(locflags), base=2), \"\", \"hypocenter\", \"\", \"SPONG\")\n\n # ========================================================================\n # Focal mechanism line(s)\n #= Note: planes F and G azimuth and an incidence are NOT in N°E. They're\n measured clockwise from the (N°E) azimuth of the dip vector, because R.\n Crosson wanted to be a unique special snowflake.\n\n The axes copied to Hdr.axes are therefore P, T, with the last field of\n the 3Tuple set to 0.0.\n =#\n seekstart(pf)\n mline = nextline(pf,'M')\n m = 0\n PAX = Array{Float64,2}(undef, 2 ,2)\n NP = Array{Float64,2}(undef, 2, 2)\n if mline != \"-1\"\n # Convert first mechanism line\n M = split(mline)\n\n setindex!(NP, parse(Float64, getindex(M, 3)), 1)\n setindex!(NP, parse(Float64, getindex(M, 4)), 2)\n setindex!(NP, parse(Float64, getindex(M, 6)), 3)\n setindex!(NP, parse(Float64, getindex(M, 7)), 4)\n\n # Order here is T, P\n setindex!(PAX, parse(Float64, getindex(M, 18)), 1)\n setindex!(PAX, parse(Float64, getindex(M, 19)), 2)\n setindex!(PAX, parse(Float64, getindex(M, 15)), 3)\n setindex!(PAX, parse(Float64, getindex(M, 16)), 4)\n\n setfield!(R, :pax, PAX)\n setfield!(R, :planes, NP)\n pf_str = abspath(pickfile)\n setfield!(R, :src, pf_str)\n note!(R, \"+source ¦ \" * pf_str)\n\n # Add rest to a dictionary\n mech_lines = Array{String, 1}(undef, 0)\n mline = nextline(pf,'M')\n while mline != \"-1\"\n m += 1\n push!(mech_lines, mline)\n mline = nextline(pf,'M')\n end\n R.gap = getindex(loc, 10)\n if !isempty(mech_lines)\n R.misc[\"mech_lines\"] = mech_lines\n end\n v>0 && println(stdout, \"Processed \", m, \" focal mechanism lines.\")\n note!(R, string(\"planes are arranged [θ₁ θ₂; ϕ₁ ϕ₂] but θ₁, θ₂ are NOT oriented N°E. \",\n \"They're measured clockwise from the N°E azimuth of the dip vector.\"))\n note!(R, string(\"gap is copied from the A-card line; this likely \",\n \"under-represents the true focal mechanism gap.\"))\n end\n\n # ========================================================================\n # Comment lines\n seekstart(pf)\n m = 0\n cline = nextline(pf,'C')\n if cline != \"-1\"\n D[\"comment\"] = Array{String, 1}(undef, 0)\n while cline != \"-1\"\n m = m + 1\n L = lastindex(cline)\n if occursin(\"NEAR\", cline)\n D[\"loc_name\"] = getindex(cline, 8:L)\n elseif occursin(\"EVENT ID\", cline)\n ID = getindex(cline, 13:L)\n elseif occursin(\"LOCATED BY\", cline)\n setfield!(LOC, :src, getfield(LOC, :src) * \"; \" * getindex(cline, 3:L))\n else\n push!(D[\"comment\"], getindex(cline, 3:L))\n end\n cline = nextline(pf,'C')\n end\n v > 0 && println(stdout, \"Processed \", m, \" comment lines.\")\n end\n\n # ========================================================================\n # Done reading\n close(pf)\n H = SeisHdr()\n src_str = abspath(pickfile)\n setfield!(H, :loc, LOC)\n setfield!(H, :src, src_str)\n note!(H, \"+source ¦ \" * src_str)\n if MAG != -5.0f0\n setfield!(H, :mag, EQMag(val = MAG, scale = \"Md\", src = \"SPONG\"))\n end\n if OT != zero(Float64)\n setfield!(H, :ot, u2d(OT))\n end\n if isempty(ID) == false\n setfield!(H, :id, string(ID))\n setfield!(R, :eid, string(ID))\n end\n if isempty(D) == false\n setfield!(H, :misc, D)\n end\n\n return H, R\nend\n\n@doc (@doc uwpf)\nfunction uwpf!(S::SeisEvent, pickfile::String; v::Integer=KW.v)\n (H, R) = uwpf(pickfile, v=v)\n\n N = getfield(getfield(S, :data), :n)\n ID = getfield(getfield(S, :data), :id)\n PHA = getfield(getfield(S, :data), :pha)\n cha = Array{String,1}(undef, N)\n for i = 1:N\n id = split(getindex(ID, i), \".\", keepempty=true)\n setindex!(cha, string(\".\", getindex(id, 2), \".\", getindex(id, 4)), i)\n end\n v > 2 && println(\"cha = \", cha)\n\n # Pick lines (requires reopening/rereading file)\n m = 0\n ndur = 0\n npol = 0\n pf = open(pickfile, \"r\")\n pick_line = nextline(pf, '.')\n\n while pick_line != \"-1\"\n v>1 && println(stdout, \"pick_line = \", pick_line)\n m += 1\n pdat = split(pick_line, \"(\")\n pick_cha = getindex(pdat, 1)\n pcat = PhaseCat()\n dur = 0.0\n\n # Parse picks\n for j = 2:length(pdat)\n pha = split(getindex(pdat, j))\n if getindex(pha, 1) == \"P\"\n v > 2 && println(pha)\n pol = getindex(pha, 3)[1]\n if pol != '_'\n npol = npol + 1\n end\n pcat[getindex(pha,2)] = SeisPha(\n 0.0, # amp\n 0.0, # d\n 0.0, # inc\n parse(Float64, pha[7][1:end-1]), # res\n 0.0, # rp\n 0.0, # ta\n parse(Float64, pha[4]), # tt --> relative to file begin; fixed below\n parse(Float64, pha[6]), # unc\n pol, # polarity\n pha[5][1] # quality\n )\n elseif getindex(pha, 1) == \"D\"\n dur = parse(Float64, getindex(pha,2)[1:end-1])\n end\n end\n\n # Assign to the correct channel\n for i = 1:N\n if startswith(pick_cha, getindex(cha, i))\n for p in keys(pcat)\n PHA[i][p] = pcat[p]\n end\n if dur > 0.0\n ndur = ndur + 1\n S.data.misc[i][\"dur\"] = dur\n end\n break\n end\n end\n pick_line = nextline(pf, '.')\n end\n v>0 && println(stdout, \"Processed \", m, \" pick lines.\")\n close(pf)\n\n # Set ndur, npol\n setfield!(getfield(H, :mag), :nst, ndur)\n setfield!(R, :npol, npol)\n\n # Place hdr, source\n setfield!(S, :hdr, H)\n setfield!(S, :source, R)\n\n # Done\n return S\nend\n", "meta": {"hexsha": "dce26843da12811e552fc6a6d11567834295d535", "size": 10794, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Submodules/UW/uwpf.jl", "max_stars_repo_name": "jpjones76/SeisIO.jl", "max_stars_repo_head_hexsha": "ddbb529b9c9b158df83f1a438facae08fc44d680", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2016-05-28T07:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T04:28:21.000Z", "max_issues_repo_path": "src/Submodules/UW/uwpf.jl", "max_issues_repo_name": "tclements/SeisIO.jl", "max_issues_repo_head_hexsha": "2bc58ef028f0b811b02340239c940fdec1288339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 79, "max_issues_repo_issues_event_min_datetime": "2018-08-11T08:32:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T23:46:41.000Z", "max_forks_repo_path": "src/Submodules/UW/uwpf.jl", "max_forks_repo_name": "tclements/SeisIO.jl", "max_forks_repo_head_hexsha": "2bc58ef028f0b811b02340239c940fdec1288339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-05-08T00:52:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:57:21.000Z", "avg_line_length": 32.8085106383, "max_line_length": 180, "alphanum_fraction": 0.5069483046, "num_tokens": 3830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.23749227824054397}} {"text": "const pyjlnumbertype = pynew()\nconst pyjlcomplextype = pynew()\nconst pyjlrealtype = pynew()\nconst pyjlrationaltype = pynew()\nconst pyjlintegertype = pynew()\n\nstruct pyjlnumber_op{OP}\n op :: OP\nend\n(op::pyjlnumber_op)(self) = Py(op.op(self))\nfunction (op::pyjlnumber_op)(self, other_::Py)\n if pyisjl(other_)\n other = pyjlvalue(other_)\n else\n other = @pyconvert(Number, other_, return Py(pybuiltins.NotImplemented))\n end\n Py(op.op(self, other))\nend\nfunction (op::pyjlnumber_op)(self, other_::Py, other2_::Py)\n if pyisjl(other_)\n other = pyjlvalue(other_)\n else\n other = @pyconvert(Number, other_, return Py(pybuiltins.NotImplemented))\n end\n if pyisjl(other2_)\n other2 = pyjlvalue(other2_)\n else\n other2 = @pyconvert(Number, other2_, return Py(pybuiltins.NotImplemented))\n end\n Py(op.op(self, other, other2))\nend\npyjl_handle_error_type(op::pyjlnumber_op, self, exc) = exc isa MethodError && exc.f === op.op ? pybuiltins.TypeError : PyNULL\n\nstruct pyjlnumber_rev_op{OP}\n op :: OP\nend\nfunction (op::pyjlnumber_rev_op)(self, other_::Py)\n if pyisjl(other_)\n other = pyjlvalue(other_)\n else\n other = @pyconvert(Number, other_, return Py(pybuiltins.NotImplemented))\n end\n Py(op.op(other, self))\nend\nfunction (op::pyjlnumber_rev_op)(self, other_::Py, other2_::Py)\n if pyisjl(other_)\n other = pyjlvalue(other_)\n else\n other = @pyconvert(Number, other_, return Py(pybuiltins.NotImplemented))\n end\n if pyisjl(other2_)\n other2 = pyjlvalue(other2_)\n else\n other2 = @pyconvert(Number, other2_, return Py(pybuiltins.NotImplemented))\n end\n Py(op.op(other, self, other2))\nend\npyjl_handle_error_type(op::pyjlnumber_rev_op, self, exc) = exc isa MethodError && exc.f === op.op ? pybuiltins.TypeError : PyNULL\n\npyjlreal_trunc(self::Real) = Py(trunc(Integer, self))\npyjl_handle_error_type(::typeof(pyjlreal_trunc), self, exc::MethodError) = exc.f === trunc ? pybuiltins.TypeError : PyNULL\n\npyjlreal_floor(self::Real) = Py(floor(Integer, self))\npyjl_handle_error_type(::typeof(pyjlreal_floor), self, exc::MethodError) = exc.f === floor ? pybuiltins.TypeError : PyNULL\n\npyjlreal_ceil(self::Real) = Py(ceil(Integer, self))\npyjl_handle_error_type(::typeof(pyjlreal_ceil), self, exc::MethodError) = exc.f === ceil ? pybuiltins.TypeError : PyNULL\n\nfunction pyjlreal_round(self::Real, ndigits_::Py)\n ndigits = pyconvertarg(Union{Int,Nothing}, ndigits_, \"ndigits\")\n if ndigits === nothing\n Py(round(Integer, self))\n else\n Py(round(self; digits = ndigits))\n end\nend\npyjl_handle_error_type(::typeof(pyjlreal_round), self, exc::MethodError) = exc.f === round ? pybuiltins.TypeError : PyNULL\n\nfunction init_jlwrap_number()\n jl = pyjuliacallmodule\n filename = \"$(@__FILE__):$(1+@__LINE__)\"\n pybuiltins.exec(pybuiltins.compile(\"\"\"\n class NumberValue(AnyValue):\n __slots__ = ()\n __module__ = \"juliacall\"\n def __bool__(self):\n return not self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(iszero))))\n def __add__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(+))), other)\n def __sub__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(-))), other)\n def __mul__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(*))), other)\n def __truediv__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(/))), other)\n def __floordiv__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(÷))), other)\n def __mod__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(%))), other)\n def __pow__(self, other, modulo=None):\n if modulo is None:\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(^))), other)\n else:\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(powermod))), other, modulo)\n def __lshift__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(<<))), other)\n def __rshift__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(>>))), other)\n def __and__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(&))), other)\n def __xor__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(⊻))), other)\n def __or__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(|))), other)\n def __radd__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(+))), other)\n def __rsub__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(-))), other)\n def __rmul__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(*))), other)\n def __rtruediv__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(/))), other)\n def __rfloordiv__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(÷))), other)\n def __rmod__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(%))), other)\n def __rpow__(self, other, modulo=None):\n if modulo is None:\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(^))), other)\n else:\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(powermod))), other, modulo)\n def __rlshift__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(<<))), other)\n def __rrshift__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(>>))), other)\n def __rand__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(&))), other)\n def __rxor__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(⊻))), other)\n def __ror__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_rev_op(|))), other)\n def __eq__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(==))), other)\n def __ne__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(!=))), other)\n def __le__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(≤))), other)\n def __lt__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(<))), other)\n def __ge__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(≥))), other)\n def __gt__(self, other):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(>))), other)\n class ComplexValue(NumberValue):\n __slots__ = ()\n __module__ = \"juliacall\"\n def __complex__(self):\n return self._jl_callmethod($(pyjl_methodnum(pycomplex)))\n @property\n def real(self):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(real))))\n @property\n def imag(self):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(imag))))\n def conjugate(self):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(conj))))\n class RealValue(ComplexValue):\n __slots__ = ()\n __module__ = \"juliacall\"\n def __float__(self):\n return self._jl_callmethod($(pyjl_methodnum(pyfloat)))\n @property\n def real(self):\n return self\n @property\n def imag(self):\n return 0\n def conjugate(self):\n return self\n def __complex__(self):\n return complex(float(self))\n def __trunc__(self):\n return self._jl_callmethod($(pyjl_methodnum(pyjlreal_trunc)))\n def __floor__(self):\n return self._jl_callmethod($(pyjl_methodnum(pyjlreal_floor)))\n def __ceil__(self):\n return self._jl_callmethod($(pyjl_methodnum(pyjlreal_ceil)))\n def __round__(self, ndigits=None):\n return self._jl_callmethod($(pyjl_methodnum(pyjlreal_round)), ndigits)\n class RationalValue(RealValue):\n __slots__ = ()\n __module__ = \"juliacall\"\n @property\n def numerator(self):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(numerator))))\n @property\n def denominator(self):\n return self._jl_callmethod($(pyjl_methodnum(pyjlnumber_op(denominator))))\n class IntegerValue(RationalValue):\n __slots__ = ()\n __module__ = \"juliacall\"\n def __int__(self):\n return self._jl_callmethod($(pyjl_methodnum(pyint)))\n def __index__(self):\n return self.__int__()\n @property\n def numerator(self):\n return self\n @property\n def denominator(self):\n return 1\n import numbers\n numbers.Number.register(NumberValue)\n numbers.Complex.register(ComplexValue)\n numbers.Real.register(RealValue)\n numbers.Rational.register(RationalValue)\n numbers.Integral.register(IntegerValue)\n del numbers\n \"\"\", filename, \"exec\"), jl.__dict__)\n pycopy!(pyjlnumbertype, jl.NumberValue)\n pycopy!(pyjlcomplextype, jl.ComplexValue)\n pycopy!(pyjlrealtype, jl.RealValue)\n pycopy!(pyjlrationaltype, jl.RationalValue)\n pycopy!(pyjlintegertype, jl.IntegerValue)\nend\n\npyjl(v::Number) = pyjl(pyjlnumbertype, v)\npyjl(v::Complex) = pyjl(pyjlcomplextype, v)\npyjl(v::Real) = pyjl(pyjlrealtype, v)\npyjl(v::Rational) = pyjl(pyjlrationaltype, v)\npyjl(v::Integer) = pyjl(pyjlintegertype, v)\n", "meta": {"hexsha": "497c04b54e5fd5985e871763b937c372fdb27988", "size": 9918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jlwrap/number.jl", "max_stars_repo_name": "jlapeyre/PythonCall.jl", "max_stars_repo_head_hexsha": "05237b2c4f0486129ff7a3969add58912bfbbbfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 200, "max_stars_repo_stars_event_min_datetime": "2021-03-02T06:02:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:06:46.000Z", "max_issues_repo_path": "src/jlwrap/number.jl", "max_issues_repo_name": "jlapeyre/PythonCall.jl", "max_issues_repo_head_hexsha": "05237b2c4f0486129ff7a3969add58912bfbbbfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 121, "max_issues_repo_issues_event_min_datetime": "2021-03-04T16:49:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:02:48.000Z", "max_forks_repo_path": "src/jlwrap/number.jl", "max_forks_repo_name": "jlapeyre/PythonCall.jl", "max_forks_repo_head_hexsha": "05237b2c4f0486129ff7a3969add58912bfbbbfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-03-01T22:26:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T08:20:10.000Z", "avg_line_length": 42.75, "max_line_length": 129, "alphanum_fraction": 0.6561806816, "num_tokens": 2649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23741462155908738}} {"text": "module Samplers\n\nexport GibbsSampler, SequentialMonteCarlo, SequentialImportanceSampler, MetropolisHastingsSampler\nexport MetropolisHastingsSampler, MetropolisWithinGibbsSampler\n\nabstract type Sampler end\n\nabstract type MetropolisWithinGibbsSampler <: Sampler end\n\nstruct GibbsSampler <: MetropolisWithinGibbsSampler\n num_iterations::Int64\n num_burn_in::Int64\n skip::Int64\n assignment_types::Vector{String}\n function GibbsSampler(;num_iterations::Int64=1000, num_burn_in::Int64=0, skip::Int64=1, \n assignment_types::Vector{String}=[\"random\"])\n if num_iterations < 1\n error(\"Number of iterations should be positive.\")\n end\n if num_burn_in < 0\n error(\"Number of burn in iterations should be positive.\")\n end\n if !(all(map(x -> x in [\"random\", \"all same cluster\", \"all different clusters\"], assignment_types)))\n error(\"Initial assignment types can only be one of 'random', 'all same cluster' or 'all different clusters'\")\n end\n return new(num_iterations, num_burn_in, skip, assignment_types)\n end\nend\n\nmutable struct MetropolisHastingsSampler <: MetropolisWithinGibbsSampler \n num_iterations::Int64 \n num_burn_in::Int64\n proposal_radius::Int64 \n skip::Int64\n adaptive::Bool\n assignment_types::Vector{String}\n function MetropolisHastingsSampler(;num_iterations=1000, num_burn_in=1000, proposal_radius=5, skip=1, \n adaptive=false, assignment_types::Vector{String}=[\"random\"])\n if num_iterations < 1\n error(\"Number of iterations should be positive.\")\n end\n if num_burn_in < 0\n error(\"Number of burn in iterations should be positive.\")\n end\n if !(all(map(x -> x in [\"random\", \"all same cluster\", \"all different clusters\"], assignment_types)))\n error(\"Initial assignment types can only be one of 'random', 'all same cluster' or 'all different clusters'\")\n end\n return new(num_iterations, num_burn_in, proposal_radius, skip, adaptive, assignment_types)\n end\nend\n\nstruct SequentialMonteCarlo <: Sampler\n num_particles::Int64\n ess_threshold::Float64\n function SequentialMonteCarlo(;num_particles::Int64=1000, ess_threshold::T=0.5) where \n {T <: Real}\n if num_particles < 1\n error(\"Number of particles should be positive.\")\n end\n if ess_threshold < 0\n error(\"ESS Threshold should be non-negative.\")\n end\n if typeof(ess_threshold) <: AbstractFloat && ess_threshold > 1\n error(\"ESS Threshold should be either a non-negative integer or a fraction\")\n end\n if ess_threshold < 1\n ess_threshold = num_particles*ess_threshold\n end\n return new(num_particles, ess_threshold)\n end\nend\n\nstruct SequentialImportanceSampler <: Sampler\n num_particles::Int64\n function SequentialImportanceSampler(;num_particles=1000)\n return new(num_particles)\n end\nend\n\nend", "meta": {"hexsha": "f78132b0b6b8267b33aebc1dd0f09624a1f9d2f9", "size": 3068, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/samplers.jl", "max_stars_repo_name": "realseanla/ntl-stick-breaking-julia", "max_stars_repo_head_hexsha": "f6f0a07637029fd25dc7474182c20bef75fe0858", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/samplers.jl", "max_issues_repo_name": "realseanla/ntl-stick-breaking-julia", "max_issues_repo_head_hexsha": "f6f0a07637029fd25dc7474182c20bef75fe0858", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/samplers.jl", "max_forks_repo_name": "realseanla/ntl-stick-breaking-julia", "max_forks_repo_head_hexsha": "f6f0a07637029fd25dc7474182c20bef75fe0858", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.35, "max_line_length": 121, "alphanum_fraction": 0.6730769231, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2372464746477365}} {"text": "export iauUtctai\n\"\"\"\nTime scale transformation: Coordinated Universal Time, UTC, to\nInternational Atomic Time, TAI.\n\nThis function is part of the International Astronomical Union's\nSOFA (Standards of Fundamental Astronomy) software collection.\n\nStatus: canonical.\n\nGiven:\n utc1,utc2 double UTC as a 2-part quasi Julian Date (Notes 1-4)\n\nReturned:\n tai1,tai2 double TAI as a 2-part Julian Date (Note 5)\n\nReturned (function value):\n int status: +1 = dubious year (Note 3)\n 0 = OK\n -1 = unacceptable date\n\nNotes:\n\n 1. utc1+utc2 is quasi Julian Date (see Note 2), apportioned in any\n convenient way between the two arguments, for example where utc1\n is the Julian Day Number and utc2 is the fraction of a day.\n\n 2. JD cannot unambiguously represent UTC during a leap second unless\n special measures are taken. The convention in the present\n function is that the JD day represents UTC days whether the\n length is 86399, 86400 or 86401 SI seconds. In the 1960-1972 era\n there were smaller jumps (in either direction) each time the\n linear UTC(TAI) expression was changed, and these \"mini-leaps\"\n are also included in the SOFA convention.\n\n 3. The warning status \"dubious year\" flags UTCs that predate the\n introduction of the time scale or that are too far in the future\n to be trusted. See iauDat for further details.\n\n 4. The function iauDtf2d converts from calendar date and time of day\n into 2-part Julian Date, and in the case of UTC implements the\n leap-second-ambiguity convention described above.\n\n 5. The returned TAI1,TAI2 are such that their sum is the TAI Julian\n Date.\n\nCalled:\n iauJd2cal JD to Gregorian calendar\n iauDat delta(AT) = TAI-UTC\n iauCal2jd Gregorian calendar to JD\n\nReferences:\n\n McCarthy, D. D., Petit, G. (eds.), IERS Conventions (2003),\n IERS Technical Note No. 32, BKG (2004)\n\n Explanatory Supplement to the Astronomical Almanac,\n P. Kenneth Seidelmann (ed), University Science Books (1992)\n\nThis revision: 2013 July 26\n\nSOFA release 2018-01-30\n\nCopyright (C) 2018 IAU SOFA Board. See notes at end.\n\"\"\"\n\n# int iauUtctai(double utc1, double utc2, double *tai1, double *tai2)\n\nfunction iauUtctai(utc1::Real, utc2::Real)\n ref_tai1 = Ref{Float64}(0.0)\n ref_tai2 = Ref{Float64}(0.0)\n\n status = ccall((:iauUtctai, libsofa_c), Cint,\n (Cdouble, Cdouble, Ref{Cdouble}, Ref{Cdouble}),\n convert(Float64, utc1), convert(Float64, utc2),\n ref_tai1, ref_tai2)\n\n return status, ref_tai1[], ref_tai2[]\nend", "meta": {"hexsha": "08b838db8932dd66f4e0f95cebeecc24a0fc06b6", "size": 2633, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utctai.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_stars_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-12-11T05:19:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T03:10:26.000Z", "max_issues_repo_path": "src/utctai.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_issues_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-02T00:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T06:42:23.000Z", "max_forks_repo_path": "src/utctai.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_forks_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:41:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:41:12.000Z", "avg_line_length": 33.3291139241, "max_line_length": 71, "alphanum_fraction": 0.6931257121, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23695500573931236}} {"text": "using DataFrames # readtable function\n# using Requests\ntype Bus\n nodeID::Int\n root::Int\n Pd::Float64\n Qd::Float64\n Vmax::Float64\n Vmin::Float64\n B::Float64\n R::Float64\n X::Float64\n children::Vector{Int}\n ancestor::Vector{Int}\n genids::Int\n function Bus(nodeID, root, Pd, Qd, B, R, X, Vmax, Vmin)\n b = new(nodeID, root, Pd, Qd)\n b.Vmax = Vmax\n b.Vmin = Vmin\n b.R = R\n b.X = X\n b.B = B\n b.children = Int[]\n b.ancestor = Int[]\n # b.genids = 0\n return b\n end\nend\n#################################################################\ntype Generator\n genID::Int\n busidx::Int\n Pgmax::Float64\n Pgmin::Float64\n Qgmax::Float64\n Qgmin::Float64\n cost::Float64\n function Generator( busidx, Pgmax, Pgmin, Qgmax, Qgmin, cost)\n g = new(busidx)\n g.busidx = busidx\n g.cost = cost\n g.Pgmax = Pgmax\n g.Pgmin = Pgmin\n g.Qgmax = Qgmax\n g.Qgmin = Qgmin\n return g\n end\nend\n\n##################################################################\ntype Line\n arcID::Int\n tail::Int # the \"to\" node\n head::Int # the \"from\" node\n r::Float64 # the resistance value\n x::Float64 # the reactance value\n u::Float64 # the capacity of the line\n function Line(arcID, tail, head, r, x, u)\n line = new(arcID, tail, head, r, x)\n line.u = u\n return line\n end\nend\n#########################################\n## storage data\ntype Storage\n ID::Int\n busidx::Int\n Pkmax::Float64\n Ekmax::Float64\n Aleph::Float64\n Co::Float64\n Cp::Float64\n Ce::Float64\n function Storage(ID, busidx, Pkmax, Ekmax, Aleph, Co, Cp, Ce)\n s = new(ID)\n s.ID = ID\n s.busidx = busidx\n s.Pkmax = Pkmax\n s.Ekmax = Ekmax\n s.Aleph = Aleph\n s.Co = Co\n s.Cp = Cp\n s.Ce = Ce\n return s\n end\nend\n#########################################\n## station data\ntype Station\n ID::Int\n busidx::Int\n Cf::Float64\n function Station(ID, busidx, Cf)\n st = new(ID)\n st.ID = ID\n st.busidx = busidx\n st.Cf = Cf\n return st\n end\nend\n######################################################################################################\n\n\nfunction DataImport(filename_Node, filename_Generator, filename_Line, filename_Storage, filename_Station, filename_SMP)\n\n ######################################################################################################\n # Bus/Node Data\n # busmat = readtable(filename_Node)\n busmat = readcsv(filename_Node, header=true)[1]\n\n buses = Bus[]\n busIDmap = Dict()\n for i in 1:size(busmat,1)\n\n nodeID = i\n busIDmap[busmat[i,1]] = i\n\n if i==1\n root = busIDmap[busmat[i,1]]\n else\n root = 0\n end\n\n Pd = busmat[i,2]\n Qd = busmat[i,3]\n R = busmat[i,6]\n X = busmat[i,7]\n\n Vmax = busmat[i,4]\n Vmin = busmat[i,5]\n B = busmat[i,8]\n\n b = Bus(nodeID, root, Pd, Qd, B, R, X, Vmax, Vmin)\n push!(buses, b)\n end\n\n #######################################################################################################\n ## generator data\n generatorlist = Int[]\n generators = Generator[]\n # genmat = readtable(filename_Generator)\n genmat = readcsv(filename_Generator, header=true)[1]\n\n for i in 1:size(genmat,1)\n busidx = genmat[i,1]\n Pgmax = genmat[i,2]\n Pgmin = genmat[i,3]\n Qgmax = genmat[i,4]\n Qgmin = genmat[i,5]\n cost = genmat[i,6]\n\n g = Generator(busidx, Pgmax, Pgmin, Qgmax, Qgmin, cost)\n push!(generators, g)\n # setg(buses[busidx], i)\n end\n #for g in 1:length(generators)\n # generators[g].cost = genmat[g,4]\n #end\n #################################################################\n ## branch data\n # branchmat = readtable(filename_Line)\n branchmat = readcsv(filename_Line, header=true)[1]\n\n\n lines = Line[]\n for i in 1:size(branchmat,1)\n fbus = busIDmap[branchmat[i,2]]\n tbus = busIDmap[branchmat[i,1]]\n abus = busIDmap[branchmat[i,1]]\n x = branchmat[i,4]\n r = branchmat[i,3]\n u = branchmat[i,6] # flow limit\n push!(buses[tbus].children, fbus)#children\n push!(buses[fbus].ancestor, abus)#ancestor\n l = Line(i, tbus, fbus, r, x, u)\n push!(lines,l)\n end\n #########################################\n ## storage data\n # storagemat = readtable(filename_Storage)\n storagemat = readcsv(filename_Storage, header=true)[1]\n\n storages = Storage[]\n for i in 1:size(storagemat,1)\n storageID = i\n busidx = 1\n Pkmax = storagemat[i,2]\n Ekmax = storagemat[i,3]\n Aleph = storagemat[i,4]\n Co = storagemat[i,5]\n Cp = storagemat[i,6]\n Ce = storagemat[i,7]\n\n temp = Storage(storageID, busidx, Pkmax, Ekmax, Aleph, Co, Cp, Ce)\n push!(storages,temp)\n end\n\n #########################################\n ## charging/discharing station data\n # stationmat = readtable(filename_Station)\n stationmat = readcsv(filename_Station, header=true)[1]\n stations = Station[]\n for i in 1:size(stationmat,1)\n stationID = i\n busidx = stationmat[i,2]\n Cf = stationmat[i,3]\n\n temp = Station(stationID, busidx, Cf)\n push!(stations,temp)\n end\n\n #########################################\n SMP_raw = readcsv(filename_SMP, header=true)[1]\n SMP = SMP_raw[3:end]\n\n return buses, generators,lines, storages, stations, SMP\nend\n", "meta": {"hexsha": "837c67a072ceb7ca90fd596e9f368ebebfe9f3aa", "size": 5406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DataImport.jl", "max_stars_repo_name": "JipKim/MES_resilience", "max_stars_repo_head_hexsha": "bc5e526828999cb7127509e4b1a814651d96fe03", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-05T05:32:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T05:32:44.000Z", "max_issues_repo_path": "DataImport.jl", "max_issues_repo_name": "wuyou33/MES_resilience", "max_issues_repo_head_hexsha": "bc5e526828999cb7127509e4b1a814651d96fe03", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DataImport.jl", "max_forks_repo_name": "wuyou33/MES_resilience", "max_forks_repo_head_hexsha": "bc5e526828999cb7127509e4b1a814651d96fe03", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-09-14T03:49:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:27:24.000Z", "avg_line_length": 24.6849315068, "max_line_length": 119, "alphanum_fraction": 0.5112837588, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23695500573931236}} {"text": "using Base\nusing Interpolations\n\n# While the StateID struct and its helper functions may seem a little over-engineered, they\n# primarily exist to document the iSLP and iLV quantities used by TOPBase\n\n\"\"\"\n StateID(iSLP, iLV)\n\n`StateID` represents a given state (electron configuration) of an ion species. The arguments are\ntaken from the TOPBase.\n\n# Arguments\n- `iSLP::UInt16`: An integer representing the quantum atomic numbers SLπ (total spin, orbital\n angular momentum, and parity). The value is given by `100*(2*S+1) + 10*L + π`. Note that TOPBase\n documentation refers to the parity quantum number as P or π, but for consistency with how TOPBase\n presents the data, we prefer P in our implementation code.\n- `iLV::UInt8`: Distinguishes between configurations that have the same values of `iSLP`. TOPBase\n seems to index the configuration based on the energy level of the configuration (with `iLV = 1`\n corresponding to the lowest energy).\n\n# Notes\nThe combination of this struct and an ion species (or neutral element) should be enough to fully\nspecify a given electron configuration. For example, consider He I:\n- `iSLP = 100, iLV = 1` has the electron configuration: 1s²\n- `iSLP = 100, iLV = 2` has the electron configuration: 1s 2s\n- `iSLP = 100, iLV = 3` has the electron configuration: 1s 3s\n- `iSLP = 111, iLV = 1` has the electron configuration: 1s 2p\n- `iSLP = 111, iLV = 2` has the electron configuration: 1s 3p\n\"\"\"\nstruct StateID\n iSLP::UInt16\n iLV::UInt8\n function StateID(iSLP, iLV)\n @assert 99 < iSLP < 992 # this upper limit is set based on the data source\n @assert (iSLP % 10) < 2 # trailing digit must be 0 or 1\n @assert 0 < iLV # the upper limit is set based on the data source\n new(iSLP, iLV)\n end\nend\n\nBase.:(<)(a::StateID, b::StateID) = (a.iSLP < b.iSLP) || ((a.iSLP == b.iSLP) && (a.iLV < b.iLV))\nBase.show(io::IO, obj::StateID) = print(io, \"StateID{iSLP = \", obj.iSLP, \", iLV = \", obj.iLV, \"}\")\n\n_parity_vals = (\"even\", \"odd\") # predefine these to avoid allocations\n\nfunction _quantum_prop_type(state_id::StateID)\n S_code = div(state_id.iSLP, 100) # hundreds place of state_id.iSLP\n twice_S = S_code - 1\n L = div(state_id.iSLP - S_code*100, 10) # tens place of state_id.iSLP\n parity = _parity_vals[(state_id.iSLP % 2) + 1] # 0 or 1 in ones place of state_id.iSLP\n (Int32(twice_S), Int32(L), parity)\nend\nget_S_quantum_num(state_id::StateID) = _quantum_prop_type(state_id)[1] / 2.0f0\nget_L_quantum_num(state_id::StateID) = _quantum_prop_type(state_id)[2]\nget_parity(state_id::StateID) = _quantum_prop_type(state_id)[3]\n\nfunction get_statistical_weight(state_id::StateID)\n twice_S, L, _ = _quantum_prop_type(state_id)\n (twice_S+1)*(2*L+1)\nend\n\n\"\"\"\n StateProp(ion_energy_ryd, excitation_potential_ryd, statistical_weight, electron_config)\n\n`StateProp` holds data associated with different electron configurations. It's used to hold\ndata read from the TOPBase cross-section queries and to compute the statistical weight.\n\"\"\"\nstruct StateProp\n ion_energy_ryd::Float64 # energy with respect to ionization potential in Rydbergs\n excitation_potential_ryd::Float64 # energy above ground state in Rydbergs\n statistical_weight::UInt16\n electron_config::String\nend\n\n\n# define some generally useful functions related to parsing\nfunction _parse_species_stateid(str::AbstractString, start_Z::Integer,\n start_numElectrons::Integer, start_iSLP::Integer,\n start_iLV::Integer, last_iLV::Integer)\n # parses the atomic_num, number of electrons, iSLP, and iLV entries of the table\n atomic_num = parse(UInt8, str[start_Z:start_numElectrons-1])\n num_electrons = parse(UInt8, str[start_numElectrons:start_iSLP-1])\n iSLP = parse(UInt16, str[start_iSLP:start_iLV-1])\n iLV = parse(UInt16, str[start_iLV:last_iLV])\n (Species(Formula(atomic_num), atomic_num - num_electrons), StateID(iSLP, iLV))\nend\n\n# Functionallity for reading photoionization cross sections. Since these tables can be massive, we\n# use an iterator to do this. This is based on the design used in the Julia standard library for\n# implementing the ``EachLine`` iterable object. That code used the following license:\n#\n# Copyright (c) 2009-2021: Jeff Bezanson, Stefan Karpinski, Viral B. Shah,\n# and other contributors:\n#\n# https://github.com/JuliaLang/julia/contributors\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\nconst _TABLE_BREAK = \" ================================================\"\nconst _HEADER_LINE_LENGTH = length(_TABLE_BREAK)\n\nstruct EachPhotoIonSubtable{IOT <: IO}\n stream::IOT\n ondone::Function\nend\n\n\"\"\"\n each_photo_ion_subtable(filename::AbstractString)\n\nCreate an iterable `EachPhotoIonSubtable` object for parsing photoionization cross-sections.\n\nThe input file is organized as a series of subtables. Each subtable provides the photoionization\nenergies (make sure this isn't the energy of the photoionized electron) in Ryd, and the associated\ncross section (in megabarns) for a different state.\n\nEach entry in the `EachPhotoIonSubtable` iterable provides a named tuple with the keys:\n- name: holds the species name\n- state_id: holds a `StateID` instance\n- photon_energy_ryd: the photoionization values (check), in Ryd, stored in an array of Float32 vals\n- cross_section_MegaBarn: the associated photoionization cross-sections. This array should have the\n same shape and datatype as photon_energy_ryd\n\nThe underlying file is only closed after the `EachPhotoIonSubtable` is garbage collected.\n\n#Notes\nThis implementation is not robust enough to deal with blank lines at the start or end of the file.\n\nThe table should have been produced by a\n[TOPbase Photoionisation Cross Section query](http://cdsweb.u-strasbg.fr/topbase/xsections.html)\nthat uses the following query options:\n- Only a single atomic number and a single number of electrons is included in the query (other\n choices may yield too many results, which causes TOPBase to truncate output).\n- There isn't any limitation on the number the quantum numbers, the energy or the levels\n- The query request levels ordered in the \"Level order in each series\"\n\"\"\"\nfunction each_photo_ion_subtable(filename::AbstractString)\n stream = open(filename, \"r\")\n # confirm that standard file header is present and move the position of the\n # stream past this point\n @assert readline(stream) == _TABLE_BREAK\n @assert readline(stream) == \" I NZ NE ISLP ILV E(RYD) NP\"\n @assert readline(stream) == _TABLE_BREAK\n EachPhotoIonSubtable(stream, ()->close(stream))::EachPhotoIonSubtable\nend\n\nfunction Base.iterate(itr::EachPhotoIonSubtable, state=nothing)\n next_line = readline(itr.stream)\n\n if next_line == _TABLE_BREAK\n return (itr.ondone(); nothing)\n end\n\n # first parse the subtable's header\n species, state_id = _parse_species_stateid(next_line, 9, 13, 17, 23, 27)\n ion_energy_ryd = parse(Float32, next_line[28:41])\n\n num_entries = parse(UInt32, next_line[42:49])\n\n # this could probably be 32-bit.\n photon_energy_ryd = Array{Float32,1}(undef, num_entries)\n cross_section_MegaBarn = Array{Float32,1}(undef, num_entries)\n for i = 1:num_entries # this properly handles the case when num_entries == 0\n cur_line = readline(itr.stream)\n photon_energy_ryd[i] = parse(Float32, cur_line[1:14])\n cross_section_MegaBarn[i] = parse(Float32, cur_line[15:24])\n end\n\n # parse the species, and the level\n ((species = species, state_id=state_id, ion_energy_ryd = ion_energy_ryd,\n photon_energy_ryd_arr = photon_energy_ryd,\n cross_section_MegaBarn_arr = cross_section_MegaBarn), nothing)\nend\n\n# this and the following definition implement Julia's informal iterator interface\nBase.eltype(::Type{<:EachPhotoIonSubtable}) =\n Tuple{String, StateID, Float32, Array{Float32,1}, Array{Float32,1}}\nBase.IteratorSize(::Type{<:EachPhotoIonSubtable}) = SizeUnknown()\n\n# In a couple tables, there's a place where the photon energy is listed out of order. This seems to\n# be okay given that this is in a section of the table where the cross-section is zero.\nconst _species_with_problematic_subtables = (Species(\"He_I\"), Species(\"C_I\"), Species(\"C_II\"),\n Species(\"Al_II\"), Species(\"O_II\"))\n\nfunction _interpolator_from_subtable(table_photon_energy_ryd::Vector{Float32},\n table_cross_section_MBarn::Vector{Float32},\n species::Union{Species,Nothing} = nothing,\n extrapolation_bc = 0.0)\n if species in _species_with_problematic_subtables\n \n for j in 1:length(table_photon_energy_ryd)-1\n if table_photon_energy_ryd[j+1] < table_photon_energy_ryd[j]\n @assert j > 1\n @assert (j + 2) <= length(table_photon_energy_ryd)\n @assert table_photon_energy_ryd[j+2] >= table_photon_energy_ryd[j+1]\n @assert table_photon_energy_ryd[j+2] >= table_photon_energy_ryd[j]\n @assert table_photon_energy_ryd[j+1] >= table_photon_energy_ryd[j-1]\n @assert table_photon_energy_ryd[j] >= table_photon_energy_ryd[j-1]\n\n @assert table_cross_section_MBarn[j+2] == 0.0\n @assert table_cross_section_MBarn[j+1] == 0.0\n @assert table_cross_section_MBarn[j] == 0.0\n @assert table_cross_section_MBarn[j-1] == 0.0\n\n # swap the order of the 2 values\n temp = table_photon_energy_ryd[j]\n table_photon_energy_ryd[j] = table_photon_energy_ryd[j+1]\n table_photon_energy_ryd[j+1] = temp\n end\n end\n end\n LinearInterpolation(table_photon_energy_ryd, table_cross_section_MBarn,\n extrapolation_bc=extrapolation_bc)\nend\n\nfunction _try_env_prefix_path(prefix_env_var, fname)\n prefix = get(ENV, prefix_env_var, nothing)\n if isnothing(prefix)\n e = ErrorException(string(\"The \\\"\", prefix_env_var, \"\\\" environment variable was not set\"))\n throw(e);\n end\n path = joinpath(prefix, fname)\n if !isfile(path) # this properly handles the case where path is a symlink to a file\n throw(ErrorException(string(\"There is no file at \", path)));\n end\n path\nend\n\n# return the minimum iterator over cross_section subtables and the ionization energy of the ground\n# state (according to the table)\nfunction _get_cross_sec_data(species::Species,\n cross_sec_file::Union{AbstractString,Nothing} = nothing)\n\n # get the photo-ionization subtable iterator:\n my_cross_sec_file = if isnothing(cross_sec_file)\n # determine the string representation of Species\n # we don't directly use repr(species) since the representation could change in the future\n # to not use roman numeral (e.g. if support is added for negatively charged species)\n formula_str = repr(\"text/plain\", species.formula)\n roman_numeral = get_roman_numeral(species)\n fname = string(formula_str, \"_\", roman_numeral, \".txt\")\n\n println(\"cross_sec_file isn't specified. Searching for file in the directory specified \",\n \"by the KORG_OP_DIR environment variable.\")\n _try_env_prefix_path(\"KORG_OP_DIR\", fname)\n else\n cross_sec_file\n end\n\n # determine the ionization energy of the ground state (from the subtables)\n gs_ion_energy_ryd = begin # this could be optimized significantly!\n cur_min = floatmax(Float32)\n for (cur_species, _, ion_energy_ryd, _, _) in each_photo_ion_subtable(my_cross_sec_file)\n @assert (cur_species == species) # this will catch mistakes in the query that generated\n # the cross_section data file \n cur_min = min(ion_energy_ryd, cur_min)\n end\n cur_min\n end\n\n subtable_iter = each_photo_ion_subtable(my_cross_sec_file)\n subtable_iter, gs_ion_energy_ryd\nend\n\n@doc raw\"\"\"\n weighted_bf_cross_section_TOPBase(λ_vals, T_vals, species; extrapolation_bc = 0.0\n cross_sec_file = nothing,\n partition_func = partition_funcs[species])\n\nCalculate the combined bound-free cross section (in cm²) of an ion species using data from the\nOpacity Project. The result is the mean of the the bound-free cross section of each electron state,\nweighted by their Boltzmann probabilities. It includes the LTE correction for stimulated emission. \nThe result is stored in a 2D array with a size given by `(length(λ_vals), length(T_vals))`.\n\n# Arguments\n- `λ_vals::AbstractVector`: wavelengths (in cm) to compute the cross sections at\n- `T_vals::AbstractVector`: temperatures (in K) to compute the cross sections at\n- `species::Species`: the starting atom or atomic ion of the bound-free reaction.\n\n# Keyword Arguments\n- `extrapolation_bc`: Specifies handling of extrapolation during linear interpolation (this is\n passed to `Interpolations.LinearInterpolation`).\n- `cross_sec_file`: Optional keyword that specifies the path to the text file that holds the\n cross-section subtables. When `nothing` (the default), this function tries to load the file\n from `$KORG_OP_DIR/_.txt`. `` is replaced with the\n atomic symbol of the species (e.g. `H`, `He`, `Al`) and `` is replaced with the \n capital Roman numeral(s) specifying the ionization state.\n- `partition_func`: Specifies the partition function for the current species. This should be a\n callable that accepts temperature as an argument. When this is `nothing`, it falls back to the\n default partition functions.\n\n# Explanation\nIn more mathematical rigor, this function basically evaluates the following equation:\n\n``\\overline{\\sigma_{\\rm bf}}(\\lambda,T) = \\sum_{{\\bf n}\\in{\\rm states}} \\frac{ g_{\\bf n}}{U(T)} e^{-E_{\\bf n}/(k_B T)}\\left(1 - e^{-h c/(\\lambda k_B T)}\\right) \\sigma_{{\\rm bf}, {\\bf n}}(\\lambda)``\n\nIn this equation:\n- ``g_{\\bf n}`` is the statistical weight of state ``{\\bf n}``.\n- ``U`` is the partition function.\n- ``E_{\\bf n}`` is the excitation potential of state ``{\\bf n}``. In other words, its the energy \n difference between state ``{\\bf n}`` and the ground state.\n- ``\\sigma_{\\lambda,{\\rm bf}, {\\bf n}}`` is the bound-free cross-section (a.k.a. photo-ionization\n cross section) of state ``{\\bf n}``.\n\nThe linear aborption coefficient for bound-free absorption is simply:\n``\\alpha_{\\lambda,{\\rm bf}} = n_{\\rm tot} \\overline{\\sigma_{\\rm bf}}(\\lambda,T)``.\n\n# Notes\nIn the future, it needs to be possible to pass an argument that adjusts the energy levels of\ndifferent electron configurations.\n\"\"\"\nfunction weighted_bf_cross_section_TOPBase(λ_vals::AbstractVector, T_vals::AbstractVector,\n species::Species; extrapolation_bc=0.0,\n cross_sec_file::Union{AbstractString,Nothing} = nothing,\n partition_func = partition_funcs[species])\n # Note: it would not take a lot of work to make this work with 32-bit floats (since the tables\n # only store 32-bit floats). If doing that, it might be wise to accept λ in units of ångstroms\n # (for precision purposes)\n\n # TODO: make it possible to pass in a dict mapping dict names to the various energy levels\n # (to allow for overwriting the values in the table with empirical values)\n\n @assert !ismolecule(species) # species must be an atom or atomic ion\n\n # precompute Temperature-dependent constant\n inv_partition_func_val = 1.0./partition_func.(T_vals)\n\n β_Ryd = RydbergH_eV./(kboltz_eV .* T_vals)\n\n # convert λ_vals to photon energies\n photon_energies = (hplanck_eV * c_cgs / RydbergH_eV) ./ λ_vals\n\n # prepare the output array where results will be accumulated\n weighted_average = zeros(eltype(photon_energies), (length(photon_energies),length(T_vals)))\n\n cross_section_subtables, gs_ion_energy_ryd = _get_cross_sec_data(species, cross_sec_file)\n\n for subtable in cross_section_subtables\n if length(subtable.photon_energy_ryd_arr) == 0\n continue\n end\n\n cross_section_interp = _interpolator_from_subtable(subtable.photon_energy_ryd_arr,\n subtable.cross_section_MegaBarn_arr,\n species, extrapolation_bc)\n statistical_weight = get_statistical_weight(subtable.state_id)\n excitation_potential_ryd = subtable.ion_energy_ryd - gs_ion_energy_ryd\n\n # now iterate over Temperatures\n for j in 1:length(T_vals)\n\n # now compute the weighting of the current state under LTE\n weight = inv_partition_func_val[j] * statistical_weight * exp(-excitation_potential_ryd\n * β_Ryd[j])\n\n current_cross_section = ( cross_section_interp.(photon_energies) .*\n (1.0 .- exp.(-photon_energies.*β_Ryd[j])) )\n view(weighted_average, :, j) .+= (current_cross_section .* weight)\n end\n end\n\n # convert weighted_average units from megabarn to cm²\n weighted_average .*= 1e-18\n weighted_average\nend\n\n\n\"\"\"\n absorption_coef_bf_TOPBase(λ, T, ndens_species, species; kwargs...)\n\nComputes the bound-free linear absorption coefficient, α, (in units of cm⁻¹) using data from the \nOpacity Project (downloaded from TOPBase) and assuming LTE. The result is stored in a 2D array with\na size given by `(length(λ), length(T))`.\n\n# Arguments\n- `λ::AbstractVector`: wavelengths (in cm) to compute α at.\n- `T::AbstractVector`: temperatures (in K) to compute α at.\n- `ndens_species::AbstractVector`: number density (in cm⁻³) of the species at each temperature \n (this should have the same length as T).\n- `species::Species`: the starting atom or atomic ion of the bound-free reaction.\n\n# Keyword Arguments\nThis function accepts all the same keyword arguments as `weighted_bf_cross_section_TOPBase`.\n\"\"\"\nfunction absorption_coef_bf_TOPBase(λ::AbstractVector, T::AbstractVector,\n ndens_species::AbstractVector, species::Species; kwargs...)\n @assert size(T) == size(ndens_species)\n\n arr = weighted_bf_cross_section_TOPBase(λ, T, species; kwargs...)\n\n # to save time and memory, let's modify the values of arr in-place\n for (i,n) in enumerate(ndens_species)\n view(arr,:,i) .*= n\n end\n\n arr\nend\n", "meta": {"hexsha": "8b6d549773c01ed9e308f003d59b89f70c1f9cdb", "size": 19660, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/continuum_absorption/absorption_metal.jl", "max_stars_repo_name": "ajwheeler/SSSynth.jl", "max_stars_repo_head_hexsha": "be068e43d18fcd9bb51979ce6a12c057ee36172e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-06-10T12:45:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T15:22:57.000Z", "max_issues_repo_path": "src/continuum_absorption/absorption_metal.jl", "max_issues_repo_name": "ajwheeler/Korg.jl", "max_issues_repo_head_hexsha": "a51ec7ce5c7ddb25e0d582880ef05a8bb84cc2be", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 60, "max_issues_repo_issues_event_min_datetime": "2021-05-01T23:04:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:20:07.000Z", "max_forks_repo_path": "src/continuum_absorption/absorption_metal.jl", "max_forks_repo_name": "ajwheeler/SSSynth.jl", "max_forks_repo_head_hexsha": "be068e43d18fcd9bb51979ce6a12c057ee36172e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2596153846, "max_line_length": 197, "alphanum_fraction": 0.7007121058, "num_tokens": 4952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23666946512787237}} {"text": "using Revise\nusing Plots\nusing Pkg\n# Pkg.activate(\".\")\nusing RadiativeTransfer\nusing RadiativeTransfer.Architectures\nusing RadiativeTransfer.Absorption\nusing RadiativeTransfer.Scattering\nusing RadiativeTransfer.vSmartMOM\nusing RadiativeTransfer.SolarModel\nusing InstrumentOperator\nusing Interpolations\nusing Polynomials\nusing ForwardDiff \nusing Distributions\nusing NCDatasets\n\n## Atmospheric Radiative Transfer\n\n# Load parameters from file\nparameters = vSmartMOM.parameters_from_yaml(\"RadiativeTransfer/test/helper/O2Parameters.yaml\")\nFT = Float64\n\n# oco2_L1bScND_18688a_180105_B8100r_180206190633\n\noco_file = \"/net/fluo/data1/group/oco2/L1bSc/oco2_L1bScGL_15258a_170515_B10003r_200214061601.h5\"\noco_met_file = \"/net/fluo/data1/group/oco2/L2Met/oco2_L2MetGL_26777a_190715_B10003r_200429213029.h5\"\nils_file = \"/home/rjeyaram/RadiativeTransfer/src/vSmartMOM/ils_oco2.json\"\n\nfp = 5\niOrbit = 4400\nband = 1\n\nsza_ = 32.4436\nvza_ = [0.072]\n\n\nfunction conv_spectra_local(m::VariableKernelInstrument, ν, spectrum; stride=1)\n # FT = eltype(m.ν_out)\n # Define grid where to perform convolution:\n \n # Padding at both sides required:\n off = ceil(Int, size(m.kernel, 1) / 2)\n ind = off:stride:(length(ν) - off)\n \n # knots where convolution will be applied to\n knots = view(ν, ind)\n te = LinearInterpolation(m.ν_out, Float32.(m.ind_out))\n spec_out = zeros(Real, length(knots));\n for i in eachindex(knots)\n # Simple first, nearest neighbor ILS\n ind_fraction = round(Int, te(knots[i]));\n kernel = view(m.kernel, :, ind_fraction)\n for j in eachindex(kernel)\n spec_out[i] += kernel[j] * spectrum[ind[i] + j] \n end\n end\n # Change this later to only perform conv around output grid!\n fin = LinearInterpolation(ν[ind], spec_out; extrapolation_bc=Interpolations.Flat())\n return fin(m.ν_out)\nend;\n\n# Runner is used to set AD fields as duals\nfunction runner!(y, x, parameters=parameters, oco_file=oco_file, \n oco_met_file=oco_met_file, \n ils_file=ils_file, fp=fp, iOrbit=iOrbit,\n sza_=sza_, vza_=vza_)\n\n # Set parameters fields as the dual numbers\n parameters.brdf = [LambertianSurfaceScalar(x[1])]\n\n parameters.scattering_params.rt_aerosols[1].τ_ref = x[2];\n\n # parameters.scattering_params.rt_aerosols[1].aerosol.size_distribution = LogNormal(log(x[3]), log(x[4]), check_args=false)\n\n # parameters.scattering_params.rt_aerosols[1].aerosol.nᵣ = x[5];\n # parameters.scattering_params.rt_aerosols[1].aerosol.nᵢ = x[6];\n\n # parameters.scattering_params.rt_aerosols[1].p₀ = x[7];\n # parameters.scattering_params.rt_aerosols[1].σp = x[8];\n\n # Set profiles properly\n met = Dataset(oco_met_file);\n T_met = met.group[\"Meteorology\"][\"temperature_profile_met\"][:,fp,iOrbit];\n ak = met.group[\"MeteorologyDiagnostics\"][\"ak\"][:,fp,iOrbit];\n bk = met.group[\"MeteorologyDiagnostics\"][\"bk\"][:,fp,iOrbit];\n p_surf = met.group[\"Meteorology\"][\"surface_pressure_met\"][fp,iOrbit];\n p_half = (ak + bk * p_surf);\n p_half = vcat(p_half, p_surf);\n q = met.group[\"Meteorology\"][\"specific_humidity_profile_met\"][:,fp,iOrbit];\n parameters.p = p_half / 100\n parameters.q = q # zeros(size(q))\n parameters.T = T_met\n parameters.sza = sza_\n parameters.vza = vza_\n\n @show parameters.sza, parameters.vza\n\n # @show parameters.sza\n # plot!(parameters.p)\n # return \n\n\n model = model_from_parameters(parameters);\n\n # Run the model to obtain reflectance matrix\n R = vSmartMOM.rt_run(model, i_band=1);\n\n # Produce black-body in wavenumber range\n T = 5777\n λ_grid = reverse(1e4 ./ parameters.spec_bands[1]) #collect(757:0.01:777)\n black_body = planck_spectrum_wl(T, λ_grid) * 2.1629e-05 * pi\n black_body = SolarModel.watts_to_photons(λ_grid, black_body)\n\n # Get solar transmittance spectrum \n solar_transmission = solar_transmission_from_file(\"/home/rjeyaram/RadiativeTransfer/src/solar_merged_20160127_600_26316_100.out\", parameters.spec_bands[1])\n\n # Get outgoing solar radiation\n sun_out = reverse(solar_transmission) .* black_body\n\n # Apply Earth reflectance matrix \n earth_out = sun_out .* reverse(R[:])\n\n # Set up InstrumentOperator\n ils_Δ, ils_in, dispersion = InstrumentOperator.read_ils_table(oco_file, ils_file);\n\n # Define model grid:\n res = 0.001\n\n # Just consider the ILS within ± 0.35nm\n grid_x = -0.35e-3:res*1e-3:0.35e-3\n \n extended_dims = [fp,band] # Footprint, band\n\n # Re-interpolate I from ν_grid to new grid/resolution\n interp_I = LinearInterpolation(λ_grid, earth_out);\n wl = 757.5:res:771.0\n I_wl = interp_I(wl/1000)\n\n # Pixels to be used\n ind_out = collect(0:1015); \n\n # Eventual grid of OCO-2 for Band 1, FP 5:\n dispPoly = Polynomial(view(dispersion, :, extended_dims...))\n ν = Float32.(dispPoly.(1:1016))\n\n # Prepare ILS table:\n ils_pixel = InstrumentOperator.prepare_ils_table(grid_x, ils_in, ils_Δ,extended_dims)\n oco2_kernel = VariableKernelInstrument(ils_pixel, ν, ind_out)\n\n # Convolve input spectrum with variable kernel\n I_conv = conv_spectra_local(oco2_kernel, wl./1e3, I_wl)\n\n y[:] = I_conv[:]\n\nend\n\ndirectory = \"/net/fluo/data1/group/oco2/L1bSc/\"\nfiles_list = filter(x->endswith(x, \".h5\") && startswith(x, \"oco2_L1bScGL_26\"), readdir(directory))\n\nmet_files_list = filter(x->endswith(x, \".h5\"), readdir(\"/net/fluo/data1/group/oco2/L2Met/\"))\n\nI_convs_all = zeros(1016, length(files_list))\noco2_Abands_all = zeros(1016, length(files_list))\n\nalbedos = zeros(length(files_list))\ncloud_levels = zeros(length(files_list))\n\noptimal_x = zeros(8, length(files_list))\n\nfor i in 1:length(files_list)\n\n @show i\n\n oco_file = files_list[i]\n\n # try\n ocoData = Dataset(directory * oco_file)\n\n oco_met_file = \"/net/fluo/data1/group/oco2/L2Met/\" * filter(x->contains(x, oco_file[14:19]), met_files_list)[1]\n\n oco_file = directory * oco_file\n # @show oco_file\n # @show oco_met_file\n\n met = Dataset(oco_met_file)\n cloud_levels[i] = met.group[\"Meteorology\"][\"cloud_liquid_water_path_met\"][fp,iOrbit]\n\n # println()\n\n # continue\n\n ## Getting an OCO spectrum for fun to fit:\n o2AbandSpectra = ocoData.group[\"SoundingMeasurements\"][\"radiance_o2\"]\n SoundingGeometry = ocoData.group[\"SoundingGeometry\"]\n vza = SoundingGeometry[\"sounding_zenith\"]\n sza = SoundingGeometry[\"sounding_solar_zenith\"]\n lat = SoundingGeometry[\"sounding_latitude\"]\n lon = SoundingGeometry[\"sounding_longitude\"]\n o2AbandSpectra = ocoData.group[\"SoundingMeasurements\"][\"radiance_o2\"]\n oco2_Aband = o2AbandSpectra[:,fp,iOrbit]\n\n println(\"$(round(Float64(lat[fp,iOrbit]), digits=2)) $(round(Float64(lon[fp,iOrbit]), digits=4))\")\n # continue\n\n sza_ = sza[fp,iOrbit]\n vza_ = [vza[fp,iOrbit]]\n\n x = FT[0.05,\n 0.05]#,\n # 1.3,\n # 2.0,\n # 1.3,\n # 0.00000001,\n # 90000,\n # 5000.0]\n\n # Run FW model:\n # @time runner(x);\n I_conv = zeros(1016)\n dfdx = ForwardDiff.jacobian(runner!, I_conv, x);\n\n dfdx[:,2] .= 0;\n\n @show size(dfdx)\n\n\n y = oco2_Aband;\n Fx = I_conv;\n K = dfdx;\n\n # Regular least squares:\n dx = K \\ (y-Fx)\n\n I_convs_all[:,i] = I_conv\n oco2_Abands_all[:,i] = oco2_Aband\n\n # optimal_x[:,i] = x+dx\n albedos[i] = x[1] + dx[1]\n\n\n # @show dx, x+dx\n\n # catch\n # println(\"Error on \" * oco_file)\n # continue\n # end\n\nend", "meta": {"hexsha": "142b32fb66d792e2e26a61213f81fdcd851073d2", "size": 7698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/prototyping/AD_simple_test.jl", "max_stars_repo_name": "RadiativeTransfer/RadiativeTransfer.jl", "max_stars_repo_head_hexsha": "41c228d6058b9293338299a80baf7196b7833d23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2021-05-07T21:58:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T18:03:07.000Z", "max_issues_repo_path": "test/prototyping/AD_simple_test.jl", "max_issues_repo_name": "RupeshJey/RadiativeTransfer.jl", "max_issues_repo_head_hexsha": "dcb0cfcdbb8b462d7badddbd00110e66c88602a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-08-24T21:33:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T19:30:14.000Z", "max_forks_repo_path": "test/prototyping/AD_simple_test.jl", "max_forks_repo_name": "RadiativeTransfer/RadiativeTransfer.jl", "max_forks_repo_head_hexsha": "41c228d6058b9293338299a80baf7196b7833d23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-22T23:35:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T23:35:29.000Z", "avg_line_length": 30.9156626506, "max_line_length": 159, "alphanum_fraction": 0.6630293583, "num_tokens": 2293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.23661163743040994}} {"text": "# simulate.jl: functions to simulate the model\n# include(\"setup.jl\")\nfunction evolve!( pop::Population, generations::Int64 = 1 )\n # from ReputationSets https://github.com/tkessinger/reputation_sets\n # the main function to evolve the population\n # generations specifies the total number of generations for which to run the simulation\n for i::Int64 in 1:generations\n if pop.verbose println(\"\\ninitiating generation $(pop.generation)\") end\n \n # first, update payoffs\n if pop.verbose println(\"updating actions and payoffs\") end\n update_payoffs_using_matrix!(pop) # method that stores payoffs in a matrix\n \n # then, select a learner and a role model and perform update\n if pop.verbose println(\"\") end\n if pop.verbose println(\"evolving, generation $(pop.generation)\") end\n update_strategies_and_opinions_db!(pop)\n \n if pop.verbose println(\"\") end\n if pop.verbose println(\"ending generation $(pop.generation)\") end\n pop.generation += 1\n end\nend\n\nfunction update_payoffs_using_matrix!( pop::Population )\n # update individual payoffs by computing pairwise payoffs and storing them in a matrix\n \n # to make the code run faster, we only update payoffs in a given generation \n # if strategies or sets have changed. sets_changed and strategies_changed are \n # initialized as true so that payoffs are computed in the first round\n if pop.sets_changed \n # if (previous) learner's sets have changed, re-compute all payoffs\n if pop.verbose println(\"updating all payoffs because set_changed = $(pop.sets_changed)\") end\n pop.payoffs_mat .= zero(Float64) # reset all payoffs_mat\n pop.prev_actions .= zero(Int64) # reset all prev_actions\n \n # then, recompute all payoffs\n for k in 1:pop.sets.M # for each set\n for (i, j) in pop.sets.set_pairs[k] # for each pair within each set\n compute_payoffs!( pop, i, j, k ) # compute payoffs for i & j when intereacting in set k\n # this also updates pop.prev_actions accordingly\n end\n end\n\n elseif pop.strategies_changed \n # if (previous) learner's strategy has changed, recompute payoffs involving that individual\n if pop.verbose println(\"updating payoffs involving $(pop.prev_learner) because strategies_changed = $(pop.strategies_changed)\") end\n pop.payoffs_mat[pop.prev_learner,:] .= zero(Float64) # first, reset payoffs involving prev_learner\n pop.payoffs_mat[:,pop.prev_learner] .= zero(Float64)\n pop.prev_actions[:,pop.prev_learner,:] .= zero(Int64)\n pop.prev_actions[:,:,pop.prev_learner] .= zero(Int64)\n\n # then, recompute payoffs involving prev_learner\n for k in 1:pop.sets.M # for each set\n for (i, j) in pop.sets.set_pairs[k] # for each pair within each set\n if i == pop.prev_learner || j == pop.prev_learner \n compute_payoffs!( pop, i, j, k ) # compute payoffs for i & j when intereacting in set k\n # this also updates pop.prev_actions accordingly\n end\n end\n end \n else \n if pop.verbose println(\"not updating payoffs b/c sets_changed = $(pop.sets_changed) and strategies_changed = $(pop.strategies_changed)\") end\n return # no need to update prev_interactions or payoffs\n end\n\n # sum rows to get total individual payoffs\n pop.payoffs = [round( x, digits=13 ) for x in vec( sum(pop.payoffs_mat, dims=2) )] # rounding avoids precision errors\n pop.prev_interactions = 2 * sum([length(x) for x in pop.sets.set_pairs])\n\n if pop.verbose println( \"\\npayoff matrix is now $(pop.payoffs_mat)\" ) end\n if pop.verbose println( \"payoffs are now $(pop.payoffs)\" ) end\n if pop.verbose println( \"there were $(pop.prev_interactions) interactions, $(sum(pop.prev_actions)) of which were C\" ) end\nend\n\nfunction compute_payoffs!( pop::Population, i::Int64, j::Int64, k::Int64 )\n # function to compute payoffs for individuals i and j when they interact in set k\n pop.sim.i_action, pop.sim.j_action = -1, -1 # set to -1 to catch any errors in action assignment\n\n # actions depend on whether i and j agree on issue k or not\n if pop.sets.h[i,k] == 0 || pop.sets.h[j,k] == 0\n # if either i or j does not belong to set k, something's wrong\n # leave pop.sim.i_action, pop.sim.j_action as -1 so that the compute_payoffs! throws an error when assigning payoffs\n @warn(\"$i and $j should not be interacting in set $k\"); return\n elseif pop.sets.h[i,k] == pop.sets.h[j,k] \n pop.sim.i_action, pop.sim.j_action = pop.strategies[i,1], pop.strategies[j,1] # if they agree, play s_agree\n else \n pop.sim.i_action, pop.sim.j_action = pop.strategies[i,2], pop.strategies[j,2] # if they disagree, play s_disagree\n end\n\n if pop.verbose\n println(\"\\n\\tupdating actions of $i and $j in set $k; agree on issue $k? $(pop.sets.h[i,k] == pop.sets.h[j,k])\")\n println(\"\\t\\t$i has strats $(pop.strategies[i,:]); $i plays strat $(pop.sim.i_action), earns a payoff of $(pop.game.A[pop.sim.i_action+1, pop.sim.j_action+1])\")\n println(\"\\t\\t$j has strats $(pop.strategies[j,:]); $j plays strat $(pop.sim.j_action), earns a payoff of $(pop.game.A[pop.sim.j_action+1, pop.sim.i_action+1])\")\n end\n\n # add i and j's payoffs to the payoff matrix according to their strategies and the game matrix\n pop.payoffs_mat[i,j] += pop.game.A[pop.sim.i_action+1, pop.sim.j_action+1] # +1 because julia is 1-indexed\n pop.payoffs_mat[j,i] += pop.game.A[pop.sim.j_action+1, pop.sim.i_action+1]\n\n # track actions\n pop.prev_actions[k,i,j] = pop.sim.i_action\n pop.prev_actions[k,j,i] = pop.sim.j_action\nend\n\nfunction update_strategies_and_opinions_db!( pop::Population )\n # function to perform death-birth update\n if pop.verbose println(\"Strategies before updating:\\t $(pop.strategies)\") end\n if pop.verbose println(\"Set memberships before updating: $(pop.sets.h)\") end\n \n # randomly choose a learner and store a list of non_learners\n pop.sim.learner = sample( 1:pop.sets.N )\n \n # compute the fitness of every individual in the population\n for i in 1:pop.sets.N pop.sim.fitnesses[i] = 1.0 + pop.game.β * pop.payoffs[i] end\n if any(x->x<0.0, pop.sim.fitnesses) throw(\"!!! negative fitness detected, aborting !!!\"); end\n \n # choose a role model from the rest of the population, weighted by fitness\n # OLD: pop.sim.role_model = sample( pop.sim.non_learners, Weights(pop.sim.fitnesses) )\n pop.sim.role_model = sample( 1:pop.sets.N, Weights(pop.sim.fitnesses) )\n\n # learner updates\n if pop.verbose println(\"\\n\\trandomly chosen learner is $(pop.sim.learner), role_model is $(pop.sim.role_model)\") end\n if pop.verbose println(\"\\t\\tall payoffs are $(pop.payoffs)\") end\n if pop.verbose println(\"\\t\\tfitnesses are $(pop.sim.fitnesses)\") end\n \n # compute probability of imitation: 1 if same party, 1-p if different parties\n pop.sets.affils[pop.sim.learner] == pop.sets.affils[pop.sim.role_model] ? imit_prob = 1.0 : imit_prob = 1-pop.game.ps[pop.sets.affils[pop.sim.learner]]\n \n if pop.verbose \n println(\"\\t\\tlearner and role model in the same party? $(pop.sets.affils[ pop.sim.learner ] == pop.sets.affils[ pop.sim.role_model ]), imitate with prob $(imit_prob)\") \n end\n\n # update strategies and sets: imitation / mutation occurs with probability imit_prob\n if rand() < imit_prob\n if pop.verbose println(\"\\twill consider imitating\") end\n update_strategies!( pop ) # includes mutation\n update_opinions!( pop ) # includes mutation\n pop.num_imitating += 1\n else\n if pop.verbose println(\"\\tnah won't imitate\") end\n no_strategy_or_opinion_update!( pop )\n pop.num_not_imitating += 1\n end\n\n # track updates\n pop.prev_learner = pop.sim.learner\n if pop.sets_changed == true\n # h is updated above; need to update h_bar, h_base10, h_bar_base10, set_members, set_pairs\n pop.sets.set_members, pop.sets.set_pairs = set_members_and_pairs(pop.sets.h) # update set_members and set_pairs\n pop.sets.h_bar = [abs(x) for x in pop.sets.h]\n pop.sets.h_base10 = [vectobase3(pop.sets.h[i,:]) for i in 1:pop.sets.N] \n pop.sets.h_bar_base10 = [vectobase3(pop.sets.h_bar[i,:]) for i in 1:pop.sets.N] \n pop.num_sets_changed += 1\n end\n if pop.strategies_changed == true\n # strategies are updated above; need to update strategies_base10\n pop.strategies_base10 = [2 * pop.strategies[i,1] + pop.strategies[i,2] for i in 1:pop.sets.N]\n pop.num_strategies_changed += 1\n end\n if pop.strategies_changed && pop.sets_changed\n pop.num_both_changed += 1\n end\n\n if pop.verbose println(\"\\nStrategies after updating:\\t $(pop.strategies)\") end\n if pop.verbose println(\"Set memberships after updating:\\t $(pop.sets.h)\") end\n if pop.verbose \n println(\"tracking: prev_learner = $(pop.prev_learner), strategies_changed = $(pop.strategies_changed), sets_changed = $(pop.sets_changed)\") \n end \nend\n\nfunction update_strategies!( pop::Population )\n # function to update strategy of learner based on role_model\n pop.sim.strategy_copy = copy(pop.strategies[pop.sim.learner,:]) # save a copy to track changes\n # copy suffices here because the assignments below replace elements of pop.sets.h with Int64 (immutable)\n\n if rand() < pop.game.u\n # strategy mutation occurs\n pop.strategies[pop.sim.learner,:] = rand(collect(0:1), 1, 2) # conditional case\n pop.num_random_strategies += 1\n pop.num_random_sa_flipped += (pop.sim.strategy_copy[1] != pop.strategies[pop.sim.learner,1])\n pop.num_random_sd_flipped += (pop.sim.strategy_copy[2] != pop.strategies[pop.sim.learner,2])\n if pop.verbose println(\"\\t\\tmutating $(pop.sim.learner) to strategy $(pop.strategies[pop.sim.learner,:])\") end\n else\n # learner imitates the strategy of role model\n pop.strategies[pop.sim.learner,:] = pop.strategies[pop.sim.role_model,:]\n if pop.verbose println(\"\\t\\tadopting $(pop.sim.role_model)'s strategy $(pop.strategies[pop.sim.role_model,:])\") end\n end\n pop.strategies_changed = (pop.sim.strategy_copy != pop.strategies[pop.sim.learner,:]) # track changes\nend\n\nfunction update_opinions!( pop::Population )\n # function to update set memberships / opinions of learner based on role_model\n pop.sim.sets_copy = copy(pop.sets.h[pop.sim.learner,:]) # save a copy to track changes\n # copy suffices here because the assignments below replace elements of pop.sets.h with Int64 (immutable)\n \n # with probability v, set mutation occurs\n if rand() < pop.game.v \n if rand() < 1 - pop.game.ϵ * pop.game.ps[pop.sets.affils[pop.sim.learner]] \n # with probability 1-p*ϵ, select opinions without bias\n # select a random arrangement of K opinions\n pop.sets.h[pop.sim.learner,:] = shuffle( vcat( zeros(Int64, pop.sets.M-pop.sets.K), rand([-1,1], pop.sets.K) ) )\n\n pop.num_random_opinions += 1\n pop.num_random_opinions_flipped += (pop.sim.sets_copy != pop.sets.h[ pop.sim.learner,: ]) # new\n if pop.verbose println(\"\\t\\tmutating $(pop.sim.learner) to random opinions $(pop.sets.h[pop.sim.learner,:])\") end\n else \n # with probability p*ϵ, select opinions with bias\n # select a random set of K issues, select opinions corresponding to party\n if pop.sets.affils[pop.sim.learner] == 1\n pop.sets.h[pop.sim.learner,:] = shuffle( vcat( zeros(Int64, pop.sets.M-pop.sets.K), -ones(Int64, pop.sets.K) ) )\n elseif pop.sets.affils[pop.sim.learner] == 2\n pop.sets.h[pop.sim.learner,:] = shuffle( vcat( zeros(Int64, pop.sets.M-pop.sets.K), ones(Int64, pop.sets.K) ) )\n end\n pop.num_biased_opinions += 1\n pop.num_biased_opinions_flipped += (pop.sim.sets_copy != pop.sets.h[ pop.sim.learner,: ]) # new\n if pop.verbose \n println(\"\\t\\t$(pop.sim.learner) is in party $(pop.sets.affils[ pop.sim.learner ]), mutating to biased opinions $(pop.sets.h[ pop.sim.learner,: ])\") \n end\n end\n else\n # with probability 1-v, learner imitates the strategy of role model\n pop.sets.h[ pop.sim.learner,: ] = pop.sets.h[ pop.sim.role_model,: ]\n if pop.verbose println(\"\\t\\tadopting $( pop.sim.role_model )'s set membership $(pop.sets.h[ pop.sim.role_model,: ])\") end\n end\n # h is updated above; need to update h_bar, sets_changed, set_members, set_pairs\n # pop.sets.set_members, pop.sets.set_pairs = set_members_and_pairs(pop.sets.h) # update set_members and set_pairs # moved up\n pop.sets_changed = (pop.sim.sets_copy != pop.sets.h[ pop.sim.learner,: ]) # track changes\nend\n\nfunction no_strategy_or_opinion_update!( pop::Population )\n # function to keep track of changes when no imitation/mutation occurs\n pop.strategies_changed = false # track changes\n pop.sets_changed = false\nend\n\n", "meta": {"hexsha": "f84f4ae1846608c249e274d776f4c13510a8ec9d", "size": 13358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simulate.jl", "max_stars_repo_name": "marikawakatsu/CooperationPolarization2", "max_stars_repo_head_hexsha": "4c2b8681352949e1e220beabfe8e0b10c8c0c2ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-24T02:02:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T01:57:50.000Z", "max_issues_repo_path": "src/simulate.jl", "max_issues_repo_name": "marikawakatsu/CooperationPolarization2", "max_issues_repo_head_hexsha": "4c2b8681352949e1e220beabfe8e0b10c8c0c2ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulate.jl", "max_forks_repo_name": "marikawakatsu/CooperationPolarization2", "max_forks_repo_head_hexsha": "4c2b8681352949e1e220beabfe8e0b10c8c0c2ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.3628691983, "max_line_length": 176, "alphanum_fraction": 0.6608025153, "num_tokens": 3475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23643120734596224}} {"text": "##### Get prognostic variable list\n\nimport ..BalanceLaws: prognostic_vars\n\nprognostic_vars(::DryModel) = ()\nprognostic_vars(::EquilMoist) = (TotalMoisture(),)\nprognostic_vars(::NonEquilMoist) =\n (TotalMoisture(), LiquidMoisture(), IceMoisture())\n\nprognostic_vars(::NoPrecipitation) = ()\nprognostic_vars(::RainModel) = (Rain(),)\nprognostic_vars(::RainSnowModel) = (Rain(), Snow())\n\nprognostic_vars(::NoTracers) = ()\nprognostic_vars(::NTracers{N}) where {N} = (Tracers{N}(),)\n\nprognostic_vars(m::AtmosModel) = (\n Mass(),\n Momentum(),\n Energy(),\n prognostic_vars(m.moisture)...,\n prognostic_vars(m.precipitation)...,\n prognostic_vars(m.tracers)...,\n prognostic_vars(m.turbconv)...,\n)\n", "meta": {"hexsha": "d9c897b3fffc8c3a4fbfb7b6fbfe782af09ef7d2", "size": 705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Atmos/Model/get_prognostic_vars.jl", "max_stars_repo_name": "christophernhill/ClimateMachine.jl", "max_stars_repo_head_hexsha": "702924d29c197f9cc0301691fa69ff0e8eb2a64f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Atmos/Model/get_prognostic_vars.jl", "max_issues_repo_name": "christophernhill/ClimateMachine.jl", "max_issues_repo_head_hexsha": "702924d29c197f9cc0301691fa69ff0e8eb2a64f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-07-21T16:27:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-10T22:50:13.000Z", "max_forks_repo_path": "src/Atmos/Model/get_prognostic_vars.jl", "max_forks_repo_name": "jm-c/CLIMA", "max_forks_repo_head_hexsha": "8e2ef08353183dbf6daaf3e5e12d3f5b5a1db0f9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1153846154, "max_line_length": 58, "alphanum_fraction": 0.6865248227, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23638273164247678}} {"text": "#\n# Powell.jl --\n#\n# Mike Powell's derivative free optimization methods for Julia.\n#\n# ----------------------------------------------------------------------------\n#\n# This file is part of OptimPack.jl which is licensed under the MIT\n# \"Expat\" License:\n#\n# Copyright (C) 2015, Éric Thiébaut.\n#\n# ----------------------------------------------------------------------------\n\n# Possible status values returned by COBYLA.\nconst COBYLA_INITIAL_ITERATE = convert(Cint, 2)\nconst COBYLA_ITERATE = convert(Cint, 1)\nconst COBYLA_SUCCESS = convert(Cint, 0)\nconst COBYLA_ROUNDING_ERRORS = convert(Cint, -1)\nconst COBYLA_TOO_MANY_EVALUATIONS = convert(Cint, -2)\nconst COBYLA_BAD_ADDRESS = convert(Cint, -3)\nconst COBYLA_CORRUPTED = convert(Cint, -4)\n\n# Get a textual explanation of the status returned by COBYLA.\nfunction cobyla_reason(status::Integer)\n ptr = ccall((:cobyla_reason, opklib), Ptr{UInt8}, (Cint,), status)\n if ptr == C_NULL\n error(\"unknown COBYLA status: \", status)\n end\n bytestring(ptr)\nend\n\n# Wrapper for the objective function in COBYLA, the actual objective\n# function is provided by the client data.\nfunction cobyla_objfun(n::Cptrdiff_t, m::Cptrdiff_t, x_::Ptr{Cdouble},\n c_::Ptr{Cdouble}, f_::Ptr{Any})\n x = pointer_to_array(x_, n)\n f = unsafe_pointer_to_objref(f_)\n fx::Cdouble = (m > 0 ? f(x, pointer_to_array(c_, m)) : f(x))\n return fx\nend\nconst cobyla_objfun_c = cfunction(cobyla_objfun, Cdouble,\n (Cptrdiff_t, Cptrdiff_t, Ptr{Cdouble},\n Ptr{Cdouble}, Ptr{Any}))\n\nfunction cobyla_check(n::Integer, m::Integer, rhobeg::Real, rhoend::Real)\n if n < 2\n \"bad number of variables\"\n elseif m < 0\n \"bad number of constraints\"\n elseif rhoend < 0 || rhoend > rhobeg\n \"bad trust region radius settings\"\n end\nend\n\nfunction cobyla!(f::Function, x::Vector{Cdouble},\n m::Integer, rhobeg::Real, rhoend::Real;\n verbose::Integer=0, maxeval::Integer=500)\n n = length(x)\n reason = cobyla_check(n, m, rhobeg, rhoend)\n reason == nothing || error(reason)\n w = Array(Cdouble, n*(3*n + 2*m + 11) + 4*m + 6)\n iact = Array(Cptrdiff_t, m + 1)\n maxfun = Cptrdiff_t[maxeval]\n status = ccall((:cobyla, opklib), Cint,\n (Cptrdiff_t, Cptrdiff_t, Ptr{Void}, Ptr{Any},\n Ptr{Cdouble}, Cdouble, Cdouble, Cptrdiff_t,\n Ptr{Cptrdiff_t}, Ptr{Cdouble}, Ptr{Cptrdiff_t}),\n n, m, cobyla_objfun_c, pointer_from_objref(f),\n x, rhobeg, rhoend, verbose, maxfun, w, iact)\n if status != COBYLA_SUCCESS\n error(cobyla_reason(status))\n end\n #return w[1]\nend\n\n# Context for reverse communication variant of COBYLA.\ntype CobylaContext\n ptr::Ptr{Void}\n n::Int\n m::Int\n rhobeg::Cdouble\n rhoend::Cdouble\n verbose::Int\n maxeval::Int\nend\n\n# Create a new reverse communication workspace for COBYLA algorithm.\n# A typical usage is:\n# ```\n# x = Array(Cdouble, n)\n# c = Array(Cdouble, m)\n# x[...] = ... # initial solution\n# ctx = cobyla_create(n, m, rhobeg, rhoend, verbose=1, maxeval=500)\n# status = cobyla_get_status(ctx)\n# while status == COBYLA_ITERATE\n# fx = ... # compute function value at X\n# c[...] = ... # compute constraints at X\n# status = cobyla_iterate(ctx, fx, x, c)\n# end\n# if status != COBYLA_SUCCESS\n# println(\"Something wrong occured in COBYLA: \", cobyla_reason(status))\n# end\n# ```\nfunction cobyla_create(n::Integer, m::Integer,\n rhobeg::Real, rhoend::Real;\n verbose::Integer=0, maxeval::Integer=500)\n reason = cobyla_check(n, m, rhobeg, rhoend)\n reason == nothing || error(reason)\n ptr = ccall((:cobyla_create, opklib), Ptr{Void},\n (Cptrdiff_t, Cptrdiff_t, Cdouble, Cdouble,\n Cptrdiff_t, Cptrdiff_t),\n n, m, rhobeg, rhoend, verbose, maxeval)\n if ptr == C_NULL\n reason = (errno() == Base.Errno.ENOMEM\n ? \"insufficient memory\"\n : \"unexpected error\")\n error(reason)\n end\n ctx = CobylaContext(ptr, n, m, rhobeg, rhoend, verbose, maxeval)\n finalizer(ctx, ctx -> ccall((:cobyla_delete, opklib), Void,\n (Ptr{Void},), ctx.ptr))\n return ctx\nend\n\n# Perform the next iteration of the reverse communication variant of the\n# COBYLA algorithm. On entry, the workspace status must be\n# `COBYLA_ITERATE`, `f` and `c` are the function value and the constraints\n# at `x`. On exit, the returned value (the new workspace status) is:\n# `COBYLA_ITERATE` if a new trial point has been stored in `x` and if user\n# is requested to compute the function value and the constraints on the new\n# point; `COBYLA_SUCCESS` if algorithm has converged and `x` has been set\n# with the variables at the solution (the corresponding function value can\n# be retrieved with `cobyla_get_last_f`); anything else indicates an error\n# (see `cobyla_reason` for an explanatory message).\nfunction cobyla_iterate(ctx::CobylaContext, f::Real, x::Vector{Cdouble},\n c::Vector{Cdouble})\n length(x) == ctx.n || error(\"bad number of variables\")\n length(c) == ctx.m || error(\"bad number of constraints\")\n ccall((:cobyla_iterate, opklib), Cint,\n (Ptr{Void}, Cdouble, Ptr{Cdouble}, Ptr{Cdouble}),\n ctx.ptr, f, x, c)\nend\n# The same but without constraints.\nfunction cobyla_iterate(ctx::CobylaContext, f::Real, x::Vector{Cdouble})\n length(x) == ctx.n || error(\"bad number of variables\")\n ctx.m == 0 || error(\"bad number of constraints\")\n ccall((:cobyla_iterate, opklib), Cint,\n (Ptr{Void}, Cdouble, Ptr{Cdouble}, Ptr{Void}),\n ctx.ptr, f, x, C_NULL)\nend\n\n# Restart COBYLA algorithm using the same parameters. The return value is\n# the new status of the algorithm, see `cobyla_get_status` for details.\nfunction cobyla_restart(ctx::CobylaContext)\n ccall((:cobyla_restart, opklib), Cint, (Ptr{Void},), ctx.ptr)\nend\n\n# Get the current status of the algorithm. Result is: `COBYLA_ITERATE` if\n# user is requested to compute F(X) and C(X); `COBYLA_SUCCESS` if algorithm\n# has converged; anything else indicates an error (see `cobyla_reason` for\n# an explanatory message).\nfunction cobyla_get_status(ctx::CobylaContext)\n ccall((:cobyla_get_status, opklib), Cint, (Ptr{Void},), ctx.ptr)\nend\n\n# Get the current number of function evaluations. Result is -1 if\n# something is wrong (e.g. CTX is NULL), nonnegative otherwise.\nfunction cobyla_get_nevals(ctx::CobylaContext)\n ccall((:cobyla_get_nevals, opklib), Cptrdiff_t, (Ptr{Void},), ctx.ptr)\nend\n\n# Get the current size of the trust region. Result is 0 if algorithm not\n# yet started (before first iteration), -1 if something is wrong (e.g. CTX\n# is NULL), strictly positive otherwise.\nfunction cobyla_get_rho(ctx::CobylaContext)\n ccall((:cobyla_get_rho, opklib), Cdouble, (Ptr{Void},), ctx.ptr)\nend\n\n# Get the last function value. Upon convergence of `cobyla_iterate`\n# (i.e. return with status `COBYLA_SUCCESS`), this value corresponds to the\n# function at the solution; otherwise, this value corresponds to the\n# previous set of variables.\nfunction cobyla_get_last_f(ctx::CobylaContext)\n ccall((:cobyla_get_last_f, opklib), Cdouble, (Ptr{Void},), ctx.ptr)\nend\n\n# Get a textual explanation of the current status.\ncobyla_get_reason(ctx::CobylaContext) = cobyla_reason(cobyla_get_status(ctx))\n\nfunction cobyla_test(revcom::Bool=false)\n # Beware that order of operations may affect the result (whithin\n # rounding errors). I have tried to keep the same ordering as F2C\n # which takes care of that, in particular when converting expressions\n # involving powers.\n prt(s) = println(\"\\n \"*s)\n for nprob in 1:10\n if nprob == 1\n # Minimization of a simple quadratic function of two variables.\n prt(\"Output from test problem 1 (Simple quadratic)\")\n n = 2\n m = 0\n xopt = Array(Cdouble, n)\n xopt[1] = -1.0\n xopt[2] = 0.0\n function ftest(x::Vector{Cdouble})\n r1 = x[1] + 1.0\n r2 = x[2]\n fc = 10.0*(r1*r1) + (r2*r2)\n return fc\n end\n elseif nprob == 2\n # Easy two dimensional minimization in unit circle.\n prt(\"Output from test problem 2 (2D unit circle calculation)\")\n n = 2\n m = 1\n xopt = Array(Cdouble, n)\n xopt[1] = sqrt(0.5)\n xopt[2] = -xopt[1]\n function ftest(x::Vector{Cdouble}, con::Vector{Cdouble})\n fc = x[1]*x[2]\n con[1] = 1.0 - x[1]*x[1] - x[2]*x[2]\n return fc\n end\n elseif nprob == 3\n # Easy three dimensional minimization in ellipsoid.\n prt(\"Output from test problem 3 (3D ellipsoid calculation)\")\n n = 3\n m = 1\n xopt = Array(Cdouble, n)\n xopt[1] = 1.0/sqrt(3.0)\n xopt[2] = 1.0/sqrt(6.0)\n xopt[3] = -0.33333333333333331\n function ftest(x::Vector{Cdouble}, con::Vector{Cdouble})\n fc = x[1]*x[2]*x[3]\n con[1] = 1.0 - (x[1]*x[1]) - 2.0*(x[2]*x[2]) - 3.0*(x[3]*x[3])\n return fc\n end\n elseif nprob == 4\n # Weak version of Rosenbrock's problem.\n prt(\"Output from test problem 4 (Weak Rosenbrock)\")\n n = 2\n m = 0\n xopt = Array(Cdouble, n)\n xopt[1] = -1.0\n xopt[2] = 1.0\n function ftest(x::Vector{Cdouble})\n r2 = x[1]\n r1 = r2*r2 - x[2]\n r3 = x[1] + 1.0\n fc = r1*r1 + r3*r3\n return fc\n end\n elseif nprob == 5\n # Intermediate version of Rosenbrock's problem.\n prt(\"Output from test problem 5 (Intermediate Rosenbrock)\")\n n = 2\n m = 0\n xopt = Array(Cdouble, n)\n xopt[1] = -1.0\n xopt[2] = 1.0\n function ftest(x::Vector{Cdouble})\n r2 = x[1]\n r1 = r2*r2 - x[2]\n r3 = x[1] + 1.0\n fc = r1*r1*10.0 + r3*r3\n return fc\n end\n elseif nprob == 6\n # This problem is taken from Fletcher's book Practical Methods\n # of Optimization and has the equation number (9.1.15).\n prt(\"Output from test problem 6 (Equation (9.1.15) in Fletcher)\")\n n = 2\n m = 2\n xopt = Array(Cdouble, n)\n xopt[1] = sqrt(0.5)\n xopt[2] = xopt[1]\n function ftest(x::Vector{Cdouble}, con::Vector{Cdouble})\n fc = -x[1] - x[2]\n r1 = x[1]\n con[1] = x[2] - r1*r1\n r1 = x[1]\n r2 = x[2]\n con[2] = 1.0 - r1*r1 - r2*r2\n return fc\n end\n elseif nprob == 7\n # This problem is taken from Fletcher's book Practical Methods\n # of Optimization and has the equation number (14.4.2).\n prt(\"Output from test problem 7 (Equation (14.4.2) in Fletcher)\")\n n = 3\n m = 3\n xopt = Array(Cdouble, n)\n xopt[1] = 0.0\n xopt[2] = -3.0\n xopt[3] = -3.0\n function ftest(x::Vector{Cdouble}, con::Vector{Cdouble})\n fc = x[3]\n con[1] = x[1]*5.0 - x[2] + x[3]\n r1 = x[1]\n r2 = x[2]\n con[2] = x[3] - r1*r1 - r2*r2 - x[2]*4.0\n con[3] = x[3] - x[1]*5.0 - x[2]\n return fc\n end\n elseif nprob == 8\n # This problem is taken from page 66 of Hock and Schittkowski's\n # book Test Examples for Nonlinear Programming Codes. It is\n # their test problem Number 43, and has the name Rosen-Suzuki.\n prt(\"Output from test problem 8 (Rosen-Suzuki)\")\n n = 4\n m = 3\n xopt = Array(Cdouble, n)\n xopt[1] = 0.0\n xopt[2] = 1.0\n xopt[3] = 2.0\n xopt[4] = -1.0\n function ftest(x::Vector{Cdouble}, con::Vector{Cdouble})\n r1 = x[1]\n r2 = x[2]\n r3 = x[3]\n r4 = x[4]\n fc = (r1*r1 + r2*r2 + r3*r3*2.0 + r4*r4 - x[1]*5.0\n - x[2]*5.0 - x[3]*21.0 + x[4]*7.0)\n r1 = x[1]\n r2 = x[2]\n r3 = x[3]\n r4 = x[4]\n con[1] = (8.0 - r1*r1 - r2*r2 - r3*r3 - r4*r4 - x[1]\n + x[2] - x[3] + x[4])\n r1 = x[1]\n r2 = x[2]\n r3 = x[3]\n r4 = x[4]\n con[2] = (10.0 - r1*r1 - r2*r2*2.0 - r3*r3 - r4*r4*2.0\n + x[1] + x[4])\n r1 = x[1]\n r2 = x[2]\n r3 = x[3]\n con[3] = (5.0 - r1*r1*2.0 - r2*r2 - r3*r3 - x[1]*2.0\n + x[2] + x[4])\n return fc\n end\n elseif nprob == 9\n # This problem is taken from page 111 of Hock and\n # Schittkowski's book Test Examples for Nonlinear Programming\n # Codes. It is their test problem Number 100.\n prt(\"Output from test problem 9 (Hock and Schittkowski 100)\")\n n = 7\n m = 4\n xopt = Array(Cdouble, n)\n xopt[1] = 2.330499\n xopt[2] = 1.951372\n xopt[3] = -0.4775414\n xopt[4] = 4.365726\n xopt[5] = -0.624487\n xopt[6] = 1.038131\n xopt[7] = 1.594227\n function ftest(x::Vector{Cdouble}, con::Vector{Cdouble})\n r1 = x[1] - 10.0\n r2 = x[2] - 12.0\n r3 = x[3]\n r3 *= r3\n r4 = x[4] - 11.0\n r5 = x[5]\n r5 *= r5\n r6 = x[6]\n r7 = x[7]\n r7 *= r7\n fc = (r1*r1 + r2*r2*5.0 + r3*r3 + r4*r4*3.0\n + r5*(r5*r5)*10.0 + r6*r6*7.0 + r7*r7\n - x[6]*4.0*x[7] - x[6]*10.0 - x[7]*8.0)\n r1 = x[1]\n r2 = x[2]\n r2 *= r2\n r3 = x[4]\n con[1] = (127.0 - r1*r1*2.0 - r2*r2*3.0 - x[3]\n - r3*r3*4.0 - x[5]*5.0)\n r1 = x[3]\n con[2] = (282.0 - x[1]*7.0 - x[2]*3.0 - r1*r1*10.0\n - x[4] + x[5])\n r1 = x[2]\n r2 = x[6]\n con[3] = (196.0 - x[1]*23.0 - r1*r1 - r2*r2*6.0\n + x[7]*8.0)\n r1 = x[1]\n r2 = x[2]\n r3 = x[3]\n con[4] = (r1*r1*-4.0 - r2*r2 + x[1]*3.0*x[2]\n - r3*r3*2.0 - x[6]*5.0 + x[7]*11.0)\n return fc\n end\n elseif nprob == 10\n # This problem is taken from page 415 of Luenberger's book\n # Applied Nonlinear Programming. It is to maximize the area of\n # a hexagon of unit diameter.\n prt(\"Output from test problem 10 (Hexagon area)\")\n n = 9\n m = 14\n xopt = Array(Cdouble, n)\n function ftest(x::Vector{Cdouble}, con::Vector{Cdouble})\n fc = -0.5*(x[1]*x[4] - x[2]*x[3] + x[3]*x[9] - x[5]*x[9]\n + x[5]*x[8] - x[6]*x[7])\n r1 = x[3]\n r2 = x[4]\n con[1] = 1.0 - r1*r1 - r2*r2\n r1 = x[9]\n con[2] = 1.0 - r1*r1\n r1 = x[5]\n r2 = x[6]\n con[3] = 1.0 - r1*r1 - r2*r2\n r1 = x[1]\n r2 = x[2] - x[9]\n con[4] = 1.0 - r1*r1 - r2*r2\n r1 = x[1] - x[5]\n r2 = x[2] - x[6]\n con[5] = 1.0 - r1*r1 - r2*r2\n r1 = x[1] - x[7]\n r2 = x[2] - x[8]\n con[6] = 1.0 - r1*r1 - r2*r2\n r1 = x[3] - x[5]\n r2 = x[4] - x[6]\n con[7] = 1.0 - r1*r1 - r2*r2\n r1 = x[3] - x[7]\n r2 = x[4] - x[8]\n con[8] = 1.0 - r1*r1 - r2*r2\n r1 = x[7]\n r2 = x[8] - x[9]\n con[9] = 1.0 - r1*r1 - r2*r2\n con[10] = x[1]*x[4] - x[2]*x[3]\n con[11] = x[3]*x[9]\n con[12] = -x[5]*x[9]\n con[13] = x[5]*x[8] - x[6]*x[7]\n con[14] = x[9]\n return fc\n end\n else\n error(\"bad problem number ($nprob)\")\n end\n\n x = Array(Cdouble, n)\n for icase in 1:2\n for i in 1:n\n x[i] = 1.0\n end\n rhobeg = 0.5\n rhoend = (icase == 2 ? 1e-4 : 0.001)\n if revcom\n # Test the reverse communication variant.\n c = (m > 0 ? Array(Cdouble, m) : nothing)\n ctx = cobyla_create(n, m, rhobeg, rhoend, verbose=1, maxeval=2000)\n status = cobyla_get_status(ctx)\n while status == COBYLA_ITERATE\n if m > 0\n # Some constraints.\n fx = ftest(x, c)\n status = cobyla_iterate(ctx, fx, x, c)\n else\n # No constraints.\n fx = ftest(x)\n status = cobyla_iterate(ctx, fx, x)\n end\n end\n if status != COBYLA_SUCCESS\n println(\"Something wrong occured in COBYLA: \", cobyla_reason(status))\n end\n else\n cobyla!(ftest, x, m, rhobeg, rhoend, verbose=1, maxeval=2000)\n end\n if nprob == 10\n tempa = x[1] + x[3] + x[5] + x[7]\n tempb = x[2] + x[4] + x[6] + x[8]\n tempc = 0.5/sqrt(tempa*tempa + tempb*tempb)\n tempd = tempc*sqrt(3.0)\n xopt[1] = tempd*tempa + tempc*tempb\n xopt[2] = tempd*tempb - tempc*tempa\n xopt[3] = tempd*tempa - tempc*tempb\n xopt[4] = tempd*tempb + tempc*tempa\n for i in 1:4\n xopt[i + 4] = xopt[i]\n end\n end\n temp = 0.0\n for i in 1:n\n r1 = x[i] - xopt[i]\n temp += r1*r1\n end\n @printf(\"\\n Least squares error in variables =%16.6E\\n\", sqrt(temp))\n end\n @printf(\" ------------------------------------------------------------------\\n\")\n end\nend\n\n# ----------------------------------------------------------------------------\n\n# Possible status values returned by NEWUOA.\nconst NEWUOA_INITIAL_ITERATE = convert(Cint, 2)\nconst NEWUOA_ITERATE = convert(Cint, 1)\nconst NEWUOA_SUCCESS = convert(Cint, 0)\nconst NEWUOA_BAD_NPT = convert(Cint, -1)\nconst NEWUOA_ROUNDING_ERRORS = convert(Cint, -2)\nconst NEWUOA_TOO_MANY_EVALUATIONS = convert(Cint, -3)\nconst NEWUOA_STEP_FAILED = convert(Cint, -4)\nconst NEWUOA_BAD_ADDRESS = convert(Cint, -5)\nconst NEWUOA_CORRUPTED = convert(Cint, -6)\n\n# Get a textual explanation of the status returned by NEWUOA.\nfunction newuoa_reason(status::Integer)\n ptr = ccall((:newuoa_reason, opklib), Ptr{UInt8}, (Cint,), status)\n if ptr == C_NULL\n error(\"unknown NEWUOA status: \", status)\n end\n bytestring(ptr)\nend\n\n# Wrapper for the objective function in NEWUOA, the actual objective\n# function is provided by the client data.\nfunction newuoa_objfun(n::Cptrdiff_t, x_::Ptr{Cdouble}, f_::Ptr{Any})\n x = pointer_to_array(x_, n)\n f = unsafe_pointer_to_objref(f_)\n fx::Cdouble = f(x)\n return fx\nend\nconst newuoa_objfun_c = cfunction(newuoa_objfun, Cdouble,\n (Cptrdiff_t, Ptr{Cdouble}, Ptr{Any}))\n\nfunction newuoa_check(n::Integer, npt::Integer, rhobeg::Real, rhoend::Real)\n if n < 2\n \"bad number of variables\"\n elseif npt < n + 2 || npt > div((n + 2)*(n + 1),2)\n \"NPT is not in the required interval\"\n elseif rhoend < 0 || rhoend > rhobeg\n \"bad trust region radius settings\"\n end\nend\n\nfunction newuoa!(f::Function, x::Vector{Cdouble},\n npt::Integer, rhobeg::Real, rhoend::Real;\n verbose::Integer=0, maxeval::Integer=500)\n n = length(x)\n reason = newuoa_check(n, npt, rhobeg, rhoend)\n reason == nothing || error(reason)\n w = Array(Cdouble, (npt + 13)*(npt + n) + div(3*n*(n + 3),2))\n status = ccall((:newuoa, opklib), Cint,\n (Cptrdiff_t, Cptrdiff_t, Ptr{Void}, Ptr{Any},\n Ptr{Cdouble}, Cdouble, Cdouble, Cptrdiff_t,\n Cptrdiff_t, Ptr{Cdouble}),\n n, npt, newuoa_objfun_c, pointer_from_objref(f),\n x, rhobeg, rhoend, verbose, maxeval, w)\n if status != NEWUOA_SUCCESS\n error(newuoa_reason(status))\n end\n return nothing\nend\n\n# Context for reverse communication variant of NEWUOA.\ntype NewuoaContext\n ptr::Ptr{Void}\n n::Int\n npt::Int\n rhobeg::Cdouble\n rhoend::Cdouble\n verbose::Int\n maxeval::Int\nend\n\n# Create a new reverse communication workspace for NEWUOA algorithm.\n# A typical usage is:\n# ```\n# x = Array(Cdouble, n)\n# x[...] = ... # initial solution\n# ctx = newuoa_create(n, npt, rhobeg, rhoend, verbose=0, maxeval=500)\n# status = newuoa_get_status(ctx)\n# while status == NEWUOA_ITERATE\n# fx = ... # compute function value at X\n# status = newuoa_iterate(ctx, fx, x)\n# end\n# if status != NEWUOA_SUCCESS\n# println(\"Something wrong occured in NEWUOA: \", newuoa_reason(status))\n# end\n# ```\nfunction newuoa_create(n::Integer, npt::Integer,\n rhobeg::Real, rhoend::Real;\n verbose::Integer=0, maxeval::Integer=500)\n reason = newuoa_check(n, npt, rhobeg, rhoend)\n reason == nothing || error(reason)\n ptr = ccall((:newuoa_create, opklib), Ptr{Void},\n (Cptrdiff_t, Cptrdiff_t, Cdouble, Cdouble,\n Cptrdiff_t, Cptrdiff_t),\n n, npt, rhobeg, rhoend, verbose, maxeval)\n if ptr == C_NULL\n reason = (errno() == Base.Errno.ENOMEM\n ? \"insufficient memory\"\n : \"unexpected error\")\n error(reason)\n end\n ctx = NewuoaContext(ptr, n, npt, rhobeg, rhoend, verbose, maxeval)\n finalizer(ctx, ctx -> ccall((:newuoa_delete, opklib), Void,\n (Ptr{Void},), ctx.ptr))\n return ctx\nend\n\n# Perform the next iteration of the reverse communication version of the\n# NEWUOA algorithm. On entry, the wokspace status must be\n# `NEWUOA_ITERATE`, `f` is the function value at `x`. On exit, the\n# returned value (the new wokspace status) is: `NEWUOA_ITERATE` if a new\n# trial point has been stored in `x` and if user is requested to compute\n# the function value for the new point; `NEWUOA_SUCCESS` if algorithm has\n# converged; anything else indicates an error (see `newuoa_reason` for an\n# explanatory message).\nfunction newuoa_iterate(ctx::NewuoaContext, f::Real, x::Vector{Cdouble})\n length(x) == ctx.n || error(\"bad number of variables\")\n ccall((:newuoa_iterate, opklib), Cint,\n (Ptr{Void}, Cdouble, Ptr{Cdouble}),\n ctx.ptr, f, x)\nend\n\n# Restart NEWUOA algorithm using the same parameters. The return value is the\n# new status of the algorithm, see `newuoa_get_status` for details.\nfunction newuoa_restart(ctx::NewuoaContext)\n ccall((:newuoa_restart, opklib), Cint, (Ptr{Void},), ctx.ptr)\nend\n\n# Get the current status of the algorithm. Result is: `NEWUOA_ITERATE` if\n# user is requested to compute F(X); `NEWUOA_SUCCESS` if algorithm has\n# converged; anything else indicates an error (see `newuoa_reason` for an\n# explanatory message).\nfunction newuoa_get_status(ctx::NewuoaContext)\n ccall((:newuoa_get_status, opklib), Cint, (Ptr{Void},), ctx.ptr)\nend\n\n# Get the current number of function evaluations. Result is -1 if\n# something is wrong (e.g. CTX is NULL), nonnegative otherwise.\nfunction newuoa_get_nevals(ctx::NewuoaContext)\n ccall((:newuoa_get_nevals, opklib), Cptrdiff_t, (Ptr{Void},), ctx.ptr)\nend\n\n# Get the current size of the trust region. Result is 0 if algorithm not\n# yet started (before first iteration), -1 if something is wrong (e.g. CTX\n# is NULL), strictly positive otherwise.\nfunction newuoa_get_rho(ctx::NewuoaContext)\n ccall((:newuoa_get_rho, opklib), Cdouble, (Ptr{Void},), ctx.ptr)\nend\n\nfunction newuoa_test(revcom::Bool=false)\n # The Chebyquad test problem (Fletcher, 1965) for N = 2,4,6 and 8, with\n # NPT = 2N+1.\n function ftest(x::Vector{Cdouble})\n n = length(x)\n np = n + 1\n y = Array(Cdouble, np, n)\n for j in 1:n\n y[1,j] = 1.0\n y[2,j] = x[j]*2.0 - 1.0\n end\n for i in 2:n\n for j in 1:n\n y[i+1,j] = y[2,j]*2.0*y[i,j] - y[i-1,j]\n end\n end\n f = 0.0\n iw = 1\n for i in 1:np\n sum = 0.0\n for j in 1:n\n sum += y[i,j]\n end\n sum /= n\n if iw > 0\n sum += 1.0/(i*i - 2*i)\n end\n iw = -iw\n f += sum*sum\n end\n return f\n end\n\n # Run the tests.\n rhoend = 1e-6\n for n = 2:2:8\n npt = 2*n + 1\n x = Array(Cdouble, n)\n for i in 1:n\n x[i] = i/(n + 1)\n end\n rhobeg = x[1]*0.2\n @printf(\"\\n\\n Results with N =%2d and NPT =%3d\\n\", n, npt)\n if revcom\n # Test the reverse communication variant.\n ctx = newuoa_create(n, npt, rhobeg, rhoend, verbose=2, maxeval=5000)\n status = newuoa_get_status(ctx)\n while status == NEWUOA_ITERATE\n fx = ftest(x)\n status = newuoa_iterate(ctx, fx, x)\n end\n if status != NEWUOA_SUCCESS\n println(\"Something wrong occured in NEWUOA: \", newuoa_reason(status))\n end\n else\n newuoa!(ftest, x, npt, rhobeg, rhoend, verbose=2, maxeval=5000)\n end\n end\nend\n\n# ----------------------------------------------------------------------------\n\nconst BOBYQA_SUCCESS = convert(Cint, 0)\nconst BOBYQA_BAD_NPT = convert(Cint, -1)\nconst BOBYQA_TOO_CLOSE = convert(Cint, -2)\nconst BOBYQA_ROUNDING_ERRORS = convert(Cint, -3)\nconst BOBYQA_TOO_MANY_EVALUATIONS = convert(Cint, -4)\nconst BOBYQA_STEP_FAILED = convert(Cint, -5)\n\nfunction bobyqa_reason(status::Integer)\n if status == BOBYQA_SUCCESS\n return \"algorithm converged\"\n elseif status == BOBYQA_BAD_NPT\n return \"NPT is not in the required interval\"\n elseif status == BOBYQA_TOO_CLOSE\n return \"insufficient space between the bounds\"\n elseif status == BOBYQA_ROUNDING_ERRORS\n return \"too much cancellation in a denominator\"\n elseif status == BOBYQA_TOO_MANY_EVALUATIONS\n return \"maximum number of function evaluations exceeded\"\n elseif status == BOBYQA_STEP_FAILED\n return \"a trust region step has failed to reduce quadratic approximation\"\n else\n return \"unknown BOBYQA status\"\n end\nend\n\n# Wrapper for the objective function in BOBYQA, the actual objective\n# function is provided by the client data.\nfunction bobyqa_objfun(n::Cptrdiff_t, x_::Ptr{Cdouble}, f_::Ptr{Any})\n x = pointer_to_array(x_, n)\n f = unsafe_pointer_to_objref(f_)\n fx::Cdouble = f(x)\n return fx\nend\nconst bobyqa_objfun_c = cfunction(bobyqa_objfun, Cdouble,\n (Cptrdiff_t, Ptr{Cdouble}, Ptr{Any}))\n\nfunction bobyqa!(f::Function, x::Vector{Cdouble},\n xl::Vector{Cdouble}, xu::Vector{Cdouble},\n rhobeg::Real, rhoend::Real;\n npt::Union{Integer,Void}=nothing,\n verbose::Integer=0, maxeval::Integer=500)\n n = length(x)\n length(xl) == n || error(\"bad length for inferior bound\")\n length(xu) == n || error(\"bad length for superior bound\")\n if npt == nothing\n npt = 2*n + 1\n end\n w = Array(Cdouble, (npt + 5)*(npt + n) + div(3*n*(n + 5),2))\n status = ccall((:bobyqa, opklib), Cint,\n (Cptrdiff_t, Cptrdiff_t, Ptr{Void}, Ptr{Any},\n Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},\n Cdouble, Cdouble, Cptrdiff_t, Cptrdiff_t,\n Ptr{Cdouble}),\n n, npt, bobyqa_objfun_c, pointer_from_objref(f),\n x, xl, xu, rhobeg, rhoend, verbose, maxeval, w)\n if status != BOBYQA_SUCCESS\n error(bobyqa_reason(status))\n end\n return w[1]\nend\n\nfunction bobyqa_test()\n # The test function.\n function f(x::Vector{Cdouble})\n fx = 0.0\n n = length(x)\n for i in 4:2:n\n for j in 2:2:i-2\n tempa = x[i - 1] - x[j - 1]\n tempb = x[i] - x[j]\n temp = tempa*tempa + tempb*tempb\n temp = max(temp,1e-6)\n fx += 1.0/sqrt(temp)\n end\n end\n return fx\n end\n\n # Run the tests.\n bdl = -1.0\n bdu = 1.0\n rhobeg = 0.1\n rhoend = 1e-6\n for m in (5,10)\n q = 2.0*pi/m\n n = 2*m\n x = Array(Cdouble, n)\n xl = Array(Cdouble, n)\n xu = Array(Cdouble, n)\n for i in 1:n\n xl[i] = bdl\n xu[i] = bdu\n end\n for jcase in 1:2\n if jcase == 2\n npt = 2*n + 1\n else\n npt = n + 6\n end\n @printf(\"\\n\\n 2D output with M =%4ld, N =%4ld and NPT =%4ld\\n\",\n m, n, npt)\n for j in 1:m\n temp = q*j\n x[2*j - 1] = cos(temp)\n x[2*j] = sin(temp)\n end\n fx = bobyqa!(f, x, xl, xu, rhobeg, rhoend, npt=npt, verbose=2, maxeval=500000)\n @printf(\"\\n***** least function value: %.15e\\n\", fx)\n end\n end\nend\n", "meta": {"hexsha": "909ce774d1ecf528964c4eb00178743aa337ba8e", "size": 30448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Powell.jl", "max_stars_repo_name": "JuliaPackageMirrors/OptimPack.jl", "max_stars_repo_head_hexsha": "1577ad0265efc46fcbab223becf5c667383a140d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Powell.jl", "max_issues_repo_name": "JuliaPackageMirrors/OptimPack.jl", "max_issues_repo_head_hexsha": "1577ad0265efc46fcbab223becf5c667383a140d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Powell.jl", "max_forks_repo_name": "JuliaPackageMirrors/OptimPack.jl", "max_forks_repo_head_hexsha": "1577ad0265efc46fcbab223becf5c667383a140d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2224938875, "max_line_length": 90, "alphanum_fraction": 0.51881897, "num_tokens": 9177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.23633853784694356}} {"text": "using Parameters, Random\nimport Distributions: logpdf, loglikelihood\n\nstruct Paired{T1,T2} <: ContinuousUnivariateDistribution\n d::T1\n parms::T2\nend\n\nPaired(;d, parms) = Paired(d, parms)\n\nloglikelihood(d::Paired, data::Array{<:NamedTuple,1}) = logpdf(d, data)\n\nfunction logpdf(d::Paired, data::Array{<:NamedTuple,1})\n LL = computeLL(data, d.parms; d=d.d)\n return LL\nend\n\nfunction sample_stimuli(stimuli, N)\n return stimuli[1:N]\nend\n\nfunction simulate(all_stimuli, fixed_parms, n_blocks, n_trials, deadline=5.0, isi=5.0; d)\n # sample unique stimului for the simulation\n stimuli = sample_stimuli(all_stimuli, n_trials)\n # initialize declarative memory\n chunks = [Chunk(word=:_,number=1)] |> empty!\n memory = Declarative(;memory=chunks)\n # create act-r object\n actr = ACTR(;declarative=memory, fixed_parms..., d)\n # preallocate data\n data = Array{NamedTuple,1}()\n # iterate through all blocks\n for block in 1:n_blocks\n # randomize stimulus order\n shuffle!(stimuli)\n temp = simulate_block(actr, stimuli, block, deadline, isi)\n push!(data, temp...)\n end\n return vcat(data...)\nend\n\nfunction simulate_block(actr, stimuli, block, deadline=5.0, isi=5.0)\n # initialize data for the current block\n data = Array{NamedTuple,1}()\n start_time = get_time(actr)\n for stimulus in stimuli\n temp = simulate_trial(actr, stimulus, block, deadline)\n push!(data, temp)\n # 5 second response deadline + additional 5 seconds\n start_time += (deadline + isi) \n set_time!(actr, start_time)\n end\n return data\nend\n\nfunction simulate_trial(actr, stimulus, block, deadline=5.0)\n N=0;L=0.0;recent=Float64[];retrieved=:failed;time_created=0.0\n trial_start = get_time(actr)\n # encode and conflict resolution time\n e_time = 0.085 + 0.05 + 0.05\n add_time!(actr, e_time)\n # retrieve paired associate based on word\n chunk = retrieve(actr; word=stimulus.word)\n # retrieval time \n r_time = compute_RT(actr, chunk)\n # add encoding time and retrieval time to reaction time\n rt = e_time + r_time + .05 + 0.300\n # interrupt retrieval if exceeds deadline\n if rt > deadline\n # set to truncated value\n rt = deadline\n # advance current time to deadline\n set_time!(actr, trial_start + deadline)\n retrieved = :truncated\n # retrieval info if no chunk is retrieved\n chunk = get_chunks(actr; stimulus...)\n if !isempty(chunk)\n # get chunk state at time of retrieval\n @unpack N,L,recent,time_created = chunk[1]\n recent = copy(recent)\n end\n elseif !isempty(chunk)\n # add retreival time to current time\n add_time!(actr, r_time)\n # next conflict resolution\n add_time!(actr, .05)\n retrieved = :retrieved\n # get chunk state at time of retrieval\n @unpack N,L,recent,time_created = chunk[1]\n recent = copy(recent)\n # add chunk if new, or update N and time stamps\n add_chunk!(actr; stimulus...)\n else\n # add retreival failure time to current time\n add_time!(actr, r_time)\n # next conflict resolution\n add_time!(actr, .05)\n # retrieval info if no chunk is retrieved\n chunk = get_chunks(actr; stimulus...)\n if !isempty(chunk)\n # get chunk state at time of retrieval\n @unpack N,L,recent,time_created = chunk[1]\n recent = copy(recent)\n end\n end\n # feedback is always presented after the deadline\n set_time!(actr, trial_start + deadline)\n # encode feedback\n add_time!(actr, 0.05 + 0.05 + 0.085)\n # add chunk: create new chunk if does not exist, otherwise increment N and add time stamp\n add_chunk!(actr; stimulus...)\n data = (stimulus=stimulus,N=N,L=L,block=block,time_created=time_created,\n recent=recent,rt=rt,retrieved=retrieved)\n return data\nend\n\nfunction computeLL(data, fixed_parms; d)\n chunk = Chunk(act=zero(d))\n # initialize declarative memory\n memory = Declarative(;memory=[chunk])\n # create ACTR object with declarative memory and parameters\n actr = ACTR(;declarative=memory, fixed_parms..., d)\n # extract parameters\n @unpack s,lf,τ,ter=actr.parms\n # do not add noise activation values\n actr.parms.noise = false\n σ = s * pi / sqrt(3)\n # initialize log likelihood\n LL = 0.0\n for k in data\n cur_time = k.L + k.time_created\n if k.retrieved == :retrieved\n # reproduce the memory state right before retrieval\n modify!(chunk; N=k.N, recent=k.recent, time_created=k.time_created)\n # compute activation\n compute_activation!(actr, chunk, cur_time)\n # adjust activation values for latency factor\n v = [chunk.act,τ] .- log(lf)\n # log normal race distribution object\n dist = LNR(-v, σ, ter)\n # compute log likelihood of retrieving chunk at time k.rt\n LL += logpdf(dist, 1, k.rt)\n elseif k.retrieved == :truncated\n # special case in which chunk has not been created yet\n if k.N == 0\n v = τ .- log(lf)\n # compute log likelihood of failing to respond within deadline\n LL += logccdf(LogNormal(-v, σ), 5)\n else\n # reproduce the memory state right before retrieval\n modify!(chunk; N=k.N, recent=k.recent, time_created=k.time_created)\n # compute activation\n compute_activation!(actr, chunk, cur_time)\n # adjust activation values for latency factor\n v = [chunk.act,τ] .- log(lf)\n # compute log likelihood of failing to respond within deadline\n LL += logccdf(LogNormal(-v[1], σ), 5) + logccdf(LogNormal(-v[2], σ), 5)\n end\n else\n # retrieval failure for novel pair\n if k.N == 0\n dist = LNR(-[τ-log(lf)], σ, ter)\n LL += logpdf(dist, 1, k.rt)\n else\n # reproduce the memory state immediately prior to retrieval\n modify!(chunk; N=k.N, recent=k.recent, time_created=k.time_created)\n # compute activation \n compute_activation!(actr, chunk, cur_time)\n # mean activation values\n v = [chunk.act,τ] .- log(lf)\n # log normal race distribution object\n dist = LNR(-v, σ, ter)\n # compute log likelihood of failing to retrieve chunk at time k.rt\n LL += logpdf(dist, 2, k.rt)\n end\n end\n end\n return LL\nend\n\nfunction show_learning(all_stimuli, parms, n_blocks=8, n_trials=20; d)\n data = simulate(all_stimuli, parms, n_blocks, n_trials; d)\n df = DataFrame(data)\n groups = groupby(df, [:block,:retrieved])\n return combine(groups, :rt=>mean=>:rt)\nend\n", "meta": {"hexsha": "fca37a7861e1e3784d31aa0a170ec08f7dccd051", "size": 6953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/Paired/Paired_Model.jl", "max_stars_repo_name": "itsdfish/ACTRFundamentalTools.jl", "max_stars_repo_head_hexsha": "0314b4a79c71712d36052a549f577dd4b4bfd065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-26T09:17:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T09:17:29.000Z", "max_issues_repo_path": "models/Paired/Paired_Model.jl", "max_issues_repo_name": "itsdfish/ACTRFundamentalTools.jl", "max_issues_repo_head_hexsha": "0314b4a79c71712d36052a549f577dd4b4bfd065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/Paired/Paired_Model.jl", "max_forks_repo_name": "itsdfish/ACTRFundamentalTools.jl", "max_forks_repo_head_hexsha": "0314b4a79c71712d36052a549f577dd4b4bfd065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1818181818, "max_line_length": 93, "alphanum_fraction": 0.6134042859, "num_tokens": 1785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23622817686374634}} {"text": "\n\"\"\"\nVoxel corner and edge indexing conventions\n\n Z\n |\n\n 5------5------6 Extra edges not drawn\n /| /| -----------\n 8 | 6 | - face diagonals\n / 9 / 10 - 13: 1 to 3\n 8------7------7 | - 14: 1 to 8\n | | | | - 15: 1 to 6\n | 1------1--|---2 -- Y - 16: 5 to 7\n 12 / 11 / - 17: 2 to 7\n | 4 | 2 - 18: 4 to 7\n |/ |/ - body diagonal\n 4------3------3 - 19: 1 to 7\n\n /\n X\n\"\"\"\n# this gets vectorized so we want to ensure it is the\n# same type as out vertex\n@inline function voxCrnrPos(::Type{PT}) where {PT}\n (PT(0, 0, 0),\n PT(0, 1, 0),\n PT(1, 1, 0),\n PT(1, 0, 0),\n PT(0, 0, 1),\n PT(0, 1, 1),\n PT(1, 1, 1),\n PT(1, 0, 1))\nend\n\nconst voxCrnrPosInt = voxCrnrPos(SVector{3,UInt8})\n\n# the voxel IDs at either end of the tetrahedra edges, by edge ID\nconst voxEdgeCrnrs = ((0x01, 0x02),\n (0x02, 0x03),\n (0x04, 0x03),\n (0x01, 0x04),\n (0x05, 0x06),\n (0x06, 0x07),\n (0x08, 0x07),\n (0x05, 0x08),\n (0x01, 0x05),\n (0x02, 0x06),\n (0x03, 0x07),\n (0x04, 0x08),\n (0x01, 0x03),\n (0x01, 0x08),\n (0x01, 0x06),\n (0x05, 0x07),\n (0x02, 0x07),\n (0x04, 0x07),\n (0x01, 0x07))\n\n# direction codes:\n# 0 => +x, 1 => +y, 2 => +z,\n# 3 => +xy, 4 => +xz, 5 => +yz, 6 => +xyz\nconst voxEdgeDir = (0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x02, 0x02, 0x02, 0x03, 0x04, 0x05, 0x03, 0x04, 0x05, 0x06)\n\n# For a pair of corner IDs, the edge ID joining them\n# 0 denotes a pair with no edge\nconst voxEdgeIx = ((0x00, 0x01, 0x0d, 0x04, 0x09, 0x0f, 0x13, 0x0e),\n (0x01, 0x00, 0x02, 0x00, 0x00, 0x0a, 0x11, 0x00),\n (0x0d, 0x02, 0x00, 0x03, 0x00, 0x00, 0x0b, 0x00),\n (0x04, 0x00, 0x03, 0x00, 0x00, 0x00, 0x12, 0x0c),\n (0x09, 0x00, 0x00, 0x00, 0x00, 0x05, 0x10, 0x08),\n (0x0f, 0x0a, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00),\n (0x13, 0x11, 0x0b, 0x12, 0x10, 0x06, 0x00, 0x07),\n (0x0e, 0x00, 0x00, 0x0c, 0x08, 0x00, 0x07, 0x00))\n\n# voxel corners that comprise each of the six tetrahedra\nconst subTets = ((0x01, 0x03, 0x02, 0x07),\n (0x01, 0x08, 0x04, 0x07),\n (0x01, 0x04, 0x03, 0x07),\n (0x01, 0x02, 0x06, 0x07),\n (0x01, 0x05, 0x08, 0x07),\n (0x01, 0x06, 0x05, 0x07))\n# tetrahedron corners for each edge (indices 1-4)\nconst tetEdgeCrnrs = ((0x01, 0x02),\n (0x02, 0x03),\n (0x01, 0x03),\n (0x01, 0x04),\n (0x02, 0x04),\n (0x03, 0x04))\n\n# triangle cases for a given tetrahedron edge code\nconst tetTri = ((0x01, 0x03, 0x04, 0x00, 0x00, 0x00),\n (0x01, 0x05, 0x02, 0x00, 0x00, 0x00),\n (0x03, 0x05, 0x02, 0x03, 0x04, 0x05),\n (0x02, 0x06, 0x03, 0x00, 0x00, 0x00),\n (0x01, 0x06, 0x04, 0x01, 0x02, 0x06),\n (0x01, 0x05, 0x06, 0x01, 0x06, 0x03),\n (0x04, 0x05, 0x06, 0x00, 0x00, 0x00),\n (0x04, 0x06, 0x05, 0x00, 0x00, 0x00),\n (0x01, 0x06, 0x05, 0x01, 0x03, 0x06),\n (0x01, 0x04, 0x06, 0x01, 0x06, 0x02),\n (0x02, 0x03, 0x06, 0x00, 0x00, 0x00),\n (0x03, 0x02, 0x05, 0x03, 0x05, 0x04),\n (0x01, 0x02, 0x05, 0x00, 0x00, 0x00),\n (0x01, 0x04, 0x03, 0x00, 0x00, 0x00))\n", "meta": {"hexsha": "f787da7bfe6cabf8c5f2dd21db3545aefefe4813", "size": 3996, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lut/mt.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Meshing.jl-e6723b4c-ebff-59f1-b4b7-d97aa5274f73", "max_stars_repo_head_hexsha": "ed185419fa4dd629faf61d179902a44125ab3502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-15T11:14:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-15T11:14:17.000Z", "max_issues_repo_path": "src/lut/mt.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Meshing.jl-e6723b4c-ebff-59f1-b4b7-d97aa5274f73", "max_issues_repo_head_hexsha": "654b8adcfde949dff8c6f8a64615e26d7329bace", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lut/mt.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Meshing.jl-e6723b4c-ebff-59f1-b4b7-d97aa5274f73", "max_forks_repo_head_hexsha": "654b8adcfde949dff8c6f8a64615e26d7329bace", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0571428571, "max_line_length": 133, "alphanum_fraction": 0.4126626627, "num_tokens": 1788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23622817686374634}} {"text": "export\n Event,\n EventList,\n AllEventList,\n getevent,\n getlastevent,\n pushevent!,\n samplelocalpath,\n quadpathpoly,\n pathmean,\n tmax\n\n\"\"\"\n AllowedVarType\n\nSyntactic sugar to make it explicit what variable types are handled in the\nlocal BPS (i.e, the type of the variables on each node of the factor graph).\nSee also, Event, EventList.\n\"\"\"\nconst AllowedVarType = Union{Real, Vector{<:Real}}\n\n\"\"\"\n Event{T <: AllowedVarType}\n\nEncapsulation of a local event: a tuple made out of (position, velocity, time)\nfor a node in the local BPS algorithm.\nSee also: `EventList`.\n\"\"\"\nstruct Event{T <: AllowedVarType}\n x::T\n v::T\n t::Real\nend\n\n\"\"\"\n EventList{T <: AllowedVarType}\n\nStorage for all events that happened for a variable in the local BPS.\nEach variable is stored explicitly (as opposed to storing a list of Event)\nso that the times can be traversed efficiently. The xs, vs must all have the\nsame type within the list.\nSee also: `Event`, `AllEventList`.\n\"\"\"\nmutable struct EventList{T <: AllowedVarType}\n xs::Vector{T} # coordinates\n vs::Vector{T} # associated velocities\n ts::Vector{Real} # associated times\nend\n\nfunction EventList(T::Type)\n @assert T <: AllowedVarType\n EventList(Vector{T}(undef, 0), Vector{T}(undef, 0), Vector{Real}(undef, 0))\nend\n\n\"\"\"\n AllEventList\n\nStorage for all the `EventList` objects corresponding to a factor graph in a\nlocal BPS setting. The element `evl` can be accessed by the variable index so\n`a.evl[k]` will return the eventlist associated with variable `k`. Note that\nthe different `EventList` may have different types (in particular, different\ndimensions). See also: `Event`, `EventList`.\n\"\"\"\nmutable struct AllEventList\n evl::Vector{EventList}\n types::Vector{DataType}\n function AllEventList(types::Vector{DataType})\n new([EventList(types[i]) for i ∈ 1:length(types)], types)\n end\nend\nAllEventList(T::DataType, nvars::Int) = AllEventList([T for i ∈ 1:nvars])\n\ntmax(aev::AllEventList) = maximum(aev.evl[i].ts[end] for i ∈ 1:length(aev.evl))\n\n\"\"\"\n getevent(evl, evidx)\n\nRetrieve a specfic event (at index `evidx`) in an `EventList` object `evl` and\nreturn it as an `Event` object.\nSee also: `Event`, `EventList`.\n\"\"\"\nfunction getevent(evl::EventList, evidx::Int)\n Event(evl.xs[evidx], evl.vs[evidx], evl.ts[evidx])\nend\n\n\"\"\"\n getlastevent(evl)\n\nRetrieve the last `Event` in an `EventList` object `evl`.\nSee also: `getevent`, `EventList`.\n\"\"\"\nfunction getlastevent(evl::EventList)\n Event(evl.xs[end], evl.vs[end], evl.ts[end])\nend\n\n\"\"\"\n pushevent!(evl, ev)\n\nAppend an `Event` object `ev` to an `EventList` object `evl`. The `Event`\nobject is unpacked and pushed to the vectors encapsulated by `evl`.\nSee also: `EventList`.\n\"\"\"\nfunction pushevent!(evl::EventList, ev::Event)\n push!(evl.xs, ev.x)\n push!(evl.vs, ev.v)\n push!(evl.ts, ev.t)\n evl\nend\n\n\"\"\"\n getlocalsegment(evl, j)\n\nRetrieve the `j`th event in an `EventList` object `evl` and return as a tuple\nthat event and the next event. If there is no next event (end of event list),\nan \"infinity event\" is returned (in order to allow extrapolation).\nSee also: `samplelocalpath`.\n\"\"\"\nfunction getlocalsegment(evl::EventList, j::Int)\n if j == length(evl.ts)\n return (getevent(evl,j), Event(NaN, NaN, Inf))\n end\n (getevent(evl,j), getevent(evl,j+1))\nend\n\n\"\"\"\n samplelocalpath(evl, t)\n\nSample x_k(t) given the corresponding `EventList` object `evl`. The times `t`\nmust be a list of sorted times (or a single positive time).\nSee also: `getlocalsegment`.\n\"\"\"\nfunction samplelocalpath(evl::EventList, t::AllowedTimeType)\n @assert issorted(t) \"list of times should be sorted\"\n ti = t[1]\n @assert ti >= 0.0 \"the first time should be greater than 0.0\"\n # find the starting local segment\n j = searchsortedlast(evl.ts, ti)\n # event and next event (describes the \"segment\")\n eva, evb = getlocalsegment(evl,j)\n # allocation of samples\n samples = Vector{typeof(eva.x)}(undef, length(t))\n # recursively work with local segments\n i=1\n while i<= length(t)\n ti = t[i]\n if ti <= evb.t\n # stay in the current segment\n samples[i] = eva.x + (ti - eva.t) * eva.v\n i += 1\n else\n # get the next segment\n j += searchsortedlast(evl.ts[j+1:end], ti)\n eva, evb = getlocalsegment(evl, j)\n end\n end\n samples\nend\nsamplelocalpath(evl::EventList, t::Real) = samplelocalpath(evl, [t])[1]\n\n\"\"\"\n quadpathpoly(evl, pol, T)\n\nIntegrate a polynomial on the elements along a path for a single node.\nSo if we are sampling in Rd and have phi(X)=Poly(xk), then we can integrate the\npolynomial along the path. Note that we can't do the same thing if phi(X) mixes\n2 or more nodes. See also syntactic sugar to perform the same operation on all\nnodes.\n\"\"\"\nfunction quadpathpoly(evl::EventList, pol::Poly, T::Real)\n dim = length(evl.xs[1])\n res = zeros(dim)\n nseg = searchsortedlast(evl.ts,T)\n for segidx = 1:nseg-1\n # for each segment in the path\n eva, evb = getlocalsegment(evl, segidx)\n # segment time, initial point and velocity\n tau = evb.t - eva.t\n xa = eva.x\n v = (evb.x - xa) / tau\n # integrate along that segment\n for d = 1:dim\n res[d] += polyint(polyval(pol,Poly([xa[d],v[d]])))(tau)\n end\n end\n # last segment\n eva = getevent(evl, nseg)\n # characteristics\n tau = T - eva.t\n for d = 1:dim\n res[d] += polyint(polyval(pol,Poly([eva.x[d],eva.v[d]])))(tau)\n end\n return res / T\nend\nfunction quadpathpoly(aev::AllEventList, pol::Poly, T::Real)\n res = Vector{Vector{<:Real}}(undef, length(aev.evl))\n for (d, evl) in enumerate(aev.evl)\n res[d] = quadpathpoly(evl, pol, T)\n end\n return res\n end\npathmean(evl::EventList, T::Real) = quadpathpoly(evl, Poly([0.0,1.0]), T)\npathmean(aev::AllEventList, T::Real) = quadpathpoly(aev, Poly([0.0,1.0]), T)\npathmean(aev::AllEventList) = pathmean(aev, tmax(aev))\n", "meta": {"hexsha": "be4e430f5606189448980c5b41c75005289b50a1", "size": 6053, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/local/event.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PDSampler.jl-f9d848e4-75a0-5321-a43a-fbaa97166838", "max_stars_repo_head_hexsha": "22bb24cc13cbba64f2f6ec3c1513773c5b8215ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2017-11-02T20:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T07:32:47.000Z", "max_issues_repo_path": "src/local/event.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PDSampler.jl-f9d848e4-75a0-5321-a43a-fbaa97166838", "max_issues_repo_head_hexsha": "22bb24cc13cbba64f2f6ec3c1513773c5b8215ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2017-04-06T20:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-13T11:59:13.000Z", "max_forks_repo_path": "src/local/event.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PDSampler.jl-f9d848e4-75a0-5321-a43a-fbaa97166838", "max_forks_repo_head_hexsha": "22bb24cc13cbba64f2f6ec3c1513773c5b8215ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:33:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-05T13:35:59.000Z", "avg_line_length": 29.6715686275, "max_line_length": 79, "alphanum_fraction": 0.6590120601, "num_tokens": 1807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2359099410213478}} {"text": "\"\"\"\r\nType for storing data acquired with a steady state response (SSR) experimental paradigm.\r\n\r\nIn addition to the functions available for all EEG types,\r\nthe SSR type supports:\r\n\r\n* `modulationrate()`\r\n\r\nThe following standard names are used when saving data to the processing dictionary.\r\n\r\n* `Name`: The identifier for the participant\r\n* `Side`: Side of stimulation\r\n* `Carrier_Frequency`: Carrier frequency of the stimulus\r\n* `Amplitude`: Amplitude of the stimulus\r\n* `epochs`: The epochs extracted from the recording\r\n* `sweeps`: The extracted sweeps from the recording\r\n\r\n#### Example\r\n\r\nPut an example here\r\n\r\n```julia\r\ns = read_SSR(\"filename\")\r\ns.modulationrate = 40.0391u\"Hz\"\r\ns = rereference(s, \"Cz\")\r\n```\r\n\r\n\"\"\"\r\nmutable struct SSR <: EEG\r\n data::Array\r\n sensors::Array{Sensor}\r\n triggers::Dict\r\n system_codes::Dict\r\n samplingrate::typeof(1.0u\"Hz\")\r\n modulationrate::typeof(1.0u\"Hz\")\r\n reference_channel::Array{AbstractString,1}\r\n file_path::AbstractString\r\n file_name::AbstractString\r\n processing::Dict\r\n header::Dict\r\nend\r\n\r\n\r\n#######################################\r\n#\r\n# SSR info\r\n#\r\n#######################################\r\n\r\n\r\n\r\n\r\n\"\"\"\r\nReturn the modulation rate of a steady state type.\r\nIf no type is provided, the modulation rate is returned as a floating point.\r\n\r\n#### Example\r\n\r\nReturn the modulation rate of a recording\r\n\r\n```julia\r\ns = read_SSR(filename)\r\nmodulationrate(s)\r\n```\r\n\"\"\"\r\nmodulationrate(t, s::SSR) = convert(t, ustrip(s.modulationrate))\r\nmodulationrate(s::SSR) = modulationrate(AbstractFloat, s)\r\n\r\n\r\n#######################################\r\n#\r\n# Show\r\n#\r\n#######################################\r\n\r\nimport Base.show\r\nfunction Base.show(io::IO, a::SSR)\r\n time_length = round.(size(a.data, 1) / samplingrate(a) / 60)\r\n println(\r\n io,\r\n \"SSR measurement of $time_length mins with $(size(a.data,2)) channels sampled at $(a.samplingrate)\",\r\n )\r\n println(io, \" Modulation frequency: $(a.modulationrate )\")\r\n\r\n if haskey(a.processing, \"Amplitude\")\r\n println(io, \" Stimulation amplitude: $(a.processing[\"Amplitude\"]) dB\")\r\n end\r\n if haskey(a.processing, \"Name\")\r\n println(io, \" Participant name: $(a.processing[\"Name\"] )\")\r\n end\r\n if haskey(a.processing, \"Side\")\r\n println(io, \" Stimulation side: $(a.processing[\"Side\"] )\")\r\n end\r\n if haskey(a.processing, \"Carrier_Frequency\")\r\n println(io, \" Carrier frequency: $(a.processing[\"Carrier_Frequency\"] ) Hz\")\r\n end\r\n\r\nend\r\n\r\n\r\n#######################################\r\n#\r\n# Helper functions\r\n#\r\n#######################################\r\n\r\nfunction assr_frequency(\r\n rounded_freq::Number;\r\n stimulation_samplingrate::Number = 32000,\r\n stimulation_frames_per_epoch::Number = 32768,\r\n)\r\n\r\n round.(rounded_freq / (stimulation_samplingrate / stimulation_frames_per_epoch)) *\r\n stimulation_samplingrate / stimulation_frames_per_epoch\r\nend\r\n\r\nfunction assr_frequency(rounded_freq::AbstractVector)\r\n\r\n [assr_frequency(f) for f in rounded_freq]\r\nend\r\n", "meta": {"hexsha": "6c0821ebcf8582ecc1123eca2626a1bd1d769e0b", "size": 3050, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/types/SSR/SSR.jl", "max_stars_repo_name": "behinger/Neuroimaging.jl", "max_stars_repo_head_hexsha": "0bed495b40cced7f1945931f26305b809cf0b501", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/types/SSR/SSR.jl", "max_issues_repo_name": "behinger/Neuroimaging.jl", "max_issues_repo_head_hexsha": "0bed495b40cced7f1945931f26305b809cf0b501", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types/SSR/SSR.jl", "max_forks_repo_name": "behinger/Neuroimaging.jl", "max_forks_repo_head_hexsha": "0bed495b40cced7f1945931f26305b809cf0b501", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2066115702, "max_line_length": 109, "alphanum_fraction": 0.6193442623, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23589574284857076}} {"text": "include(\"DGFVModel_kernels.jl\")\nstruct DGFVModel{BL, G, FVR, NFND, NFD, GNF, AS, DS, HDS, D, DD, MD, GF, TF} <:\n SpaceDiscretization\n balance_law::BL\n grid::G\n fv_reconstruction::FVR\n numerical_flux_first_order::NFND\n numerical_flux_second_order::NFD\n numerical_flux_gradient::GNF\n state_auxiliary::AS\n state_gradient_flux::DS\n states_higher_order::HDS\n direction::D\n diffusion_direction::DD\n modeldata::MD\n gradient_filter::GF\n tendency_filter::TF\n check_for_crashes::Bool\nend\n\nfunction DGFVModel(\n balance_law,\n grid,\n fv_reconstruction,\n numerical_flux_first_order,\n numerical_flux_second_order,\n numerical_flux_gradient;\n fill_nan = false,\n check_for_crashes = false,\n state_auxiliary = create_state(\n balance_law,\n grid,\n Auxiliary(),\n fill_nan = fill_nan,\n ),\n state_gradient_flux = create_state(balance_law, grid, GradientFlux()),\n states_higher_order = (\n create_state(balance_law, grid, GradientLaplacian()),\n create_state(balance_law, grid, Hyperdiffusive()),\n ),\n direction = EveryDirection(),\n diffusion_direction = direction,\n modeldata = nothing,\n gradient_filter = nothing,\n tendency_filter = nothing,\n)\n # Make sure we are FVM in the vertical\n @assert polynomialorders(grid)[end] == 0\n @assert isstacked(grid.topology)\n state_auxiliary =\n init_state(state_auxiliary, balance_law, grid, direction, Auxiliary())\n DGFVModel(\n balance_law,\n grid,\n fv_reconstruction,\n numerical_flux_first_order,\n numerical_flux_second_order,\n numerical_flux_gradient,\n state_auxiliary,\n state_gradient_flux,\n states_higher_order,\n direction,\n diffusion_direction,\n modeldata,\n gradient_filter,\n tendency_filter,\n check_for_crashes,\n )\nend\n\n\"\"\"\n (dgfvm::DGFVModel)(tendency, state_prognostic, _, t, α, β)\n\nUses spectral element discontinuous Galerkin in the horizontal and finite volume\nin the vertical to compute the tendency.\n\nComputes the tendency terms compatible with `IncrementODEProblem`\n\n tendency .= α .* dQdt(state_prognostic, p, t) .+ β .* tendency\n\nThe 4-argument form will just compute\n\n tendency .= dQdt(state_prognostic, p, t)\n\"\"\"\nfunction (dgfvm::DGFVModel)(tendency, state_prognostic, _, t, α, β)\n device = array_device(state_prognostic)\n\n FT = eltype(state_prognostic)\n num_state_prognostic = number_states(dgfvm.balance_law, Prognostic())\n num_state_gradient_flux = number_states(dgfvm.balance_law, GradientFlux())\n @assert 0 == number_states(dgfvm.balance_law, Hyperdiffusive())\n num_state_tendency = size(tendency, 2)\n\n if num_state_prognostic < num_state_tendency && β != 1\n # If we don't operate on the full state, then we need to scale here instead of volume_tendency!\n tendency .*= β\n β = β != 0 # if β==0 then we can avoid the memory load in volume_tendency!\n end\n\n communicate =\n !(\n isstacked(dgfvm.grid.topology) &&\n typeof(dgfvm.direction) <: VerticalDirection\n )\n\n update_auxiliary_state!(\n dgfvm,\n dgfvm.balance_law,\n state_prognostic,\n t,\n dgfvm.grid.topology.realelems,\n )\n\n exchange_state_gradient_flux = NoneEvent()\n exchange_state_prognostic = NoneEvent()\n\n comp_stream = Event(device)\n\n if communicate\n exchange_state_prognostic = MPIStateArrays.begin_ghost_exchange!(\n state_prognostic;\n dependencies = comp_stream,\n )\n end\n\n if num_state_gradient_flux > 0\n ########################\n # Gradient Computation #\n ########################\n\n comp_stream = launch_volume_gradients!(\n dgfvm,\n state_prognostic,\n t;\n dependencies = comp_stream,\n )\n\n comp_stream = launch_interface_gradients!(\n dgfvm,\n state_prognostic,\n t;\n surface = :interior,\n dependencies = comp_stream,\n )\n\n if communicate\n exchange_state_prognostic = MPIStateArrays.end_ghost_exchange!(\n state_prognostic;\n dependencies = exchange_state_prognostic,\n check_for_crashes = dgfvm.check_for_crashes,\n )\n\n # Update_aux may start asynchronous work on the compute device and\n # we synchronize those here through a device event.\n checked_wait(\n device,\n exchange_state_prognostic,\n nothing,\n dgfvm.check_for_crashes,\n )\n update_auxiliary_state!(\n dgfvm,\n dgfvm.balance_law,\n state_prognostic,\n t,\n dgfvm.grid.topology.ghostelems,\n )\n exchange_state_prognostic = Event(device)\n end\n\n comp_stream = launch_interface_gradients!(\n dgfvm,\n state_prognostic,\n t;\n surface = :exterior,\n dependencies = (comp_stream, exchange_state_prognostic),\n )\n\n if dgfvm.gradient_filter !== nothing\n comp_stream = Filters.apply_async!(\n dgfvm.state_gradient_flux,\n 1:num_state_gradient_flux,\n dgfvm.grid,\n dgfvm.gradient_filter;\n dependencies = comp_stream,\n )\n end\n\n\n if communicate\n if num_state_gradient_flux > 0\n exchange_state_gradient_flux =\n MPIStateArrays.begin_ghost_exchange!(\n dgfvm.state_gradient_flux,\n dependencies = comp_stream,\n )\n end\n end\n\n if num_state_gradient_flux > 0\n # Update_aux_diffusive may start asynchronous work on the compute device\n # and we synchronize those here through a device event.\n checked_wait(device, comp_stream, nothing, dgfvm.check_for_crashes)\n update_auxiliary_state_gradient!(\n dgfvm,\n dgfvm.balance_law,\n state_prognostic,\n t,\n dgfvm.grid.topology.realelems,\n )\n comp_stream = Event(device)\n end\n end\n\n ###################\n # RHS Computation #\n ###################\n comp_stream = launch_volume_tendency!(\n dgfvm,\n tendency,\n state_prognostic,\n t,\n α,\n β;\n dependencies = comp_stream,\n )\n\n comp_stream = launch_interface_tendency!(\n dgfvm,\n tendency,\n state_prognostic,\n t,\n α,\n β;\n surface = :interior,\n dependencies = comp_stream,\n )\n\n if communicate\n if num_state_gradient_flux > 0\n exchange_state_gradient_flux = MPIStateArrays.end_ghost_exchange!(\n dgfvm.state_gradient_flux;\n dependencies = exchange_state_gradient_flux,\n check_for_crashes = dgfvm.check_for_crashes,\n )\n\n # Update_aux_diffusive may start asynchronous work on the\n # compute device and we synchronize those here through a device\n # event.\n checked_wait(\n device,\n exchange_state_gradient_flux,\n nothing,\n dgfvm.check_for_crashes,\n )\n update_auxiliary_state_gradient!(\n dgfvm,\n dgfvm.balance_law,\n state_prognostic,\n t,\n dgfvm.grid.topology.ghostelems,\n )\n exchange_state_gradient_flux = Event(device)\n else\n exchange_state_prognostic = MPIStateArrays.end_ghost_exchange!(\n state_prognostic;\n dependencies = exchange_state_prognostic,\n check_for_crashes = dgfvm.check_for_crashes,\n )\n\n # Update_aux may start asynchronous work on the compute device and\n # we synchronize those here through a device event.\n checked_wait(\n device,\n exchange_state_prognostic,\n nothing,\n dgfvm.check_for_crashes,\n )\n update_auxiliary_state!(\n dgfvm,\n dgfvm.balance_law,\n state_prognostic,\n t,\n dgfvm.grid.topology.ghostelems,\n )\n exchange_state_prognostic = Event(device)\n end\n end\n\n comp_stream = launch_interface_tendency!(\n dgfvm,\n tendency,\n state_prognostic,\n t,\n α,\n β;\n surface = :exterior,\n dependencies = (\n comp_stream,\n exchange_state_prognostic,\n exchange_state_gradient_flux,\n # XXX: This is disabled until FVM with hyperdiffusion for DG is implemented: exchange_Qhypervisc_grad,\n ),\n )\n\n if dgfvm.tendency_filter !== nothing\n comp_stream = Filters.apply_async!(\n tendency,\n 1:num_state_tendency,\n dgfvm.grid,\n dgfvm.tendency_filter;\n dependencies = comp_stream,\n )\n end\n\n # The synchronization here through a device event prevents CuArray based and\n # other default stream kernels from launching before the work scheduled in\n # this function is finished.\n checked_wait(device, comp_stream, nothing, dgfvm.check_for_crashes)\nend\n\nfunction fvm_balance!(\n balance_func,\n m::BalanceLaw,\n state_auxiliary::MPIStateArray,\n grid,\n)\n device = array_device(state_auxiliary)\n\n\n dim = dimensionality(grid)\n N = polynomialorders(grid)\n Nq = N .+ 1\n Nqj = dim == 2 ? 1 : Nq[2]\n\n topology = grid.topology\n elems = topology.elems\n nelem = length(elems)\n nvertelem = topology.stacksize\n horzelems = fld1(first(elems), nvertelem):fld1(last(elems), nvertelem)\n\n event = Event(device)\n event = kernel_fvm_balance!(device, (Nq[1], Nqj))(\n balance_func,\n m,\n Val(nvertelem),\n state_auxiliary.data,\n grid.vgeo,\n horzelems;\n ndrange = (length(horzelems) * Nq[1], Nqj),\n dependencies = (event,),\n )\n wait(device, event)\nend\n", "meta": {"hexsha": "dd2464b1dc96e92427088ed7c3dc8e9e19581ad5", "size": 10395, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Numerics/DGMethods/DGFVModel.jl", "max_stars_repo_name": "ErikQQY/ClimateMachine.jl", "max_stars_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 256, "max_stars_repo_stars_event_min_datetime": "2020-05-06T08:03:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:01:20.000Z", "max_issues_repo_path": "src/Numerics/DGMethods/DGFVModel.jl", "max_issues_repo_name": "ErikQQY/ClimateMachine.jl", "max_issues_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1174, "max_issues_repo_issues_event_min_datetime": "2020-05-06T16:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T17:51:13.000Z", "max_forks_repo_path": "src/Numerics/DGMethods/DGFVModel.jl", "max_forks_repo_name": "ErikQQY/ClimateMachine.jl", "max_forks_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2020-05-08T02:28:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T22:44:56.000Z", "avg_line_length": 29.2816901408, "max_line_length": 114, "alphanum_fraction": 0.5889369889, "num_tokens": 2298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2358912139196506}} {"text": "module Inference\n\nusing ..Core\nusing ..Utilities\nusing DynamicPPL: Metadata, _tail, VarInfo, TypedVarInfo, \n islinked, invlink!, getlogp, tonamedtuple, VarName, getsym, vectorize, \n settrans!, _getvns, getdist, CACHERESET,\n Model, Sampler, SampleFromPrior, SampleFromUniform,\n Selector, DefaultContext, PriorContext,\n LikelihoodContext, MiniBatchContext, set_flag!, unset_flag!, NamedDist, NoDist,\n getspace, inspace\nusing Distributions, Libtask, Bijectors\nusing DistributionsAD: VectorOfMultivariate\nusing LinearAlgebra\nusing ..Turing: PROGRESS, Turing\nusing StatsFuns: logsumexp\nusing Random: AbstractRNG\nusing DynamicPPL\nusing AbstractMCMC: AbstractModel, AbstractSampler\nusing DocStringExtensions: TYPEDEF, TYPEDFIELDS\n\nimport AbstractMCMC\nimport AdvancedHMC; const AHMC = AdvancedHMC\nimport AdvancedMH; const AMH = AdvancedMH\nimport AdvancedPS\nimport BangBang\nimport ..Core: getchunksize, getADbackend\nimport DynamicPPL: get_matching_type,\n VarName, _getranges, _getindex, getval, _getvns\nimport EllipticalSliceSampling\nimport Random\nimport MCMCChains\nimport StatsBase: predict\n\nexport InferenceAlgorithm,\n Hamiltonian,\n GibbsComponent,\n StaticHamiltonian,\n AdaptiveHamiltonian,\n SampleFromUniform,\n SampleFromPrior,\n MH,\n ESS,\n Emcee,\n Gibbs, # classic sampling\n GibbsConditional,\n HMC,\n SGLD,\n SGHMC,\n HMCDA,\n NUTS, # Hamiltonian-like sampling\n DynamicNUTS,\n IS,\n SMC,\n CSMC,\n PG,\n Prior,\n assume,\n dot_assume,\n observe,\n dot_observe,\n resume,\n predict,\n isgibbscomponent\n\n#######################\n# Sampler abstraction #\n#######################\nabstract type AbstractAdapter end\nabstract type InferenceAlgorithm end\nabstract type ParticleInference <: InferenceAlgorithm end\nabstract type Hamiltonian{AD} <: InferenceAlgorithm end\nabstract type StaticHamiltonian{AD} <: Hamiltonian{AD} end\nabstract type AdaptiveHamiltonian{AD} <: Hamiltonian{AD} end\n\ngetchunksize(::Type{<:Hamiltonian{AD}}) where AD = getchunksize(AD)\ngetADbackend(::Hamiltonian{AD}) where AD = AD()\n\n# Algorithm for sampling from the prior\nstruct Prior <: InferenceAlgorithm end\n\n\"\"\"\n mh_accept(logp_current::Real, logp_proposal::Real, log_proposal_ratio::Real)\n\nDecide if a proposal ``x'`` with log probability ``\\\\log p(x') = logp_proposal`` and\nlog proposal ratio ``\\\\log k(x', x) - \\\\log k(x, x') = log_proposal_ratio`` in a\nMetropolis-Hastings algorithm with Markov kernel ``k(x_t, x_{t+1})`` and current state\n``x`` with log probability ``\\\\log p(x) = logp_current`` is accepted by evaluating the\nMetropolis-Hastings acceptance criterion\n```math\n\\\\log U \\\\leq \\\\log p(x') - \\\\log p(x) + \\\\log k(x', x) - \\\\log k(x, x')\n```\nfor a uniform random number ``U \\\\in [0, 1)``.\n\"\"\"\nfunction mh_accept(logp_current::Real, logp_proposal::Real, log_proposal_ratio::Real)\n # replacing log(rand()) with -randexp() yields test errors\n return log(rand()) + logp_current ≤ logp_proposal + log_proposal_ratio\nend\n\n######################\n# Default Transition #\n######################\n\nstruct Transition{T, F<:AbstractFloat}\n θ :: T\n lp :: F\nend\n\nfunction Transition(vi::AbstractVarInfo, nt::NamedTuple=NamedTuple())\n theta = merge(tonamedtuple(vi), nt)\n lp = getlogp(vi)\n return Transition{typeof(theta), typeof(lp)}(theta, lp)\nend\n\nmetadata(t::Transition) = (lp = t.lp,)\n\nDynamicPPL.getlogp(t::Transition) = t.lp\n\n# Metadata of VarInfo object\nmetadata(vi::AbstractVarInfo) = (lp = getlogp(vi),)\n\n#########################################\n# Default definitions for the interface #\n#########################################\n\nfunction AbstractMCMC.sample(\n model::AbstractModel,\n alg::InferenceAlgorithm,\n N::Integer;\n kwargs...\n)\n return AbstractMCMC.sample(Random.GLOBAL_RNG, model, alg, N; kwargs...)\nend\n\nfunction AbstractMCMC.sample(\n rng::AbstractRNG,\n model::AbstractModel,\n alg::InferenceAlgorithm,\n N::Integer;\n kwargs...\n)\n return AbstractMCMC.sample(rng, model, Sampler(alg, model), N; kwargs...)\nend\n\nfunction AbstractMCMC.sample(\n rng::AbstractRNG,\n model::AbstractModel,\n sampler::Sampler{<:InferenceAlgorithm},\n N::Integer;\n chain_type=MCMCChains.Chains,\n resume_from=nothing,\n progress=PROGRESS[],\n kwargs...\n)\n if resume_from === nothing\n return AbstractMCMC.mcmcsample(rng, model, sampler, N;\n chain_type=chain_type, progress=progress, kwargs...)\n else\n return resume(resume_from, N; chain_type=chain_type, progress=progress, kwargs...)\n end\nend\n\nfunction AbstractMCMC.sample(\n rng::AbstractRNG,\n model::AbstractModel,\n alg::Prior,\n N::Integer;\n chain_type=MCMCChains.Chains,\n resume_from=nothing,\n progress=PROGRESS[],\n kwargs...\n)\n if resume_from === nothing\n return AbstractMCMC.mcmcsample(rng, model, SampleFromPrior(), N;\n chain_type=chain_type, progress=progress, kwargs...)\n else\n return resume(resume_from, N; chain_type=chain_type, progress=progress, kwargs...)\n end\nend\n\nfunction AbstractMCMC.sample(\n model::AbstractModel,\n alg::InferenceAlgorithm,\n parallel::AbstractMCMC.AbstractMCMCParallel,\n N::Integer,\n n_chains::Integer;\n kwargs...\n)\n return AbstractMCMC.sample(Random.GLOBAL_RNG, model, alg, parallel, N, n_chains;\n kwargs...)\nend\n\nfunction AbstractMCMC.sample(\n rng::AbstractRNG,\n model::AbstractModel,\n alg::InferenceAlgorithm,\n parallel::AbstractMCMC.AbstractMCMCParallel,\n N::Integer,\n n_chains::Integer;\n kwargs...\n)\n return AbstractMCMC.sample(rng, model, Sampler(alg, model), parallel, N, n_chains;\n kwargs...)\nend\n\nfunction AbstractMCMC.sample(\n rng::AbstractRNG,\n model::AbstractModel,\n sampler::Sampler{<:InferenceAlgorithm},\n parallel::AbstractMCMC.AbstractMCMCParallel,\n N::Integer,\n n_chains::Integer;\n chain_type=MCMCChains.Chains,\n progress=PROGRESS[],\n kwargs...\n)\n return AbstractMCMC.mcmcsample(rng, model, sampler, parallel, N, n_chains;\n chain_type=chain_type, progress=progress, kwargs...)\nend\n\nfunction AbstractMCMC.sample(\n rng::AbstractRNG,\n model::AbstractModel,\n alg::Prior,\n parallel::AbstractMCMC.AbstractMCMCParallel,\n N::Integer,\n n_chains::Integer;\n chain_type=MCMCChains.Chains,\n progress=PROGRESS[],\n kwargs...\n)\n return AbstractMCMC.sample(rng, model, SampleFromPrior(), parallel, N, n_chains;\n chain_type=chain_type, progress=progress, kwargs...)\nend\n\n##########################\n# Chain making utilities #\n##########################\n\n\"\"\"\n getparams(t)\n\nReturn a named tuple of parameters.\n\"\"\"\ngetparams(t) = t.θ\ngetparams(t::VarInfo) = tonamedtuple(TypedVarInfo(t))\n\nfunction _params_to_array(ts::Vector)\n names = Vector{Symbol}()\n # Extract the parameter names and values from each transition.\n dicts = map(ts) do t\n nms, vs = flatten_namedtuple(getparams(t))\n for nm in nms\n if !(nm in names)\n push!(names, nm)\n end\n end\n # Convert the names and values to a single dictionary.\n return Dict(nms[j] => vs[j] for j in 1:length(vs))\n end\n # names = collect(names_set)\n vals = [get(dicts[i], key, missing) for i in eachindex(dicts), \n (j, key) in enumerate(names)]\n\n return names, vals\nend\n\nfunction flatten_namedtuple(nt::NamedTuple)\n names_vals = mapreduce(vcat, keys(nt)) do k\n v = nt[k]\n if length(v) == 1\n return [(Symbol(k), v)]\n else\n return mapreduce(vcat, zip(v[1], v[2])) do (vnval, vn)\n return collect(FlattenIterator(vn, vnval))\n end\n end\n end\n return [vn[1] for vn in names_vals], [vn[2] for vn in names_vals]\nend\n\nfunction get_transition_extras(ts::AbstractVector{<:VarInfo})\n valmat = reshape([getlogp(t) for t in ts], :, 1)\n return [:lp], valmat\nend\n\nfunction get_transition_extras(ts::AbstractVector)\n # Extract all metadata.\n extra_data = map(metadata, ts)\n return names_values(extra_data)\nend\n\nfunction names_values(extra_data::AbstractVector{<:NamedTuple{names}}) where names\n values = [getfield(data, name) for data in extra_data, name in names]\n return collect(names), values\nend\n\nfunction names_values(extra_data::AbstractVector{<:NamedTuple})\n # Obtain all parameter names.\n names_set = Set(Symbol[])\n for data in extra_data\n for name in names(data)\n push!(extra_names_set, name)\n end\n end\n extra_names = collect(extra_names_set)\n\n # Extract all values as matrix.\n values = [\n hasfield(data, name) ? missing : getfield(data, name)\n for data in extra_data, name in extra_names\n ]\n\n return extra_names, values\nend\n\ngetlogevidence(transitions, sampler, state) = missing\n\n# Default MCMCChains.Chains constructor.\n# This is type piracy (at least for SampleFromPrior).\nfunction AbstractMCMC.bundle_samples(\n ts::Vector,\n model::AbstractModel,\n spl::Union{Sampler{<:InferenceAlgorithm},SampleFromPrior},\n state,\n chain_type::Type{MCMCChains.Chains};\n save_state = false,\n kwargs...\n)\n # Convert transitions to array format.\n # Also retrieve the variable names.\n nms, vals = _params_to_array(ts)\n\n # Get the values of the extra parameters in each transition.\n extra_params, extra_values = get_transition_extras(ts)\n\n # Extract names & construct param array.\n nms = [nms; extra_params]\n parray = hcat(vals, extra_values)\n\n # Get the average or final log evidence, if it exists.\n le = getlogevidence(ts, spl, state)\n\n # Set up the info tuple.\n if save_state\n info = (model = model, sampler = spl, samplerstate = state)\n else\n info = NamedTuple()\n end\n\n # Conretize the array before giving it to MCMCChains.\n parray = MCMCChains.concretize(parray)\n\n # Chain construction.\n return MCMCChains.Chains(\n parray,\n nms,\n (internals = extra_params,);\n evidence=le,\n info=info,\n ) |> sort\nend\n\n# This is type piracy (for SampleFromPrior).\nfunction AbstractMCMC.bundle_samples(\n ts::Vector,\n model::AbstractModel,\n spl::Union{Sampler{<:InferenceAlgorithm},SampleFromPrior},\n state,\n chain_type::Type{Vector{NamedTuple}};\n kwargs...\n)\n return map(ts) do t\n params = map(first, getparams(t))\n return merge(params, metadata(t))\n end\nend\n\nfunction save(c::MCMCChains.Chains, spl::Sampler, model, vi, samples)\n nt = NamedTuple{(:sampler, :model, :vi, :samples)}((spl, model, deepcopy(vi), samples))\n return setinfo(c, merge(nt, c.info))\nend\n\nfunction resume(chain::MCMCChains.Chains, args...; kwargs...)\n return resume(Random.GLOBAL_RNG, chain, args...; kwargs...)\nend\n\nfunction resume(rng::Random.AbstractRNG, chain::MCMCChains.Chains, args...;\n progress=PROGRESS[], kwargs...)\n isempty(chain.info) && error(\"[Turing] cannot resume from a chain without state info\")\n\n # Sample a new chain.\n return AbstractMCMC.mcmcsample(\n rng,\n chain.info[:model],\n chain.info[:sampler],\n args...;\n resume_from = chain,\n chain_type = MCMCChains.Chains,\n progress = progress,\n kwargs...\n )\nend\n\nDynamicPPL.loadstate(chain::MCMCChains.Chains) = chain.info[:samplerstate]\n\n#######################################\n# Concrete algorithm implementations. #\n#######################################\n\ninclude(\"ess.jl\")\ninclude(\"hmc.jl\")\ninclude(\"mh.jl\")\ninclude(\"is.jl\")\ninclude(\"AdvancedSMC.jl\")\ninclude(\"gibbs.jl\")\ninclude(\"gibbs_conditional.jl\")\ninclude(\"../contrib/inference/sghmc.jl\")\ninclude(\"emcee.jl\")\n\n################\n# Typing tools #\n################\n\nfor alg in (:SMC, :PG, :MH, :IS, :ESS, :Gibbs, :Emcee)\n @eval DynamicPPL.getspace(::$alg{space}) where {space} = space\nend\nfor alg in (:HMC, :HMCDA, :NUTS, :SGLD, :SGHMC)\n @eval DynamicPPL.getspace(::$alg{<:Any, space}) where {space} = space\nend\n\nfunction get_matching_type(\n spl::Sampler{<:Union{PG, SMC}}, \n vi,\n ::Type{TV},\n) where {T, N, TV <: Array{T, N}}\n return TArray{T, N}\nend\n\n##############\n# Utilities #\n##############\n\nDynamicPPL.getspace(spl::Sampler) = getspace(spl.alg)\nDynamicPPL.inspace(vn::VarName, spl::Sampler) = inspace(vn, getspace(spl.alg))\n\n\"\"\"\n\n predict([rng::AbstractRNG,] model::Model, chain::MCMCChains.Chains; include_all=false)\n\nExecute `model` conditioned on each sample in `chain`, and return the resulting `Chains`.\n\nIf `include_all` is `false`, the returned `Chains` will contain only those variables\nsampled/not present in `chain`.\n\n# Details\nInternally calls `Turing.Inference.transitions_from_chain` to obtained the samples\nand then converts these into a `Chains` object using `AbstractMCMC.bundle_samples`.\n\n# Example\n```jldoctest\njulia> using Turing; Turing.turnprogress(false);\n[ Info: [Turing]: progress logging is disabled globally\n\njulia> @model function linear_reg(x, y, σ = 0.1)\n β ~ Normal(0, 1)\n\n for i ∈ eachindex(y)\n y[i] ~ Normal(β * x[i], σ)\n end\n end;\n\njulia> σ = 0.1; f(x) = 2 * x + 0.1 * randn();\n\njulia> Δ = 0.1; xs_train = 0:Δ:10; ys_train = f.(xs_train);\n\njulia> xs_test = [10 + Δ, 10 + 2 * Δ]; ys_test = f.(xs_test);\n\njulia> m_train = linear_reg(xs_train, ys_train, σ);\n\njulia> chain_lin_reg = sample(m_train, NUTS(100, 0.65), 200);\n┌ Info: Found initial step size\n└ ϵ = 0.003125\n\njulia> m_test = linear_reg(xs_test, Vector{Union{Missing, Float64}}(undef, length(ys_test)), σ);\n\njulia> predictions = predict(m_test, chain_lin_reg)\nObject of type Chains, with data of type 100×2×1 Array{Float64,3}\n\nIterations = 1:100\nThinning interval = 1\nChains = 1\nSamples per chain = 100\nparameters = y[1], y[2]\n\n2-element Array{ChainDataFrame,1}\n\nSummary Statistics\n parameters mean std naive_se mcse ess r_hat\n ────────── ─────── ────── ──────── ─────── ──────── ──────\n y[1] 20.1974 0.1007 0.0101 missing 101.0711 0.9922\n y[2] 20.3867 0.1062 0.0106 missing 101.4889 0.9903\n\nQuantiles\n parameters 2.5% 25.0% 50.0% 75.0% 97.5%\n ────────── ─────── ─────── ─────── ─────── ───────\n y[1] 20.0342 20.1188 20.2135 20.2588 20.4188\n y[2] 20.1870 20.3178 20.3839 20.4466 20.5895\n\n\njulia> ys_pred = vec(mean(Array(group(predictions, :y)); dims = 1));\n\njulia> sum(abs2, ys_test - ys_pred) ≤ 0.1\ntrue\n```\n\"\"\"\nfunction predict(model::Model, chain::MCMCChains.Chains; kwargs...)\n return predict(Random.GLOBAL_RNG, model, chain; kwargs...)\nend\nfunction predict(rng::AbstractRNG, model::Model, chain::MCMCChains.Chains; include_all = false)\n spl = DynamicPPL.SampleFromPrior()\n\n # Sample transitions using `spl` conditioned on values in `chain`\n transitions = [\n transitions_from_chain(rng, model, chain[:, :, chn_idx]; sampler = spl)\n for chn_idx = 1:size(chain, 3)\n ]\n\n # Let the Turing internals handle everything else for you\n chain_result = reduce(\n MCMCChains.chainscat, [\n AbstractMCMC.bundle_samples(\n transitions[chn_idx],\n model,\n spl,\n nothing,\n MCMCChains.Chains\n ) for chn_idx = 1:size(chain, 3)\n ]\n )\n\n parameter_names = if include_all\n names(chain_result, :parameters)\n else\n filter(k -> ∉(k, names(chain, :parameters)), names(chain_result, :parameters))\n end\n\n return chain_result[parameter_names]\nend\n\n\"\"\"\n\n transitions_from_chain(\n [rng::AbstractRNG,]\n model::Model, \n chain::MCMCChains.Chains; \n sampler = DynamicPPL.SampleFromPrior()\n )\n\nExecute `model` conditioned on each sample in `chain`, and return resulting transitions.\n\nThe returned transitions are represented in a `Vector{<:Turing.Inference.Transition}`.\n\n# Details\n\nIn a bit more detail, the process is as follows:\n1. For every `sample` in `chain`\n 1. For every `variable` in `sample`\n 1. Set `variable` in `model` to its value in `sample`\n 2. Execute `model` with variables fixed as above, sampling variables NOT present\n in `chain` using `SampleFromPrior`\n 3. Return sampled variables and log-joint\n\n# Example\n```julia-repl\njulia> using Turing\n\njulia> @model function demo()\n m ~ Normal(0, 1)\n x ~ Normal(m, 1)\n end;\n\njulia> m = demo();\n\njulia> chain = Chains(randn(2, 1, 1), [\"m\"]); # 2 samples of `m`\n\njulia> transitions = Turing.Inference.transitions_from_chain(m, chain);\n\njulia> [Turing.Inference.getlogp(t) for t in transitions] # extract the logjoints\n2-element Array{Float64,1}:\n -3.6294991938628374\n -2.5697948166987845\n\njulia> [first(t.θ.x) for t in transitions] # extract samples for `x`\n2-element Array{Array{Float64,1},1}:\n [-2.0844148956440796]\n [-1.704630494695469]\n```\n\"\"\"\nfunction transitions_from_chain(\n model::Turing.Model,\n chain::MCMCChains.Chains;\n kwargs...\n)\n return transitions_from_chain(Random.GLOBAL_RNG, model, chain; kwargs...)\nend\nfunction transitions_from_chain(\n rng::AbstractRNG,\n model::Turing.Model,\n chain::MCMCChains.Chains;\n sampler = DynamicPPL.SampleFromPrior()\n)\n vi = Turing.VarInfo(model)\n\n transitions = map(1:length(chain)) do i\n c = chain[i]\n md = vi.metadata\n for v in keys(md)\n for vn in md[v].vns\n vn_sym = Symbol(vn)\n\n # Cannot use `vn_sym` to index in the chain\n # so we have to extract the corresponding \"linear\"\n # indices and use those.\n # `ks` is empty if `vn_sym` not in `c`.\n ks = MCMCChains.namesingroup(c, vn_sym)\n\n if !isempty(ks)\n # 1st dimension is of size 1 since `c`\n # only contains a single sample, and the\n # last dimension is of size 1 since\n # we're assuming we're working with a single chain.\n val = copy(vec(c[ks].value))\n DynamicPPL.setval!(vi, val, vn)\n DynamicPPL.settrans!(vi, false, vn)\n else\n DynamicPPL.set_flag!(vi, vn, \"del\")\n end\n end\n end\n # Execute `model` on the parameters set in `vi` and sample those with `\"del\"` flag using `sampler`\n model(rng, vi, sampler)\n\n # Convert `VarInfo` into `NamedTuple` and save\n theta = DynamicPPL.tonamedtuple(vi)\n lp = Turing.getlogp(vi)\n Transition(theta, lp)\n end\n\n return transitions\nend\n\nend # module\n", "meta": {"hexsha": "3ad81f79f35ec7d70341deb01fbc0829465f711a", "size": 18904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/inference/Inference.jl", "max_stars_repo_name": "mrchaos/Turing.jl", "max_stars_repo_head_hexsha": "aac9436236afc00d944e091a1c6a1470306386ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inference/Inference.jl", "max_issues_repo_name": "mrchaos/Turing.jl", "max_issues_repo_head_hexsha": "aac9436236afc00d944e091a1c6a1470306386ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inference/Inference.jl", "max_forks_repo_name": "mrchaos/Turing.jl", "max_forks_repo_head_hexsha": "aac9436236afc00d944e091a1c6a1470306386ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9051987768, "max_line_length": 106, "alphanum_fraction": 0.6350507829, "num_tokens": 5140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23589120855962284}} {"text": "#include(\"../ReadWrite/Header.jl\")\n\n\"\"\"\n**SeisBin**\n\n*Bin seismic data onto regular grid using trace headers*\n\n**IN**\n\n* in: filename of input, irregularly sampled data\n* out: filename of output, regularly sampled data\n* style=\"sxsygxgy\"\n* ang=90\n* gamma=1\n* osx=0\n* osy=0\n* ogx=0\n* ogy=0\n* omx=0\n* omy=0\n* ohx=0\n* ohy=0\n* oh=0\n* oaz=0\n* dsx=1\n* dsy=1\n* dgx=1\n* dgy=1\n* dmx=1\n* dmy=1\n* dhx=1\n* dhy=1\n* dh=1\n* daz=1\n* min_isx=0\n* max_isx=0\n* min_isy=0\n* max_isy=0\n* min_igx=0\n* max_igx=0\n* min_igy=0\n* max_igy=0\n* min_imx=0\n* max_imx=0\n* min_imy=0\n* max_imy=0\n* min_ihx=0\n* max_ihx=0\n* min_ihy=0\n* max_ihy=0\n* min_ih=0\n* max_ih=0\n* min_iaz=0\n* max_iaz=0\n\n**OUT**\n\n*Credits: Aaron Stanton, 2015*\n\n\"\"\"\n\nfunction SeisBin(in,out;style=\"sxsygxgy\",ang=90,gamma=1,osx=0,osy=0,ogx=0,ogy=0,omx=0,omy=0,ohx=0,ohy=0,oh=0,oaz=0,dsx=1,dsy=1,dgx=1,dgy=1,dmx=1,dmy=1,dhx=1,dhy=1,dh=1,daz=1,min_isx=0,max_isx=0,min_isy=0,max_isy=0,min_igx=0,max_igx=0,min_igy=0,max_igy=0,min_imx=0,max_imx=0,min_imy=0,max_imy=0,min_ihx=0,max_ihx=0,min_ihy=0,max_ihy=0,min_ih=0,max_ih=0,min_iaz=0,max_iaz=0,ntrace=10000)\n\n\trad2deg = 180/pi;\n\tdeg2rad = pi/180;\n\tgammainv = 1/gamma;\n\tif (ang > 90) \n\t\tang2=-deg2rad*(ang-90)\n\telse \n\t\tang2=deg2rad*(90-ang)\n\tend\n\n\tnsx = max_isx - min_isx + 1\n\tnsy = max_isy - min_isy + 1\n\tngx = max_igx - min_igx + 1\n\tngy = max_igy - min_igy + 1\n\tnmx = max_imx - min_imx + 1\n\tnmy = max_imy - min_imy + 1\n\tnhx = max_ihx - min_ihx + 1\n\tnhy = max_ihy - min_ihy + 1\n\tnh = max_ih - min_ih + 1\n\tnaz = max_iaz - min_iaz + 1\n\n\tif (style==\"sxsygxgy\")\n\t\tnx1=nsx;nx2=nsy;nx3=ngx;nx4=ngy;\n\t\tox1=osx;ox2=osy;ox3=ogx;ox4=ogy;\n\t\tdx1=dsx;dx2=dsy;dx3=dgx;dx4=dgy;\n\t\tlabel2=\"sx\";label3=\"sy\";label4=\"gx\";label5=\"gy\";\n\t\tunit2=\"m\";unit3=\"m\";unit4=\"m\";unit5=\"m\";\n\telseif (style==\"mxmyhxhy\")\n\t\tnx1=nmx;nx2=nmy;nx3=nhx;nx4=nhy;\n\t\tox1=omx;ox2=omy;ox3=ohx;ox4=ohy;\n\t\tdx1=dmx;dx2=dmy;dx3=dhx;dx4=dhy;\n\t\tlabel2=\"mx\";label3=\"my\";label4=\"hx\";label5=\"hy\";\n\t\tunit2=\"m\";unit3=\"m\";unit4=\"m\";unit5=\"m\";\n\telseif (style==\"mxmyhaz\")\n\t\tnx1=nmx;nx2=nmy;nx3=nh;nx4=naz;\n\t\tox1=omx;ox2=omy;ox3=oh;ox4=oaz;\n\t\tdx1=dmx;dx2=dmy;dx3=dh;dx4=daz;\n\t\tlabel2=\"mx\";label3=\"my\";label4=\"h\";label5=\"az\";\n\t\tunit2=\"m\";unit3=\"m\";unit4=\"m\";unit5=\"Degrees\";\n\telseif (style==\"sxsyhxhy\")\n\t\tnx1=nsx;nx2=nsy;nx3=nhx;nx4=nhy;\n\t\tox1=osx;ox2=osy;ox3=ohx;ox4=ohy;\n\t\tdx1=dsx;dx2=dsy;dx3=dhx;dx4=dhy;\n\t\tlabel2=\"sx\";label3=\"sy\";label4=\"hx\";label5=\"hy\";\n\t\tunit2=\"m\";unit3=\"m\";unit4=\"m\";unit5=\"m\";\n\telseif (style==\"gxgyhxhy\")\n\t\tnx1=ngx;nx2=ngy;nx3=nhx;nx4=nhy;\n\t\tox1=ogx;ox2=ogy;ox3=ohx;ox4=ohy;\n\t\tdx1=dgx;dx2=dgy;dx3=dhx;dx4=dhy;\n\t\tlabel2=\"gx\";label3=\"gy\";label4=\"hx\";label5=\"hy\";\n\t\tunit2=\"m\";unit3=\"m\";unit4=\"m\";unit5=\"m\";\n\telseif (style==\"sxsyhaz\")\n\t\tnx1=nsx;nx2=nsy;nx3=nh;nx4=naz;\n\t\tox1=osx;ox2=osy;ox3=oh;ox4=oaz;\n\t\tdx1=dsx;dx2=dsy;dx3=dh;dx4=daz;\n\t\tlabel2=\"sx\";label3=\"sy\";label4=\"hx\";label5=\"az\";\n\t\tunit2=\"m\";unit3=\"m\";unit4=\"m\";unit5=\"Degrees\";\n\telseif (style==\"gxgyhaz\")\n\t\tnx1=ngx;nx2=ngy;nx3=nh;nx4=naz;\n\t\tox1=ogx;ox2=ogy;ox3=oh;ox4=oaz;\n\t\tdx1=dgx;dx2=dgy;dx3=dh;dx4=daz;\n\t\tlabel2=\"gx\";label3=\"gy\";label4=\"h\";label5=\"az\";\n\t\tunit2=\"m\";unit3=\"m\";unit4=\"m\";unit5=\"Degrees\";\n\telse\n\t\terror(\"style not recognized.\")\n\tend\n\tnx_out = nx1*nx2*nx3*nx4\n\n\tstream = open(ParseHeaderName(in))\n\t@compat nx_in = int(filesize(stream)/(4*length(fieldnames(Header))))\n\tseek(stream, header_count[\"n1\"])\n\tnt = read(stream,Int32)\n\tseek(stream, header_count[\"d1\"])\n\tdt = read(stream,Float32)\n\tclose(stream)\n\td = zeros(Float32,nt,1)\n\th = Array(Header,1)\n\th[1] = InitSeisHeader()\n\n\textent = Extent(convert(Int32,nt),convert(Int32,nx1),convert(Int32,nx2),convert(Int32,nx3),convert(Int32,nx4),\n\t\t convert(Float32,0),convert(Float32,ox1),convert(Float32,ox2),convert(Float32,ox3),convert(Float32,ox4),\n\t\t convert(Float32,dt),convert(Float32,dx1),convert(Float32,dx2),convert(Float32,dx3),convert(Float32,dx4),\n\t\t \"Time\",label2,label3,label4,label5,\n\t\t \"s\",unit2,unit3,unit4,unit5,\n\t\t \"\")\n\t\n\tj = 1 \n\tfor ix1 = 1 : nx1\n\t\tfor ix2 = 1 : nx2\n\t\t\tfor ix3 = 1 : nx3\n\t\t\t\tfor ix4 = 1 : nx4\n\t\t\t\t\th[1].tracenum = convert(typeof(h[1].tracenum),j)\n\t\t\t\t\th[1].o1 = convert(typeof(h[1].o1),0)\n\t\t\t\t\th[1].n1 = convert(typeof(h[1].n1),nt)\n\t\t\t\t\th[1].d1 = convert(typeof(h[1].d1),dt)\n\t\t\t\t\tif (style==\"sxsygxgy\")\n\t\t\t\t\t\th[1].isx = convert(typeof(h[1].isx),ix1 - 1 + min_isx)\n\t\t\t\t\t\th[1].isy = convert(typeof(h[1].isy),ix2 - 1 + min_isy)\n\t\t\t\t\t\th[1].igx = convert(typeof(h[1].igx),ix3 - 1 + min_igx)\n\t\t\t\t\t\th[1].igy = convert(typeof(h[1].igy),ix4 - 1 + min_igy)\n\t\t\t\t\t\tsx_rot = convert(Float32,(ix1 - 1 + min_isx)*dsx + osx);\n\t\t\t\t\t\tsy_rot = convert(Float32,(ix2 - 1 + min_isy)*dsy + osy);\n\t\t\t\t\t\tgx_rot = convert(Float32,(ix3 - 1 + min_igx)*dgx + ogx);\n\t\t\t\t\t\tgy_rot = convert(Float32,(ix4 - 1 + min_igy)*dgy + ogy);\n\t\t\t\t\t\th[1].sx = (sx_rot-osx)*cos(ang2) + (sy_rot-osy)*sin(ang2) + osx;\n\t\t\t\t\t\th[1].sy = -(sx_rot-osx)*sin(ang2) + (sy_rot-osy)*cos(ang2) + osy;\n\t\t\t\t\t\th[1].gx = (gx_rot-ogx)*cos(ang2) + (gy_rot-ogy)*sin(ang2) + ogx;\n\t\t\t\t\t\th[1].gy = -(gx_rot-ogx)*sin(ang2) + (gy_rot-ogy)*cos(ang2) + ogy;\t\t\n\t\t\t\t\t\th[1].hx = h[1].gx - h[1].sx\n\t\t\t\t\t\th[1].hy = h[1].gy - h[1].sy\n\t\t\t\t\t\th[1].h = sqrt((h[1].hx^2) + (h[1].hy^2))\n\t\t\t\t\t\th[1].az = rad2deg*atan2((h[1].gy-h[1].sy),(h[1].gx-h[1].sx))\n\t\t\t\t\t\tif (h[1].az < 0) \n\t\t\t\t\t\t\th[1].az += 360.0\n\t\t\t\t\t\tend\n\t\t\t\t\t\th[1].mx = h[1].sx + h[1].hx/(1 + gammainv);\n\t\t\t\t\t\th[1].my = h[1].sy + h[1].hy/(1 + gammainv);\n\t\t\t\t\t\tmx_rot = (h[1].mx-omx)*cos(ang2) - (h[1].my-omy)*sin(ang2) + omx;\n\t\t\t\t\t\tmy_rot = (h[1].mx-omx)*sin(ang2) + (h[1].my-omy)*cos(ang2) + omy;\n\t\t\t\t\t\thx_rot = (h[1].hx-ohx)*cos(ang2) - (h[1].hy-ohy)*sin(ang2) + ohx;\n\t\t\t\t\t\thy_rot = (h[1].hx-ohx)*sin(ang2) + (h[1].hy-ohy)*cos(ang2) + ohy;\n\t\t\t\t\t\th[1].imx = convert(Int32,round((mx_rot-omx)/dmx))\n\t\t\t\t\t\th[1].imy = convert(Int32,round((my_rot-omy)/dmy))\n\t\t\t\t\t\th[1].ihx = convert(Int32,round((hx_rot-ohx)/dhx))\n\t\t\t\t\t\th[1].ihy = convert(Int32,round((hy_rot-ohy)/dhy))\n\t\t\t\t\t\th[1].ih = convert(Int32,round((h[1].h-oh)/dh))\n\t\t\t\t\t\th[1].iaz = convert(Int32,round((h[1].az-oaz)/daz))\n\t\t\t\t\telseif (style==\"mxmyhxhy\")\n\t\t\t\t\t\th[1].imx = convert(typeof(h[1].imx),ix1 - 1 + min_imx)\n\t\t\t\t\t\th[1].imy = convert(typeof(h[1].imy),ix2 - 1 + min_imy)\n\t\t\t\t\t\th[1].ihx = convert(typeof(h[1].ihx),ix3 - 1 + min_ihx)\n\t\t\t\t\t\th[1].ihy = convert(typeof(h[1].ihy),ix4 - 1 + min_ihy)\n\t\t\t\t\t\tmx_rot = convert(Float32,(ix1 - 1 + min_imx)*dmx + omx);\n\t\t\t\t\t\tmy_rot = convert(Float32,(ix2 - 1 + min_imy)*dmy + omy);\n\t\t\t\t\t\thx_rot = convert(Float32,(ix3 - 1 + min_ihx)*dhx + ohx);\n\t\t\t\t\t\thy_rot = convert(Float32,(ix4 - 1 + min_ihy)*dhy + ohy);\n\t\t\t\t\t\th[1].mx = (mx_rot-omx)*cos(ang2) + (my_rot-omy)*sin(ang2) + omx;\n\t\t\t\t\t\th[1].my = -(mx_rot-omx)*sin(ang2) + (my_rot-omy)*cos(ang2) + omy;\n\t\t\t\t\t\th[1].hx = (hx_rot-ohx)*cos(ang2) + (hy_rot-ohy)*sin(ang2) + ohx;\n\t\t\t\t\t\th[1].hy = -(hx_rot-ohx)*sin(ang2) + (hy_rot-ohy)*cos(ang2) + ohy;\n\t\t\t\t\t\th[1].sx = h[1].mx - h[1].hx/(1 + gammainv);\n\t\t\t\t\t\th[1].sy = h[1].my - h[1].hy/(1 + gammainv);\n\t\t\t\t\t\th[1].gx = h[1].mx + h[1].hx*(1-(1/(1 + gammainv)));\n\t\t\t\t\t\th[1].gy = h[1].my + h[1].hy*(1-(1/(1 + gammainv)));\n\t\t\t\t\t\tsx_rot = (h[1].sx-osx)*cos(ang2) - (h[1].sy-osy)*sin(ang2) + osx;\n\t\t\t\t\t\tsy_rot = (h[1].sx-osx)*sin(ang2) + (h[1].sy-osy)*cos(ang2) + osy;\n\t\t\t\t\t\tgx_rot = (h[1].gx-ogx)*cos(ang2) - (h[1].gy-ogy)*sin(ang2) + ogx;\n\t\t\t\t\t\tgy_rot = (h[1].gx-ogx)*sin(ang2) + (h[1].gy-ogy)*cos(ang2) + ogy;\n\t\t\t\t\t\th[1].isx = convert(Int32,round((sx_rot-osx)/dsx))\n\t\t\t\t\t\th[1].isy = convert(Int32,round((sy_rot-osy)/dsy))\n\t\t\t\t\t\th[1].igx = convert(Int32,round((gx_rot-ogx)/dgx))\n\t\t\t\t\t\th[1].igy = convert(Int32,round((gy_rot-ogy)/dgy))\n\t\t\t\t\t\th[1].h = sqrt((h[1].hx^2) + (h[1].hy^2))\n\t\t\t\t\t\th[1].az = rad2deg*atan2((h[1].gy-h[1].sy),(h[1].gx-h[1].sx))\n\t\t\t\t\t\tif (h[1].az < 0)\n\t\t\t\t\t\t\th[1].az += 360.0\n\t\t\t\t\t\tend\n\t\t\t\t\t\th[1].ih = convert(Int32,round((h[1].h-oh)/dh))\n\t\t\t\t\t\th[1].iaz = convert(Int32,round((h[1].az-oaz)/daz))\n\t\t\t\t\telseif (style==\"mxmyhaz\")\n\t\t\t\t\t\th[1].imx = convert(typeof(h[1].imx),ix1 - 1 + min_imx)\n\t\t\t\t\t\th[1].imy = convert(typeof(h[1].imy),ix2 - 1 + min_imy)\n\t\t\t\t\t\th[1].ih = convert(typeof(h[1].ih), ix3 - 1 + min_ih)\n\t\t\t\t\t\th[1].iaz = convert(typeof(h[1].iaz),ix4 - 1 + min_iaz)\n\t\t\t\t\t\tmx_rot = convert(Float32,(ix1 - 1 + min_imx)*dmx + omx);\n\t\t\t\t\t\tmy_rot = convert(Float32,(ix2 - 1 + min_imy)*dmy + omy);\n\t\t\t\t\t\th[1].mx = (mx_rot-omx)*cos(ang2) + (my_rot-omy)*sin(ang2) + omx;\n\t\t\t\t\t\th[1].my = -(mx_rot-omx)*sin(ang2) + (my_rot-omy)*cos(ang2) + omy;\n\t\t\t\t\t\th[1].h = convert(Float32,(ix3 - 1 + min_ih)*dh + oh);\n\t\t\t\t\t\th[1].az = convert(Float32,(ix4 - 1 + min_iaz)*daz + oaz);\n\t\t\t\t\t\tif (h[1].az <= 90)\n\t\t\t\t\t\t\th[1].hx = h[1].h*cos(deg2rad*h[1].az);\n\t\t\t\t\t\t\th[1].hy = h[1].h*sin(deg2rad*h[1].az);\n\t\t\t\t\t\telseif (h[1].az > 90 && h[1].az <= 180)\n\t\t\t\t\t\t\th[1].hx =-h[1].h*cos(pi-(deg2rad*h[1].az));\n\t\t\t\t\t\t\th[1].hy = h[1].h*sin(pi-(deg2rad*h[1].az));\n\t\t\t\t\t\telseif (h[1].az > 180 && h[1].az <= 270)\n\t\t\t\t\t\t\th[1].hx =-h[1].h*cos((deg2rad*h[1].az)-pi);\n\t\t\t\t\t\t\th[1].hy =-h[1].h*sin((deg2rad*h[1].az)-pi);\n\t\t\t\t\t\telse \n\t\t\t\t\t\t\th[1].hx = h[1].h*cos(2*pi-(deg2rad*h[1].az));\n\t\t\t\t\t\t\th[1].hy =-h[1].h*sin(2*pi-(deg2rad*h[1].az));\n\t\t\t\t\t\tend\t\t\t\t\t\n\t\t\t\t\t\th[1].sx = h[1].mx - h[1].hx/(1 + gammainv);\n\t\t\t\t\t\th[1].sy = h[1].my - h[1].hy/(1 + gammainv);\n\t\t\t\t\t\th[1].gx = h[1].mx + h[1].hx*(1-(1/(1 + gammainv)));\n\t\t\t\t\t\th[1].gy = h[1].my + h[1].hy*(1-(1/(1 + gammainv)));\n\t\t\t\t\t\tsx_rot = (h[1].sx-osx)*cos(ang2) - (h[1].sy-osy)*sin(ang2) + osx;\n\t\t\t\t\t\tsy_rot = (h[1].sx-osx)*sin(ang2) + (h[1].sy-osy)*cos(ang2) + osy;\n\t\t\t\t\t\tgx_rot = (h[1].gx-ogx)*cos(ang2) - (h[1].gy-ogy)*sin(ang2) + ogx;\n\t\t\t\t\t\tgy_rot = (h[1].gx-ogx)*sin(ang2) + (h[1].gy-ogy)*cos(ang2) + ogy;\n\t\t\t\t\t\th[1].isx = convert(Int32,round((sx_rot-osx)/dsx))\n\t\t\t\t\t\th[1].isy = convert(Int32,round((sy_rot-osy)/dsy))\n\t\t\t\t\t\th[1].igx = convert(Int32,round((gx_rot-ogx)/dgx))\n\t\t\t\t\t\th[1].igy = convert(Int32,round((gy_rot-ogy)/dgy))\n\t\t\t\t\t\thx_rot = (h[1].hx-ohx)*cos(ang2) - (h[1].hy-ohy)*sin(ang2) + ohx;\n\t\t\t\t\t\thy_rot = (h[1].hx-ohx)*sin(ang2) + (h[1].hy-ohy)*cos(ang2) + ohy;\n\t\t\t\t\t\th[1].ihx = convert(Int32,round((hx_rot-ohx)/dhx))\n\t\t\t\t\t\th[1].ihy = convert(Int32,round((hy_rot-ohy)/dhy))\n\t\t\t\t\telseif (style==\"sxsyhxhy\")\n\t\t\t\t\t\th[1].isx = convert(typeof(h[1].isx),ix1 - 1 + min_isx)\n\t\t\t\t\t\th[1].isy = convert(typeof(h[1].isy),ix2 - 1 + min_isy)\n\t\t\t\t\t\th[1].ihx = convert(typeof(h[1].ihx),ix3 - 1 + min_ihx)\n\t\t\t\t\t\th[1].ihy = convert(typeof(h[1].ihy),ix4 - 1 + min_ihy)\n\t\t\t\t\t\tsx_rot = convert(Float32,(ix1 - 1 + min_isx)*dsx + osx);\n\t\t\t\t\t\tsy_rot = convert(Float32,(ix2 - 1 + min_isy)*dsy + osy);\n\t\t\t\t\t\thx_rot = convert(Float32,(ix3 - 1 + min_ihx)*dhx + ohx);\n\t\t\t\t\t\thy_rot = convert(Float32,(ix4 - 1 + min_ihy)*dhy + ohy);\n\t\t\t\t\t\th[1].sx = (sx_rot-osx)*cos(ang2) + (sy_rot-osy)*sin(ang2) + osx;\n\t\t\t\t\t\th[1].sy = -(sx_rot-osx)*sin(ang2) + (sy_rot-osy)*cos(ang2) + osy;\n\t\t\t\t\t\th[1].hx = (hx_rot-ohx)*cos(ang2) + (hy_rot-ohy)*sin(ang2) + ohx;\n\t\t\t\t\t\th[1].hy = -(hx_rot-ohx)*sin(ang2) + (hy_rot-ohy)*cos(ang2) + ohy;\n\t\t\t\t\t\th[1].gx = h[1].sx + h[1].hx;\n\t\t\t\t\t\th[1].gy = h[1].sy + h[1].hy;\n\t\t\t\t\t\th[1].h = sqrt((h[1].hx^2) + (h[1].hy^2))\n\t\t\t\t\t\th[1].az = rad2deg*atan2((h[1].gy-h[1].sy),(h[1].gx-h[1].sx))\n\t\t\t\t\t\tif (h[1].az < 0) \n\t\t\t\t\t\t\th[1].az += 360.0\n\t\t\t\t\t\tend\n\t\t\t\t\t\th[1].mx = h[1].sx + h[1].hx/(1 + gammainv);\n\t\t\t\t\t\th[1].my = h[1].sy + h[1].hy/(1 + gammainv);\n\t\t\t\t\t\tmx_rot = (h[1].mx-omx)*cos(ang2) - (h[1].my-omy)*sin(ang2) + omx;\n\t\t\t\t\t\tmy_rot = (h[1].mx-omx)*sin(ang2) + (h[1].my-omy)*cos(ang2) + omy;\n\t\t\t\t\t\thx_rot = (h[1].hx-ohx)*cos(ang2) - (h[1].hy-ohy)*sin(ang2) + ohx;\n\t\t\t\t\t\thy_rot = (h[1].hx-ohx)*sin(ang2) + (h[1].hy-ohy)*cos(ang2) + ohy;\n\t\t\t\t\t\th[1].imx = convert(Int32,round((mx_rot-omx)/dmx))\n\t\t\t\t\t\th[1].imy = convert(Int32,round((my_rot-omy)/dmy))\n\t\t\t\t\t\th[1].ihx = convert(Int32,round((hx_rot-ohx)/dhx))\n\t\t\t\t\t\th[1].ihy = convert(Int32,round((hy_rot-ohy)/dhy))\n\t\t\t\t\t\th[1].ih = convert(Int32,round((h[1].h-oh)/dh))\n\t\t\t\t\t\th[1].iaz = convert(Int32,round((h[1].az-oaz)/daz))\n\t\t\t\t\telseif (style==\"gxgyhxhy\")\n\t\t\t\t\t\th[1].igx = convert(typeof(h[1].igx),ix1 - 1 + min_igx)\n\t\t\t\t\t\th[1].igy = convert(typeof(h[1].igy),ix2 - 1 + min_igy)\n\t\t\t\t\t\th[1].ihx = convert(typeof(h[1].ihx),ix3 - 1 + min_ihx)\n\t\t\t\t\t\th[1].ihy = convert(typeof(h[1].ihy),ix4 - 1 + min_ihy)\n\t\t\t\t\t\tgx_rot = convert(Float32,(ix1 - 1 + min_igx)*dgx + ogx);\n\t\t\t\t\t\tgy_rot = convert(Float32,(ix2 - 1 + min_igy)*dgy + ogy);\n\t\t\t\t\t\thx_rot = convert(Float32,(ix3 - 1 + min_ihx)*dhx + ohx);\n\t\t\t\t\t\thy_rot = convert(Float32,(ix4 - 1 + min_ihy)*dhy + ohy);\n\t\t\t\t\t\th[1].gx = (gx_rot-ogx)*cos(ang2) + (gy_rot-ogy)*sin(ang2) + ogx;\n\t\t\t\t\t\th[1].gy = -(gx_rot-ogx)*sin(ang2) + (gy_rot-ogy)*cos(ang2) + ogy;\n\t\t\t\t\t\th[1].hx = (hx_rot-ohx)*cos(ang2) + (hy_rot-ohy)*sin(ang2) + ohx;\n\t\t\t\t\t\th[1].hy = -(hx_rot-ohx)*sin(ang2) + (hy_rot-ohy)*cos(ang2) + ohy;\n\t\t\t\t\t\th[1].sx = h[1].gx - h[1].hx;\n\t\t\t\t\t\th[1].sy = h[1].gy - h[1].hy;\n\t\t\t\t\t\th[1].h = sqrt((h[1].hx^2) + (h[1].hy^2))\n\t\t\t\t\t\th[1].az = rad2deg*atan2((h[1].gy-h[1].sy),(h[1].gx-h[1].sx))\n\t\t\t\t\t\tif (h[1].az < 0) \n\t\t\t\t\t\t\th[1].az += 360.0\n\t\t\t\t\t\tend\n\t\t\t\t\t\th[1].mx = h[1].sx + h[1].hx/(1 + gammainv);\n\t\t\t\t\t\th[1].my = h[1].sy + h[1].hy/(1 + gammainv);\n\t\t\t\t\t\tmx_rot = (h[1].mx-omx)*cos(ang2) - (h[1].my-omy)*sin(ang2) + omx;\n\t\t\t\t\t\tmy_rot = (h[1].mx-omx)*sin(ang2) + (h[1].my-omy)*cos(ang2) + omy;\n\t\t\t\t\t\thx_rot = (h[1].hx-ohx)*cos(ang2) - (h[1].hy-ohy)*sin(ang2) + ohx;\n\t\t\t\t\t\thy_rot = (h[1].hx-ohx)*sin(ang2) + (h[1].hy-ohy)*cos(ang2) + ohy;\n\t\t\t\t\t\th[1].imx = convert(Int32,round((mx_rot-omx)/dmx))\n\t\t\t\t\t\th[1].imy = convert(Int32,round((my_rot-omy)/dmy))\n\t\t\t\t\t\th[1].ihx = convert(Int32,round((hx_rot-ohx)/dhx))\n\t\t\t\t\t\th[1].ihy = convert(Int32,round((hy_rot-ohy)/dhy))\n\t\t\t\t\t\th[1].ih = convert(Int32,round((h[1].h-oh)/dh))\n\t\t\t\t\t\th[1].iaz = convert(Int32,round((h[1].az-oaz)/daz))\n\t\t\t\t\telseif (style==\"sxsyhaz\")\n\t\t\t\t\t\terror(\"sxsyhaz not developed yet.\")\n\t\t\t\t\telseif (style==\"gxgyhaz\")\n\t\t\t\t\t\terror(\"gxgyhaz not developed yet.\")\n\t\t\t\t\tend\n\t\t\t\t\th[1].selev = convert(typeof(h[1].selev),0)\n\t\t\t\t\th[1].gelev = convert(typeof(h[1].gelev),0)\n\t\t\t\t\th[1].trid = convert(typeof(h[1].trid),0)\n\t\t\t\t\tSeisWrite(out,d,h,extent,itrace=j)\n\t\t\t\t\tj += 1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\n\tout_d = ParseDataName(out)\n\tout_h = ParseHeaderName(out)\n\tstream_d = open(out_d,\"a\")\n\tstream_h = open(out_h,\"a\")\n\n\tif (style==\"sxsygxgy\")\n\t\tj = 1\n\t\twhile j <= nx_in\t\n\t\t\td,h,e = SeisRead(in,group=\"some\",itrace=j,ntrace=ntrace)\n\t\t\tnum_traces_in = size(d[:,:],2)\n\t\t\tfor k = 1 : num_traces_in\n\t\t\t\titrace = (h[k].isx - min_isx)*nx2*nx3*nx4 + (h[k].isy - min_isy)*nx3*nx4 + (h[k].igx - min_igx)*nx4 + h[k].igy - min_igy + 1\n\t\t\t\tif (h[k].isx >= min_isx && h[k].isx <= max_isx && h[k].isy >= min_isy && h[k].isy <= max_isy && h[k].igx >= min_igx && h[k].igx <= max_igx && h[k].igy >= min_igy && h[k].igy <= max_igy)\n\t\t\t\t\th[k].tracenum = convert(Int32,itrace)\n\t\t\t\t\tif (itrace > 0 && itrace <= nx_out)\n\t\t\t\t\t\tposition_d = 4*nt*(itrace - 1)\n\t\t\t\t\t\tseek(stream_d,position_d)\n\t\t\t\t\t\twrite(stream_d,d[:,k])\n\t\t\t\t\t\tPutHeader(stream_h,h[k],itrace)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tj += num_traces_in\n\t\tend\n\telseif (style==\"mxmyhxhy\")\n\t\tj = 1\n\t\twhile j <= nx_in\t\n\t\t\td,h,e = SeisRead(in,group=\"some\",itrace=j,ntrace=ntrace)\n\t\t\tnum_traces_in = size(d[:,:],2)\n\t\t\tfor k = 1 : num_traces_in\n\t\t\t\titrace = (h[k].imx - min_imx)*nx2*nx3*nx4 + (h[k].imy - min_imy)*nx3*nx4 + (h[k].ihx - min_ihx)*nx4 + h[k].ihy - min_ihy + 1\n\t\t\t\tif (h[k].imx >= min_imx && h[k].imx <= max_imx && h[k].imy >= min_imy && h[k].imy <= max_imy && h[k].ihx >= min_ihx && h[k].ihx <= max_ihx && h[k].ihy >= min_ihy && h[k].ihy <= max_ihy)\n\t\t\t\t\th[k].tracenum = convert(Int32,itrace)\n\t\t\t\t\tif (itrace > 0 && itrace <= nx_out)\n\t\t\t\t\t\tposition_d = 4*nt*(itrace - 1)\n\t\t\t\t\t\tseek(stream_d,position_d)\n\t\t\t\t\t\twrite(stream_d,d[:,k])\n\t\t\t\t\t\tPutHeader(stream_h,h[k],itrace)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tj += num_traces_in\n\t\tend\n\telseif (style==\"mxmyhaz\")\n\t\tj = 1\n\t\twhile j <= nx_in\t\n\t\t\td,h,e = SeisRead(in,group=\"some\",itrace=j,ntrace=ntrace)\n\t\t\tnum_traces_in = size(d[:,:],2)\n\t\t\tfor k = 1 : num_traces_in\n\t\t\t\titrace = (h[k].imx - min_imx)*nx2*nx3*nx4 + (h[k].imy - min_imy)*nx3*nx4 + (h[k].ih - min_ih)*nx4 + h[k].iaz - min_iaz + 1\n\t\t\t\tif (h[k].imx >= min_imx && h[k].imx <= max_imx && h[k].imy >= min_imy && h[k].imy <= max_imy && h[k].ih >= min_ih && h[k].ih <= max_ih && h[k].iaz >= min_iaz && h[k].iaz <= max_iaz)\n\t\t\t\t\th[k].tracenum = convert(Int32,itrace)\n\t\t\t\t\tif (itrace > 0 && itrace <= nx_out)\n\t\t\t\t\t\tposition_d = 4*nt*(itrace - 1)\n\t\t\t\t\t\tseek(stream_d,position_d)\n\t\t\t\t\t\twrite(stream_d,d[:,k])\n\t\t\t\t\t\tPutHeader(stream_h,h[k],itrace)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tj += num_traces_in\n\t\tend\n\telseif (style==\"sxsyhxhy\")\n\t\tj = 1\n\t\twhile j <= nx_in\t\n\t\t\td,h,e = SeisRead(in,group=\"some\",itrace=j,ntrace=ntrace)\n\t\t\tnum_traces_in = size(d[:,:],2)\n\t\t\tfor k = 1 : num_traces_in\n\t\t\t\titrace = (h[k].isx - min_isx)*nx2*nx3*nx4 + (h[k].isy - min_isy)*nx3*nx4 + (h[k].ihx - min_ihx)*nx4 + h[k].ihy - min_ihy + 1\n\t\t\t\tif (h[k].isx >= min_isx && h[k].isx <= max_isx && h[k].isy >= min_isy && h[k].isy <= max_isy && h[k].ihx >= min_ihx && h[k].ihx <= max_ihx && h[k].ihy >= min_ihy && h[k].ihy <= max_ihy)\n\t\t\t\t\th[k].tracenum = convert(Int32,itrace)\n\t\t\t\t\tif (itrace > 0 && itrace <= nx_out)\n\t\t\t\t\t\tposition_d = 4*nt*(itrace - 1)\n\t\t\t\t\t\tseek(stream_d,position_d)\n\t\t\t\t\t\twrite(stream_d,d[:,k])\n\t\t\t\t\t\tPutHeader(stream_h,h[k],itrace)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tj += num_traces_in\n\t\tend\n\telseif (style==\"gxgyhxhy\")\n\t\tj = 1\n\t\twhile j <= nx_in\t\n\t\t\td,h,e = SeisRead(in,group=\"some\",itrace=j,ntrace=ntrace)\n\t\t\tnum_traces_in = size(d[:,:],2)\n\t\t\tfor k = 1 : num_traces_in\n\t\t\t\titrace = (h[k].igx - min_igx)*nx2*nx3*nx4 + (h[k].igy - min_igy)*nx3*nx4 + (h[k].ihx - min_ihx)*nx4 + h[k].ihy - min_ihy + 1\n\t\t\t\tif (h[k].igx >= min_igx && h[k].igx <= max_igx && h[k].igy >= min_igy && h[k].igy <= max_igy && h[k].ihx >= min_ihx && h[k].ihx <= max_ihx && h[k].ihy >= min_ihy && h[k].ihy <= max_ihy)\n\t\t\t\t\th[k].tracenum = convert(Int32,itrace)\n\t\t\t\t\tif (itrace > 0 && itrace <= nx_out)\n\t\t\t\t\t\tposition_d = 4*nt*(itrace - 1)\n\t\t\t\t\t\tseek(stream_d,position_d)\n\t\t\t\t\t\twrite(stream_d,d[:,k])\n\t\t\t\t\t\tPutHeader(stream_h,h[k],itrace)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tj += num_traces_in\n\t\tend\n\telseif (style==\"sxsyhaz\")\n\t\tj = 1\n\t\twhile j <= nx_in\t\n\t\t\td,h,e = SeisRead(in,group=\"some\",itrace=j,ntrace=ntrace)\n\t\t\tnum_traces_in = size(d[:,:],2)\n\t\t\tfor k = 1 : num_traces_in\n\t\t\t\titrace = (h[k].isx - min_isx)*nx2*nx3*nx4 + (h[k].isy - min_isy)*nx3*nx4 + (h[k].ih - min_ih)*nx4 + h[k].iaz - min_iaz + 1\n\t\t\t\tif (h[k].isx >= min_isx && h[k].isx <= max_isx && h[k].isy >= min_isy && h[k].isy <= max_isy && h[k].ih >= min_ih && h[k].ih <= max_ih && h[k].iaz >= min_iaz && h[k].iaz <= max_iaz)\n\t\t\t\t\th[k].tracenum = convert(Int32,itrace)\n\t\t\t\t\tif (itrace > 0 && itrace <= nx_out)\n\t\t\t\t\t\tposition_d = 4*nt*(itrace - 1)\n\t\t\t\t\t\tseek(stream_d,position_d)\n\t\t\t\t\t\twrite(stream_d,d[:,k])\n\t\t\t\t\t\tPutHeader(stream_h,h[k],itrace)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tj += num_traces_in\n\t\tend\n\telseif (style==\"gxgyhaz\")\n\t\tj = 1\n\t\twhile j <= nx_in\t\n\t\t\td,h,e = SeisRead(in,group=\"some\",itrace=j,ntrace=ntrace)\n\t\t\tnum_traces_in = size(d[:,:],2)\n\t\t\tfor k = 1 : num_traces_in\n\t\t\t\titrace = (h[k].igx - min_igx)*nx2*nx3*nx4 + (h[k].igy - min_igy)*nx3*nx4 + (h[k].ih - min_ih)*nx4 + h[k].iaz - min_iaz + 1\n\t\t\t\tif (h[k].igx >= min_igx && h[k].igx <= max_igx && h[k].igy >= min_igy && h[k].igy <= max_igy && h[k].ih >= min_ih && h[k].ih <= max_ih && h[k].iaz >= min_iaz && h[k].iaz <= max_iaz)\n\t\t\t\t\th[k].tracenum = convert(Int32,itrace)\n\t\t\t\t\tif (itrace > 0 && itrace <= nx_out)\n\t\t\t\t\t\tposition_d = 4*nt*(itrace - 1)\n\t\t\t\t\t\tseek(stream_d,position_d)\n\t\t\t\t\t\twrite(stream_d,d[:,k])\n\t\t\t\t\t\tPutHeader(stream_h,h[k],itrace)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tj += num_traces_in\n\t\tend\n\tend\t\n\tclose(stream_d)\n\tclose(stream_h)\n\nend\n", "meta": {"hexsha": "0585bddea03f52b7e47a45d4ea17a764f7367b5a", "size": 19441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/SeisBin.jl", "max_stars_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_stars_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/SeisBin.jl", "max_issues_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_issues_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/SeisBin.jl", "max_forks_repo_name": "JuliaPackageMirrors/Seismic.jl", "max_forks_repo_head_hexsha": "7fb94347c2486f8de3185edf92bbf023f9e68cc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1673553719, "max_line_length": 385, "alphanum_fraction": 0.5650943881, "num_tokens": 8648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.23584497665788742}} {"text": "# This file is a part of Julia. License is MIT: https://julialang.org/license\n\nmodule Sort\n\nimport ..@__MODULE__, ..parentmodule\nconst Base = parentmodule(@__MODULE__)\nusing .Base.Order\nusing .Base: copymutable, LinearIndices, length, (:),\n eachindex, axes, first, last, similar, zip, OrdinalRange,\n AbstractVector, @inbounds, AbstractRange, @eval, @inline, Vector, @noinline,\n AbstractMatrix, AbstractUnitRange, isless, identity, eltype, >, <, <=, >=, |, +, -, *, !,\n extrema, sub_with_overflow, add_with_overflow, oneunit, div, getindex, setindex!,\n length, resize!, fill, Missing, require_one_based_indexing, keytype\n\nusing .Base: >>>, !==\n\nimport .Base:\n sort,\n sort!,\n issorted,\n sortperm,\n to_indices\n\nexport # also exported by Base\n # order-only:\n issorted,\n searchsorted,\n searchsortedfirst,\n searchsortedlast,\n # order & algorithm:\n sort,\n sort!,\n sortperm,\n sortperm!,\n partialsort,\n partialsort!,\n partialsortperm,\n partialsortperm!,\n # algorithms:\n InsertionSort,\n QuickSort,\n MergeSort,\n PartialQuickSort\n\nexport # not exported by Base\n Algorithm,\n DEFAULT_UNSTABLE,\n DEFAULT_STABLE,\n SMALL_ALGORITHM,\n SMALL_THRESHOLD\n\n\n## functions requiring only ordering ##\n\nfunction issorted(itr, order::Ordering)\n y = iterate(itr)\n y === nothing && return true\n prev, state = y\n y = iterate(itr, state)\n while y !== nothing\n this, state = y\n lt(order, this, prev) && return false\n prev = this\n y = iterate(itr, state)\n end\n return true\nend\n\n\"\"\"\n issorted(v, lt=isless, by=identity, rev:Bool=false, order::Ordering=Forward)\n\nTest whether a vector is in sorted order. The `lt`, `by` and `rev` keywords modify what\norder is considered to be sorted just as they do for [`sort`](@ref).\n\n# Examples\n```jldoctest\njulia> issorted([1, 2, 3])\ntrue\n\njulia> issorted([(1, \"b\"), (2, \"a\")], by = x -> x[1])\ntrue\n\njulia> issorted([(1, \"b\"), (2, \"a\")], by = x -> x[2])\nfalse\n\njulia> issorted([(1, \"b\"), (2, \"a\")], by = x -> x[2], rev=true)\ntrue\n```\n\"\"\"\nissorted(itr;\n lt=isless, by=identity, rev::Union{Bool,Nothing}=nothing, order::Ordering=Forward) =\n issorted(itr, ord(lt,by,rev,order))\n\nfunction partialsort!(v::AbstractVector, k::Union{Integer,OrdinalRange}, o::Ordering)\n inds = axes(v, 1)\n sort!(v, first(inds), last(inds), PartialQuickSort(k), o)\n maybeview(v, k)\nend\n\nmaybeview(v, k) = view(v, k)\nmaybeview(v, k::Integer) = v[k]\n\n\"\"\"\n partialsort!(v, k; by=, lt=, rev=false)\n\nPartially sort the vector `v` in place, according to the order specified by `by`, `lt` and\n`rev` so that the value at index `k` (or range of adjacent values if `k` is a range) occurs\nat the position where it would appear if the array were fully sorted via a non-stable\nalgorithm. If `k` is a single index, that value is returned; if `k` is a range, an array of\nvalues at those indices is returned. Note that `partialsort!` does not fully sort the input\narray.\n\n# Examples\n```jldoctest\njulia> a = [1, 2, 4, 3, 4]\n5-element Array{Int64,1}:\n 1\n 2\n 4\n 3\n 4\n\njulia> partialsort!(a, 4)\n4\n\njulia> a\n5-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 4\n\njulia> a = [1, 2, 4, 3, 4]\n5-element Array{Int64,1}:\n 1\n 2\n 4\n 3\n 4\n\njulia> partialsort!(a, 4, rev=true)\n2\n\njulia> a\n5-element Array{Int64,1}:\n 4\n 4\n 3\n 2\n 1\n```\n\"\"\"\npartialsort!(v::AbstractVector, k::Union{Integer,OrdinalRange};\n lt=isless, by=identity, rev::Union{Bool,Nothing}=nothing, order::Ordering=Forward) =\n partialsort!(v, k, ord(lt,by,rev,order))\n\n\"\"\"\n partialsort(v, k, by=, lt=, rev=false)\n\nVariant of [`partialsort!`](@ref) which copies `v` before partially sorting it, thereby returning the\nsame thing as `partialsort!` but leaving `v` unmodified.\n\"\"\"\npartialsort(v::AbstractVector, k::Union{Integer,OrdinalRange}; kws...) =\n partialsort!(copymutable(v), k; kws...)\n\n# This implementation of `midpoint` is performance-optimized but safe\n# only if `lo <= hi`.\nmidpoint(lo::T, hi::T) where T<:Integer = lo + ((hi - lo) >>> 0x01)\nmidpoint(lo::Integer, hi::Integer) = midpoint(promote(lo, hi)...)\n\n# reference on sorted binary search:\n# http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary\n\n# index of the first value of vector a that is greater than or equal to x;\n# returns length(v)+1 if x is greater than all values in v.\nfunction searchsortedfirst(v::AbstractVector, x, lo::T, hi::T, o::Ordering)::keytype(v) where T<:Integer\n u = T(1)\n lo = lo - u\n hi = hi + u\n @inbounds while lo < hi - u\n m = midpoint(lo, hi)\n if lt(o, v[m], x)\n lo = m\n else\n hi = m\n end\n end\n return hi\nend\n\n# index of the last value of vector a that is less than or equal to x;\n# returns 0 if x is less than all values of v.\nfunction searchsortedlast(v::AbstractVector, x, lo::T, hi::T, o::Ordering)::keytype(v) where T<:Integer\n u = T(1)\n lo = lo - u\n hi = hi + u\n @inbounds while lo < hi - u\n m = midpoint(lo, hi)\n if lt(o, x, v[m])\n hi = m\n else\n lo = m\n end\n end\n return lo\nend\n\n# returns the range of indices of v equal to x\n# if v does not contain x, returns a 0-length range\n# indicating the insertion point of x\nfunction searchsorted(v::AbstractVector, x, ilo::T, ihi::T, o::Ordering)::UnitRange{keytype(v)} where T<:Integer\n u = T(1)\n lo = ilo - u\n hi = ihi + u\n @inbounds while lo < hi - u\n m = midpoint(lo, hi)\n if lt(o, v[m], x)\n lo = m\n elseif lt(o, x, v[m])\n hi = m\n else\n a = searchsortedfirst(v, x, max(lo,ilo), m, o)\n b = searchsortedlast(v, x, m, min(hi,ihi), o)\n return a : b\n end\n end\n return (lo + 1) : (hi - 1)\nend\n\nfunction searchsortedlast(a::AbstractRange{<:Real}, x::Real, o::DirectOrdering)::keytype(a)\n require_one_based_indexing(a)\n if step(a) == 0\n lt(o, x, first(a)) ? 0 : length(a)\n else\n n = round(Integer, clamp((x - first(a)) / step(a) + 1, 1, length(a)))\n lt(o, x, a[n]) ? n - 1 : n\n end\nend\n\nfunction searchsortedfirst(a::AbstractRange{<:Real}, x::Real, o::DirectOrdering)::keytype(a)\n require_one_based_indexing(a)\n if step(a) == 0\n lt(o, first(a), x) ? length(a) + 1 : 1\n else\n n = round(Integer, clamp((x - first(a)) / step(a) + 1, 1, length(a)))\n lt(o, a[n] ,x) ? n + 1 : n\n end\nend\n\nfunction searchsortedlast(a::AbstractRange{<:Integer}, x::Real, o::DirectOrdering)::keytype(a)\n require_one_based_indexing(a)\n h = step(a)\n if h == 0\n lt(o, x, first(a)) ? 0 : length(a)\n elseif h > 0 && x < first(a)\n firstindex(a) - 1\n elseif h > 0 && x >= last(a)\n lastindex(a)\n elseif h < 0 && x > first(a)\n firstindex(a) - 1\n elseif h < 0 && x <= last(a)\n lastindex(a)\n else\n if o isa ForwardOrdering\n fld(floor(Integer, x) - first(a), h) + 1\n else\n fld(ceil(Integer, x) - first(a), h) + 1\n end\n end\nend\n\nfunction searchsortedfirst(a::AbstractRange{<:Integer}, x::Real, o::DirectOrdering)::keytype(a)\n require_one_based_indexing(a)\n h = step(a)\n if h == 0\n lt(o, first(a), x) ? length(a)+1 : 1\n elseif h > 0 && x <= first(a)\n firstindex(a)\n elseif h > 0 && x > last(a)\n lastindex(a) + 1\n elseif h < 0 && x >= first(a)\n firstindex(a)\n elseif h < 0 && x < last(a)\n lastindex(a) + 1\n else\n if o isa ForwardOrdering\n -fld(floor(Integer, -x) + Signed(first(a)), h) + 1\n else\n -fld(ceil(Integer, -x) + Signed(first(a)), h) + 1\n end\n end\nend\n\nfunction searchsortedfirst(a::AbstractRange{<:Integer}, x::Unsigned, o::DirectOrdering)::keytype(a)\n require_one_based_indexing(a)\n if lt(o, first(a), x)\n if step(a) == 0\n length(a) + 1\n else\n min(cld(x - first(a), step(a)), length(a)) + 1\n end\n else\n 1\n end\nend\n\nfunction searchsortedlast(a::AbstractRange{<:Integer}, x::Unsigned, o::DirectOrdering)::keytype(a)\n require_one_based_indexing(a)\n if lt(o, x, first(a))\n 0\n elseif step(a) == 0\n length(a)\n else\n min(fld(x - first(a), step(a)) + 1, length(a))\n end\nend\n\nsearchsorted(a::AbstractRange{<:Real}, x::Real, o::DirectOrdering) =\n searchsortedfirst(a, x, o) : searchsortedlast(a, x, o)\n\nfor s in [:searchsortedfirst, :searchsortedlast, :searchsorted]\n @eval begin\n $s(v::AbstractVector, x, o::Ordering) = (inds = axes(v, 1); $s(v,x,first(inds),last(inds),o))\n $s(v::AbstractVector, x;\n lt=isless, by=identity, rev::Union{Bool,Nothing}=nothing, order::Ordering=Forward) =\n $s(v,x,ord(lt,by,rev,order))\n end\nend\n\n\"\"\"\n searchsorted(a, x; by=, lt=, rev=false)\n\nReturn the range of indices of `a` which compare as equal to `x` (using binary search)\naccording to the order specified by the `by`, `lt` and `rev` keywords, assuming that `a`\nis already sorted in that order. Return an empty range located at the insertion point\nif `a` does not contain values equal to `x`.\n\n# Examples\n```jldoctest\njulia> searchsorted([1, 2, 4, 5, 5, 7], 4) # single match\n3:3\n\njulia> searchsorted([1, 2, 4, 5, 5, 7], 5) # multiple matches\n4:5\n\njulia> searchsorted([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle\n3:2\n\njulia> searchsorted([1, 2, 4, 5, 5, 7], 9) # no match, insert at end\n7:6\n\njulia> searchsorted([1, 2, 4, 5, 5, 7], 0) # no match, insert at start\n1:0\n```\n\"\"\" searchsorted\n\n\"\"\"\n searchsortedfirst(a, x; by=, lt=, rev=false)\n\nReturn the index of the first value in `a` greater than or equal to `x`, according to the\nspecified order. Return `length(a) + 1` if `x` is greater than all values in `a`.\n`a` is assumed to be sorted.\n\n# Examples\n```jldoctest\njulia> searchsortedfirst([1, 2, 4, 5, 5, 7], 4) # single match\n3\n\njulia> searchsortedfirst([1, 2, 4, 5, 5, 7], 5) # multiple matches\n4\n\njulia> searchsortedfirst([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle\n3\n\njulia> searchsortedfirst([1, 2, 4, 5, 5, 7], 9) # no match, insert at end\n7\n\njulia> searchsortedfirst([1, 2, 4, 5, 5, 7], 0) # no match, insert at start\n1\n```\n\"\"\" searchsortedfirst\n\n\"\"\"\n searchsortedlast(a, x; by=, lt=, rev=false)\n\nReturn the index of the last value in `a` less than or equal to `x`, according to the\nspecified order. Return `0` if `x` is less than all values in `a`. `a` is assumed to\nbe sorted.\n\n# Examples\n```jldoctest\njulia> searchsortedlast([1, 2, 4, 5, 5, 7], 4) # single match\n3\n\njulia> searchsortedlast([1, 2, 4, 5, 5, 7], 5) # multiple matches\n5\n\njulia> searchsortedlast([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle\n2\n\njulia> searchsortedlast([1, 2, 4, 5, 5, 7], 9) # no match, insert at end\n6\n\njulia> searchsortedlast([1, 2, 4, 5, 5, 7], 0) # no match, insert at start\n0\n```\n\"\"\" searchsortedlast\n\n\n## sorting algorithms ##\n\nabstract type Algorithm end\n\nstruct InsertionSortAlg <: Algorithm end\nstruct QuickSortAlg <: Algorithm end\nstruct MergeSortAlg <: Algorithm end\n\n\"\"\"\n PartialQuickSort{T <: Union{Integer,OrdinalRange}}\n\nIndicate that a sorting function should use the partial quick sort\nalgorithm. Partial quick sort returns the smallest `k` elements sorted from smallest\nto largest, finding them and sorting them using [`QuickSort`](@ref).\n\nCharacteristics:\n * *not stable*: does not preserve the ordering of elements which\n compare equal (e.g. \"a\" and \"A\" in a sort of letters which\n ignores case).\n * *in-place* in memory.\n * *divide-and-conquer*: sort strategy similar to [`MergeSort`](@ref).\n\"\"\"\nstruct PartialQuickSort{T <: Union{Integer,OrdinalRange}} <: Algorithm\n k::T\nend\n\n\n\"\"\"\n InsertionSort\n\nIndicate that a sorting function should use the insertion sort\nalgorithm. Insertion sort traverses the collection one element\nat a time, inserting each element into its correct, sorted position in\nthe output list.\n\nCharacteristics:\n * *stable*: preserves the ordering of elements which\n compare equal (e.g. \"a\" and \"A\" in a sort of letters\n which ignores case).\n * *in-place* in memory.\n * *quadratic performance* in the number of elements to be sorted:\n it is well-suited to small collections but should not be used for large ones.\n\"\"\"\nconst InsertionSort = InsertionSortAlg()\n\"\"\"\n QuickSort\n\nIndicate that a sorting function should use the quick sort\nalgorithm, which is *not* stable.\n\nCharacteristics:\n * *not stable*: does not preserve the ordering of elements which\n compare equal (e.g. \"a\" and \"A\" in a sort of letters which\n ignores case).\n * *in-place* in memory.\n * *divide-and-conquer*: sort strategy similar to [`MergeSort`](@ref).\n * *good performance* for large collections.\n\"\"\"\nconst QuickSort = QuickSortAlg()\n\"\"\"\n MergeSort\n\nIndicate that a sorting function should use the merge sort\nalgorithm. Merge sort divides the collection into\nsubcollections and repeatedly merges them, sorting each\nsubcollection at each step, until the entire\ncollection has been recombined in sorted form.\n\nCharacteristics:\n * *stable*: preserves the ordering of elements which compare\n equal (e.g. \"a\" and \"A\" in a sort of letters which ignores\n case).\n * *not in-place* in memory.\n * *divide-and-conquer* sort strategy.\n\"\"\"\nconst MergeSort = MergeSortAlg()\n\nconst DEFAULT_UNSTABLE = QuickSort\nconst DEFAULT_STABLE = MergeSort\nconst SMALL_ALGORITHM = InsertionSort\nconst SMALL_THRESHOLD = 20\n\nfunction sort!(v::AbstractVector, lo::Integer, hi::Integer, ::InsertionSortAlg, o::Ordering)\n @inbounds for i = lo+1:hi\n j = i\n x = v[i]\n while j > lo\n if lt(o, x, v[j-1])\n v[j] = v[j-1]\n j -= 1\n continue\n end\n break\n end\n v[j] = x\n end\n return v\nend\n\n# selectpivot!\n#\n# Given 3 locations in an array (lo, mi, and hi), sort v[lo], v[mi], v[hi]) and\n# choose the middle value as a pivot\n#\n# Upon return, the pivot is in v[lo], and v[hi] is guaranteed to be\n# greater than the pivot\n\n@inline function selectpivot!(v::AbstractVector, lo::Integer, hi::Integer, o::Ordering)\n @inbounds begin\n mi = midpoint(lo, hi)\n\n # sort v[mi] <= v[lo] <= v[hi] such that the pivot is immediately in place\n if lt(o, v[lo], v[mi])\n v[mi], v[lo] = v[lo], v[mi]\n end\n\n if lt(o, v[hi], v[lo])\n if lt(o, v[hi], v[mi])\n v[hi], v[lo], v[mi] = v[lo], v[mi], v[hi]\n else\n v[hi], v[lo] = v[lo], v[hi]\n end\n end\n\n # return the pivot\n return v[lo]\n end\nend\n\n# partition!\n#\n# select a pivot, and partition v according to the pivot\n\nfunction partition!(v::AbstractVector, lo::Integer, hi::Integer, o::Ordering)\n pivot = selectpivot!(v, lo, hi, o)\n # pivot == v[lo], v[hi] > pivot\n i, j = lo, hi\n @inbounds while true\n i += 1; j -= 1\n while lt(o, v[i], pivot); i += 1; end;\n while lt(o, pivot, v[j]); j -= 1; end;\n i >= j && break\n v[i], v[j] = v[j], v[i]\n end\n v[j], v[lo] = pivot, v[j]\n\n # v[j] == pivot\n # v[k] >= pivot for k > j\n # v[i] <= pivot for i < j\n return j\nend\n\nfunction sort!(v::AbstractVector, lo::Integer, hi::Integer, a::QuickSortAlg, o::Ordering)\n @inbounds while lo < hi\n hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o)\n j = partition!(v, lo, hi, o)\n if j-lo < hi-j\n # recurse on the smaller chunk\n # this is necessary to preserve O(log(n))\n # stack space in the worst case (rather than O(n))\n lo < (j-1) && sort!(v, lo, j-1, a, o)\n lo = j+1\n else\n j+1 < hi && sort!(v, j+1, hi, a, o)\n hi = j-1\n end\n end\n return v\nend\n\nfunction sort!(v::AbstractVector, lo::Integer, hi::Integer, a::MergeSortAlg, o::Ordering, t=similar(v,0))\n @inbounds if lo < hi\n hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o)\n\n m = midpoint(lo, hi)\n (length(t) < m-lo+1) && resize!(t, m-lo+1)\n\n sort!(v, lo, m, a, o, t)\n sort!(v, m+1, hi, a, o, t)\n\n i, j = 1, lo\n while j <= m\n t[i] = v[j]\n i += 1\n j += 1\n end\n\n i, k = 1, lo\n while k < j <= hi\n if lt(o, v[j], t[i])\n v[k] = v[j]\n j += 1\n else\n v[k] = t[i]\n i += 1\n end\n k += 1\n end\n while k < j\n v[k] = t[i]\n k += 1\n i += 1\n end\n end\n\n return v\nend\n\nfunction sort!(v::AbstractVector, lo::Integer, hi::Integer, a::PartialQuickSort{<:Integer},\n o::Ordering)\n @inbounds while lo < hi\n hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o)\n j = partition!(v, lo, hi, o)\n if j >= a.k\n # we don't need to sort anything bigger than j\n hi = j-1\n elseif j-lo < hi-j\n # recurse on the smaller chunk\n # this is necessary to preserve O(log(n))\n # stack space in the worst case (rather than O(n))\n lo < (j-1) && sort!(v, lo, j-1, a, o)\n lo = j+1\n else\n (j+1) < hi && sort!(v, j+1, hi, a, o)\n hi = j-1\n end\n end\n return v\nend\n\n\nfunction sort!(v::AbstractVector, lo::Integer, hi::Integer, a::PartialQuickSort{T},\n o::Ordering) where T<:OrdinalRange\n @inbounds while lo < hi\n hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o)\n j = partition!(v, lo, hi, o)\n\n if j <= first(a.k)\n lo = j+1\n elseif j >= last(a.k)\n hi = j-1\n else\n if j-lo < hi-j\n lo < (j-1) && sort!(v, lo, j-1, a, o)\n lo = j+1\n else\n hi > (j+1) && sort!(v, j+1, hi, a, o)\n hi = j-1\n end\n end\n end\n return v\nend\n\n\n## generic sorting methods ##\n\ndefalg(v::AbstractArray) = DEFAULT_STABLE\ndefalg(v::AbstractArray{<:Union{Number, Missing}}) = DEFAULT_UNSTABLE\n\nfunction sort!(v::AbstractVector, alg::Algorithm, order::Ordering)\n inds = axes(v,1)\n sort!(v,first(inds),last(inds),alg,order)\nend\n\n\"\"\"\n sort!(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nSort the vector `v` in place. [`QuickSort`](@ref) is used by default for numeric arrays while\n[`MergeSort`](@ref) is used for other arrays. You can specify an algorithm to use via the `alg`\nkeyword (see [Sorting Algorithms](@ref) for available algorithms). The `by` keyword lets you provide\na function that will be applied to each element before comparison; the `lt` keyword allows\nproviding a custom \"less than\" function; use `rev=true` to reverse the sorting order. These\noptions are independent and can be used together in all possible combinations: if both `by`\nand `lt` are specified, the `lt` function is applied to the result of the `by` function;\n`rev=true` reverses whatever ordering specified via the `by` and `lt` keywords.\n\n# Examples\n```jldoctest\njulia> v = [3, 1, 2]; sort!(v); v\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> v = [3, 1, 2]; sort!(v, rev = true); v\n3-element Array{Int64,1}:\n 3\n 2\n 1\n\njulia> v = [(1, \"c\"), (3, \"a\"), (2, \"b\")]; sort!(v, by = x -> x[1]); v\n3-element Array{Tuple{Int64,String},1}:\n (1, \"c\")\n (2, \"b\")\n (3, \"a\")\n\njulia> v = [(1, \"c\"), (3, \"a\"), (2, \"b\")]; sort!(v, by = x -> x[2]); v\n3-element Array{Tuple{Int64,String},1}:\n (3, \"a\")\n (2, \"b\")\n (1, \"c\")\n```\n\"\"\"\nfunction sort!(v::AbstractVector;\n alg::Algorithm=defalg(v),\n lt=isless,\n by=identity,\n rev::Union{Bool,Nothing}=nothing,\n order::Ordering=Forward)\n ordr = ord(lt,by,rev,order)\n if (ordr === Forward || ordr === Reverse) && eltype(v)<:Integer\n n = length(v)\n if n > 1\n min, max = extrema(v)\n (diff, o1) = sub_with_overflow(max, min)\n (rangelen, o2) = add_with_overflow(diff, oneunit(diff))\n if !o1 && !o2 && rangelen < div(n,2)\n return sort_int_range!(v, rangelen, min, ordr === Reverse ? reverse : identity)\n end\n end\n end\n sort!(v, alg, ordr)\nend\n\n# sort! for vectors of few unique integers\nfunction sort_int_range!(x::AbstractVector{<:Integer}, rangelen, minval, maybereverse)\n offs = 1 - minval\n\n where = fill(0, rangelen)\n @inbounds for i = eachindex(x)\n where[x[i] + offs] += 1\n end\n\n idx = firstindex(x)\n @inbounds for i = maybereverse(1:rangelen)\n lastidx = idx + where[i] - 1\n val = i-offs\n for j = idx:lastidx\n x[j] = val\n end\n idx = lastidx + 1\n end\n\n return x\nend\n\n\"\"\"\n sort(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nVariant of [`sort!`](@ref) that returns a sorted copy of `v` leaving `v` itself unmodified.\n\n# Examples\n```jldoctest\njulia> v = [3, 1, 2];\n\njulia> sort(v)\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> v\n3-element Array{Int64,1}:\n 3\n 1\n 2\n```\n\"\"\"\nsort(v::AbstractVector; kws...) = sort!(copymutable(v); kws...)\n\n## partialsortperm: the permutation to sort the first k elements of an array ##\n\n\"\"\"\n partialsortperm(v, k; by=, lt=, rev=false)\n\nReturn a partial permutation `I` of the vector `v`, so that `v[I]` returns values of a fully\nsorted version of `v` at index `k`. If `k` is a range, a vector of indices is returned; if\n`k` is an integer, a single index is returned. The order is specified using the same\nkeywords as `sort!`. The permutation is stable, meaning that indices of equal elements\nappear in ascending order.\n\nNote that this function is equivalent to, but more efficient than, calling `sortperm(...)[k]`.\n\n# Examples\n```jldoctest\njulia> v = [3, 1, 2, 1];\n\njulia> v[partialsortperm(v, 1)]\n1\n\njulia> p = partialsortperm(v, 1:3)\n3-element view(::Array{Int64,1}, 1:3) with eltype Int64:\n 2\n 4\n 3\n\njulia> v[p]\n3-element Array{Int64,1}:\n 1\n 1\n 2\n```\n\"\"\"\npartialsortperm(v::AbstractVector, k::Union{Integer,OrdinalRange}; kwargs...) =\n partialsortperm!(similar(Vector{eltype(k)}, axes(v,1)), v, k; kwargs..., initialized=false)\n\n\"\"\"\n partialsortperm!(ix, v, k; by=, lt=, rev=false, initialized=false)\n\nLike [`partialsortperm`](@ref), but accepts a preallocated index vector `ix` the same size as\n`v`, which is used to store (a permutation of) the indices of `v`.\n\nIf the index vector `ix` is initialized with the indices of `v` (or a permutation thereof), `initialized` should be set to\n`true`.\n\nIf `initialized` is `false` (the default), then `ix` is initialized to contain the indices of `v`.\n\nIf `initialized` is `true`, but `ix` does not contain (a permutation of) the indices of `v`, the behavior of\n`partialsortperm!` is undefined.\n\n(Typically, the indices of `v` will be `1:length(v)`, although if `v` has an alternative array type\nwith non-one-based indices, such as an `OffsetArray`, `ix` must also be an `OffsetArray` with the same\nindices, and must contain as values (a permutation of) these same indices.)\n\nUpon return, `ix` is guaranteed to have the indices `k` in their sorted positions, such that\n\n```julia\npartialsortperm!(ix, v, k);\nv[ix[k]] == partialsort(v, k)\n```\n\nThe return value is the `k`th element of `ix` if `k` is an integer, or view into `ix` if `k` is\na range.\n\n# Examples\n```jldoctest\njulia> v = [3, 1, 2, 1];\n\njulia> ix = Vector{Int}(undef, 4);\n\njulia> partialsortperm!(ix, v, 1)\n2\n\njulia> ix = [1:4;];\n\njulia> partialsortperm!(ix, v, 2:3, initialized=true)\n2-element view(::Array{Int64,1}, 2:3) with eltype Int64:\n 4\n 3\n```\n \"\"\"\nfunction partialsortperm!(ix::AbstractVector{<:Integer}, v::AbstractVector,\n k::Union{Integer, OrdinalRange};\n lt::Function=isless,\n by::Function=identity,\n rev::Union{Bool,Nothing}=nothing,\n order::Ordering=Forward,\n initialized::Bool=false)\n if axes(ix,1) != axes(v,1)\n throw(ArgumentError(\"The index vector is used as a workspace and must have the \" *\n \"same length/indices as the source vector, $(axes(ix,1)) != $(axes(v,1))\"))\n end\n if !initialized\n @inbounds for i = axes(ix,1)\n ix[i] = i\n end\n end\n\n # do partial quicksort\n sort!(ix, PartialQuickSort(k), Perm(ord(lt, by, rev, order), v))\n\n maybeview(ix, k)\nend\n\n## sortperm: the permutation to sort an array ##\n\n\"\"\"\n sortperm(v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nReturn a permutation vector `I` that puts `v[I]` in sorted order. The order is specified\nusing the same keywords as [`sort!`](@ref). The permutation is guaranteed to be stable even\nif the sorting algorithm is unstable, meaning that indices of equal elements appear in\nascending order.\n\nSee also [`sortperm!`](@ref).\n\n# Examples\n```jldoctest\njulia> v = [3, 1, 2];\n\njulia> p = sortperm(v)\n3-element Array{Int64,1}:\n 2\n 3\n 1\n\njulia> v[p]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n```\n\"\"\"\nfunction sortperm(v::AbstractVector;\n alg::Algorithm=DEFAULT_UNSTABLE,\n lt=isless,\n by=identity,\n rev::Union{Bool,Nothing}=nothing,\n order::Ordering=Forward)\n ordr = ord(lt,by,rev,order)\n if ordr === Forward && isa(v,Vector) && eltype(v)<:Integer\n n = length(v)\n if n > 1\n min, max = extrema(v)\n (diff, o1) = sub_with_overflow(max, min)\n (rangelen, o2) = add_with_overflow(diff, oneunit(diff))\n if !o1 && !o2 && rangelen < div(n,2)\n return sortperm_int_range(v, rangelen, min)\n end\n end\n end\n ax = axes(v, 1)\n p = similar(Vector{eltype(ax)}, ax)\n for (i,ind) in zip(eachindex(p), ax)\n p[i] = ind\n end\n sort!(p, alg, Perm(ordr,v))\nend\n\n\n\"\"\"\n sortperm!(ix, v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward, initialized::Bool=false)\n\nLike [`sortperm`](@ref), but accepts a preallocated index vector `ix`. If `initialized` is `false`\n(the default), `ix` is initialized to contain the values `1:length(v)`.\n\n# Examples\n```jldoctest\njulia> v = [3, 1, 2]; p = zeros(Int, 3);\n\njulia> sortperm!(p, v); p\n3-element Array{Int64,1}:\n 2\n 3\n 1\n\njulia> v[p]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n```\n\"\"\"\nfunction sortperm!(x::AbstractVector{<:Integer}, v::AbstractVector;\n alg::Algorithm=DEFAULT_UNSTABLE,\n lt=isless,\n by=identity,\n rev::Union{Bool,Nothing}=nothing,\n order::Ordering=Forward,\n initialized::Bool=false)\n if axes(x,1) != axes(v,1)\n throw(ArgumentError(\"index vector must have the same length/indices as the source vector, $(axes(x,1)) != $(axes(v,1))\"))\n end\n if !initialized\n @inbounds for i = axes(v,1)\n x[i] = i\n end\n end\n sort!(x, alg, Perm(ord(lt,by,rev,order),v))\nend\n\n# sortperm for vectors of few unique integers\nfunction sortperm_int_range(x::Vector{<:Integer}, rangelen, minval)\n offs = 1 - minval\n n = length(x)\n\n where = fill(0, rangelen+1)\n where[1] = 1\n @inbounds for i = 1:n\n where[x[i] + offs + 1] += 1\n end\n\n #cumsum!(where, where)\n @inbounds for i = 2:length(where)\n where[i] += where[i-1]\n end\n\n P = Vector{Int}(undef, n)\n @inbounds for i = 1:n\n label = x[i] + offs\n P[where[label]] = i\n where[label] += 1\n end\n\n return P\nend\n\n## sorting multi-dimensional arrays ##\n\n\"\"\"\n sort(A; dims::Integer, alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nSort a multidimensional array `A` along the given dimension.\nSee [`sort!`](@ref) for a description of possible\nkeyword arguments.\n\nTo sort slices of an array, refer to [`sortslices`](@ref).\n\n# Examples\n```jldoctest\njulia> A = [4 3; 1 2]\n2×2 Array{Int64,2}:\n 4 3\n 1 2\n\njulia> sort(A, dims = 1)\n2×2 Array{Int64,2}:\n 1 2\n 4 3\n\njulia> sort(A, dims = 2)\n2×2 Array{Int64,2}:\n 3 4\n 1 2\n```\n\"\"\"\nfunction sort(A::AbstractArray;\n dims::Integer,\n alg::Algorithm=DEFAULT_UNSTABLE,\n lt=isless,\n by=identity,\n rev::Union{Bool,Nothing}=nothing,\n order::Ordering=Forward)\n dim = dims\n order = ord(lt,by,rev,order)\n n = length(axes(A, dim))\n if dim != 1\n pdims = (dim, setdiff(1:ndims(A), dim)...) # put the selected dimension first\n Ap = permutedims(A, pdims)\n Av = vec(Ap)\n sort_chunks!(Av, n, alg, order)\n permutedims(Ap, invperm(pdims))\n else\n Av = A[:]\n sort_chunks!(Av, n, alg, order)\n reshape(Av, axes(A))\n end\nend\n\n@noinline function sort_chunks!(Av, n, alg, order)\n inds = LinearIndices(Av)\n for s = first(inds):n:last(inds)\n sort!(Av, s, s+n-1, alg, order)\n end\n Av\nend\n\n\"\"\"\n sort!(A; dims::Integer, alg::Algorithm=defalg(A), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nSort the multidimensional array `A` along dimension `dims`.\nSee [`sort!`](@ref) for a description of possible keyword arguments.\n\nTo sort slices of an array, refer to [`sortslices`](@ref).\n\n!!! compat \"Julia 1.1\"\n This function requires at least Julia 1.1.\n\n# Examples\n```jldoctest\njulia> A = [4 3; 1 2]\n2×2 Array{Int64,2}:\n 4 3\n 1 2\n\njulia> sort!(A, dims = 1); A\n2×2 Array{Int64,2}:\n 1 2\n 4 3\n\njulia> sort!(A, dims = 2); A\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n```\n\"\"\"\nfunction sort!(A::AbstractArray;\n dims::Integer,\n alg::Algorithm=defalg(A),\n lt=isless,\n by=identity,\n rev::Union{Bool,Nothing}=nothing,\n order::Ordering=Forward)\n ordr = ord(lt, by, rev, order)\n nd = ndims(A)\n k = dims\n\n 1 <= k <= nd || throw(ArgumentError(\"dimension out of range\"))\n\n remdims = ntuple(i -> i == k ? 1 : size(A, i), nd)\n for idx in CartesianIndices(remdims)\n Av = view(A, ntuple(i -> i == k ? Colon() : idx[i], nd)...)\n sort!(Av, alg, ordr)\n end\n A\nend\n\n## fast clever sorting for floats ##\n\nmodule Float\nusing ..Sort\nusing ...Order\nusing ..Base: @inbounds, AbstractVector, Vector, last, axes\n\nimport Core.Intrinsics: slt_int\nimport ..Sort: sort!\nimport ...Order: lt, DirectOrdering\n\nconst Floats = Union{Float32,Float64}\n\nstruct Left <: Ordering end\nstruct Right <: Ordering end\n\nleft(::DirectOrdering) = Left()\nright(::DirectOrdering) = Right()\n\nleft(o::Perm) = Perm(left(o.order), o.data)\nright(o::Perm) = Perm(right(o.order), o.data)\n\nlt(::Left, x::T, y::T) where {T<:Floats} = slt_int(y, x)\nlt(::Right, x::T, y::T) where {T<:Floats} = slt_int(x, y)\n\nisnan(o::DirectOrdering, x::Floats) = (x!=x)\nisnan(o::Perm, i::Integer) = isnan(o.order,o.data[i])\n\nfunction nans2left!(v::AbstractVector, o::Ordering, lo::Integer=first(axes(v,1)), hi::Integer=last(axes(v,1)))\n i = lo\n @inbounds while i <= hi && isnan(o,v[i])\n i += 1\n end\n j = i + 1\n @inbounds while j <= hi\n if isnan(o,v[j])\n v[i], v[j] = v[j], v[i]\n i += 1\n end\n j += 1\n end\n return i, hi\nend\nfunction nans2right!(v::AbstractVector, o::Ordering, lo::Integer=first(axes(v,1)), hi::Integer=last(axes(v,1)))\n i = hi\n @inbounds while lo <= i && isnan(o,v[i])\n i -= 1\n end\n j = i - 1\n @inbounds while lo <= j\n if isnan(o,v[j])\n v[i], v[j] = v[j], v[i]\n i -= 1\n end\n j -= 1\n end\n return lo, i\nend\n\nnans2end!(v::AbstractVector, o::ForwardOrdering) = nans2right!(v,o)\nnans2end!(v::AbstractVector, o::ReverseOrdering) = nans2left!(v,o)\nnans2end!(v::AbstractVector{<:Integer}, o::Perm{<:ForwardOrdering}) = nans2right!(v,o)\nnans2end!(v::AbstractVector{<:Integer}, o::Perm{<:ReverseOrdering}) = nans2left!(v,o)\n\nissignleft(o::ForwardOrdering, x::Floats) = lt(o, x, zero(x))\nissignleft(o::ReverseOrdering, x::Floats) = lt(o, x, -zero(x))\nissignleft(o::Perm, i::Integer) = issignleft(o.order, o.data[i])\n\nfunction fpsort!(v::AbstractVector, a::Algorithm, o::Ordering)\n i, j = lo, hi = nans2end!(v,o)\n @inbounds while true\n while i <= j && issignleft(o,v[i]); i += 1; end\n while i <= j && !issignleft(o,v[j]); j -= 1; end\n i <= j || break\n v[i], v[j] = v[j], v[i]\n i += 1; j -= 1\n end\n sort!(v, lo, j, a, left(o))\n sort!(v, i, hi, a, right(o))\n return v\nend\n\n\nfpsort!(v::AbstractVector, a::Sort.PartialQuickSort, o::Ordering) =\n sort!(v, first(axes(v,1)), last(axes(v,1)), a, o)\n\nsort!(v::AbstractVector{<:Floats}, a::Algorithm, o::DirectOrdering) = fpsort!(v,a,o)\nsort!(v::Vector{Int}, a::Algorithm, o::Perm{<:DirectOrdering,<:Vector{<:Floats}}) = fpsort!(v,a,o)\n\nend # module Sort.Float\n\nend # module Sort\n", "meta": {"hexsha": "ff8edf15bd645d160561df6d8c537e9d70066c41", "size": 33279, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "base/sort.jl", "max_stars_repo_name": "TimoLarson/julia", "max_stars_repo_head_hexsha": "38f2c594c49cec46d38be6dd614a5592582a3016", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-06-25T00:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T12:06:34.000Z", "max_issues_repo_path": "base/sort.jl", "max_issues_repo_name": "TimoLarson/julia", "max_issues_repo_head_hexsha": "38f2c594c49cec46d38be6dd614a5592582a3016", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-30T22:03:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-13T22:12:07.000Z", "max_forks_repo_path": "base/sort.jl", "max_forks_repo_name": "TimoLarson/julia", "max_forks_repo_head_hexsha": "38f2c594c49cec46d38be6dd614a5592582a3016", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-08-11T12:41:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T10:20:16.000Z", "avg_line_length": 27.48059455, "max_line_length": 144, "alphanum_fraction": 0.596111662, "num_tokens": 10488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2357087954044889}} {"text": "################################################################################\n#\n#\tINTERFACE FOR DEFAULT POINTS IN RECIPROCAL SPACE\n#\t(implementations see below)\n#\n################################################################################\n\n# general interface\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Symbol,\n instance :: Int64 = 1\n ) :: R where {D,N,LS,LB, R<:AbstractReciprocalPoint{D}, S<:AbstractSite{LS,D}, B<:AbstractBond{LB,N}, U<:AbstractUnitcell{S,B}}\n\n # maybe instance is passed from another source in some notation as e.g. X_2\n if instance == 1 && occursin('_', string(identifier))\n return getReciprocalPoint(R, unitcell, Val(Symbol(split(string(identifier),'_')[1])), Val(Meta.eval(Meta.parse(split(string(identifier),'_')[2]))))\n end\n # return the specific val typed function\n return getReciprocalPoint(R, unitcell, Val(identifier), Val(instance))\nend\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Tuple{Symbol, Int64}\n ) :: R where {D,N,LS,LB, R<:AbstractReciprocalPoint{D}, S<:AbstractSite{LS,D}, B<:AbstractBond{LB,N}, U<:AbstractUnitcell{S,B}}\n\n # return the specific val typed function\n return getReciprocalPoint(R, unitcell, Val(identifier[1]), Val(identifier[2]))\nend\n\n# interface for own concrete reciprocal point type\nfunction getReciprocalPoint(\n unitcell :: U,\n identifier :: Symbol,\n instance :: Int64 = 1\n ) :: ReciprocalPoint{D} where {D,N,LS,LB, S<:AbstractSite{LS,D}, B<:AbstractBond{LB,N}, U<:AbstractUnitcell{S,B}}\n\n # maybe instance is passed from another source in some notation as e.g. X_2\n if instance == 1 && occursin('_', string(identifier))\n return getReciprocalPoint(ReciprocalPoint{D}, unitcell, Val(Symbol(split(string(identifier),'_')[1])), Val(Meta.eval(Meta.parse(split(string(identifier),'_')[2]))))\n end\n # return the specific val typed function\n return getReciprocalPoint(ReciprocalPoint{D}, unitcell, Val(identifier), Val(instance))\nend\n\n\n\n# Fallback for all functions\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{I1},\n instance :: Val{I2}\n ) :: R where {I1,I2,D,N,LS,LB, R<:AbstractReciprocalPoint{D}, S<:AbstractSite{LS,D}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # fallback / fail due to missing implementation\n error(\"Implementation of reciprocal point \" * string(I1) * \" (instance \" * string(I2) * \") not implemented yet \" *\n \"for concrete reciprocal point type \" * string(R) * \" and unitcells of dimension D=\" * string(D) * \" and N=\"*string(N))\nend\n\n\n# export the general interface function\nexport getReciprocalPoint\n\n\n\n\n\n################################################################################\n#\n#\tIMPLEMENTATIONS OF DEFAULT POINTS IN RECIPROCAL SPACE\n#\n################################################################################\n\n\n\n\n#########################\n#\n#\tGAMMA POINT\n#\n#########################\n\n# Gamma point in arbitrary dimension (Fallback)\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:Gamma},\n instance :: Val{I}\n ) :: R where {I,D,N,LS,LB, R<:AbstractReciprocalPoint{D}, S<:AbstractSite{LS,D}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # fallback / fail due to missing implementation\n error(\"Implementation of Gamma point in \" * string(D) * \" spatial dimensions missing \" *\n \"for concrete reciprocal point type \" * string(R))\nend\n\n# Gamma point in 2D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:Gamma},\n instance :: Val{I}\n ) :: R where {I,N,LS,LB, R<:AbstractReciprocalPoint{2}, S<:AbstractSite{LS,2}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # return the specific type\n return newReciprocalPoint(\n R,\n [0.0, 0.0],\n \"Gamma\",\n \"\\\\Gamma\"\n )\nend\n\n# Gamma point in 3D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:Gamma},\n instance :: Val{I}\n ) :: R where {I,N,LS,LB, R<:AbstractReciprocalPoint{3}, S<:AbstractSite{LS,3}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # return the specific type\n return newReciprocalPoint(\n R,\n [0.0, 0.0, 0.0],\n \"Gamma\",\n \"\\\\Gamma\"\n )\nend\n\n\n\n\n\n\n\n#########################\n#\n#\tK POINT (and K')\n#\n#########################\n\n# K point (Based on BZ object) in 2D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:K},\n instance :: Val{I}\n ) :: R where {D,I,N,LS,LB, R<:AbstractReciprocalPoint{2}, S<:AbstractSite{LS,2}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # get the bz\n bz = getBrillouinZone(getReciprocalUnitcell(unitcell))\n\n # return the specific type\n return newReciprocalPoint(\n R,\n corners(bz)[faces(bz)[1][mod(I,length(corners(bz))) + 1]],\n \"K\",\n \"K\"\n )\nend\n\n# K' point (Based on BZ object) in 2D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:Kp},\n instance :: Val{I}\n ) :: R where {D,I,N,LS,LB, R<:AbstractReciprocalPoint{2}, S<:AbstractSite{LS,2}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # get the bz\n bz = getBrillouinZone(getReciprocalUnitcell(unitcell))\n\n # return the specific type\n return newReciprocalPoint(\n R,\n corners(bz)[faces(bz)[1][mod(I+1,length(corners(bz))) + 1]],\n \"K\\'\",\n \"K\\'\"\n )\nend\n\n\n\n# K point (Based on BZ object) in 3D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:K},\n instance :: Val{I}\n ) :: R where {D,I,N,LS,LB, R<:AbstractReciprocalPoint{3}, S<:AbstractSite{LS,3}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # get the bz\n bz = getBrillouinZone(getReciprocalUnitcell(unitcell))\n\n # get the faceindex\n faceindex = mod(div(I, 10), length(faces(bz))) + 1\n face = faces(bz)[faceindex]\n # first and second index\n cornerindex = mod(I, 10)\n i = face[mod(cornerindex, length(face))+1]\n\n # return the specific type\n return newReciprocalPoint(\n R,\n corners(bz)[i],\n \"K\",\n \"K\"\n )\nend\n\n# K' point (Based on BZ object) in 3D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:Kp},\n instance :: Val{I}\n ) :: R where {D,I,N,LS,LB, R<:AbstractReciprocalPoint{3}, S<:AbstractSite{LS,3}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # get the bz\n bz = getBrillouinZone(getReciprocalUnitcell(unitcell))\n\n # get the faceindex\n faceindex = mod(div(I, 10), length(faces(bz))) + 1\n face = faces(bz)[faceindex]\n # first and second index\n cornerindex = mod(I, 10)\n i = face[mod(cornerindex+1, length(face))+1]\n\n # return the specific type\n return newReciprocalPoint(\n R,\n corners(bz)[i],\n \"K\\'\",\n \"K\\'\"\n )\nend\n\n\n\n\n\n\n#########################\n#\n#\tM POINT (and M')\n#\n#########################\n\n# M point (Based on BZ object) in 2D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:M},\n instance :: Val{I}\n ) :: R where {D,I,N,LS,LB, R<:AbstractReciprocalPoint{2}, S<:AbstractSite{LS,2}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # get the bz\n bz = getBrillouinZone(getReciprocalUnitcell(unitcell))\n\n # first and second index\n i1 = faces(bz)[1][mod(I-1,length(faces(bz)[1])) + 1]\n i2 = faces(bz)[1][mod(I,length(faces(bz)[1])) + 1]\n # find the first and next corner\n c1 = corners(bz)[i1]\n c2 = corners(bz)[i2]\n\n # return the specific type\n return newReciprocalPoint(\n R,\n (c1.+c2)./2,\n \"M\",\n \"M\"\n )\nend\n\n# M' point (Based on BZ object) in 2D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:Mp},\n instance :: Val{I}\n ) :: R where {D,I,N,LS,LB, R<:AbstractReciprocalPoint{2}, S<:AbstractSite{LS,2}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # get the bz\n bz = getBrillouinZone(getReciprocalUnitcell(unitcell))\n\n # first and second index\n i1 = faces(bz)[1][mod(I,length(faces(bz)[1])) + 1]\n i2 = faces(bz)[1][mod(I+1,length(faces(bz)[1])) + 1]\n # find the first and next corner\n c1 = corners(bz)[i1]\n c2 = corners(bz)[i2]\n\n # return the specific type\n return newReciprocalPoint(\n R,\n (c1.+c2)./2,\n \"M\\'\",\n \"M\\'\"\n )\nend\n\n\n\n# M point (Based on BZ object) in 3D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:M},\n instance :: Val{I}\n ) :: R where {D,I,N,LS,LB, R<:AbstractReciprocalPoint{3}, S<:AbstractSite{LS,3}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # get the bz\n bz = getBrillouinZone(getReciprocalUnitcell(unitcell))\n\n # get the faceindex\n faceindex = mod(div(I, 10), length(faces(bz))) + 1\n face = faces(bz)[faceindex]\n # first and second index\n cornerindex = mod(I, 10)\n i1 = face[mod(cornerindex-1, length(face)) + 1]\n i2 = face[mod(cornerindex, length(face)) + 1]\n # find the first and next corner\n c1 = corners(bz)[i1]\n c2 = corners(bz)[i2]\n\n # return the specific type\n return newReciprocalPoint(\n R,\n (c1.+c2)./2,\n \"M\",\n \"M\"\n )\nend\n\n# M' point (Based on BZ object) in 3D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:Mp},\n instance :: Val{I}\n ) :: R where {D,I,N,LS,LB, R<:AbstractReciprocalPoint{3}, S<:AbstractSite{LS,3}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # get the bz\n bz = getBrillouinZone(getReciprocalUnitcell(unitcell))\n\n # get the faceindex\n faceindex = mod(div(I, 10), length(faces(bz))) + 1\n face = faces(bz)[faceindex]\n # first and second index\n cornerindex = mod(I, 10)\n i1 = face[mod(cornerindex, length(face)) + 1]\n i2 = face[mod(cornerindex+1, length(face)) + 1]\n # find the first and next corner\n c1 = corners(bz)[i1]\n c2 = corners(bz)[i2]\n\n # return the specific type\n return newReciprocalPoint(\n R,\n (c1.+c2)./2,\n \"M\\'\",\n \"M\\'\"\n )\nend\n\n\n\n\n\n\n\n#########################\n#\n#\tX POINT (center of face)\n#\n#########################\n\n# X point (Based on BZ object) in 3D\nfunction getReciprocalPoint(\n :: Type{R},\n unitcell :: U,\n identifier :: Val{:X},\n instance :: Val{I}\n ) :: R where {D,I,N,LS,LB, R<:AbstractReciprocalPoint{3}, S<:AbstractSite{LS,3}, B<:AbstractBond{LB,N},U<:AbstractUnitcell{S,B}}\n\n # get the bz\n bz = getBrillouinZone(getReciprocalUnitcell(unitcell))\n\n # get the faceindex\n faceindex = mod(I-1, length(faces(bz))) + 1\n face = faces(bz)[faceindex]\n # find the center\n center = [0.0, 0.0, 0.0]\n for c in face\n center .+= corners(bz)[c]\n end\n center ./= length(face)\n\n # return the specific type\n return newReciprocalPoint(\n R,\n center,\n \"X\",\n \"X\"\n )\nend\n", "meta": {"hexsha": "1a58b8951155bd0373643309cbd71a601274cf1c", "size": 11609, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/reciprocal_points/default_points.jl", "max_stars_repo_name": "crstnbr/LatPhysReciprocal.jl", "max_stars_repo_head_hexsha": "67923b7f37b09c9395dd87ef04bae3ae2000ba77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/reciprocal_points/default_points.jl", "max_issues_repo_name": "crstnbr/LatPhysReciprocal.jl", "max_issues_repo_head_hexsha": "67923b7f37b09c9395dd87ef04bae3ae2000ba77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reciprocal_points/default_points.jl", "max_forks_repo_name": "crstnbr/LatPhysReciprocal.jl", "max_forks_repo_head_hexsha": "67923b7f37b09c9395dd87ef04bae3ae2000ba77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-13T15:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-09T20:01:53.000Z", "avg_line_length": 28.2457420925, "max_line_length": 172, "alphanum_fraction": 0.5544835903, "num_tokens": 3413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2354791944714021}} {"text": "struct Events{T <: DiseaseStateSequence}\n exposure::Union{Nothing, Vector{Float64}}\n infection::Vector{Float64}\n removal::Union{Nothing, Vector{Float64}}\n\n function Events{T}(e::V, i::V, r::V) where {T <: SEIR, V <: Vector{Float64}}\n if length(unique((length.([e; i; r])))) != 1\n @error \"Length of event time vectors must be equal\"\n end\n return new{T}(e, i, r)\n end\n\n function Events{T}(n::Integer) where T <: SEIR\n return new{T}(fill(NaN, n), fill(NaN, n), fill(NaN, n))\n end\n\n function Events{T}(e::V, i::V) where {T <: SEI, V <: Vector{Float64}}\n if length(unique((length.([e; i])))) != 1\n @error \"Length of event time vectors must be equal\"\n end\n return new{T}(e, i, nothing)\n end\n\n function Events{T}(n::Integer) where T <: SEI\n return new{T}(fill(NaN, n), fill(NaN, n), nothing)\n end\n\n function Events{T}(i::V, r::V) where {T <: SIR, V <: Vector{Float64}}\n if length(unique((length.([i; r])))) != 1\n @error \"Length of event time vectors must be equal\"\n end\n return new{T}(nothing, i, r)\n end\n\n function Events{T}(n::Integer) where T <: SIR\n return new{T}(nothing, fill(NaN, n), fill(NaN, n))\n end\n\n function Events{T}(i::V) where {T <: SI, V <: Vector{Float64}}\n return new{T}(nothing, i, nothing)\n end\n\n function Events{T}(n::Integer) where T <: SI\n return new{T}(nothing, fill(NaN, n), nothing)\n end\nend\n\nfunction Events{T}(a::Array{Float64,2}) where T <: DiseaseStateSequence\n if size(a, 2) == 3\n return Events{T}(a[:,1], a[:,2], a[:,3])\n elseif size(a, 2) == 2\n return Events{T}(a[:,1], a[:,2])\n elseif size(a, 2) == 1\n return Events{T}(a[:,1])\n else\n @error \"Invalid array size for construction of an $(Events{T}) object\"\n end\nend\n\nfunction Events{T}(x::DiseaseStates) where T <: DiseaseStateSequence\n events = Events{T}(length(x))\n for i = 1:length(x)\n if x[i] in convert(DiseaseStates, T)\n for j = convert(DiseaseStates, T)[2:findfirst(Ref(x[i]) .== convert(DiseaseStates, T))]\n events[j][i] = -Inf\n end\n else\n @error \"Invalid initial state for individual $i\"\n end\n end\n return events\nend\n\nfunction individuals(x::Events{M}) where{\n M <: DiseaseStateSequence}\n return length(x.infection)\nend\n\nfunction Base.show(io::IO, x::Events{T}) where T <: DiseaseStateSequence\n return print(io, \"$T model event times (n=$(individuals(x)))\")\nend\n\nfunction Base.getindex(x::Events{T}, new_state::DiseaseState) where T <: DiseaseStateSequence\n if new_state == State_E\n return x.exposure\n elseif new_state == State_I\n return x.infection\n elseif new_state == State_R\n return x.removal\n else\n error(\"Unsupported indexing disease state\")\n end\nend\n\nfunction Base.getindex(x::Events{T}, states::DiseaseStates) where T <: DiseaseStateSequence\n y = x[states[1]]\n for i = 2:length(states)\n y = hcat(y, x[states[i]])\n end\n return y\nend\n\nfunction Base.convert(::Type{Array{Float64, 2}}, x::Events{T}) where T <: DiseaseStateSequence\n return x[convert(DiseaseStates, T)[2:end]]\nend\n\nfunction Base.convert(::Type{Vector{Float64}}, x::Events{T}) where T <: DiseaseStateSequence\n return x[convert(DiseaseStates, T)[2:end]][:]\nend\n\nfunction Base.convert(::Type{Array{Float64, 2}}, x::Array{Events{T}, 1}) where T <: DiseaseStateSequence\n y = convert(Vector{Float64}, x[1])'\n for i = 2:length(x)\n y = vcat(y, convert(Vector{Float64}, x[i])')\n end\n return y\nend\n\nfunction Base.minimum(x::Events{T}) where T <: DiseaseStateSequence\n y = convert(Array{Float64, 2}, x)\n return minimum(y[(y .!== NaN) .& (y .> -Inf)])\nend\n\nfunction Base.maximum(x::Events{T}) where T <: DiseaseStateSequence\n y = convert(Array{Float64, 2}, x)\n return maximum(y[(y .!== NaN) .& (y .> -Inf)])\nend\n\nfunction mean(x::Vector{Events{T}}) where T <: DiseaseStateSequence\n return Events{T}(mean([convert(Array{Float64, 2}, i) for i in x]))\nend", "meta": {"hexsha": "9a1c096671b882b52c71a2cf7f8c3017d353f432", "size": 3883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core/Events/Events.jl", "max_stars_repo_name": "jangevaa/Pathogen.jl", "max_stars_repo_head_hexsha": "7036cdcbbf7edea85a9f48ffe96650fa39a3cee0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/Events/Events.jl", "max_issues_repo_name": "jangevaa/Pathogen.jl", "max_issues_repo_head_hexsha": "7036cdcbbf7edea85a9f48ffe96650fa39a3cee0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-05-19T18:52:18.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-19T18:52:18.000Z", "max_forks_repo_path": "src/core/Events/Events.jl", "max_forks_repo_name": "jangevaa/Pathogen.jl", "max_forks_repo_head_hexsha": "7036cdcbbf7edea85a9f48ffe96650fa39a3cee0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.641221374, "max_line_length": 104, "alphanum_fraction": 0.6435745558, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23547919447140206}} {"text": "###\n### Janzen-Connell Model\n### (c) Daniel Vedder, MIT license\n###\n\n\"\"\"\nA cons cell to implement a double linked list for the forest\n(Boy, do I miss Lisp :-/ )\n\"\"\"\nmutable struct Cons\n car::Union{Tree,Nothing} # The Tree object held by this cell\n cdr::Union{Cons,Nothing} # A pointer to the next cell down the line\n prev::Union{Cons,Nothing} # A pointer to the previous cell\nend\n\n# The first cons cells in the forest list, and the number of trees\nconst forest = Cons(nothing,nothing,nothing)\nforestlen = 0 #XXX do I actually need this?\n\n\"\"\"\nInsert a new tree object at the correct position in the forest list.\n(Sorted by ascending x values.)\n\"\"\"\nfunction planttree!(tree::Tree,cons::Cons=forest)\n #FIXME sometimes doesn't insert trees into the forest list\n # (at least when called from initworld()\n while cons != nothing\n if !isa(cons.car, Tree)\n # If we have an empty cons cell, plant the tree here\n cons.car = tree\n global forestlen += 1\n @debug \"Planted tree $(tree.uid) @$(tree.position.x)/$(tree.position.y)\"\n return\n elseif tree.position.x < cons.car.position.x\n # If the next tree in the list is further east, insert a new cons cell\n if cons.prev != nothing #inserting in the middle\n newcons = Cons(tree,cons,cons.prev) \n cons.prev.cdr = newcons\n cons.prev = newcons\n else #if we're inserting before the first cell\n newcons = Cons(cons.car, cons.cdr, cons)\n cons.car = tree\n cons.cdr = newcons\n end\n global forestlen += 1\n @debug \"Planted tree $(tree.uid) @$(tree.position.x)/$(tree.position.y)\"\n return\n elseif cons.cdr == nothing\n # If we're at the end of the list, append a new cons cell\n cons.cdr = Cons(nothing,nothing,cons)\n end\n cons = cons.cdr\n end\nend\n\n\"\"\"\nRemove a tree from the forest list.\n(Don't let Idefix see this function :D )\n\"\"\"\nfunction killtree!(tree::Tree,cons::Cons=forest,reason::String=\"malice aforethought\")\n while cons != nothing\n if cons.car == tree\n if cons.prev != nothing #excise a cons cell from the list\n cons.prev.cdr = cons.cdr\n cons.cdr != nothing && (cons.cdr.prev = cons.prev)\n cons = nothing\n else\n #removing the first tree is a bit more tricky, because the\n #first cons cell (global variable `forest`) mustn't be deleted\n if cons.cdr != nothing\n cons.car = cons.cdr.car\n cons.cdr.cdr != nothing && (cons.cdr.cdr.prev = cons)\n cons.cdr = cons.cdr.cdr\n else\n cons.car = nothing\n end\n end\n #cleanup and decrease the tree count\n global forestlen -= 1\n @debug \"Killed tree $(tree.uid) @$(tree.position.x)/$(tree.position.y) because of $(reason)\"\n tree = nothing\n return\n end\n cons = cons.cdr\n end\n @warn \"Attempted to remove nonexistent tree.\"\nend\n\n\"\"\"\nProduce seeds and disperse them in the landscape, planting them where possible\n\"\"\"\nfunction disperse!(cons::Cons=forest)\n i::Int16 = 1\n while cons != nothing\n tree = cons.car\n if !tree.mature\n i += 1\n cons = cons.cdr\n continue\n end\n @debug \"Reproducing tree $(tree.uid)\"\n dx = tree.species.dispersal_distance\n # Each tree produces multiple seeds\n for s in 1:tree.species.seed_production\n #TODO implement a proper dispersal kernel\n # Find a random location in a circle around the tree\n sx = tree.position.x + rand(-dx:dx)\n #FIXME sqrt() was called with an argument of -32768.0?\n # (only happens in scenarios with variance?)\n dy = convert(Int16, round(sqrt(abs(dx^2-(sx-tree.position.x)^2))))\n sy = tree.position.y + rand(-dy:dy)\n if sx >= -settings[\"worldsize\"] && sx <= settings[\"worldsize\"] &&\n sy >= -settings[\"worldsize\"] && sy <= settings[\"worldsize\"]\n seed = Tree(tree.species, sx, sy)\n planttree!(seed)\n end\n end\n i += 1\n cons = cons.cdr\n end\nend\n\n\"\"\"\nTest whether the trees in two cons cells intersect, and if so, kill the\nsmaller tree. The integer return value indicates the outcome:\n0 - no intersection (no tree killed)\n1 - the first tree is larger (second tree killed)\n2 - the second tree is larger (first tree killed)\nNeeded by `compete_individual!()`\n\"\"\"\nfunction compete_pair!(cons1::Cons, cons2::Cons)::UInt8\n tree1 = cons1.car\n tree2 = cons2.car\n (tree1 == nothing || tree2 == nothing) && return\n mindist = (tree1.size + tree2.size)/2\n dx = abs(tree1.position.x - tree2.position.x)\n dy = abs(tree1.position.y - tree2.position.y)\n if dx >= mindist || dy >= mindist || hypot(dx,dy) >= mindist\n return 0\n elseif tree1.size > tree2.size\n killtree!(tree2, cons2, \"competition\")\n return 1\n else\n killtree!(tree1, cons1, \"competition\")\n return 2\n end\nend\n\n\"\"\"\nCheck whether the tree in this cons cell conflicts with trees in the\nvicinity and, if so, kill the smaller one.\nNeeded by `compete!()`\n\"\"\"\nfunction compete_individual!(cons::Cons)\n tree = cons.car\n # go right until we're sure we won't find any more conflicts\n next = cons.cdr\n while next != nothing && abs(next.car.position.x - tree.position.x) < (tree.size/2)+2^7\n next2 = next.cdr # We have to save the coming step already, in case `next` is killed\n conflict = compete_pair!(cons, next)\n if conflict == 2\n return # This tree was killed, so we can break off\n else # otherwise, keep going\n next = next2\n end\n end\n # then go left and repeat\n next = cons.prev\n while next != nothing && abs(next.car.position.x - tree.position.x) < (tree.size/2)+2^7\n next2 = next.prev\n conflict = compete_pair!(cons, next)\n if conflict == 2\n return\n else\n next = next2\n end\n end\nend\n\n\"\"\"\nGo through the landscape and check each tree for space conflicts\n\"\"\"\nfunction compete!(cons::Cons=forest)\n while cons != nothing\n compete_individual!(cons)\n cons = cons.cdr\n end\nend\n\n\"\"\"\nAll saplings grow until they reach maturity, then eventually die of old age.\n\"\"\"\nfunction grow!(cons::Cons=forest)\n while cons != nothing\n tree = cons.car\n next = cons.cdr\n if !tree.mature\n tree.size += tree.species.growth_rate\n tree.size >= tree.species.max_size && (tree.mature = true)\n elseif tree.age >= tree.species.max_age\n killtree!(tree, cons, \"old age\")\n cons = next\n continue\n end\n tree.age += 1\n cons = next\n recordindividual(tree)\n end\nend\n\n\"\"\"\nAn infected tree in the given cons cell spreads its infection\n\"\"\"\nfunction spread_infection(cons::Cons)\n tree = cons.car\n pathogen = tree.infection\n maxdist = pathogen.infection_radius\n # go right until we're sure we're out of the infection range\n next = cons.cdr\n while next != nothing && abs(next.car.position.x - tree.position.x) < maxdist\n tree2 = next.car\n dist = hypot(abs(tree.position.x-tree2.position.x),\n abs(tree.position.y-tree2.position.y))\n prob = (pathogen.infection_rate-tree2.species.pathogen_resistance)*((maxdist-dist)/maxdist)\n #A tree is infected if...\n if dist <= maxdist && #... it's within range\n tree2.infection == nothing && #... it isn't infected anyway\n tree2.species.id == tree.species.id && #... it belongs to the same species\n prob > rand(Float16) #... it passes a random draw dependent on its resistance and distance\n tree2.infection = Pathogen(pathogen.host)\n @debug \"Infected tree $(tree.uid) @$(tree2.position.x)/$(tree2.position.y)\"\n end\n next = next.cdr\n end\n # then go left and repeat\n next = cons.prev\n while next != nothing && abs(next.car.position.x - tree.position.x) < maxdist\n tree2 = next.car\n dist = hypot(abs(tree.position.x-tree2.position.x),\n abs(tree.position.y-tree2.position.y))\n prob = (pathogen.infection_rate-tree2.species.pathogen_resistance)*((maxdist-dist)/maxdist)\n if dist <= maxdist &&\n tree2.infection == nothing &&\n tree2.species.id == tree.species.id &&\n prob > rand(Float16)\n tree2.infection = Pathogen(pathogen.host)\n @debug \"Infected tree $(tree.uid) @$(tree2.position.x)/$(tree2.position.y)\"\n end\n next = next.prev\n end\nend\n\n\"\"\"\nCarry out the pathogen spread phase and check for mortality\n\"\"\"\nfunction infect!(cons::Cons=forest)\n while cons != nothing\n tree = cons.car\n next = cons.cdr\n if tree.infection != nothing\n pathogen = tree.infection\n # pathogens have a one-update incubation period\n pathogen.infectious ? spread_infection(cons) : pathogen.infectious = true\n if pathogen.lethality > rand(Float16)\n killtree!(tree, cons, \"disease\")\n end\n end\n cons = next\n end\nend\n", "meta": {"hexsha": "26ba60806ee4b281560e3baceb5c7d17d6c26192", "size": 9535, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "forest.jl", "max_stars_repo_name": "veddox/jcm", "max_stars_repo_head_hexsha": "5a46d7383517ede9eb4f69f5dcbfed2010ad25f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "forest.jl", "max_issues_repo_name": "veddox/jcm", "max_issues_repo_head_hexsha": "5a46d7383517ede9eb4f69f5dcbfed2010ad25f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "forest.jl", "max_forks_repo_name": "veddox/jcm", "max_forks_repo_head_hexsha": "5a46d7383517ede9eb4f69f5dcbfed2010ad25f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.184501845, "max_line_length": 104, "alphanum_fraction": 0.5906659675, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.23545749950404726}} {"text": "# General case - to be used with bc::NoBC or m::PrescribedXModels\nfunction soil_boundary_flux!(\n nf,\n bc::AbstractBoundaryConditions,\n m::AbstractSoilComponentModel,\n land::LandModel,\n state⁺::Vars,\n diff⁺::Vars,\n aux⁺::Vars,\n nM,\n state⁻::Vars,\n diff⁻::Vars,\n aux⁻::Vars,\n t,\n _...,\n) end\n\n\n\n\nfunction soil_boundary_state!(\n nf,\n bc::AbstractBoundaryConditions,\n m::AbstractSoilComponentModel,\n land::LandModel,\n state⁺::Vars,\n aux⁺::Vars,\n nM,\n state⁻::Vars,\n aux⁻::Vars,\n t,\n _...,\n)\n\nend\n\n# Dirichlet Methods for SoilHeat and SoilWater\n\n\"\"\"\n function soil_boundary_state!(\n nf,\n bc::Dirichlet,\n water::SoilWaterModel,\n land::LandModel,\n state⁺::Vars,\n aux⁺::Vars,\n nM,\n state⁻::Vars,\n aux⁻::Vars,\n t,\n )\n\nThe Dirichlet-type method for `soil_boundary_state!` for the\n`SoilWaterModel`.\n\"\"\"\nfunction soil_boundary_state!(\n nf,\n bc::Dirichlet,\n water::SoilWaterModel,\n land::LandModel,\n state⁺::Vars,\n aux⁺::Vars,\n nM,\n state⁻::Vars,\n aux⁻::Vars,\n t,\n _...,\n)\n bc_function = bc.state_bc\n state⁺.soil.water.ϑ_l = bc_function(aux⁻, t)\n\nend\n\n\n\"\"\"\n function soil_boundary_state!(\n nf,\n bc::Dirichlet,\n heat::SoilHeatModel,\n land::LandModel,\n state⁺::Vars,\n aux⁺::Vars,\n nM,\n state⁻::Vars,\n aux⁻::Vars,\n t,\n )\n\nThe Dirichlet-type method for `soil_boundary_state!` for the\n`SoilHeatModel`.\n\"\"\"\nfunction soil_boundary_state!(\n nf,\n bc::Dirichlet,\n heat::SoilHeatModel,\n land::LandModel,\n state⁺::Vars,\n aux⁺::Vars,\n nM,\n state⁻::Vars,\n aux⁻::Vars,\n t,\n _...,\n)\n bc_function = bc.state_bc\n param_set = parameter_set(land)\n ϑ_l, θ_i = get_water_content(land.soil.water, aux⁻, state⁻, t)\n θ_l = volumetric_liquid_fraction(ϑ_l, land.soil.param_functions.porosity)\n ρc_s = volumetric_heat_capacity(\n θ_l,\n θ_i,\n land.soil.param_functions.ρc_ds,\n param_set,\n )\n\n ρe_int_bc =\n volumetric_internal_energy(θ_i, ρc_s, bc_function(aux⁻, t), param_set)\n\n state⁺.soil.heat.ρe_int = ρe_int_bc\nend\n\n# Neumann conditions for SoilHeat and SoilWater\n\n\"\"\"\n function soil_boundary_flux!(\n nf,\n bc::Neumann,\n water::SoilWaterModel,\n land::LandModel,\n state⁺::Vars,\n diff⁺::Vars,\n aux⁺::Vars,\n n̂,\n state⁻::Vars,\n diff⁻::Vars,\n aux⁻::Vars,\n t,\n )\n\nThe Neumann method for `soil_boundary_flux!` for the\n`SoilWaterModel`.\n\"\"\"\nfunction soil_boundary_flux!(\n nf,\n bc::Neumann,\n water::SoilWaterModel,\n land::LandModel,\n state⁺::Vars,\n diff⁺::Vars,\n aux⁺::Vars,\n n̂,\n state⁻::Vars,\n diff⁻::Vars,\n aux⁻::Vars,\n t,\n _...,\n)\n bc_function = bc.scalar_flux_bc\n # on faces at the top and bottom of the domain,\n # the vector n̂ can point in either ± ẑ, depending on which side of the domain\n # we are on. The user supplies a scalar flux F, such that the flux at the boundary\n # is assumed to be F⃗ = F ẑ - i.e. the user doesn't need to worry about the normal vector.\n # so, we take the absolute value of n̂ here.\n # The minus sign is because the condition is applied on minus the flux.\n # the same argument applies for the other directions.\n diff⁺.soil.water.K∇h = abs.(n̂) * (-bc_function(aux⁻, t))\nend\n\n\n\"\"\"\n function soil_boundary_flux!(\n nf,\n bc::Neumann,\n heat::SoilHeatModel,\n land::LandModel,\n state⁺::Vars,\n diff⁺::Vars,\n aux⁺::Vars,\n n̂,\n state⁻::Vars,\n diff⁻::Vars,\n aux⁻::Vars,\n t,\n )\n\nThe Neumann method for `soil_boundary_flux!` for the\n`SoilHeatModel`.\n\"\"\"\nfunction soil_boundary_flux!(\n nf,\n bc::Neumann,\n heat::SoilHeatModel,\n land::LandModel,\n state⁺::Vars,\n diff⁺::Vars,\n aux⁺::Vars,\n n̂,\n state⁻::Vars,\n diff⁻::Vars,\n aux⁻::Vars,\n t,\n _...,\n)\n bc_function = bc.scalar_flux_bc\n # on faces at the top and bottom of the domain,\n # the vector n̂ can point in either ± ẑ, depending on which side of the domain\n # we are on. The user supplies a scalar flux F, such that the flux at the boundary\n # is assumed to be F⃗ = F ẑ - i.e. the user doesn't need to worry about the normal vector.\n # so, we take the absolute value of n̂ here.\n # The minus sign is because the condition is applied on minus the flux.\n # the same argument applies for the other directions.\n diff⁺.soil.heat.κ∇T = abs.(n̂) * (-bc_function(aux⁻, t))\nend\n\n\n# SurfaceDriven conditions for for SoilHeat and SoilWater\n\n\"\"\"\n function soil_boundary_flux!(\n nf,\n bc::SurfaceDrivenWaterBoundaryConditions,\n water::SoilWaterModel,\n land::LandModel,\n state⁺::Vars,\n diff⁺::Vars,\n aux⁺::Vars,\n n̂,\n state⁻::Vars,\n diff⁻::Vars,\n aux⁻::Vars,\n t,\n )\n\nThe Surface Driven BC method for `soil_boundary_flux!` for the\n`SoilWaterModel`.\n\"\"\"\nfunction soil_boundary_flux!(\n nf,\n bc::SurfaceDrivenWaterBoundaryConditions,\n water::SoilWaterModel,\n land::LandModel,\n state⁺::Vars,\n diff⁺::Vars,\n aux⁺::Vars,\n n̂,\n state⁻::Vars,\n diff⁻::Vars,\n aux⁻::Vars,\n t,\n _...,\n)\n\n diff⁺.soil.water.K∇h = compute_surface_grad_bc(\n land.soil,\n bc.runoff_model,\n bc.precip_model,\n n̂,\n state⁻,\n diff⁻,\n aux⁻,\n t,\n )\n\nend\n\n\"\"\"\n soil_boundary_flux!(\n nf,\n bc::SurfaceDrivenHeatBoundaryConditions,\n heat::SoilHeatModel,\n land::LandModel,\n state⁺::Vars,\n diff⁺::Vars,\n aux⁺::Vars,\n n̂,\n state⁻::Vars,\n diff⁻::Vars,\n aux⁻::Vars,\n t,\n )\n\nThe Surface Driven BC method for `soil_boundary_flux!` for the\n`SoilHeatModel`.\n\"\"\"\nfunction soil_boundary_flux!(\n nf,\n bc::SurfaceDrivenHeatBoundaryConditions,\n heat::SoilHeatModel,\n land::LandModel,\n state⁺::Vars,\n diff⁺::Vars,\n aux⁺::Vars,\n n̂,\n state⁻::Vars,\n diff⁻::Vars,\n aux⁻::Vars,\n t,\n _...,\n)\n\n net_surface_flux = compute_net_radiative_energy_flux(bc.nswf_model, t)\n diff⁺.soil.heat.κ∇T = n̂ * (-net_surface_flux)\nend\n", "meta": {"hexsha": "a427488ace34b28ca2d9cd5772b8f17af0b5d933", "size": 6359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Land/Model/soil_bc.jl", "max_stars_repo_name": "thomasgibson/ClimateMachine.jl", "max_stars_repo_head_hexsha": "147eee06be26269a596adc31666d82fddfb95ac4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Land/Model/soil_bc.jl", "max_issues_repo_name": "thomasgibson/ClimateMachine.jl", "max_issues_repo_head_hexsha": "147eee06be26269a596adc31666d82fddfb95ac4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Land/Model/soil_bc.jl", "max_forks_repo_name": "thomasgibson/ClimateMachine.jl", "max_forks_repo_head_hexsha": "147eee06be26269a596adc31666d82fddfb95ac4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9177631579, "max_line_length": 95, "alphanum_fraction": 0.5818524925, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23544472958611862}} {"text": "struct SimulationResults\n global_index::MAPPING_DICT\n bus_lookup::Dict{Int, Int}\n system::PSY.System\n time_log::Dict{Symbol, Any}\n solution::SciMLBase.AbstractODESolution\n function SimulationResults(\n inputs::SimulationInputs,\n system::PSY.System,\n time_log,\n solution,\n )\n new(make_global_state_map(inputs), get_lookup(inputs), system, time_log, solution)\n end\nend\n\nget_global_index(res::SimulationResults) = res.global_index\nget_bus_count(res::SimulationResults) = get_n_buses(res.system)\nget_bus_lookup(res::SimulationResults) = res.bus_lookup\nget_system(res::SimulationResults) = res.system\nget_solution(res::SimulationResults) = res.solution\n\n\"\"\"\nInternal function to obtain as a Vector of Float64 of a specific state. It receives the solution and the\nglobal index for a state.\n\n\"\"\"\nfunction _post_proc_state_series(solution, ix::Int, dt::Union{Nothing, Float64})\n if dt === nothing\n ix_t = unique(i -> solution.t[i], eachindex(solution.t))\n ts = solution.t[ix_t]\n state = solution[ix, ix_t]\n else\n ts = range(0, stop = solution.t[end], step = dt)\n state = solution(collect(ts); idxs = ix)\n end\n return ts, state\nend\n\n\"\"\"\nFunction to obtain the state time series of a specific state. It receives the simulation, and a tuple\ncontaining the name of the Dynamic Device and the symbol of the state.\n\"\"\"\nfunction post_proc_state_series(\n res::SimulationResults,\n ref::Tuple{String, Symbol},\n dt::Union{Nothing, Float64},\n)\n global_state_index = get_global_index(res)\n ix = get(global_state_index[ref[1]], ref[2], 0)\n return _post_proc_state_series(get_solution(res), ix, dt)\nend\n\n\"\"\"\nFunction to obtain voltage and output currents for a dynamic device. It receives the simulation, and the name\nof the Dynamic Device.\n\"\"\"\nfunction post_proc_voltage_current_series(\n res::SimulationResults,\n name::String,\n dt::Union{Nothing, Float64},\n)::NTuple{5, Vector{Float64}}\n #Note: Type annotation since get_dynamic_injector is type unstable and solution is Union{Nothing, DAESol}\n system = get_system(res)\n bus_lookup = get_bus_lookup(res)\n n_buses = length(bus_lookup)\n solution = res.solution\n device = PSY.get_component(PSY.StaticInjection, system, name)\n if isnothing(device)\n error(\"Device $(name) not found in the system\")\n end\n bus_ix = get(bus_lookup, PSY.get_number(PSY.get_bus(device)), -1)\n ts, V_R, V_I = post_proc_voltage_series(solution, bus_ix, n_buses, dt)\n dyn_device = PSY.get_dynamic_injector(device)\n _, I_R, I_I = compute_output_current(res, dyn_device, V_R, V_I, dt)\n return ts, V_R, V_I, I_R, I_I\nend\n\n\"\"\"\nFunction to obtain voltage using the bus index (and not the bus number). It receives the solution, the bus index and\nthe total number of buses.\n\n\"\"\"\nfunction post_proc_voltage_series(\n solution,\n bus_ix::Int,\n n_buses::Int,\n dt::Union{Nothing, Float64},\n)\n bus_ix < 0 && error(\"Bus number $(bus_number) not found.\")\n ts, V_R = _post_proc_state_series(solution, bus_ix, dt)\n _, V_I = _post_proc_state_series(solution, bus_ix + n_buses, dt)\n return collect(ts), collect(V_R), collect(V_I)\nend\n\n\"\"\"\nFunction to compute the real current output time series of a Dynamic Injection series out of the DAE Solution. It receives the solution and the\nstring name of the Dynamic Injection device.\n\n\"\"\"\nfunction post_proc_real_current_series(\n res::SimulationResults,\n name::String,\n dt::Union{Nothing, Float64},\n)\n ts, _, _, I_R, _ = post_proc_voltage_current_series(res, name, dt)\n return ts, I_R\nend\n\"\"\"\nFunction to compute the imaginary current output time series of a Dynamic Injection series out of the DAE Solution. It receives the solution and the\nstring name of the Dynamic Injection device.\n\n\"\"\"\nfunction post_proc_imaginary_current_series(\n res::SimulationResults,\n name::String,\n dt::Union{Nothing, Float64},\n)\n ts, _, _, _, I_I = post_proc_voltage_current_series(res, name, dt)\n return ts, I_I\nend\n\n\"\"\"\nFunction to compute the active power output time series of a Dynamic Injection series out of the DAE Solution. It receives the solution and the\nstring name of the Dynamic Injection device.\n\n\"\"\"\nfunction post_proc_activepower_series(\n res::SimulationResults,\n name::String,\n dt::Union{Nothing, Float64},\n)\n ts, V_R, V_I, I_R, I_I = post_proc_voltage_current_series(res, name, dt)\n return ts, V_R .* I_R + V_I .* I_I\nend\n\n\"\"\"\nFunction to compute the active power output time series of a Dynamic Injection series out of the DAE Solution. It receives the solution and the\nstring name of the Dynamic Injection device.\n\n\"\"\"\nfunction post_proc_reactivepower_series(\n res::SimulationResults,\n name::String,\n dt::Union{Nothing, Float64},\n)\n ts, V_R, V_I, I_R, I_I = post_proc_voltage_current_series(res, name, dt)\n return ts, V_I .* I_R - V_R .* I_I\nend\n\n\"\"\"\nFunction to compute the field current output time series of a Dynamic Injection series out of the DAE Solution. It receives the solution and the\nstring name of the Dynamic Injection device.\n\n\"\"\"\nfunction post_proc_field_current_series(\n res::SimulationResults,\n name::String,\n dt::Union{Nothing, Float64},\n)\n system = get_system(res)\n bus_lookup = get_bus_lookup(res)\n n_buses = length(bus_lookup)\n solution = res.solution\n device = PSY.get_component(PSY.StaticInjection, system, name)\n bus_ix = get(bus_lookup, PSY.get_number(PSY.get_bus(device)), -1)\n ts, V_R, V_I = post_proc_voltage_series(solution, bus_ix, n_buses, dt)\n dyn_device = PSY.get_dynamic_injector(device)\n _, I_fd = compute_field_current(res, dyn_device, V_R, V_I, dt)\n return ts, I_fd\nend\n\n\"\"\"\nFunction to compute the field voltage output time series of a Dynamic Injection series out of the DAE Solution. It receives the solution and the\nstring name of the Dynamic Injection device.\n\n\"\"\"\nfunction post_proc_field_voltage_series(\n res::SimulationResults,\n name::String,\n dt::Union{Nothing, Float64},\n)\n system = get_system(res)\n device = PSY.get_component(PSY.StaticInjection, system, name)\n dyn_device = PSY.get_dynamic_injector(device)\n ts, Vf = compute_field_voltage(res, dyn_device, dt)\n return ts, Vf\nend\n\n\"\"\"\n get_state_series(\n res::SimulationResults,\n ref::Tuple{String, Symbol};\n dt::Union{Nothing, Float64} = nothing\n )\n end\n\nFunction to obtain series of states out of DAE Solution.\n\n# Arguments\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n- `ref:Tuple{String, Symbol}` : Tuple used to identify the dynamic device, via its name, as a `String`, and the associated state as a `Symbol`.\n\"\"\"\nfunction get_state_series(res::SimulationResults, ref::Tuple{String, Symbol}; dt = nothing)\n return post_proc_state_series(res, ref, dt)\nend\n\n\"\"\"\n get_voltage_magnitude_series(\n res::SimulationResults,\n bus_number::Int\n )\n\nFunction to obtain the voltage magnitude series out of the DAE Solution.\n\n# Arguments:\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n- `bus_number::Int` : Bus number identifier\n\"\"\"\nfunction get_voltage_magnitude_series(res::SimulationResults, bus_number::Int; dt = nothing)\n n_buses = get_bus_count(res)\n bus_ix = get(get_bus_lookup(res), bus_number, 0)\n ts, V_R, V_I = post_proc_voltage_series(res.solution, bus_ix, n_buses, dt)\n return ts, sqrt.(V_R .^ 2 .+ V_I .^ 2)\nend\n\n\"\"\"\n get_voltage_angle_series(\n res::SimulationResults,\n bus_number::Int\n )\n\nFunction to obtain the voltage angle series out of the DAE Solution.\n\n# Arguments\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n- `bus_number::Int` : Bus number identifier\n\"\"\"\nfunction get_voltage_angle_series(res::SimulationResults, bus_number::Int; dt = nothing)\n n_buses = get_bus_count(res)\n bus_ix = get(get_bus_lookup(res), bus_number, 0)\n ts, V_R, V_I = post_proc_voltage_series(res.solution, bus_ix, n_buses, dt)\n return ts, atan.(V_I, V_R)\nend\n\n\"\"\"\n get_real_current_series(\n res::SimulationResults,\n name::String,\n )\n\nFunction to obtain the real current time series of a Dynamic Injection series out of the DAE Solution.\n\n# Arguments\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n- `name::String` : Name to identify the specified device\n\"\"\"\nfunction get_real_current_series(res::SimulationResults, name::String; dt = nothing)\n return post_proc_real_current_series(res, name, dt)\nend\n\n\"\"\"\n get_imaginary_current_series(\n res::SimulationResults,\n name::String,\n )\n\nFunction to obtain the imaginary current time series of a Dynamic Injection series out of the DAE Solution.\n\n# Arguments\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n- `name::String` : Name to identify the specified device\n\"\"\"\nfunction get_imaginary_current_series(res::SimulationResults, name::String; dt = nothing)\n return post_proc_imaginary_current_series(res, name, dt)\nend\n\n\"\"\"\n get_activepower_series(\n res::SimulationResults,\n name::String,\n )\n\nFunction to obtain the active power output time series of a Dynamic Injection series out of the DAE Solution.\n\n# Arguments\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n- `name::String` : Name to identify the specified device\n\"\"\"\nfunction get_activepower_series(res::SimulationResults, name::String; dt = nothing)\n return post_proc_activepower_series(res, name, dt)\nend\n\n\"\"\"\n get_reactivepower_series(\n res::SimulationResults,\n name::String,\n )\n\nFunction to obtain the reactive power output time series of a Dynamic Injection series out of the DAE Solution.\n\n# Arguments\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n- `name::String` : Name to identify the specified device\n\"\"\"\nfunction get_reactivepower_series(res::SimulationResults, name::String; dt = nothing)\n return post_proc_reactivepower_series(res, name, dt)\nend\n\n\"\"\"\n get_field_current_series(\n res::SimulationResults,\n name::String,\n )\n\nFunction to obtain the field current time series of a Dynamic Generator out of the DAE Solution.\n\n# Arguments\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n- `name::String` : Name to identify the specified device\n\"\"\"\nfunction get_field_current_series(res::SimulationResults, name::String; dt = nothing)\n return post_proc_field_current_series(res, name, dt)\nend\n\n\"\"\"\n get_field_voltage_series(\n res::SimulationResults,\n name::String,\n )\n\nFunction to obtain the field voltage time series of a Dynamic Generator out of the DAE Solution.\n\n# Arguments\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n- `name::String` : Name to identify the specified device\n\"\"\"\nfunction get_field_voltage_series(res::SimulationResults, name::String; dt = nothing)\n return post_proc_field_voltage_series(res, name, dt)\nend\n\n\"\"\"\n show_states_initial_value(res::SimulationResults)\n\nFunction to print initial states.\n\n# Arguments\n\n- `res::SimulationResults` : Simulation Results object that contains the solution\n\"\"\"\nfunction show_states_initial_value(res::SimulationResults)\n bus_size = get_bus_count(res)\n system = get_system(res)\n x0_init = res.solution.u[1]\n println(\"Voltage Variables\")\n println(\"====================\")\n buses_sorted =\n sort(collect(PSY.get_components(PSY.Bus, system)); by = x -> PSY.get_number(x))\n for bus in buses_sorted\n name = PSY.get_name(bus)\n println(name)\n println(\"====================\")\n bus_n = PSY.get_number(bus)\n bus_ix = get_bus_lookup(res)[bus_n]\n V_R = x0_init[bus_ix]\n V_I = x0_init[bus_ix + bus_size]\n Vm = sqrt(V_R^2 + V_I^2)\n θ = angle(V_R + V_I * 1im)\n print(\"Vm \", round(Vm, digits = 4), \"\\n\")\n print(\"θ \", round(θ, digits = 4), \"\\n\")\n println(\"====================\")\n end\n println(\"====================\")\n for device in PSY.get_components(PSY.DynamicInjection, system)\n states = PSY.get_states(device)\n name = PSY.get_name(device)\n println(\"Differential States\")\n println(name)\n println(\"====================\")\n global_index = get_global_index(res)[name]\n for s in states\n print(s, \" \", round(x0_init[global_index[s]], digits = 4), \"\\n\")\n end\n println(\"====================\")\n end\n dyn_branches = PSY.get_components(PSY.DynamicBranch, system)\n if !isempty(dyn_branches)\n println(\"====================\")\n println(\"Line Current States\")\n for br in dyn_branches\n states = PSY.get_states(br)\n name = PSY.get_name(br)\n printed_name = \"Line \" * name\n println(\"====================\")\n println(printed_name)\n global_index = get_global_index(res)[name]\n for (i, s) in enumerate(states)\n print(s, \" \", round(x0_init[global_index[s]], digits = 5), \"\\n\")\n end\n println(\"====================\")\n end\n end\n return\nend\n", "meta": {"hexsha": "b22f187ac56e17bdb04aeb5a6275e6d681d12465", "size": 13361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/base/simulation_results.jl", "max_stars_repo_name": "tavovalmo/PowerSimulationsDynamics.jl", "max_stars_repo_head_hexsha": "61ba0433ab89caa37f9cf2caedaa2bcc2566591c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/base/simulation_results.jl", "max_issues_repo_name": "tavovalmo/PowerSimulationsDynamics.jl", "max_issues_repo_head_hexsha": "61ba0433ab89caa37f9cf2caedaa2bcc2566591c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/simulation_results.jl", "max_forks_repo_name": "tavovalmo/PowerSimulationsDynamics.jl", "max_forks_repo_head_hexsha": "61ba0433ab89caa37f9cf2caedaa2bcc2566591c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2729468599, "max_line_length": 148, "alphanum_fraction": 0.6938103435, "num_tokens": 3184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23522124954095835}} {"text": "\nconst DenseNativeArray = DenseArray{<:NativeTypes}\n\n\"\"\"\n`vstorent!` (non-temporal store) requires data to be aligned.\n`alignstores!` will align `y` in preparation for the non-temporal maps.\n\"\"\"\nfunction alignstores!(\n f::F, y::DenseArray{T},\n args::Vararg{DenseNativeArray,A}\n) where {F, T <: Base.HWReal, A}\n N = length(y)\n ptry = VectorizationBase.zero_offsets(stridedpointer(y))\n ptrargs = VectorizationBase.zero_offsets.(stridedpointer.(args))\n V = VectorizationBase.pick_vector_width_val(T)\n W = unwrap(V)\n zero_index = MM{W}(Static(0))\n uintptry = reinterpret(UInt, pointer(ptry))\n @assert iszero(uintptry & (sizeof(T) - 1)) \"The destination vector (`dest`) must be aligned at least to `sizeof(eltype(dest))`.\"\n alignment = uintptry & (VectorizationBase.REGISTER_SIZE - 1)\n if alignment > 0\n i = reinterpret(Int, W - (alignment >>> VectorizationBase.intlog2(sizeof(T))))\n m = mask(T, i)\n if N < i\n m &= mask(T, N & (W - 1))\n end\n vnoaliasstore!(ptry, f(vload.(ptrargs, ((zero_index,),), m)...), (zero_index,), m)\n gesp(ptry, (i,)), gesp.(ptrargs, ((i,),)), N - i\n else\n ptry, ptrargs, N\n end\nend\n\nfunction vmap_singlethread!(\n f::F, y::DenseArray{T},\n ::Val{NonTemporal},\n args::Vararg{DenseNativeArray,A}\n) where {F,T <: Base.HWReal, A, NonTemporal}\n if NonTemporal # if stores into `y` aren't aligned, we'll get a crash\n ptry, ptrargs, N = alignstores!(f, y, args...)\n else\n N = length(y)\n ptry = VectorizationBase.zero_offsets(stridedpointer(y))\n ptrargs = VectorizationBase.zero_offsets.(stridedpointer.(args))\n end\n i = 0\n V = VectorizationBase.pick_vector_width_val(T)\n W = unwrap(V)\n st = VectorizationBase.static_sizeof(T)\n zero_index = MM{W}(Static(0), st)\n while i < N - ((W << 2) - 1)\n\n # vstore!(stridedpointer(B), VectorizationBase.VecUnroll((v1,v2,v3)), VectorizationBase.Unroll{AU,1,3,AV,W64,zero(UInt)}((i, j, k)))\n # vload(stridedpointer(B), VectorizationBase.Unroll{1,1,4,1,W,0x0000000000000000}((i,)))\n \n index = VectorizationBase.Unroll{1,1,4,1,W,0x0000000000000000}((i,))\n v = f(vload.(ptrargs, index)...)\n if NonTemporal\n vstorent!(ptry, v, index)\n else\n vnoaliasstore!(ptry, v, index)\n end\n i = vadd(i, 4W)\n end\n while i < N - (W - 1) # stops at 16 when\n vᵣ = f(vload.(ptrargs, ((MM{W}(i),),))...)\n if NonTemporal\n vstorent!(ptry, vᵣ, (MM{W}(i),))\n else\n vnoaliasstore!(ptry, vᵣ, (MM{W}(i),))\n end\n i = vadd(i, W)\n end\n if i < N\n m = mask(T, N & (W - 1))\n vnoaliasstore!(ptry, f(vload.(ptrargs, ((MM{W}(i),),), m)...), (MM{W}(i,),), m)\n end\n y\nend\n\nfunction vmap_multithreaded!(\n f::F,\n y::DenseArray{T},\n ::Val{true},\n args::Vararg{DenseNativeArray,A}\n) where {F,T,A}\n ptry, ptrargs, N = alignstores!(f, y, args...)\n N > 0 || return y\n W, Wshift = VectorizationBase.pick_vector_width_shift(T)\n V = VectorizationBase.pick_vector_width_val(T)\n Wsh = Wshift + 2\n Niter = N >>> Wsh\n Base.Threads.@threads for j ∈ 0:Niter-1\n index = VectorizationBase.Unroll{1,1,4,1,W,0x0000000000000000}((j << Wsh,))\n vstorent!(ptry, f(vload.(ptrargs, index)...), index)\n end\n ii = Niter << Wsh\n while ii < N - (W - 1) # stops at 16 when\n vstorent!(ptry, f(vload.(ptrargs, ((MM{W}(ii),),))...), (MM{W}(ii),))\n ii = vadd(ii, W)\n end\n if ii < N\n m = mask(T, N & (W - 1))\n vnoaliasstore!(ptry, f(vload.(ptrargs, ((MM{W}(ii),),), m)...), (MM{W}(ii),), m)\n end\n y\nend\nfunction vmap_multithreaded!(\n f::F,\n y::DenseArray{T},\n ::Val{false},\n args::Vararg{DenseNativeArray,A}\n) where {F,T,A}\n N = length(y)\n ptry = VectorizationBase.zero_offsets(stridedpointer(y))\n ptrargs = VectorizationBase.zero_offsets.(stridedpointer.(args))\n N > 0 || return y\n W, Wshift = VectorizationBase.pick_vector_width_shift(T)\n V = VectorizationBase.pick_vector_width_val(T)\n Wsh = Wshift + 2\n Niter = N >>> Wsh\n Base.Threads.@threads for j ∈ 0:Niter-1\n index = VectorizationBase.Unroll{1,1,4,1,W,0x0000000000000000}((j << Wsh,))\n vnoaliasstore!(ptry, f(vload.(ptrargs, index)...), index)\n end\n ii = Niter << Wsh\n while ii < N - (W - 1) # stops at 16 when\n vnoaliasstore!(ptry, f(vload.(ptrargs, ((MM{W}(ii),),))...), (MM{W}(ii),))\n ii = vadd(ii, W)\n end\n if ii < N\n m = mask(T, N & (W - 1))\n vnoaliasstore!(ptry, f(vload.(ptrargs, ((MM{W}(ii),),), m)...), (MM{W}(ii),), m)\n end\n y\nend\n\n\n\"\"\"\n vmap!(f, destination, a::AbstractArray)\n vmap!(f, destination, a::AbstractArray, b::AbstractArray, ...)\n\nVectorized-`map!`, applying `f` to each element of `a` (or paired elements of `a`, `b`, ...)\nand storing the result in `destination`.\n\"\"\"\nfunction vmap!(\n f::F, y::DenseArray{T}, args::Vararg{DenseNativeArray,A}\n) where {F,T<:Base.HWReal,A}\n vmap_singlethread!(f, y, Val{false}(), args...)\nend\n\n\n\"\"\"\n vmapt!(::Function, dest, args...)\n\nLike `vmap!` (see `vmap!`), but uses `Threads.@threads` for parallel execution.\n\"\"\"\nfunction vmapt!(\n f::F, y::DenseArray{T}, args::Vararg{DenseNativeArray,A}\n) where {F,T<:Base.HWReal,A}\n vmap_multithreaded!(f, y, Val{false}(), args...)\nend\n\n\n\"\"\"\n vmapnt!(::Function, dest, args...)\n\n\nThis is a vectorized map implementation using nontemporal store operations. This means that the write operations to the destination will not go to the CPU's cache.\nIf you will not immediately be reading from these values, this can improve performance because the writes won't pollute your cache. This can especially be the case if your arguments are very long.\n\n```julia\njulia> using LoopVectorization, BenchmarkTools\n\njulia> x = rand(10^8); y = rand(10^8); z = similar(x);\n\njulia> f(x,y) = exp(-0.5abs2(x - y))\nf (generic function with 1 method)\n\njulia> @benchmark map!(f, \\$z, \\$x, \\$y)\nBenchmarkTools.Trial:\n memory estimate: 0 bytes\n allocs estimate: 0\n --------------\n minimum time: 439.613 ms (0.00% GC)\n median time: 440.729 ms (0.00% GC)\n mean time: 440.695 ms (0.00% GC)\n maximum time: 441.665 ms (0.00% GC)\n --------------\n samples: 12\n evals/sample: 1\n\njulia> @benchmark vmap!(f, \\$z, \\$x, \\$y)\nBenchmarkTools.Trial:\n memory estimate: 0 bytes\n allocs estimate: 0\n --------------\n minimum time: 178.147 ms (0.00% GC)\n median time: 178.381 ms (0.00% GC)\n mean time: 178.430 ms (0.00% GC)\n maximum time: 179.054 ms (0.00% GC)\n --------------\n samples: 29\n evals/sample: 1\n\njulia> @benchmark vmapnt!(f, \\$z, \\$x, \\$y)\nBenchmarkTools.Trial:\n memory estimate: 0 bytes\n allocs estimate: 0\n --------------\n minimum time: 144.183 ms (0.00% GC)\n median time: 144.338 ms (0.00% GC)\n mean time: 144.349 ms (0.00% GC)\n maximum time: 144.641 ms (0.00% GC)\n --------------\n samples: 35\n evals/sample: 1\n```\n\"\"\"\nfunction vmapnt!(\n f::F, y::DenseArray{T}, args::Vararg{DenseNativeArray,A}\n) where {F,T<:Base.HWReal,A}\n vmap_singlethread!(f, y, Val{true}(), args...)\nend\n\n\"\"\"\n vmapntt!(::Function, dest, args...)\n\nLike `vmapnt!` (see `vmapnt!`), but uses `Threads.@threads` for parallel execution.\n\"\"\"\nfunction vmapntt!(\n f::F, y::DenseArray{T}, args::Vararg{DenseNativeArray,A}\n) where {F,T<:Base.HWReal,A}\n vmap_multithreaded!(f, y, Val{true}(), args...)\nend\n\n# generic fallbacks\n@inline vmap!(f, args...) = map!(f, args...)\n@inline vmapt!(f, args...) = map!(f, args...)\n@inline vmapnt!(f, args...) = map!(f, args...)\n@inline vmapntt!(f, args...) = map!(f, args...)\n\nfunction vmap_call(f::F, vm!::V, args::Vararg{Any,N}) where {V,F,N}\n T = Base._return_type(f, Base.Broadcast.eltypes(args))\n dest = similar(first(args), T)\n vm!(f, dest, args...)\nend\n\n\"\"\"\n vmap(f, a::AbstractArray)\n vmap(f, a::AbstractArray, b::AbstractArray, ...)\n\nSIMD-vectorized `map`, applying `f` to each element of `a` (or paired elements of `a`, `b`, ...)\nand returning a new array.\n\"\"\"\nvmap(f::F, args::Vararg{Any,N}) where {F,N} = vmap_call(f, vmap!, args...)\n\n\"\"\"\n vmapt(f, a::AbstractArray)\n vmapt(f, a::AbstractArray, b::AbstractArray, ...)\n\nA threaded variant of [`vmap`](@ref).\n\"\"\"\nvmapt(f::F, args::Vararg{Any,N}) where {F,N} = vmap_call(f, vmapt!, args...)\n\n\"\"\"\n vmapnt(f, a::AbstractArray)\n vmapnt(f, a::AbstractArray, b::AbstractArray, ...)\n\nA \"non-temporal\" variant of [`vmap`](@ref). This can improve performance in cases where\n`destination` will not be needed soon.\n\"\"\"\nvmapnt(f::F, args::Vararg{Any,N}) where {F,N} = vmap_call(f, vmapnt!, args...)\n\n\"\"\"\n vmapntt(f, a::AbstractArray)\n vmapntt(f, a::AbstractArray, b::AbstractArray, ...)\n\nA threaded variant of [`vmapnt`](@ref).\n\"\"\"\nvmapntt(f::F, args::Vararg{Any,N}) where {F,N} = vmap_call(f, vmapntt!, args...)\n\n\n# @inline vmap!(f, y, x...) = @avx y .= f.(x...)\n# @inline vmap(f, x...) = @avx f.(x...)\n", "meta": {"hexsha": "a3878f0c93e99b7aadaf0ce799bfaa0d5eb4e37d", "size": 9085, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/map.jl", "max_stars_repo_name": "timholy/LoopVectorization.jl", "max_stars_repo_head_hexsha": "ad11641a459e023746e8dcfed01b42463fb6701b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/map.jl", "max_issues_repo_name": "timholy/LoopVectorization.jl", "max_issues_repo_head_hexsha": "ad11641a459e023746e8dcfed01b42463fb6701b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-05T10:19:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-05T10:19:17.000Z", "max_forks_repo_path": "src/map.jl", "max_forks_repo_name": "timholy/LoopVectorization.jl", "max_forks_repo_head_hexsha": "ad11641a459e023746e8dcfed01b42463fb6701b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7657342657, "max_line_length": 196, "alphanum_fraction": 0.5949367089, "num_tokens": 3063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23517796009321698}} {"text": "using Revise\nusing Plots\nusing Pkg\n# Pkg.activate(\".\")\nusing RadiativeTransfer\nusing RadiativeTransfer.Architectures\nusing RadiativeTransfer.Absorption\nusing RadiativeTransfer.Scattering\nusing RadiativeTransfer.vSmartMOM\nusing RadiativeTransfer.SolarModel\nusing InstrumentOperator\nusing Interpolations\nusing Polynomials\nusing ForwardDiff \nusing Distributions\nusing NCDatasets\n\n## Atmospheric Radiative Transfer\n\n# Load parameters from file\nparameters = vSmartMOM.parameters_from_yaml(\"test/test_parameters/O2Parameters.yaml\")\n#parameters.architecture = CPU()\nFT = Float64\n\n# Load OCO Data: \n# File names:\nL1File = \"/net/fluo/data1/group/oco2/L1bSc/oco2_L1bScND_26780a_190715_B10003r_200429212407.h5\"\nmetFile = \"/net/fluo/data1/group/oco2/L2Met/oco2_L2MetND_26780a_190715_B10003r_200429212406.h5\"\ndictFile = \"/home/cfranken/code/gitHub/InstrumentOperator.jl/json/oco2.yaml\"\n\n\n# Load L1 file (could just use filenames here as well)\noco = InstrumentOperator.load_L1(dictFile,L1File, metFile);\n\n# oco2_L1bScND_18688a_180105_B8100r_180206190633\n\noco_file = \"/net/fluo/data1/group/oco2/L1bSc/oco2_L1bScGL_15258a_170515_B10003r_200214061601.h5\"\noco_met_file = \"/net/fluo/data1/group/oco2/L2Met/oco2_L2MetGL_26777a_190715_B10003r_200429213029.h5\"\nils_file = \"test/prototyping/ils_oco2.json\"\n\n# Pick some bands as tuple (or just one)\nbands = (1,);\n# Indices within that band:\nindices = (92:885,);\n# Geo Index (footprint,sounding):\nGeoInd = [5,5000];\n\n# Get data for that sounding:\noco_sounding = InstrumentOperator.getMeasurement(oco, bands, indices, GeoInd)\n\nfp = 5\niOrbit = 5000\nband = 1\n\nsza_ = 32.4436\nvza_ = [0.072]\n\n\nfunction conv_spectra_local(m::VariableKernelInstrument, ν, spectrum; stride=1)\n # FT = eltype(m.ν_out)\n # Define grid where to perform convolution:\n \n # Padding at both sides required:\n off = ceil(Int, size(m.kernel, 1) / 2)\n ind = off:stride:(length(ν) - off)\n \n # knots where convolution will be applied to\n knots = view(ν, ind)\n te = LinearInterpolation(m.ν_out, Float32.(m.ind_out))\n spec_out = zeros(Real, length(knots));\n for i in eachindex(knots)\n # Simple first, nearest neighbor ILS\n ind_fraction = round(Int, te(knots[i]));\n kernel = view(m.kernel, :, ind_fraction)\n for j in eachindex(kernel)\n spec_out[i] += kernel[j] * spectrum[ind[i] + j] \n end\n end\n # Change this later to only perform conv around output grid!\n fin = LinearInterpolation(ν[ind], spec_out; extrapolation_bc=Interpolations.Flat())\n return fin(m.ν_out)\nend;\n\n# Runner is used to set AD fields as duals\nfunction runner!(y, x, parameters=parameters, oco_file=oco_file, \n oco_met_file=oco_met_file, \n ils_file=ils_file, fp=fp, iOrbit=iOrbit,\n sza_=sza_, vza_=vza_)\n\n # Set parameters fields as the dual numbers\n parameters.brdf = [vSmartMOM.LambertianSurfaceLegendre([x[1],x[3],x[4]])]\n\n parameters.scattering_params.rt_aerosols[1].τ_ref = exp(x[2]);\n parameters.scattering_params.rt_aerosols[1].p₀ = 70000.0; #x[4]\n # parameters.scattering_params.rt_aerosols[1].aerosol.size_distribution = LogNormal(log(x[3]), log(x[4]), check_args=false)\n\n # parameters.scattering_params.rt_aerosols[1].aerosol.nᵣ = x[5];\n # parameters.scattering_params.rt_aerosols[1].aerosol.nᵢ = x[6];\n\n # parameters.scattering_params.rt_aerosols[1].p₀ = x[7];\n # parameters.scattering_params.rt_aerosols[1].σp = x[8];\n ocoData = Dataset(oco_file)\n SoundingGeometry = ocoData.group[\"SoundingGeometry\"]\n ϕ = SoundingGeometry[\"sounding_polarization_angle\"][fp,iOrbit]\n m₁ = 0.5\n m₂ = cosd(2ϕ)/2\n m₃ = sind(2ϕ)/2\n # Stokes:\n\n # Set profiles properly\n met = Dataset(oco_met_file);\n T_met = met.group[\"Meteorology\"][\"temperature_profile_met\"][:,fp,iOrbit];\n ak = met.group[\"MeteorologyDiagnostics\"][\"ak\"][:,fp,iOrbit];\n bk = met.group[\"MeteorologyDiagnostics\"][\"bk\"][:,fp,iOrbit];\n ak = [0.000000e+00, 4.804826e-02, 6.593752e+00, 1.313480e+01, 1.961311e+01, 2.609201e+01,\n3.257081e+01, 3.898201e+01, 4.533901e+01, 5.169611e+01, 5.805321e+01, 6.436264e+01,\n7.062198e+01, 7.883422e+01, 8.909992e+01, 9.936521e+01, 1.091817e+02, 1.189586e+02,\n1.286959e+02, 1.429100e+02, 1.562600e+02, 1.696090e+02, 1.816190e+02, 1.930970e+02,\n2.032590e+02, 2.121500e+02, 2.187760e+02, 2.238980e+02, 2.243630e+02, 2.168650e+02,\n2.011920e+02, 1.769300e+02, 1.503930e+02, 1.278370e+02, 1.086630e+02, 9.236572e+01,\n7.851231e+01, 6.660341e+01, 5.638791e+01, 4.764391e+01, 4.017541e+01, 3.381001e+01,\n2.836781e+01, 2.373041e+01, 1.979160e+01, 1.645710e+01, 1.364340e+01, 1.127690e+01,\n9.292942e+00, 7.619842e+00, 6.216801e+00, 5.046801e+00, 4.076571e+00, 3.276431e+00,\n2.620211e+00, 2.084970e+00, 1.650790e+00, 1.300510e+00, 1.019440e+00, 7.951341e-01,\n6.167791e-01, 4.758061e-01, 3.650411e-01, 2.785261e-01, 2.113490e-01, 1.594950e-01,\n1.197030e-01, 8.934502e-02, 6.600001e-02, 4.758501e-02, 3.270000e-02, 2.000000e-02,\n1.000000e-02][end:-1:1]\n\nbk = [1.000000e+00, 9.849520e-01, 9.634060e-01, 9.418650e-01, 9.203870e-01, 8.989080e-01,\n8.774290e-01, 8.560180e-01, 8.346609e-01, 8.133039e-01, 7.919469e-01, 7.706375e-01,\n7.493782e-01, 7.211660e-01, 6.858999e-01, 6.506349e-01, 6.158184e-01, 5.810415e-01,\n5.463042e-01, 4.945902e-01, 4.437402e-01, 3.928911e-01, 3.433811e-01, 2.944031e-01,\n2.467411e-01, 2.003501e-01, 1.562241e-01, 1.136021e-01, 6.372006e-02, 2.801004e-02,\n6.960025e-03, 8.175413e-09, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,\n0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,\n0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,\n0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,\n0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,\n0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,\n0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,\n0.000000e+00][end:-1:1]\n\n p_surf = met.group[\"Meteorology\"][\"surface_pressure_met\"][fp,iOrbit];\n p_half = (ak + bk * p_surf);\n #p_half = vcat(p_half, p_surf);\n q = met.group[\"Meteorology\"][\"specific_humidity_profile_met\"][:,fp,iOrbit];\n parameters.p = p_half / 100\n parameters.q = q # zeros(size(q))\n parameters.T = T_met \n #parameters.T[end-30:end] .-= 10\n parameters.sza = sza_\n parameters.vza = vza_\n\n @show parameters.sza, parameters.vza\n\n # @show parameters.sza\n # plot!(parameters.p)\n # return \n\n\n model = model_from_parameters(parameters);\n @show sum(model.τ_rayl[1] )\n # Run the model to obtain reflectance matrix\n R = vSmartMOM.rt_run(model, i_band=1);\n RR = m₁*R[1,1,:] + m₂*R[1,2,:] + m₃*R[1,3,:]\n @show size(R)\n # Produce black-body in wavenumber range\n T = 5777\n λ_grid = reverse(1e4 ./ parameters.spec_bands[1]) #collect(757:0.01:777)\n black_body = planck_spectrum_wl(T, λ_grid) * 2.1629e-05 * pi\n black_body = SolarModel.watts_to_photons(λ_grid, black_body)\n\n # Get solar transmittance spectrum \n #solar_transmission = solar_transmission_from_file(\"/home/rjeyaram/RadiativeTransfer/src/solar_merged_20160127_600_26316_100.out\", parameters.spec_bands[1])\n solar_transmission = solar_transmission_from_file(\"/home/rjeyaram/RadiativeTransfer/src/SolarModel/solar.out\", parameters.spec_bands[1])\n # Get outgoing solar radiation\n sun_out = reverse(solar_transmission) .* black_body\n\n # Apply Earth reflectance matrix \n earth_out = sun_out .* reverse(RR[:])\n\n # Set up InstrumentOperator\n ils_Δ, ils_in, dispersion = InstrumentOperator.read_ils_table(oco_file, ils_file);\n\n # Define model grid:\n res = 0.001\n\n # Just consider the ILS within ± 0.35nm\n grid_x = -0.35e-3:res*1e-3:0.35e-3\n \n extended_dims = [fp,band] # Footprint, band\n\n # Re-interpolate I from ν_grid to new grid/resolution\n interp_I = LinearInterpolation(λ_grid, earth_out);\n wl = 757.5:res:771.0\n I_wl = interp_I(wl/1000)\n\n # Pixels to be used\n ind_out = collect(0:1015); \n\n # Eventual grid of OCO-2 for Band 1, FP 5:\n dispPoly = Polynomial(view(dispersion, :, extended_dims...))\n ν = Float32.(dispPoly.(1:1016))\n\n # Prepare ILS table:\n ils_pixel = InstrumentOperator.prepare_ils_table(grid_x, ils_in, ils_Δ,extended_dims)\n oco2_kernel = VariableKernelInstrument(ils_pixel, ν, ind_out)\n\n # Convolve input spectrum with variable kernel\n I_conv = conv_spectra_local(oco2_kernel, wl./1e3, I_wl)\n\n y[:] = I_conv[:]\n\nend\n\ndirectory = \"/net/fluo/data1/group/oco2/L1bSc/\"\nfiles_list = filter(x->endswith(x, \".h5\") && startswith(x, \"oco2_L1bScND_26\"), readdir(directory))\n\nmet_files_list = filter(x->endswith(x, \".h5\"), readdir(\"/net/fluo/data1/group/oco2/L2Met/\"))\n\nI_convs_all = zeros(1016, length(files_list))\noco2_Abands_all = zeros(1016, length(files_list))\n\nalbedos = zeros(length(files_list))\ncloud_levels = zeros(length(files_list))\n\noptimal_x = zeros(8, length(files_list))\n\n#for i in 1:length(files_list)\ni = 1\nind = 92:885\n@show i\n\noco_file = files_list[i]\n\n # try\nocoData = Dataset(directory * oco_file)\noco_met_file = \"/net/fluo/data1/group/oco2/L2Met/\" * filter(x->contains(x, oco_file[14:19]), met_files_list)[1]\noco_file = directory * oco_file\nmet = Dataset(oco_met_file)\ncloud_levels[i] = met.group[\"Meteorology\"][\"cloud_liquid_water_path_met\"][fp,iOrbit]\n\n\n## Getting an OCO spectrum for fun to fit:\no2AbandSpectra = ocoData.group[\"SoundingMeasurements\"][\"radiance_o2\"]\nSoundingGeometry = ocoData.group[\"SoundingGeometry\"]\nϕ = SoundingGeometry[\"sounding_polarization_angle\"][fp,iOrbit]\nm₁ = 0.5\nm₂ = cosd(2ϕ)/2\nm₃ = sind(2ϕ)/2\nvza = SoundingGeometry[\"sounding_zenith\"]\nsza = SoundingGeometry[\"sounding_solar_zenith\"]\nlat = SoundingGeometry[\"sounding_latitude\"]\nlon = SoundingGeometry[\"sounding_longitude\"]\no2AbandSpectra = ocoData.group[\"SoundingMeasurements\"][\"radiance_o2\"]\noco2_Aband = o2AbandSpectra[:,fp,iOrbit]\n\nprintln(\"$(round(Float64(lat[fp,iOrbit]), digits=2)) $(round(Float64(lon[fp,iOrbit]), digits=4))\")\n# continue\nsza_ = sza[fp,iOrbit]\nvza_ = [vza[fp,iOrbit]]\n\n# State vector\nx = FT[0.2377,\n -1, -0.00244, 0]#,\n\n\n# Run FW model:\n# @time runner(x);\nI_conv = zeros(1016)\ny = oco2_Aband[ind];\nfor i=1:3\n dfdx = ForwardDiff.jacobian(runner!, I_conv, x);\n Fx = I_conv[ind];\n K = dfdx[ind,:];\n dx = K \\ (y-Fx)\n x += dx\n @show x\nend\nrunner!(I_conv,x)\nFx = I_conv[ind];\n\n \n# plot fits\nils_Δ, ils_in, dispersion = InstrumentOperator.read_ils_table(oco_file, ils_file);\nextended_dims = [fp,band]; # Footprint, band\n# Eventual grid of OCO-2 for Band 1, FP 5:\ndispPoly = Polynomial(view(dispersion, :, extended_dims...));\nν = Float32.(dispPoly.(1:1016));\nplot(ν[ind]*1e3, y/1e20, label=\"Meas\")\nplot!(ν[ind]*1e3, Fx/1e20, label=\"Mod\")\nplot!(ν[ind]*1e3, (y-Fx)/1e20, label=\"Meas-mod\")\n\n\nfunction sampleOCO_Orbit(fp,iOrbit,l1,met)\n\nend", "meta": {"hexsha": "b3ef66925127f9d82df6bec98af55ae61efd00c1", "size": 11014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/prototyping/AD_simple_test.jl", "max_stars_repo_name": "RemoteSensingTools/vSmartMOM.jl", "max_stars_repo_head_hexsha": "fe5b7d28ca99bef0d1702293749d217e8c839db6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/prototyping/AD_simple_test.jl", "max_issues_repo_name": "RemoteSensingTools/vSmartMOM.jl", "max_issues_repo_head_hexsha": "fe5b7d28ca99bef0d1702293749d217e8c839db6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-10T21:24:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T21:31:57.000Z", "max_forks_repo_path": "test/prototyping/AD_simple_test.jl", "max_forks_repo_name": "RemoteSensingTools/vSmartMOM.jl", "max_forks_repo_head_hexsha": "fe5b7d28ca99bef0d1702293749d217e8c839db6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-11T17:24:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T17:24:22.000Z", "avg_line_length": 37.0841750842, "max_line_length": 160, "alphanum_fraction": 0.7029235518, "num_tokens": 4108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2350037122015945}} {"text": "function FieldVector3D(arg0::Field, arg1::Vector3D)\n return FieldVector3D((Field, Vector3D), arg0, arg1)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::FieldVector3D)\n return FieldVector3D((RealFieldElement, FieldVector3D), arg0, arg1)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::FieldVector3D, arg2::RealFieldElement, arg3::FieldVector3D)\n return FieldVector3D((RealFieldElement, FieldVector3D, RealFieldElement, FieldVector3D), arg0, arg1, arg2, arg3)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::FieldVector3D, arg2::RealFieldElement, arg3::FieldVector3D, arg4::RealFieldElement, arg5::FieldVector3D)\n return FieldVector3D((RealFieldElement, FieldVector3D, RealFieldElement, FieldVector3D, RealFieldElement, FieldVector3D), arg0, arg1, arg2, arg3, arg4, arg5)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::FieldVector3D, arg2::RealFieldElement, arg3::FieldVector3D, arg4::RealFieldElement, arg5::FieldVector3D, arg6::RealFieldElement, arg7::FieldVector3D)\n return FieldVector3D((RealFieldElement, FieldVector3D, RealFieldElement, FieldVector3D, RealFieldElement, FieldVector3D, RealFieldElement, FieldVector3D), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::RealFieldElement)\n return FieldVector3D((RealFieldElement, RealFieldElement), arg0, arg1)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::RealFieldElement, arg2::RealFieldElement)\n return FieldVector3D((RealFieldElement, RealFieldElement, RealFieldElement), arg0, arg1, arg2)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::Vector3D)\n return FieldVector3D((RealFieldElement, Vector3D), arg0, arg1)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::Vector3D, arg2::RealFieldElement, arg3::Vector3D)\n return FieldVector3D((RealFieldElement, Vector3D, RealFieldElement, Vector3D), arg0, arg1, arg2, arg3)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::Vector3D, arg2::RealFieldElement, arg3::Vector3D, arg4::RealFieldElement, arg5::Vector3D)\n return FieldVector3D((RealFieldElement, Vector3D, RealFieldElement, Vector3D, RealFieldElement, Vector3D), arg0, arg1, arg2, arg3, arg4, arg5)\nend\n\nfunction FieldVector3D(arg0::RealFieldElement, arg1::Vector3D, arg2::RealFieldElement, arg3::Vector3D, arg4::RealFieldElement, arg5::Vector3D, arg6::RealFieldElement, arg7::Vector3D)\n return FieldVector3D((RealFieldElement, Vector3D, RealFieldElement, Vector3D, RealFieldElement, Vector3D, RealFieldElement, Vector3D), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\nend\n\nfunction FieldVector3D(arg0::Vector{RealFieldElement})\n return FieldVector3D((Vector{RealFieldElement},), arg0)\nend\n\nfunction FieldVector3D(arg0::jdouble, arg1::FieldVector3D)\n return FieldVector3D((jdouble, FieldVector3D), arg0, arg1)\nend\n\nfunction FieldVector3D(arg0::jdouble, arg1::FieldVector3D, arg2::jdouble, arg3::FieldVector3D)\n return FieldVector3D((jdouble, FieldVector3D, jdouble, FieldVector3D), arg0, arg1, arg2, arg3)\nend\n\nfunction FieldVector3D(arg0::jdouble, arg1::FieldVector3D, arg2::jdouble, arg3::FieldVector3D, arg4::jdouble, arg5::FieldVector3D)\n return FieldVector3D((jdouble, FieldVector3D, jdouble, FieldVector3D, jdouble, FieldVector3D), arg0, arg1, arg2, arg3, arg4, arg5)\nend\n\nfunction FieldVector3D(arg0::jdouble, arg1::FieldVector3D, arg2::jdouble, arg3::FieldVector3D, arg4::jdouble, arg5::FieldVector3D, arg6::jdouble, arg7::FieldVector3D)\n return FieldVector3D((jdouble, FieldVector3D, jdouble, FieldVector3D, jdouble, FieldVector3D, jdouble, FieldVector3D), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\nend\n\nfunction add(obj::FieldVector3D, arg0::FieldVector3D)\n return jcall(obj, \"add\", FieldVector3D, (FieldVector3D,), arg0)\nend\n\nfunction add(obj::FieldVector3D, arg0::RealFieldElement, arg1::FieldVector3D)\n return jcall(obj, \"add\", FieldVector3D, (RealFieldElement, FieldVector3D), arg0, arg1)\nend\n\nfunction add(obj::FieldVector3D, arg0::RealFieldElement, arg1::Vector3D)\n return jcall(obj, \"add\", FieldVector3D, (RealFieldElement, Vector3D), arg0, arg1)\nend\n\nfunction add(obj::FieldVector3D, arg0::Vector3D)\n return jcall(obj, \"add\", FieldVector3D, (Vector3D,), arg0)\nend\n\nfunction add(obj::FieldVector3D, arg0::jdouble, arg1::FieldVector3D)\n return jcall(obj, \"add\", FieldVector3D, (jdouble, FieldVector3D), arg0, arg1)\nend\n\nfunction add(obj::FieldVector3D, arg0::jdouble, arg1::Vector3D)\n return jcall(obj, \"add\", FieldVector3D, (jdouble, Vector3D), arg0, arg1)\nend\n\nfunction angle(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"angle\", RealFieldElement, (FieldVector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction angle(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::Vector3D)\n return jcall(FieldVector3D, \"angle\", RealFieldElement, (FieldVector3D, Vector3D), arg0, arg1)\nend\n\nfunction angle(::Type{FieldVector3D}, arg0::Vector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"angle\", RealFieldElement, (Vector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction cross_product(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"crossProduct\", FieldVector3D, (FieldVector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction cross_product(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::Vector3D)\n return jcall(FieldVector3D, \"crossProduct\", FieldVector3D, (FieldVector3D, Vector3D), arg0, arg1)\nend\n\nfunction cross_product(::Type{FieldVector3D}, arg0::Vector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"crossProduct\", FieldVector3D, (Vector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction cross_product(obj::FieldVector3D, arg0::FieldVector3D)\n return jcall(obj, \"crossProduct\", FieldVector3D, (FieldVector3D,), arg0)\nend\n\nfunction cross_product(obj::FieldVector3D, arg0::Vector3D)\n return jcall(obj, \"crossProduct\", FieldVector3D, (Vector3D,), arg0)\nend\n\nfunction distance(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"distance\", RealFieldElement, (FieldVector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction distance(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::Vector3D)\n return jcall(FieldVector3D, \"distance\", RealFieldElement, (FieldVector3D, Vector3D), arg0, arg1)\nend\n\nfunction distance(::Type{FieldVector3D}, arg0::Vector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"distance\", RealFieldElement, (Vector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction distance(obj::FieldVector3D, arg0::FieldVector3D)\n return jcall(obj, \"distance\", RealFieldElement, (FieldVector3D,), arg0)\nend\n\nfunction distance(obj::FieldVector3D, arg0::Vector3D)\n return jcall(obj, \"distance\", RealFieldElement, (Vector3D,), arg0)\nend\n\nfunction distance1(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"distance1\", RealFieldElement, (FieldVector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction distance1(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::Vector3D)\n return jcall(FieldVector3D, \"distance1\", RealFieldElement, (FieldVector3D, Vector3D), arg0, arg1)\nend\n\nfunction distance1(::Type{FieldVector3D}, arg0::Vector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"distance1\", RealFieldElement, (Vector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction distance1(obj::FieldVector3D, arg0::FieldVector3D)\n return jcall(obj, \"distance1\", RealFieldElement, (FieldVector3D,), arg0)\nend\n\nfunction distance1(obj::FieldVector3D, arg0::Vector3D)\n return jcall(obj, \"distance1\", RealFieldElement, (Vector3D,), arg0)\nend\n\nfunction distance_inf(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"distanceInf\", RealFieldElement, (FieldVector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction distance_inf(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::Vector3D)\n return jcall(FieldVector3D, \"distanceInf\", RealFieldElement, (FieldVector3D, Vector3D), arg0, arg1)\nend\n\nfunction distance_inf(::Type{FieldVector3D}, arg0::Vector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"distanceInf\", RealFieldElement, (Vector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction distance_inf(obj::FieldVector3D, arg0::FieldVector3D)\n return jcall(obj, \"distanceInf\", RealFieldElement, (FieldVector3D,), arg0)\nend\n\nfunction distance_inf(obj::FieldVector3D, arg0::Vector3D)\n return jcall(obj, \"distanceInf\", RealFieldElement, (Vector3D,), arg0)\nend\n\nfunction distance_sq(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"distanceSq\", RealFieldElement, (FieldVector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction distance_sq(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::Vector3D)\n return jcall(FieldVector3D, \"distanceSq\", RealFieldElement, (FieldVector3D, Vector3D), arg0, arg1)\nend\n\nfunction distance_sq(::Type{FieldVector3D}, arg0::Vector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"distanceSq\", RealFieldElement, (Vector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction distance_sq(obj::FieldVector3D, arg0::FieldVector3D)\n return jcall(obj, \"distanceSq\", RealFieldElement, (FieldVector3D,), arg0)\nend\n\nfunction distance_sq(obj::FieldVector3D, arg0::Vector3D)\n return jcall(obj, \"distanceSq\", RealFieldElement, (Vector3D,), arg0)\nend\n\nfunction dot_product(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"dotProduct\", RealFieldElement, (FieldVector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction dot_product(::Type{FieldVector3D}, arg0::FieldVector3D, arg1::Vector3D)\n return jcall(FieldVector3D, \"dotProduct\", RealFieldElement, (FieldVector3D, Vector3D), arg0, arg1)\nend\n\nfunction dot_product(::Type{FieldVector3D}, arg0::Vector3D, arg1::FieldVector3D)\n return jcall(FieldVector3D, \"dotProduct\", RealFieldElement, (Vector3D, FieldVector3D), arg0, arg1)\nend\n\nfunction dot_product(obj::FieldVector3D, arg0::FieldVector3D)\n return jcall(obj, \"dotProduct\", RealFieldElement, (FieldVector3D,), arg0)\nend\n\nfunction dot_product(obj::FieldVector3D, arg0::Vector3D)\n return jcall(obj, \"dotProduct\", RealFieldElement, (Vector3D,), arg0)\nend\n\nfunction equals(obj::FieldVector3D, arg0::Object)\n return jcall(obj, \"equals\", jboolean, (Object,), arg0)\nend\n\nfunction get_alpha(obj::FieldVector3D)\n return jcall(obj, \"getAlpha\", RealFieldElement, ())\nend\n\nfunction get_delta(obj::FieldVector3D)\n return jcall(obj, \"getDelta\", RealFieldElement, ())\nend\n\nfunction get_minus_i(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getMinusI\", FieldVector3D, (Field,), arg0)\nend\n\nfunction get_minus_j(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getMinusJ\", FieldVector3D, (Field,), arg0)\nend\n\nfunction get_minus_k(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getMinusK\", FieldVector3D, (Field,), arg0)\nend\n\nfunction get_na_n(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getNaN\", FieldVector3D, (Field,), arg0)\nend\n\nfunction get_negative_infinity(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getNegativeInfinity\", FieldVector3D, (Field,), arg0)\nend\n\nfunction get_norm(obj::FieldVector3D)\n return jcall(obj, \"getNorm\", RealFieldElement, ())\nend\n\nfunction get_norm1(obj::FieldVector3D)\n return jcall(obj, \"getNorm1\", RealFieldElement, ())\nend\n\nfunction get_norm_inf(obj::FieldVector3D)\n return jcall(obj, \"getNormInf\", RealFieldElement, ())\nend\n\nfunction get_norm_sq(obj::FieldVector3D)\n return jcall(obj, \"getNormSq\", RealFieldElement, ())\nend\n\nfunction get_plus_i(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getPlusI\", FieldVector3D, (Field,), arg0)\nend\n\nfunction get_plus_j(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getPlusJ\", FieldVector3D, (Field,), arg0)\nend\n\nfunction get_plus_k(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getPlusK\", FieldVector3D, (Field,), arg0)\nend\n\nfunction get_positive_infinity(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getPositiveInfinity\", FieldVector3D, (Field,), arg0)\nend\n\nfunction get_x(obj::FieldVector3D)\n return jcall(obj, \"getX\", RealFieldElement, ())\nend\n\nfunction get_y(obj::FieldVector3D)\n return jcall(obj, \"getY\", RealFieldElement, ())\nend\n\nfunction get_z(obj::FieldVector3D)\n return jcall(obj, \"getZ\", RealFieldElement, ())\nend\n\nfunction get_zero(::Type{FieldVector3D}, arg0::Field)\n return jcall(FieldVector3D, \"getZero\", FieldVector3D, (Field,), arg0)\nend\n\nfunction hash_code(obj::FieldVector3D)\n return jcall(obj, \"hashCode\", jint, ())\nend\n\nfunction is_infinite(obj::FieldVector3D)\n return jcall(obj, \"isInfinite\", jboolean, ())\nend\n\nfunction is_na_n(obj::FieldVector3D)\n return jcall(obj, \"isNaN\", jboolean, ())\nend\n\nfunction negate(obj::FieldVector3D)\n return jcall(obj, \"negate\", FieldVector3D, ())\nend\n\nfunction normalize(obj::FieldVector3D)\n return jcall(obj, \"normalize\", FieldVector3D, ())\nend\n\nfunction orthogonal(obj::FieldVector3D)\n return jcall(obj, \"orthogonal\", FieldVector3D, ())\nend\n\nfunction scalar_multiply(obj::FieldVector3D, arg0::RealFieldElement)\n return jcall(obj, \"scalarMultiply\", FieldVector3D, (RealFieldElement,), arg0)\nend\n\nfunction scalar_multiply(obj::FieldVector3D, arg0::jdouble)\n return jcall(obj, \"scalarMultiply\", FieldVector3D, (jdouble,), arg0)\nend\n\nfunction subtract(obj::FieldVector3D, arg0::FieldVector3D)\n return jcall(obj, \"subtract\", FieldVector3D, (FieldVector3D,), arg0)\nend\n\nfunction subtract(obj::FieldVector3D, arg0::RealFieldElement, arg1::FieldVector3D)\n return jcall(obj, \"subtract\", FieldVector3D, (RealFieldElement, FieldVector3D), arg0, arg1)\nend\n\nfunction subtract(obj::FieldVector3D, arg0::RealFieldElement, arg1::Vector3D)\n return jcall(obj, \"subtract\", FieldVector3D, (RealFieldElement, Vector3D), arg0, arg1)\nend\n\nfunction subtract(obj::FieldVector3D, arg0::Vector3D)\n return jcall(obj, \"subtract\", FieldVector3D, (Vector3D,), arg0)\nend\n\nfunction subtract(obj::FieldVector3D, arg0::jdouble, arg1::FieldVector3D)\n return jcall(obj, \"subtract\", FieldVector3D, (jdouble, FieldVector3D), arg0, arg1)\nend\n\nfunction subtract(obj::FieldVector3D, arg0::jdouble, arg1::Vector3D)\n return jcall(obj, \"subtract\", FieldVector3D, (jdouble, Vector3D), arg0, arg1)\nend\n\nfunction to_array(obj::FieldVector3D)\n return jcall(obj, \"toArray\", Vector{RealFieldElement}, ())\nend\n\nfunction to_string(obj::FieldVector3D)\n return jcall(obj, \"toString\", JString, ())\nend\n\nfunction to_string(obj::FieldVector3D, arg0::NumberFormat)\n return jcall(obj, \"toString\", JString, (NumberFormat,), arg0)\nend\n\nfunction to_vector3d(obj::FieldVector3D)\n return jcall(obj, \"toVector3D\", Vector3D, ())\nend\n\n", "meta": {"hexsha": "35256cb8bb114db8fab187d9683140b1fd877248", "size": 14829, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gen/HipparchusWrapper/GeometryWrapper/EuclideanWrapper/ThreedWrapper/field_vector3_d.jl", "max_stars_repo_name": "JuliaAstrodynamics/Orekit.jl", "max_stars_repo_head_hexsha": "e2dd3d8b2085dcbb1d2c75471dab42d6ddf52c99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-07T12:26:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T16:02:35.000Z", "max_issues_repo_path": "gen/HipparchusWrapper/GeometryWrapper/EuclideanWrapper/ThreedWrapper/field_vector3_d.jl", "max_issues_repo_name": "JuliaSpace/Orekit.jl", "max_issues_repo_head_hexsha": "e2dd3d8b2085dcbb1d2c75471dab42d6ddf52c99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-05T10:16:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-30T05:17:19.000Z", "max_forks_repo_path": "gen/HipparchusWrapper/GeometryWrapper/EuclideanWrapper/ThreedWrapper/field_vector3_d.jl", "max_forks_repo_name": "JuliaSpace/Orekit.jl", "max_forks_repo_head_hexsha": "e2dd3d8b2085dcbb1d2c75471dab42d6ddf52c99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7560321716, "max_line_length": 206, "alphanum_fraction": 0.7691685211, "num_tokens": 4662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23493508547998257}} {"text": "include(\"boundary_conditions_adapted.jl\")\n\"\"\"\n calc_boundary_state!(::NumericalFluxSecondOrder, ::Impenetrable{FreeSlip}, ::ModelSetup)\napply free slip boundary condition for velocity\napply zero numerical flux in the normal direction\n\"\"\"\nfunction calc_boundary_state!(\n ::NumericalFluxSecondOrder,\n ::Impenetrable{FreeSlip},\n ::Union{ModelSetup},\n ::Nothing,\n state⁺,\n gradflux⁺,\n hyperflux⁺,\n aux⁺,\n n⁻,\n state⁻,\n gradflux⁻,\n hyperflux⁻,\n aux⁻,\n t,\n _...,\n)\n state⁺.ρu = state⁻.ρu\n\n return nothing\nend\n\nfunction calc_boundary_state!(\n ::NumericalFluxSecondOrder,\n ::Impenetrable{FreeSlip},\n ::Union{ModelSetup},\n ::ConstantViscosity,\n state⁺,\n gradflux⁺,\n hyperflux⁺,\n aux⁺,\n n⁻,\n state⁻,\n gradflux⁻,\n hyperflux⁻,\n aux⁻,\n t,\n _...,\n)\n state⁺.ρu = state⁻.ρu\n gradflux⁺.ν∇u = n⁻ * (@SVector [-0, -0, -0])'\n\n return nothing\nend\n\n\"\"\"\n calc_boundary_state!(::NumericalFluxSecondOrder, ::Impenetrable{NoSlip}, ::ModelSetup)\napply no slip boundary condition for velocity\nsets ghost point to have no numerical flux on the boundary for U\n\"\"\"\n@inline function calc_boundary_state!(\n ::NumericalFluxSecondOrder,\n ::Impenetrable{NoSlip},\n ::Union{ModelSetup},\n ::Nothing,\n state⁺,\n gradflux⁺,\n hyperflux⁺,\n aux⁺,\n n⁻,\n state⁻,\n gradflux⁻,\n hyperflux⁻,\n aux⁻,\n t,\n _...,\n)\n state⁺.ρu = -state⁻.ρu\n\n return nothing\nend\n\n@inline function calc_boundary_state!(\n ::NumericalFluxSecondOrder,\n ::Impenetrable{NoSlip},\n ::Union{ModelSetup},\n ::ConstantViscosity,\n state⁺,\n gradflux⁺,\n hyperflux⁺,\n aux⁺,\n n⁻,\n state⁻,\n gradflux⁻,\n hyperflux⁻,\n aux⁻,\n t,\n _...,\n)\n state⁺.ρu = -state⁻.ρu\n gradflux⁺.ν∇u = gradflux⁻.ν∇u\n\n return nothing\nend\n\n\"\"\"\n calc_boundary_state!(::NumericalFluxSecondOrder, ::Insulating, ::HBModel)\n\napply insulating boundary condition for velocity\nsets ghost point to have no numerical flux on the boundary for κ∇θ\n\"\"\"\n@inline function calc_boundary_state!(\n ::NumericalFluxSecondOrder,\n ::Union{Insulating, CoupledSecondaryBoundary, CoupledPrimaryBoundary},\n ::Union{ModelSetup},\n ::Nothing,\n state⁺,\n gradflux⁺,\n hyperflux⁺,\n aux⁺,\n n⁻,\n state⁻,\n gradflux⁻,\n hyperflux⁻,\n aux⁻,\n t,\n _...,\n)\n state⁺.ρθ = state⁻.ρθ\n\n return nothing\nend\n\n@inline function calc_boundary_state!(\n ::NumericalFluxSecondOrder,\n ::Union{Insulating, CoupledSecondaryBoundary, CoupledPrimaryBoundary},\n ::Union{ModelSetup},\n ::ConstantViscosity,\n state⁺,\n gradflux⁺,\n hyperflux⁺,\n aux⁺,\n n⁻,\n state⁻,\n gradflux⁻,\n hyperflux⁻,\n aux⁻,\n t,\n _...,\n)\n state⁺.ρθ = state⁻.ρθ\n gradflux⁺.κ∇θ = n⁻ * -0\n\n return nothing\nend\n", "meta": {"hexsha": "cf48bcd4d4e153da410565a86dfc7d9890d6fe14", "size": 2817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/ClimateMachine/SlabLand/boundary_conditions/bc_second_order.jl", "max_stars_repo_name": "CliMA/CouplerMachine", "max_stars_repo_head_hexsha": "34768de8dbca05b8c03c5c24626dea6c14404b03", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-05T07:09:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T07:09:01.000Z", "max_issues_repo_path": "experiments/ClimateMachine/SlabLand/boundary_conditions/bc_second_order.jl", "max_issues_repo_name": "CliMA/CouplerMachine", "max_issues_repo_head_hexsha": "34768de8dbca05b8c03c5c24626dea6c14404b03", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2021-04-01T13:23:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T04:15:01.000Z", "max_forks_repo_path": "experiments/ClimateMachine/SlabLand/boundary_conditions/bc_second_order.jl", "max_forks_repo_name": "CliMA/ClimaCoupler.jl", "max_forks_repo_head_hexsha": "d21349895a9bdaf9e192b534977deff9bb05385b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-05T16:29:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-05T16:29:27.000Z", "avg_line_length": 18.5328947368, "max_line_length": 92, "alphanum_fraction": 0.6215832446, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2349350854799825}} {"text": "for (syevd, elty, relty) in ((:ssyevd, :Float32, :Float32),\n (:dsyevd, :Float64, :Float64)),\n interface in (:Matrix, :CuMatrix)\n @eval begin\n function magma_syevd!(jobz::AbstractChar, uplo::AbstractChar, A::$interface{$elty})\n A = Matrix{$elty}(A)\n\n n = checksquare(A)\n lda = max(1, stride(A, 2))\n W = similar(A, $relty, n)\n work = Vector{$elty}(undef, 1)\n lwork = -1\n iwork = Vector{Int32}(undef, 1)\n liwork = -1\n info = Ref{Int}()\n\n jobz_magma = char_to_magmaInt(jobz)\n uplo_magma = char_to_magmaIntUplo(uplo)\n\n for i in 1:2\n func = eval(@magmafunc($syevd))\n func(\n jobz_magma,\n uplo_magma,\n n,\n A,\n lda,\n W,\n work,\n lwork,\n iwork,\n liwork,\n info\n )\n\n if i == 1\n lwork = ceil(Int, nextfloat(real(work[1])))\n resize!(work, lwork)\n liwork = Int(iwork[1])\n resize!(iwork, liwork)\n end\n end\n\n jobz == 'V' ? (W, A) : W\n end\n\n function magma_syevd_m!(ngpu::Int, jobz::AbstractChar, uplo::AbstractChar, A::$interface{$elty})\n A = Matrix{$elty}(A)\n\n n = checksquare(A)\n lda = max(1, stride(A, 2))\n W = similar(A, $relty, n)\n work = Vector{$elty}(undef, 1)\n lwork = -1\n iwork = Vector{Int32}(undef, 1)\n liwork = -1\n info = Ref{Int}()\n\n jobz_magma = char_to_magmaInt(jobz)\n uplo_magma = char_to_magmaIntUplo(uplo)\n\n for i in 1:2\n func = eval(@magmafunc_m($syevd))\n func(\n ngpu,\n jobz_magma,\n uplo_magma,\n n,\n A,\n lda,\n W,\n work,\n lwork,\n iwork,\n liwork,\n info\n )\n\n if i == 1\n lwork = ceil(Int, nextfloat(real(work[1])))\n resize!(work, lwork)\n liwork = Int(iwork[1])\n resize!(iwork, liwork)\n end\n end\n\n jobz == 'V' ? (W, A) : W\n end\n end\nend\n\nfor (syevd, elty, relty) in ((:cheevd, :ComplexF32, :Float32),\n (:zheevd, :ComplexF64, :Float64)),\n interface in (:Matrix, :CuMatrix)\n @eval begin\n function magma_syevd!(jobz::AbstractChar, uplo::AbstractChar, A::$interface{$elty})\n A = Matrix{$elty}(A)\n\n n = checksquare(A)\n lda = max(1, stride(A, 2))\n W = similar(A, $relty, n)\n work = Vector{$elty}(undef, 1)\n lwork = -1\n rwork = Vector{$relty}(undef, 1)\n lrwork = -1\n iwork = Vector{Int32}(undef, 1)\n liwork = -1\n info = Ref{Int}()\n\n jobz_magma = char_to_magmaInt(jobz)\n uplo_magma = char_to_magmaIntUplo(uplo)\n\n for i in 1:2\n func = eval(@magmafunc($syevd))\n func(\n jobz_magma,\n uplo_magma,\n n,\n A,\n lda,\n W,\n work,\n lwork,\n rwork,\n lrwork,\n iwork,\n liwork,\n info\n )\n\n if i == 1\n lwork = ceil(Int, nextfloat(real(work[1])))\n resize!(work, lwork)\n lrwork = ceil(Int, nextfloat(real(rwork[1])))\n resize!(rwork, lrwork)\n liwork = Int(iwork[1])\n resize!(iwork, liwork)\n end\n end\n\n jobz == 'V' ? (W, A) : W\n end\n\n function magma_syevd_m!(ngpu::Int, jobz::AbstractChar, uplo::AbstractChar, A::$interface{$elty})\n A = Matrix{$elty}(A)\n\n n = checksquare(A)\n lda = max(1, stride(A, 2))\n W = similar(A, $relty, n)\n work = Vector{$elty}(undef, 1)\n lwork = -1\n rwork = Vector{$relty}(undef, 1)\n lrwork = -1\n iwork = Vector{Int32}(undef, 1)\n liwork = -1\n info = Ref{Int}()\n\n jobz_magma = char_to_magmaInt(jobz)\n uplo_magma = char_to_magmaIntUplo(uplo)\n\n for i in 1:2\n func = eval(@magmafunc_m($syevd))\n func(\n ngpu,\n jobz_magma,\n uplo_magma,\n n,\n A,\n lda,\n W,\n work,\n lwork,\n rwork,\n lrwork,\n iwork,\n liwork,\n info\n )\n\n if i == 1\n lwork = ceil(Int, nextfloat(real(work[1])))\n resize!(work, lwork)\n lrwork = ceil(Int, nextfloat(real(rwork[1])))\n resize!(rwork, lrwork)\n liwork = Int(iwork[1])\n resize!(iwork, liwork)\n end\n end\n\n jobz == 'V' ? (W, A) : W\n end\n end\nend", "meta": {"hexsha": "a99ac76cb60c8f7207e9356e204f4504ecc73a3e", "size": 5878, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dense/eigen.jl", "max_stars_repo_name": "MGYamada/MAGMA.jl", "max_stars_repo_head_hexsha": "5545b1a27ee2516d9766c6a15238f006eceb1629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dense/eigen.jl", "max_issues_repo_name": "MGYamada/MAGMA.jl", "max_issues_repo_head_hexsha": "5545b1a27ee2516d9766c6a15238f006eceb1629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dense/eigen.jl", "max_forks_repo_name": "MGYamada/MAGMA.jl", "max_forks_repo_head_hexsha": "5545b1a27ee2516d9766c6a15238f006eceb1629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4559585492, "max_line_length": 104, "alphanum_fraction": 0.3633889078, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23484044302713086}} {"text": "struct Replicate_Report\n ids::Vector{Chain_ID} #replicates \n state_vecs::Dict{Chain_ID,Matrix{Float64}} #vectors of autotransition probabilities evolving by iterate, concatanated to matrices, indexed by Chain_ID\n emission_arrays::Dict{Chain_ID,Array{Float64}} #iterate*symbol*state_vecs\n sorted_id1_states::Vector{Integer}\n sort_dicts::Dict{Chain_ID,Dict{Integer,Integer}}#emission channels sorted on the basis of euclidean closeness to ids[1]\n sorted_symbols::Dict{Integer,Vector{Integer}}\n\n\n Replicate_Report(ids,state_vecs,emission_arrays, sorted_id1_states,sort_dicts,sorted_symbols) = assert_repreport(ids) && new(ids,state_vecs,emission_arrays,sorted_id1_states,sort_dicts,sorted_symbols)\nend\n\nfunction assert_repreport(ids::Vector{Chain_ID})\n Ks=Vector{Int64}()\n orders=Vector{Int64}()\n replicates=Vector{Int64}()\n obsids=Vector{String}()\n\n for id in ids\n push!(Ks,id.K)\n push!(orders,id.order)\n push!(obsids,id.obs_id)\n push!(replicates, id.replicate)\n end\n\n length(unique(Ks)) > 1 && throw(ArgumentError(\"Replicate set includes chains with different K state numbers! All chains must have HMMs with the same number of states.\"))\n length(unique(orders)) > 1 && throw(ArgumentError(\"Replicate set includes chains with different order coding numbers! All chains must have HMMs with the same order coding.\"))\n !allunique(replicates) && throw(ArgumentError(\"Replicate set includes chains with the same replicate #. Replicates should be unique!\"))\n\n return true\nend\n\nfunction report_replicates(repset::Vector{Chain_ID},chains::Dict{Chain_ID,Vector{EM_step}})\n assert_repreport(repset) #check that the repset will pass its constructor before doing the work\n emission_arrays=Dict{Chain_ID,AbstractArray{AbstractFloat}}()\n state_arrays=Dict{Chain_ID,AbstractArray{AbstractFloat}}()\n \n for id in repset\n emission_array=zeros(length(chains[id]),4^(id.order+1),id.K)\n state_array=zeros(length(chains[id]),id.K)\n for (it, step) in enumerate(chains[id])\n for k in 1:id.K\n emission_array[it,:,k]=step.hmm.B[k].p\n state_array[it,k]=step.hmm.A[k,k]\n end\n end\n emission_arrays[id]=emission_array\n state_arrays[id]=state_array\n end\n\n println(repset)\n println(emission_arrays)\n println(state_arrays)\n sort_dicts,sorted_id1_states,sorted_symbols=sort_emitters_by_distance!(repset,emission_arrays)\n\n return Replicate_Report(repset,state_arrays,emission_arrays,sorted_id1_states, sort_dicts,sorted_symbols)\nend\n\nfunction sort_emitters_by_distance!(repset,emission_arrays)\n id1=repset[1]\n length(repset)==1 && (return Dict{Chain_ID,Dict{Integer,Integer}}(),[1:id1.K...],[1:4^id1.order+1])\n\n final_emissions = zeros(length(repset),size(emission_arrays[id1])[2:3]...)\n for (n,id) in enumerate(repset)\n final_emissions[n,:,:] = emission_arrays[id][end,:,:]\n end\n\n distances=zeros(length(repset)-1,id1.K,id1.K)\n for rep in 1:length(repset)-1\n for k in 1:id1.K, j in 1:id1.K\n distances[rep,k,j]=euclidean(final_emissions[1,:,k],final_emissions[1+rep,:,j])\n end\n end\n\n sortdicts=Dict{Chain_ID,Dict{Integer,Integer}}()\n sorted_id1_states=Vector{Integer}()\n sorted_symbols=Dict{Integer,Vector{Integer}}()\n for rep in 1:length(repset)-1\n sortdicts[repset[rep+1]]=Dict{Integer,Integer}()\n end\n\n for i in 1:id1.K\n id1_mindist_K=findmin([sum([minimum(distances[rep,k,:]) for rep in 1:length(repset)-1]) for k in 1:id1.K])[2]#find the state from the first replicate that has minimum cumulative distance to the closest state in the other replicates, excluding already-chosen states by spiking their values\n push!(sorted_id1_states,id1_mindist_K)\n for rep in 1:length(repset)-1\n rep_k=findmin(distances[rep,id1_mindist_K,:])[2]\n sortdicts[repset[rep+1]][id1_mindist_K]=rep_k\n distances[rep,:,rep_k].=1.0 #mask\n distances[1,id1_mindist_K,:].=1.0 #mask\n end\n\n symbol_distances=sum(hcat([euclidean.(final_emissions[1,:,id1_mindist_K],final_emissions[n+1,:,sortdicts[id][id1_mindist_K]]) for (n,id) in enumerate(repset[2:end])]...),dims=2)\n sorted_symbols[id1_mindist_K]=sortperm(symbol_distances[:,1])\n end\n\n return sortdicts,sorted_id1_states,sorted_symbols\nend\n\n\nfunction Base.show(io::IO, report::Replicate_Report; top_states::Integer=report.ids[1].K, top_symbols::Integer=2)\n printstyled(io, \"REPLICATE CONVERGENCE REPORT\\n\", color=:green)\n println(\" ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶ ̶̶ ̶ ̶ ̶\")\n for i in 1:top_states\n id=report.ids[1]\n id1_state=report.sorted_id1_states[i]\n itmax=maximum([size(report.state_vecs[id],1) for id in report.ids])\n\n autoplt=lineplot(report.state_vecs[id][:,id1_state],\n title=\"Autotransition prob. convergence\",\n name=\"$(report.ids[1]) K$id1_state\",\n xlim=(0,ceil(itmax, sigdigits=2)),\n ylim=(0,1),\n xlabel=\"iterate\",\n ylabel=\"p\")\n\n symplot=lineplot(report.emission_arrays[id][:,report.sorted_symbols[id1_state][1],id1_state],\n report.emission_arrays[id][:,report.sorted_symbols[id1_state][2],id1_state], \n title=\"Symbol prob. convergence\",\n name=\"$(report.ids[1]) K$id1_state\",\n xlim=(0,1),\n ylim=(0,1),\n xlabel=\"Symbol 1 p\",\n ylabel=\"S2 p\")\n\n for (n,id) in enumerate(report.ids)\n if n > 1\n lineplot!(autoplt, report.state_vecs[id][:,report.sort_dicts[id][id1_state]],\n name=\"$(report.ids[n]) K$(report.sort_dicts[id][id1_state])\")\n lineplot!(symplot,\n report.emission_arrays[id][:,report.sorted_symbols[id1_state][1],report.sort_dicts[id][id1_state]],\n report.emission_arrays[id][:,report.sorted_symbols[id1_state][2],report.sort_dicts[id][id1_state]],\n name=\"$(report.ids[n]) K$(report.sort_dicts[id][id1_state])\")\n end\n end\n\n show(autoplt)\n println(\"\\n\")\n show(symplot)\n println(\"\\n\")\n end\nend", "meta": {"hexsha": "0daf9e83f34da27000ec80cc3be0f2c9f3f718e8", "size": 6517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/reports/replicate_convergence.jl", "max_stars_repo_name": "mmattocks/BioBackgroundModels.jl", "max_stars_repo_head_hexsha": "f64fd86ccb9ffcb24d6dffd7e37d21d3d8cb3223", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/reports/replicate_convergence.jl", "max_issues_repo_name": "mmattocks/BioBackgroundModels.jl", "max_issues_repo_head_hexsha": "f64fd86ccb9ffcb24d6dffd7e37d21d3d8cb3223", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reports/replicate_convergence.jl", "max_forks_repo_name": "mmattocks/BioBackgroundModels.jl", "max_forks_repo_head_hexsha": "f64fd86ccb9ffcb24d6dffd7e37d21d3d8cb3223", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.219858156, "max_line_length": 296, "alphanum_fraction": 0.6381770753, "num_tokens": 1861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23484043695244028}} {"text": "import Base\n\n\"\"\"Base class for a single optimization objective.\n\nAll objectives must have a field `initial_state` and a field `generator`, at\nminimum.\n\"\"\"\nabstract type AbstractControlObjective end\n\n\n\"\"\"Standard optimization objective.\n\n```julia\nObjective(;\n initial_state=,\n generator=,\n target_state=\n)\n```\n\ndescribes an optimization objective where the time evoluation of the given\n`initial_state` under the given `generator` aims towards `target_state`. The\n`generator` here is e.g. a time-dependent Hamiltonian or Liouvillian.\n\nThe most common control problems in quantum control, e.g. state-to-state\ntransitions or quantum gate implementations can be expressed by simultaneously\nfulfilling multiple objectives of this type.\n\nNote that the objective can only be instantiated via keyword arguments.\n\"\"\"\nstruct Objective{ST, GT} <: AbstractControlObjective\n initial_state :: ST\n generator :: GT\n target_state :: ST\n function Objective(;initial_state::ST, generator::GT, target_state::ST) where {ST, GT}\n new{ST, GT}(initial_state, generator, target_state)\n end\nend\n\n\n\"\"\"Standard optimization objective with a weight.\n\n```julia\nWeightedObjective(;\n initial_state=,\n generator=,\n target_state=,\n weight=\n)\n```\n\ninitializes a control objective like [`Objective`](@ref), but with an\nadditional `weight` parameter (a float generally between 0 and 1) that weights\nthe objective relative to other objectives that are part of the same control\nproblem.\n\"\"\"\nstruct WeightedObjective{ST, GT} <: AbstractControlObjective\n initial_state :: ST\n generator :: GT\n target_state :: ST\n weight :: Float64\n function WeightedObjective(;initial_state::ST, generator::GT, target_state::ST, weight::Float64) where {ST, GT}\n new{ST, GT}(initial_state, generator, target_state, weight)\n end\nend\n\n\n\"\"\"A full control problem with multiple objectives.\n\n```julia\nControlProblem(\n objectives=,\n pulse_options=,\n tlist=