licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
9722
function θ(l, lA, lB, PA, PB, r, g) θ = cₖ(l, lA, lB, PA, PB) θ *= factorial(l) * g^(r - l) θ /= factorial(r) * factorial(l - 2 * r) return θ end function gi(l, lp, r, rp, i, lA, lB, Ai, Bi, Pi, gP, lC, lD, Ci, Di, Qi, gQ) δ = 1 / (4 * gP) + 1 / (4 * gQ) gi = (-1.0)^l gi *= θ(l, lA, lB, Pi - Ai, Pi - Bi, r, gP) * θ(lp, lC, lD, Qi - Ci, Qi - Di, rp, gQ) gi *= (-1.0)^i * (2 * δ)^(2 * (r + rp)) gi *= factorial(l + lp - 2 * r - 2 * rp) * δ^i gi *= (Pi - Qi)^(l + lp - 2 * (r + rp + i)) gi /= (4 * δ)^(l + lp) * factorial(i) gi /= factorial(l + lp - 2 * (r + rp + i)) return gi end function Gxyz(lA, mA, nA, lB, mB, nB, lC, mC, nC, lD, mD, nD, a, b, c, d, RA, RB, RC, RD) gP = a + b gQ = c + d δ = 1 / (4 * gP) + 1 / (4 * gQ) RP = gaussianproduct(a, RA, b, RB, gP) RQ = gaussianproduct(c, RC, d, RD, gQ) AB = distance(RA, RB) CD = distance(RC, RD) PQ = distance(RP, RQ) Gxyz = 0.0 for l = 0:(lA+lB) for r = 0:trunc(Int64, l / 2) for lp = 0:(lC+lD) for rp = 0:trunc(Int64, lp / 2) for i = 0:trunc(Int64, (l + lp - 2 * r - 2 * rp) / 2) gx = gi( l, lp, r, rp, i, lA, lB, RA[1], RB[1], RP[1], gP, lC, lD, RC[1], RD[1], RQ[1], gQ, ) for m = 0:(mA+mB) for s = 0:trunc(Int64, m / 2) for mp = 0:(mC+mD) for sp = 0:trunc(Int64, mp / 2) for j = 0:trunc(Int64, (m + mp - 2 * s - 2 * sp) / 2) gy = gi( m, mp, s, sp, j, mA, mB, RA[2], RB[2], RP[2], gP, mC, mD, RC[2], RD[2], RQ[2], gQ, ) for n = 0:(nA+nB) for t = 0:trunc(Int64, n / 2) for np = 0:(nC+nD) for tp = 0:trunc(Int64, np / 2) for k = 0:trunc( Int64, (n + np - 2 * t - 2 * tp) / 2, ) gz = gi( n, np, t, tp, k, nA, nB, RA[3], RB[3], RP[3], gP, nC, nD, RC[3], RD[3], RQ[3], gQ, ) ν = l + lp + m + mp + n + np - 2 * ( r + rp + s + sp + t + tp ) - (i + j + k) F = boys(ν, PQ / (4 * δ)) Gxyz += gx * gy * gz * F end end end end end end end end end end end end end end end Gxyz *= (2 * π^2) / (gP * gQ) Gxyz *= sqrt(π / (gP + gQ)) Gxyz *= exp(-(a * b * AB) / gP) Gxyz *= exp(-(c * d * CD) / gQ) Na = normalization(a, lA, mA, nA) Nb = normalization(b, lB, mB, nB) Nc = normalization(c, lC, mC, nC) Nd = normalization(d, lD, mD, nD) Gxyz *= Na * Nb * Nc * Nd return Gxyz end function repulsion(basis, molecule::Molecule) K = length(basis) G = zeros(K, K, K, K) Ntei = 0 for (A, bA) in enumerate(basis) for (B, bB) in enumerate(basis) for (C, bC) in enumerate(basis) for (D, bD) in enumerate(basis) Ntei += 1 for (a, dA) in zip(bA.α, bA.d) for (b, dB) in zip(bB.α, bB.d) for (c, dC) in zip(bC.α, bC.d) for (d, dD) in zip(bD.α, bD.d) RA = bA.R RB = bB.R RC = bC.R RD = bD.R lA, mA, nA = bA.ℓ, bA.m, bA.n lB, mB, nB = bB.ℓ, bB.m, bB.n lC, mC, nC = bC.ℓ, bC.m, bC.n lD, mD, nD = bD.ℓ, bD.m, bD.n tei = dA * dB * dC * dD tei *= Gxyz( lA, mA, nA, lB, mB, nB, lC, mC, nC, lD, mD, nD, a, b, c, d, RA, RB, RC, RD, ) G[A, B, C, D] += tei end end end end end end end end return G end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
1237
sto3g_α = [ [0.16885540 0.62391373 3.42525091], [0.31364979 1.15892300 6.36242139], [ 0.79465050 2.93620070 16.1195750 0.04808870 0.14786010 0.63628970 ], [ 1.48719270 5.49511530 30.1678710 0.09937070 0.30553890 1.31483310 ], [ 2.40526700 8.88736220 48.7911130 0.16906180 0.51982050 2.23695610 ], [ 3.53051220 13.0450960 71.6168370 0.22228990 0.68348310 2.94124940 ], [ 4.88566020 18.0523120 99.1061690 0.28571440 0.87849660 3.78045590 ], [ 6.44360830 23.8088610 130.709320 0.38038900 1.16959610 5.03315130 ], [ 8.21682070 30.3608120 166.679130 0.48858850 1.50228120 6.46480320 ], [ 10.2052970 37.7081510 207.015610 0.62322930 1.91626620 8.24631510 ], ] sto3g_d = [ 0.44463454 0.53532814 0.15432897 # 1s 0.70011547 0.39951283 0.09996723 # 2s 0.39195739 0.60768372 0.15591627 # 2p 0.91667696 0.21754360 0.22776350 # 3s 0.48464037 0.57776647 0.00495151 # 3p 1.13103444 0.01960641 0.30884412 # 4s 0.54989495 0.57152276 0.12154686 # 4p 0.28657326 0.65554736 0.21976795 ] # 3d
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
8846
@time @testset "attraction.jl" begin methane = molecule("data/methane.xyz") basis = buildbasis(methane) @test isapprox( attraction(basis, methane), [ -33.65274107343551 -8.128483186582468 -4.302248061220742e-21 0.0 -2.3395627422600606e-21 -3.4425727128838974 -3.4423838127848048 -3.442376404838094 -3.4424634522019817 -8.128483186582468 -7.846737221379609 4.219867102568401e-21 0.0 -1.119237077081978e-21 -4.79382406264269 -4.793670170629788 -4.7936641354365905 -4.793735051582429 -4.302248061220742e-21 4.219867102568401e-21 -5.148220575651905 0.0 2.6630060539633543e-42 0.42467567253014044 -1.6326583088487174 -0.7572395638430469 1.9654157862614763 0.0 0.0 0.0 -5.148220575651905 0.0 -1.8707161038007107 -0.5291502469186976 1.7580585175794305 0.6419347128998832 -2.3395627422600606e-21 -1.119237077081978e-21 2.6630060539633543e-42 0.0 -5.148220575651905 1.3347769187166876 -1.5861870562726248 1.3406644617589194 -1.0893213729460038 -3.4425727128838974 -4.79382406264269 0.42467567253014044 -1.870716103800711 1.3347769187166876 -4.615301624567201 -2.6795202055027674 -2.679474986263546 -2.6796317899448994 -3.4423838127848048 -4.79367017062979 -1.632658308848718 -0.5291502469186975 -1.5861870562726248 -2.679520205502768 -4.615179534172651 -2.6794528751610276 -2.6794685962180727 -3.4423764048380936 -4.7936641354365905 -0.7572395638430469 1.7580585175794308 1.3406644617589194 -2.679474986263546 -2.6794528751610276 -4.615174746193909 -2.6795497777543855 -3.4424634522019817 -4.793735051582428 1.965415786261476 0.6419347128998832 -1.0893213729460038 -2.6796317899448994 -2.679468596218072 -2.6795497777543855 -4.6152310072574805;;; -0.9107389698526694 -0.3795871839543028 0.010708951446337912 -0.04717342956362168 0.03365877100769186 -0.1992626319340502 -0.16952044433007313 -0.1695194191663955 -0.16952544011072102 -0.37958718395430274 -0.9032122062813566 0.05863419606223139 -0.25828636275189426 0.18429021630811865 -0.8337147753125443 -0.5495603117904125 -0.5495545381128815 -0.5495760942118206 0.010708951446337916 0.05863419606223139 -0.6384475869485977 0.034151804587261234 -0.02436769555946219 0.14209301980379188 -0.169358869599552 -0.06271002385670235 0.26898441827177416 -0.04717342956362169 -0.2582863627518942 0.034151804587261234 -0.7811349940684297 0.10734083312098289 -0.6259263658804498 -0.1945949930362779 0.08404740559235227 -0.05193199698996576 0.033658771007691865 0.18429021630811865 -0.02436769555946219 0.10734083312098289 -0.7072835934612206 0.4466054813426914 -0.10038899970305869 0.25617424897466046 -0.039854863453873984 -0.19926263193405017 -0.8337147753125443 0.14209301980379188 -0.6259263658804497 0.4466054813426913 -1.2266137219491882 -0.4318888250002644 -0.4318765476042394 -0.43191569787886486 -0.16952044433007313 -0.5495603117904125 -0.16935886959955201 -0.1945949930362779 -0.10038899970305869 -0.4318888250002644 -0.5367469302894173 -0.3033106457503562 -0.30331867982304805 -0.16951941916639557 -0.5495545381128816 -0.06271002385670235 0.08404740559235227 0.25617424897466046 -0.4318765476042393 -0.3033106457503562 -0.5367384931715369 -0.3033261028397706 -0.16952544011072102 -0.5495760942118206 0.2689844182717742 -0.05193199698996575 -0.039854863453873984 -0.43191569787886486 -0.3033186798230481 -0.3033261028397706 -0.5367653976154632;;; -0.9106990014859211 -0.3795707017035383 -0.04116693582330486 -0.013342347347099678 -0.03999517865766886 -0.16952242674506915 -0.19924275184121823 -0.16951345426078793 -0.16951720549577387 -0.37957070170353824 -0.9031910419934925 -0.225414204973128 -0.07305752929075675 -0.21899811631773003 -0.5495643535053908 -0.8336893953594898 -0.5495511215613695 -0.5495552421471761 -0.04116693582330486 -0.22541420497312803 -0.7452693442854489 -0.037138099480749615 -0.11132560748853085 -0.0618381841731841 -0.546271580829469 -0.2058207142440771 0.12586284080675023 -0.013342347347099678 -0.07305752929075675 -0.037138099480749615 -0.642718766662381 -0.03608101730267709 -0.2647062269846173 -0.17704852283783343 0.1773658655497961 0.041393980362606234 -0.03999517865766886 -0.21899811631773003 -0.11132560748853085 -0.03608101730267709 -0.738839064626213 0.05226598036943966 -0.5307227519837265 0.052987827167382796 -0.24304342855010574 -0.16952242674506915 -0.5495643535053907 -0.0618381841731841 -0.2647062269846174 0.05226598036943966 -0.5367469302894173 -0.4318888250002644 -0.30330968752313736 -0.30332647552321096 -0.19924275184121823 -0.8336893953594897 -0.546271580829469 -0.17704852283783346 -0.5307227519837265 -0.4318888250002644 -1.2266137219491882 -0.4318808816900268 -0.4318804369555949 -0.16951345426078795 -0.5495511215613695 -0.2058207142440771 0.17736586554979614 0.052987827167382796 -0.30330968752313736 -0.4318808816900268 -0.5367414715847842 -0.3033196047920976 -0.16951720549577387 -0.5495552421471761 0.12586284080675023 0.041393980362606234 -0.24304342855010577 -0.303326475523211 -0.4318804369555949 -0.3033196047920975 -0.5367411659601181;;; -0.9106974341057493 -0.37957005534205596 -0.01909348092168746 0.044328714936995174 0.0338042972729354 -0.16952147935209944 -0.16951353200811492 -0.19924197224248894 -0.1695182913895787 -0.3795700553420559 -0.9031902119957118 -0.1045487815638409 0.24272751280723975 0.1850997262365567 -0.5495587383633193 -0.5495512800692732 -0.8336884000295924 -0.5495652479601771 -0.01909348092168746 -0.1045487815638409 -0.6553313996768082 0.05722843559391346 0.04364139705000036 -0.0009403389367754497 -0.2515723624579084 -0.25336494142881977 0.18676052883914027 0.044328714936995174 0.24272751280723975 0.05722843559391346 -0.7635470894273965 -0.10132081505810173 -0.10560024362690602 0.05783024645338575 0.5882291610258157 0.20050290742444832 0.0338042972729354 0.1850997262365567 0.04364139705000036 -0.10132081505810173 -0.7079471570314896 0.2558649180855194 -0.09997718317327248 0.44857319803175755 -0.03944410197497965 -0.16952147935209944 -0.5495587383633191 -0.0009403389367754519 -0.10560024362690602 0.2558649180855195 -0.5367384931715369 -0.30331240193726666 -0.4318765476042393 -0.30332876991772734 -0.16951353200811495 -0.5495512800692733 -0.2515723624579084 0.05783024645338576 -0.09997718317327245 -0.3033124019372667 -0.5367414715847842 -0.4318808816900268 -0.30331447615278273 -0.19924197224248894 -0.8336884000295924 -0.25336494142881977 0.5882291610258157 0.4485731980317575 -0.4318765476042394 -0.4318808816900268 -1.2266137219491882 -0.4319036342283779 -0.16951829138957872 -0.5495652479601772 0.18676052883914024 0.2005029074244483 -0.03944410197497964 -0.30332876991772734 -0.30331447615278273 -0.43190363422837796 -0.5367571073331551;;; -0.9107158517997539 -0.3795776504852406 0.04955905250252896 0.016186740923820338 -0.027467844458829306 -0.16952658669590845 -0.16951636968852066 -0.16951737785504375 -0.19925113305827521 -0.3795776504852406 -0.9031999648473785 0.27135862361672736 0.08862985703175622 -0.1503990913806498 -0.5495784318852318 -0.5495535381321905 -0.549563385460914 -0.8337000955764959 0.04955905250252896 0.2713586236167274 -0.7967438234046095 -0.054236535892840554 0.0920358668184978 0.18846338657623457 -0.06218103647883193 0.04447021739016323 0.6576103070669037 0.016186740923820338 0.08862985703175622 -0.054236535892840554 -0.6484019384033824 0.030060315051709995 -0.18324457047127696 -0.01980969322988889 0.2588341023478038 0.21478553628083843 -0.02746784445882931 -0.15039909138064983 0.0920358668184978 0.030060315051709995 -0.6816978558186101 0.0868302239931666 -0.26901148111261713 0.0875511940865913 -0.3644770575086145 -0.16952658669590848 -0.5495784318852318 0.1884633865762346 -0.18324457047127696 0.0868302239931666 -0.5367653976154632 -0.3033205343198842 -0.3033201143467384 -0.43191569787886486 -0.16951636968852063 -0.5495535381321905 -0.062181036478831934 -0.01980969322988889 -0.26901148111261713 -0.30332053431988426 -0.5367411659601181 -0.3033145744789922 -0.43188043695559486 -0.16951737785504375 -0.549563385460914 0.044470217390163234 0.2588341023478038 0.08755119408659132 -0.30332011434673845 -0.30331457447899224 -0.5367571073331551 -0.43190363422837796 -0.19925113305827524 -0.8337000955764958 0.6576103070669038 0.2147855362808384 -0.36447705750861453 -0.43191569787886486 -0.4318804369555949 -0.4319036342283779 -1.2266137219491882 ], atol = 1e-4, ) end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
333
@time @testset "basis.jl" begin methane = molecule("data/methane.xyz") sto3gBasis = buildbasis(methane) @test sto3gBasis[1].R == [0.00001021434087, 0.00001532972083, -0.00001493500137] @test sto3gBasis[1].α == [3.53051220, 13.0450960, 71.6168370] @test sto3gBasis[1].d == [0.44463454, 0.53532814, 0.15432897] end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
247
@time @testset "auxiliary.jl" begin @test doublefactorial(1) == 1 @test doublefactorial(2) == 2 @test doublefactorial(3) == 3 @test doublefactorial(4) == 8 @test doublefactorial(5) == 15 @test doublefactorial(9) == 945 end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
1818
@time @testset "kinetic.jl" begin methane = molecule("data/methane.xyz") basis = buildbasis(methane) @test isapprox( kinetic(basis, methane), [ 15.891121686559655 0.9286241920313923 1.367784730397128e-21 0.0 2.395388571832957e-21 0.09394295851111978 0.0939291959311415 0.09392865624610672 0.09393499798489882 0.9286241920313925 0.71960967113485 -9.459524706040978e-22 0.0 7.578163395828373e-22 0.375944046589143 0.3759257153692945 0.3759249964765981 0.3759334437974228 -1.5028089507498071e-21 -2.9264920152842656e-22 1.4777280379047113 0.0 7.118883883942926e-43 -0.1043967714076755 0.4013444534028426 0.18614653493348993 -0.48314741266422623 0.0 0.0 0.0 1.4777280379047113 0.0 0.4598726371435354 0.130077135838251 -0.43217036837968165 -0.15780329933488668 -5.116781801072144e-21 -3.952986845522944e-23 7.118883883942926e-43 0.0 1.4777280379047113 -0.3281242837229337 0.38992076519875674 -0.32956551134010936 0.26778191494015297 0.09394295851111983 0.3759440465891428 -0.10439677140767545 0.4598726371435353 -0.32812428372293356 0.7600318766425666 0.13139233630351171 0.13138510105941034 0.13140817322560117 0.09392919593114145 0.37592571536929414 0.4013444534028424 0.13007713583825095 0.3899207651987568 0.13139233630351171 0.7600318766425666 0.13138765518627363 0.13138739309855152 0.09392865624610672 0.37592499647659794 0.1861465349334899 -0.4321703683796816 -0.32956551134010936 0.13138510105941031 0.13138765518627366 0.7600318766425666 0.13140106372667984 0.09393499798489874 0.3759334437974225 -0.48314741266422606 -0.1578032993348867 0.26778191494015285 0.1314081732256011 0.1313873930985515 0.13140106372667987 0.7600318766425666 ], atol = 1e-4, ) end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
518
@time @testset "molecule.jl" begin methane = molecule("data/methane.xyz") @test methane.atoms == ["C", "H", "H", "H", "H"] @test methane.coords == [ 0.00001021434087 0.00001532972083 -0.00001493500137 -0.19951695340554 0.87894179053067 -0.62713882127936 0.76712229809243 0.24863902907755 0.74526241504934 0.35580334399536 -0.82601803138729 -0.62993342769733 -0.92343260142312 -0.30159515034176 0.51179839372872 ] @test methane.numbers == [6, 1, 1, 1, 1] end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
104
@time @testset "auxiliary.jl" begin @test normalization(0.28294, 0, 0, 0) == 0.2764909076098983 end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
1806
@time @testset "overlap.jl" begin methane = molecule("data/methane.xyz") basis = buildbasis(methane) @test isapprox( overlap(basis, methane), [ 0.999999999881269 0.417217495549548 4.755302191269753e-22 0.0 -2.245487389655587e-23 0.19385525790537905 0.19384502244263016 0.19384462104479344 0.19384933767728355 0.417217495549548 1.2128613399525237 -1.3349160118206168e-21 0.0 1.1349281180613959e-22 0.8591634048050029 0.8591462825287147 0.8591456110342427 0.8591535013433647 4.755302191269753e-22 -1.334916011820617e-21 0.9999999729969503 0.0 -4.146488823526061e-43 -0.09395364954355068 0.3612081113887419 0.16753120813212868 -0.43482462947800954 0.0 0.0 0.0 0.9999999729969503 0.0 0.4138701992624604 0.11706880753583301 -0.388951768344355 -0.142020342787981 -2.245487389655577e-23 1.1349281180613963e-22 -4.146488823526061e-43 0.0 0.9999999729969503 -0.29530102841251776 0.35092684599113616 -0.29660776813932477 0.2409992662543452 0.19385525790537908 0.859163404805003 -0.09395364954355068 0.4138701992624603 -0.2953010284125178 0.9999999908897999 0.5270998376751642 0.5270892307634182 0.5271230537189303 0.19384502244263013 0.8591462825287147 0.36120811138874187 0.11706880753583301 0.35092684599113616 0.5270998376751642 0.9999999908897999 0.5270929751609674 0.5270925909370973 0.1938446210447935 0.8591456110342426 0.1675312081321287 -0.3889517683443551 -0.29660776813932477 0.5270892307634182 0.5270929751609674 0.9999999908897999 0.5271126317567845 0.19384933767728357 0.8591535013433647 -0.4348246294780095 -0.14202034278798098 0.2409992662543452 0.5271230537189303 0.5270925909370973 0.5271126317567845 0.9999999908897999 ], atol = 1e-4, ) end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
626
@time @testset "repulsion.jl" begin hydrogen = molecule("data/h2.xyz") basis = buildbasis(hydrogen) @test isapprox( repulsion(basis, hydrogen), [ 0.7746059298062673 0.6482052325853882 0.6482052325853882 0.6994796252934075;;; 0.6482052325853882 0.5707519808185033 0.5707519808185033 0.6482052325853881;;;; 0.6482052325853882 0.5707519808185033 0.5707519808185033 0.6482052325853881;;; 0.6994796252934075 0.6482052325853882 0.6482052325853883 0.7746059298062673 ], atol = 1e-4, ) end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
code
298
using OohataHuzinaga using Test @testset "OohataHuzinaga.jl" begin include("molecule.jl") include("basis.jl") include("doublefactorial.jl") include("normalization.jl") include("overlap.jl") include("kinetic.jl") include("attraction.jl") include("repulsion.jl") end
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
docs
2025
# OohataHuzinaga.jl [![Issues](https://img.shields.io/github/issues-raw/Leticia-maria/Foca.jl?style=for-the-badge)](https://github.com/Leticia-maria/OohataHuzinaga.jl/) [![Build Status](https://img.shields.io/github/workflow/status/Leticia-maria/Foca.jl/CI?style=for-the-badge)](https://github.com/Leticia-maria/OohataHuzinaga.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Commit Activity](https://img.shields.io/github/commit-activity/w/Leticia-maria/Foca.jl/main?style=for-the-badge)](https://github.com/Leticia-maria/OohataHuzinaga.jl/) [![DOI](https://zenodo.org/badge/419452183.svg)](https://zenodo.org/badge/latestdoi/419452183) ![HartreeFoca jl](https://user-images.githubusercontent.com/60739184/170071106-68ba0e42-08a5-4923-b69a-d5db945bdf7b.svg) ## Overview ## Installation To install the package, you will call the Julia Package Manager on your REPL: ```julia ]add OohataHuzinaga ``` Done! Now it is *ready to use* ## Package Features - *Calculates overlap integrals* - *Calculate kinetic integrals* - *Calculate electron-nuclear attraction integrals* - *Calculate electron-electron repulsion integrals* ## Quick Example Consider that you want to calculate the electronic energy of a methane molecule. First, you will need the cartesian coordinates of the molecule of interest. This information is stored in our ```methane.xyz``` file, formatted as follows: ```julia 5 C 0.00001021434087 0.00001532972083 -0.00001493500137 H -0.19951695340554 0.87894179053067 -0.62713882127936 H 0.76712229809243 0.24863902907755 0.74526241504934 H 0.35580334399536 -0.82601803138729 -0.62993342769733 H -0.92343260142312 -0.30159515034176 0.51179839372872 ``` ```julia methane = molecule("methane.xyz") ``` For any molecular calculations, you will need a basis set. ```julia sto3g = buildbasis(methane) ``` With this information, we can build the molecular integrals. ```julia S = overlap(sto3g, methane) T = kinetic(sto3g, methane) V = attraction(sto3g, methane) G = repulsion(sto3g, methane) ```
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
docs
95
## Gaussian Basis Sets ```@docs GaussianBasis ``` ```@docs buildbasis(molecule::Molecule) ```
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
docs
1324
# OohataHuzinaga.jl: An application for Computational Chemists ## Overview ## Installation To install the package, you will call the Julia Package Manager on your REPL: ```julia ]add OohataHuzinaga ``` Done! Now it is *ready to use* ## Package Features - *Calculates overlap integrals* - *Calculate kinetic integrals* - *Calculate electron-nuclear attraction integrals* - *Calculate electron-electron repulsion integrals* ## Quick Example Consider that you want to calculate the electronic energy of a methane molecule. First, you will need the cartesian coordinates of the molecule of interest. This information is stored in our ```methane.xyz``` file, formatted as follows: ```julia 5 C 0.00001021434087 0.00001532972083 -0.00001493500137 H -0.19951695340554 0.87894179053067 -0.62713882127936 H 0.76712229809243 0.24863902907755 0.74526241504934 H 0.35580334399536 -0.82601803138729 -0.62993342769733 H -0.92343260142312 -0.30159515034176 0.51179839372872 ``` ```julia methane = molecule("methane.xyz") ``` For any molecular calculations, you will need a basis set. ```julia sto3g = buildbasis(methane) ``` With this information, we can build the molecular integrals. ```julia S = overlap(sto3g, methane) T = kinetic(sto3g, methane) V = attraction(sto3g, methane) G = repulsion(sto3g, methane) ```
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.1.1
d192a27769e653b00dfa3d7e49dba341aea8dc50
docs
82
## The input system ```@docs Molecule ``` ```@docs molecule(xyzfile::String) ```
OohataHuzinaga
https://github.com/HartreeFoca/OohataHuzinaga.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
5132
### A Pluto.jl notebook ### # v0.19.36 #> [frontmatter] #> title = "Home" using Markdown using InteractiveUtils # ╔═╡ 8a70f0c0-c70e-4022-8a06-ea8fec31a7c7 # ╠═╡ show_logs = false begin using Pkg Pkg.activate(joinpath(pwd(), "docs")) Pkg.instantiate() using HTMLStrings: to_html, head, link, script, divv, h1, img, p, span, a, figure, hr using PlutoUI end # ╔═╡ 5e70dc3d-85b6-4149-9962-70215d3c7f1e md""" ## Tutorials """ # ╔═╡ 8b5d431a-f91c-422b-86cf-3ace891e742f md""" ## Python Usage """ # ╔═╡ b3349485-1a5f-4da6-be79-965fec5fbc13 md""" ## API """ # ╔═╡ d0ec67d4-26bd-4960-b4d9-75d9c0b740b0 to_html(hr()) # ╔═╡ 4195fc74-92a0-4ad4-8c36-9d652ac36fd5 TableOfContents() # ╔═╡ febd9959-70d6-409d-b216-762ec0b751dc data_theme = "cupcake"; # ╔═╡ 0af240e8-ccf7-4bf8-b21c-08e2972d2459 function index_title_card(title::String, subtitle::String, image_url::String; data_theme::String = "pastel", border_color::String = "primary") return to_html( divv( head( link(:href => "https://cdn.jsdelivr.net/npm/[email protected]/dist/full.css", :rel => "stylesheet", :type => "text/css"), script(:src => "https://cdn.tailwindcss.com") ), divv(:data_theme => "$data_theme", :class => "card card-bordered flex justify-center items-center border-$border_color text-center w-full dark:text-[#e6e6e6]", divv(:class => "card-body flex flex-col justify-center items-center", img(:src => "$image_url", :class => "h-24 w-24 md:h-52 md:w-52 rounded-md", :alt => "$title Logo"), divv(:class => "text-5xl font-bold bg-gradient-to-r from-accent to-primary inline-block text-transparent bg-clip-text py-10", "$title"), p(:class => "card-text text-md font-serif", "$subtitle" ) ) ) ) ) end; # ╔═╡ 18be66cd-28c4-4137-b16b-428430b7f996 index_title_card( "DistanceTransforms.jl", "Fast Distance Transforms in Julia", "https://img.freepik.com/free-vector/global-communication-background-business-network-vector-design_53876-151122.jpg"; data_theme = data_theme ) # ╔═╡ 09b3d1e1-b44f-461d-abaf-2e5a1f6f6cc2 struct Article title::String path::String image_url::String end # ╔═╡ 0d222d9d-7576-40a7-acb4-b0e27f9a9ef8 article_list_tutorials = Article[ Article("Getting Started", "docs/01_getting_started.jl", "https://img.freepik.com/free-photo/futuristic-spaceship-takes-off-into-purple-galaxy-fueled-by-innovation-generated-by-ai_24640-100023.jpg"), Article("Advanced Usage", "docs/02_advanced_usage.jl", "https://images.pexels.com/photos/3091200/pexels-photo-3091200.jpeg?auto=compress&cs=tinysrgb&w=800") ]; # ╔═╡ e0ef1b4d-0076-410c-b325-32a7a274f487 article_list_python = Article[ Article("Python", "https://colab.research.google.com/drive/1moYjSiGEA4GoYD_8BeSw69fBPv2MtROZ?authuser=2", "https://img.freepik.com/free-vector/code-typing-concept-illustration_114360-3581.jpg?size=626&ext=jpg&ga=GA1.1.1694943658.1700350224&semt=sph"), ]; # ╔═╡ 8d11bae1-d232-4c03-981a-cd9f1db24e6b article_list_api = Article[ Article("API", "docs/99_api.jl", "https://img.freepik.com/free-photo/modern-technology-workshop-creativity-innovation-communication-development-generated-by-ai_188544-24548.jpg"), ]; # ╔═╡ 3bcd40f0-e8dd-48bd-8249-51b89f5766de function article_card(article::Article, color::String; data_theme = "pastel") a(:href => article.path, :class => "w-1/2 p-2", divv(:data_theme => "$data_theme", :class => "card card-bordered border-$color text-center dark:text-[#e6e6e6]", divv(:class => "card-body justify-center items-center", p(:class => "card-title", article.title), p("Click to open the notebook") ), figure( img(:class =>"w-full h-40", :src => article.image_url, :alt => article.title) ) ) ) end; # ╔═╡ ace65d98-fe6b-45b7-990d-df8f59f6a5b3 to_html( divv(:class => "flex flex-wrap justify-center items-start", [article_card(article, "secondary"; data_theme = data_theme) for article in article_list_tutorials]... ) ) # ╔═╡ 75f02433-7ef3-45f4-ad2a-d610923824af to_html( divv(:class => "flex flex-wrap justify-center items-start", [article_card(article, "secondary"; data_theme = data_theme) for article in article_list_python]... ) ) # ╔═╡ 0c5f21fe-80fc-4810-b4a8-bb1c290c5d81 to_html( divv(:class => "flex flex-wrap justify-center items-start", [article_card(article, "secondary"; data_theme = data_theme) for article in article_list_api]... ) ) # ╔═╡ Cell order: # ╟─18be66cd-28c4-4137-b16b-428430b7f996 # ╟─5e70dc3d-85b6-4149-9962-70215d3c7f1e # ╟─ace65d98-fe6b-45b7-990d-df8f59f6a5b3 # ╟─8b5d431a-f91c-422b-86cf-3ace891e742f # ╟─75f02433-7ef3-45f4-ad2a-d610923824af # ╟─b3349485-1a5f-4da6-be79-965fec5fbc13 # ╟─0c5f21fe-80fc-4810-b4a8-bb1c290c5d81 # ╟─d0ec67d4-26bd-4960-b4d9-75d9c0b740b0 # ╟─4195fc74-92a0-4ad4-8c36-9d652ac36fd5 # ╟─febd9959-70d6-409d-b216-762ec0b751dc # ╟─8a70f0c0-c70e-4022-8a06-ea8fec31a7c7 # ╟─0af240e8-ccf7-4bf8-b21c-08e2972d2459 # ╟─09b3d1e1-b44f-461d-abaf-2e5a1f6f6cc2 # ╟─0d222d9d-7576-40a7-acb4-b0e27f9a9ef8 # ╟─e0ef1b4d-0076-410c-b325-32a7a274f487 # ╟─8d11bae1-d232-4c03-981a-cd9f1db24e6b # ╟─3bcd40f0-e8dd-48bd-8249-51b89f5766de
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
8213
### A Pluto.jl notebook ### # v0.19.36 #> [frontmatter] #> title = "Getting Started" #> category = "Quick Start" using Markdown using InteractiveUtils # ╔═╡ 26b9d680-1004-4440-a392-16c178230066 # ╠═╡ show_logs = false using Pkg; Pkg.activate("."); Pkg.instantiate() # ╔═╡ 7cfeb5d8-ceb6-499f-982f-e91fa89a2a3c using PlutoUI: TableOfContents # ╔═╡ 1a062240-c8a9-4187-b02c-9d1ffdeddf83 using CairoMakie: Figure, Axis, heatmap, heatmap!, hidedecorations! # ╔═╡ 0ebe93c9-8278-40e7-b51a-6ea8f37431a8 using Images: Gray, load # ╔═╡ 73978188-b49d-455c-986c-bb149236745d using ImageMorphology: distance_transform, feature_transform # ╔═╡ 59fcb1fc-c439-4027-b443-2ddae5a577fd using DistanceTransforms: boolean_indicator, transform # ╔═╡ 86243827-7f59-4230-bd3d-3d3edb6b2958 md""" # DistanceTransforms.jl ## Why This Library? | | DistanceTransforms.jl | [ImageMorphology.jl](https://github.com/JuliaImages/ImageMorphology.jl/blob/master/src/feature_transform.jl) | [SciPy](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.distance_transform_edt.html) | |-----------------------|:---------------------:|:---------------:|:---------------:| | Fast Distance Transform | ✅✅ | ✅ | ✅ | | CPU Single-Threaded Support | ✅ | ✅ | ✅ | | CPU Multi-Threaded Support | ✅ | ✅ | ❌ | | NVIDIA/CUDA Support | ✅ | ❌ | ❌ | | AMD/ROCM Support | ✅ | ❌ | ❌ | | Apple/Metal Support | ✅ | ❌ | ❌ | | Comprehensive Documentation | ✅✅ | ❌ | ✅ | ## Set up To get started, we first need to set up our Julia environment. This includes activating the current project environment, ensuring all necessary packages are installed and up-to-date. We will then load the essential libraries required for this exploration. These libraries not only include DistanceTransforms.jl but also additional packages for visualization, benchmarking, and handling GPU functionality. For local use, install the necessary packages as follows: ```julia begin using Pkg; Pkg.activate(temp = true) Pkg.add(["PlutoUI", "CairoMakie", "Images", "ImageMorphology"]) Pkg.add(url = "https://github.com/Dale-Black/DistanceTransforms.jl") end ``` """ # ╔═╡ c579c92a-3d1c-4213-82c5-cca54b5c0144 TableOfContents() # ╔═╡ 903bf2fa-de7b-420f-a6ff-381ea6312287 md""" # Introduction Distance transforms play a crucial role in many computer vision tasks. This section will demonstrate how DistanceTransforms.jl facilitates efficient distance transform operations on arrays in Julia. ## Basic Usage The primary function in DistanceTransforms.jl is `transform`. This function processes an array of 0s and 1s, converting each background element (0) into a value representing its squared Euclidean distance to the nearest foreground element (1). ## Example Let's begin with a basic example: """ # ╔═╡ 862747e5-e88f-47ab-bc97-f5a456738b22 arr = rand([0f0, 1f0], 10, 10) # ╔═╡ b9ba3bde-8779-4f3c-a3fb-ef157e121632 transform(boolean_indicator(arr)) # ╔═╡ 73cfc148-5af4-4ad7-a8ff-7520c891564b md""" ## Visualization Visualization aids in understanding the effects of the distance transform. We use Makie.jl for this purpose: """ # ╔═╡ d3498bb0-6f8f-470a-b1de-b1760229cc1c heatmap(arr, colormap=:grays) # ╔═╡ ec3a90f1-f2d7-4d5a-8785-476073ee0079 heatmap(transform(boolean_indicator(arr)); colormap=:grays) # ╔═╡ cd89f08c-44b4-43f6-9313-b4737725b39a md""" # Intermediate Usage We load an example image from the Images.jl library to demonstrate a distance transform applied to a real-world scenario. """ # ╔═╡ 158ef85a-28ef-4756-8120-53450f2ef7cd img = load(Base.download("http://docs.opencv.org/3.1.0/water_coins.jpg")); # ╔═╡ cf258b9d-e6bf-4128-b669-c8a5b91ecdef img_bw = Gray.(img) .> 0.5; # theshold image # ╔═╡ 361835a4-eda2-4eed-a249-4c6cce212662 img_tfm = transform(boolean_indicator(img_bw)); # ╔═╡ 6dbbdb71-5d86-4613-8900-95da2f40143e md""" ## Visualization """ # ╔═╡ 80cbd0a5-5be1-4e7b-b54e-007f4ad0fb7d let f = Figure(size = (700, 600)) ax = Axis( f[1:2, 1], title = "Original Image", ) heatmap!(rotr90(img); colormap = :grays) hidedecorations!(ax) ax = Axis( f[3:4, 1], title = "Segmented Image", ) heatmap!(rotr90(img_bw); colormap = :grays) hidedecorations!(ax) ax = Axis( f[2:3, 2], title = "Distance Transformed Image", ) heatmap!(rotr90(img_tfm); colormap = :grays) hidedecorations!(ax) f end # ╔═╡ 24ff9beb-81c0-4c5c-865e-4446aa4df435 md""" # Helpful Information ## About the Algorithm DistanceTransforms.jl implements sophisticated algorithms for both CPU and GPU environments, ensuring efficient computation regardless of the platform. **CPU**: On the CPU, DistanceTransforms.jl employs the squared Euclidean distance transform algorithm, a method well-documented and respected in computational geometry. This approach, detailed by [Felzenszwalb and Huttenlocher](https://theoryofcomputing.org/articles/v008a019/), is known for its accuracy and efficiency in distance calculations. **GPU**: For GPU computations, DistanceTransforms.jl uses a custom algorithm, optimized for performance across various GPU architectures. This is facilitated by KernelAbstractions.jl, a Julia package designed for writing hardware-agnostic Julia code. This ensures that DistanceTransforms.jl can leverage the power of GPUs from different vendors, including NVIDIA (CUDA), AMD (ROCM), and Apple (Metal). **Simplified Interface via Multiple Dispatch**: One of the key features of DistanceTransforms.jl is its simplicity for the end user. Thanks to Julia's multiple dispatch system, the complexity of choosing between CPU and GPU algorithms is abstracted away. Users need only call `transform(boolean_indicator(...))`, and the library intelligently dispatches the appropriate method based on the input's characteristics. This simplification means users can focus on their tasks without worrying about the underlying computational details. ## Note on Euclidean Distance The library, by default, returns the squared Euclidean distance, as it is often sufficient for many applications and more computationally efficient. However, for cases where the true Euclidean distance is needed, users can easily obtain it by taking the square root of each element in the transformed array. This flexibility allows for a balance between computational efficiency and the specific needs of the application. """ # ╔═╡ 77de39d7-5d30-410f-baa5-460ae2d8a4a3 array2 = [ 0 1 1 0 1 0 0 0 1 0 1 1 0 0 0 ] # ╔═╡ 7c557d32-2bb8-47a2-8216-e18755d258c7 array2_bool = boolean_indicator(array2) # ╔═╡ d6b06775-2ded-4e15-9616-f3e4653d1396 sq_euc_transform = transform(array2_bool) # ╔═╡ 7597fa37-b406-4fca-8eaa-1627b1eb835d euc_transform = sqrt.(sq_euc_transform) # ╔═╡ 239e0053-a16e-4651-b9a0-e163e1bc3892 md""" ## Comparative Example We will now compare the functionality of DistanceTransforms.jl with ImageMorphology.jl: """ # ╔═╡ e49f34f6-2b22-42c4-9c16-e94f8ee2030a euc_transform2 = distance_transform(feature_transform(Bool.(array2))) # ╔═╡ 26f4ca31-2e74-4231-9f94-c8bbbbd2fce7 isapprox(euc_transform2, euc_transform; rtol = 1e-2) # ╔═╡ Cell order: # ╟─86243827-7f59-4230-bd3d-3d3edb6b2958 # ╠═26b9d680-1004-4440-a392-16c178230066 # ╠═7cfeb5d8-ceb6-499f-982f-e91fa89a2a3c # ╠═1a062240-c8a9-4187-b02c-9d1ffdeddf83 # ╠═0ebe93c9-8278-40e7-b51a-6ea8f37431a8 # ╠═73978188-b49d-455c-986c-bb149236745d # ╠═59fcb1fc-c439-4027-b443-2ddae5a577fd # ╠═c579c92a-3d1c-4213-82c5-cca54b5c0144 # ╟─903bf2fa-de7b-420f-a6ff-381ea6312287 # ╠═862747e5-e88f-47ab-bc97-f5a456738b22 # ╠═b9ba3bde-8779-4f3c-a3fb-ef157e121632 # ╟─73cfc148-5af4-4ad7-a8ff-7520c891564b # ╟─d3498bb0-6f8f-470a-b1de-b1760229cc1c # ╟─ec3a90f1-f2d7-4d5a-8785-476073ee0079 # ╟─cd89f08c-44b4-43f6-9313-b4737725b39a # ╠═158ef85a-28ef-4756-8120-53450f2ef7cd # ╠═cf258b9d-e6bf-4128-b669-c8a5b91ecdef # ╠═361835a4-eda2-4eed-a249-4c6cce212662 # ╟─6dbbdb71-5d86-4613-8900-95da2f40143e # ╟─80cbd0a5-5be1-4e7b-b54e-007f4ad0fb7d # ╟─24ff9beb-81c0-4c5c-865e-4446aa4df435 # ╠═77de39d7-5d30-410f-baa5-460ae2d8a4a3 # ╠═7c557d32-2bb8-47a2-8216-e18755d258c7 # ╠═d6b06775-2ded-4e15-9616-f3e4653d1396 # ╠═7597fa37-b406-4fca-8eaa-1627b1eb835d # ╟─239e0053-a16e-4651-b9a0-e163e1bc3892 # ╠═e49f34f6-2b22-42c4-9c16-e94f8ee2030a # ╠═26f4ca31-2e74-4231-9f94-c8bbbbd2fce7
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
11501
### A Pluto.jl notebook ### # v0.19.36 #> [frontmatter] #> title = "Advanced Usage" using Markdown using InteractiveUtils # ╔═╡ e7b64851-7108-4c14-9710-c991d5b7021a # ╠═╡ show_logs = false using Pkg; Pkg.activate("."); Pkg.instantiate() # ╔═╡ a3966df9-1107-4f2b-9fb0-704ad7dbe26a using PlutoUI: TableOfContents # ╔═╡ ab982cb6-d37c-4d27-a695-d3d8378ab32b using DistanceTransforms: transform, boolean_indicator # ╔═╡ c79a8a06-262c-4733-aa31-a0e9a896fafb using CairoMakie: Figure, Axis, Label, Legend, scatterlines! # ╔═╡ 1a7c3ed0-7453-4f53-ac5a-99d0b3f84a85 # ╠═╡ show_logs = false using DistanceTransformsPy: pytransform # ╔═╡ fe295739-2a9f-46a5-92b9-19e5b5b5dc50 using ImageMorphology: distance_transform, feature_transform # ╔═╡ b4125c21-43cf-42a5-b685-bc47b8b1f8b8 using BenchmarkTools # ╔═╡ 53545152-a6ca-4f13-8275-95a8a04017c0 using KernelAbstractions # ╔═╡ 197c25db-3cc1-4b65-bf49-f0f27694bcc3 # ╠═╡ show_logs = false using CUDA, AMDGPU, Metal # ╔═╡ c80da3e8-ff14-4f8c-9a67-b1601395ff40 using FileIO: save, load # ╔═╡ 481bdd21-744e-424e-992b-b3e19c4c06f7 using ImageShow # ╔═╡ dec905ec-5ca9-4ef9-b0a6-2a8d31f3f5c7 md""" # Introduction Welcome to this advanced exploration of the DistanceTransforms.jl library. In this notebook, we delve into the sophisticated capabilities of DistanceTransforms.jl, focusing on its multi-threading and GPU acceleration features. These advanced functionalities are crucial for enhancing performance in complex Julia applications, particularly in the fields of image processing and computer vision. We will benchmark these features to demonstrate the significant performance gains they offer. This guide is tailored for users who are already acquainted with the basic aspects of DistanceTransforms.jl and are looking to exploit its full potential in demanding computational tasks. ## Setup To get started, we first need to set up our Julia environment. This includes activating the current project environment, ensuring all necessary packages are installed and up-to-date. We will then load the essential libraries required for this exploration. These libraries not only include DistanceTransforms.jl but also additional packages for visualization, benchmarking, and handling GPU functionality. With our environment ready, we can now proceed to explore the advanced features of DistanceTransforms.jl. """ # ╔═╡ 0e6b49a2-7590-4800-871e-6a2b0019a9f3 TableOfContents() # ╔═╡ 9dd1c30d-3472-492f-a06c-84777f1aabf4 md""" # Multi-threading DistanceTransforms.jl efficiently utilizes multi-threading, particularly in its Felzenszwalb distance transform algorithm. This parallelization significantly enhances performance, especially for large data sets and high-resolution images. ## Multi-threading Benefits With Julia's multi-threading support, the library can concurrently process distance transform operations, automatically optimizing performance based on the system's capabilities. This leads to faster execution times and increased efficiency in computations, reducing the complexity for the users. ## Practical Advantages This feature is highly beneficial in scenarios requiring rapid processing, such as real-time computer vision applications and large-scale image analysis. It allows users to focus more on application development rather than on managing computational workloads. Next, we will examine benchmarks demonstrating these performance improvements in various use cases. """ # ╔═╡ 9ff0aadf-80b1-4cfd-b3a1-33fbcbc3fb1a x = boolean_indicator(rand([0f0, 1f0], 100, 100)); # ╔═╡ a6a3ce15-251c-4edf-8a85-d80cec6f4b3f single_threaded = @benchmark transform($x; threaded = false) # ╔═╡ a0785853-9091-4fb8-a23c-536032edee74 multi_threaded = @benchmark transform($x; threaded = true) # ╔═╡ b8daf192-a46e-4b49-b09b-04f793c3b8cc md""" # GPU Acceleration DistanceTransforms.jl extends its performance capabilities by embracing GPU acceleration. This section explores how GPU support is integrated into the library, offering substantial performance enhancements, particularly for large-scale computations. One of the features of DistanceTransforms.jl is its GPU compatibility, achieved through Julia's multiple dispatch. This means that the same `transform` function used for CPU computations automatically adapts to leverage GPU resources when available. Multiple dispatch in Julia allows the `transform` function to intelligently determine the computing resource to utilize, based on the input array's type. When a GPU-compatible array type (like `CUDA.CuArray`) is passed, DistanceTransforms.jl automatically dispatches a GPU-optimized version of the algorithm. ## GPU Execution Example Below is an illustrative example of how GPU acceleration can be employed in DistanceTransforms.jl: ```julia x_gpu = CUDA.CuArray(boolean_indicator(rand([0, 1], 100, 100))) # The `transform` function recognizes the GPU array and uses GPU for computations gpu_transformed = transform(x_gpu) ``` In this example, the `transform` function identifies `x_gpu` as a GPU array and thus, invokes the GPU-accelerated version of the distance transform algorithm. ## Advantages of GPU The use of GPU acceleration in DistanceTransforms.jl is particularly advantageous for handling large data sets where the parallel computing capabilities of GPUs can be fully utilized. This results in significantly reduced computation times and increased efficiency, making DistanceTransforms.jl a suitable choice for high-performance computing tasks. In the following sections, we'll delve into benchmark comparisons to demonstrate the efficacy of GPU acceleration in DistanceTransforms.jl. """ # ╔═╡ 1f1867f0-05a4-4071-8f7d-9e238a8c940f md""" # Benchmarks """ # ╔═╡ 595dbaea-a238-44e5-b22a-57c423c1f6ac if CUDA.functional() @info "Using CUDA" CUDA.versioninfo() backend = CUDABackend() dev = CuArray elseif AMDGPU.functional() @info "Using AMD" AMDGPU.versioninfo() backend = ROCBackend() dev = ROCArray elseif Metal.functional() @info "Using Metal" Metal.versioninfo() backend = MetalBackend() dev = MtlArray else @info "No GPU is available. Using CPU." backend = CPU() dev = Array end # ╔═╡ be5b4e09-2a6d-472d-9790-623ae3e99bb8 Threads.nthreads() # ╔═╡ c1e55d37-d0c9-4da2-8841-89a714e50c21 begin range_size_2D = range(4, 1000, 4) range_size_3D = range(4, 100, 4) end # ╔═╡ 90142aaa-8a1f-4221-aadf-ad858b05f716 md""" ## 2D """ # ╔═╡ f0ca70f4-ab9b-48ae-b701-cf4ac47b7bf4 # ╠═╡ disabled = true #=╠═╡ begin sizes = Float64[] dt_scipy = Float64[] dt_scipy_std = Float64[] dt_maurer = Float64[] dt_maurer_std = Float64[] dt_fenz = Float64[] dt_fenz_std = Float64[] dt_proposed = Float64[] dt_proposed_std = Float64[] for _n in range_size_2D n = round(Int, _n) @info n push!(sizes, n^2) f = Float32.(rand([0, 1], n, n)) # Python (Scipy) dt = @benchmark pytransform($f) push!(dt_scipy, BenchmarkTools.minimum(dt).time) push!(dt_scipy_std, BenchmarkTools.std(dt).time) # Maurer (ImageMorphology.jl) bool_f = Bool.(f) dt = @benchmark distance_transform($feature_transform($bool_f)) push!(dt_maurer, BenchmarkTools.minimum(dt).time) # ns push!(dt_maurer_std, BenchmarkTools.std(dt).time) # Felzenszwalb (DistanceTransforms.jl) dt = @benchmark transform($boolean_indicator($f)) push!(dt_fenz, BenchmarkTools.minimum(dt).time) push!(dt_fenz_std, BenchmarkTools.std(dt).time) # Proposed-GPU (DistanceTransforms.jl) if dev != Array f_gpu = dev(f) dt = @benchmark transform($boolean_indicator($f_gpu)) push!(dt_proposed, BenchmarkTools.minimum(dt).time) push!(dt_proposed_std, BenchmarkTools.std(dt).time) end end end ╠═╡ =# # ╔═╡ 9d94d434-67c7-41fa-b8fc-3c2ce76c22d0 md""" ## 3D """ # ╔═╡ cbf39927-96e7-48f0-9812-7a24c3ce5cb4 # ╠═╡ disabled = true #=╠═╡ begin sizes_3D = Float64[] dt_scipy_3D = Float64[] dt_scipy_std_3D = Float64[] dt_maurer_3D = Float64[] dt_maurer_std_3D = Float64[] dt_fenz_3D = Float64[] dt_fenz_std_3D = Float64[] dt_proposed_3D = Float64[] dt_proposed_std_3D = Float64[] for _n in range_size_3D n = round(Int, _n) @info n push!(sizes_3D, n^3) f = Float32.(rand([0, 1], n, n, n)) # Python (Scipy) dt = @benchmark pytransform($f) push!(dt_scipy_3D, BenchmarkTools.minimum(dt).time) push!(dt_scipy_std_3D, BenchmarkTools.std(dt).time) # Maurer (ImageMorphology.jl) bool_f = Bool.(f) dt = @benchmark distance_transform($feature_transform($bool_f)) push!(dt_maurer_3D, BenchmarkTools.minimum(dt).time) # ns push!(dt_maurer_std_3D, BenchmarkTools.std(dt).time) # Felzenszwalb (DistanceTransforms.jl) dt = @benchmark transform($boolean_indicator($f)) push!(dt_fenz_3D, BenchmarkTools.minimum(dt).time) push!(dt_fenz_std_3D, BenchmarkTools.std(dt).time) # Proposed-GPU (DistanceTransforms.jl) if dev != Array f_gpu = dev(f) dt = @benchmark transform($boolean_indicator($f_gpu)) push!(dt_proposed_3D, BenchmarkTools.minimum(dt).time) push!(dt_proposed_std_3D, BenchmarkTools.std(dt).time) end end end ╠═╡ =# # ╔═╡ 969ddeaa-8ffc-4f7d-8aa6-47b201a8376d md""" ## Results """ # ╔═╡ 104ff068-ad07-4f94-8f3b-18c3660353c1 #=╠═╡ let f = Figure() ax = Axis( f[1, 1], title="2D" ) scatterlines!(dt_scipy, label="Python") scatterlines!(dt_maurer, label="Maurer") scatterlines!(dt_fenz, label="Felzenszwalb") scatterlines!(dt_proposed, label="GPU") ax = Axis( f[2, 1], title="3D" ) scatterlines!(dt_scipy_3D, label="Python") scatterlines!(dt_maurer_3D, label="Maurer") scatterlines!(dt_fenz_3D, label="Felzenszwalb") scatterlines!(dt_proposed_3D, label="GPU") f[1:2, 2] = Legend(f, ax, "Distance Transforms", framevisible = false) Label(f[0, 1:2]; text="Distance Transforms", fontsize=30) # save("gpu_fig.png", f) f end ╠═╡ =# # ╔═╡ 9a5245de-2d04-4d0b-abab-011e2bd5a980 md""" ## GPU Results Since Glass Notebook does not yet support GPU exports and to save resources, I saved a version of the benchmark results that include the GPU accelerated version (METAL) from my M1 Macbook Air which can be seen below. If you want to run these benchmarks on your own hardware, just simply run this notebook and enable all of the above cells """ # ╔═╡ 29834554-0f91-4542-95e4-afdb085a74b8 load("gpu_fig.png") # ╔═╡ Cell order: # ╟─dec905ec-5ca9-4ef9-b0a6-2a8d31f3f5c7 # ╠═e7b64851-7108-4c14-9710-c991d5b7021a # ╠═a3966df9-1107-4f2b-9fb0-704ad7dbe26a # ╠═ab982cb6-d37c-4d27-a695-d3d8378ab32b # ╠═c79a8a06-262c-4733-aa31-a0e9a896fafb # ╠═1a7c3ed0-7453-4f53-ac5a-99d0b3f84a85 # ╠═fe295739-2a9f-46a5-92b9-19e5b5b5dc50 # ╠═b4125c21-43cf-42a5-b685-bc47b8b1f8b8 # ╠═53545152-a6ca-4f13-8275-95a8a04017c0 # ╠═197c25db-3cc1-4b65-bf49-f0f27694bcc3 # ╠═c80da3e8-ff14-4f8c-9a67-b1601395ff40 # ╠═481bdd21-744e-424e-992b-b3e19c4c06f7 # ╠═0e6b49a2-7590-4800-871e-6a2b0019a9f3 # ╟─9dd1c30d-3472-492f-a06c-84777f1aabf4 # ╠═9ff0aadf-80b1-4cfd-b3a1-33fbcbc3fb1a # ╠═a6a3ce15-251c-4edf-8a85-d80cec6f4b3f # ╠═a0785853-9091-4fb8-a23c-536032edee74 # ╟─b8daf192-a46e-4b49-b09b-04f793c3b8cc # ╟─1f1867f0-05a4-4071-8f7d-9e238a8c940f # ╠═595dbaea-a238-44e5-b22a-57c423c1f6ac # ╠═be5b4e09-2a6d-472d-9790-623ae3e99bb8 # ╠═c1e55d37-d0c9-4da2-8841-89a714e50c21 # ╟─90142aaa-8a1f-4221-aadf-ad858b05f716 # ╠═f0ca70f4-ab9b-48ae-b701-cf4ac47b7bf4 # ╟─9d94d434-67c7-41fa-b8fc-3c2ce76c22d0 # ╠═cbf39927-96e7-48f0-9812-7a24c3ce5cb4 # ╟─969ddeaa-8ffc-4f7d-8aa6-47b201a8376d # ╟─104ff068-ad07-4f94-8f3b-18c3660353c1 # ╟─9a5245de-2d04-4d0b-abab-011e2bd5a980 # ╟─29834554-0f91-4542-95e4-afdb085a74b8
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
1154
### A Pluto.jl notebook ### # v0.19.36 #> [frontmatter] #> title = "API" #> category = "API" using Markdown using InteractiveUtils # ╔═╡ 94428604-9725-417c-a3c4-174b32b7cfd6 # ╠═╡ show_logs = false begin using Pkg Pkg.activate(".") Pkg.instantiate() using DistanceTransforms using PlutoUI end # ╔═╡ 0e3a840c-aebe-47e6-bdba-be8b54af2e55 TableOfContents() # ╔═╡ 5cb2767d-7ab0-4fec-ad61-163204d8913a all_names = [name for name in names(DistanceTransforms)]; # ╔═╡ cbb16a36-41b5-450d-b0ce-6bd2b2601706 exported_functions = filter(x -> x != :DistanceTransforms, all_names); # ╔═╡ d4b66280-c9e4-4c27-9cd3-6aaf179b8e0d function generate_docs(exported_functions) PlutoUI.combine() do Child md""" $([md" $(Docs.doc(eval(name)))" for name in exported_functions]) """ end end; # ╔═╡ d7559c62-1c0a-4e86-a642-74171d742c41 generate_docs(exported_functions) # ╔═╡ Cell order: # ╟─d7559c62-1c0a-4e86-a642-74171d742c41 # ╟─94428604-9725-417c-a3c4-174b32b7cfd6 # ╟─0e3a840c-aebe-47e6-bdba-be8b54af2e55 # ╟─5cb2767d-7ab0-4fec-ad61-163204d8913a # ╟─cbb16a36-41b5-450d-b0ce-6bd2b2601706 # ╟─d4b66280-c9e4-4c27-9cd3-6aaf179b8e0d
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
117
module DistanceTransforms abstract type DistanceTransform end include("./transform.jl") include("./utils.jl") end
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
9236
using GPUArraysCore: AbstractGPUVector, AbstractGPUMatrix, AbstractGPUArray using KernelAbstractions """ ## `transform!` ```julia transform!(f::AbstractVector, output, v, z) transform!(img::AbstractMatrix, output, v, z; threaded=true) transform!(vol::AbstractArray{<:Real,3}, output, v, z, temp; threaded=true) transform!(img::AbstractGPUMatrix, output, v, z) ``` In-place squared Euclidean distance transforms. These functions apply the transform to the input data and store the result in the `output` argument. - The first function operates on vectors. - The second function operates on matrices with optional threading. - The third function operates on 3D arrays with optional threading. - The fourth function is specialized for GPU matrices. The intermediate arrays `v` and `z` (and `temp` for 3D arrays) are used for computation. The `threaded` parameter enables parallel computation on the CPU. #### Arguments - `f`: Input vector, matrix, or 3D array. - `output`: Preallocated array to store the result. - `v`: Preallocated array for indices, matching the dimensions of `f`. - `z`: Preallocated array for intermediate values, one element larger than `f`. - `temp`: Preallocated array for intermediate values when transforming 3D arrays, matching the dimensions of `output`. #### Examples ```julia f = rand([0f0, 1f0], 10) f_bool = boolean_indicator(f) output = similar(f) v = ones(Int32, size(f)) z = ones(eltype(f), size(f) .+ 1) transform!(f_bool, output, v, z) ``` """ function transform!(f::AbstractVector, output, v, z) z[1] = -Inf32 z[2] = Inf32 k = 1 @inbounds for q in 2:length(f) s = ((f[q] + q^2) - (f[v[k]] + v[k]^2)) / (2 * q - 2 * v[k]) while s ≤ z[k] k -= 1 s = ((f[q] + q^2) - (f[v[k]] + v[k]^2)) / (2 * q - 2 * v[k]) end k += 1 v[k] = q z[k] = s z[k+1] = Inf32 end k = 1 @inbounds for q in 1:length(f) while z[k+1] < q k += 1 end output[q] = (q - v[k])^2 + f[v[k]] end end # 2D function transform!(img::AbstractMatrix, output, v, z; threaded = true) if threaded Threads.@threads for i in CartesianIndices(@view(img[:, 1])) @views transform!(img[i, :], output[i, :], v[i, :], z[i, :]) end copyto!(img, output) Threads.@threads for j in CartesianIndices(@view(img[1, :])) @views transform!( img[:, j], output[:, j], fill!(v[:, j], 1), fill!(z[:, j], 1), ) end else for i in CartesianIndices(@view(img[:, 1])) @views transform!(img[i, :], output[i, :], v[i, :], z[i, :]) end copyto!(img, output) for j in CartesianIndices(@view(img[1, :])) @views transform!( img[:, j], output[:, j], fill!(v[:, j], 1), fill!(z[:, j], 1), ) end end end # 3D function transform!(vol::AbstractArray{<:Real, 3}, output, v, z; threaded = true) if threaded Threads.@threads for i in CartesianIndices(@view(vol[:, 1, 1])) @views transform!(vol[i, :, :], output[i, :, :], v[i, :, :], z[i, :, :]) end copyto!(vol, output) Threads.@threads for idx in CartesianIndices(@view(vol[1, :, :])) j, k = Tuple(idx) @views transform!( vol[:, j, k], output[:, j, k], fill!(v[:, j, k], 1), fill!(z[:, j, k], 1), ) end else for i in CartesianIndices(@view(vol[:, 1, 1])) @views transform!(vol[i, :, :], output[i, :, :], v[i, :, :], z[i, :, :]) end copyto!(vol, output) for idx in CartesianIndices(@view(vol[1, :, :])) j, k = Tuple(idx) @views transform!( vol[:, j, k], output[:, j, k], fill!(v[:, j, k], 1), fill!(z[:, j, k], 1), ) end end end # GPU (2D) @kernel function _first_pass_2D!(f, out, s2) row, col = @index(Global, NTuple) if f[row, col] < 0.5f0 ct = 1 curr_l = min(col - 1, s2 - col) finished = false while !finished && ct <= curr_l if f[row, col-ct] > 0.5f0 || f[row, col+ct] > 0.5f0 out[row, col] = ct * ct finished = true end ct += 1 end while !finished && ct < col if f[row, col-ct] > 0.5f0 out[row, col] = ct * ct finished = true end ct += 1 end while !finished && col + ct <= s2 if f[row, col+ct] > 0.5f0 out[row, col] = ct * ct finished = true end ct += 1 end if !finished out[row, col] = 1.0f10 end else out[row, col] = 0.0f0 end end @kernel function _second_pass_2D!(org, out, s1, s2) row, col = @index(Global, NTuple) ct = 1 curr_l = sqrt(out[row, col]) while ct < curr_l && row + ct <= s1 temp = muladd(ct, ct, org[row+ct, col]) if temp < out[row, col] out[row, col] = temp curr_l = sqrt(temp) end ct += 1 end ct = 1 while ct < curr_l && row > ct temp = muladd(ct, ct, org[row-ct, col]) if temp < out[row, col] out[row, col] = temp curr_l = sqrt(temp) end ct += 1 end end function transform!(img::AbstractGPUMatrix, output) s1, s2 = size(img) backend = get_backend(img) kernel1! = _first_pass_2D!(backend) kernel2! = _second_pass_2D!(backend) kernel1!(img, output, s2, ndrange = (s1, s2)) copyto!(img, output) kernel2!(img, output, s1, s2, ndrange = (s1, s2)) KernelAbstractions.synchronize(backend) end # GPU (3D) @kernel function _first_pass_3D!(f, out, s2) dim1, dim2, dim3 = @index(Global, NTuple) # 1D along dimension 2 if f[dim1, dim2, dim3] < 0.5f0 ct = 1 curr_l = min(dim2 - 1, s2 - dim2) finished = false while !finished && ct <= curr_l if f[dim1, dim2-ct, dim3] > 0.5f0 || f[dim1, dim2+ct, dim3] > 0.5f0 out[dim1, dim2, dim3] = ct * ct finished = true end ct += 1 end while !finished && ct < dim2 if f[dim1, dim2-ct, dim3] > 0.5f0 out[dim1, dim2, dim3] = ct * ct finished = true end ct += 1 end while !finished && dim2 + ct <= s2 if f[dim1, dim2+ct, dim3] > 0.5f0 out[dim1, dim2, dim3] = ct * ct finished = true end ct += 1 end if !finished out[dim1, dim2, dim3] = 1.0f10 end else out[dim1, dim2, dim3] = 0.0f0 end end @kernel function _second_pass_3D!(org, out, s1) dim1, dim2, dim3 = @index(Global, NTuple) # 2D along dimension 1 ct = 1 curr_l = sqrt(out[dim1, dim2, dim3]) while ct < curr_l && dim1 + ct <= s1 temp = muladd(ct, ct, org[dim1+ct, dim2, dim3]) if temp < out[dim1, dim2, dim3] out[dim1, dim2, dim3] = temp curr_l = sqrt(temp) end ct += 1 end ct = 1 while ct < curr_l && dim1 - ct > 0 temp = muladd(ct, ct, org[dim1-ct, dim2, dim3]) if temp < out[dim1, dim2, dim3] out[dim1, dim2, dim3] = temp curr_l = sqrt(temp) end ct += 1 end end @kernel function _third_pass_3D!(org, out, s3) dim1, dim2, dim3 = @index(Global, NTuple) # 2D along dimension 3 ct = 1 curr_l = sqrt(out[dim1, dim2, dim3]) while ct < curr_l && dim3 + ct <= s3 temp = muladd(ct, ct, org[dim1, dim2, dim3+ct]) if temp < out[dim1, dim2, dim3] out[dim1, dim2, dim3] = temp curr_l = sqrt(temp) end ct += 1 end ct = 1 while ct < curr_l && ct < dim3 temp = muladd(ct, ct, org[dim1, dim2, dim3-ct]) if temp < out[dim1, dim2, dim3] out[dim1, dim2, dim3] = temp curr_l = sqrt(temp) end ct += 1 end end function transform!(img::AbstractGPUArray, output) backend = get_backend(img) s1, s2, s3 = size(img) kernel1! = _first_pass_3D!(backend) kernel2! = _second_pass_3D!(backend) kernel3! = _third_pass_3D!(backend) kernel1!(img, output, s2, ndrange = (s1, s2, s3)) copyto!(img, output) kernel2!(img, output, s1, ndrange = (s1, s2, s3)) copyto!(img, output) kernel3!(img, output, s3, ndrange = (s1, s2, s3)) KernelAbstractions.synchronize(backend) end export transform! """ ## `transform` ```julia transform(f::AbstractVector) transform(img::AbstractMatrix; threaded=true) transform(vol::AbstractArray{<:Real,3}; threaded=true) transform(img::AbstractGPUMatrix) ``` Non-in-place squared Euclidean distance transforms that return a new array with the result. They allocate necessary intermediate arrays internally. - The first function operates on vectors. - The second function operates on matrices with optional threading. - The third function operates on 3D arrays with optional threading. - The fourth function is specialized for GPU matrices. The `threaded` parameter can be used to enable or disable parallel computation on the CPU. #### Arguments - `f/img/vol`: Input vector, matrix, or 3D array to be transformed. #### Examples ```julia f = rand([0f0, 1f0], 10) f_bool = boolean_indicator(f) f_tfm = transform(f_bool) ``` """ function transform(f::AbstractVector) output = similar(f, eltype(f)) v = ones(Int32, length(f)) z = ones(eltype(f), length(f) + 1) transform!(f, output, v, z) return output end # 2D function transform(img::AbstractMatrix; threaded = true) output = similar(img, eltype(img)) v = ones(Int32, size(img)) z = ones(eltype(img), size(img) .+ 1) transform!(img, output, v, z; threaded = threaded) return output end # 3D function transform(vol::AbstractArray{<:Real, 3}; threaded = true) output = similar(vol, eltype(vol)) v = ones(Int32, size(vol)) z = ones(eltype(vol), size(vol) .+ 1) transform!(vol, output, v, z; threaded = threaded) return output end # GPU (2D) function transform(img::AbstractGPUMatrix) output = similar(img, Float32) transform!(img, output) return output end # GPU (3D) function transform(img::AbstractGPUArray) output = similar(img, Float32) transform!(img, output) return output end export transform
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
2998
using KernelAbstractions using GPUArraysCore: AbstractGPUArray """ ## `boolean_indicator` ```julia boolean_indicator(f::AbstractArray) boolean_indicator(f::AbstractGPUArray) boolean_indicator(f::BitArray) ``` Create a float representation of a boolean indicator array where `0` represents the background and `1` represents the foreground. This function converts a logical array into a floating-point array where foreground values (logical `1`) are marked as `0.0f0` (float representation of `0`), and background values (logical `0`) are marked with a large float number `1.0f10`. This representation is useful in distance transform operations to differentiate between the foreground and the background. #### Arguments - `f`: An array of boolean values or an `AbstractGPUArray` of boolean values, where `true` indicates the foreground and `false` indicates the background. #### Returns - A floating-point array of the same dimensions as `f`, with foreground values set to `0.0f0` and background values set to `1.0f10`. #### Performance - If `f` is a `BitArray`, the conversion uses LoopVectorization.jl for a potential speedup. The warning check arguments are disabled for performance reasons. - If `f` is an `AbstractGPUArray`, the computation is offloaded to the GPU using a custom kernel, `boolean_indicator_kernel`, which is expected to yield a significant speedup on compatible hardware. #### Examples ```julia f = BitArray([true, false, true, false]) f_float = boolean_indicator(f) # f_float will be Float32[0.0f0, 1.0f10, 0.0f0, 1.0f10] f_gpu = CUDA.zeros(Bool, 10) # assuming CUDA.jl is used for GPU arrays f_gpu[5] = true f_float_gpu = boolean_indicator(f_gpu) # f_float_gpu will be a GPU array with the fifth element as 0.0f0 and others as 1.0f10 ``` #### Notes - The choice of `1.0f10` as the large number is arbitrary and can be adjusted if needed for specific applications. - The `@turbo` macro from LoopVectorization.jl is used when `f` is a `BitArray` to unroll and vectorize the loop for optimal performance. - When `f` is an `AbstractGPUArray`, the `boolean_indicator_kernel` kernel function is used to perform the operation in parallel on the GPU. - The `KernelAbstractions.synchronize(backend)` call ensures that all GPU operations are completed before returning the result. """ function boolean_indicator(f) return @. ifelse(f == 0, 1.0f10, 0.0f0) end function boolean_indicator(f::BitArray) f_new = similar(f, Float32) for i in CartesianIndices(f_new) @inbounds f_new[i] = f[i] ? 0.0f0 : 1.0f10 end return f_new end @kernel function boolean_indicator_kernel(f, output) i = @index(Global) output[i] = ifelse(f[i] == 0, 1.0f10, 0.0f0) end function boolean_indicator(f::AbstractGPUArray) backend = get_backend(f) output = similar(f, Float32) kernel = boolean_indicator_kernel(backend) kernel(f, output, ndrange=size(f)) KernelAbstractions.synchronize(backend) return output end export boolean_indicator
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
695
using DistanceTransforms using Test using KernelAbstractions using CUDA, AMDGPU, Metal using oneAPI using Random if CUDA.functional() @info "Using CUDA" CUDA.versioninfo() backend = CUDABackend() dev = CuArray elseif AMDGPU.functional() @info "Using AMD" AMDGPU.versioninfo() backend = ROCBackend() dev = ROCArray elseif oneAPI.functional() ## not well supported @info "Using oneAPI" oneAPI.versioninfo() backend = oneBackend() dev = oneArray elseif Metal.functional() @info "Using Metal" Metal.versioninfo() backend = MetalBackend() dev = MtlArray else @info "No GPU is available. Using CPU." backend = CPU() dev = Array end include("transform.jl") include("utils.jl")
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
4883
using ImageMorphology: distance_transform, feature_transform test_transform(img) = distance_transform(feature_transform(Bool.(img))) @testset "transform!" begin @testset "1D transform!" begin for n in [10, 50, 100] for test_idx in 1:20 img = rand([0f0, 1f0], n) img_bool = boolean_indicator(img) output = similar(img, Float32) v = ones(Int32, size(img)) z = ones(Float32, size(img) .+ 1) transform!(img_bool, output, v, z) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end @testset "2D transform!" begin for n in [10, 50, 100] for test_idx in 1:20 img = rand([0f0, 1f0], n, n) img_bool = boolean_indicator(img) output = similar(img, Float32) v = ones(Int32, size(img)) z = ones(Float32, size(img) .+ 1) transform!(img_bool, output, v, z) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end # non-threaded for test_idx in 1:20 img = rand([0f0, 1f0], n, n) img_bool = boolean_indicator(img) output = similar(img, Float32) v = ones(Int32, size(img)) z = ones(Float32, size(img) .+ 1) transform!(img_bool, output, v, z; threaded = false) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end @testset "3D transform!" begin for n in [10, 100] for test_idx in 1:5 img = rand([0f0, 1f0], n, n, n) img_bool = boolean_indicator(img) output = similar(img, Float32) v = ones(Int32, size(img)) z = ones(Float32, size(img) .+ 1) transform!(img_bool, output, v, z) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end # non-threaded for test_idx in 1:5 img = rand([0f0, 1f0], n, n, n) img_bool = boolean_indicator(img) output = similar(img, Float32) v = ones(Int32, size(img)) z = ones(Float32, size(img) .+ 1) transform!(img_bool, output, v, z; threaded = false) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end if dev != Array @testset "2D GPU transform!" begin for n in [10, 50, 100] for test_idx in 1:20 img = rand([0f0, 1f0], n, n) img_gpu = dev(copy(img)) output = similar(img_gpu) transform!(img_gpu, output) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end @testset "3D GPU transform!" begin for n in [10, 50, 100] for test_idx in 1:20 img = rand([0f0, 1f0], n, n, n) img_gpu = dev(copy(img)) output = similar(img_gpu) transform!(img_gpu, output) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end else @info "No GPU available, skipping tests" end end @testset "transform" begin @testset "1D transform" begin for n in [10, 50, 100] for test_idx in 1:20 img = rand([0.0f0, 1.0f0], n) img_bool = boolean_indicator(img) output = transform(img_bool) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end @testset "2D transform" begin for n in [10, 50, 100] for test_idx in 1:20 img = rand([0.0f0, 1.0f0], n, n) img_bool = boolean_indicator(img) output = transform(img_bool) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end # non-threaded for test_idx in 1:20 img = rand([0.0f0, 1.0f0], n, n) img_bool = boolean_indicator(img) output = transform(img_bool; threaded = false) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end @testset "3D transform" begin for n in [10, 100] for test_idx in 1:5 img = rand([0.0f0, 1.0f0], n, n, n) img_bool = boolean_indicator(img) output = transform(img_bool) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end # non-threaded for test_idx in 1:5 img = rand([0.0f0, 1.0f0], n, n, n) img_bool = boolean_indicator(img) output = transform(img_bool; threaded = false) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end if dev != Array @testset "2D GPU transform" begin for n in [10, 50, 100] for test_idx in 1:20 img = rand([0.0f0, 1.0f0], n, n) img_gpu = dev(img) output = transform(img_gpu) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end @testset "3D GPU transform" begin for n in [10, 50, 100] for test_idx in 1:20 img = rand([0.0f0, 1.0f0], n, n, n) img_gpu = dev(img) output = transform(img_gpu) img_test = test_transform(img) .^ 2 @test Array(output) ≈ img_test end end end else @info "No GPU available, skipping tests" end end
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
code
1006
@testset "boolean_indicator CPU" begin ns = [10, 100] for n in ns f = rand([0, 1], n) f_bool = Bool.(f) @test boolean_indicator(f) == boolean_indicator(f_bool) end for n in ns f = rand([0, 1], n, n) f_bool = Bool.(f) @test boolean_indicator(f) == boolean_indicator(f_bool) end for n in ns f = rand([0, 1], n, n, n) f_bool = Bool.(f) @test boolean_indicator(f) == boolean_indicator(f_bool) end end @testset "boolean_indicator GPU" begin ns = [10, 100] for n in ns f = rand!(KernelAbstractions.allocate(backend, Float32, n)) .> 0.5f0 f_arr = Array(f) @test Array(boolean_indicator(f)) == boolean_indicator(f_arr) end for n in ns f = rand!(KernelAbstractions.allocate(backend, Float32, n, n)) .> 0.5f0 f_arr = Array(f) @test Array(boolean_indicator(f)) == boolean_indicator(f_arr) end for n in ns f = rand!(KernelAbstractions.allocate(backend, Float32, n, n, n)) .> 0.5f0 f_arr = Array(f) @test Array(boolean_indicator(f)) == boolean_indicator(f_arr) end end
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.2
2ef35d0921e6ad1bf04fbe745bde164673cb2deb
docs
3413
# DistanceTransforms [![Glass Notebook](https://img.shields.io/badge/Docs-Glass%20Notebook-aquamarine.svg)](https://glassnotebook.io/r/DxnIPJnIqpEqiQnJgqiBP/index.jl) [![CI Stable](https://github.com/Dale-Black/DistanceTransforms.jl/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/Dale-Black/DistanceTransforms.jl/actions/workflows/CI.yml) [![CI Nightly](https://github.com/Dale-Black/DistanceTransforms.jl/actions/workflows/Nightly.yml/badge.svg?branch=master)](https://github.com/Dale-Black/DistanceTransforms.jl/actions/workflows/Nightly.yml) [![Coverage](https://codecov.io/gh/Dale-Black/DistanceTransforms.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/Dale-Black/DistanceTransforms.jl) DistanceTransforms.jl is a Julia package that provides efficient distance transform operations on arrays. ## Table of Contents - [Getting Started](#getting-started) - [Quick Start](#quick-start) - [Transforms](#transforms) - [Advanced Usage](#advanced-usage) - [Python](#python) ## Getting Started To get started with DistanceTransforms.jl, you'll first need to import the package: ```julia using DistanceTransforms ``` The most up-to-date version of DistanceTransforms.jl can be found on the main/master branch of the [GitHub repository](https://github.com/Dale-Black/DistanceTransforms.jl). If you're using an unregistered version, you may need to add the package explicitly. For detailed documentation and tutorials, you can refer to the [official notebook](https://glassnotebook.io/r/DxnIPJnIqpEqiQnJgqiBP/index.jl). ## Quick Start Distance transforms are essential for many computer vision-related tasks. With DistanceTransforms.jl, you can easily apply efficient distance transform operations on arrays in Julia. For example, to use the quintessential distance transform operation: ```julia using DistanceTransforms arr = [ 0 1 1 0 0 0 0 0 1 1 0 0 ] result = transform(boolean_indicator(arr)) ``` ## Transforms The library is built around a common `transform` interface, allowing users to apply various distance transform algorithms to arrays using a unified approach. ## Advanced Usage DistanceTransforms.jl offers advanced features such as multi-threading and GPU acceleration. These capabilities significantly enhance performance, especially for large data sets and high-resolution images. ### Multi-threading DistanceTransforms.jl efficiently utilizes multi-threading, particularly in its Felzenszwalb distance transform algorithm. This parallelization improves performance for large data sets and high-resolution images. ```julia x = boolean_indicator(rand([0f0, 1f0], 100, 100)) single_threaded = @benchmark transform($x; threaded = false) multi_threaded = @benchmark transform($x; threaded = true) ``` ### GPU Acceleration DistanceTransforms.jl extends its performance capabilities by embracing GPU acceleration. The same `transform` function used for CPU computations automatically adapts to leverage GPU resources when available. ```julia x_gpu = CUDA.CuArray(boolean_indicator(rand([0, 1], 100, 100))) gpu_transformed = transform(x_gpu) ``` For benchmarks and more details on advanced usage, refer to the [advanced usage notebook](https://glassnotebook.io/r/DxnIPJnIqpEqiQnJgqiBP/index.jl). ## Python Check out the corresponding Python (wrapper) package: [py-distance-transforms](https://github.com/MolloiLab/py-distance-transforms)
DistanceTransforms
https://github.com/MolloiLab/DistanceTransforms.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
2101
using Revise using AsymptoticNumericalMethod, Plots using LinearAlgebra: norm using BifurcationKit const BK = BifurcationKit function LW(x, p) (;λ) = p f = similar(x) s = sum(x) for i in eachindex(f) f[i] = x[i] - λ * exp(cos(i * s)) end return f end sol0 = zeros(10) par = (λ = 0.0, ) prob = BifurcationProblem(LW, sol0, par, (@optic _.λ); record_from_solution = (x,p) -> (xₙ = x[end], x₁ = x[1], s = sum(x), xinf = norminf(x))) optcont = ContinuationPar(dsmin = 0.0001, dsmax = 0.05, ds= 0.01, newton_options = NewtonPar(tol = 1e-11, max_iterations = 4, verbose = false), max_steps = 1500, detect_bifurcation = 0, p_max = 1., p_min = 0., detect_fold=false) alg = PALC(tangent = Bordered()) alg = MoorePenrose() alg = MoorePenrose(tangent = PALC(tangent = Secant())) br = continuation(prob, alg, optcont; verbosity = 0) plot(br, vars=(:param, :xN)) plot(br, vars=(:param, :s)) ################################################################################# using LinearAlgebra defop = DeflationOperator(2, dot, 0.1, [sol0]) algdc = DefCont(deflation_operator = defop, alg = PALC(tangent = Bordered()), perturb_solution = (x, p, id) -> x .+ 0.02 * rand(length(x)), jacobian = Val(:autodiff) ) brdc = continuation(prob, algdc, ContinuationPar(optcont; ds = 0.00002, dsmin = 1e-6, max_steps = 20000, p_max = 1.2, detect_bifurcation = 0, plot_every_step = 1000, newton_options = NewtonPar(verbose = false, max_iterations = 10)); plot = true, verbosity = 2, # callback_newton = ((x, f, J, res, iteration, itlinear, options); kwargs...) -> res <1e2, # normN = norminf ) plot(brdc) ################################################################################# optanm = ContinuationPar(optcont, max_steps = 1700, detect_bifurcation = 0) @reset optanm.newton_options.max_iterations = 10 @reset optanm.newton_options.verbose = true branm = @time continuation(prob, ANM(17, 1e-7), optanm, normC = norminf, verbosity = 1) plot(branm; vars=(:param, :xₙ), plotseries = false)
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
1327
using Revise using AsymptoticNumericalMethod, Plots using BifurcationKit const BK = BifurcationKit function TMvf!(dz, z, p, t = 0) (;J, α, E0, τ, τD, τF, U0) = p E, x, u = z SS0 = J * u * x * E + E0 SS1 = α * log(1 + exp(SS0 / α)) dz[1] = (-E + SS1) / τ dz[2] = (1.0 - x) / τD - u * x * E dz[3] = (U0 - u) / τF + U0 * (1.0 - u) * E dz end par_tm = (α = 1.5, τ = 0.013, J = 3.07, E0 = -2.0, τD = 0.200, U0 = 0.3, τF = 1.5, τS = 0.007) #2.87 z0 = [0.238616, 0.982747, 0.367876 ] prob = BK.BifurcationProblem(TMvf!, z0, par_tm, (@optic _.E0); record_from_solution = (x, p) -> (E = x[1], x = x[2], u = x[3]),) opts_br = ContinuationPar(p_min = -10.0, p_max = -0.9, ds = 0.04, dsmax = 0.125, n_inversion = 8, detect_bifurcation = 3, max_bisection_steps = 25, nev = 3) br0 = continuation(prob, PALC(tangent=Bordered()), opts_br, normC = norminf) plot(br0) ################################################################################# optanm = ContinuationPar(opts_br, ds= 0.01, newton_options = NewtonPar(tol = 1e-9, verbose = false), n_inversion = 6, max_bisection_steps = 15, max_steps = 15, )#p_max = 0.1) branm = @time continuation(prob, ANM(20, 1e-8), optanm, normC = norminf, verbosity = 2) plot(branm) plot(branm.branch) plot(branm, plotseries = true) plot!(br0, color = :black)
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
1092
using Revise using AsymptoticNumericalMethod, Plots using BifurcationKit const BK = BifurcationKit Nl(x; a = 0.5, b = 0.01) = 1 + (x + a*x^2)/(1 + b*x^2) function F_chan(x, p) (;α, β) = p f = similar(x) n = length(x) f[1] = x[1] - β f[n] = x[n] - β for i=2:n-1 f[i] = (x[i-1] - 2 * x[i] + x[i+1]) * (n-1)^2 + α * Nl(x[i], b = β) end return f end n = 101 sol = [(i-1)*(n-i)/n^2+0.1 for i=1:n] # set of parameters par = (α = 3.3, β = 0.01) optnewton = NewtonPar(tol = 1e-11, verbose = true) prob = BifurcationProblem(F_chan, sol, par, (@optic _.α)) optcont0 = ContinuationPar(dsmin = 0.01, dsmax = 0.15, ds= 0.01, p_max = 4.1, newton_options = NewtonPar(tol = 1e-9)) br0 = @time continuation(prob, PALC(tangent = Bordered()), optcont0) plot(br0) ################################################################################# optcont = ContinuationPar(dsmin = 0.01, dsmax = 0.15, ds = 0.01, p_max = 4.1, newton_options = NewtonPar(tol = 1e-9)) branm = continuation(prob, ANM(15, 1e-4), optcont, normC = norminf) plot(branm, plotseries = true)
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
2938
using Revise using DiffEqOperators, ForwardDiff using BifurcationKit, Plots, SparseArrays, Parameters, AsymptoticNumericalMethod const BK = BifurcationKit # define the sup norm and a L2 norm normbratu(x) = norm(x .* w) / sqrt(length(x)) # the weight w is defined below # some plotting functions to simplify our life plotsol!(x, nx = Nx, ny = Ny; kwargs...) = heatmap!(reshape(x, nx, ny); color = :viridis, kwargs...) plotsol(x, nx = Nx, ny = Ny; kwargs...) = (plot();plotsol!(x, nx, ny; kwargs...)) function Laplacian2D(Nx, Ny, lx, ly, bc = :Neumann) hx = 2lx/Nx hy = 2ly/Ny D2x = CenteredDifference(2, 2, hx, Nx) D2y = CenteredDifference(2, 2, hy, Ny) Qx = Neumann0BC(hx) Qy = Neumann0BC(hy) D2xsp = sparse(D2x * Qx)[1] D2ysp = sparse(D2y * Qy)[1] A = kron(sparse(I, Ny, Ny), D2xsp) + kron(D2ysp, sparse(I, Nx, Nx)) return A end ϕ(u, λ) = -10(u-λ*exp(u)) dϕ(u, λ) = -10(1-λ*exp(u)) function NL!(dest, u, p) @unpack λ = p dest .= ϕ.(u, λ) return dest end NL(u, p) = NL!(similar(u), u, p) function Fmit!(f, u, p) mul!(f, p.Δ, u) f .= f .+ NL(u, p) return f end Fmit(u, p) = Fmit!(similar(u), u, p) function JFmit(x,p) J = p.Δ dg = dϕ.(x, p.λ) return J + spdiagm(0 => dg) end Nx = 30; Ny = 30 lx = 0.5; ly = 0.5 # weight for the weighted norm const w = (lx .+ LinRange(-lx,lx,Nx)) * (LinRange(-ly,ly,Ny))' |> vec Δ = Laplacian2D(Nx, Ny, lx, ly) par_mit = (λ = .05, Δ = Δ) # initial guess f for newton sol0 = zeros(Nx, Ny) |> vec # Bifurcation Problem prob = BifurcationProblem(Fmit, sol0, par_mit, (@optic _.λ),; J = JFmit, record_from_solution = (x, p) -> (x = normbratu(x), n2 = norm(x), n∞ = norminf(x)), plot_solution = (x, p; k...) -> plotsol!(x ; k...)) # eigensolver eigls = EigKrylovKit(dim = 70) # options for Newton solver, we pass the eigensolverr opt_newton = NewtonPar(tol = 1e-8, eigsolver = eigls, max_iterations = 20) # options for continuation opts_br = ContinuationPar(p_max = 3.5, p_min = 0.025, # for a good looking curve dsmin = 0.001, dsmax = 0.05, ds = 0.01, # number of eigenvalues to compute nev = 30, plot_every_step = 10, newton_options = (@set opt_newton.verbose = false), max_steps = 100, tol_stability = 1e-6, # detect codim 1 bifurcations detect_bifurcation = 3, # Optional: bisection options for locating bifurcations n_inversion = 4, dsmin_bisection = 1e-7, max_bisection_steps = 25) # optional arguments for continuation kwargsC = (verbosity = 0, plot = true, normC = norminf) br = continuation(prob, PALC(), opts_br; kwargsC...) show(br) ################################################################################# optanm = ContinuationPar(opts_br, ds= 0.01, n_inversion = 6, max_bisection_steps = 15, max_steps = 15, )#p_max = 0.1) branm = @time continuation(prob, ANM(20, 1e-8), optanm, normC = norminf, verbosity = 3) plot(branm; plotseries = true)
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
1778
using Revise using AsymptoticNumericalMethod, LinearAlgebra, Plots using BifurcationKit const BK = BifurcationKit function F_chan(x, p) (;α) = p N = length(x) h = 1/(N) f = similar(x) n = length(x) f[1] = (-2x[1]+x[2])/h^2 + α * exp(x[1]) f[n] = ( x[N-1]-2x[N])/h^2 + α * exp(x[N]) for i=2:n-1 f[i] = (x[i-1] - 2 * x[i] + x[i+1]) / h^2 + α * exp(x[i]) end return f end n = 109 sol = zeros(n) par = (α = 0.0, ) optnewton = NewtonPar(tol = 1e-11, verbose = true) prob = BifurcationProblem(F_chan, sol, par, (@optic _.α); record_from_solution = (x,p) -> norminf(x)) optcont0 = ContinuationPar(dsmin = 0.01, dsmax = 0.05, ds= 0.01, p_max = 4.1, newton_options = NewtonPar(tol = 1e-9), max_steps = 550) br0 = @time continuation(prob, PALC(),optcont0, normC = norminf, verbosity = 0) plot(br0) ################################################################################# # optanm = ContinuationPar(dsmin = 0.01, dsmax = 0.15, ds= 0.01, p_max = 4.1, newton_options = NewtonPar(tol = 1e-9)) # # polU, polp = ANM.anm(F_chan, Jac_mat, out, par, (@lens _.α), 5, 70, 1e-4, optanm, normC = x->norm(x,2), verbosity = 1) # # plot() # for ii in eachindex(polU) # a = LinRange(0, 4polU[ii].radius, 20) # plot!([polp[ii].(a)], [norm(polU[ii](_a), Inf) for _a in a], legend = false, marker=:d) # end # plot!(br0) # title!(""); # ylims!(0,2) ################################################################################# optanm = ContinuationPar(dsmin = 0.01, dsmax = 0.15, ds= 0.01, p_max = 4.1, newton_options = NewtonPar(tol = 1e1, verbose = false), detect_bifurcation = 3, max_steps = 6) br_anm = @time continuation(prob, ANM(30, 1e-6), optanm, normC = norm, verbosity = 1) plot(br_anm)
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
1679
using Revise using AsymptoticNumericalMethod, Plots using LinearAlgebra: norm using BifurcationKit const BK = BifurcationKit function F(x, p) (;α) = p f = similar(x) f[1] = (-2x[1]+x[2]) + α * exp(x[1]) f[2] = ( x[1]-2x[2]) + α * exp(x[2]) return f end sol0 = zeros(2) par = (α = 0.0, ) prob = BifurcationProblem(F, sol0, par, (@optic _.α); record_from_solution = (x,p) -> norminf(x)) optcont = ContinuationPar(dsmin = 0.01, dsmax = 0.15, ds= 0.1, newton_options = NewtonPar(tol = 1e-11), max_steps = 100, detect_bifurcation = 3) br0 = @time continuation(prob, PALC(), optcont, normC = norminf) plot(br0) ################################################################################# br1 = continuation(br0, 2) plot(br0,br1) ################################################################################# optanm = ContinuationPar(optcont, ds= 0.01, newton_options = NewtonPar(tol = 1e-9, verbose = false), detect_bifurcation = 3, n_inversion = 6, max_bisection_steps = 15, max_steps = 15, )#p_max = 0.1) branm = @time continuation(prob, ANM(20, 1e-8), optanm, normC = norminf, verbosity = 2) plot(branm) plot(branm, plotseries = true) plot!(br0, color = :black) ################ # plot the norm of the series plot() for ii in eachindex(branm.polU) s = LinRange(-0*branm.radius[ii], branm.radius[ii], 20) plot!([branm.polp[ii].(s)], [norminf(F(branm.polU[ii](_s), BK.setparam(prob,branm.polp[ii](_s)))) for _s in s], legend = false, linewidth=5)#, marker=:d) end title!("") ################################################################################# # WIP !!! does not work yet # branm1 = continuation(branm, 2)
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
453
module AsymptoticNumericalMethod using BifurcationKit, Parameters using ForwardDiff, TaylorIntegration using DocStringExtensions import BifurcationKit: getparams, setParam, residual, jacobian import LinearAlgebra: dot, norm using RecipesBase const BK = BifurcationKit include("Taylor.jl") include("Results.jl") include("Wrap.jl") include("plotting/Recipes.jl") export ANM, continuation end # module
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
1051
""" $(SIGNATURES) Continuation result from the ANM method. ## Fields $(TYPEDFIELDS) """ struct ANMResult{Tkind, Tprob, U, P, T, B <: BK.AbstractResult{Tkind, Tprob}} <: BK.AbstractResult{Tkind, Tprob} "Vector of Taylor series solutions" polU::U "Vector of Taylor series parameter" polp::P "Radius of validity for each Taylor series" radius::Vector{T} "Corresponnding `::ContResult`" branch::B end function Base.getproperty(br::ANMResult, s::Symbol) if s in (:polU, :polp, :radius, :branch) return getfield(br, s) else return getfield(br.branch, s) end end @inline BK.haseigenvalues(br::ANMResult) = false @inline BK.kernel_dimension(br::ANMResult, ind) = BK.kernel_dimension(br.branch, ind) @inline BK.get_contresult(br::ANMResult) = br.branch function Base.show(io::IO, br::ANMResult; comment = "", prefix = " ") comment = "\n" * prefix * "├─ $(length(br.polU)) series of degree $(br.alg.order), tol = $(br.alg.tol)" BK.show(io, BK.get_contresult(br); comment = comment) end
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
11883
""" $(SIGNATURES) Continuation algorithm based on Asymptotic Numerical Method. It can be used from the package https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl ## Fields $(TYPEDFIELDS) ## References - Charpentier, Isabelle, Bruno Cochelin, and Komlanvi Lampoh. “Diamanlab - An Interactive Taylor-Based Continuation Tool in MATLAB,” n.d., 12. - Rubbert, Lennart, Isabelle Charpentier, Simon Henein, and Pierre Renaud. “Higher-Order Continuation Method for the Rigid-Body Kinematic Design of Compliant Mechanisms”, n.d., 18. """ struct ANM{T} <: BK.AbstractContinuationAlgorithm "order of the polynomial approximation" order::Int "tolerance which is used to estimate the neighbourhood on which the polynomial approximation is valid" tol::T end """ $(SIGNATURES) # Arguments - `prob::BifurcationProblem` - `alg::` ANM continuation algorithm. See [`ANM`](@ref). - `contParams` see [`BK.ContinuationPar`](@ref) """ function BK.continuation(prob::BK.AbstractBifurcationProblem, alg::ANM, contParams::BK.ContinuationPar{T, L, E}; linear_algo = MatrixBLS(), plot = false, normC = norm, finalise_solution = BK.finalise_default, callback_newton = BifurcationKit.cb_default, kind = BK.EquilibriumCont(), verbosity = 0, kwargs...) where {T, L <: BK.AbstractLinearSolver, E <: BK.AbstractEigenSolver} it = BK.ContIterable(prob, alg, contParams; finalise_solution = finalise_solution, callback_newton = callback_newton, normC = normC, verbosity = verbosity, plot = plot) # the keyword argument is to overwrite verbosity behaviour, like when locating bifurcations verbose = verbosity > 0 p₀ = BK.getparam(prob) nmax = contParams.max_steps # get parameters @unpack p_min, p_max, max_steps, newton_options, ds = contParams ϵFD = BK.getdelta(prob) # apply Newton algo to initial guess verbose && printstyled(color=:red, bold=true, ""*"─"^20*" ANM Method "*"─"^20*"\n") verbose && printstyled("━"^18*" INITIAL GUESS "*"━"^18, bold = true, color = :magenta) # we pass additional kwargs to newton so that it is sent to the newton callback sol₀ = newton(prob, newton_options; normN = normC, callback = callback_newton, iterationC = 0, p = p₀) @assert BK.converged(sol₀) "Newton failed to converge initial guess on the branch." verbose && (print("\n──▶ convergence of the initial guess = ");printstyled("OK\n", color=:green)) verbose && println("──▶ parameter = $(p₀), initial step") # define continuation state @unpack η, ds = contParams states = BK.iterate_from_two_points(it, sol₀.u, p₀, copy(sol₀.u), p₀ + ds / η; _verbosity = verbosity) # variable to hold the result from continuation, i.e. a branch contres = ContResult(it, states[1]) ######################## # η = T(1) # u_pred, fval, isconverged, itnewton = newton(F, dF, # u0, set(par, lens, p0 + ds / η), newton_options; normN = normC, callback = callback_newton, iterationC = 0, p = p0 + ds / η) # _U1 = BorderedArray(u_pred - u0, ds / η) # nrm = √(norm(_U1.u,2)^2 + _U1.p^2) # _U1.u ./= nrm; _U1.p /= nrm ######################## # compute jacobian and derivatives J = BK.jacobian(prob, sol₀.u, getparams(prob)) dFdp = (residual(prob, sol₀.u, BK.setparam(prob, p₀ + ϵFD)) .- residual(prob, sol₀.u, getparams(prob))) ./ ϵFD # compute initial tangent U1 = getTangent(J, dFdp, length(prob.u0), linear_algo) # initialize the vector of Taylor1 expansions n = length(prob.u0) a = Taylor1(T, alg.order) polu = Array{Taylor1{T}}(undef, n) polp = Taylor1([p₀, U1.p], alg.order) tmp = copy(prob.u0) for i in eachindex(sol₀.u) @inbounds polu[i] = Taylor1( [sol₀.u[i], U1.u[i]], alg.order ) end # continuation loop resu = Array{Taylor1{T}}[] resp = Taylor1{T}[] radius = Vector{T}(undef, 0) for ii = 1:nmax # J is fixed so we pass it taylorstep!(prob, J, dFdp, U1, tmp, polu, polp, linear_algo) # compute radius using that tmp contains Rk am = (alg.tol / normC(tmp)) ^ (1/alg.order) verbose && println("\n──▶ $ii, radius = $am, pmax = ", polp(am)) if isfinite(am) == false println("\n\n") @error "Radius is infinite" break end # save series push!(resu, deepcopy(polu)); push!(resp, deepcopy(polp)); push!(radius, am) # compute last point given by series _x0 = polu(am); _p0 = polp(am) # correct solution if needed verbose && printstyled("─"^70, bold = true) sol₀ = newton(re_make(prob, u0 = _x0, params = BK.setparam(prob, _p0)), newton_options; normN = normC, callback = callback_newton, iterationC = 0, p = _p0) if BK.converged(sol₀) == false println("\n\n") @error "\nNewton did not converged" break end # update derivatives J = BK.jacobian(prob, sol₀.u, getparams(sol₀.prob)) dFdp = (residual(prob, sol₀.u, BK.setparam(prob, _p0 + ϵFD)) .- residual(prob, sol₀.u, getparams(sol₀.prob))) ./ ϵFD # dFdp .= (F(u0, set(par, lens, _p0 + ϵFD)) .- F(u0, set(par, lens, _p0))) ./ ϵFD # compute tangent U1 = getTangent(J, dFdp, length(prob.u0), linear_algo) # update series with new values polp .*= 0; polu .*= 0 polp[0] = _p0; polp[1] = U1.p for ii in eachindex(polu) polu[ii][0] = sol₀.u[ii] polu[ii][1] = U1.u[ii] end if (contParams.p_min <= polp(am) <= contParams.p_max) == false @warn "Hitting boundary, polp(am) = $(polp(am))" break end end verbose && println("") save!(contres, it, states[1], resu, resp, radius) return ANMResult(resu, resp, radius, contres) end function getTangent(J, dFdp, n, linear_algo) T = eltype(dFdp) u1, p1, iscv, itlin = linear_algo(J, dFdp, rand(n), rand(), zeros(n), T(1)) ~iscv && @error "Initial tangent computation failed" nrm = √(dot(u1,u1) + p1^2) U1 = BorderedArray(u1./nrm, p1/nrm) end function taylorstep!(prob, J, dFdp, U1, tmp, polU, polp::Taylor1{T}, linear_algo) where T order = polp.order for ord in 2:order R = residual(prob, polU, BK.setparam(prob, polp)) # put Rk in tmp for ii in eachindex(tmp) tmp[ii] = R[ii][ord] end Uk, λk, iscv, itlin = linear_algo(J, dFdp, U1.u, U1.p, -tmp, T(0)) ~iscv && @warn "Bordered Linear solver did not converge" polp[ord] = λk for ii in eachindex(tmp) polU[ii][ord] = Uk[ii] end end end function BK.initialize!(state::BK.AbstractContinuationState, iter::BK.AbstractContinuationIterable, alg::ANM, nrm = false) return nothing end function _contresult(prob, alg, contParams::ContinuationPar, τ; recordFromSolution, get_eigen_elements ) x0 = prob.u0 par0 = getparams(prob) pt = recordFromSolution(x0, 0.) pts = BK.mergefromuser(pt, (param = 0.0, am = 0.0, ip = 1, itnewton = 0, ds = 0., step = 0, n_imag = 0, n_unstable = 0, stable = false)) if BK.compute_eigen_elements(contParams) eiginfo = get_eigen_elements(0.0, 1) _, n_unstable, n_imag = BK.isStable(contParams, eiginfo[1]) return BK._contresult(prob, alg, pt, pts, x0, τ, eiginfo, contParams, true, BK.EquilibriumCont()) else eiginfo = (Complex{eltype(x0)}(0), nothing, false, 0) return BK._contresult(prob, alg, pt, pts, x0, τ, eiginfo, contParams, false, BK.EquilibriumCont()) end end function save!(contres, it, state, resu, resp, radius) state.converged = true state.step = 0 state.itnewton = 0 state.itlinear = 0 for ip in eachindex(radius) Sr = LinRange(0, radius[ip], 20) for (is, s) in pairs(Sr) # update state copyto!(state.z.u, resu[ip](s)) state.z_old.p = state.z.p state.z.p = resp[ip](s) if BK.compute_eigenelements(it) it_eigen = BK.compute_eigenvalues!(it, state) end state.step += 1 BK.save!(contres, it, state) if it.contparams.detect_bifurcation > 1 _isstable, n_unstable, n_imag = BifurcationKit.is_stable(it.contparams, state.eigvals) if BK.detect_bifurcation(state) status::Symbol = :guess interval = BK.getinterval(BK.getpreviousp(state), getp(state)) printstyled(color=:red, "──▶ Bifurcation at p ≈ $(resp[ip](s)), δ = ", n_unstable - contres.n_unstable[end-1] ,"\n") @debug interval if it.contparams.detect_bifurcation > 2 sbif, interval = locate_bifurcation(it, Sr[is-1], contres.n_unstable[end-1], s, n_unstable, ip, resu, resp; verbose = it.verbosity == 3) status = :converged end # save the bifurcation point _, bifpt = BK.get_bifurcation_type(it, state, status, interval) if bifpt.type != :none; push!(contres.specialpoint, bifpt); end end end end end end function get_eigen_elements(resu, resp, prob, _s::Number, _ip::Int, it) _J = jacobian(prob, resu[_ip](_s), BK.setparam(prob, resp[_ip](_s))) return it.contparams.newton_options.eigsolver(_J, it.contparams.nev) end function locate_bifurcation(it, _s1, _n1, _s2, _n2, _ip::Int, resu, resp; verbose = false) getinterval(a,b) = (min(a,b), max(a,b)) contparams = it.contparams # interval which contains the bifurcation point interval = getinterval(resp[_ip](_s1), resp[_ip](_s2)) indinterval = 2 # index of active bound in the bisection, allows to track interval # we compute the number of changes in n_unstable n_inversion = 0 stepBis = 0 local s = (_s2 + _s1)/2 δs = (_s2 - _s1)/2 n_pred = _n1 n_unstable = _n1 biflocated = true while stepBis < contparams.max_bisection_steps eiginfo = get_eigen_elements(resu, resp, it.prob, s, _ip, it) isstable, n_unstable, n_imag = BifurcationKit.is_stable(contparams, eiginfo[1]) if n_pred == n_unstable δs /= 2 else δs /= -2 n_inversion += 1 indinterval = (indinterval == 2) ? 1 : 2 end stepBis > 0 && (interval = @set interval[indinterval] = resp[_ip](s)) verbose && printstyled(color=:blue, "────▶ $(stepBis) - [Loc-Bif] (n1, nc, n2) = ",(_n1, n_unstable, _n2), ", p = ", resp[_ip](s), ", s = $s, #reverse = ", n_inversion, "\n────▶ bifurcation ∈ ", getinterval(interval...), ", precision = ", interval[2] - interval[1], "\n────▶ 5 Eigenvalues closest to ℜ=0:\n") verbose && Base.display(BifurcationKit.closesttozero(eiginfo[1])[1:min(5, 2)]) biflocated = abs(real.(BifurcationKit.closesttozero(eiginfo[1]))[1]) < it.contparams.tol_bisection_eigenvalue if (abs(s) >= contparams.dsmin_bisection && stepBis < contparams.max_bisection_steps && n_inversion < contparams.n_inversion && biflocated == false) == false break end n_pred = n_unstable s += δs stepBis += 1 end verbose && printstyled(color=:red, "────▶ Found at p = ", resp[_ip](s), ", δn = ", abs(2n_unstable-_n1-_n2)," from p = ",resp[_ip](_s2),"\n") return s, getinterval(interval...) end
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
127
BK.get_normal_form1d(br::ANMResult, ind_bif::Int; kwargs...) = BK.get_normal_form1d(BK.get_contresult(br), ind_bif; kwargs...)
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
code
1787
RecipesBase.@recipe function Plots(br::ANMResult; plotfold = false, putspecialptlegend = true, filterspecialpoints = false, vars = nothing, plotstability = true, plotspecialpoints = true, branchlabel = "", linewidthunstable = 1.0, linewidthstable = 2linewidthunstable, plotcirclesbif = false, applytoY = identity, applytoX = identity, plotseries = false) contres = br.branch record_from_solution = BK.record_from_solution(contres.prob) ind1, ind2 = BK.get_plot_vars(contres, vars) if plotseries prob = br.branch.prob for ii in eachindex(br.polU) s = LinRange(-0 * br.radius[ii], br.radius[ii], 20) @series begin label --> "" linewidth --> 5 markerstrokewidth --> 0 map(applytoX, [br.polp[ii].(s)]), map(applytoY, [getproperty( BK.namedprintsol(record_from_solution(br.polU[ii](_s), BK.setparam(prob, br.polp[ii].(s)))), ind2) for _s in s]) end end end @series begin putspecialptlegend --> false plotfold --> plotfold plotspecialpoints --> plotspecialpoints plotstability --> plotstability branchlabel --> branchlabel linewidthunstable --> linewidthunstable linewidthstable --> linewidthstable applytoX --> applytoX applytoY --> applytoY vars --> vars contres end end
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.2.0
a39578fb466dbe1d6cec89dbc56ab990191cfa40
docs
2002
# AsymptoticNumericalMethod.jl | **Documentation** | **Build Status** | |:-------------------------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------:| | [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://bifurcationkit.github.io/BifurcationKitDocs.jl/dev) | [![Build status](https://github.com/rveltz/AsymptoticNumericalMethod.jl/workflows/CI/badge.svg)](https://github.com/rveltz/AsymptoticNumericalMethod.jl/actions) [![codecov](https://codecov.io/gh/bifurcationkit/AsymptoticNumericalMethod.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/bifurcationkit/AsymptoticNumericalMethod.jl) | This Julia package provides the numerical continuation algorithm **Asymptotic Numerical Method** (ANM) which is to be used with [BifurcationKit.jl](https://github.com/bifurcationkit/BifurcationKit.jl). ## Support and citation If you use this package for your work, we ask that you cite the following paper. Open source development as part of academic research strongly depends on this. Please also consider starring this repository if you like our work, this will help us to secure funding in the future. It is referenced on HAL-Inria as follows: ``` @misc{veltz:hal-02902346, TITLE = {{BifurcationKit.jl}}, AUTHOR = {Veltz, Romain}, URL = {https://hal.archives-ouvertes.fr/hal-02902346}, INSTITUTION = {{Inria Sophia-Antipolis}}, YEAR = {2020}, MONTH = Jul, KEYWORDS = {pseudo-arclength-continuation ; periodic-orbits ; floquet ; gpu ; bifurcation-diagram ; deflation ; newton-krylov}, PDF = {https://hal.archives-ouvertes.fr/hal-02902346/file/354c9fb0d148262405609eed2cb7927818706f1f.tar.gz}, HAL_ID = {hal-02902346}, HAL_VERSION = {v1}, } ``` ## Installation To install it, please run `] add AsymptoticNumericalMethod`
AsymptoticNumericalMethod
https://github.com/bifurcationkit/AsymptoticNumericalMethod.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
2994
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ module GeoStatsProcessesImageQuiltingExt using Tables using Random using Meshes using GeoTables using GeoStatsBase: initbuff using ImageQuilting: iqsim using GeoStatsProcesses: RandSetup using GeoStatsProcesses: QuiltingProcess, DefaultRandMethod import GeoStatsProcesses: randprep, randsingle function randprep(::AbstractRNG, process::QuiltingProcess, ::DefaultRandMethod, setup::RandSetup) # retrieve domain info sdomain = setup.domain simsize = size(sdomain) lin2cart = CartesianIndices(simsize) Dim = embeddim(sdomain) # retrieve process paramaters TI = process.trainimg init = process.init # default overlap overlap = isnothing(process.overlap) ? ntuple(i -> 1 / 6, Dim) : process.overlap # initialize buffers for realization and simulation mask vars = Dict(zip(setup.varnames, setup.vartypes)) buff, mask = initbuff(sdomain, vars, init, data=setup.geotable) pairs = map(setup.varnames) do var # training image as simple array trainimg = asarray(TI, var) # create soft data object soft = if !isnothing(process.soft) data, dataTI = process.soft @assert domain(data) == sdomain "incompatible soft data for target domain" @assert domain(dataTI) == domain(TI) "incompatible soft data for training image" schema = Tables.schema(values(data)) schemaTI = Tables.schema(values(dataTI)) vars = schema.names |> collect |> sort varsTI = schemaTI.names |> collect |> sort @assert vars == varsTI "variables for target domain and training image differ" [(asarray(data, var), asarray(dataTI, var)) for var in vars] else [] end # create hard data object linds = findall(mask[var]) cinds = [lin2cart[ind] for ind in linds] hvals = view(buff[var], linds) hard = Dict{CartesianIndex{Dim},Real}() for (ind, val) in zip(cinds, hvals) push!(hard, ind => val) end # disable inactive voxels if !isnothing(process.inactive) for icoords in process.inactive push!(hard, icoords => NaN) end end var => (trainimg, simsize, overlap, soft, hard) end Dict(pairs) end function randsingle(rng::AbstractRNG, process::QuiltingProcess, ::DefaultRandMethod, setup::RandSetup, prep) pairs = map(setup.varnames) do var # unpack parameters threads = setup.threads (; tilesize, path, tol) = process trainimg, simsize, overlap, soft, hard = prep[var] # run image quilting core function reals = iqsim( trainimg, tilesize, simsize; overlap, path, soft, hard, tol, threads, rng ) # replace NaN with missing vals = [isnan(v) ? missing : v for v in reals[1]] # flatten result var => vec(vals) end Dict(pairs) end end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1710
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ module GeoStatsProcessesStratiGraphicsExt using Random using Meshes using StratiGraphics: LandState, Strata, simulate, voxelize using GeoStatsProcesses: RandSetup using GeoStatsProcesses: StrataProcess, DefaultRandMethod import GeoStatsProcesses: randprep, randsingle function randprep(::AbstractRNG, process::StrataProcess, ::DefaultRandMethod, setup::RandSetup) # retrieve domain info domain = setup.domain @assert embeddim(domain) == 3 "process implemented for 3D domain only" pairs = map(setup.varnames) do var # determine initial state state = if isnothing(process.state) nx, ny, _ = size(domain) land = zeros(nx, ny) LandState(land) else process.state end # save preprocessed input var => state end Dict(pairs) end function randsingle(::AbstractRNG, process::StrataProcess, ::DefaultRandMethod, setup::RandSetup, prep) # retrieve domain info domain = setup.domain _, __, nz = size(domain) # retrieve process parameters (; environment, stack, nepochs) = process pairs = map(setup.varnames) do var # get parameters for the variable state = prep[var] # simulate the environment record = simulate(environment, state, nepochs) # build stratigraphy strata = Strata(record, stack) # return voxel model model = voxelize(strata, nz) # replace NaN with missing vals = [isnan(v) ? missing : v for v in model] # flatten result var => vec(vals) end Dict(pairs) end end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1952
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ module GeoStatsProcessesTuringPatternsExt using Random using Meshes using TuringPatterns: BoxBlur, Clamp, SimplePattern, Sim using TuringPatterns: Params, step!, scale01 using GeoStatsProcesses: RandSetup using GeoStatsProcesses: TuringProcess, DefaultRandMethod import GeoStatsProcesses: randprep, randsingle const PARAMS1 = [Params(2, 4, 0.01), Params(5, 10, 0.02), Params(10, 20, 0.03), Params(20, 40, 0.04), Params(50, 100, 0.05)] function randprep(::AbstractRNG, process::TuringProcess, ::DefaultRandMethod, setup::RandSetup) # retrieve domain of simulation domain = setup.domain topo = topology(domain) # assert grid topology @assert topo isa GridTopology "process only defined over grid topology" # retrieve simulation size sz = size(topo) # retrieve simulation parameters params = isnothing(process.params) ? PARAMS1 : process.params pairs = map(setup.varnames) do var # construct patterns from parameters patterns = [SimplePattern(param, sz) for param in params] var => patterns end Dict(pairs) end function randsingle(::AbstractRNG, process::TuringProcess, ::DefaultRandMethod, setup::RandSetup, prep) # retrieve domain size sz = size(topology(setup.domain)) # retrieve process parameters blur = isnothing(process.blur) ? BoxBlur(sz) : process.blur(sz) edge = isnothing(process.edge) ? Clamp() : process.edge() iter = process.iter pairs = map(setup.vartypes, setup.varnames) do V, var # unpack preprocessed parameters patterns = prep[var] # perform simulation sim = Sim(rand(V, sz), patterns, edge, blur) for _ in 1:iter step!(sim) end real = scale01(sim.fluid) # flatten result var => vec(real) end Dict(pairs) end end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1036
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ module GeoStatsProcesses using Meshes using Unitful using GeoTables using GeoStatsFunctions using GeoStatsModels using FFTW using CpuId using Tables using Distances using Distributions using ProgressMeter using Bessels: gamma using Random using Statistics using Distributed using LinearAlgebra using GeoStatsBase: Ensemble, integrate using GeoStatsBase: NearestInit, initbuff include("units.jl") include("ioutils.jl") include("processes.jl") include("operations.jl") export # point processes BinomialProcess, ClusterProcess, InhibitionProcess, PoissonProcess, UnionProcess, ishomogeneous, # point operations RandomThinning, thin, # field processes GaussianProcess, LindgrenProcess, QuiltingProcess, TuringProcess, StrataProcess, # field methods LUMethod, FFTMethod, SEQMethod end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
928
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ prettyname(obj) = prettyname(typeof(obj)) function prettyname(T::Type) name = string(T) name = replace(name, r"{.*" => "") replace(name, r".*\." => "") end printfields(io, obj; kwargs...) = printfields(io, obj, fieldnames(typeof(obj)); kwargs...) function printfields(io, obj, fnames; singleline=false) if singleline vals = map(enumerate(fnames)) do (i, field) val = getfield(obj, i) str = repr(val, context=io) "$field: $str" end join(io, vals, ", ") else len = length(fnames) for (i, field) in enumerate(fnames) div = i == len ? "\n└─ " : "\n├─ " val = getfield(obj, i) str = repr(val, context=io) print(io, "$div$field: $str") end end end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1276
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ ThinningMethod A method for thinning spatial point processes and patterns. """ abstract type ThinningMethod end """ thin(process, method) Thin spatial point `process` with thinning `method`. """ function thin end #----------------- # IMPLEMENTATIONS #----------------- include("thinning/random.jl") #--------------- # PROCESS UNION #--------------- """ p₁ ∪ p₂ Return the union of point processes `p₁` and `p₂`. """ Base.union(p₁::PointProcess, p₂::PointProcess) = UnionProcess(p₁, p₂) Base.union(p₁::PoissonProcess{<:Real}, p₂::PoissonProcess{<:Real}) = PoissonProcess(p₁.λ + p₂.λ) Base.union(p₁::PoissonProcess{<:Function}, p₂::PoissonProcess{<:Function}) = PoissonProcess(x -> p₁.λ(x) + p₂.λ(x)) Base.union(p₁::PoissonProcess{<:Real}, p₂::PoissonProcess{<:Function}) = PoissonProcess(x -> p₁.λ + p₂.λ(x)) Base.union(p₁::PoissonProcess{<:Function}, p₂::PoissonProcess{<:Real}) = PoissonProcess(x -> p₁.λ(x) + p₂.λ) Base.union(p₁::PoissonProcess{<:AbstractVector}, p₂::PoissonProcess{<:AbstractVector}) = PoissonProcess(x -> p₁.λ + p₂.λ)
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1332
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ GeoStatsProcess A geostatistical process that can be simulated with the `rand` function. """ abstract type GeoStatsProcess end """ RandMethod A `rand` method for geostatistical processes. """ abstract type RandMethod end """ DefaultRandMethod() Default `rand` method used by some geostatistical processes. """ struct DefaultRandMethod <: RandMethod end """ defaultmethod(process, setup) -> RandMethod Returns the default method for the `process` and `setup`. """ defaultmethod(process, setup) = DefaultRandMethod() # ---------------- # IMPLEMENTATIONS # ---------------- include("processes/point.jl") include("processes/field.jl") # ----------- # IO METHODS # ----------- Base.summary(io::IO, process::GeoStatsProcess) = print(io, prettyname(process)) function Base.show(io::IO, process::GeoStatsProcess) name = prettyname(process) ioctx = IOContext(io, :compact => true) print(io, "$name(") printfields(ioctx, process, singleline=true) print(io, ")") end function Base.show(io::IO, ::MIME"text/plain", process::GeoStatsProcess) summary(io, process) printfields(io, process) end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
297
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ const Len{T} = Quantity{T,u"𝐋"} addunit(x::Number, u) = x * u addunit(x::Quantity, _) = x
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
4253
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ FieldProcess <: GeoStatsProcess Parent type of all field processes. """ abstract type FieldProcess <: GeoStatsProcess end """ rand([rng], process::FieldProcess, domain, data, [nreals], [method]; [parameters]) Generate one or `nreals` realizations of the field `process` with `method` over the `domain` with `data` and optional `paramaters`. Optionally, specify the random number generator `rng` and global `parameters`. The `data` can be a geotable, a pair, or an iterable of pairs of the form `var => T`, where `var` is a symbol or string with the variable name and `T` is the corresponding data type. ## Parameters * `workers` - Worker processes (default to `[myid()]`) * `threads` - Number of threads (default to `cpucores()`) * `verbose` - Show progress and other information (default to `true`) # Examples ```julia julia> rand(process, domain, geotable, 3) julia> rand(process, domain, :z => Float64) julia> rand(process, domain, "z" => Float64) julia> rand(process, domain, [:a => Float64, :b => Float64]) julia> rand(process, domain, ["a" => Float64, "b" => Float64]) ``` """ Base.rand(process::FieldProcess, domain::Domain, data, method=nothing; kwargs...) = rand(Random.default_rng(), process, domain, data, method; kwargs...) Base.rand(process::FieldProcess, domain::Domain, data, nreals::Int, method=nothing; kwargs...) = rand(Random.default_rng(), process, domain, data, nreals, method; kwargs...) function Base.rand( rng::AbstractRNG, process::FieldProcess, domain::Domain, data, method=nothing; threads=cpucores() ) setup = randsetup(domain, data, threads) rmethod = isnothing(method) ? defaultmethod(process, setup) : method prep = randprep(rng, process, rmethod, setup) real = randsingle(rng, process, rmethod, setup, prep) table = (; (var => real[var] for var in setup.varnames)...) georef(table, domain) end function Base.rand( rng::AbstractRNG, process::FieldProcess, domain::Domain, data, nreals::Int, method=nothing; workers=[myid()], threads=cpucores(), verbose=true ) # perform preprocessing step setup = randsetup(domain, data, threads) rmethod = isnothing(method) ? defaultmethod(process, setup) : method prep = randprep(rng, process, rmethod, setup) # pool of worker processes pool = CachingPool(workers) # simulation loop reals = if verbose pname = prettyname(process) mname = prettyname(rmethod) vname = join(setup.varnames, " ,", " and ") message = "$pname with $mname → $vname" @showprogress desc = message pmap(pool, 1:nreals) do _ randsingle(rng, process, rmethod, setup, prep) end else pmap(pool, 1:nreals) do _ randsingle(rng, process, rmethod, setup, prep) end end varreals = (; (var => [real[var] for real in reals] for var in setup.varnames)...) Ensemble(domain, varreals) end struct RandSetup{D<:Domain,T} domain::D geotable::T varnames::Vector{Symbol} vartypes::Vector{DataType} threads::Int end function randsetup(domain::Domain, data, threads) geotable, names, types = _extract(data) RandSetup(domain, geotable, collect(names), collect(types), threads) end function _extract(geotable::AbstractGeoTable) schema = Tables.schema(values(geotable)) geotable, schema.names, schema.types end _extract(pair::Pair{Symbol,DataType}) = nothing, [first(pair)], [last(pair)] _extract(pair::Pair{T,DataType}) where {T<:AbstractString} = nothing, [Symbol(first(pair))], [last(pair)] _extract(pairs) = _extract(eltype(pairs), pairs) _extract(::Type{Pair{Symbol,DataType}}, pairs) = nothing, first.(pairs), last.(pairs) _extract(::Type{Pair{T,DataType}}, pairs) where {T<:AbstractString} = nothing, Symbol.(first.(pairs)), last.(pairs) _extract(::Type, pairs) = throw(ArgumentError("the data argument must be a geotable, a pair, or an iterable of pairs")) #----------------- # IMPLEMENTATIONS #----------------- include("field/gaussian.jl") include("field/lindgren.jl") include("field/quilting.jl") include("field/turing.jl") include("field/strata.jl")
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1405
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ PointProcess <: GeoStatsProcess Parent type of all point processes. """ abstract type PointProcess <: GeoStatsProcess end """ ishomogeneous(process::PointProcess) Tells whether or not the spatial point process `process` is homogeneous. """ ishomogeneous(process::PointProcess) = false """ rand([rng], process::PointProcess, geometry, [nreals]) rand([rng], process::PointProcess, domain, [nreals]) Generate one or `nreals` realizations of the point `process` inside `geometry` or `domain`. Optionally specify the random number generator `rng`. """ Base.rand(process::PointProcess, geomdom) = rand(Random.default_rng(), process, geomdom) Base.rand(process::PointProcess, geomdom, nreals::Int) = rand(Random.default_rng(), process, geomdom, nreals) Base.rand(rng::AbstractRNG, process::PointProcess, geomdom) = randsingle(rng, process, geomdom) Base.rand(rng::AbstractRNG, process::PointProcess, geomdom, nreals::Int) = [randsingle(rng, process, geomdom) for _ in 1:nreals] #----------------- # IMPLEMENTATIONS #----------------- include("point/binomial.jl") include("point/poisson.jl") include("point/inhibition.jl") include("point/cluster.jl") include("point/union.jl")
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
956
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ GaussianProcess(variogram=GaussianVariogram(), mean=0.0) Gaussian process with given theoretical `variogram` and global `mean`. """ struct GaussianProcess{V,T} <: FieldProcess variogram::V mean::T end GaussianProcess(variogram) = GaussianProcess(variogram, 0.0) GaussianProcess() = GaussianProcess(GaussianVariogram(), 0.0) #--------- # METHODS #--------- include("gaussian/lu.jl") include("gaussian/fft.jl") include("gaussian/seq.jl") function defaultmethod(process::GaussianProcess, setup::RandSetup) γ = process.variogram d = setup.domain p = parent(d) b = boundingbox(p) if p isa Grid && range(γ) ≤ minimum(sides(b)) / 3 FFTMethod() elseif nelements(d) < 100 * 100 LUMethod() else SEQMethod() end end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
3932
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ LindgrenProcess(range=1.0, sill=1.0; init=NearestInit()) Lindgren process with given `range` (correlation length) and `sill` (total variance) as described in Lindgren 2011. Optionally, specify the data initialization method `init`. The process relies relies on a discretization of the Laplace-Beltrami operator on meshes and is adequate for highly curved domains (e.g. surfaces). ## References * Lindgren et al. 2011. [An explicit link between Gaussian fields and Gaussian Markov random fields: the stochastic partial differential equation approach](https://rss.onlinelibrary.wiley.com/doi/10.1111/j.1467-9868.2011.00777.x) """ struct LindgrenProcess{ℒ<:Len,V,I} <: FieldProcess range::ℒ sill::V init::I LindgrenProcess(range::ℒ, sill::V, init::I) where {ℒ<:Len,V,I} = new{float(ℒ),float(V),I}(range, sill, init) end LindgrenProcess(range=1.0u"m", sill=1.0; init=NearestInit()) = LindgrenProcess(addunit(range, u"m"), sill, init) function randprep(::AbstractRNG, process::LindgrenProcess, ::DefaultRandMethod, setup::RandSetup) # retrieve setup paramaters (; domain, geotable, varnames, vartypes) = setup # retrieve sill and range 𝓁 = process.range σ = process.sill # retrieve initialization method init = process.init # sanity checks @assert domain isa Mesh "domain must be a `Mesh`" @assert 𝓁 > zero(𝓁) "range must be positive" @assert σ > zero(σ) "sill must be positive" # Laplace-Beltrami operator W = laplacematrix(domain) M = measurematrix(domain) Δ = inv(M) * W # retrieve parametric dimension d = paramdim(domain) # LHS of SPDE (κ² - Δ)Z = τW with Δ = M⁻¹W α = 2 ν = α - d / 2 κ = 1 / 𝓁 A = κ^2 * I - Δ # Matérn precision matrix τ² = σ^2 * κ^(2ν) * (4π)^(d / 2) * gamma(α) / gamma(ν) Q = ustrip.(A'A / τ²) # factorization F = cholesky(Array(Q)) L = inv(Array(F.U)) # initialize buffers for realizations and simulation mask pset = PointSet(vertices(domain)) vars = Dict(zip(varnames, vartypes)) buff, mask = initbuff(pset, vars, init, data=geotable) # result of preprocessing pairs = map(varnames) do var # retrieve buffer and mask for variable z = buff[var] m = mask[var] # retrieve data locations and data values i₁ = findall(m) z₁ = view(z, i₁) # retrieve simulation locations i₂ = setdiff(1:nvertices(domain), i₁) # interpolate at simulation locations if necessary z̄ = if isempty(i₁) nothing else z[i₂] .= -Q[i₂,i₂] \ (Q[i₂,i₁] * z₁) z end # save preprocessed inputs for variable var => (; Q, L, i₁, i₂, z̄) end Dict(pairs) end function randsingle(rng::AbstractRNG, ::LindgrenProcess, ::DefaultRandMethod, setup::RandSetup, prep) # retrieve setup paramaters (; domain, geotable, varnames, vartypes) = setup # simulation at vertices varreal = map(varnames, vartypes) do var, V # unpack preprocessed parameters (; Q, L, i₁, i₂, z̄) = prep[var] # unconditional realization w = randn(rng, V, nvertices(domain)) zᵤ = L * w # perform conditioning if necessary z = if isempty(i₁) zᵤ # we are all set else # view realization at data locations zᵤ₁ = view(zᵤ, i₁) # interpolate at simulation locations z̄ᵤ = similar(zᵤ) zᵤ₂ = -Q[i₂,i₂] \ (Q[i₂,i₁] * zᵤ₁) z̄ᵤ[i₁] .= zᵤ₁ z̄ᵤ[i₂] .= zᵤ₂ # add residual field z̄ .+ (zᵤ .- z̄ᵤ) end var => z end # vertex table vtable = (; varreal...) # change of support vdata = GeoTable(domain; vtable) edata = integrate(vdata, varnames...) # columns of element table cols = Tables.columns(values(edata)) Dict(var => Tables.getcolumn(cols, var) for var in varnames) end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1658
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ QuiltingProcess(trainimg, tilesize; [paramaters]) Image quilting process with training image `trainimg` and tile size `tilesize` as described in Hoffimann et al. 2017. ## Parameters * `overlap` - Overlap size (default to (1/6, 1/6, ..., 1/6)) * `path` - Process path (`:raster` (default), `:dilation`, or `:random`) * `inactive` - Vector of inactive voxels (i.e. `CartesianIndex`) in the grid * `soft` - A pair `(data,dataTI)` of geospatial data objects (default to `nothing`) * `tol` - Initial relaxation tolerance in (0,1] (default to `0.1`) * `init` - Data initialization method (default to `NearestInit()`) ## References * Hoffimann et al 2017. [Stochastic simulation by image quilting of process-based geological models](https://www.sciencedirect.com/science/article/abs/pii/S0098300417301139) * Hoffimann et al 2015. [Geostatistical modeling of evolving landscapes by means of image quilting](https://www.researchgate.net/publication/295902985_Geostatistical_Modeling_of_Evolving_Landscapes_by_Means_of_Image_Quilting) """ struct QuiltingProcess{TR,TS,O,P,IN,S,T,I} <: FieldProcess trainimg::TR tilesize::TS overlap::O path::P inactive::IN soft::S tol::T init::I end QuiltingProcess( trainimg, tilesize; overlap=nothing, path=:raster, inactive=nothing, soft=nothing, tol=0.1, init=NearestInit() ) = QuiltingProcess(trainimg, tilesize, overlap, path, inactive, soft, tol, init)
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
926
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ StrataProcess(environment; [paramaters]) Strata process with given geological `environment` as described in Hoffimann 2018. ## Parameters * `state` - Initial geological state * `stack` - Stacking scheme (:erosional or :depositional) * `nepochs` - Number of epochs (default to 10) ## References * Hoffimann 2018. [Morphodynamic analysis and statistical synthesis of geormorphic data](https://agupubs.onlinelibrary.wiley.com/doi/full/10.1029/2019JF005245) """ struct StrataProcess{E,S,ST,N} <: FieldProcess environment::E state::S stack::ST nepochs::N end StrataProcess(environment; state=nothing, stack=:erosional, nepochs=10) = StrataProcess(environment, state, stack, nepochs)
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
854
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ TuringProcess(; [paramaters]) Turing process as described in Turing 1952. ## Parameters * `params` - basic parameters (default to `nothing`) * `blur` - blur algorithm (default to `nothing`) * `edge` - edge condition (default to `nothing`) * `iter` - number of iterations (default to `100`) ## References * Turing 1952. [The chemical basis of morphogenesis](https://royalsocietypublishing.org/doi/10.1098/rstb.1952.0012) """ struct TuringProcess{P,B,E,I} <: FieldProcess params::P blur::B edge::E iter::I end TuringProcess(; params=nothing, blur=nothing, edge=nothing, iter=100) = TuringProcess(params, blur, edge, iter)
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
4713
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ FFTMethod(; [paramaters]) The FFT Gaussian process method introduced by Gutjahr 1997. The covariance function is perturbed in the frequency domain after a fast Fourier transform. White noise is added to the phase of the spectrum, and a realization is produced by an inverse Fourier transform. ## Parameters * `minneighbors` - Minimum number of neighbors (default to `1`) * `maxneighbors` - Maximum number of neighbors (default to `10`) * `neighborhood` - Search neighborhood (default to `nothing`) * `distance` - Distance used to find nearest neighbors (default to `Euclidean()`) ## References * Gutjahr 1997. [General joint conditional simulations using a fast Fourier transform method](https://link.springer.com/article/10.1007/BF02769641) * Gómez-Hernández, J. & Srivastava, R. 2021. [One Step at a Time: The Origins of Sequential Simulation and Beyond](https://link.springer.com/article/10.1007/s11004-021-09926-0) ### Notes * The method is limited to simulations on Cartesian grids, and care must be taken to make sure that the correlation length is small enough compared to the grid size. * As a general rule of thumb, avoid correlation lengths greater than 1/3 of the grid. * The method is extremely fast, and can be used to generate large 3D realizations. """ @kwdef struct FFTMethod{N,D} <: RandMethod minneighbors::Int = 1 maxneighbors::Int = 10 neighborhood::N = nothing distance::D = Euclidean() end function randprep(::AbstractRNG, process::GaussianProcess, method::FFTMethod, setup::RandSetup) # retrive variogram model and mean γ = process.variogram μ = process.mean # check stationarity if !isstationary(γ) throw(ArgumentError("variogram model must be stationary")) end dom = setup.domain data = setup.geotable grid = parent(dom) dims = size(grid) center = CartesianIndex(dims .÷ 2) cindex = LinearIndices(dims)[center] # number of threads in FFTW FFTW.set_num_threads(setup.threads) # perform Kriging in case of conditional simulation pred = if isnothing(data) nothing else (; minneighbors, maxneighbors, neighborhood, distance) = method pred = GeoStatsModels.fitpredict(Kriging(γ, μ), data, dom; minneighbors, maxneighbors, neighborhood, distance) end pairs = map(setup.vartypes, setup.varnames) do V, var # compute covariances between centroid and all points 𝒟c = [centroid(grid, cindex)] 𝒟p = [centroid(grid, i) for i in 1:nelements(grid)] cs = sill(γ) .- GeoStatsFunctions.pairwise(γ, 𝒟c, 𝒟p) C = reshape(cs, dims) # move to frequency domain F = sqrt.(abs.(fft(fftshift(C)))) F[1] = zero(V) # set reference level # get variable prediction and data locations if necessary z̄, dinds = nothing, nothing if !isnothing(pred) z̄ = pred[:, var] # find data locations in target domain ddom = domain(data) searcher = KNearestSearch(dom, 1) found = [search(centroid(ddom, i), searcher) for i in 1:nelements(ddom)] dinds = unique(first.(found)) end # save preprocessed inputs for variable var => (; F, z̄, dinds) end Dict(pairs) end function randsingle(rng::AbstractRNG, process::GaussianProcess, method::FFTMethod, setup::RandSetup, prep) # retrieve domain info dom = setup.domain data = setup.geotable grid = parent(dom) inds = parentindices(dom) dims = size(grid) # retrive variogram model and mean γ = process.variogram μ = process.mean varreal = map(setup.vartypes, setup.varnames) do V, var # unpack preprocessed parameters (; F, z̄, dinds) = prep[var] # perturbation in frequency domain P = F .* exp.(im .* angle.(fft(rand(rng, V, dims)))) # move back to time domain Z = real(ifft(P)) # adjust mean and variance σ² = Statistics.var(Z, mean=zero(V)) Z .= √(sill(γ) / σ²) .* Z .+ μ # unconditional realization zᵤ = Z[inds] # perform conditioning if necessary z = if isnothing(data) zᵤ # we are all set else # view realization at data locations ktab = (; var => view(zᵤ, dinds)) kdom = view(dom, dinds) kdata = georef(ktab, kdom) # perform Kriging prediction (; minneighbors, maxneighbors, neighborhood, distance) = method pred = GeoStatsModels.fitpredict(Kriging(γ, μ), kdata, dom; minneighbors, maxneighbors, neighborhood, distance) z̄ᵤ = pred[:, var] # add residual field z̄ .+ (zᵤ .- z̄ᵤ) end var => z end Dict(varreal) end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
4716
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ LUMethod(; [paramaters]) The LU Gaussian process method introduced by Alabert 1987. The full covariance matrix is built to include all locations of the process domain, and samples from the multivariate Gaussian are drawn via LU factorization. ## Parameters * `factorization` - Factorization method (default to `cholesky`) * `correlation` - Correlation coefficient between two covariates (default to `0`) * `init` - Data initialization method (default to `NearestInit()`) ## References * Alabert 1987. [The practice of fast conditional simulations through the LU decomposition of the covariance matrix] (https://link.springer.com/article/10.1007/BF00897191) * Oliver 2003. [Gaussian cosimulation: modeling of the cross-covariance] (https://link.springer.com/article/10.1023%2FB%3AMATG.0000002984.56637.ef) ### Notes * The method is only adequate for domains with relatively small number of elements (e.g. 100x100 grids) where it is feasible to factorize the full covariance. * For larger domains (e.g. 3D grids), other methods are preferred such as [`SEQMethod`](@ref) and [`FFTMethod`](@ref). """ @kwdef struct LUMethod{F,C,I} <: FieldProcess factorization::F = cholesky correlation::C = 0.0 init::I = NearestInit() end function randprep(::AbstractRNG, process::GaussianProcess, method::LUMethod, setup::RandSetup) # retrieve setup paramaters (; domain, geotable, varnames, vartypes) = setup # check the number of variables nvars = length(varnames) @assert nvars ∈ (1, 2) "only 1 or 2 variables can be simulated simultaneously" # check process paramaters _checkparam(process.variogram, nvars) _checkparam(process.mean, nvars) # retrieve method parameters fact = method.factorization init = method.init # initialize buffers for realizations and simulation mask vars = Dict(zip(varnames, vartypes)) buff, mask = initbuff(domain, vars, init, data=geotable) # preprocess parameters for individual variables pairs = map(enumerate(varnames)) do (i, var) # get variable specific parameters γ = _getparam(process.variogram, i) μ = _getparam(process.mean, i) # check stationarity @assert isstationary(γ) "variogram model must be stationary" # retrieve data locations and data values in domain dlocs = findall(mask[var]) z₁ = view(buff[var], dlocs) # retrieve simulation locations slocs = setdiff(1:nelements(domain), dlocs) # create views of the domain 𝒟d = [centroid(domain, i) for i in dlocs] 𝒟s = [centroid(domain, i) for i in slocs] # covariance between simulation locations C₂₂ = sill(γ) .- GeoStatsFunctions.pairwise(γ, 𝒟s) if isempty(dlocs) d₂ = zero(eltype(z₁)) L₂₂ = fact(Symmetric(C₂₂)).L else # covariance beween data locations C₁₁ = sill(γ) .- GeoStatsFunctions.pairwise(γ, 𝒟d) C₁₂ = sill(γ) .- GeoStatsFunctions.pairwise(γ, 𝒟d, 𝒟s) L₁₁ = fact(Symmetric(C₁₁)).L B₁₂ = L₁₁ \ C₁₂ A₂₁ = B₁₂' d₂ = A₂₁ * (L₁₁ \ z₁) L₂₂ = fact(Symmetric(C₂₂ - A₂₁ * B₁₂)).L end # save preprocessed parameters for variable var => (z₁, d₂, L₂₂, μ, dlocs, slocs) end Dict(pairs) end function randsingle(rng::AbstractRNG, ::GaussianProcess, method::LUMethod, setup::RandSetup, prep) # list of variable names vars = setup.varnames # simulate first variable v₁ = first(vars) Y₁, w₁ = _lusim(rng, prep[v₁]) varreal = Dict(v₁ => Y₁) # simulate second variable if length(vars) == 2 ρ = method.correlation v₂ = last(vars) Y₂, _ = _lusim(rng, prep[v₂], ρ, w₁) push!(varreal, v₂ => Y₂) end varreal end #----------- # UTILITIES #----------- function _checkparam(param, nvars) if param isa Tuple @assert length(param) == nvars "the number of parameters must be equal to the number of variables" end end _getparam(param, i) = param _getparam(params::Tuple, i) = params[i] function _lusim(rng, params, ρ=nothing, w₁=nothing) # unpack parameters z₁, d₂, L₂₂, μ, dlocs, slocs = params # number of points in domain npts = length(dlocs) + length(slocs) # allocate memory for result y = Vector{eltype(z₁)}(undef, npts) # conditional simulation w₂ = randn(rng, size(L₂₂, 2)) if isnothing(ρ) y₂ = d₂ .+ L₂₂ * w₂ else y₂ = d₂ .+ L₂₂ * (ρ * w₁ + √(1 - ρ^2) * w₂) end # hard data and simulated values y[dlocs] = z₁ y[slocs] = y₂ # adjust mean in case of unconditional simulation isempty(dlocs) && (y .+= μ) y, w₂ end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
5686
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ SEQMethod(; [paramaters]) The sequential process method introduced by Gomez-Hernandez 1993. It traverses all locations of the geospatial domain according to a path, approximates the conditional Gaussian distribution within a neighborhood using simple Kriging, and assigns a value to the center of the neighborhood by sampling from this distribution. ## Parameters * `path` - Process path (default to `LinearPath()`) * `minneighbors` - Minimum number of neighbors (default to `1`) * `maxneighbors` - Maximum number of neighbors (default to `36`) * `neighborhood` - Search neighborhood (default to `:range`) * `distance` - Distance used to find nearest neighbors (default to `Euclidean()`) * `init` - Data initialization method (default to `NearestInit()`) For each location in the process `path`, a maximum number of neighbors `maxneighbors` is used to fit the conditional Gaussian distribution. The neighbors are searched according to a `neighborhood`. The `neighborhood` can be a `MetricBall`, the symbol `:range` or `nothing`. The symbol `:range` is converted to `MetricBall(range(γ))` where `γ` is the variogram of the Gaussian process. If `neighborhood` is `nothing`, the nearest neighbors are used without additional constraints. ## References * Gomez-Hernandez & Journel 1993. [Joint Sequential Simulation of MultiGaussian Fields](https://link.springer.com/chapter/10.1007/978-94-011-1739-5_8) ### Notes * This method is very sensitive to the various parameters. Care must be taken to make sure that enough neighbors are used in the underlying Kriging model. """ @kwdef struct SEQMethod{P,N,D,I} <: RandMethod path::P = LinearPath() minneighbors::Int = 1 maxneighbors::Int = 36 # 6x6 grid cells neighborhood::N = :range distance::D = Euclidean() init::I = NearestInit() end function randprep(::AbstractRNG, process::GaussianProcess, method::SEQMethod, setup::RandSetup) # retrieve paramaters (; variogram, mean) = process (; minneighbors, maxneighbors, neighborhood, distance) = method # scale domains for numerical stability finv, dom, data = _scaledomains(setup) # scale variogram model accordingly gamma = GeoStatsFunctions.scale(variogram, finv) # scale neighborhood accordingly neigh = if neighborhood isa MetricBall finv * neighborhood elseif neighborhood == :range MetricBall(range(gamma)) else nothing end # determine probability model probmodel = GeoStatsModels.SimpleKriging(gamma, mean) marginal = Normal(mean, √sill(gamma)) # adjust min/max neighbors nobs = nelements(dom) if maxneighbors > nobs || maxneighbors < 1 maxneighbors = nobs end if minneighbors > maxneighbors || minneighbors < 1 minneighbors = 1 end # determine search method searcher = if isnothing(neigh) # nearest neighbor search with a metric KNearestSearch(dom, maxneighbors; metric=distance) else # neighbor search with ball neighborhood KBallSearch(dom, maxneighbors, neigh) end (; dom, data, probmodel, marginal, minneighbors, maxneighbors, searcher) end function randsingle(rng::AbstractRNG, ::GaussianProcess, method::SEQMethod, setup::RandSetup, prep) # retrieve parameters (; path, init) = method (; varnames, vartypes) = setup (; dom, data, probmodel, marginal, minneighbors, maxneighbors, searcher) = prep # initialize buffers for realization and simulation mask vars = Dict(zip(varnames, vartypes)) buff, mask = initbuff(dom, vars, init, data=data) # consider point set with centroids for now pointset = PointSet([centroid(dom, ind) for ind in 1:nelements(dom)]) varreals = map(varnames) do var # pre-allocate memory for neighbors neighbors = Vector{Int}(undef, maxneighbors) # retrieve realization and mask for variable realization = buff[var] simulated = mask[var] # simulation loop for ind in traverse(dom, path) if !simulated[ind] center = pointset[ind] # search neighbors with simulated data nneigh = search!(neighbors, center, searcher, mask=simulated) if nneigh < minneighbors # draw from marginal realization[ind] = rand(rng, marginal) else # neighborhood with data neigh = let ninds = view(neighbors, 1:nneigh) dom = view(pointset, ninds) val = view(realization, ninds) tab = (; var => val) georef(tab, dom) end # fit distribution probmodel fitted = GeoStatsModels.fit(probmodel, neigh) # draw from conditional or marginal distribution = if GeoStatsModels.status(fitted) GeoStatsModels.predictprob(fitted, var, center) else marginal end realization[ind] = rand(rng, distribution) end # mark location as simulated and continue simulated[ind] = true end end var => realization end Dict(varreals) end function _scaledomains(setup) sdom = setup.domain sdat = setup.geotable fdom = _scalefactor(sdom) fdat = isnothing(sdat) ? 1 : _scalefactor(domain(sdat)) fmax = max(fdom, fdat) finv = 1 / fmax func = Scale(finv) dom = func(sdom) dat = isnothing(sdat) ? nothing : func(sdat) finv, dom, dat end function _scalefactor(domain) pmin, pmax = extrema(boundingbox(domain)) cmin = abs.(to(pmin)) cmax = abs.(to(pmax)) ustrip(max(cmin..., cmax...)) end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
480
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ BinomialProcess(n) A Binomial point process with `n` points. """ struct BinomialProcess <: PointProcess n::Int end ishomogeneous(p::BinomialProcess) = true randsingle(rng::AbstractRNG, p::BinomialProcess, g) = PointSet(sample(rng, g, HomogeneousSampling(p.n)))
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1302
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ ClusterProcess(proc, ofun) A cluster process with parent process `proc` and offsprings generated with `ofun`. It is a function that takes a parent point and returns a point pattern from another point process. ClusterProcess(proc, offs, gfun) Alternatively, specify the parent process `proc`, the offspring process `offs` and the geometry function `gfun`. It is a function that takes a parent point and returns a geometry or domain for the offspring process. """ struct ClusterProcess{P<:PointProcess,F<:Function} <: PointProcess proc::P ofun::F end ClusterProcess(p::PointProcess, o::PointProcess, gfun::Function) = ClusterProcess(p, parent -> rand(o, gfun(parent))) function randsingle(rng::AbstractRNG, p::ClusterProcess, g) # generate parents parents = rand(rng, p.proc, g) # generate offsprings offsprings = filter(!isnothing, p.ofun.(parents)) # intersect with geometry intersects = filter(!isnothing, [o ∩ g for o in offsprings]) # combine offsprings into single set isempty(intersects) ? nothing : PointSet(mapreduce(collect, vcat, intersects)) end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
464
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ InhibitionProcess(δ) An inhibition point process with minimum distance `δ`. """ struct InhibitionProcess{D<:Real} <: PointProcess δ::D end randsingle(rng::AbstractRNG, p::InhibitionProcess, g) = PointSet(sample(rng, g, MinDistanceSampling(p.δ)))
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1986
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ PoissonProcess(λ) A Poisson process with intensity `λ`. For a homogeneous process, define `λ` as a constant real value, while for an inhomogeneous process, define `λ` as a function or vector of values. If `λ` is a vector, it is assumed that the process is associated with a `Domain` with the same number of elements as `λ`. """ struct PoissonProcess{L<:Union{Real,Function,AbstractVector}} <: PointProcess λ::L end ishomogeneous(p::PoissonProcess{<:Real}) = true ishomogeneous(p::PoissonProcess{<:Function}) = false ishomogeneous(p::PoissonProcess{<:AbstractVector}) = false #------------------ # HOMOGENEOUS CASE #------------------ function randsingle(rng::AbstractRNG, p::PoissonProcess{<:Real}, g) # simulate number of points λ = p.λ V = measure(g) n = rand(rng, Poisson(ustrip(λ * V))) # simulate n points iszero(n) ? nothing : PointSet(sample(rng, g, HomogeneousSampling(n))) end #-------------------- # INHOMOGENEOUS CASE #-------------------- function randsingle(rng::AbstractRNG, p::PoissonProcess{<:Function}, g) # upper bound for intensity λmax = _maxintensity(p, g) # simulate a homogeneous process pset = randsingle(rng, PoissonProcess(ustrip(λmax)), g) # thin point pattern isnothing(pset) ? nothing : thin(pset, RandomThinning(x -> p.λ(x) / λmax)) end function randsingle(rng::AbstractRNG, p::PoissonProcess{<:AbstractVector}, d::Domain) # simulate number of points λ = p.λ .* measure.(d) n = rand(rng, Poisson(ustrip(sum(λ)))) # simulate point pattern iszero(n) ? nothing : PointSet(sample(rng, d, HomogeneousSampling(n, λ))) end function _maxintensity(p::PoissonProcess{<:Function}, g) points = sample(g, HomogeneousSampling(10000)) λmin, λmax = extrema(p.λ, points) λmax + 0.05 * (λmax - λmin) end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
635
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ UnionProcess(p₁, p₂) Union (or superposition) of spatial point processes `p₁` and `p₂`. """ struct UnionProcess{P₁<:PointProcess,P₂<:PointProcess} <: PointProcess p₁::P₁ p₂::P₂ end ishomogeneous(p::UnionProcess) = ishomogeneous(p.p₁) && ishomogeneous(p.p₂) function randsingle(rng::AbstractRNG, p::UnionProcess, g) pp₁ = rand(rng, p.p₁, g) pp₂ = rand(rng, p.p₂, g) PointSet([collect(pp₁); collect(pp₂)]) end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
1545
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ """ RandomThinning(p) Random thinning with retention probability `p`, which can be a constant probability value in `[0,1]` or a function mapping a point to a probability. ## Examples ```julia RandomThinning(0.5) RandomThinning(p -> sum(to(p))) ``` """ struct RandomThinning{P<:Union{Real,Function}} <: ThinningMethod p::P end # ----------------------- # THINNING POINT PROCESS # ----------------------- thin(p::PoissonProcess{<:Real}, t::RandomThinning{<:Real}) = PoissonProcess(t.p * p.λ) thin(p::PoissonProcess{<:Function}, t::RandomThinning{<:Function}) = PoissonProcess(x -> t.p(x) * p.λ(x)) thin(p::PoissonProcess{<:Real}, t::RandomThinning{<:Function}) = PoissonProcess(x -> t.p(x) * p.λ) thin(p::PoissonProcess{<:Function}, t::RandomThinning{<:Real}) = PoissonProcess(x -> t.p * p.λ(x)) # ----------------------- # THINNING POINT PATTERN # ----------------------- function thin(pp::PointSet, t::RandomThinning{<:Real}) draws = rand(Bernoulli(t.p), nelements(pp)) inds = findall(isequal(1), draws) points = collect(view(pp, inds)) PointSet(points) end function thin(pp::PointSet, t::RandomThinning{<:Function}) inds = Vector{Int}() for j in 1:nelements(pp) x = element(pp, j) if rand(Bernoulli(t.p(x))) push!(inds, j) end end points = collect(view(pp, inds)) PointSet(points) end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
11222
@testset "FieldProcess" begin @testset "data argument" begin grid = CartesianGrid(10, 10) gtb = georef((; z=rand(100)), grid) # geotable setup = GeoStatsProcesses.randsetup(grid, gtb, 1) @test setup.geotable == gtb @test setup.varnames == [:z] @test setup.vartypes == [Float64] # pair setup = GeoStatsProcesses.randsetup(grid, :z => Float64, 1) @test isnothing(setup.geotable) @test setup.varnames == [:z] @test setup.vartypes == [Float64] setup = GeoStatsProcesses.randsetup(grid, "z" => Float64, 1) @test isnothing(setup.geotable) @test setup.varnames == [:z] @test setup.vartypes == [Float64] # iterable of pairs setup = GeoStatsProcesses.randsetup(grid, [:a => Float64, :b => Int], 1) @test isnothing(setup.geotable) @test setup.varnames == [:a, :b] @test setup.vartypes == [Float64, Int] setup = GeoStatsProcesses.randsetup(grid, ["a" => Float64, "b" => Int], 1) @test isnothing(setup.geotable) @test setup.varnames == [:a, :b] @test setup.vartypes == [Float64, Int] # error: invalid iterator @test_throws ArgumentError GeoStatsProcesses.randsetup(grid, [:a, :b], 1) end @testset "GaussianProcess" begin @testset "defaultmethod" begin grid = CartesianGrid(100, 100) vgrid = view(grid, 1:1000) pset1 = PointSet(rand(Point, 1000)) pset2 = PointSet(rand(Point, 10000)) process = GaussianProcess() setup = GeoStatsProcesses.randsetup(grid, :z => Float64, 1) @test GeoStatsProcesses.defaultmethod(process, setup) isa FFTMethod setup = GeoStatsProcesses.randsetup(vgrid, :z => Float64, 1) @test GeoStatsProcesses.defaultmethod(process, setup) isa FFTMethod setup = GeoStatsProcesses.randsetup(pset1, :z => Float64, 1) @test GeoStatsProcesses.defaultmethod(process, setup) isa LUMethod setup = GeoStatsProcesses.randsetup(pset2, :z => Float64, 1) @test GeoStatsProcesses.defaultmethod(process, setup) isa SEQMethod end @testset "FFTMethod" begin # isotropic simulation rng = StableRNG(2019) dom = CartesianGrid(100, 100) process = GaussianProcess(GaussianVariogram(range=10.0)) method = FFTMethod() sims = rand(rng, process, dom, :z => Float64, 3, method) @test eltype(sims[1].z) <: Float64 # anisotropic simulation rng = StableRNG(2019) dom = CartesianGrid(100, 100) process = GaussianProcess(GaussianVariogram(MetricBall((20.0, 5.0)))) method = FFTMethod() sims = rand(rng, process, dom, :z => Float64, 3, method) # simulation on view of grid rng = StableRNG(2022) grid = CartesianGrid(100, 100) vgrid = view(grid, 1:5000) process = GaussianProcess(GaussianVariogram(range=10.0)) method = FFTMethod() sim = rand(rng, process, vgrid, :z => Float64, method) @test domain(sim) == vgrid @test length(sim.geometry) == 5000 # conditional simulation rng = StableRNG(2022) table = (; z=[1.0, -1.0, 1.0]) coords = [(25.0, 25.0), (50.0, 75.0), (75.0, 50.0)] samples = georef(table, coords) sdomain = CartesianGrid(100, 100) process = GaussianProcess(GaussianVariogram(range=10.0)) method = FFTMethod(maxneighbors=3) sim = rand(rng, process, sdomain, samples, method) end @testset "SEQMethod" begin 𝒮 = georef((; z=[1.0, 0.0, 1.0]), [(25.0, 25.0), (50.0, 75.0), (75.0, 50.0)]) 𝒟 = CartesianGrid((100, 100), (0.5, 0.5), (1.0, 1.0)) N = 3 process = GaussianProcess(SphericalVariogram(range=35.0)) method = SEQMethod(neighborhood=MetricBall(30.0), maxneighbors=3) rng = StableRNG(2017) sims₁ = rand(rng, process, 𝒟, 𝒮, 3) sims₂ = rand(rng, process, 𝒟, :z => Float64, 3) @test eltype(sims₁[1].z) <: Float64 @test eltype(sims₂[1].z) <: Float64 # basic checks reals = sims₁[:z] inds = LinearIndices(size(𝒟)) @test all(reals[i][inds[25, 25]] == 1.0 for i in 1:N) @test all(reals[i][inds[50, 75]] == 0.0 for i in 1:N) @test all(reals[i][inds[75, 50]] == 1.0 for i in 1:N) end @testset "LUMethod" begin 𝒮 = georef((; z=[0.0, 1.0, 0.0, 1.0, 0.0]), [(0.0,), (25.0,), (50.0,), (75.0,), (100.0,)]) 𝒟 = CartesianGrid(100) # ---------------------- # conditional simulation # ---------------------- rng = StableRNG(123) process = GaussianProcess(SphericalVariogram(range=10.0)) method = LUMethod() sims = rand(rng, process, 𝒟, 𝒮, 2, method) @test eltype(sims[1].z) <: Float64 # ------------------------ # unconditional simulation # ------------------------ rng = StableRNG(123) process = GaussianProcess(SphericalVariogram(range=10.0)) method = LUMethod() sims = rand(rng, process, 𝒟, :z => Float64, 2, method) # ------------- # co-simulation # ------------- rng = StableRNG(123) 𝒟 = CartesianGrid(500) process = GaussianProcess((SphericalVariogram(range=10.0), GaussianVariogram(range=10.0))) method = LUMethod(correlation=0.95) sim = rand(rng, process, 𝒟, [:a => Float64, :b => Float64], method) # ----------- # 2D example # ----------- rng = StableRNG(123) 𝒟 = CartesianGrid(100, 100) process = GaussianProcess(GaussianVariogram(range=10.0)) method = LUMethod() sims = rand(rng, process, 𝒟, :z => Float64, 3, method) # ------------------- # anisotropy example # ------------------- rng = StableRNG(123) 𝒟 = CartesianGrid(100, 100) ball = MetricBall((20.0, 5.0)) process = GaussianProcess(GaussianVariogram(ball)) method = LUMethod() sims = rand(rng, process, 𝒟, :z => Float64, 3, method) # --------------------- # custom factorization # --------------------- rng = StableRNG(123) 𝒟 = CartesianGrid(100) process = GaussianProcess(SphericalVariogram(range=10.0)) method1 = LUMethod(factorization=lu) method2 = LUMethod(factorization=cholesky) sim1 = rand(rng, process, 𝒟, 𝒮, 2, method1) sim2 = rand(rng, process, 𝒟, 𝒮, 2, method2) # throws 𝒟 = CartesianGrid(100, 100) process = GaussianProcess(GaussianVariogram(range=10.0)) method = LUMethod() # only 1 or 2 variables can be simulated simultaneously @test_throws AssertionError rand(process, 𝒟, [:a => Float64, :b => Float64, :c => Float64], method) process = GaussianProcess((GaussianVariogram(range=10.0),)) # the number of parameters must be equal to the number of variables @test_throws AssertionError rand(process, 𝒟, [:a => Float64, :b => Float64], method) end @testset "show" begin process = GaussianProcess() @test sprint(show, process) == "GaussianProcess(variogram: GaussianVariogram(sill: 1.0, nugget: 0.0, range: 1.0 m, distance: Euclidean), mean: 0.0)" @test sprint(show, MIME("text/plain"), process) == """ GaussianProcess ├─ variogram: GaussianVariogram(sill: 1.0, nugget: 0.0, range: 1.0 m, distance: Euclidean) └─ mean: 0.0""" end end @testset "LindgrenProcess" begin process = LindgrenProcess() @test process.range == 1u"m" @test process.sill == 1.0 process = LindgrenProcess(2.0) @test process.range == 2.0u"m" @test process.sill == 1.0 process = LindgrenProcess(2.0u"km") @test process.range == 2.0u"km" @test process.sill == 1.0 process = LindgrenProcess(2.0, 2.0) @test process.range == 2.0u"m" @test process.sill == 2.0 process = LindgrenProcess(2.0u"km", 2.0) @test process.range == 2.0u"km" @test process.sill == 2.0 process = LindgrenProcess(2, 2) @test Unitful.numtype(process.range) == Float64 @test process.sill isa Float64 # simulation on sphere p = LindgrenProcess(0.1) s = Sphere((0,0,0)) m = simplexify(s) # unconditional realization rng = StableRNG(2024) r = rand(rng, p, m, :z => Float64, 3) for i in 1:3 @test isapprox(sum(r[i].z) / length(r[i].z), 0.0, atol=1e-3) end # conditional realization rng = StableRNG(2024) d = georef((z=[0.,1.],), [(0,0,-1), (0,0,1)]) r = rand(rng, p, m, d, 3) for i in 1:3 @test isapprox(sum(r[i].z) / length(r[i].z), 0.0, atol=1e-3) end process = LindgrenProcess() @test sprint(show, process) == "LindgrenProcess(range: 1.0 m, sill: 1.0, init: NearestInit())" @test sprint(show, MIME("text/plain"), process) == """ LindgrenProcess ├─ range: 1.0 m ├─ sill: 1.0 └─ init: GeoStatsBase.NearestInit()""" end @testset "QuiltingProcess" begin sdata = georef((; facies=[1.0, 0.0, 1.0]), [(25.0, 25.0), (50.0, 75.0), (75.0, 50.0)]) sdomain = CartesianGrid(100, 100) rng = StableRNG(2017) trainimg = geostatsimage("Strebelle") inactive = [CartesianIndex(i, j) for i in 1:30 for j in 1:30] process = QuiltingProcess(trainimg, (30, 30); inactive) sims = rand(rng, process, sdomain, sdata, 3) @test length(sims) == 3 @test size(domain(sims[1])) == (100, 100) @test eltype(sims[1].facies) <: Union{Float64,Missing} @test any(ismissing, sims[1].facies) @test all(!isnan, skipmissing(sims[1].facies)) process = QuiltingProcess(trainimg, (30, 30)) @test sprint(show, process) == "QuiltingProcess(trainimg: 62500×2 GeoTable over 250×250 CartesianGrid, tilesize: (30, 30), overlap: nothing, path: :raster, inactive: nothing, soft: nothing, tol: 0.1, init: NearestInit())" @test sprint(show, MIME("text/plain"), process) == """ QuiltingProcess ├─ trainimg: 62500×2 GeoTable over 250×250 CartesianGrid ├─ tilesize: (30, 30) ├─ overlap: nothing ├─ path: :raster ├─ inactive: nothing ├─ soft: nothing ├─ tol: 0.1 └─ init: GeoStatsBase.NearestInit()""" end @testset "TuringProcess" begin rng = StableRNG(2019) sdomain = CartesianGrid(200, 200) sims = rand(rng, TuringProcess(), sdomain, :z => Float64, 3) @test length(sims) == 3 @test size(domain(sims[1])) == (200, 200) @test eltype(sims[1].z) <: Float64 process = TuringProcess() @test sprint(show, process) == "TuringProcess(params: nothing, blur: nothing, edge: nothing, iter: 100)" @test sprint(show, MIME("text/plain"), process) == """ TuringProcess ├─ params: nothing ├─ blur: nothing ├─ edge: nothing └─ iter: 100""" end @testset "StrataProcess" begin rng = StableRNG(2019) proc = SmoothingProcess() env = Environment(rng, [proc, proc], [0.5 0.5; 0.5 0.5], ExponentialDuration(rng, 1.0)) sdomain = CartesianGrid(50, 50, 20) sims = rand(StrataProcess(env), sdomain, :z => Float64, 3) @test length(sims) == 3 @test size(domain(sims[1])) == (50, 50, 20) @test eltype(sims[1].z) <: Union{Float64,Missing} @test any(ismissing, sims[1].z) @test all(!isnan, skipmissing(sims[1].z)) rng = StableRNG(2019) proc = SmoothingProcess() env = Environment(rng, [proc, proc], [0.5 0.5; 0.5 0.5], ExponentialDuration(rng, 1.0)) process = StrataProcess(env) end end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
5000
@testset "PointProcess" begin # geometries and domains seg = Segment((0.0, 0.0), (11.3, 11.3)) tri = Triangle((0.0, 0.0), (5.65, 0.0), (5.65, 5.65)) quad = Quadrangle((0.0, 0.0), (0.0, 4.0), (4.0, 4.0), (4.0, 0.0)) box = Box((0.0, 0.0), (4.0, 4.0)) ball = Ball((1.0, 1.0), 2.25) outer = [(0.0, -4.0), (4.0, -1.0), (4.0, 1.5), (0.0, 3.0)] hole1 = [(0.2, 0.6), (1.4, 0.6), (1.4, -0.2), (0.2, -0.2)] hole2 = [(2.0, 0.4), (3.0, 0.4), (3.0, -0.2), (2.0, -0.2)] poly = PolyArea([outer, hole1, hole2]) grid = CartesianGrid((0, 0), (4, 4), dims=(10, 10)) points = [(0, 0), (4.5, 0), (0, 4.2), (4, 4.3), (1.5, 1.5)] connec = connect.([(1, 2, 5), (2, 4, 5), (4, 3, 5), (3, 1, 5)], Triangle) mesh = SimpleMesh(points, connec) geoms = [seg, tri, quad, box, ball, poly, grid, mesh] # point processes λ(s) = sum(to(s) .^ 2) binom = BinomialProcess(100) poisson1 = PoissonProcess(100.0) poisson2 = PoissonProcess(λ) inhibit = InhibitionProcess(0.1) procs = [binom, poisson1, poisson2, inhibit] @testset "Basic" begin rng = StableRNG(2024) for p in procs pp = rand(rng, p, box) @test all(∈(box), pp) end for g in geoms pp = rand(rng, binom, g) @test all(∈(g), pp) end end @testset "Binomial" begin rng = StableRNG(2024) p = BinomialProcess(10) for g in geoms pp = rand(rng, p, g) @test nelements(pp) == 10 end p = BinomialProcess(10) @test sprint(show, p) == "BinomialProcess(n: 10)" @test sprint(show, MIME("text/plain"), p) == """ BinomialProcess └─ n: 10""" end @testset "Poisson" begin rng = StableRNG(2024) # inhomogeneous with piecewise constant intensity for g in [grid, mesh] p = PoissonProcess(λ.(centroid.(g))) pp = rand(rng, p, g) @test all(∈(g), pp) end # empty pointsets for g in geoms @test isnothing(rand(rng, PoissonProcess(0.0), seg)) end pp = PointSet(rand(rng, Point, 10)) @test isnothing(rand(rng, PoissonProcess(100.0), pp)) p = PoissonProcess(100.0) @test sprint(show, p) == "PoissonProcess(λ: 100.0)" @test sprint(show, MIME("text/plain"), p) == """ PoissonProcess └─ λ: 100.0""" end @testset "Inhibition" begin p = InhibitionProcess(0.1) @test sprint(show, p) == "InhibitionProcess(δ: 0.1)" @test sprint(show, MIME("text/plain"), p) == """ InhibitionProcess └─ δ: 0.1""" end @testset "Cluster" begin rng = StableRNG(2024) binom = BinomialProcess(100) poisson = PoissonProcess(100.0) procs = [binom, poisson] ofun1 = parent -> rand(rng, BinomialProcess(10), Ball(parent, 0.2)) ofun2 = parent -> rand(rng, PoissonProcess(100), Ball(parent, 0.2)) ofun3 = parent -> rand(rng, PoissonProcess(x -> 100 * sum((x - parent) .^ 2)), Ball(parent, 0.5)) ofun4 = parent -> PointSet(sample(Sphere(parent, 0.1), RegularSampling(10))) ofuns = [ofun1, ofun2, ofun3, ofun4] box = Box((0.0, 0.0), (4.0, 4.0)) ball = Ball((1.0, 1.0), 2.25) tri = Triangle((0.0, 0.0), (5.65, 0.0), (5.65, 5.65)) grid = CartesianGrid((0, 0), (4, 4), dims=(10, 10)) geoms = [box, ball, tri, grid] for p in procs, ofun in ofuns cp = ClusterProcess(p, ofun) pp = rand(rng, cp, box) if !isnothing(pp) @test all(∈(box), pp) end end for g in geoms cp = ClusterProcess(binom, ofun1) pp = rand(rng, cp, g) if !isnothing(pp) @test all(∈(g), pp) end end p = ClusterProcess(binom, identity) @test sprint(show, p) == "ClusterProcess(proc: BinomialProcess(n: 100), ofun: identity)" @test sprint(show, MIME("text/plain"), p) == """ ClusterProcess ├─ proc: BinomialProcess(n: 100) └─ ofun: identity""" end @testset "Union" begin rng = StableRNG(2024) b = Box((0.0, 0.0), (100.0, 100.0)) p₁ = BinomialProcess(50) p₂ = BinomialProcess(50) p = p₁ ∪ p₂ # 100 points s = rand(rng, p, b, 2) @test length(s) == 2 @test s[1] isa PointSet @test s[2] isa PointSet @test nelements.(s) == [100, 100] p = BinomialProcess(50) ∪ BinomialProcess(100) @test sprint(show, p) == "UnionProcess(p₁: BinomialProcess(n: 50), p₂: BinomialProcess(n: 100))" @test sprint(show, MIME("text/plain"), p) == """ UnionProcess ├─ p₁: BinomialProcess(n: 50) └─ p₂: BinomialProcess(n: 100)""" end @testset "Thinning" begin rng = StableRNG(2024) p = PoissonProcess(10) q = Quadrangle((0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)) pp = rand(rng, p, q) tp = thin(pp, RandomThinning(0.3)) @test length(tp) ≤ length(pp) xs = to.(tp) @test all(0u"m" .≤ first.(xs) .≤ 4.0u"m") @test all(0u"m" .≤ last.(xs) .≤ 4.0u"m") tp = thin(pp, RandomThinning(s -> λ(s) / λ(Point(4.0, 4.0)))) @test length(tp) ≤ length(pp) xs = to.(tp) @test all(0u"m" .≤ first.(xs) .≤ 4.0u"m") @test all(0u"m" .≤ last.(xs) .≤ 4.0u"m") end end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
code
425
using GeoStatsProcesses using Meshes using Unitful using GeoTables using GeoStatsFunctions using GeoStatsImages using LinearAlgebra using Test, StableRNGs import ImageQuilting import TuringPatterns using StratiGraphics: SmoothingProcess, Environment, ExponentialDuration # list of tests testfiles = ["point.jl", "field.jl"] @testset "GeoStatsProcesses.jl" begin for testfile in testfiles include(testfile) end end
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
0.7.1
b678d403be2ebed544f68fc8616ea30f3b606406
docs
642
# GeoStatsProcesses.jl [![Build Status](https://github.com/JuliaEarth/GeoStatsProcesses.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/JuliaEarth/GeoStatsProcesses.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/JuliaEarth/GeoStatsProcesses.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/JuliaEarth/GeoStatsProcesses.jl) Geostatistical processes for the [GeoStats.jl](https://github.com/JuliaEarth/GeoStats.jl) framework. ## Asking for help If you have any questions, please [contact our community](https://juliaearth.github.io/GeoStats.jl/stable/about/community.html).
GeoStatsProcesses
https://github.com/JuliaEarth/GeoStatsProcesses.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
373
using Documenter using LoweredCodeUtils makedocs( sitename = "LoweredCodeUtils", format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true"), modules = [LoweredCodeUtils], pages = ["Home" => "index.md", "signatures.md", "edges.md", "api.md"] ) deploydocs( repo = "github.com/JuliaDebug/LoweredCodeUtils.jl.git", push_preview = true )
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
856
module LoweredCodeUtils # We use a code structure where all `using` and `import` # statements in the package that load anything other than # a Julia base or stdlib package are located in this file here. # Nothing else should appear in this file here, apart from # the `include("packagedef.jl")` statement, which loads what # we would normally consider the bulk of the package code. # This somewhat unusual structure is in place to support # the VS Code extension integration. using JuliaInterpreter using JuliaInterpreter: SSAValue, SlotNumber, Frame using JuliaInterpreter: @lookup, moduleof, pc_expr, step_expr!, is_global_ref, is_quotenode_egal, whichtt, next_until!, finish_and_return!, get_return, nstatements, codelocation, linetable, is_return, lookup_return include("packagedef.jl") end # module
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
38815
## Phase 1: direct links # There are 3 types of entities to track: ssavalues (line/statement numbers), slots, and named objects. # Each entity can have a number of "predecessors" (forward edges), which can be any combination of these # three entity types. Likewise, each entity can have a number of "successors" (backward edges), also any # combination of these entity types. struct Links ssas::Vector{Int} slots::Vector{Int} names::Vector{GlobalRef} end Links() = Links(Int[], Int[], GlobalRef[]) function Base.show(io::IO, l::Links) print(io, "ssas: ", showempty(l.ssas), ", slots: ", showempty(l.slots), ", names: ") print(IOContext(io, :typeinfo=>Vector{GlobalRef}), showempty(l.names)) print(io, ';') end struct CodeLinks thismod::Module ssapreds::Vector{Links} ssasuccs::Vector{Links} slotpreds::Vector{Links} slotsuccs::Vector{Links} slotassigns::Vector{Vector{Int}} namepreds::Dict{GlobalRef,Links} namesuccs::Dict{GlobalRef,Links} nameassigns::Dict{GlobalRef,Vector{Int}} end function CodeLinks(thismod::Module, nlines::Int, nslots::Int) makelinks(n) = [Links() for _ = 1:n] return CodeLinks(thismod, makelinks(nlines), makelinks(nlines), makelinks(nslots), makelinks(nslots), [Int[] for _ = 1:nslots], Dict{GlobalRef,Links}(), Dict{GlobalRef,Links}(), Dict{GlobalRef,Vector{Int}}()) end function CodeLinks(thismod::Module, src::CodeInfo) cl = CodeLinks(thismod, length(src.code), length(src.slotnames)) direct_links!(cl, src) end function Base.show(io::IO, cl::CodeLinks) print(io, "CodeLinks:") print_slots(io, cl) print_names(io, cl) nstmts = length(cl.ssapreds) nd = ndigits(nstmts) print(io, "\nCode:") for i = 1:nstmts print(io, '\n', lpad(i, nd), " preds: ") show(io, cl.ssapreds[i]) print(io, '\n', lpad(i, nd), " succs: ") show(io, cl.ssasuccs[i]) end end function print_slots(io::IO, cl::CodeLinks) nslots = length(cl.slotpreds) nd = ndigits(nslots) for i = 1:nslots print(io, "\nslot ", lpad(i, nd), ':') print(io, "\n preds: ") show(io, cl.slotpreds[i]) print(io, "\n succs: ") show(io, cl.slotsuccs[i]) print(io, "\n assign @: ") show(io, cl.slotassigns[i]) end end function print_names(io::IO, cl::CodeLinks) ukeys = namedkeys(cl) for key in ukeys print(io, '\n', key, ':') if haskey(cl.namepreds, key) print(io, "\n preds: ") show(io, cl.namepreds[key]) end if haskey(cl.namesuccs, key) print(io, "\n succs: ") show(io, cl.namesuccs[key]) end if haskey(cl.nameassigns, key) print(io, "\n assign @: ") show(io, cl.nameassigns[key]) end end end const preprinter_sentinel = isdefined(Base.IRShow, :statementidx_lineinfo_printer) ? 0 : typemin(Int32) function print_with_code(preprint, postprint, io::IO, src::CodeInfo) src = copy(src) JuliaInterpreter.replace_coretypes!(src; rev=true) if isdefined(JuliaInterpreter, :reverse_lookup_globalref!) JuliaInterpreter.reverse_lookup_globalref!(src.code) end io = IOContext(io, :displaysize=>displaysize(io), :SOURCE_SLOTNAMES => Base.sourceinfo_slotnames(src)) used = BitSet() cfg = compute_basic_blocks(src.code) for stmt in src.code Core.Compiler.scan_ssa_use!(push!, used, stmt) end line_info_preprinter = Base.IRShow.lineinfo_disabled line_info_postprinter = Base.IRShow.default_expr_type_printer preprint(io) bb_idx_prev = bb_idx = 1 for idx = 1:length(src.code) preprint(io, idx) bb_idx = Base.IRShow.show_ir_stmt(io, src, idx, line_info_preprinter, line_info_postprinter, used, cfg, bb_idx) postprint(io, idx, bb_idx != bb_idx_prev) bb_idx_prev = bb_idx end max_bb_idx_size = ndigits(length(cfg.blocks)) line_info_preprinter(io, " "^(max_bb_idx_size + 2), preprinter_sentinel) postprint(io) return nothing end """ print_with_code(io, src::CodeInfo, cl::CodeLinks) Interweave display of code and links. !!! compat "Julia 1.6" This function produces dummy output if suitable support is missing in your version of Julia. """ function print_with_code(io::IO, src::CodeInfo, cl::CodeLinks) function preprint(io::IO) print(io, "Slots:") print_slots(io, cl) print(io, "\nNames:") print_names(io, cl) println(io) end preprint(::IO, ::Int) = nothing postprint(::IO) = nothing postprint(io::IO, idx::Int, bbchanged::Bool) = postprint_linelinks(io, idx, src, cl, bbchanged) print_with_code(preprint, postprint, io, src) end function postprint_linelinks(io::IO, idx::Int, src::CodeInfo, cl::CodeLinks, bbchanged::Bool) printstyled(io, bbchanged ? " " : "│", color=:light_black) printstyled(io, " # ", color=:yellow) stmt = src.code[idx] if is_assignment_like(stmt) lhs = normalize_defsig(stmt.args[1], cl.thismod) if @issslotnum(lhs) # id = lhs.id # preds, succs = cl.slotpreds[id], cl.slotsuccs[id] printstyled(io, "see slot ", lhs.id, '\n', color=:yellow) else # preds, succs = cl.namepreds[lhs], cl.namesuccs[lhs] printstyled(io, "see name ", lhs, '\n', color=:yellow) end else preds, succs = cl.ssapreds[idx], cl.ssasuccs[idx] printstyled(io, "preds: ", preds, " succs: ", succs, '\n', color=:yellow) end return nothing end function namedkeys(cl::CodeLinks) ukeys = Set{GlobalRef}() for c in (cl.namepreds, cl.namesuccs, cl.nameassigns) for k in keys(c) push!(ukeys, k) end end return ukeys end is_assignment_like(stmt::Expr) = isexpr(stmt, :(=)) || (isexpr(stmt, :const) && length(stmt.args) == 2) is_assignment_like(@nospecialize stmt) = false function direct_links!(cl::CodeLinks, src::CodeInfo) # Utility for when a stmt itself contains a CodeInfo function add_inner!(cl::CodeLinks, icl::CodeLinks, idx) for (name, _) in icl.nameassigns assigns = get(cl.nameassigns, name, nothing) if assigns === nothing cl.nameassigns[name] = assigns = Int[] end push!(assigns, idx) end for (name, _) in icl.namesuccs succs = get(cl.namesuccs, name, nothing) if succs === nothing cl.namesuccs[name] = succs = Links() end push!(succs.ssas, idx) end end P = Pair{Union{SSAValue,SlotNumber,GlobalRef},Links} for (i, stmt) in enumerate(src.code) if isexpr(stmt, :thunk) && isa(stmt.args[1], CodeInfo) icl = CodeLinks(cl.thismod, stmt.args[1]) add_inner!(cl, icl, i) continue elseif isa(stmt, Expr) && stmt.head ∈ trackedheads if stmt.head === :method && length(stmt.args) === 3 && isa(stmt.args[3], CodeInfo) icl = CodeLinks(cl.thismod, stmt.args[3]) add_inner!(cl, icl, i) end name = stmt.args[1] if isa(name, GlobalRef) || isa(name, Symbol) if isa(name, Symbol) name = GlobalRef(cl.thismod, name) end assign = get(cl.nameassigns, name, nothing) if assign === nothing cl.nameassigns[name] = assign = Int[] end push!(assign, i) targetstore = get(cl.namepreds, name, nothing) if targetstore === nothing cl.namepreds[name] = targetstore = Links() end target = P(name, targetstore) add_links!(target, stmt, cl) elseif name in (nothing, false) else @show stmt error("name ", typeof(name), " not recognized") end rhs = stmt target = P(SSAValue(i), cl.ssapreds[i]) elseif is_assignment_like(stmt) # An assignment stmt = stmt::Expr lhs, rhs = stmt.args[1], stmt.args[2] if @issslotnum(lhs) lhs = lhs::AnySlotNumber id = lhs.id target = P(SlotNumber(id), cl.slotpreds[id]) push!(cl.slotassigns[id], i) elseif isa(lhs, GlobalRef) || isa(lhs, Symbol) if isa(lhs, Symbol) lhs = GlobalRef(cl.thismod, lhs) end targetstore = get(cl.namepreds, lhs, nothing) if targetstore === nothing cl.namepreds[lhs] = targetstore = Links() end target = P(lhs, targetstore) assign = get(cl.nameassigns, lhs, nothing) if assign === nothing cl.nameassigns[lhs] = assign = Int[] end push!(assign, i) else error("lhs ", lhs, " not recognized") end else rhs = stmt target = P(SSAValue(i), cl.ssapreds[i]) end add_links!(target, rhs, cl) end return cl end function add_links!(target::Pair{Union{SSAValue,SlotNumber,GlobalRef},Links}, @nospecialize(stmt), cl::CodeLinks) _targetid, targetstore = target targetid = _targetid::Union{SSAValue,SlotNumber,GlobalRef} # Adds bidirectional edges if @isssa(stmt) stmt = stmt::AnySSAValue push!(targetstore, SSAValue(stmt.id)) # forward edge push!(cl.ssasuccs[stmt.id], targetid) # backward edge elseif @issslotnum(stmt) stmt = stmt::AnySlotNumber push!(targetstore, SlotNumber(stmt.id)) push!(cl.slotsuccs[stmt.id], targetid) elseif isa(stmt, GlobalRef) || isa(stmt, Symbol) if isa(stmt, Symbol) stmt = GlobalRef(cl.thismod, stmt) end push!(targetstore, stmt) namestore = get(cl.namesuccs, stmt, nothing) if namestore === nothing cl.namesuccs[stmt] = namestore = Links() end push!(namestore, targetid) elseif isa(stmt, Expr) && stmt.head !== :copyast stmt = stmt::Expr arng = 1:length(stmt.args) if stmt.head === :call f = stmt.args[1] if !@isssa(f) && !@issslotnum(f) # Avoid putting named callees on the namestore arng = 2:length(stmt.args) end end for i in arng add_links!(target, stmt.args[i], cl) end elseif stmt isa Core.GotoIfNot add_links!(target, stmt.cond, cl) elseif stmt isa Core.ReturnNode add_links!(target, stmt.val, cl) end return nothing end function Base.push!(l::Links, id) if isa(id, SSAValue) k = id.id k ∉ l.ssas && push!(l.ssas, k) elseif isa(id, SlotNumber) k = id.id k ∉ l.slots && push!(l.slots, k) else id = id::GlobalRef id ∉ l.names && push!(l.names, id) end return id end ## Phase 2: replacing slot-links with statement-links (and adding name-links to statement-links) # Now that we know the full set of dependencies, we can safely replace references to names # by references to the relevant line numbers. """ `Variable` holds information about named variables. Unlike SSAValues, a single Variable can be assigned from multiple code locations. If `v` is a `Variable`, then - `v.assigned` is a list of statement numbers on which it is assigned - `v.preds` is the set of statement numbers upon which this assignment depends - `v.succs` is the set of statement numbers which make use of this variable `preds` and `succs` are short for "predecessors" and "successors," respectively. These are meant in the sense of execution order, not statement number; depending on control-flow, a variable may have entries in `preds` that are larger than the smallest entry in `assigned`. """ struct Variable assigned::Vector{Int} preds::Vector{Int} succs::Vector{Int} end Variable() = Variable(Int[], Int[], Int[]) function Base.show(io::IO, v::Variable) print(io, "assigned on ", showempty(v.assigned)) print(io, ", depends on ", showempty(v.preds)) print(io, ", and used by ", showempty(v.succs)) end # This will be documented below at the "user-level" constructor. # preds[i] is the list of predecessors for the `i`th statement in the CodeInfo # succs[i] is the list of successors for the `i`th statement in the CodeInfo # byname[name] summarizes this CodeInfo's dependence on Variable `name`. struct CodeEdges preds::Vector{Vector{Int}} succs::Vector{Vector{Int}} byname::Dict{GlobalRef,Variable} end CodeEdges(n::Integer) = CodeEdges([Int[] for i = 1:n], [Int[] for i = 1:n], Dict{GlobalRef,Variable}()) function Base.show(io::IO, edges::CodeEdges) println(io, "CodeEdges:") for (name, v) in edges.byname print(io, " ", name, ": ") show(io, v) println(io) end n = length(edges.preds) nd = ndigits(n) for i = 1:n println(io, " statement ", lpad(i, nd), " depends on ", showempty(edges.preds[i]), " and is used by ", showempty(edges.succs[i])) end return nothing end """ edges = CodeEdges(src::CodeInfo) Analyze `src` and determine the chain of dependencies. - `edges.preds[i]` lists the preceding statements that statement `i` depends on. - `edges.succs[i]` lists the succeeding statements that depend on statement `i`. - `edges.byname[v]` returns information about the predecessors, successors, and assignment statements for an object `v::GlobalRef`. """ function CodeEdges(mod::Module, src::CodeInfo) cl = CodeLinks(mod, src) CodeEdges(src, cl) end function CodeEdges(src::CodeInfo, cl::CodeLinks) # The main task here is to elide the slot-dependencies and convert # everything to just ssas & names. # Replace/add named intermediates (slot & named-variable references) with statement numbers nstmts, nslots = length(src.code), length(src.slotnames) marked, slothandled = BitSet(), fill(false, nslots) # working storage during resolution edges = CodeEdges(nstmts) emptylink = Links() emptylist = Int[] for (i, stmt) in enumerate(src.code) # Identify line predecents for slots and named variables if is_assignment_like(stmt) stmt = stmt::Expr lhs = stmt.args[1] # Mark predecessors and successors of this line by following ssas & named assignments if @issslotnum(lhs) lhs = lhs::AnySlotNumber # This line assigns a slot. Mark all predecessors. id = lhs.id linkpreds, linksuccs, listassigns = cl.slotpreds[id], cl.slotsuccs[id], cl.slotassigns[id] else lhs = lhs::Union{GlobalRef,Symbol} if lhs isa Symbol lhs = GlobalRef(cl.thismod, lhs) end linkpreds = get(cl.namepreds, lhs, emptylink) linksuccs = get(cl.namesuccs, lhs, emptylink) listassigns = get(cl.nameassigns, lhs, emptylist) end else linkpreds, linksuccs, listassigns = cl.ssapreds[i], cl.ssasuccs[i], emptylist end # Assign the predecessors # For "named" predecessors, we depend only on their assignments empty!(marked) fill!(slothandled, false) follow_links!(marked, linkpreds, cl.slotpreds, cl.slotassigns, slothandled) pushall!(marked, listassigns) for key in linkpreds.names pushall!(marked, get(cl.nameassigns, key, emptylist)) end delete!(marked, i) append!(edges.preds[i], marked) # Similarly for successors empty!(marked) fill!(slothandled, false) follow_links!(marked, linksuccs, cl.slotsuccs, cl.slotassigns, slothandled) pushall!(marked, listassigns) for key in linksuccs.names pushall!(marked, get(cl.nameassigns, key, emptylist)) end delete!(marked, i) append!(edges.succs[i], marked) end # Add named variables ukeys = namedkeys(cl) for key in ukeys assigned = get(cl.nameassigns, key, Int[]) empty!(marked) linkpreds = get(cl.namepreds, key, emptylink) pushall!(marked, linkpreds.ssas) for j in linkpreds.slots pushall!(marked, cl.slotassigns[j]) end for key in linkpreds.names pushall!(marked, get(cl.nameassigns, key, emptylist)) end preds = append!(Int[], marked) empty!(marked) linksuccs = get(cl.namesuccs, key, emptylink) pushall!(marked, linksuccs.ssas) for j in linksuccs.slots pushall!(marked, cl.slotassigns[j]) pushall!(marked, cl.slotsuccs[j].ssas) end for key in linksuccs.names pushall!(marked, get(cl.nameassigns, key, emptylist)) end succs = append!(Int[], marked) edges.byname[key] = Variable(assigned, preds, succs) end return edges end # Follow slot links to their non-slot leaves function follow_links!(marked, l::Links, slotlinks, slotassigns, slothandled) pushall!(marked, l.ssas) for id in l.slots slothandled[id] && continue slothandled[id] = true pushall!(marked, slotassigns[id]) follow_links!(marked, slotlinks[id], slotlinks, slotassigns, slothandled) end return marked end """ print_with_code(io, src::CodeInfo, edges::CodeEdges) Interweave display of code and edges. !!! compat "Julia 1.6" This function produces dummy output if suitable support is missing in your version of Julia. """ function print_with_code(io::IO, src::CodeInfo, edges::CodeEdges) function preprint(io::IO) printstyled(io, "Names:", color=:yellow) for (name, var) in edges.byname print(io, '\n', name, ": ") show(io, var) end printstyled(io, "\nCode:\n", color=:yellow) end @static if isdefined(Base.IRShow, :show_ir_stmt) preprint(::IO, ::Int) = nothing else nd = ndigits(length(src.code)) preprint(io::IO, i::Int) = print(io, lpad(i, nd), " ") end postprint(::IO) = nothing postprint(io::IO, idx::Int, bbchanged::Bool) = postprint_lineedges(io, idx, edges, bbchanged) print_with_code(preprint, postprint, io, src) end function postprint_lineedges(io::IO, idx::Int, edges::CodeEdges, bbchanged::Bool) printstyled(io, bbchanged ? " " : "│", color=:light_black) printstyled(io, " # ", color=:yellow) preds, succs = edges.preds[idx], edges.succs[idx] printstyled(io, "preds: ", showempty(preds), ", succs: ", showempty(succs), '\n', color=:yellow) return nothing end function terminal_preds(i::Int, edges::CodeEdges) s, covered = BitSet(), BitSet() push!(covered, i) for p in edges.preds[i] terminal_preds!(s, p, edges, covered) end return s end function terminal_preds!(s, j, edges, covered) # can't be an inner function because it calls itself (Core.Box) j ∈ covered && return s push!(covered, j) preds = edges.preds[j] if isempty(preds) push!(s, j) else for p in preds terminal_preds!(s, p, edges, covered) end end return s end """ isrequired = lines_required(obj::GlobalRef, src::CodeInfo, edges::CodeEdges) isrequired = lines_required(idx::Int, src::CodeInfo, edges::CodeEdges) Determine which lines might need to be executed to evaluate `obj` or the statement indexed by `idx`. If `isrequired[i]` is `false`, the `i`th statement is *not* required. In some circumstances all statements marked `true` may be needed, in others control-flow will end up skipping a subset of such statements, perhaps while repeating others multiple times. See also [`lines_required!`](@ref) and [`selective_eval!`](@ref). """ function lines_required(obj::GlobalRef, src::CodeInfo, edges::CodeEdges; kwargs...) isrequired = falses(length(edges.preds)) objs = Set{GlobalRef}([obj]) return lines_required!(isrequired, objs, src, edges; kwargs...) end function lines_required(idx::Int, src::CodeInfo, edges::CodeEdges; kwargs...) isrequired = falses(length(edges.preds)) isrequired[idx] = true objs = Set{GlobalRef}() return lines_required!(isrequired, objs, src, edges; kwargs...) end """ lines_required!(isrequired::AbstractVector{Bool}, src::CodeInfo, edges::CodeEdges; norequire = ()) Like `lines_required`, but where `isrequired[idx]` has already been set to `true` for all statements that you know you need to evaluate. All other statements should be marked `false` at entry. On return, the complete set of required statements will be marked `true`. `norequire` keyword argument specifies statements (represented as iterator of `Int`s) that should _not_ be marked as a requirement. For example, use `norequire = LoweredCodeUtils.exclude_named_typedefs(src, edges)` if you're extracting method signatures and not evaluating new definitions. """ function lines_required!(isrequired::AbstractVector{Bool}, src::CodeInfo, edges::CodeEdges; kwargs...) objs = Set{GlobalRef}() return lines_required!(isrequired, objs, src, edges; kwargs...) end function exclude_named_typedefs(src::CodeInfo, edges::CodeEdges) norequire = BitSet() i = 1 nstmts = length(src.code) while i <= nstmts stmt = rhs(src.code[i]) if istypedef(stmt) && !isanonymous_typedef(stmt::Expr) r = typedef_range(src, i) pushall!(norequire, r) i = last(r)+1 else i += 1 end end return norequire end function lines_required!(isrequired::AbstractVector{Bool}, objs, src::CodeInfo, edges::CodeEdges; norequire = ()) # Mark any requested objects (their lines of assignment) objs = add_requests!(isrequired, objs, edges, norequire) # Compute basic blocks, which we'll use to make sure we mark necessary control-flow cfg = compute_basic_blocks(src.code) # needed for control-flow analysis postdomtree = construct_postdomtree(cfg.blocks) # We'll mostly use generic graph traversal to discover all the lines we need, # but structs are in a bit of a different category (especially on Julia 1.5+). # It's easiest to discover these at the beginning. typedefs = find_typedefs(src) changed = true iter = 0 while changed changed = false # Handle ssa predecessors changed |= add_ssa_preds!(isrequired, src, edges, norequire) # Handle named dependencies changed |= add_named_dependencies!(isrequired, edges, objs, norequire) # Add control-flow changed |= add_control_flow!(isrequired, src, cfg, postdomtree) # So far, everything is generic graph traversal. Now we add some domain-specific information changed |= add_typedefs!(isrequired, src, edges, typedefs, norequire) changed |= add_inplace!(isrequired, src, edges, norequire) iter += 1 # just for diagnostics end # now mark the active goto nodes add_active_gotos!(isrequired, src, cfg, postdomtree) return isrequired end function add_requests!(isrequired, objs, edges::CodeEdges, norequire) objsnew = Set{GlobalRef}() for obj in objs add_obj!(isrequired, objsnew, obj, edges, norequire) end return objsnew end function add_ssa_preds!(isrequired, src::CodeInfo, edges::CodeEdges, norequire) changed = false for idx = 1:length(src.code) if isrequired[idx] changed |= add_preds!(isrequired, idx, edges, norequire) end end return changed end function add_named_dependencies!(isrequired, edges::CodeEdges, objs, norequire) changed = false for (obj, uses) in edges.byname obj ∈ objs && continue if any(view(isrequired, uses.succs)) changed |= add_obj!(isrequired, objs, obj, edges, norequire) end end return changed end function add_preds!(isrequired, idx, edges::CodeEdges, norequire) chngd = false preds = edges.preds[idx] for p in preds isrequired[p] && continue p ∈ norequire && continue isrequired[p] = true chngd = true add_preds!(isrequired, p, edges, norequire) end return chngd end function add_succs!(isrequired, idx, edges::CodeEdges, succs, norequire) chngd = false for p in succs isrequired[p] && continue p ∈ norequire && continue isrequired[p] = true chngd = true add_succs!(isrequired, p, edges, edges.succs[p], norequire) end return chngd end function add_obj!(isrequired, objs, obj, edges::CodeEdges, norequire) chngd = false for d in edges.byname[obj].assigned d ∈ norequire && continue isrequired[d] || add_preds!(isrequired, d, edges, norequire) isrequired[d] = true chngd = true end push!(objs, obj) return chngd end ## Add control-flow using Core: CodeInfo using Core.Compiler: CFG, BasicBlock, compute_basic_blocks # The goal of this function is to request concretization of the minimal necessary control # flow to evaluate statements whose concretization have already been requested. # The basic algorithm is based on what was proposed in [^Wei84]. If there is even one active # block in the blocks reachable from a conditional branch up to its successors' nearest # common post-dominator (referred to as 𝑰𝑵𝑭𝑳 in the paper), it is necessary to follow # that conditional branch and execute the code. Otherwise, execution can be short-circuited # from the conditional branch to the nearest common post-dominator. # # COMBAK: It is important to note that in Julia's intermediate code representation (`CodeInfo`), # "short-circuiting" a specific code region is not a simple task. Simply ignoring the path # to the post-dominator does not guarantee fall-through to the post-dominator. Therefore, # a more careful implementation is required for this aspect. # # [Wei84]: M. Weiser, "Program Slicing," IEEE Transactions on Software Engineering, 10, pages 352-357, July 1984. function add_control_flow!(isrequired, src::CodeInfo, cfg::CFG, postdomtree) local changed::Bool = false function mark_isrequired!(idx::Int) if !isrequired[idx] changed |= isrequired[idx] = true return true end return false end for bbidx = 1:length(cfg.blocks) # forward traversal bb = cfg.blocks[bbidx] nsuccs = length(bb.succs) if nsuccs == 0 continue elseif nsuccs == 1 continue # leave a fall-through terminator unmarked: `GotoNode`s are marked later elseif nsuccs == 2 termidx = bb.stmts[end] @assert is_conditional_terminator(src.code[termidx]) "invalid IR" if is_conditional_block_active(isrequired, bb, cfg, postdomtree) mark_isrequired!(termidx) else # fall-through to the post dominator block (by short-circuiting all statements between) end end end return changed end is_conditional_terminator(@nospecialize stmt) = stmt isa GotoIfNot || (@static @isdefined(EnterNode) ? stmt isa EnterNode : isexpr(stmt, :enter)) function is_conditional_block_active(isrequired, bb::BasicBlock, cfg::CFG, postdomtree) return visit_𝑰𝑵𝑭𝑳_blocks(bb, cfg, postdomtree) do postdominator::Int, 𝑰𝑵𝑭𝑳::BitSet for blk in 𝑰𝑵𝑭𝑳 if blk == postdominator continue # skip the post-dominator block and continue to a next infl block end if any(@view isrequired[cfg.blocks[blk].stmts]) return true end end return false end end function visit_𝑰𝑵𝑭𝑳_blocks(func, bb::BasicBlock, cfg::CFG, postdomtree) succ1, succ2 = bb.succs postdominator = nearest_common_dominator(postdomtree, succ1, succ2) 𝑰𝑵𝑭𝑳 = reachable_blocks(cfg, succ1, postdominator) ∪ reachable_blocks(cfg, succ2, postdominator) return func(postdominator, 𝑰𝑵𝑭𝑳) end function reachable_blocks(cfg, from_bb::Int, to_bb::Int) worklist = Int[from_bb] visited = BitSet(from_bb) if to_bb == from_bb return visited end push!(visited, to_bb) function visit!(bb::Int) if bb ∉ visited push!(visited, bb) push!(worklist, bb) end end while !isempty(worklist) foreach(visit!, cfg.blocks[pop!(worklist)].succs) end return visited end function add_active_gotos!(isrequired, src::CodeInfo, cfg::CFG, postdomtree) dead_blocks = compute_dead_blocks(isrequired, src, cfg, postdomtree) changed = false for bbidx = 1:length(cfg.blocks) if bbidx ∉ dead_blocks bb = cfg.blocks[bbidx] nsuccs = length(bb.succs) if nsuccs == 1 termidx = bb.stmts[end] if src.code[termidx] isa GotoNode changed |= isrequired[termidx] = true end end end end return changed end # find dead blocks using the same approach as `add_control_flow!`, for the converged `isrequired` function compute_dead_blocks(isrequired, src::CodeInfo, cfg::CFG, postdomtree) dead_blocks = BitSet() for bbidx = 1:length(cfg.blocks) bb = cfg.blocks[bbidx] nsuccs = length(bb.succs) if nsuccs == 2 termidx = bb.stmts[end] @assert is_conditional_terminator(src.code[termidx]) "invalid IR" visit_𝑰𝑵𝑭𝑳_blocks(bb, cfg, postdomtree) do postdominator::Int, 𝑰𝑵𝑭𝑳::BitSet is_𝑰𝑵𝑭𝑳_active = false for blk in 𝑰𝑵𝑭𝑳 if blk == postdominator continue # skip the post-dominator block and continue to a next infl block end if any(@view isrequired[cfg.blocks[blk].stmts]) is_𝑰𝑵𝑭𝑳_active |= true break end end if !is_𝑰𝑵𝑭𝑳_active union!(dead_blocks, delete!(𝑰𝑵𝑭𝑳, postdominator)) end end end end return dead_blocks end # Do a traveral of "numbered" predecessors and find statement ranges and names of type definitions function find_typedefs(src::CodeInfo) typedef_blocks, typedef_names = UnitRange{Int}[], Symbol[] i = 1 nstmts = length(src.code) while i <= nstmts stmt = rhs(src.code[i]) if istypedef(stmt) && !isanonymous_typedef(stmt::Expr) stmt = stmt::Expr r = typedef_range(src, i) push!(typedef_blocks, r) name = stmt.head === :call ? stmt.args[3] : stmt.args[1] if isa(name, QuoteNode) name = name.value end isa(name, Symbol) || @show src i r stmt push!(typedef_names, name::Symbol) i = last(r)+1 else i += 1 end end return typedef_blocks, typedef_names end # New struct definitions, including their constructors, get spread out over many # statements. If we're evaluating any of them, it's important to evaluate *all* of them. function add_typedefs!(isrequired, src::CodeInfo, edges::CodeEdges, (typedef_blocks, typedef_names), norequire) changed = false stmts = src.code idx = 1 while idx < length(stmts) stmt = stmts[idx] isrequired[idx] || (idx += 1; continue) for (typedefr, typedefn) in zip(typedef_blocks, typedef_names) if idx ∈ typedefr ireq = view(isrequired, typedefr) if !all(ireq) changed = true ireq .= true # Also mark any by-type constructor(s) associated with this typedef var = get(edges.byname, typedefn, nothing) if var !== nothing for s in var.succs s ∈ norequire && continue stmt2 = stmts[s] if isexpr(stmt2, :method) && (fname = (stmt2::Expr).args[1]; fname === false || fname === nothing) isrequired[s] = true end end end end idx = last(typedefr) + 1 continue end end # Anonymous functions may not yet include the method definition if isanonymous_typedef(stmt) i = idx + 1 while i <= length(stmts) && !ismethod3(stmts[i]) i += 1 end if i <= length(stmts) && (stmts[i]::Expr).args[1] == false tpreds = terminal_preds(i, edges) if minimum(tpreds) == idx && i ∉ norequire changed |= !isrequired[i] isrequired[i] = true end end end idx += 1 end return changed end # For arrays, add any `push!`, `pop!`, `empty!` or `setindex!` statements # This is needed for the "Modify @enum" test in Revise function add_inplace!(isrequired, src, edges, norequire) function mark_if_inplace(stmt, j) _changed = false fname = stmt.args[1] if (callee_matches(fname, Base, :push!) || callee_matches(fname, Base, :pop!) || callee_matches(fname, Base, :empty!) || callee_matches(fname, Base, :setindex!)) _changed = !isrequired[j] isrequired[j] = true end return _changed end changed = false for (i, isreq) in pairs(isrequired) isreq || continue for j in edges.succs[i] j ∈ norequire && continue stmt = src.code[j] if isexpr(stmt, :call) && length(stmt.args) >= 2 arg = stmt.args[2] if @isssa(arg) && arg.id == i changed |= mark_if_inplace(stmt, j) elseif @issslotnum(arg) id = arg.id # Check to see if we use this slot for k in edges.preds[j] isrequired[k] || continue predstmt = src.code[k] if is_assignment_like(predstmt) lhs = predstmt.args[1] if @issslotnum(lhs) && lhs.id == id changed |= mark_if_inplace(stmt, j) break end end end end end end end return changed end """ selective_eval!([recurse], frame::Frame, isrequired::AbstractVector{Bool}, istoplevel=false) Execute the code in `frame` in the manner of `JuliaInterpreter.finish_and_return!`, but skipping all statements that are marked `false` in `isrequired`. See [`lines_required`](@ref). Upon entry, if needed the caller must ensure that `frame.pc` is set to the correct statement, typically `findfirst(isrequired)`. See [`selective_eval_fromstart!`](@ref) to have that performed automatically. The default value for `recurse` is `JuliaInterpreter.finish_and_return!`. `isrequired` pertains only to `frame` itself, not any of its callees. This will return either a `BreakpointRef`, the value obtained from the last executed statement (if stored to `frame.framedata.ssavlues`), or `nothing`. Typically, assignment to a variable binding does not result in an ssa store by JuliaInterpreter. """ function selective_eval!(@nospecialize(recurse), frame::Frame, isrequired::AbstractVector{Bool}, istoplevel::Bool=false) pc = pcexec = pclast = frame.pc while isa(pc, Int) frame.pc = pc te = isrequired[pc] pclast = pcexec::Int if te pcexec = pc = step_expr!(recurse, frame, istoplevel) else pc = next_or_nothing!(recurse, frame) end end isa(pc, BreakpointRef) && return pc pcexec = (pcexec === nothing ? pclast : pcexec)::Int frame.pc = pcexec node = pc_expr(frame) is_return(node) && return isrequired[pcexec] ? lookup_return(frame, node) : nothing isassigned(frame.framedata.ssavalues, pcexec) && return frame.framedata.ssavalues[pcexec] return nothing end function selective_eval!(frame::Frame, isrequired::AbstractVector{Bool}, istoplevel::Bool=false) selective_eval!(finish_and_return!, frame, isrequired, istoplevel) end """ selective_eval_fromstart!([recurse], frame, isrequired, istoplevel=false) Like [`selective_eval!`](@ref), except it sets `frame.pc` to the first `true` statement in `isrequired`. """ function selective_eval_fromstart!(@nospecialize(recurse), frame, isrequired, istoplevel::Bool=false) pc = findfirst(isrequired) pc === nothing && return nothing frame.pc = pc return selective_eval!(recurse, frame, isrequired, istoplevel) end function selective_eval_fromstart!(frame::Frame, isrequired::AbstractVector{Bool}, istoplevel::Bool=false) selective_eval_fromstart!(finish_and_return!, frame, isrequired, istoplevel) end """ print_with_code(io, src::CodeInfo, isrequired::AbstractVector{Bool}) Mark each line of code with its requirement status. !!! compat "Julia 1.6" This function produces dummy output if suitable support is missing in your version of Julia. """ function print_with_code(io::IO, src::CodeInfo, isrequired::AbstractVector{Bool}) nd = ndigits(length(isrequired)) preprint(::IO) = nothing preprint(io::IO, idx::Int) = (c = isrequired[idx]; printstyled(io, lpad(idx, nd), ' ', c ? "t " : "f "; color = c ? :cyan : :plain)) postprint(::IO) = nothing postprint(io::IO, idx::Int, bbchanged::Bool) = nothing print_with_code(preprint, postprint, io, src) end function print_with_code(io::IO, frame::Frame, obj) src = frame.framecode.src if isdefined(JuliaInterpreter, :reverse_lookup_globalref!) src = copy(src) JuliaInterpreter.reverse_lookup_globalref!(src.code) end print_with_code(io, src, obj) end
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
15639
# This was copied from Julia's source code (base/compiler/ssair/domtree.jl) and # unnecessary parts were removed. The original license statement is: # # This file is a part of Julia. License is MIT: https://julialang.org/license # A few items needed to be added: using Core.Compiler: BasicBlock import Base: length, copy, copy! # END additions const BBNumber = Int const PreNumber = Int const PostNumber = Int struct DFSTree # These map between BB number and pre- or postorder numbers to_pre::Vector{PreNumber} from_pre::Vector{BBNumber} to_post::Vector{PostNumber} from_post::Vector{BBNumber} # Records parent relationships in the DFS tree # (preorder number -> preorder number) # Storing it this way saves a few lookups in the snca_compress! algorithm to_parent_pre::Vector{PreNumber} end function DFSTree(n_blocks::Int) return DFSTree(zeros(PreNumber, n_blocks), Vector{BBNumber}(undef, n_blocks), zeros(PostNumber, n_blocks), Vector{BBNumber}(undef, n_blocks), zeros(PreNumber, n_blocks)) end copy(D::DFSTree) = DFSTree(copy(D.to_pre), copy(D.from_pre), copy(D.to_post), copy(D.from_post), copy(D.to_parent_pre)) function copy!(dst::DFSTree, src::DFSTree) copy!(dst.to_pre, src.to_pre) copy!(dst.from_pre, src.from_pre) copy!(dst.to_post, src.to_post) copy!(dst.from_post, src.from_post) copy!(dst.to_parent_pre, src.to_parent_pre) return dst end length(D::DFSTree) = length(D.from_pre) function DFS!(D::DFSTree, blocks::Vector{BasicBlock}, is_post_dominator::Bool) copy!(D, DFSTree(length(blocks))) if is_post_dominator # TODO: We're using -1 as the virtual exit node here. Would it make # sense to actually have a real BB for the exit always? to_visit = Tuple{BBNumber, PreNumber, Bool}[(-1, 0, false)] else to_visit = Tuple{BBNumber, PreNumber, Bool}[(1, 0, false)] end pre_num = is_post_dominator ? 0 : 1 post_num = 1 while !isempty(to_visit) # Because we want the postorder number as well as the preorder number, # we don't pop the current node from the stack until we're moving up # the tree (current_node_bb, parent_pre, pushed_children) = to_visit[end] if pushed_children # Going up the DFS tree, so all we need to do is record the # postorder number, then move on if current_node_bb != -1 D.to_post[current_node_bb] = post_num D.from_post[post_num] = current_node_bb end post_num += 1 pop!(to_visit) elseif current_node_bb != -1 && D.to_pre[current_node_bb] != 0 # Node has already been visited, move on pop!(to_visit) continue else # Going down the DFS tree # Record preorder number if current_node_bb != -1 D.to_pre[current_node_bb] = pre_num D.from_pre[pre_num] = current_node_bb D.to_parent_pre[pre_num] = parent_pre end # Record that children (will) have been pushed to_visit[end] = (current_node_bb, parent_pre, true) if is_post_dominator && current_node_bb == -1 edges = Int[bb for bb in 1:length(blocks) if isempty(blocks[bb].succs)] else edges = is_post_dominator ? blocks[current_node_bb].preds : blocks[current_node_bb].succs end # Push children to the stack for succ_bb in edges if succ_bb == 0 # Edge 0 indicates an error entry, but shouldn't affect # the post-dominator tree. @assert is_post_dominator continue end push!(to_visit, (succ_bb, pre_num, false)) end pre_num += 1 end end # If all blocks are reachable, this is a no-op, otherwise, we shrink these # arrays. resize!(D.from_pre, pre_num - 1) resize!(D.from_post, post_num - 1) # should be same size as pre_num - 1 resize!(D.to_parent_pre, pre_num - 1) return D end DFS(blocks::Vector{BasicBlock}, is_post_dominator::Bool=false) = DFS!(DFSTree(0), blocks, is_post_dominator) """ Keeps the per-BB state of the Semi NCA algorithm. In the original formulation, there are three separate length `n` arrays, `label`, `semi` and `ancestor`. Instead, for efficiency, we use one array in a array-of-structs style setup. """ struct SNCAData semi::PreNumber label::PreNumber end "Represents a Basic Block, in the DomTree" struct DomTreeNode # How deep we are in the DomTree level::Int # The BB indices in the CFG for all Basic Blocks we immediately dominate children::Vector{BBNumber} end DomTreeNode() = DomTreeNode(1, Vector{BBNumber}()) "Data structure that encodes which basic block dominates which." struct GenericDomTree{IsPostDom} # These can be reused when updating domtree dynamically dfs_tree::DFSTree snca_state::Vector{SNCAData} # Which basic block immediately dominates each basic block, using BB indices idoms_bb::Vector{BBNumber} # The nodes in the tree (ordered by BB indices) nodes::Vector{DomTreeNode} end const DomTree = GenericDomTree{false} const PostDomTree = GenericDomTree{true} function (T::Type{<:GenericDomTree})() return T(DFSTree(0), SNCAData[], BBNumber[], DomTreeNode[]) end function construct_domtree(blocks::Vector{BasicBlock}) return update_domtree!(blocks, DomTree(), true, 0) end function construct_postdomtree(blocks::Vector{BasicBlock}) return update_domtree!(blocks, PostDomTree(), true, 0) end function update_domtree!(blocks::Vector{BasicBlock}, domtree::GenericDomTree{IsPostDom}, recompute_dfs::Bool, max_pre::PreNumber) where {IsPostDom} if recompute_dfs DFS!(domtree.dfs_tree, blocks, IsPostDom) end if max_pre == 0 max_pre = length(domtree.dfs_tree) end SNCA!(domtree, blocks, max_pre) compute_domtree_nodes!(domtree) return domtree end function compute_domtree_nodes!(domtree::GenericDomTree{IsPostDom}) where {IsPostDom} # Compute children copy!(domtree.nodes, DomTreeNode[DomTreeNode() for _ in 1:length(domtree.idoms_bb)]) for (idx, idom) in Iterators.enumerate(domtree.idoms_bb) ((!IsPostDom && idx == 1) || idom == 0) && continue push!(domtree.nodes[idom].children, idx) end # n.b. now issorted(domtree.nodes[*].children) since idx is sorted above # Recursively set level if IsPostDom for (node, idom) in enumerate(domtree.idoms_bb) idom == 0 || continue update_level!(domtree.nodes, node, 1) end else update_level!(domtree.nodes, 1, 1) end return domtree.nodes end function update_level!(nodes::Vector{DomTreeNode}, node::BBNumber, level::Int) worklist = Tuple{BBNumber, Int}[(node, level)] while !isempty(worklist) (node, level) = pop!(worklist) nodes[node] = DomTreeNode(level, nodes[node].children) foreach(nodes[node].children) do child push!(worklist, (child, level+1)) end end end dom_edges(domtree::DomTree, blocks::Vector{BasicBlock}, idx::BBNumber) = blocks[idx].preds dom_edges(domtree::PostDomTree, blocks::Vector{BasicBlock}, idx::BBNumber) = blocks[idx].succs """ The main Semi-NCA algorithm. Matches Figure 2.8 in [LG05]. Note that the pseudocode in [LG05] is not entirely accurate. The best way to understand what's happening is to read [LT79], then the description of SLT in [LG05] (warning: inconsistent notation), then the description of Semi-NCA. """ function SNCA!(domtree::GenericDomTree{IsPostDom}, blocks::Vector{BasicBlock}, max_pre::PreNumber) where {IsPostDom} D = domtree.dfs_tree state = domtree.snca_state # There may be more blocks than are reachable in the DFS / dominator tree n_blocks = length(blocks) n_nodes = length(D) # `label` is initialized to the identity mapping (though the paper doesn't # make that clear). The rationale for this is Lemma 2.4 in [LG05] (i.e. # Theorem 4 in [LT79]). Note however, that we don't ever look at `semi` # until it is fully initialized, so we could leave it uninitialized here if # we wanted to. resize!(state, n_nodes) for w in 1:max_pre # Only reset semidominators for nodes we want to recompute state[w] = SNCAData(typemax(PreNumber), w) end # If we are only recomputing some of the semidominators, the remaining # labels should be reset, because they may have become inapplicable to the # node/semidominator we are currently processing/recomputing. They can # become inapplicable because of path compressions that were triggered by # nodes that should only be processed after the current one (but were # processed the last time `SNCA!` was run). # # So, for every node that is not being reprocessed, we reset its label to # its semidominator, which is the value that its label assumes once its # semidominator is computed. If this was too conservative, i.e. if the # label would have been updated before we process the current node in a # situation where all semidominators were recomputed, then path compression # will produce the correct label. for w in max_pre+1:n_nodes semi = state[w].semi state[w] = SNCAData(semi, semi) end # Calculate semidominators, but only for blocks with preorder number up to # max_pre ancestors = copy(D.to_parent_pre) relevant_blocks = IsPostDom ? (1:max_pre) : (2:max_pre) for w::PreNumber in reverse(relevant_blocks) # LLVM initializes this to the parent, the paper initializes this to # `w`, but it doesn't really matter (the parent is a predecessor, so at # worst we'll discover it below). Save a memory reference here. semi_w = typemax(PreNumber) last_linked = PreNumber(w + 1) for v ∈ dom_edges(domtree, blocks, D.from_pre[w]) # For the purpose of the domtree, ignore virtual predecessors into # catch blocks. v == 0 && continue v_pre = D.to_pre[v] # Ignore unreachable predecessors v_pre == 0 && continue # N.B.: This conditional is missing from the pseudocode in figure # 2.8 of [LG05]. It corresponds to the `ancestor[v] != 0` check in # the `eval` implementation in figure 2.6 if v_pre >= last_linked # `v` has already been processed, so perform path compression # For performance, if the number of ancestors is small avoid # the extra allocation of the worklist. if length(ancestors) <= 32 snca_compress!(state, ancestors, v_pre, last_linked) else snca_compress_worklist!(state, ancestors, v_pre, last_linked) end end # The (preorder number of the) semidominator of a block is the # minimum over the labels of its predecessors semi_w = min(semi_w, state[v_pre].label) end state[w] = SNCAData(semi_w, semi_w) end # Compute immediate dominators, which for a node must be the nearest common # ancestor in the (immediate) dominator tree between its semidominator and # its parent (see Lemma 2.6 in [LG05]). idoms_pre = copy(D.to_parent_pre) for v in (IsPostDom ? (1:n_nodes) : (2:n_nodes)) idom = idoms_pre[v] vsemi = state[v].semi while idom > vsemi idom = idoms_pre[idom] end idoms_pre[v] = idom end # Express idoms in BB indexing resize!(domtree.idoms_bb, n_blocks) for i::BBNumber in 1:n_blocks if (!IsPostDom && i == 1) || D.to_pre[i] == 0 domtree.idoms_bb[i] = 0 else ip = idoms_pre[D.to_pre[i]] domtree.idoms_bb[i] = ip == 0 ? 0 : D.from_pre[ip] end end end """ Matches the snca_compress algorithm in Figure 2.8 of [LG05], with the modification suggested in the paper to use `last_linked` to determine whether an ancestor has been processed rather than storing `0` in the ancestor array. """ function snca_compress!(state::Vector{SNCAData}, ancestors::Vector{PreNumber}, v::PreNumber, last_linked::PreNumber) u = ancestors[v] @assert u < v if u >= last_linked snca_compress!(state, ancestors, u, last_linked) if state[u].label < state[v].label state[v] = SNCAData(state[v].semi, state[u].label) end ancestors[v] = ancestors[u] end nothing end function snca_compress_worklist!( state::Vector{SNCAData}, ancestors::Vector{PreNumber}, v::PreNumber, last_linked::PreNumber) # TODO: There is a smarter way to do this u = ancestors[v] worklist = Tuple{PreNumber, PreNumber}[(u,v)] @assert u < v while !isempty(worklist) u, v = last(worklist) if u >= last_linked if ancestors[u] >= last_linked push!(worklist, (ancestors[u], u)) continue end if state[u].label < state[v].label state[v] = SNCAData(state[v].semi, state[u].label) end ancestors[v] = ancestors[u] end pop!(worklist) end end """ dominates(domtree::DomTree, bb1::Int, bb2::Int) -> Bool Checks if `bb1` dominates `bb2`. `bb1` and `bb2` are indexes into the `CFG` blocks. `bb1` dominates `bb2` if the only way to enter `bb2` is via `bb1`. (Other blocks may be in between, e.g `bb1->bbx->bb2`). """ dominates(domtree::DomTree, bb1::BBNumber, bb2::BBNumber) = _dominates(domtree, bb1, bb2) """ postdominates(domtree::PostDomTree, bb1::Int, bb2::Int) -> Bool Checks if `bb1` post-dominates `bb2`. `bb1` and `bb2` are indexes into the `CFG` blocks. `bb1` post-dominates `bb2` if every pass from `bb2` to the exit is via `bb1`. (Other blocks may be in between, e.g `bb2->bbx->bb1->exit`). """ postdominates(domtree::PostDomTree, bb1::BBNumber, bb2::BBNumber) = _dominates(domtree, bb1, bb2) function _dominates(domtree::GenericDomTree, bb1::BBNumber, bb2::BBNumber) bb1 == bb2 && return true target_level = domtree.nodes[bb1].level source_level = domtree.nodes[bb2].level source_level < target_level && return false for _ in (source_level - 1):-1:target_level bb2 = domtree.idoms_bb[bb2] end return bb1 == bb2 end """ nearest_common_dominator(domtree::GenericDomTree, a::BBNumber, b::BBNumber) Compute the nearest common (post-)dominator of `a` and `b`. """ function nearest_common_dominator(domtree::GenericDomTree, a::BBNumber, b::BBNumber) a == 0 && return a b == 0 && return b alevel = domtree.nodes[a].level blevel = domtree.nodes[b].level # W.l.g. assume blevel <= alevel if alevel < blevel a, b = b, a alevel, blevel = blevel, alevel end while alevel > blevel a = domtree.idoms_bb[a] alevel -= 1 end while a != b && a != 0 a = domtree.idoms_bb[a] b = domtree.idoms_bb[b] end @assert a == b return a end
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
2242
if isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol("@optlevel")) @eval Base.Experimental.@optlevel 1 end using Core: SimpleVector using Core.IR using Base.Meta: isexpr const SSAValues = Union{Core.Compiler.SSAValue, JuliaInterpreter.SSAValue} const trackedheads = (:method,) const structdecls = (:_structtype, :_abstracttype, :_primitivetype) export signature, rename_framemethods!, methoddef!, methoddefs!, bodymethod export CodeEdges, lines_required, lines_required!, selective_eval!, selective_eval_fromstart! include("utils.jl") include("signatures.jl") include("codeedges.jl") if Base.VERSION < v"1.10" include("domtree.jl") else const construct_domtree = Core.Compiler.construct_domtree const construct_postdomtree = Core.Compiler.construct_postdomtree const postdominates = Core.Compiler.postdominates const nearest_common_dominator = Core.Compiler.nearest_common_dominator end # precompilation if ccall(:jl_generating_output, Cint, ()) == 1 ex = :(f(x; color::Symbol=:green) = 2x) lwr = Meta.lower(@__MODULE__, ex) frame = Frame(@__MODULE__, lwr.args[1]) rename_framemethods!(frame) ex = quote s = 0 k = 5 for i = 1:3 global s, k s += rand(1:5) k += i end end lwr = Meta.lower(@__MODULE__, ex) src = lwr.args[1] edges = CodeEdges(@__MODULE__, src) isrequired = lines_required(GlobalRef(@__MODULE__, :s), src, edges) lines_required(GlobalRef(@__MODULE__, :s), src, edges; norequire=()) lines_required(GlobalRef(@__MODULE__, :s), src, edges; norequire=exclude_named_typedefs(src, edges)) for isreq in (isrequired, convert(Vector{Bool}, isrequired)) lines_required!(isreq, src, edges; norequire=()) lines_required!(isreq, src, edges; norequire=exclude_named_typedefs(src, edges)) end frame = Frame(@__MODULE__, src) # selective_eval_fromstart!(frame, isrequired, true) precompile(selective_eval_fromstart!, (typeof(frame), typeof(isrequired), Bool)) # can't @eval during precompilation print_with_code(Base.inferencebarrier(devnull)::IO, src, edges) print_with_code(Base.inferencebarrier(devnull)::IO, src, isrequired) end
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
29231
""" sig = signature(sigsv::SimpleVector) Compute a method signature from a suitable `SimpleVector`: `sigsv[1]` holds the signature and `sigsv[2]` the `TypeVar`s. # Example: For `f(x::AbstractArray{T}) where T`, the corresponding `sigsv` is constructed as T = TypeVar(:T) sig1 = Core.svec(typeof(f), AbstractArray{T}) sig2 = Core.svec(T) sigsv = Core.svec(sig1, sig2) sig = signature(sigsv) """ function signature(sigsv::SimpleVector) sigp::SimpleVector, sigtv::SimpleVector = sigsv sig = Tuple{sigp...} for i = length(sigtv):-1:1 sig = UnionAll(sigtv[i], sig) end return sig::Union{DataType,UnionAll} end """ sigt, lastpc = signature(recurse, frame, pc) sigt, lastpc = signature(frame, pc) Compute the signature-type `sigt` of a method whose definition in `frame` starts at `pc`. Generally, `pc` should point to the `Expr(:method, methname)` statement, in which case `lastpc` is the final statement number in `frame` that is part of the signature (i.e, the line above the 3-argument `:method` expression). Alternatively, `pc` can point to the 3-argument `:method` expression, as long as all the relevant SSAValues have been assigned. In this case, `lastpc == pc`. If no 3-argument `:method` expression is found, `sigt` will be `nothing`. """ function signature(@nospecialize(recurse), frame::Frame, @nospecialize(stmt), pc) mod = moduleof(frame) lastpc = frame.pc = pc while !isexpr(stmt, :method, 3) # wait for the 3-arg version if isanonymous_typedef(stmt) lastpc = pc = step_through_methoddef(recurse, frame, stmt) # define an anonymous function elseif is_Typeof_for_anonymous_methoddef(stmt, frame.framecode.src.code, mod) return nothing, pc else lastpc = pc pc = step_expr!(recurse, frame, stmt, true) pc === nothing && return nothing, lastpc end stmt = pc_expr(frame, pc) end isa(stmt, Expr) || return nothing, pc sigsv = @lookup(frame, stmt.args[2])::SimpleVector sigt = signature(sigsv) return sigt, lastpc end signature(@nospecialize(recurse), frame::Frame, pc) = signature(recurse, frame, pc_expr(frame, pc), pc) signature(frame::Frame, pc) = signature(finish_and_return!, frame, pc) function is_Typeof_for_anonymous_methoddef(@nospecialize(stmt), code::Vector{Any}, mod::Module) isexpr(stmt, :call) || return false f = stmt.args[1] isa(f, QuoteNode) || return false f.value === Core.Typeof || return false arg1 = stmt.args[2] if isa(arg1, SSAValue) arg1 = code[arg1.id] end arg1 isa Symbol || return false return !isdefined(mod, arg1) end function minid(@nospecialize(node), stmts, id) if isa(node, SSAValue) id = min(id, node.id) stmt = stmts[node.id] return minid(stmt, stmts, id) elseif isa(node, Expr) for a in node.args id = minid(a, stmts, id) end end return id end function signature_top(frame, stmt::Expr, pc) @assert ismethod3(stmt) return minid(stmt.args[2], frame.framecode.src.code, pc) end function step_through_methoddef(@nospecialize(recurse), frame, @nospecialize(stmt)) while !isexpr(stmt, :method) pc = step_expr!(recurse, frame, stmt, true) stmt = pc_expr(frame, pc) end return step_expr!(recurse, frame, stmt, true) # also define the method end """ MethodInfo(start, stop, refs) Given a frame and its CodeInfo, `start` is the line of the first `Expr(:method, name)`, whereas `stop` is the line of the last `Expr(:method, name, sig, src)` expression for `name`. `refs` is a vector of line numbers of other references. Some of these will be the location of the "declaration" of a method, the `:thunk` expression containing a CodeInfo that just returns a 1-argument `:method` expression. Others may be `:global` declarations. In some cases there may be more than one method with the same name in the `start:stop` range. """ mutable struct MethodInfo start::Int stop::Int refs::Vector{Int} end MethodInfo(start) = MethodInfo(start, -1, Int[]) struct SelfCall linetop::Int linebody::Int callee::GlobalRef caller::Union{GlobalRef,Bool,Nothing} end """ methodinfos, selfcalls = identify_framemethod_calls(frame) Analyze the code in `frame` to locate method definitions and "self-calls," i.e., calls to methods defined in `frame` that occur within `frame`. `methodinfos` is a Dict of `name=>info` pairs, where `info` is a [`MethodInfo`](@ref). `selfcalls` is a list of `SelfCall(linetop, linebody, callee, caller)` that holds the location of calls the methods defined in `frame`. `linetop` is the line in `frame` (top meaning "top level"), which will correspond to a 3-argument `:method` expression containing a `CodeInfo` body. `linebody` is the line within the `CodeInfo` body from which the call is made. `callee` is the Symbol of the called method. """ function identify_framemethod_calls(frame) refs = Pair{GlobalRef,Int}[] methodinfos = Dict{GlobalRef,MethodInfo}() selfcalls = SelfCall[] for (i, stmt) in enumerate(frame.framecode.src.code) isa(stmt, Expr) || continue if stmt.head === :global && length(stmt.args) == 1 key = normalize_defsig(stmt.args[1], frame) if isa(key, GlobalRef) # We don't know for sure if this is a reference to a method, but let's # tentatively cue it push!(refs, key=>i) end elseif stmt.head === :thunk && stmt.args[1] isa CodeInfo tsrc = stmt.args[1]::CodeInfo if length(tsrc.code) == 1 tstmt = tsrc.code[1] if is_return(tstmt) tex = tstmt.val if isa(tex, Expr) if tex.head === :method && (methname = tex.args[1]; isa(methname, Union{Symbol, GlobalRef})) push!(refs, normalize_defsig(methname, frame)=>i) end end end end elseif ismethod1(stmt) key = stmt.args[1] key = normalize_defsig(key, frame) key = key::GlobalRef mi = get(methodinfos, key, nothing) if mi === nothing methodinfos[key] = MethodInfo(i) else mi.stop == -1 && (mi.start = i) # advance the statement # unless we've seen the method3 end elseif ismethod3(stmt) key = stmt.args[1] key = normalize_defsig(key, frame) if key isa GlobalRef # XXX A temporary hack to fix https://github.com/JuliaDebug/LoweredCodeUtils.jl/issues/80 # We should revisit it. mi = get(methodinfos, key, MethodInfo(1)) mi.stop = i elseif key isa Expr # this is a module-scoped call. We don't have to worry about these because they are named continue end msrc = stmt.args[3] if msrc isa CodeInfo key = key::Union{GlobalRef,Bool,Nothing} for (j, mstmt) in enumerate(msrc.code) isa(mstmt, Expr) || continue jj = j if mstmt.head === :call mkey = normalize_defsig(mstmt.args[1], frame) if isa(mkey, SSAValue) || isa(mkey, Core.SSAValue) refstmt = msrc.code[mkey.id] if isa(refstmt, Union{Symbol, GlobalRef}) jj = mkey.id mkey = normalize_defsig(refstmt, frame) end end if is_global_ref(mkey, Core, isdefined(Core, :_apply_iterate) ? :_apply_iterate : :_apply) ssaref = mstmt.args[end-1] if isa(ssaref, JuliaInterpreter.SSAValue) id = ssaref.id has_self_call(msrc, msrc.code[id]) || continue end mkey = normalize_defsig(mstmt.args[end-2], frame) if isa(mkey, GlobalRef) haskey(methodinfos, mkey) && push!(selfcalls, SelfCall(i, jj, mkey, key)) end elseif isa(mkey, GlobalRef) haskey(methodinfos, mkey) && push!(selfcalls, SelfCall(i, jj, mkey, key)) end elseif mstmt.head === :meta && mstmt.args[1] === :generated newex = mstmt.args[2] if isa(newex, Expr) if newex.head === :new && length(newex.args) >= 2 && is_global_ref(newex.args[1], Core, :GeneratedFunctionStub) mkey = newex.args[2] if isa(mkey, Symbol) mkey = GlobalRef(moduleof(frame), mkey) end haskey(methodinfos, mkey) && push!(selfcalls, SelfCall(i, jj, mkey, key)) end end end end end end end for r in refs mi = get(methodinfos, r.first, nothing) mi === nothing || push!(mi.refs, r.second) end return methodinfos, selfcalls end # try to normalize `def` to `GlobalRef` representation function normalize_defsig(@nospecialize(def), mod::Module) if def isa QuoteNode def = nameof(def.value) end if def isa Symbol def = GlobalRef(mod, def) end return def end normalize_defsig(@nospecialize(def), frame::Frame) = normalize_defsig(def, moduleof(frame)) function callchain(selfcalls) calledby = Dict{GlobalRef,Union{GlobalRef,Bool,Nothing}}() for sc in selfcalls startswith(String(sc.callee.name), '#') || continue caller = get(calledby, sc.callee, nothing) if caller === nothing calledby[sc.callee] = sc.caller elseif caller == sc.caller else error("unexpected multiple callers, ", caller, " and ", sc.caller) end end return calledby end function set_to_running_name!(@nospecialize(recurse), replacements, frame, methodinfos, selfcall, calledby, callee, caller) if isa(caller, GlobalRef) && startswith(String(caller.name), '#') rep = get(replacements, caller, nothing) if rep === nothing parentcaller = get(calledby, caller, nothing) if parentcaller !== nothing set_to_running_name!(recurse, replacements, frame, methodinfos, selfcall, calledby, caller, parentcaller) end else caller = rep end end # Back up to the beginning of the signature pc = selfcall.linetop stmt = pc_expr(frame, pc) while pc > 1 && !ismethod1(stmt) pc -= 1 stmt = pc_expr(frame, pc) end @assert ismethod1(stmt) cname, _pc, _ = try get_running_name(recurse, frame, pc+1, callee, get(replacements, caller, caller)) catch err if isa(err, UndefVarError) # The function may not be defined, in which case there is nothing to replace return replacements end throw(err) end replacements[callee] = cname mi = methodinfos[cname] = methodinfos[callee] src = frame.framecode.src replacename!(@view(src.code[mi.start:mi.stop]), callee=>cname) # the method itself for r in mi.refs # the references replacename!((src.code[r])::Expr, callee=>cname) end return replacements end """ methranges = rename_framemethods!(frame) methranges = rename_framemethods!(recurse, frame) Rename the gensymmed methods in `frame` to match those that are currently active. The issues are described in https://github.com/JuliaLang/julia/issues/30908. `frame` will be modified in-place as needed. Returns a vector of `name=>start:stop` pairs specifying the range of lines in `frame` at which method definitions occur. In some cases there may be more than one method with the same name in the `start:stop` range. """ function rename_framemethods!(@nospecialize(recurse), frame::Frame, methodinfos, selfcalls, calledby) src = frame.framecode.src replacements = Dict{GlobalRef,GlobalRef}() for (callee, caller) in calledby (!startswith(String(callee.name), '#') || haskey(replacements, callee)) && continue idx = findfirst(sc->sc.callee === callee && sc.caller === caller, selfcalls) idx === nothing && continue try set_to_running_name!(recurse, replacements, frame, methodinfos, selfcalls[idx], calledby, callee, caller) catch err @warn "skipping callee $callee (called by $caller) due to $err" end end for sc in selfcalls linetop, linebody, callee, caller = sc.linetop, sc.linebody, sc.callee, sc.caller cname = get(replacements, callee, nothing) if cname !== nothing && cname !== callee replacename!((src.code[linetop].args[3])::CodeInfo, callee=>cname) end end return methodinfos end function rename_framemethods!(@nospecialize(recurse), frame::Frame) pc0 = frame.pc methodinfos, selfcalls = identify_framemethod_calls(frame) calledby = callchain(selfcalls) rename_framemethods!(recurse, frame, methodinfos, selfcalls, calledby) frame.pc = pc0 return methodinfos end rename_framemethods!(frame::Frame) = rename_framemethods!(finish_and_return!, frame) """ pctop, isgen = find_name_caller_sig(recurse, frame, pc, name, parentname) Scans forward from `pc` in `frame` until a method is found that calls `name`. `pctop` points to the beginning of that method's signature. `isgen` is true if `name` corresponds to sa GeneratedFunctionStub. Alternatively, this returns `nothing` if `pc` does not appear to point to either a keyword or generated method. """ function find_name_caller_sig(@nospecialize(recurse), frame, pc, name, parentname) stmt = pc_expr(frame, pc) while true pc0 = pc while !ismethod3(stmt) pc = next_or_nothing(recurse, frame, pc) pc === nothing && return nothing stmt = pc_expr(frame, pc) end body = stmt.args[3] if normalize_defsig(stmt.args[1], frame) !== name && isa(body, CodeInfo) # This might be the GeneratedFunctionStub for a @generated method for (i, bodystmt) in enumerate(body.code) if isexpr(bodystmt, :meta) && (bodystmt::Expr).args[1] === :generated return signature_top(frame, stmt, pc), true end i >= 5 && break # we should find this early end if length(body.code) > 1 bodystmt = body.code[end-1] # the line before the final return iscallto(bodystmt, moduleof(frame), name, body) && return signature_top(frame, stmt, pc), false end end pc = next_or_nothing(recurse, frame, pc) pc === nothing && return nothing stmt = pc_expr(frame, pc) end end """ replacename!(stmts, oldname=>newname) Replace a Symbol `oldname` with `newname` in `stmts`. """ function replacename!(ex::Expr, pr) replacename!(ex.args, pr) return ex end replacename!(src::CodeInfo, pr) = replacename!(src.code, pr) function replacename!(args::AbstractVector, pr) oldname, newname = pr for i = 1:length(args) a = args[i] if isa(a, Expr) replacename!(a, pr) elseif isa(a, CodeInfo) replacename!(a.code, pr) elseif isa(a, QuoteNode) && a.value === oldname args[i] = QuoteNode(newname) elseif isa(a, Vector{Any}) replacename!(a, pr) elseif isa(a, Core.ReturnNode) && isdefined(a, :val) && a.val isa Expr # there is something like `ReturnNode(Expr(:method, Symbol(...)))` replacename!(a.val::Expr, pr) elseif a === oldname args[i] = newname elseif isa(a, Symbol) && a == oldname.name args[i] = newname.name end end return args end function get_running_name(@nospecialize(recurse), frame, pc, name, parentname) nameinfo = find_name_caller_sig(recurse, frame, pc, name, parentname) if nameinfo === nothing pc = skip_until(@nospecialize(stmt)->isexpr(stmt, :method, 3), frame, pc) pc = next_or_nothing(recurse, frame, pc) return name, pc, nothing end pctop, isgen = nameinfo # Sometimes signature_top---which follows SSAValue links backwards to find the first # line needed to define the signature---misses out on a SlotNumber assignment. # Fix https://github.com/timholy/Revise.jl/issues/422 stmt = pc_expr(frame, pctop) while pctop > 1 && isa(stmt, SlotNumber) && !isassigned(frame.framedata.locals, pctop) pctop -= 1 stmt = pc_expr(frame, pctop) end # end fix sigtparent, lastpcparent = signature(recurse, frame, pctop) sigtparent === nothing && return name, pc, lastpcparent methparent = whichtt(sigtparent) methparent === nothing && return name, pc, lastpcparent # caller isn't defined, no correction is needed if isgen cname = GlobalRef(moduleof(frame), nameof(methparent.generator.gen)) else bodyparent = Base.uncompressed_ast(methparent) bodystmt = bodyparent.code[end-1] @assert isexpr(bodystmt, :call) ref = getcallee(bodystmt) if isa(ref, SSAValue) || isa(ref, Core.SSAValue) ref = bodyparent.code[ref.id] end isa(ref, GlobalRef) || @show ref typeof(ref) @assert isa(ref, GlobalRef) @assert ref.mod == moduleof(frame) cname = ref end return cname, pc, lastpcparent end """ nextpc = next_or_nothing([recurse], frame, pc) nextpc = next_or_nothing!([recurse], frame) Advance the program counter without executing the corresponding line. If `frame` is finished, `nextpc` will be `nothing`. """ next_or_nothing(frame, pc) = next_or_nothing(finish_and_return!, frame, pc) next_or_nothing(@nospecialize(recurse), frame, pc) = pc < nstatements(frame.framecode) ? pc+1 : nothing next_or_nothing!(frame) = next_or_nothing!(finish_and_return!, frame) function next_or_nothing!(@nospecialize(recurse), frame) pc = frame.pc if pc < nstatements(frame.framecode) return frame.pc = pc + 1 end return nothing end """ nextpc = skip_until(predicate, [recurse], frame, pc) nextpc = skip_until!(predicate, [recurse], frame) Advance the program counter until `predicate(stmt)` return `true`. """ skip_until(predicate, frame, pc) = skip_until(predicate, finish_and_return!, frame, pc) function skip_until(predicate, @nospecialize(recurse), frame, pc) stmt = pc_expr(frame, pc) while !predicate(stmt) pc = next_or_nothing(recurse, frame, pc) pc === nothing && return nothing stmt = pc_expr(frame, pc) end return pc end skip_until!(predicate, frame) = skip_until!(predicate, finish_and_return!, frame) function skip_until!(predicate, @nospecialize(recurse), frame) pc = frame.pc stmt = pc_expr(frame, pc) while !predicate(stmt) pc = next_or_nothing!(recurse, frame) pc === nothing && return nothing stmt = pc_expr(frame, pc) end return pc end """ ret = methoddef!(recurse, signatures, frame; define=true) ret = methoddef!(signatures, frame; define=true) Compute the signature of a method definition. `frame.pc` should point to a `:method` expression. Upon exit, the new signature will be added to `signatures`. There are several possible return values: pc, pc3 = ret is the typical return. `pc` will point to the next statement to be executed, or be `nothing` if there are no further statements in `frame`. `pc3` will point to the 3-argument `:method` expression. Alternatively, pc = ret occurs for "empty method" expressions, e.g., `:(function foo end)`. `pc` will be `nothing`. By default the method will be defined (evaluated). You can prevent this by setting `define=false`. This is recommended if you are simply extracting signatures from code that has already been evaluated. """ function methoddef!(@nospecialize(recurse), signatures, frame::Frame, @nospecialize(stmt), pc::Int; define::Bool=true) framecode, pcin = frame.framecode, pc if ismethod3(stmt) pc3 = pc arg1 = stmt.args[1] sigt, pc = signature(recurse, frame, stmt, pc) meth = whichtt(sigt) if isa(meth, Method) && (meth.sig <: sigt && sigt <: meth.sig) pc = define ? step_expr!(recurse, frame, stmt, true) : next_or_nothing!(recurse, frame) elseif define pc = step_expr!(recurse, frame, stmt, true) meth = whichtt(sigt) end if isa(meth, Method) && (meth.sig <: sigt && sigt <: meth.sig) push!(signatures, meth.sig) else if arg1 === false || arg1 === nothing # If it's anonymous and not defined, define it pc = step_expr!(recurse, frame, stmt, true) meth = whichtt(sigt) isa(meth, Method) && push!(signatures, meth.sig) return pc, pc3 else # guard against busted lookup, e.g., https://github.com/JuliaLang/julia/issues/31112 code = framecode.src codeloc = codelocation(code, pc) loc = linetable(code, codeloc) ft = Base.unwrap_unionall((Base.unwrap_unionall(sigt)::DataType).parameters[1]) if !startswith(String((ft.name::Core.TypeName).name), "##") @warn "file $(loc.file), line $(loc.line): no method found for $sigt" end if pc == pc3 pc = next_or_nothing!(recurse, frame) end end end frame.pc = pc return pc, pc3 end ismethod1(stmt) || Base.invokelatest(error, "expected method opening, got ", stmt) name = normalize_defsig(stmt.args[1], frame) if isa(name, Bool) error("not valid for anonymous methods") elseif name === missing Base.invokelatest(error, "given invalid definition: ", stmt) end name = name::GlobalRef # Is there any 3-arg method definition with the same name? If not, avoid risk of executing code that # we shouldn't (fixes https://github.com/timholy/Revise.jl/issues/758) found = false for i = pc+1:length(framecode.src.code) newstmt = framecode.src.code[i] if ismethod3(newstmt) if ismethod_with_name(framecode.src, newstmt, string(name.name)) found = true break end end end found || return nothing while true # methods containing inner methods may need multiple trips through this loop sigt, pc = signature(recurse, frame, stmt, pc) stmt = pc_expr(frame, pc) while !isexpr(stmt, :method, 3) pc = next_or_nothing(recurse, frame, pc) # this should not check define, we've probably already done this once pc === nothing && return nothing # this was just `function foo end`, signal "no def" stmt = pc_expr(frame, pc) end pc3 = pc stmt = stmt::Expr name3 = normalize_defsig(stmt.args[1], frame) sigt === nothing && (error("expected a signature"); return next_or_nothing(recurse, frame, pc)), pc3 # Methods like f(x::Ref{<:Real}) that use gensymmed typevars will not have the *exact* # signature of the active method. So let's get the active signature. frame.pc = pc pc = define ? step_expr!(recurse, frame, stmt, true) : next_or_nothing!(recurse, frame) meth = whichtt(sigt) isa(meth, Method) && push!(signatures, meth.sig) # inner methods are not visible name === name3 && return pc, pc3 # if this was an inner method we should keep going stmt = pc_expr(frame, pc) # there *should* be more statements in this frame end end methoddef!(@nospecialize(recurse), signatures, frame::Frame, pc::Int; define=true) = methoddef!(recurse, signatures, frame, pc_expr(frame, pc), pc; define=define) function methoddef!(@nospecialize(recurse), signatures, frame::Frame; define=true) pc = frame.pc stmt = pc_expr(frame, pc) if !ismethod(stmt) pc = next_until!(ismethod, recurse, frame, true) end pc === nothing && error("pc at end of frame without finding a method") methoddef!(recurse, signatures, frame, pc; define=define) end methoddef!(signatures, frame::Frame; define=true) = methoddef!(finish_and_return!, signatures, frame; define=define) function methoddefs!(@nospecialize(recurse), signatures, frame::Frame, pc; define=true) ret = methoddef!(recurse, signatures, frame, pc; define=define) pc = ret === nothing ? ret : ret[1] return _methoddefs!(recurse, signatures, frame, pc; define=define) end function methoddefs!(@nospecialize(recurse), signatures, frame::Frame; define=true) ret = methoddef!(recurse, signatures, frame; define=define) pc = ret === nothing ? ret : ret[1] return _methoddefs!(recurse, signatures, frame, pc; define=define) end methoddefs!(signatures, frame::Frame; define=true) = methoddefs!(finish_and_return!, signatures, frame; define=define) function _methoddefs!(@nospecialize(recurse), signatures, frame::Frame, pc; define=define) while pc !== nothing stmt = pc_expr(frame, pc) if !ismethod(stmt) pc = next_until!(ismethod, recurse, frame, true) end pc === nothing && break ret = methoddef!(recurse, signatures, frame, pc; define=define) pc = ret === nothing ? ret : ret[1] end return pc end function is_self_call(@nospecialize(stmt), slotnames, argno::Integer=1) if isa(stmt, Expr) if stmt.head == :call a = stmt.args[argno] if isa(a, SlotNumber) || isa(a, Core.SlotNumber) sn = slotnames[a.id] if sn == Symbol("#self#") || sn == Symbol("") # allow empty to fix https://github.com/timholy/CodeTracking.jl/pull/48 return true end end end end return false end function has_self_call(src, stmt::Expr) # Check that it has a #self# call hasself = false for i = 2:length(stmt.args) hasself |= is_self_call(stmt, src.slotnames, i) end return hasself end """ mbody = bodymethod(m::Method) Return the "body method" for a method `m`. `mbody` contains the code of the function body when `m` was defined. """ function bodymethod(mkw::Method) @static if isdefined(Core, :kwcall) Base.unwrap_unionall(mkw.sig).parameters[1] !== typeof(Core.kwcall) && isempty(Base.kwarg_decl(mkw)) && return mkw mths = methods(Base.bodyfunction(mkw)) if length(mths) != 1 @show mkw display(mths) end return only(mths) else m = mkw local src while true framecode = JuliaInterpreter.get_framecode(m) fakeargs = Any[nothing for i = 1:(framecode.scope::Method).nargs] frame = JuliaInterpreter.prepare_frame(framecode, fakeargs, isa(m.sig, UnionAll) ? sparam_ub(m) : Core.svec()) src = framecode.src (length(src.code) > 1 && is_self_call(src.code[end-1], src.slotnames)) || break # Build the optional arg, so we can get its type pc = frame.pc while pc < length(src.code) - 1 pc = step_expr!(frame) end val = pc > 1 ? frame.framedata.ssavalues[pc-1] : (src.code[1]::Expr).args[end] sig = Tuple{(Base.unwrap_unionall(m.sig)::DataType).parameters..., typeof(val)} m = whichtt(sig) end length(src.code) > 1 || return m stmt = src.code[end-1] if isexpr(stmt, :call) && (f = (stmt::Expr).args[1]; isa(f, QuoteNode)) if f.value === (isdefined(Core, :_apply_iterate) ? Core._apply_iterate : Core._apply) ssaref = stmt.args[end-1] if isa(ssaref, JuliaInterpreter.SSAValue) id = ssaref.id has_self_call(src, src.code[id]) || return m end f = stmt.args[end-2] if isa(f, JuliaInterpreter.SSAValue) f = src.code[f.id] end else has_self_call(src, stmt) || return m end f = f.value mths = methods(f) if length(mths) == 1 return first(mths) end end return m end end
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
12917
const AnySSAValue = Union{Core.Compiler.SSAValue,JuliaInterpreter.SSAValue} const AnySlotNumber = Union{Core.Compiler.SlotNumber,JuliaInterpreter.SlotNumber} # to circumvent https://github.com/JuliaLang/julia/issues/37342, we inline these `isa` # condition checks at surface AST level # https://github.com/JuliaLang/julia/pull/38905 will get rid of the need of these hacks macro isssa(stmt) :($(GlobalRef(Core, :isa))($(esc(stmt)), $(GlobalRef(Core.Compiler, :SSAValue))) || $(GlobalRef(Core, :isa))($(esc(stmt)), $(GlobalRef(JuliaInterpreter, :SSAValue)))) end macro issslotnum(stmt) :($(GlobalRef(Core, :isa))($(esc(stmt)), $(GlobalRef(Core.Compiler, :SlotNumber))) || $(GlobalRef(Core, :isa))($(esc(stmt)), $(GlobalRef(JuliaInterpreter, :SlotNumber)))) end """ iscallto(stmt, name, src) Returns `true` is `stmt` is a call expression to `name`. """ function iscallto(@nospecialize(stmt), mod::Module, name::GlobalRef, src) if isa(stmt, Expr) if stmt.head === :call a = stmt.args[1] if isa(a, SSAValue) || isa(a, Core.SSAValue) a = src.code[a.id] end normalize_defsig(a, mod) === name && return true is_global_ref(a, Core, :_apply) && normalize_defsig(stmt.args[2], mod) === name && return true is_global_ref(a, Core, :_apply_iterate) && normalize_defsig(stmt.args[3], mod) === name && return true end end return false end """ getcallee(stmt) Returns the function (or Symbol) being called in a :call expression. """ function getcallee(@nospecialize(stmt)) if isa(stmt, Expr) if stmt.head === :call a = stmt.args[1] is_global_ref(a, Core, :_apply) && return stmt.args[2] is_global_ref(a, Core, :_apply_iterate) && return stmt.args[3] return a end end error(stmt, " is not a call expression") end function callee_matches(f, mod, sym) is_global_ref(f, mod, sym) && return true if isdefined(mod, sym) && isa(f, QuoteNode) f.value === getfield(mod, sym) && return true # a consequence of JuliaInterpreter.optimize! end return false end function rhs(stmt) is_assignment_like(stmt) && return (stmt::Expr).args[2] return stmt end ismethod(frame::Frame) = ismethod(pc_expr(frame)) ismethod3(frame::Frame) = ismethod3(pc_expr(frame)) ismethod(stmt) = isexpr(stmt, :method) ismethod1(stmt) = isexpr(stmt, :method, 1) ismethod3(stmt) = isexpr(stmt, :method, 3) function ismethod_with_name(src, stmt, target::AbstractString; reentrant::Bool=false) if reentrant name = stmt else ismethod3(stmt) || return false name = stmt.args[1] if name === nothing name = stmt.args[2] end end isdone = false while !isdone if name isa AnySSAValue || name isa AnySlotNumber name = src.code[name.id] elseif isexpr(name, :call) && is_quotenode_egal(name.args[1], Core.svec) name = name.args[2] elseif isexpr(name, :call) && is_quotenode_egal(name.args[1], Core.Typeof) name = name.args[2] elseif isexpr(name, :call) && is_quotenode_egal(name.args[1], Core.apply_type) for arg in name.args[2:end] ismethod_with_name(src, arg, target; reentrant=true) && return true end isdone = true elseif isexpr(name, :call) && is_quotenode_egal(name.args[1], UnionAll) for arg in name.args[2:end] ismethod_with_name(src, arg, target; reentrant=true) && return true end isdone = true else isdone = true end end # On Julia 1.6 we have to add escaping (CBinding makes function names like "(S)") target = escape_string(target, "()") return match(Regex("(^|#)$target(\$|#)"), isa(name, GlobalRef) ? string(name.name) : string(name)) !== nothing end # anonymous function types are defined in a :thunk expr with a characteristic CodeInfo function isanonymous_typedef(stmt) if isa(stmt, Expr) stmt.head === :thunk || return false stmt = stmt.args[1] end if isa(stmt, CodeInfo) src = stmt # just for naming consistency length(src.code) >= 4 || return false stmt = src.code[end-1] isexpr(stmt, :call) || return false is_global_ref(stmt.args[1], Core, :_typebody!) || return false @static if VERSION ≥ v"1.9.0-DEV.391" stmt = isa(stmt.args[3], Core.SSAValue) ? src.code[end-3] : src.code[end-2] is_assignment_like(stmt) || return false name = stmt.args[1] if isa(name, GlobalRef) name = name.name else isa(name, Symbol) || return false end else name = stmt.args[2]::Symbol end return startswith(String(name), "#") end return false end function istypedef(stmt) isa(stmt, Expr) || return false stmt = rhs(stmt) isa(stmt, Expr) || return false @static if all(s->isdefined(Core,s), structdecls) if stmt.head === :call f = stmt.args[1] if isa(f, GlobalRef) f.mod === Core && f.name ∈ structdecls && return true end if isa(f, QuoteNode) (f.value === Core._structtype || f.value === Core._abstracttype || f.value === Core._primitivetype) && return true end end end isanonymous_typedef(stmt) && return true return false end # Given a typedef at `src.code[idx]`, return the range of statement indices that encompass the typedef. # The range does not include any constructor methods. function typedef_range(src::CodeInfo, idx) stmt = src.code[idx] istypedef(stmt) || error(stmt, " is not a typedef") stmt = stmt::Expr isanonymous_typedef(stmt) && return idx:idx # Search backwards to the previous :global istart = idx while istart >= 1 isexpr(src.code[istart], :global) && break istart -= 1 end istart >= 1 || error("no initial :global found") iend, n = idx, length(src.code) have_typebody = have_equivtypedef = false while iend <= n stmt = src.code[iend] if isa(stmt, Expr) stmt.head === :global && break if stmt.head === :call if (is_global_ref(stmt.args[1], Core, :_typebody!) || isdefined(Core, :_typebody!) && is_quotenode_egal(stmt.args[1], Core._typebody!)) have_typebody = true elseif (is_global_ref(stmt.args[1], Core, :_equiv_typedef) || isdefined(Core, :_equiv_typedef) && is_quotenode_egal(stmt.args[1], Core._equiv_typedef)) have_equivtypedef = true # Advance to the type-assignment while iend <= n stmt = src.code[iend] is_assignment_like(stmt) && break iend += 1 end end if have_typebody && have_equivtypedef iend += 1 # compensate for the `iend-1` in the return break end end end is_return(stmt) && break iend += 1 end iend <= n || (@show src; error("no final :global found")) return istart:iend-1 end function sparam_ub(meth::Method) typs = [] sig = meth.sig while sig isa UnionAll push!(typs, Symbol(sig.var.ub)) sig = sig.body end return Core.svec(typs...) end showempty(list) = isempty(list) ? '∅' : list # Smooth the transition between Core.Compiler and Base rng(bb::Core.Compiler.BasicBlock) = (r = bb.stmts; return Core.Compiler.first(r):Core.Compiler.last(r)) function pushall!(dest, src) for item in src push!(dest, item) end return dest end # computes strongly connected components of a control flow graph `cfg` # NOTE adapted from https://github.com/JuliaGraphs/Graphs.jl/blob/5878e7be4d68b2a1c179d1367aea670db115ebb5/src/connectivity.jl#L265-L357 # since to load an entire Graphs.jl is a bit cost-ineffective in terms of a trade-off of latency vs. maintainability function strongly_connected_components(g::Core.Compiler.CFG) T = Int zero_t = zero(T) one_t = one(T) nvg = nv(g) count = one_t index = zeros(T, nvg) # first time in which vertex is discovered stack = Vector{T}() # stores vertices which have been discovered and not yet assigned to any component onstack = zeros(Bool, nvg) # false if a vertex is waiting in the stack to receive a component assignment lowlink = zeros(T, nvg) # lowest index vertex that it can reach through back edge (index array not vertex id number) parents = zeros(T, nvg) # parent of every vertex in dfs components = Vector{Vector{T}}() # maintains a list of scc (order is not guaranteed in API) dfs_stack = Vector{T}() @inbounds for s in vertices(g) if index[s] == zero_t index[s] = count lowlink[s] = count onstack[s] = true parents[s] = s push!(stack, s) count = count + one_t # start dfs from 's' push!(dfs_stack, s) while !isempty(dfs_stack) v = dfs_stack[end] # end is the most recently added item u = zero_t @inbounds for v_neighbor in outneighbors(g, v) if index[v_neighbor] == zero_t # unvisited neighbor found u = v_neighbor break # GOTO A push u onto DFS stack and continue DFS elseif onstack[v_neighbor] # we have already seen n, but can update the lowlink of v # which has the effect of possibly keeping v on the stack until n is ready to pop. # update lowest index 'v' can reach through out neighbors lowlink[v] = min(lowlink[v], index[v_neighbor]) end end if u == zero_t # All out neighbors already visited or no out neighbors # we have fully explored the DFS tree from v. # time to start popping. popped = pop!(dfs_stack) lowlink[parents[popped]] = min( lowlink[parents[popped]], lowlink[popped] ) if index[v] == lowlink[v] # found a cycle in a completed dfs tree. component = Vector{T}() while !isempty(stack) # break when popped == v # drain stack until we see v. # everything on the stack until we see v is in the SCC rooted at v. popped = pop!(stack) push!(component, popped) onstack[popped] = false # popped has been assigned a component, so we will never see it again. if popped == v # we have drained the stack of an entire component. break end end reverse!(component) push!(components, component) end else # LABEL A # add unvisited neighbor to dfs index[u] = count lowlink[u] = count onstack[u] = true parents[u] = v count = count + one_t push!(stack, u) push!(dfs_stack, u) # next iteration of while loop will expand the DFS tree from u. end end end end # # assert with the original implementation # oracle_components = oracle_scc(cfg_to_sdg(g)) # @assert Set(Set.(components)) == Set(Set.(oracle_components)) return components end # compatibility with Graphs.jl interfaces @inline nv(cfg::Core.Compiler.CFG) = length(cfg.blocks) @inline vertices(cfg::Core.Compiler.CFG) = 1:nv(cfg) @inline outneighbors(cfg::Core.Compiler.CFG, v) = cfg.blocks[v].succs # using Graphs: SimpleDiGraph, add_edge!, strongly_connected_components as oracle_scc # function cfg_to_sdg(cfg::Core.Compiler.CFG) # g = SimpleDiGraph(length(cfg.blocks)) # for (v, block) in enumerate(cfg.blocks) # for succ in block.succs # add_edge!(g, v, succ) # end # end # return g # end
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
21516
module codeedges using LoweredCodeUtils using LoweredCodeUtils.JuliaInterpreter using LoweredCodeUtils: callee_matches, istypedef, exclude_named_typedefs using JuliaInterpreter: is_global_ref, is_quotenode using Test function hastrackedexpr(@nospecialize(stmt); heads=LoweredCodeUtils.trackedheads) haseval = false if isa(stmt, Expr) if stmt.head === :call f = stmt.args[1] haseval = f === :eval || (callee_matches(f, Base, :getproperty) && is_quotenode(stmt.args[2], :eval)) callee_matches(f, Core, :_typebody!) && return true, haseval callee_matches(f, Core, :_setsuper!) && return true, haseval f === :include && return true, haseval elseif stmt.head === :thunk any(s->any(hastrackedexpr(s; heads=heads)), stmt.args[1].code) && return true, haseval elseif stmt.head ∈ heads return true, haseval end end return false, haseval end function minimal_evaluation(predicate, src::Core.CodeInfo, edges::CodeEdges; kwargs...) isrequired = fill(false, length(src.code)) for (i, stmt) in enumerate(src.code) if !isrequired[i] isrequired[i], haseval = predicate(stmt) if haseval isrequired[edges.succs[i]] .= true end end end # All tracked expressions are marked. Now add their dependencies. lines_required!(isrequired, src, edges; kwargs...) return isrequired end function allmissing(mod::Module, names) for name in names isdefined(mod, name) && return false end return true end module ModEval end module ModSelective end @testset "CodeEdges" begin ex = quote x = 1 y = x+1 a = sin(0.3) z = x^2 + y k = rand() b = 2*a + 5 end frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) # Check that the result of direct evaluation agrees with selective evaluation Core.eval(ModEval, ex) isrequired = lines_required(GlobalRef(ModSelective, :x), src, edges) # theere is too much diversity in lowering across Julia versions to make it useful to test `sum(isrequired)` selective_eval_fromstart!(frame, isrequired) @test ModSelective.x === ModEval.x @test allmissing(ModSelective, (:y, :z, :a, :b, :k)) @test !allmissing(ModSelective, (:x, :y)) # add :y here to test the `all` part of the test itself # To evaluate z we need to do all the computations for y isrequired = lines_required(GlobalRef(ModSelective, :z), src, edges) selective_eval_fromstart!(frame, isrequired) @test ModSelective.y === ModEval.y @test ModSelective.z === ModEval.z @test allmissing(ModSelective, (:a, :b, :k)) # ... but not a and b isrequired = lines_required(length(src.code)-1, src, edges) # this should be the assignment of b selective_eval_fromstart!(frame, isrequired) @test ModSelective.a === ModEval.a @test ModSelective.b === ModEval.b # Test that we get two separate evaluations of k @test allmissing(ModSelective, (:k,)) isrequired = lines_required(GlobalRef(ModSelective, :k), src, edges) selective_eval_fromstart!(frame, isrequired) @test ModSelective.k != ModEval.k # Control-flow ex = quote flag2 = true z2 = 15 if flag2 x2 = 5 a2 = 1 else y2 = 7 a2 = 2 end a2 end frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) isrequired = lines_required(GlobalRef(ModSelective, :a2), src, edges) selective_eval_fromstart!(frame, isrequired, #=istoplevel=#true) Core.eval(ModEval, ex) @test ModSelective.a2 === ModEval.a2 == 1 @test allmissing(ModSelective, (:z2, :x2, :y2)) # Now do it for the other branch, to make sure it's really sound. # Also switch up the order of the assignments inside each branch. ex = quote flag3 = false z3 = 15 if flag3 a3 = 1 x3 = 5 else a3 = 2 y3 = 7 end end frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) isrequired = lines_required(GlobalRef(ModSelective, :a3), src, edges) selective_eval_fromstart!(frame, isrequired) Core.eval(ModEval, ex) @test ModSelective.a3 === ModEval.a3 == 2 @test allmissing(ModSelective, (:z3, :x3, :y3)) # ensure we mark all needed control-flow for loops and conditionals, # and don't fall-through incorrectly ex = quote valcf = 0 for i = 1:5 global valcf if valcf < 4 valcf += 1 end end end frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) isrequired = lines_required(GlobalRef(ModSelective, :valcf), src, edges) selective_eval_fromstart!(frame, isrequired) @test ModSelective.valcf == 4 ex = quote if Sys.iswindows() const ONLY_ON_WINDOWS = true end c_os = if Sys.iswindows() ONLY_ON_WINDOWS else false end end frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) isrequired = lines_required(GlobalRef(ModSelective, :c_os), src, edges) @test sum(isrequired) >= length(isrequired) - 3 selective_eval_fromstart!(frame, isrequired) Core.eval(ModEval, ex) @test ModSelective.c_os === ModEval.c_os == Sys.iswindows() # Capturing dependencies of an `@eval` statement interpT = Expr(:$, :T) # $T that won't get parsed during file-loading ex = quote foo() = 0 for T in (Float32, Float64) @eval feval1(::$interpT) = 1 end bar() = 1 end Core.eval(ModEval, ex) @test ModEval.foo() == 0 @test ModEval.bar() == 1 frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) # Mark just the load of Core.eval haseval(stmt) = (isa(stmt, Expr) && JuliaInterpreter.hasarg(isequal(:eval), stmt.args)) || (isa(stmt, Expr) && stmt.head === :call && is_quotenode(stmt.args[1], Core.eval)) isrequired = map(haseval, src.code) @test sum(isrequired) == 1 isrequired[edges.succs[findfirst(isrequired)]] .= true # add lines that use Core.eval lines_required!(isrequired, src, edges) selective_eval_fromstart!(frame, isrequired) @test ModSelective.feval1(1.0f0) == 1 @test ModSelective.feval1(1.0) == 1 @test_throws MethodError ModSelective.feval1(1) @test_throws UndefVarError ModSelective.foo() @test_throws UndefVarError ModSelective.bar() # Run test from the docs # Lowered code isn't very suitable to jldoctest (it can vary with each Julia version), # so better to run it here ex = quote s11 = 0 k11 = 5 for i = 1:3 global s11, k11 s11 += rand(1:5) k11 += i end end frame = Frame(ModSelective, ex) JuliaInterpreter.finish_and_return!(frame, true) @test ModSelective.k11 == 11 @test 3 <= ModSelective.s11 <= 15 Core.eval(ModSelective, :(k11 = 0; s11 = -1)) edges = CodeEdges(ModSelective, frame.framecode.src) isrequired = lines_required(GlobalRef(ModSelective, :s11), frame.framecode.src, edges) selective_eval_fromstart!(frame, isrequired, true) @test ModSelective.k11 == 0 @test 3 <= ModSelective.s11 <= 15 # Control-flow in an abstract type definition ex = :(abstract type StructParent{T, N} <: AbstractArray{T, N} end) frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) # Check that the StructParent name is discovered everywhere it is used var = edges.byname[GlobalRef(ModSelective, :StructParent)] isrequired = minimal_evaluation(hastrackedexpr, src, edges) selective_eval_fromstart!(frame, isrequired, true) @test supertype(ModSelective.StructParent) === AbstractArray # Also check redefinition (it's OK when the definition doesn't change) Core.eval(ModEval, ex) frame = Frame(ModEval, ex) src = frame.framecode.src edges = CodeEdges(ModEval, src) isrequired = minimal_evaluation(hastrackedexpr, src, edges) selective_eval_fromstart!(frame, isrequired, true) @test supertype(ModEval.StructParent) === AbstractArray # Finding all dependencies in a struct definition # Nonparametric ex = :(struct NoParam end) frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) isrequired = minimal_evaluation(@nospecialize(stmt)->(LoweredCodeUtils.ismethod_with_name(src, stmt, "NoParam"),false), src, edges) # initially mark only the constructor selective_eval_fromstart!(frame, isrequired, true) @test isa(ModSelective.NoParam(), ModSelective.NoParam) # Parametric ex = quote struct Struct{T} <: StructParent{T,1} x::Vector{T} end end frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) isrequired = minimal_evaluation(@nospecialize(stmt)->(LoweredCodeUtils.ismethod_with_name(src, stmt, "Struct"),false), src, edges) # initially mark only the constructor selective_eval_fromstart!(frame, isrequired, true) @test isa(ModSelective.Struct([1,2,3]), ModSelective.Struct{Int}) # Keyword constructor (this generates :copyast expressions) ex = quote struct KWStruct x::Int y::Float32 z::String function KWStruct(; x::Int=1, y::Float32=1.0f0, z::String="hello") return new(x, y, z) end end end frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) isrequired = minimal_evaluation(@nospecialize(stmt)->(LoweredCodeUtils.ismethod3(stmt),false), src, edges) # initially mark only the constructor selective_eval_fromstart!(frame, isrequired, true) kws = ModSelective.KWStruct(y=5.0f0) @test kws.y === 5.0f0 # Anonymous functions ex = :(max_values(T::Union{map(X -> Type{X}, Base.BitIntegerSmall_types)...}) = 1 << (8*sizeof(T))) frame = Frame(ModSelective, ex) src = frame.framecode.src edges = CodeEdges(ModSelective, src) isrequired = fill(false, length(src.code)) j = length(src.code) - 1 if !Meta.isexpr(src.code[end-1], :method, 3) j -= 1 end @assert Meta.isexpr(src.code[j], :method, 3) isrequired[j] = true lines_required!(isrequired, src, edges) selective_eval_fromstart!(frame, isrequired, true) @test ModSelective.max_values(Int16) === 65536 # Avoid redefining types ex = quote struct MyNewType x::Int MyNewType(y::Int) = new(y) end end Core.eval(ModEval, ex) frame = Frame(ModEval, ex) src = frame.framecode.src edges = CodeEdges(ModEval, src) isrequired = minimal_evaluation(@nospecialize(stmt)->(LoweredCodeUtils.ismethod3(stmt),false), src, edges; norequire=exclude_named_typedefs(src, edges)) # initially mark only the constructor bbs = Core.Compiler.compute_basic_blocks(src.code) for (iblock, block) in enumerate(bbs.blocks) r = LoweredCodeUtils.rng(block) if iblock == length(bbs.blocks) @test any(idx->isrequired[idx], r) else @test !any(idx->isrequired[idx], r) end end # https://github.com/timholy/Revise.jl/issues/538 thk = Meta.lower(ModEval, quote try global function revise538(x::Float32) println("F32") end catch e println("caught error") end end) src = thk.args[1] edges = CodeEdges(ModEval, src) lr = lines_required(GlobalRef(ModEval, :revise538), src, edges) selective_eval_fromstart!(Frame(ModEval, src), lr, #=istoplevel=#true) @test isdefined(ModEval, :revise538) && length(methods(ModEval.revise538, (Float32,))) == 1 # https://github.com/timholy/Revise.jl/issues/599 thk = Meta.lower(Main, quote mutable struct A x::Int A(x) = new(f(x)) f(x) = x^2 end end) src = thk.args[1] edges = CodeEdges(Main, src) idx = findfirst(@nospecialize(stmt)->Meta.isexpr(stmt, :method), src.code) lr = lines_required(idx, src, edges; norequire=exclude_named_typedefs(src, edges)) idx = findfirst(@nospecialize(stmt)->Meta.isexpr(stmt, :(=)) && Meta.isexpr(stmt.args[2], :call) && is_global_ref(stmt.args[2].args[1], Core, :Box), src.code) @test lr[idx] # but make sure we don't break primitivetype & abstracttype (https://github.com/timholy/Revise.jl/pull/611) if isdefined(Core, :_primitivetype) thk = Meta.lower(Main, quote primitive type WindowsRawSocket sizeof(Ptr) * 8 end end) src = thk.args[1] edges = CodeEdges(Main, src) idx = findfirst(istypedef, src.code) r = LoweredCodeUtils.typedef_range(src, idx) @test last(r) == length(src.code) - 1 end @testset "Display" begin # worth testing because this has proven quite crucial for debugging and # ensuring that these structures are as "self-documenting" as possible. io = IOBuffer() l = LoweredCodeUtils.Links(Int[], [3, 5], LoweredCodeUtils.GlobalRef[GlobalRef(Main, :hello)]) show(io, l) str = String(take!(io)) @test occursin('∅', str) @test !occursin("GlobalRef", str) # CodeLinks ex = quote s = 0.0 for i = 1:5 global s s += rand() end return s end lwr = Meta.lower(Main, ex) src = lwr.args[1] cl = LoweredCodeUtils.CodeLinks(Main, src) show(io, cl) str = String(take!(io)) @test occursin(r"slot 1:\n preds: ssas: \[\d+, \d+\], slots: ∅, names: ∅;\n succs: ssas: \[\d+, \d+, \d+\], slots: ∅, names: ∅;\n assign @: \[\d+, \d+\]", str) @test occursin(r"succs: ssas: ∅, slots: \[\d+\], names: ∅;", str) # Some of these differ due to changes by Julia version in global var inference if Base.VERSION < v"1.10" @test occursin(r"s:\n preds: ssas: \[\d+\], slots: ∅, names: ∅;\n succs: ssas: \[\d+, \d+, \d+\], slots: ∅, names: ∅;\n assign @: \[\d, \d+\]", str) || occursin(r"s:\n preds: ssas: \[\d+, \d+\], slots: ∅, names: ∅;\n succs: ssas: \[\d+, \d+, \d+\], slots: ∅, names: ∅;\n assign @: \[\d, \d+\]", str) # with global var inference end if Base.VERSION < v"1.8" @test occursin(r"\d+ preds: ssas: \[\d+\], slots: ∅, names: \[\:\(Main\.s\)\];\n\d+ succs: ssas: ∅, slots: ∅, names: \[\:\(Main\.s\)\];", str) end LoweredCodeUtils.print_with_code(io, src, cl) str = String(take!(io)) if isdefined(Base.IRShow, :show_ir_stmt) @test occursin(r"slot 1:\n preds: ssas: \[\d+, \d+\], slots: ∅, names: ∅;\n succs: ssas: \[\d+, \d+, \d+\], slots: ∅, names: ∅;\n assign @: \[\d+, \d+\]", str) @test occursin("# see name Main.s", str) @test occursin("# see slot 1", str) if Base.VERSION < v"1.8" # changed by global var inference @test occursin(r"# preds: ssas: \[\d+\], slots: ∅, names: \[\:\(Main\.s\)\]; succs: ssas: ∅, slots: ∅, names: \[\:\(Main\.s\)\];", str) end else @test occursin("No IR statement printer", str) end # CodeEdges edges = CodeEdges(Main, src) show(io, edges) str = String(take!(io)) if Base.VERSION < v"1.10" @test occursin(r"s: assigned on \[\d, \d+\], depends on \[\d+\], and used by \[\d+, \d+, \d+\]", str) || occursin(r"s: assigned on \[\d, \d+\], depends on \[\d+, \d+\], and used by \[\d+, \d+, \d+\]", str) # global var inference end if Base.VERSION < v"1.9" @test (count(occursin("statement $i depends on [1, $(i-1), $(i+1)] and is used by [1, $(i+1)]", str) for i = 1:length(src.code)) == 1) || (count(occursin("statement $i depends on [4, $(i-1), $(i+4)] and is used by [$(i+2)]", str) for i = 1:length(src.code)) == 1) end LoweredCodeUtils.print_with_code(io, src, edges) str = String(take!(io)) if isdefined(Base.IRShow, :show_ir_stmt) if Base.VERSION < v"1.10" @test occursin(r"s: assigned on \[\d, \d+\], depends on \[\d+\], and used by \[\d+, \d+, \d+\]", str) || occursin(r"s: assigned on \[\d, \d+\], depends on \[\d+, \d+\], and used by \[\d+, \d+, \d+\]", str) end if Base.VERSION < v"1.9" @test (count(occursin("preds: [1, $(i-1), $(i+1)], succs: [1, $(i+1)]", str) for i = 1:length(src.code)) == 1) || (count(occursin("preds: [4, $(i-1), $(i+4)], succs: [$(i+2)]", str) for i = 1:length(src.code)) == 1) # global var inference end else @test occursin("No IR statement printer", str) end # Works with Frames too frame = Frame(ModSelective, ex) edges = CodeEdges(ModSelective, frame.framecode.src) LoweredCodeUtils.print_with_code(io, frame, edges) str = String(take!(io)) if isdefined(Base.IRShow, :show_ir_stmt) if Base.VERSION < v"1.10" @test occursin(r"s: assigned on \[\d, \d+\], depends on \[\d+\], and used by \[\d+, \d+, \d+\]", str) || occursin(r"s: assigned on \[\d, \d+\], depends on \[\d, \d+\], and used by \[\d+, \d+, \d+\]", str) # global var inference end if Base.VERSION < v"1.9" @test (count(occursin("preds: [1, $(i-1), $(i+1)], succs: [1, $(i+1)]", str) for i = 1:length(src.code)) == 1) || (count(occursin("preds: [4, $(i-1), $(i+4)], succs: [$(i+2)]", str) for i = 1:length(src.code)) == 1) # global var inference end else @test occursin("No IR statement printer", str) end # display slot names ex = :(let s = 0.0 for i = 1:5 s += rand() end return s end) lwr = Meta.lower(Main, ex) src = lwr.args[1] LoweredCodeUtils.print_with_code(io, src, trues(length(src.code))) str = String(take!(io)) @test count("s = ", str) == 2 @test count("i = ", str) == 1 end end @testset "selective interpretation of toplevel definitions" begin gen_mock_module() = Core.eval(@__MODULE__, :(module $(gensym(:LoweredCodeUtilsTestMock)) end)) function check_toplevel_definition_interprete(ex, defs, undefs) m = gen_mock_module() lwr = Meta.lower(m, ex) src = first(lwr.args) stmts = src.code edges = CodeEdges(m, src) isrq = lines_required!(istypedef.(stmts), src, edges) frame = Frame(m, src) selective_eval_fromstart!(frame, isrq, #=toplevel=#true) for def in defs; @test isdefined(m, def); end for undef in undefs; @test !isdefined(m, undef); end end @testset "case: $(i), interpret: $(defs), ignore $(undefs)" for (i, ex, defs, undefs) in ( (1, :(abstract type Foo end), (:Foo,), ()), (2, :(struct Foo end), (:Foo,), ()), (3, quote struct Foo val end end, (:Foo,), ()), (4, quote struct Foo{T} val::T Foo(v::T) where {T} = new{T}(v) end end, (:Foo,), ()), (5, :(primitive type Foo 32 end), (:Foo,), ()), (6, quote abstract type Foo end struct Foo1 <: Foo end struct Foo2 <: Foo end end, (:Foo, :Foo1, :Foo2), ()), (7, quote struct Foo v Foo(f) = new(f()) end foo = Foo(()->throw("don't interpret me")) end, (:Foo,), (:foo,)), # https://github.com/JuliaDebug/LoweredCodeUtils.jl/issues/47 (8, quote struct Foo b::Bool Foo(b) = new(b) end foo = Foo(false) end, (:Foo,), (:foo,)), # https://github.com/JuliaDebug/LoweredCodeUtils.jl/pull/48 # we shouldn't make `add_links!` recur into `QuoteNode`, otherwise the variable # `bar` will be selected as a requirement for `Bar1` (, which has "bar" field) (9, quote abstract type Bar end struct Bar1 <: Bar bar end r = (throw("don't interpret me"); rand(10000000000000000)) bar = Bar1(r) show(bar) end, (:Bar, :Bar1), (:r, :bar)) ) check_toplevel_definition_interprete(ex, defs, undefs) end end end # module codeedges
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
447
using Test # using LoweredCodeUtils # @testset "Ambiguity" begin # @test isempty(detect_ambiguities(LoweredCodeUtils, LoweredCodeUtils.JuliaInterpreter, Base, Core)) # end @testset "LoweredCodeUtils.jl" begin @static if VERSION ≥ v"1.8" @testset "signatures.jl" include("signatures.jl") @testset "codeedges.jl" include("codeedges.jl") else include("signatures.jl") include("codeedges.jl") end end
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
code
17556
module Signatures using LoweredCodeUtils using InteractiveUtils using JuliaInterpreter using JuliaInterpreter: finish_and_return! using Core: CodeInfo using Base.Meta: isexpr using Test module Lowering using Parameters struct Caller end struct Gen{T} end end # Stuff for https://github.com/timholy/Revise.jl/issues/422 module Lowering422 const LVec{N, T} = NTuple{N, Base.VecElement{T}} const LT{T} = Union{LVec{<:Any, T}, T} const FloatingTypes = Union{Float32, Float64} end bodymethtest0(x) = 0 function bodymethtest0(x) y = 2x y + x end bodymethtest1(x, y=1; z="hello") = 1 bodymethtest2(x, y=Dict(1=>2); z="hello") = 2 bodymethtest3(x::T, y=Dict(1=>2); z="hello") where T<:AbstractFloat = 3 # No kw but has optional args bodymethtest4(x, y=1) = 4 bodymethtest5(x, y=Dict(1=>2)) = 5 @testset "Signatures" begin signatures = Set{Any}() newcode = CodeInfo[] for ex in (:(f(x::Int8; y=0) = y), :(f(x::Int16; y::Int=0) = 2), :(f(x::Int32; y="hello", z::Int=0) = 3), :(f(x::Int64;) = 4), :(f(x::Array{Float64,K}; y::Int=0) where K = K), # Keyword-arg functions that have an anonymous function inside :(fanon(list; sorted::Bool=true,) = sorted ? sort!(list, by=x->abs(x)) : list), # Keyword & default positional args :(g(x, y="hello"; z::Int=0) = 1), # Return type annotations :(annot(x, y; z::Bool=false,)::Nothing = nothing), # Generated methods quote @generated function h(x) if x <: Integer return :(x ^ 2) else return :(x) end end end, quote function h(x::Int, y) if @generated return y <: Integer ? :(x*y) : :(x+y) else return 2x+3y end end end, :(@generated genkw(; b=2) = nothing), # https://github.com/timholy/Revise.jl/issues/290 # Generated constructors quote function Gen{T}(x) where T if @generated return T <: Integer ? :(x^2) : :(2x) else return 7x end end end, # Conditional methods quote if 0.8 > 0.2 fctrue(x) = 1 else fcfalse(x) = 1 end end, # Call methods :((::Caller)(x::String) = length(x)), ) Core.eval(Lowering, ex) frame = Frame(Lowering, ex) rename_framemethods!(frame) pc = methoddefs!(signatures, frame; define=false) push!(newcode, frame.framecode.src) end # Manually add the signature for the Caller constructor, since that was defined # outside of manual lowering push!(signatures, Tuple{Type{Lowering.Caller}}) nms = names(Lowering; all=true) modeval, modinclude = getfield(Lowering, :eval), getfield(Lowering, :include) failed = [] for fsym in nms f = getfield(Lowering, fsym) isa(f, Base.Callable) || continue (f === modeval || f === modinclude) && continue for m in methods(f) if m.sig ∉ signatures push!(failed, m.sig) end end end @test isempty(failed) # Ensure that all names are properly resolved for code in newcode Core.eval(Lowering, code) end nms2 = names(Lowering; all=true) @test nms2 == nms @test Lowering.f(Int8(0)) == 0 @test Lowering.f(Int8(0); y="LCU") == "LCU" @test Lowering.f(Int16(0)) == Lowering.f(Int16(0), y=7) == 2 @test Lowering.f(Int32(0)) == Lowering.f(Int32(0); y=22) == Lowering.f(Int32(0); y=:cat, z=5) == 3 @test Lowering.f(Int64(0)) == 4 @test Lowering.f(rand(3,3)) == Lowering.f(rand(3,3); y=5) == 2 @test Lowering.fanon([1,3,-2]) == [1,-2,3] @test Lowering.g(0) == Lowering.g(0,"LCU") == Lowering.g(0; z=5) == Lowering.g(0,"LCU"; z=5) == 1 @test Lowering.annot(0,0) === nothing @test Lowering.h(2) == 4 @test Lowering.h(2.0) == 2.0 @test Lowering.h(2, 3) == 6 @test Lowering.h(2, 3.0) == 5.0 @test Lowering.fctrue(0) == 1 @test_throws UndefVarError Lowering.fcfalse(0) @test (Lowering.Caller())("Hello, world") == 12 g = Lowering.Gen{Float64} @test g(3) == 6 # Don't be deceived by inner methods signatures = [] ex = quote function fouter(x) finner(::Float16) = 2x return finner(Float16(1)) end end Core.eval(Lowering, ex) frame = Frame(Lowering, ex) rename_framemethods!(frame) methoddefs!(signatures, frame; define=false) @test length(signatures) == 1 @test LoweredCodeUtils.whichtt(signatures[1]) == first(methods(Lowering.fouter)) # Check output of methoddef! frame = Frame(Lowering, :(function nomethod end)) ret = methoddef!(empty!(signatures), frame; define=true) @test isempty(signatures) @test ret === nothing frame = Frame(Lowering, :(function amethod() nothing end)) ret = methoddef!(empty!(signatures), frame; define=true) @test !isempty(signatures) @test isa(ret, NTuple{2,Int}) # Anonymous functions in method signatures ex = :(max_values(T::Union{map(X -> Type{X}, Base.BitIntegerSmall_types)...}) = 1 << (8*sizeof(T))) # base/abstractset.jl frame = Frame(Base, ex) rename_framemethods!(frame) signatures = Set{Any}() methoddef!(signatures, frame; define=false) @test length(signatures) == 1 @test first(signatures) == which(Base.max_values, Tuple{Type{Int16}}).sig # define ex = :(fdefine(x) = 1) frame = Frame(Lowering, ex) empty!(signatures) methoddefs!(signatures, frame; define=false) @test_throws MethodError Lowering.fdefine(0) frame = Frame(Lowering, ex) empty!(signatures) methoddefs!(signatures, frame; define=true) @test Lowering.fdefine(0) == 1 # define with correct_name! ex = quote @generated function generated1(A::AbstractArray{T,N}, val) where {T,N} ex = Expr(:tuple) for i = 1:N push!(ex.args, :val) end return ex end end frame = Frame(Lowering, ex) rename_framemethods!(frame) empty!(signatures) methoddefs!(signatures, frame; define=true) @test length(signatures) == 2 @test Lowering.generated1(rand(2,2), 3.2) == (3.2, 3.2) ex = quote another_kwdef(x, y=1; z="hello") = 333 end frame = Frame(Lowering, ex) rename_framemethods!(frame) empty!(signatures) methoddefs!(signatures, frame; define=true) @test length(signatures) == 5 @test Lowering.another_kwdef(0) == 333 ex = :(@generated genkw2(; b=2) = nothing) # https://github.com/timholy/Revise.jl/issues/290 frame = Frame(Lowering, ex) # rename_framemethods!(frame) empty!(signatures) methoddefs!(signatures, frame; define=true) @test length(signatures) == 4 @test Lowering.genkw2() === nothing # Test for correct exit (example from base/namedtuples.jl) ex = quote function merge(a::NamedTuple{an}, b::NamedTuple{bn}) where {an, bn} if @generated names = merge_names(an, bn) types = merge_types(names, a, b) vals = Any[ :(getfield($(sym_in(n, bn) ? :b : :a), $(QuoteNode(n)))) for n in names ] :( NamedTuple{$names,$types}(($(vals...),)) ) else names = merge_names(an, bn) types = merge_types(names, typeof(a), typeof(b)) NamedTuple{names,types}(map(n->getfield(sym_in(n, bn) ? b : a, n), names)) end end end frame = Frame(Base, ex) rename_framemethods!(frame) empty!(signatures) stmt = JuliaInterpreter.pc_expr(frame) if !LoweredCodeUtils.ismethod(stmt) pc = JuliaInterpreter.next_until!(LoweredCodeUtils.ismethod, frame, true) end pc, pc3 = methoddef!(signatures, frame; define=false) # this tests that the return isn't `nothing` pc, pc3 = methoddef!(signatures, frame; define=false) @test length(signatures) == 2 # both the GeneratedFunctionStub and the main method # With anonymous functions in signatures ex = :(const BitIntegerType = Union{map(T->Type{T}, Base.BitInteger_types)...}) frame = Frame(Lowering, ex) rename_framemethods!(frame) empty!(signatures) methoddefs!(signatures, frame; define=false) @test !isempty(signatures) for m in methods(bodymethtest0) @test bodymethod(m) === m end @test startswith(String(bodymethod(first(methods(bodymethtest1))).name), "#") @test startswith(String(bodymethod(first(methods(bodymethtest2))).name), "#") @test startswith(String(bodymethod(first(methods(bodymethtest3))).name), "#") @test bodymethod(first(methods(bodymethtest4))).nargs == 3 # one extra for #self# @test bodymethod(first(methods(bodymethtest5))).nargs == 3 m = @which sum([1]; dims=1) # Issue in https://github.com/timholy/CodeTracking.jl/pull/48 mbody = bodymethod(m) @test mbody != m && mbody.file != :none # varargs keyword methods m = which(Base.print_shell_escaped, (IO, AbstractString)) mbody = bodymethod(m) @test isa(mbody, Method) && mbody != m ex = quote function print_shell_escaped(io::IO, cmd::AbstractString, args::AbstractString...; special::AbstractString="") print_shell_word(io, cmd, special) for arg in args print(io, ' ') print_shell_word(io, arg, special) end end end frame = Frame(Base, ex) rename_framemethods!(frame) empty!(signatures) methoddefs!(signatures, frame; define=false) @test length(signatures) >= 3 - isdefined(Core, :kwcall) ex = :(typedsig(x) = 1) frame = Frame(Lowering, ex) methoddefs!(signatures, frame; define=true) ex = :(typedsig(x::Int) = 2) frame = Frame(Lowering, ex) JuliaInterpreter.next_until!(LoweredCodeUtils.ismethod3, frame, true) empty!(signatures) methoddefs!(signatures, frame; define=true) @test first(signatures).parameters[end] == Int # Multiple keyword arg methods per frame # (Revise issue #363) ex = quote keywrd1(x; kwarg=false) = 1 keywrd2(x; kwarg="hello") = 2 keywrd3(x; kwarg=:stuff) = 3 end Core.eval(Lowering, ex) frame = Frame(Lowering, ex) rename_framemethods!(frame) empty!(signatures) pc, pc3 = methoddef!(signatures, frame; define=false) @test pc < length(frame.framecode.src.code) kw2sig = Tuple{typeof(Lowering.keywrd2), Any} @test kw2sig ∉ signatures pc = methoddefs!(signatures, frame; define=false) @test pc === nothing @test kw2sig ∈ signatures # Module-scoping ex = :(Base.@irrational π 3.14159265358979323846 pi) frame = Frame(Base.MathConstants, ex) rename_framemethods!(frame) empty!(signatures) methoddefs!(signatures, frame; define=false) @test !isempty(signatures) # Inner methods in structs. Comes up in, e.g., Core.Compiler.Params. # The body of CustomMS is an SSAValue. ex = quote struct MyStructWithMeth x::Int global function CustomMS(;x=1) return new(x) end MyStructWithMeth(x) = new(x) end end Core.eval(Lowering, ex) frame = Frame(Lowering, ex) rename_framemethods!(frame) empty!(signatures) methoddefs!(signatures, frame; define=false) @test Tuple{typeof(Lowering.CustomMS)} ∈ signatures # https://github.com/timholy/Revise.jl/issues/398 ex = quote @with_kw struct Items n::Int items::Vector{Int} = [i for i=1:n] end end Core.eval(Lowering, ex) frame = Frame(Lowering, ex) dct = rename_framemethods!(frame) ks = collect(filter(k->startswith(String(k.name), "#Items#"), keys(dct))) @test length(ks) == 2 @test dct[ks[1]] == dct[ks[2]] @test ks[1].mod === ks[2].mod === Lowering @test isdefined(Lowering, ks[1].name) || isdefined(Lowering, ks[2].name) if !isdefined(Core, :kwcall) nms = filter(sym->occursin(r"#Items#\d+#\d+", String(sym)), names(Lowering; all=true)) @test length(nms) == 1 end # https://github.com/timholy/Revise.jl/issues/422 ex = :(@generated function fneg(x::T) where T<:LT{<:FloatingTypes} s = """ %2 = fneg $(llvm_type(T)) %0 ret $(llvm_type(T)) %2 """ return :( $(Expr(:meta, :inline)); Base.llvmcall($s, T, Tuple{T}, x) ) end) empty!(signatures) Core.eval(Lowering422, ex) frame = Frame(Lowering422, ex) rename_framemethods!(frame) pc = methoddefs!(signatures, frame; define=false) @test typeof(Lowering422.fneg) ∈ Set(Base.unwrap_unionall(sig).parameters[1] for sig in signatures) # Scoped names (https://github.com/timholy/Revise.jl/issues/568) ex = :(f568() = -1) Core.eval(Lowering, ex) @test Lowering.f568() == -1 empty!(signatures) ex = :(f568() = -2) frame = Frame(Lowering, ex) pcstop = findfirst(LoweredCodeUtils.ismethod3, frame.framecode.src.code) pc = 1 while pc < pcstop pc = JuliaInterpreter.step_expr!(finish_and_return!, frame, true) end pc = methoddef!(finish_and_return!, signatures, frame, pc; define=true) @test Tuple{typeof(Lowering.f568)} ∈ signatures @test Lowering.f568() == -2 # Undefined names # This comes from FileWatching; WindowsRawSocket is only defined on Windows ex = quote if Sys.iswindows() using Base: WindowsRawSocket function wait(socket::WindowsRawSocket; readable=false, writable=false) fdw = _FDWatcher(socket, readable, writable) try return wait(fdw, readable=readable, writable=writable) finally close(fdw, readable, writable) end end end end frame = Frame(Lowering, ex) rename_framemethods!(frame) # https://github.com/timholy/Revise.jl/issues/550 using Pkg oldenv = Pkg.project().path try # we test with the old version of CBinding, let's do it in an isolated environment Pkg.activate(; temp=true, io=devnull) @info "Adding CBinding to the environment for test purposes" Pkg.add(; name="CBinding", version="0.9.4", io=devnull) # `@cstruct` isn't defined for v1.0 and above m = Module() Core.eval(m, :(using CBinding)) ex = :(@cstruct S { val::Int8 }) empty!(signatures) Core.eval(m, ex) frame = Frame(m, ex) rename_framemethods!(frame) pc = methoddefs!(signatures, frame; define=false) @test !isempty(signatures) # really we just need to know that `methoddefs!` completed without getting stuck finally Pkg.activate(oldenv; io=devnull) # back to the original environment end end # https://github.com/timholy/Revise.jl/issues/643 module Revise643 using LoweredCodeUtils, JuliaInterpreter, Test # make sure to not define `foogr` before macro expansion, # otherwise it will be resolved as `QuoteNode` macro deffoogr() gr = GlobalRef(__module__, :foogr) # will be lowered to `GlobalRef` quote $gr(args...) = length(args) end end let ex = quote @deffoogr @show foogr(1,2,3) end methranges = rename_framemethods!(Frame(@__MODULE__, ex)) @test haskey(methranges, GlobalRef(@__MODULE__, :foogr)) end function fooqn end macro deffooqn() sig = :($(GlobalRef(__module__, :fooqn))(args...)) # will be lowered to `QuoteNode` return Expr(:function, sig, Expr(:block, __source__, :(length(args)))) end let ex = quote @deffooqn @show fooqn(1,2,3) end methranges = rename_framemethods!(Frame(@__MODULE__, ex)) @test haskey(methranges, GlobalRef(@__MODULE__, :fooqn)) end # define methods in other module module sandboxgr end macro deffoogr_sandbox() gr = GlobalRef(sandboxgr, :foogr_sandbox) # will be lowered to `GlobalRef` quote $gr(args...) = length(args) end end let ex = quote @deffoogr_sandbox @show sandboxgr.foogr_sandbox(1,2,3) end methranges = rename_framemethods!(Frame(@__MODULE__, ex)) @test haskey(methranges, GlobalRef(sandboxgr, :foogr_sandbox)) end module sandboxqn; function fooqn_sandbox end; end macro deffooqn_sandbox() sig = :($(GlobalRef(sandboxqn, :fooqn_sandbox))(args...)) # will be lowered to `QuoteNode` return Expr(:function, sig, Expr(:block, __source__, :(length(args)))) end let ex = quote @deffooqn_sandbox @show sandboxqn.fooqn_sandbox(1,2,3) end methranges = rename_framemethods!(Frame(@__MODULE__, ex)) @test haskey(methranges, GlobalRef(sandboxqn, :fooqn_sandbox)) end end end # module signatures
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
docs
289
# LoweredCodeUtils [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaDebug.github.io/LoweredCodeUtils.jl/stable) This package performs operations on Julia's [lowered AST](https://docs.julialang.org/en/v1/devdocs/ast/#Lowered-form). See the documentation for details.
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
docs
545
# API ## Signatures ```@docs signature methoddef! rename_framemethods! bodymethod ``` ## Edges ```@docs CodeEdges lines_required lines_required! selective_eval! selective_eval_fromstart! ``` ## Internal utilities ```@docs LoweredCodeUtils.print_with_code LoweredCodeUtils.next_or_nothing LoweredCodeUtils.skip_until LoweredCodeUtils.MethodInfo LoweredCodeUtils.identify_framemethod_calls LoweredCodeUtils.iscallto LoweredCodeUtils.getcallee LoweredCodeUtils.find_name_caller_sig LoweredCodeUtils.replacename! LoweredCodeUtils.Variable ```
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
docs
7459
# Edges Edges here are a graph-theoretic concept relating the connections between individual statements in the source code. For example, consider ```julia julia> ex = quote s = 0 k = 5 for i = 1:3 global s, k s += rand(1:5) k += i end end quote #= REPL[2]:2 =# s = 0 #= REPL[2]:3 =# k = 5 #= REPL[2]:4 =# for i = 1:3 #= REPL[2]:5 =# global s, k #= REPL[2]:6 =# s += rand(1:5) #= REPL[2]:7 =# k += i end end julia> eval(ex) julia> s 10 # random julia> k 11 # reproducible ``` We lower it, ``` julia> lwr = Meta.lower(Main, ex) :($(Expr(:thunk, CodeInfo( @ REPL[2]:2 within `top-level scope' 1 ─ s = 0 │ @ REPL[2]:3 within `top-level scope' │ k = 5 │ @ REPL[2]:4 within `top-level scope' │ %3 = 1:3 │ #s1 = Base.iterate(%3) │ %5 = #s1 === nothing │ %6 = Base.not_int(%5) └── goto #4 if not %6 2 ┄ %8 = #s1 │ i = Core.getfield(%8, 1) │ %10 = Core.getfield(%8, 2) │ @ REPL[2]:5 within `top-level scope' │ global k │ global s │ @ REPL[2]:6 within `top-level scope' │ %13 = 1:5 │ %14 = rand(%13) │ %15 = s + %14 │ s = %15 │ @ REPL[2]:7 within `top-level scope' │ %17 = k + i │ k = %17 │ #s1 = Base.iterate(%3, %10) │ %20 = #s1 === nothing │ %21 = Base.not_int(%20) └── goto #4 if not %21 3 ─ goto #2 4 ┄ return )))) ``` and then extract the edges: ```julia julia> edges = CodeEdges(lwr.args[1]) CodeEdges: s: assigned on [1, 16], depends on [15], and used by [12, 15] k: assigned on [2, 18], depends on [17], and used by [11, 17] statement 1 depends on [15, 16] and is used by [12, 15, 16] statement 2 depends on [17, 18] and is used by [11, 17, 18] statement 3 depends on ∅ and is used by [4, 19] statement 4 depends on [3, 10, 19] and is used by [5, 8, 19, 20] statement 5 depends on [4, 19] and is used by [6] statement 6 depends on [5] and is used by [7] statement 7 depends on [6] and is used by ∅ statement 8 depends on [4, 19] and is used by [9, 10] statement 9 depends on [8] and is used by [17] statement 10 depends on [8] and is used by [4, 19] statement 11 depends on [2, 18] and is used by ∅ statement 12 depends on [1, 16] and is used by ∅ statement 13 depends on ∅ and is used by [14] statement 14 depends on [13] and is used by [15] statement 15 depends on [1, 14, 16] and is used by [1, 16] statement 16 depends on [1, 15] and is used by [1, 12, 15] statement 17 depends on [2, 9, 18] and is used by [2, 18] statement 18 depends on [2, 17] and is used by [2, 11, 17] statement 19 depends on [3, 4, 10] and is used by [4, 5, 8, 20] statement 20 depends on [4, 19] and is used by [21] statement 21 depends on [20] and is used by [22] statement 22 depends on [21] and is used by ∅ statement 23 depends on ∅ and is used by ∅ statement 24 depends on ∅ and is used by ∅ ``` This shows the dependencies of each line as well as the "named variables" `s` and `k`. It's worth looking specifically to see how the slot-variable `#s1` gets handled, as you'll notice there is no mention of this in the "variables" section at the top. You can see that `#s1` first gets assigned on line 4 (the `iterate` statement), which you'll notice depends on 3 (via the SSAValue printed as `%3`). But that line 4 also is shown as depending on 10 and 19. You can see that line 19 is the 2-argument call to `iterate`, and that this line depends on SSAValue `%10` (the state variable). Consequently all the line-dependencies of this slot variable have been aggregated into a single list by determining the "global" influences on that slot variable. An even more useful output can be obtained from the following: ``` julia> LoweredCodeUtils.print_with_code(stdout, lwr.args[1], edges) Names: s: assigned on [1, 16], depends on [15], and used by [12, 15] k: assigned on [2, 18], depends on [17], and used by [11, 17] Code: 1 ─ s = 0 │ # preds: [15, 16], succs: [12, 15, 16] │ k = 5 │ # preds: [17, 18], succs: [11, 17, 18] │ %3 = 1:3 │ # preds: ∅, succs: [4, 19] │ _1 = Base.iterate(%3) │ # preds: [3, 10, 19], succs: [5, 8, 19, 20] │ %5 = _1 === nothing │ # preds: [4, 19], succs: [6] │ %6 = Base.not_int(%5) │ # preds: [5], succs: [7] └── goto #4 if not %6 # preds: [6], succs: ∅ 2 ┄ %8 = _1 │ # preds: [4, 19], succs: [9, 10] │ _2 = Core.getfield(%8, 1) │ # preds: [8], succs: [17] │ %10 = Core.getfield(%8, 2) │ # preds: [8], succs: [4, 19] │ global k │ # preds: [2, 18], succs: ∅ │ global s │ # preds: [1, 16], succs: ∅ │ %13 = 1:5 │ # preds: ∅, succs: [14] │ %14 = rand(%13) │ # preds: [13], succs: [15] │ %15 = s + %14 │ # preds: [1, 14, 16], succs: [1, 16] │ s = %15 │ # preds: [1, 15], succs: [1, 12, 15] │ %17 = k + _2 │ # preds: [2, 9, 18], succs: [2, 18] │ k = %17 │ # preds: [2, 17], succs: [2, 11, 17] │ _1 = Base.iterate(%3, %10) │ # preds: [3, 4, 10], succs: [4, 5, 8, 20] │ %20 = _1 === nothing │ # preds: [4, 19], succs: [21] │ %21 = Base.not_int(%20) │ # preds: [20], succs: [22] └── goto #4 if not %21 # preds: [21], succs: ∅ 3 ─ goto #2 # preds: ∅, succs: ∅ 4 ┄ return # preds: ∅, succs: ∅ ``` Here the edges are printed right after each line. !!! note "Nice" output from `print_with_code` requires at least version 1.6.0-DEV.95 of Julia. Suppose we want to evaluate just the lines needed to compute `s`. We can find out which lines these are with ```julia julia> isrequired = lines_required(:s, lwr.args[1], edges) 24-element BitArray{1}: 1 0 1 1 1 1 1 1 0 1 0 0 1 1 1 1 0 0 1 1 1 1 1 0 ``` and display them with ``` julia> LoweredCodeUtils.print_with_code(stdout, lwr.args[1], isrequired) 1 t 1 ─ s = 0 2 f │ k = 5 3 t │ %3 = 1:3 4 t │ _1 = Base.iterate(%3) 5 t │ %5 = _1 === nothing 6 t │ %6 = Base.not_int(%5) 7 t └── goto #4 if not %6 8 t 2 ┄ %8 = _1 9 f │ _2 = Core.getfield(%8, 1) 10 t │ %10 = Core.getfield(%8, 2) 11 f │ global k 12 f │ global s 13 t │ %13 = 1:5 14 t │ %14 = rand(%13) 15 t │ %15 = s + %14 16 t │ s = %15 17 f │ %17 = k + _2 18 f │ k = %17 19 t │ _1 = Base.iterate(%3, %10) 20 t │ %20 = _1 === nothing 21 t │ %21 = Base.not_int(%20) 22 t └── goto #4 if not %21 23 t 3 ─ goto #2 24 f 4 ┄ return ``` We can test this with the following: ```julia julia> using JuliaInterpreter julia> frame = Frame(Main, lwr.args[1]) Frame for Main 1 2 1 ─ s = 0 2 3 │ k = 5 3 4 │ %3 = 1:3 ⋮ julia> k 11 julia> k = 0 0 julia> selective_eval_fromstart!(frame, isrequired, true) julia> k 0 julia> s 12 # random julia> selective_eval_fromstart!(frame, isrequired, true) julia> k 0 julia> s 9 # random ``` You can see that `k` was not reset to its value of 11 when we ran this code selectively, but that `s` was updated (to a random value) each time.
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
docs
2461
# LoweredCodeUtils.jl This package performs operations on Julia's [lowered AST](https://docs.julialang.org/en/latest/devdocs/ast/). An introduction to this representation can be found at [JuliaInterpreter](https://juliadebug.github.io/JuliaInterpreter.jl/stable/). Lowered AST (like other ASTs, type-inferred AST and SSA IR form) is generally more amenable to analysis than "surface" Julia expressions. However, sophisticated analyses can nevertheless require a fair bit of infrastructure. The purpose of this package is to standardize a few operations that are important in some applications. Currently there are two major domains of this package: the "signatures" domain and the "edges" domain. ## Signatures A major role of this package is to support extraction of method signatures, in particular to provide strong support for relating keyword-method "bodies" to their parent methods. The central challenge this addresses is the lowering of keyword-argument functions and the fact that the "gensymmed" names are different each time you lower the code, and therefore you don't recover the actual (running) keyword-body method. The technical details are described in [this Julia issue](https://github.com/JuliaLang/julia/issues/30908) and on the next page. This package provides a workaround to rename gensymmed variables in newly-lowered code to match the name of the running keyword-body method, and provides a convenience function, `bodymethod`, to obtain that otherwise difficult-to-discover method. ## Edges Sometimes you want to run only a selected subset of code. For instance, Revise tracks methods by their signatures, and therefore needs to compute signatures from the lowered representation of code. Doing this robustly (including for `@eval`ed methods, etc.) requires running module top-level code through the interpreter. For reasons of performance and safety, it is important to minimize the amount of code that gets executed when extracting the signature. This package provides a general framework for computing dependencies in code, through the `CodeEdges` constructor. It allows you to determine the lines on which any given statement depends, the lines which "consume" the result of the current line, and any "named" dependencies (`Symbol` and `GlobalRef` dependencies). In particular, this resolves the line-dependencies of all `SlotNumber` variables so that their own dependencies will be handled via the code-line dependencies.
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
3.0.2
c2b5e92eaf5101404a58ce9c6083d595472361d6
docs
6959
# Signatures and renaming We can demonstrate some of this package's functionality with the following simple example: ```julia julia> ex = :(f(x; color::Symbol=:green) = 2x) :(f(x; color::Symbol = :green) = begin #= REPL[1]:1 =# 2x end) julia> eval(ex) f (generic function with 1 method) julia> f(3) 6 ``` Things get more interesting (and complicated) when we examine the lowered code: ```julia julia> lwr = Meta.lower(Main, ex) :($(Expr(:thunk, CodeInfo( @ none within `top-level scope' 1 ─ $(Expr(:thunk, CodeInfo( @ none within `top-level scope' 1 ─ return $(Expr(:method, :f)) ))) │ $(Expr(:thunk, CodeInfo( @ none within `top-level scope' 1 ─ return $(Expr(:method, Symbol("#f#2"))) ))) │ $(Expr(:method, :f)) │ $(Expr(:method, Symbol("#f#2"))) │ %5 = Core.typeof(var"#f#2") │ %6 = Core.Typeof(f) │ %7 = Core.svec(%5, Symbol, %6, Core.Any) │ %8 = Core.svec() │ %9 = Core.svec(%7, %8, $(QuoteNode(:(#= REPL[1]:1 =#)))) │ $(Expr(:method, Symbol("#f#2"), :(%9), CodeInfo(quote $(Expr(:meta, :nkw, 1)) 2 * x return %2 end))) │ $(Expr(:method, :f)) │ %12 = Core.Typeof(f) │ %13 = Core.svec(%12, Core.Any) │ %14 = Core.svec() │ %15 = Core.svec(%13, %14, $(QuoteNode(:(#= REPL[1]:1 =#)))) │ $(Expr(:method, :f, :(%15), CodeInfo(quote var"#f#2"(:green, #self#, x) return %1 end))) │ $(Expr(:method, :f)) │ %18 = Core.Typeof(f) │ %19 = Core.kwftype(%18) │ %20 = Core.Typeof(f) │ %21 = Core.svec(%19, Core.Any, %20, Core.Any) │ %22 = Core.svec() │ %23 = Core.svec(%21, %22, $(QuoteNode(:(#= REPL[1]:1 =#)))) │ $(Expr(:method, :f, :(%23), CodeInfo(quote Base.haskey(@_2, :color) unless %1 goto %11 Base.getindex(@_2, :color) %3 isa Symbol unless %4 goto %7 goto %9 %new(Core.TypeError, Symbol("keyword argument"), :color, Symbol, %3) Core.throw(%7) @_6 = %3 goto %12 @_6 = :green color = @_6 Core.tuple(:color) Core.apply_type(Core.NamedTuple, %13) Base.structdiff(@_2, %14) Base.pairs(%15) Base.isempty(%16) unless %17 goto %20 goto %21 Base.kwerr(@_2, @_3, x) var"#f#2"(color, @_3, x) return %21 end))) │ %25 = f │ %26 = Core.ifelse(false, false, %25) └── return %26 )))) ``` This reveals the *three* methods actually got defined: - one method of `f` with a single positional argument (this is the second 3-argument `:method` expression) - a keyword-handling method that checks the names of supplied keyword arguments and fills in defaults (this is the third 3-argument `:method` expression). This method can be obtained from `Core.kwfunc(f)`, which returns a function named `f##kw`. - a "keyword-body" method that actually does the work specifies by our function definition. This method gets called by the other two. (This is the first 3-argument `:method` expression.) From examining the lowered code we might guess that this function is called `#f#2`. What happens if we try to get it? ```julia julia> fbody = var"#f#2" ERROR: UndefVarError: #f#2 not defined Stacktrace: [1] top-level scope at REPL[6]:1 ``` Curiously, however, there is a closely-related function, and looking at its body code we see it is the one we wanted: ```julia julia> fbody = var"#f#1" #f#1 (generic function with 1 method) julia> mbody = first(methods(fbody)) #f#1(color::Symbol, ::typeof(f), x) in Main at REPL[1]:1 julia> Base.uncompressed_ast(mbody) CodeInfo( @ REPL[1]:1 within `#f#1' 1 ─ nothing │ %2 = 2 * x └── return %2 ) ``` It's named `#f#1`, rather than `#f#2`, because it was actually defined by that `eval(ex)` command at the top of this page. That `eval` caused it to be lowered once, and calling `Meta.lower` causes it to be lowered a second time, with different generated names. We can obtain the running version more directly (without having to guess) via the following: ```julia julia> m = first(methods(f)) f(x; color) in Main at REPL[1]:1 julia> using LoweredCodeUtils julia> bodymethod(m) #f#1(color::Symbol, ::typeof(f), x) in Main at REPL[1]:1 ``` We can also rename these methods, if we first turn it into a `frame`: ```julia julia> using JuliaInterpreter julia> frame = Frame(Main, lwr.args[1]) Frame for Main 1 0 1 ─ $(Expr(:thunk, CodeInfo( 2 0 1 ─ return $(Expr(:method, :f)) 3 0 ))) ⋮ julia> rename_framemethods!(frame) Dict{Symbol,LoweredCodeUtils.MethodInfo} with 3 entries: :f => MethodInfo(11, 24, [1]) Symbol("#f#2") => MethodInfo(4, 10, [2]) Symbol("#f#1") => MethodInfo(4, 10, [2]) julia> frame.framecode.src CodeInfo( @ none within `top-level scope' 1 ─ $(Expr(:thunk, CodeInfo( @ none within `top-level scope' 1 ─ return $(Expr(:method, :f)) ))) │ $(Expr(:thunk, CodeInfo( @ none within `top-level scope' 1 ─ return $(Expr(:method, Symbol("#f#1"))) ))) │ $(Expr(:method, :f)) │ $(Expr(:method, Symbol("#f#1"))) │ ($(QuoteNode(typeof)))(var"#f#1") │ ($(QuoteNode(Core.Typeof)))(f) │ ($(QuoteNode(Core.svec)))(%J5, Symbol, %J6, $(QuoteNode(Any))) │ ($(QuoteNode(Core.svec)))() │ ($(QuoteNode(Core.svec)))(%J7, %J8, $(QuoteNode(:(#= REPL[1]:1 =#)))) │ $(Expr(:method, Symbol("#f#1"), %J9, CodeInfo(quote $(Expr(:meta, :nkw, 1)) 2 * x return %2 end))) │ $(Expr(:method, :f)) │ ($(QuoteNode(Core.Typeof)))(f) │ ($(QuoteNode(Core.svec)))(%J12, $(QuoteNode(Any))) │ ($(QuoteNode(Core.svec)))() │ ($(QuoteNode(Core.svec)))(%J13, %J14, $(QuoteNode(:(#= REPL[1]:1 =#)))) │ $(Expr(:method, :f, %J15, CodeInfo(quote var"#f#1"(:green, #self#, x) return %1 end))) │ $(Expr(:method, :f)) │ ($(QuoteNode(Core.Typeof)))(f) │ ($(QuoteNode(Core.kwftype)))(%J18) │ ($(QuoteNode(Core.Typeof)))(f) │ ($(QuoteNode(Core.svec)))(%J19, $(QuoteNode(Any)), %J20, $(QuoteNode(Any))) │ ($(QuoteNode(Core.svec)))() │ ($(QuoteNode(Core.svec)))(%J21, %J22, $(QuoteNode(:(#= REPL[1]:1 =#)))) │ $(Expr(:method, :f, %J23, CodeInfo(quote Base.haskey(@_2, :color) unless %1 goto %11 Base.getindex(@_2, :color) %3 isa Symbol unless %4 goto %7 goto %9 %new(Core.TypeError, Symbol("keyword argument"), :color, Symbol, %3) Core.throw(%7) @_6 = %3 goto %12 @_6 = :green color = @_6 Core.tuple(:color) Core.apply_type(Core.NamedTuple, %13) Base.structdiff(@_2, %14) Base.pairs(%15) Base.isempty(%16) unless %17 goto %20 goto %21 Base.kwerr(@_2, @_3, x) var"#f#1"(color, @_3, x) return %21 end))) │ f │ ($(QuoteNode(ifelse)))(false, false, %J25) └── return %J26 ) ``` While there are a few differences in representation stemming from converting it to a frame, you can see that the `#f#2`s have been changed to `#f#1`s to match the currently-running names.
LoweredCodeUtils
https://github.com/JuliaDebug/LoweredCodeUtils.jl.git
[ "MIT" ]
1.3.0
6842804e7867b115ca9de748a0cf6b364523c16d
code
2249
module Pipe #Reflow piped things replacing the _ in the next section export @pipe const PLACEHOLDER = :_ function replace(arg::Any, target) arg #Normally do nothing end function replace(arg::Symbol, target) if arg==PLACEHOLDER target else arg end end function replace(arg::Expr, target) rep = copy(arg) rep.args = map(x->replace(x, target), rep.args) rep end function rewrite(ff::Expr, target) rep_args = map(x->replace(x, target), ff.args) if ff.args != rep_args #_ subsitution ff.args = rep_args return ff end #No subsitution was done (no _ found) #Apply to a function that is being returned by ff, #(ff could be a function call or something more complex) rewrite_apply(ff,target) end function rewrite_broadcasted(ff::Expr, target) temp_var = gensym() rep_args = map(x->replace(x, temp_var), ff.args) if ff.args != rep_args #_ subsitution ff.args = rep_args return :($temp_var->$ff) end #No subsitution was done (no _ found) #Apply to a function that is being returned by ff, #(ff could be a function call or something more complex) rewrite_apply_broadcasted(ff,target) end function rewrite_apply(ff, target) :($ff($target)) #function application end function rewrite_apply_broadcasted(ff, target) temp_var = gensym() :($temp_var->$ff($temp_var)) end function rewrite(ff::Symbol, target) if ff==PLACEHOLDER target else rewrite_apply(ff,target) end end function rewrite_broadcasted(ff::Symbol, target) if ff==PLACEHOLDER target else rewrite_apply_broadcasted(ff,target) end end function funnel(ee::Any) #Could be a Symbol could be a literal ee #first (left most) input end function funnel(ee::Expr) if (ee.args[1]==:|>) target = funnel(ee.args[2]) #Recurse rewrite(ee.args[3],target) elseif (ee.args[1]==:.|>) target = funnel(ee.args[2]) #Recurse rewritten = rewrite_broadcasted(ee.args[3],target) ee.args[3] = rewritten ee else #Not in a piping situtation ee #make no change end end macro pipe(ee) esc(funnel(ee)) end end
Pipe
https://github.com/oxinabox/Pipe.jl.git
[ "MIT" ]
1.3.0
6842804e7867b115ca9de748a0cf6b364523c16d
code
3916
using Pipe using Test _macroexpand(q) = macroexpand(Main, q) rml! = Base.remove_linenums! # performs linenum removal and temp variable replacing to avoid different names of temp variables in different julia versions stringify_expr(e::Expr) = replace(string(rml!(e)), r"##\d{3}"=>"##000") pipe_equals(e1::Expr, e2::Expr) = stringify_expr(_macroexpand(e1)) == stringify_expr(e2) #No change to nonpipes functionality @test _macroexpand( :(@pipe a) ) == :a #doesn't change single inputs @test _macroexpand( :(@pipe b(a)) ) == :(b(a)) #doesn't change inputs that a function applications #Compatable with Julia 1.3 piping functionality @test _macroexpand( :(@pipe a|>b) ) == :(b(a)) #basic @test _macroexpand( :(@pipe a|>b|>c) ) == :(c(b(a))) #Keeps chaining 3 @test _macroexpand( :(@pipe a|>b|>c|>d) ) == :(d(c(b(a)))) #Keeps chaining 4 @test _macroexpand( :(@pipe a|>b(x)) ) == :((b(x))(a)) #applying to function calls returning functions @test _macroexpand( :(@pipe a(x)|>b ) ) == :(b(a(x))) #feeding functioncall results on wards @test _macroexpand(:(@pipe 1|>a)) ==:(a(1)) #Works with literals (int) @test _macroexpand(:(@pipe "foo"|>a)) == :(a("foo")) #Works with literal (string) @test _macroexpand( :(@pipe a|>bb[2])) == :((bb[2])(a)) #Should work with RHS that is a array reference #Marked locations @test _macroexpand( :(@pipe a |> _)) == :(a) #Identity works @test _macroexpand( :(@pipe a |> _[b])) == :(a[b]) #Indexing works @test _macroexpand( :(@pipe a|>b(_) ) ) == :(b(a)) #Marked location only @test _macroexpand( :(@pipe a|>b(x,_) ) ) == :(b(x,a)) # marked 2nd (and last) @test _macroexpand( :(@pipe a|>b(_,x) ) ) == :(b(a,x)) # marked first @test _macroexpand( :(@pipe a|>b(_,_) ) ) == :(b(a,a)) # marked double (Not certain if this is a good idea) @test _macroexpand( :(@pipe a|>bb[2](x,_))) == :((bb[2])(x,a)) #Should work with RHS that is a array reference #Macros and blocks macro testmacro(arg, n) esc(:($arg + $n)) end @test _macroexpand( :(@pipe a |> @testmacro _ 3 ) ) == :(a + 3) # Can pipe into macros @test _macroexpand( :(@pipe a |> begin b = _; c + b + _ end )) == :( begin b = a; c + b + a end) #marked Unpacking @test _macroexpand( :(@pipe a|>b(_...) ) ) == :(b(a...)) # Unpacking @test _macroexpand( :(@pipe a|>bb[2](_...))) == :((bb[2])(a...)) #Should work with RHS of arry ref and do unpacking #Mixing modes @test _macroexpand( :(@pipe a|>b|>c(_) ) ) == :(c(b(a))) @test _macroexpand( :(@pipe a|>b(x,_)|>c|>d(_,y) ) ) == :(d(c(b(x,a)),y)) @test _macroexpand( :(@pipe a|>b(xb,_)|>c|>d(_,xd)|>e(xe) |>f(xf,_,yf)|>_[i] ) ) == :(f(xf,(e(xe))(d(c(b(xb,a)),xd)),yf)[i]) #Very Complex # broadcasting vars = 1:10 .|> y->gensym() # Julia < 1.3 changes how Symbols are stringified so we compute the representation here @test pipe_equals(:(@pipe 1:10 .|> _*2 ), :(1:10 .|> $(vars[1])->$(vars[1]) * 2)) @test pipe_equals(:(@pipe 1:10 .|> fn ), :(1:10 .|> $(vars[2])->fn($(vars[2])))) @test pipe_equals(:(@pipe a .|> fn .|> _*2 ), :(a .|> ($(vars[3])->fn($(vars[3]))) .|> ($(vars[4])->$(vars[4])*2))) @test pipe_equals(:(@pipe a .|> fn |> _*2 ), :((a .|> $(vars[5])->fn($(vars[5]))) * 2)) @test pipe_equals(:(@pipe [1,2,2] |> atan.([10,20,30], _) ), :(atan.([10,20,30], [1,2,2]))) @test pipe_equals(:(@pipe [1,2,2] .|> atan.([10,20,30], _) ), :([1,2,2] .|> $(vars[6])->atan.([10,20,30], $(vars[6])))) @test pipe_equals(:(@pipe fn |> _.(1:2) ), :(fn.(1:2))) @test pipe_equals(:(@pipe fn .|> _.(1:2) ), :(fn .|> $(vars[7])->$(vars[7]).(1:2))) @test pipe_equals(:(@pipe [true,false] .|> ! ), :([true, false] .|> $(vars[8])->!$(vars[8]))) @test pipe_equals(:(@pipe [1, 2] |> .+(_, x) ), :([1, 2] .+ x)) @test pipe_equals(:(@pipe [1, 2] |> _ .+ x ), :([1, 2] .+ x)) @test pipe_equals(:(@pipe [1, 2] .|> .+(_, x) ), :([1, 2] .|> $(vars[9])->$(vars[9]).+x)) @test pipe_equals(:(@pipe [1, 2] .|> _ .+ x ), :([1, 2] .|> $(vars[10])->$(vars[10]).+x))
Pipe
https://github.com/oxinabox/Pipe.jl.git
[ "MIT" ]
1.3.0
6842804e7867b115ca9de748a0cf6b364523c16d
docs
2683
# Pipe - Julia 1.0: [![Build Status 1.0](https://travis-matrix-badges.herokuapp.com/repos/oxinabox/Pipe.jl/branches/master/1)](https://travis-ci.org/oxinabox/Pipe.jl) - Julia 1.2: [![Build Status 1.2](https://travis-matrix-badges.herokuapp.com/repos/oxinabox/Pipe.jl/branches/master/2)](https://travis-ci.org/oxinabox/Pipe.jl) - Julia 1.3: [![Build Status 1.3](https://travis-matrix-badges.herokuapp.com/repos/oxinabox/Pipe.jl/branches/master/3)](https://travis-ci.org/oxinabox/Pipe.jl) - Julia 1.4: [![Build Status 1.4](https://travis-matrix-badges.herokuapp.com/repos/oxinabox/Pipe.jl/branches/master/4)](https://travis-ci.org/oxinabox/Pipe.jl) - Julia Nightly: [![Build Status Nightly](https://travis-matrix-badges.herokuapp.com/repos/oxinabox/Pipe.jl/branches/master/5)](https://travis-ci.org/oxinabox/Pipe.jl) ## Usage To use this place `@pipe` at the start of the line for which you want "advanced piping functionality" to work. This works the same as Julia Piping, except if you place a underscore in the right hand of the expressing, it will be replaced with the lefthand side. So: ``` @pipe a |> b(x,_) # == b(x,a) #Not: (b(x,_))(a) ``` Futher the _ can be unpacked, called, deindexed offetc. ``` @pipe a |> b(_...) # == b(a...) @pipe a |> b(_(1,2)) # == b(a(1,2)) @pipe a |> b(_[3]) # == b(a[3]) ``` This last can be used for interacting with multiple returned values. In general however, this is frowned upon. Generally a pipeline is good for expressing a logical flow data through Single Input Single Output functions. When you deindex multiple times, that is case of working with Multiple Input Multiple Output functions. In that case it is likely more clear to create named variables, and call the functions normally in sequence. There is also a performace cost for doing multiple deindexes (see below). For example: ``` function get_angle(rise,run) atan(rise/run) end @pipe (2,4) |> get_angle(_[1],_[2]) # == 0.4636476090008061 get_angle(2,4) # == 0.4636476090008061 #Note the ordinary way is much clearer ``` However, for each `_` right hand side of the `|>`, the left hand side will be called. This can incurr a performance cost. Eg ``` function ratio(value, lr, rr) println("slitting on ratio $lr:$rr") value*lr/(lr+rr), value*rr/(lr+rr) end function percent(left, right) left/right*100 end @pipe 10 |> ratio(_,4,1) |> percent(_[1],_[2]) # = 400.0, outputs splitting on ratio 4:1 Twice @pipe 10 |> ratio(_,4,1) |> percent(_...) # = 400.0, outputs splitting on ratio 4:1 Once ``` --------------------- ## See Also: - [List of similar/related works](https://github.com/JuliaLang/julia/issues/5571#issuecomment-205754539)
Pipe
https://github.com/oxinabox/Pipe.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
84
using MeasureTheory dist = For(3) do j Normal(σ=j) end b = basemeasure_depth(dist)
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
1078
using Documenter using MeasureTheory DocMeta.setdocmeta!(MeasureBase, :DocTestSetup, :(using MeasureBase); recursive = true) DocMeta.setdocmeta!(MeasureTheory, :DocTestSetup, :(using MeasureTheory); recursive = true) pages = [ "Home" => "index.md", "Tutorials" => [ "Adding a new measure" => "adding.md", "AffinePushfwd transformations" => "affine.md", ], "API Reference" => [ "MeasureBase" => "api_measurebase.md", "MeasureTheory" => "api_measuretheory.md", "Index" => "api_index.md", ], ] makedocs(; modules = [MeasureBase, MeasureTheory], authors = "Chad Scherrer <[email protected]> and contributors", repo = "https://github.com/JuliaMath/MeasureTheory.jl/blob/{commit}{path}#L{line}", sitename = "MeasureTheory.jl", format = Documenter.HTML(; prettyurls = get(ENV, "CI", "false") == "true", canonical = "https://cscherrer.github.io/MeasureTheory.jl", assets = String[], ), pages = pages, ) deploydocs(; repo = "github.com/JuliaMath/MeasureTheory.jl")
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
353
struct OrderStatistic{n,r,B} <: AbstractMeasure base::B end @inline function basemeasure(d::OrderStatistic{n,r}) WeightedMeasure(logbeta(n + 1, r + 1), d.base) end @inline function logdensity_def(d::OrderStatistic{n,r}, x) logF(x) = logcdf(d.base, x) logFᶜ(x) = logccdf(d.base, x) return (r - 1) * logF(x) + (n - r) * logFᶜ(x) end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
3834
module MeasureTheory using Compat using Random using MeasureBase using MLStyle import TransformVariables const TV = TransformVariables using TransformVariables: asℝ₊, as𝕀, asℝ, transform import Base export TV export transform export ≪ export gentype export For export AbstractMeasure export Dirac export Lebesgue export ℝ, ℝ₊, 𝕀 export ⊙ export SpikeMixture export TrivialMeasure export Likelihood export testvalue export basekernel using Infinities using KeywordCalls using ConstructionBase using Accessors using StatsFuns using SpecialFunctions using ConcreteStructs import LogExpFunctions import NamedTupleTools import InverseFunctions: inverse export inverse import MeasureBase: insupport, instance, marginals import MeasureBase: testvalue, logdensity_def, density_def, basemeasure, kernel, params, paramnames, ∫, 𝒹, ∫exp, smf, invsmf, massof import MeasureBase: ≪ using MeasureBase: BoundedInts, BoundedReals, CountingBase, IntegerDomain, IntegerNumbers using MeasureBase: weightedmeasure, restrict using MeasureBase: AbstractTransitionKernel import Statistics: mean, var, std import MeasureBase: likelihoodof export likelihoodof export log_likelihood_ratio using StaticArraysCore import PrettyPrinting const Pretty = PrettyPrinting import Base: rand using Reexport @reexport using MeasureBase import IfElse using IfElse using Tricks: static_hasmethod using Static export as export AffinePushfwd export AffineTransform export insupport export For using MeasureBase: kernel using MeasureBase: Returns import MeasureBase: proxy, @useproxy import MeasureBase: basemeasure_depth using MeasureBase: LebesgueBase import DensityInterface: logdensityof import DensityInterface: densityof import DensityInterface: DensityKind using DensityInterface using ForwardDiff using ForwardDiff: Dual gentype(μ::AbstractMeasure) = typeof(testvalue(μ)) # gentype(μ::AbstractMeasure) = gentype(basemeasure(μ)) xlogx(x::Number) = LogExpFunctions.xlogx(x) xlogx(x, y) = x * log(x) xlogy(x::Number, y::Number) = LogExpFunctions.xlogy(x, y) xlogy(x, y) = x * log(y) xlog1py(x::Number, y::Number) = LogExpFunctions.xlog1py(x, y) xlog1py(x, y) = x * log(1 + y) using MeasureBase: Φ, Φinv as(args...; kwargs...) = TV.as(args...; kwargs...) # Type piracy until https://github.com/JuliaMath/MeasureBase.jl/issues/127 is fixed MeasureBase.rand(::FixedRNG, ::Type{Bool}) = true include("utils.jl") include("const.jl") include("combinators/for.jl") include("macros.jl") include("combinators/affine.jl") include("combinators/weighted.jl") include("combinators/product.jl") include("combinators/transforms.jl") # include("combinators/exponential-families.jl") include("resettable-rng.jl") include("realized.jl") include("combinators/chain.jl") include("distributions.jl") include("smart-constructors.jl") include("parameterized/normal.jl") include("parameterized/studentt.jl") include("parameterized/cauchy.jl") include("parameterized/laplace.jl") include("parameterized/uniform.jl") include("parameterized/beta.jl") include("parameterized/dirichlet.jl") include("parameterized/gumbel.jl") include("parameterized/exponential.jl") include("parameterized/mvnormal.jl") # include("parameterized/inverse-gamma.jl") include("parameterized/bernoulli.jl") include("parameterized/poisson.jl") include("parameterized/binomial.jl") include("parameterized/multinomial.jl") include("parameterized/lkj-cholesky.jl") include("parameterized/negativebinomial.jl") include("parameterized/betabinomial.jl") include("parameterized/gamma.jl") include("parameterized/snedecorf.jl") include("parameterized/inverse-gaussian.jl") include("combinators/ifelse.jl") include("transforms/corrcholesky.jl") include("transforms/ordered.jl") include("parameterized.jl") include("distproxy.jl") end # module
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
535
export asConst struct AsConst{T} <: TV.VectorTransform value::T end asConst(x) = AsConst(x) as(d::Dirac) = AsConst(d.x) TV.dimension(t::AsConst) = 0 function TV.transform_with(flag::TV.NoLogJac, t::AsConst, x, index) return (t.value, TV.NoLogJac(), index) end function TV.transform_with(flag::TV.LogJac, t::AsConst, x, index) return (t.value, 0.0, index) end TV.inverse_eltype(t::AsConst, x::AbstractVector) = Any function TV.inverse_at!(x::AbstractVector, index, t::AsConst, y::AbstractVector) return index end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
837
export proxy function proxy end import Statistics import StatsBase PROXIES = Dict( :Statistics => [ :mean :std :var :quantile ], :StatsBase => [:entropy], :Distributions => [ :cdf :ccdf :logcdf :logccdf ], ) for m in keys(PROXIES) for f in PROXIES[m] @eval begin import $m: $f export $f end end end entropy(m::AbstractMeasure, b::Real) = entropy(proxy(m), b) mean(m::AbstractMeasure) = mean(proxy(m)) std(m::AbstractMeasure) = std(proxy(m)) var(m::AbstractMeasure) = var(proxy(m)) quantile(m::AbstractMeasure, q) = quantile(proxy(m), q) for f in [ :cdf :ccdf :logcdf :logccdf ] @eval begin $f(d::AbstractMeasure, args...) = $f(MeasureTheory.proxy(d), args...) end end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
1064
import Distributions export Dists const Dists = Distributions @inline function as(d, _data::NamedTuple) if hasmethod(Dists.support, (typeof(d),)) return asTransform(Dists.support(d)) end error("Not implemented:\nas($d)") end using TransformVariables: ShiftedExp, ScaledShiftedLogistic function asTransform(supp::Dists.RealInterval) (lb, ub) = (supp.lb, supp.ub) (lb, ub) == (-Inf, Inf) && (return asℝ) isinf(ub) && return ShiftedExp(true, lb) isinf(lb) && return ShiftedExp(false, lb) return ScaledShiftedLogistic(ub - lb, lb) end as(μ::AbstractMeasure, _data::NamedTuple) = as(μ) as(d::Dists.AbstractMvNormal, _data::NamedTuple = NamedTuple()) = TV.as(Array, size(d)) function as(d::Dists.Distribution{Dists.Univariate}, _data::NamedTuple = NamedTuple()) sup = Dists.support(d) lo = isinf(sup.lb) ? -TV.∞ : sup.lb hi = isinf(sup.ub) ? TV.∞ : sup.ub as(Real, lo, hi) end function as(d::Dists.Product, _data::NamedTuple = NamedTuple()) n = length(d) v = d.v as(Vector, as(v[1]), n) end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
4136
using MLStyle using Random: AbstractRNG using KeywordCalls using ConstructionBase export @parameterized, @half # A fold over ASTs. Example usage in `replace` function foldast(leaf, branch; kwargs...) function go(ast) MLStyle.@match ast begin Expr(head, args...) => branch(head, map(go, args); kwargs...) x => leaf(x; kwargs...) end end return go end # function replace(p, f, expr) # leaf(s) = p(s) ? f(s) : s # branch(head, newargs) = Expr(head, newargs...) # foldast(leaf, branch)(expr) # end # from https://thautwarm.github.io/MLStyle.jl/latest/tutorials/capture.html function capture(template, ex, action) let template = Expr(:quote, template) quote @match $ex begin $template => $action _ => nothing end end end end macro capture(template, ex, action) capture(template, ex, action) |> esc end function _parameterized(__module__, expr) @capture ($op($μ($(p...)), $base)) expr begin @assert op ∈ [:<<, :≪, :≃] μbase = Symbol(:__, μ, :_base) μ = esc(μ) base = esc(base) # @gensym basename q = quote struct $μ{N,T} <: MeasureBase.ParameterizedMeasure{N} par::NamedTuple{N,T} $μ{N,T}(nt::NamedTuple{N,T}) where {N,T<:Tuple} = new{N,T}(nt) end const $μbase = $base MeasureBase.basemeasure(::$μ) = $μbase end if !isempty(p) # e.g. Normal(μ,σ) = Normal((μ=μ, σ=σ)) pnames = QuoteNode.(p) push!(q.args, :($μ($(p...)) = $μ(NamedTuple{($(pnames...),)}(($(p...),))))) end return q end @capture $μ($(p...)) expr begin μ = esc(μ) q = quote struct $μ{N,T} <: MeasureBase.ParameterizedMeasure{N} par::NamedTuple{N,T} $μ{N,T}(nt::NamedTuple{N,T}) where {N,T<:Tuple} = new{N,T}(nt) end end if !isempty(p) # e.g. Normal(μ,σ) = Normal((μ=μ, σ=σ)) pnames = QuoteNode.(p) push!(q.args, :($μ($(p...)) = $μ(NamedTuple{($(pnames...),)}(($(p...),))))) end return q end @capture $μ($(p...)) expr begin μ = esc(μ) q = quote struct $μ{N,T} <: MeasureBase.ParameterizedMeasure{N} par::NamedTuple{N,T} end $μ{N,T}(nt::NamedTuple{N,T}) where {N,T<:Tuple} = new{N,T}(nt) end if !isempty(p) # e.g. Normal(μ,σ) = Normal((μ=μ, σ=σ)) pnames = QuoteNode.(p) push!(q.args, :($μ($(p...)) = $μ(NamedTuple{($(pnames...),)}(($(p...),))))) end return q end end """ @parameterized <declaration> The <declaration> gives a measure and its default parameters, and specifies its relation to its base measure. For example, @parameterized Normal(μ,σ) declares the `Normal` is a measure with default parameters `μ and σ`. The result is equivalent to ``` struct Normal{N,T} <: ParameterizedMeasure{N} par :: NamedTuple{N,T} end KeywordCalls.@kwstruct Normal(μ,σ) Normal(μ,σ) = Normal((μ=μ, σ=σ)) ``` See [KeywordCalls.jl](https://github.com/cscherrer/KeywordCalls.jl) for details on `@kwstruct`. """ macro parameterized(expr) _parameterized(__module__, expr) end """ @half dist([paramnames]) Starting from a symmetric univariate measure `dist ≪ Lebesgue(ℝ)`, create a new measure `Halfdist ≪ Lebesgue(ℝ₊)`. For example, @half Normal() creates `HalfNormal()`, and @half StudentT(ν) creates `HalfStudentT(ν)`. """ macro half(ex) _half(__module__, ex) end function _half(__module__, ex) @match ex begin :($dist) => begin halfdist = esc(Symbol(:Half, dist)) dist = esc(dist) quote $halfdist(arg::NamedTuple) = Half($dist(arg)) $halfdist(args...) = Half($dist(args...)) $halfdist(; kwargs...) = Half($dist(; kwargs...)) end end end end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
6485
export asparams """ `asparams` build on `TransformVariables.as` to construct bijections to the parameter space of a given parameterized measure. Because this is only possible for continuous parameter spaces, we allow constraints to assign values to any subset of the parameters. -------- asparams(::Type{<:ParameterizedMeasure}, ::StaticSymbol) Return a transformation for a particular parameter of a given parameterized measure. For example, ``` julia> asparams(Normal, static(:σ)) asℝ₊ ``` ----- asparams(::Type{<: ParameterizedMeasure{N}}, constraints::NamedTuple) where {N} Return a transformation for a given parameterized measure subject to the named tuple `constraints`. For example, ``` julia> asparams(Binomial{(:p,)}, (n=10,)) TransformVariables.TransformTuple{NamedTuple{(:p,), Tuple{TransformVariables.ScaledShiftedLogistic{Float64}}}}((p = as𝕀,), 1) ``` ------------ aspararams(::ParameterizedMeasure) Return a transformation with no constraints. For example, ``` julia> asparams(Normal{(:μ,:σ)}) TransformVariables.TransformTuple{NamedTuple{(:μ, :σ), Tuple{TransformVariables.Identity, TransformVariables.ShiftedExp{true, Float64}}}}((μ = asℝ, σ = asℝ₊), 2) ``` """ function asparams end function asparams(μ::M, v::StaticSymbol) where {M<:ParameterizedMeasure} asparams(constructorof(M), v) end asparams(μ, s::Symbol) = asparams(μ, static(s)) asparams(M::Type{A}) where {A<:AbstractMeasure} = asparams(M, NamedTuple()) function asparams(::Type{M}, constraints::NamedTuple{N}) where {N,M<:ParameterizedMeasure} # @show M thekeys = paramnames(M, constraints) t1 = NamedTuple{thekeys}(asparams(M, StaticSymbol(k)) for k in thekeys) t2 = NamedTuple{N}(map(asConst, values(constraints))) C = constructorof(M) # @show C # @show constraints # @show transforms # Make sure we end up with a consistent ordering ordered_transforms = params(C(merge(t1, t2))) return as(ordered_transforms) end # TODO: Make this work for AffinePushfwd measures # function asparams(::Type{M}, constraints::NamedTuple{N}) where {N, M<: AffinePushfwd} # ... # end function asparams(μ::M, nt::NamedTuple = NamedTuple()) where {M<:ParameterizedMeasure} asparams(constructorof(M), nt) end as(::Half) = asℝ₊ asparams(::AffinePushfwd, ::StaticSymbol{:μ}) = asℝ asparams(::AffinePushfwd, ::StaticSymbol{:σ}) = asℝ₊ asparams(::Type{A}, ::StaticSymbol{:μ}) where {A<:AffinePushfwd} = asℝ asparams(::Type{A}, ::StaticSymbol{:σ}) where {A<:AffinePushfwd} = asℝ₊ function asparams(d::AffinePushfwd{N,M,T}, ::StaticSymbol{:μ}) where {N,M,T<:AbstractArray} as(Array, asℝ, size(d.μ)) end function asparams(d::AffinePushfwd{N,M,T}, ::StaticSymbol{:σ}) where {N,M,T<:AbstractArray} as(Array, asℝ, size(d.σ)) end asparams(::Type{<:Bernoulli}, ::StaticSymbol{:p}) = as𝕀 asparams(::Type{<:Bernoulli}, ::StaticSymbol{:logitp}) = asℝ asparams(::Type{<:Beta}, ::StaticSymbol{:α}) = asℝ₊ asparams(::Type{<:Beta}, ::StaticSymbol{:β}) = asℝ₊ asparams(::Type{<:BetaBinomial}, ::StaticSymbol{:α}) = asℝ₊ asparams(::Type{<:BetaBinomial}, ::StaticSymbol{:β}) = asℝ₊ asparams(::Type{<:Binomial}, ::StaticSymbol{:p}) = as𝕀 asparams(::Type{<:Binomial}, ::StaticSymbol{:logitp}) = asℝ asparams(::Type{<:Binomial}, ::StaticSymbol{:probitp}) = asℝ asparams(::Type{<:Exponential}, ::StaticSymbol{:β}) = asℝ₊ asparams(::Type{<:Exponential}, ::StaticSymbol{:logβ}) = asℝ asparams(::Type{<:Exponential}, ::StaticSymbol{:λ}) = asℝ₊ asparams(::Type{<:Exponential}, ::StaticSymbol{:logλ}) = asℝ asparams(::Type{<:LKJCholesky}, ::StaticSymbol{:η}) = asℝ₊ asparams(::Type{<:LKJCholesky}, ::StaticSymbol{:logη}) = asℝ asparams(::Type{<:NegativeBinomial}, ::StaticSymbol{:p}) = as𝕀 asparams(::Type{<:NegativeBinomial}, ::StaticSymbol{:logitp}) = asℝ asparams(::Type{<:NegativeBinomial}, ::StaticSymbol{:r}) = asℝ₊ asparams(::Type{<:NegativeBinomial}, ::StaticSymbol{:λ}) = asℝ₊ asparams(::Type{<:NegativeBinomial}, ::StaticSymbol{:logλ}) = asℝ asparams(::Type{<:Normal}, ::StaticSymbol{:μ}) = asℝ asparams(::Type{<:Normal}, ::StaticSymbol{:σ}) = asℝ₊ asparams(::Type{<:Normal}, ::StaticSymbol{:σ²}) = asℝ₊ asparams(::Type{<:Normal}, ::StaticSymbol{:τ}) = asℝ₊ asparams(::Type{<:Normal}, ::StaticSymbol{:logτ}) = asℝ asparams(::Type{<:Poisson}, ::StaticSymbol{:λ}) = asℝ₊ asparams(::Type{<:Poisson}, ::StaticSymbol{:logλ}) = asℝ asparams(::Type{<:SnedecorF}, ::StaticSymbol{:ν1}) = asℝ₊ asparams(::Type{<:SnedecorF}, ::StaticSymbol{:ν2}) = asℝ₊ asparams(::Type{<:StudentT}, ::StaticSymbol{:ν}) = asℝ₊ function as(d::PowerMeasure) as(Array, as(d.parent), length.(d.axes)...) end function as(d::ProductMeasure{<:AbstractArray{<:Dirac}}) return asConst(testvalue.(marginals(d))) end function as(d::ProductMeasure{A}) where {A<:AbstractArray} mar = marginals(d) ts = map(as, mar) if allequal(ts) return as(Array, first(ts), size(ts)) else error("Not yet implemented") end end function as(d::ProductMeasure{A}) where {A<:MappedArrays.ReadonlyMappedArray} d1 = marginals(d).f(first(marginals(d).data)) as(Array, as(d1), size(marginals(d))...) end function as(d::ProductMeasure{T}) where {T<:Tuple} as(map(as, d.marginals)) end function as(d::ProductMeasure{<:Base.Generator}) d1 = marginals(d).f(first(marginals(d).iter)) as(Array, as(d1), size(marginals(d))...) end as(::Beta) = as𝕀 as(::Cauchy) = asℝ as(d::Dirichlet{(:α,)}) = TV.UnitSimplex(length(d.α)) as(::Exponential) = asℝ₊ as(::Gamma) = asℝ₊ as(::Gumbel) = asℝ as(::InverseGaussian) = asℝ₊ as(::Laplace) = asℝ as(d::MvNormal{(:μ,)}) = as(Array, length(d.μ)) as(d::MvNormal{(:Σ,),Tuple{C}}) where {C<:Cholesky} = as(Array, size(d.Σ, 1)) as(d::MvNormal{(:Λ,),Tuple{C}}) where {C<:Cholesky} = as(Array, size(d.Λ, 1)) as(d::MvNormal{(:μ, :Σ),<:Tuple{T,C}}) where {T,C<:Cholesky} = as(Array, size(d.Σ, 1)) as(d::MvNormal{(:μ, :Λ),<:Tuple{T,C}}) where {T,C<:Cholesky} = as(Array, size(d.Λ, 1)) function as(d::MvNormal{(:σ,),Tuple{M}}) where {M<:Triangular} σ = d.σ if @inbounds all(i -> σ[i] ≠ 0, diagind(σ)) return as(Array, size(σ, 1)) else @error "Not implemented yet" end end function as(d::MvNormal{(:λ,),Tuple{M}}) where {M<:Triangular} λ = d.λ if @inbounds all(i -> λ[i] > 0, diagind(λ)) return as(Array, size(λ, 1)) else @error "Not implemented yet" end end as(::Normal) = asℝ as(::SnedecorF) = asℝ₊ as(::StudentT) = asℝ as(::Uniform{()}) = as𝕀
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
4494
using DynamicIterators import DynamicIterators: dub, dyniterate, evolve struct SamplesTo{M,T} measure::M element::T end export ↝ ↝(m, x) = SamplesTo(m, x) function Pretty.tile(s::SamplesTo) Pretty.pair_layout(Pretty.tile(s.measure), Pretty.tile(s.element); sep = " ↝ ") end function Base.show(io::IO, s::SamplesTo) io = IOContext(io, :compact => true) Pretty.pprint(io, s) end ############################################################################### struct Realized{R,S,T} <: DynamicIterators.DynamicIterator rng::ResettableRNG{R,S} iter::T end Base.copy(r::Realized) = Realized(copy(r.rng), r.iter) reset!(rv::Realized) = reset!(rv.rng) Base.show(io::IO, r::Realized) = Pretty.pprint(io, r) function Pretty.quoteof(r::Realized) :(Realized($(Pretty.quoteof(r.rng)), $(Pretty.quoteof(r.iter)))) end Base.IteratorEltype(mc::Realized) = Base.HasEltype() # function Base.eltype(::Type{Rz}) where {R,S,T,Rz <: Realized{R,S,T}} # eltype(T) # end Base.length(r::Realized) = length(r.iter) Base.size(r::Realized) = size(r.iter) Base.IteratorSize(::Type{Rz}) where {R,S,T,Rz<:Realized{R,S,T}} = Base.IteratorSize(T) Base.IteratorSize(r::Rz) where {R,S,T,Rz<:Realized{R,S,T}} = Base.IteratorSize(r.iter) Base.iterate(rv::Realized) = iterate(rv, nothing) function Base.iterate(rv::Realized{R,S,T}, ::Nothing) where {R,S,T} reset!(rv.rng) if static_hasmethod(evolve, Tuple{T}) dyniterate(rv, nothing) else μs = iterate(rv.iter) isnothing(μs) && return nothing (μ, s) = μs x = rand(rv.rng, μ) return (μ ↝ x), s end end function Base.iterate(rv::Realized{R,S,T}, s) where {R,S,T} if static_hasmethod(evolve, Tuple{T}) dyniterate(rv, s) else μs = iterate(rv.iter, s) isnothing(μs) && return nothing (μ, s) = μs x = rand(rv.rng, μ) return (μ ↝ x), s end end function dyniterate(rv::Realized, ::Nothing) rv = copy(rv) reset!(rv.rng) μ = evolve(rv.iter) x = rand(rv.rng, μ) (μ ↝ x), Sample(x, rv.rng) end function dyniterate(rv::Realized, u::Sample) dyniterate(rv.iter, u) end ############################################################ struct RealizedMeasures{R,S,T} <: DynamicIterators.DynamicIterator rng::ResettableRNG{R,S} iter::T end Base.show(io::IO, r::RealizedMeasures) = Pretty.pprint(io, r) function Pretty.quoteof(r::RealizedMeasures) :(RealizedMeasures($(Pretty.quoteof(r.rng)), $(Pretty.quoteof(r.iter)))) end function Base.iterate(rm::RealizedMeasures, s = nothing) val, s = iterate(rm, s) (val.measure, s) end function dyniterate(rm::RealizedMeasures, s) val, s = dyniterate(rm, s) (val.measure, s) end ########################################## struct RealizedSamples{R,S,T} <: DynamicIterators.DynamicIterator parent::Realized{R,S,T} end RealizedSamples(rng::AbstractRNG, iter) = RealizedSamples(Realized(rng, iter)) Base.show(io::IO, r::RealizedSamples) = Pretty.pprint(io, r) Base.size(r::RealizedSamples) = size(r.parent) function Pretty.quoteof(r::RealizedSamples) :(RealizedSamples($(Pretty.quoteof(r.parent.rng)), $(Pretty.quoteof(r.parent.iter)))) end function iter_helper(x) isnothing(x) && return x val, s = x (val.element, s) end function Base.iterate(rm::RealizedSamples) iter_helper(iterate(rm.parent)) end function Base.iterate(rm::RealizedSamples, ::Nothing) iter_helper(iterate(rm.parent)) end function Base.iterate(rm::RealizedSamples, s) iter_helper(iterate(rm.parent, s)) end function dyniterate(rm::RealizedSamples, s) val, s = dyniterate(rm.parent, s) (val.element, s) end Base.copy(r::RealizedSamples) = RealizedSamples(copy(r.parent)) reset!(rv::RealizedSamples) = RealizedSamples(reset!(rv.parent)) Base.IteratorEltype(mc::RealizedSamples) = Base.HasEltype() # function Base.eltype(::Type{Rz}) where {R,S,T,Rz <: RealizedSamples{R,S,T}} # eltype(T) # end Base.length(r::RealizedSamples) = length(r.parent) # Base.size(r::RealizedSamples) = ... Base.IteratorSize(r::RealizedSamples) = Base.IteratorSize(r.parent) function Base.rand( rng::AbstractRNG, ::Type{T}, d::ProductMeasure{G}, ) where {T,G<:Base.Generator} RealizedSamples(ResettableRNG(rng), marginals(d)) end function Base.rand( rng::AbstractRNG, ::Type, d::For{T,F,I}, ) where {N,T,F,I<:NTuple{N,<:Base.Generator}} RealizedSamples(ResettableRNG(rng), marginals(d)) end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
3740
using Random export ResettableRNG export reset! struct ResettableRNG{R,S} <: Random.AbstractRNG rng::R seed::S function ResettableRNG(rng, seed::S) where {S} rng = copy(rng) R2 = typeof(rng) new{R2,S}(rng, seed) end function ResettableRNG(rng) seed = rand(rng, UInt) S = typeof(seed) rng = copy(rng) R2 = typeof(rng) new{R2,UInt}(copy(rng), seed) end end function Base.copy(r::ResettableRNG) ResettableRNG(r.rng, copy(r.seed)) end function Base.show(io::IO, r::ResettableRNG) io = IOContext(io, :compact => true) print(io, "ResettableRNG(::", constructorof(typeof(r.rng)), ", ", r.seed, ")") end function reset!(r::ResettableRNG) # @info "Calling reset! on $r" Random.seed!(r.rng, r.seed) end import Random using Random: randexp using InteractiveUtils: subtypes for T in vcat(subtypes(Signed), subtypes(Unsigned), subtypes(AbstractFloat)) isbitstype(T) || continue @eval begin function Base.rand(r::ResettableRNG, ::Type{$T}) rand(r.rng, $T) end function Base.randn(r::ResettableRNG, ::Type{$T}) randn(r.rng, $T) end function Random.randexp(r::ResettableRNG, ::Type{$T}) randexp(r.rng, $T) end end end function Base.rand(r::ResettableRNG, d::AbstractMeasure) rand(r.rng, d) end function Base.rand(r::ResettableRNG, ::Type{T}, d::AbstractMeasure) where {T} rand(r.rng, T, d) end Base.iterate(r::ResettableRNG) = iterate(r, nothing) function Base.iterate(r::ResettableRNG, ::Nothing) @info "Calling `iterate(::ResettableRNG)" r = copy(r) reset!(r) return (rand(r), nothing) end Base.iterate(r::ResettableRNG, _) = (rand(r), nothing) Base.IteratorSize(r::ResettableRNG) = Base.IsInfinite() function Random.Sampler( r::Type{R}, s::Random.Sampler, rep::Random.Repetition, ) where {R<:ResettableRNG} return Random.Sampler(r.rng, s, r) end # UIntBitsTypes = [UInt128, UInt16, UInt32, UInt64, UInt8] # IntBitsTypes = [Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8] # FloatBitsTypes = [Float16, Float32, Float64] # for I in IntBitsTypes # for T in [ # Random.SamplerTrivial{Random.UInt104Raw{I}} # Random.SamplerTrivial{Random.UInt10Raw{I}} # ] # @eval begin # function Base.rand(r::ResettableRNG, sp::$T) # rand(r.rng, sp) # end # end # end # end # for U in UIntBitsTypes # for I in IntBitsTypes # for T in [ # Random.SamplerRangeInt{T,U} where {T<:Union{IntBitsTypes...}} # Random.SamplerRangeFast{U,I} # ] # @eval begin # function Base.rand(r::ResettableRNG, sp::$T) # rand(r.rng, sp) # end # end # end # end # end # for T in [ # Random.Sampler # Random.SamplerBigInt # Random.SamplerTag{<:Set,<:Random.Sampler} # # Random.SamplerTrivial{Random.CloseOpen01{T}} where {T<:FloatBitsTypes} # # Random.SamplerTrivial{Random.UInt23Raw{UInt32}} # Random.UniformT # Random.SamplerSimple{T,S,E} where {E,S,T<:Tuple} # Random.SamplerType{T} where {T<:AbstractChar} # Random.SamplerTrivial{Tuple{A}} where {A} # Random.SamplerSimple{Tuple{A,B,C},S,E} where {E,S,A,B,C} # Random.SamplerSimple{<:AbstractArray,<:Random.Sampler} # Random.Masked # Random.SamplerSimple{BitSet,<:Random.Sampler} # Random.SamplerTrivial{<:Random.UniformBits{T},E} where {E,T} # ] # @eval begin # function Base.rand(r::ResettableRNG, sp::$T) # rand(r.rng, sp) # end # end # end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
775
############################################################################### # AffinePushfwd affine(f::AffineTransform, μ::AbstractMeasure) = AffinePushfwd(f, μ) affine(nt::NamedTuple, μ::AbstractMeasure) = affine(AffineTransform(nt), μ) affine(f) = Base.Fix1(affine, f) function affine(f::AffineTransform, parent::WeightedMeasure) WeightedMeasure(parent.logweight, affine(f, parent.base)) end using MeasureBase: RealNumbers function affine(f::AffineTransform{(:μ, :σ)}, parent::Lebesgue{RealNumbers}) affine(AffineTransform((σ = f.σ,)), parent) end function affine(f::AffineTransform{(:μ, :λ)}, parent::Lebesgue{RealNumbers}) affine(AffineTransform((λ = f.λ,)), parent) end affine(f::AffineTransform, μ::LebesgueBase) = weightedmeasure(-logjac(f), μ)
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
3670
using LinearAlgebra function solve(A::Union{AbstractMatrix,Factorization}, y::AbstractArray) (m, n) = size(A) n == 1 && return [dot(A, y) / sum(a -> a^2, A)] return A \ y end @inline function mydot(a::Real, b::Real) return a * b end @inline function mydot(a::Ta, b::Tb) where {Ta<:AbstractArray,Tb<:AbstractArray} return dot(a, b) end @inline function _mydot(a::NTuple{0}, b::NTuple{0}, s) return s end @inline function mydot(a::Tuple, b::Tuple) z = 0.0 _mydot(a, b, z) end @inline function _mydot(a::Tuple, b::Tuple, s) _mydot(Base.tail(a), Base.tail(b), s + mydot(first(a), first(b))) end @generated function mydot(a::SVector{N,Ta}, b::SVector{N,Tb}) where {N,Ta,Tb} z = zero(float(Base.promote_eltype(Ta, Tb))) quote $(Expr(:meta, :inline)) result = $z @inbounds Base.Cartesian.@nexprs $N i -> begin result += a[i] * b[i] end return result end end in𝕀(x) = static(0.0) ≤ x ≤ static(1.0) inℝ₊(x) = static(0.0) ≤ x _eltype(T) = eltype(T) function _eltype(g::Base.Generator{I}) where {I} Core.Compiler.return_type(g.f, Tuple{_eltype(I)}) end function _eltype( ::Type{Base.Generator{I,ComposedFunction{Outer,Inner}}}, ) where {Outer,Inner,I} _eltype(Base.Generator{_eltype(Base.Generator{I,Inner}),Outer}) end function _eltype(::Type{Base.Generator{I,F}}) where {F<:Function,I} f = instance(F) Core.Compiler.return_type(f, Tuple{_eltype(I)}) end function _eltype(::Type{Z}) where {Z<:Iterators.Zip} map(_eltype, Z.types[1].types) end # Adapted from https://github.com/JuliaArrays/MappedArrays.jl/blob/46bf47f3388d011419fe43404214c1b7a44a49cc/src/MappedArrays.jl#L229 function func_string(f, types) ft = typeof(f) mt = ft.name.mt name = string(mt.name) if startswith(name, '#') # This is an anonymous function. See if it can be printed nicely lwrds = code_lowered(f, types) if length(lwrds) != 1 return string(f) end lwrd = lwrds[1] c = lwrd.code if length(c) == 2 && ( (isa(c[2], Expr) && c[2].head === :return) || (isdefined(Core, :ReturnNode) && isa(c[2], Core.ReturnNode)) ) # This is a single-line anonymous function, we should handle it s = lwrd.slotnames[2:end] result = "" if length(s) == 1 result *= string(s[1]) result *= "->" else result *= "(" * join(string.(tuple(s...)), ", ") * ")" result *= "->" end c1 = string(c[1]) for i in 1:length(s) c1 = replace(c1, "_" * string(i + 1) => string(s[i])) end result *= c1 return result else return string(f) end else return string(f) end end function getL(C::Cholesky) Cfactors = getfield(C, :factors) Cuplo = getfield(C, :uplo) LowerTriangular(Cuplo === 'L' ? Cfactors : Cfactors') end function getU(C::Cholesky) Cfactors = getfield(C, :factors) Cuplo = getfield(C, :uplo) UpperTriangular(Cuplo === 'U' ? Cfactors : Cfactors') end const Triangular = Union{L,U} where {L<:LowerTriangular,U<:UpperTriangular} # Ideally we could just add one method smf(μ::$M, x::Dual{TAG}) where TAG # But then we have method ambiguities macro smfAD(M) quote function MeasureBase.smf(μ::$M, x::Dual{TAG}) where {TAG} val = ForwardDiff.value(x) Δ = ForwardDiff.partials(x) Dual{TAG}(smf(μ, val), Δ * densityof(μ, val)) end end end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
11984
export AffinePushfwd, AffineTransform using LinearAlgebra import Base const AFFINEPARS = [ (:μ, :σ) (:μ, :λ) (:σ,) (:λ,) (:μ,) ] struct AffineTransform{N,T} par::NamedTuple{N,T} end function Pretty.tile(f::AffineTransform) result = Pretty.literal("AffineTransform") result *= Pretty.literal(sprint(show, params(f); context = :compact => true)) result end Base.show(io::IO, f::AffineTransform) = Pretty.pprint(io, f) params(f::AffineTransform) = getfield(f, :par) @inline Base.getproperty(d::AffineTransform, s::Symbol) = getfield(getfield(d, :par), s) Base.propertynames(d::AffineTransform{N}) where {N} = N import InverseFunctions: inverse @inline inverse(f::AffineTransform{(:μ, :σ)}) = AffineTransform((μ = -(f.σ \ f.μ), λ = f.σ)) @inline inverse(f::AffineTransform{(:μ, :λ)}) = AffineTransform((μ = -f.λ * f.μ, σ = f.λ)) @inline inverse(f::AffineTransform{(:σ,)}) = AffineTransform((λ = f.σ,)) @inline inverse(f::AffineTransform{(:λ,)}) = AffineTransform((σ = f.λ,)) @inline inverse(f::AffineTransform{(:μ,)}) = AffineTransform((μ = -f.μ,)) # `size(f) == (m,n)` means `f : ℝⁿ → ℝᵐ` Base.size(f::AffineTransform{(:μ, :σ)}) = size(f.σ) Base.size(f::AffineTransform{(:μ, :λ)}) = size(f.λ) Base.size(f::AffineTransform{(:σ,)}) = size(f.σ) Base.size(f::AffineTransform{(:λ,)}) = size(f.λ) LinearAlgebra.rank(f::AffineTransform{(:σ,)}) = rank(f.σ) LinearAlgebra.rank(f::AffineTransform{(:λ,)}) = rank(f.λ) LinearAlgebra.rank(f::AffineTransform{(:μ, :σ)}) = rank(f.σ) LinearAlgebra.rank(f::AffineTransform{(:μ, :λ)}) = rank(f.λ) function Base.size(f::AffineTransform{(:μ,)}) (n,) = size(f.μ) return (n, n) end Base.size(f::AffineTransform, n::Int) = @inbounds size(f)[n] (f::AffineTransform{(:μ,)})(x) = x + f.μ (f::AffineTransform{(:σ,)})(x) = f.σ * x (f::AffineTransform{(:λ,)})(x) = f.λ \ x (f::AffineTransform{(:μ, :σ)})(x) = f.σ * x + f.μ (f::AffineTransform{(:μ, :λ)})(x) = f.λ \ x + f.μ rowsize(x) = () rowsize(x::AbstractArray) = (size(x, 1),) function rowsize(f::AffineTransform) size_f = size(f) size_f isa Tuple{} && return 0 return first(size_f) end colsize(x) = () colsize(x::AbstractArray) = (size(x, 2),) function colsize(f::AffineTransform) size_f = size(f) size_f isa NTuple{2} && return last(size_f) return 0 end @inline function apply!(x, f::AffineTransform{(:μ,)}, z) x .= z .+ f.μ return x end @inline function apply!(x, f::AffineTransform{(:σ,)}, z) mul!(x, f.σ, z) return x end @inline function apply!(x, f::AffineTransform{(:λ,),Tuple{F}}, z) where {F<:Factorization} ldiv!(x, f.λ, z) return x end @inline function apply!(x, f::AffineTransform{(:λ,)}, z) ldiv!(x, factorize(f.λ), z) return x end @inline function apply!(x, f::AffineTransform{(:μ, :σ)}, z) apply!(x, AffineTransform((σ = f.σ,)), z) apply!(x, AffineTransform((μ = f.μ,)), x) return x end @inline function apply!(x, f::AffineTransform{(:μ, :λ)}, z) apply!(x, AffineTransform((λ = f.λ,)), z) apply!(x, AffineTransform((μ = f.μ,)), x) return x end @inline function logjac(x::AbstractMatrix) (m, n) = size(x) m == n && return first(logabsdet(x)) # Equivalent to sum(log, svdvals(x)), but much faster m > n && return first(logabsdet(x' * x)) / 2 return first(logabsdet(x * x')) / 2 end logjac(x::Number) = log(abs(x)) # TODO: `log` doesn't work for the multivariate case, we need the log absolute determinant logjac(f::AffineTransform{(:μ, :σ)}) = logjac(f.σ) logjac(f::AffineTransform{(:μ, :λ)}) = -logjac(f.λ) logjac(f::AffineTransform{(:σ,)}) = logjac(f.σ) logjac(f::AffineTransform{(:λ,)}) = -logjac(f.λ) logjac(f::AffineTransform{(:μ,)}) = static(0.0) ############################################################################### struct OrthoLebesgue{N,T} <: PrimitiveMeasure par::NamedTuple{N,T} OrthoLebesgue(nt::NamedTuple{N,T}) where {N,T} = new{N,T}(nt) end params(d::OrthoLebesgue) = getfield(d, :par) Base.getproperty(d::OrthoLebesgue, s::Symbol) = getproperty(params(d), s) Base.propertynames(d::OrthoLebesgue) = propertynames(params(d)) testvalue(d::OrthoLebesgue{(:μ, :σ)}) = d.μ testvalue(d::OrthoLebesgue{(:μ, :λ)}) = d.μ testvalue(d::OrthoLebesgue{(:μ,)}) = d.μ testvalue(d::OrthoLebesgue{(:σ,)}) = zeros(size(d.σ, 1)) testvalue(d::OrthoLebesgue{(:λ,)}) = zeros(size(d.λ, 2)) function insupport(d::OrthoLebesgue, x) f = AffineTransform(params(d)) finv = inverse(f) z = finv(x) f(z) ≈ x end basemeasure(d::OrthoLebesgue) = d logdensity_def(::OrthoLebesgue, x) = static(0.0) struct AffinePushfwd{N,M,T} <: MeasureBase.AbstractPushforward f::AffineTransform{N,T} parent::M end function Pretty.tile(d::AffinePushfwd) pars = Pretty.literal(sprint(show, params(d.f); context = :compact => true)) Pretty.list_layout([pars, Pretty.tile(d.parent)]; prefix = :AffinePushfwd) end @inline MeasureBase.transport_origin(d::AffinePushfwd) = d.parent @inline MeasureBase.to_origin(d::AffinePushfwd, y) = inverse(getfield(d, :f))(y) @inline MeasureBase.from_origin(d::AffinePushfwd, x) = getfield(d, :f)(x) @inline function testvalue(d::AffinePushfwd) f = getfield(d, :f) z = testvalue(parent(d)) return f(z) end AffinePushfwd(nt::NamedTuple, μ::AbstractMeasure) = affine(nt, μ) AffinePushfwd(nt::NamedTuple) = affine(nt) Base.parent(d::AffinePushfwd) = getfield(d, :parent) function params(μ::AffinePushfwd) nt1 = getfield(getfield(μ, :f), :par) nt2 = params(parent(μ)) return merge(nt1, nt2) end function paramnames(::Type{A}) where {N,M,A<:AffinePushfwd{N,M}} tuple(union(N, paramnames(M))...) end Base.propertynames(d::AffinePushfwd{N}) where {N} = N ∪ (:parent, :f) @inline function Base.getproperty(d::AffinePushfwd, s::Symbol) if s === :parent return getfield(d, :parent) elseif s === :f return getfield(d, :f) else return getproperty(getfield(d, :f), s) end end Base.size(d::AffinePushfwd) = size(d.μ) Base.size(d::AffinePushfwd{(:σ,)}) = (size(d.σ, 1),) Base.size(d::AffinePushfwd{(:λ,)}) = (size(d.λ, 2),) @inline function logdensity_def(d::AffinePushfwd{(:σ,)}, x::AbstractArray) z = solve(d.σ, x) MeasureBase.unsafe_logdensityof(d.parent, z) end @inline function logdensity_def(d::AffinePushfwd{(:λ,)}, x::AbstractArray) z = d.λ * x MeasureBase.unsafe_logdensityof(d.parent, z) end @inline function logdensity_def(d::AffinePushfwd{(:μ,)}, x::AbstractArray) z = mappedarray(-, x, d.μ) MeasureBase.unsafe_logdensityof(d.parent, z) end @inline function logdensity_def(d::AffinePushfwd{(:μ, :σ)}, x::AbstractArray) z = d.σ \ mappedarray(-, x, d.μ) MeasureBase.unsafe_logdensityof(d.parent, z) end @inline function logdensity_def(d::AffinePushfwd{(:μ, :λ)}, x::AbstractArray) z = d.λ * mappedarray(-, x, d.μ) MeasureBase.unsafe_logdensityof(d.parent, z) end @inline function logdensity_def(d::AffinePushfwd, x) z = inverse(d.f)(x) logdensity_def(d.parent, z) end # # # logdensity_def(d::AffinePushfwd{(:μ,:λ)}, x) = logdensity_def(d.parent, d.σ \ (x - d.μ)) # # @inline function logdensity_def(d::AffinePushfwd{(:μ,:σ), P, Tuple{V,M}}, x) where {P, V<:AbstractVector, M<:AbstractMatrix} # # z = x - d.μ # # σ = d.σ # # if σ isa Factorization # # ldiv!(σ, z) # # else # # ldiv!(factorize(σ), z) # # end # # sum(zⱼ -> logdensity_def(d.parent, zⱼ), z) # # end # # # logdensity_def(d::AffinePushfwd{(:μ,:λ)}, x) = logdensity_def(d.parent, d.λ * (x - d.μ)) # # @inline function logdensity_def(d::AffinePushfwd{(:μ,:λ), P,Tuple{V,M}}, x) where {P,V<:AbstractVector, M<:AbstractMatrix} # # z = x - d.μ # # lmul!(d.λ, z) # # logdensity_def(d.parent, z) # # end @inline function basemeasure(d::AffinePushfwd{N,M,Tuple{A}}) where {N,M,A<:AbstractArray} weightedmeasure(-logjac(d), OrthoLebesgue(params(d))) end @inline function basemeasure( d::MeasureTheory.AffinePushfwd{N,L,Tuple{A}}, ) where {N,L<:MeasureBase.Lebesgue,A<:AbstractArray} weightedmeasure(-logjac(d), OrthoLebesgue(params(d))) end @inline function basemeasure( d::AffinePushfwd{N,M,Tuple{A1,A2}}, ) where {N,M,A1<:AbstractArray,A2<:AbstractArray} weightedmeasure(-logjac(d), OrthoLebesgue(params(d))) end @inline basemeasure(d::AffinePushfwd) = affine(getfield(d, :f), basemeasure(d.parent)) # We can't do this until we know we're working with Lebesgue measure, since for # example it wouldn't make sense to apply a log-Jacobian to a point measure @inline function basemeasure(d::AffinePushfwd{N,L}) where {N,L<:Lebesgue} weightedmeasure(-logjac(d), d.parent) end @inline function basemeasure(d::AffinePushfwd{N,L}) where {N,L<:LebesgueBase} weightedmeasure(-logjac(d), d.parent) end logjac(d::AffinePushfwd) = logjac(getfield(d, :f)) function Random.rand!( rng::Random.AbstractRNG, d::AffinePushfwd, x::AbstractVector{T}, z = Vector{T}(undef, size(getfield(d, :f), 2)), ) where {T} rand!(rng, parent(d), z) f = getfield(d, :f) apply!(x, f, z) return x end # function Base.rand(rng::Random.AbstractRNG, ::Type{T}, d::AffinePushfwd) where {T} # f = getfield(d, :f) # z = rand(rng, T, parent(d)) # apply!(x, f, z) # return z # end supportdim(nt::NamedTuple{(:μ, :σ),T}) where {T} = colsize(nt.σ) supportdim(nt::NamedTuple{(:μ, :λ),T}) where {T} = rowsize(nt.λ) supportdim(nt::NamedTuple{(:σ,),T}) where {T} = colsize(nt.σ) supportdim(nt::NamedTuple{(:λ,),T}) where {T} = rowsize(nt.λ) supportdim(nt::NamedTuple{(:μ,),T}) where {T} = size(nt.μ) function Base.rand(rng::Random.AbstractRNG, ::Type{T}, d::AffinePushfwd) where {T} z = rand(rng, T, parent(d)) f = getfield(d, :f) return f(z) end @inline function insupport(d::AffinePushfwd, x) insupport(d.parent, inverse(d.f)(x)) end @inline function MeasureBase.smf(d::AffinePushfwd, x) smf(parent(d), inverse(d.f)(x)) end @inline function mean(d::AffinePushfwd) f = getfield(d, :f) f(mean(parent(d))) end @inline function std(d::AffinePushfwd{(:μ,)}) std(parent(d)) end @inline function std(d::AffinePushfwd{(:μ, :σ)}) d.σ * std(parent(d)) end @inline function std(d::AffinePushfwd{(:σ,)}) d.σ * std(parent(d)) end @inline function std(d::AffinePushfwd{(:λ,)}) std(parent(d)) / d.λ end @inline function std(d::AffinePushfwd{(:μ, :λ)}) std(parent(d)) / d.λ end ############################################################################### # smf @inline function smf(d::AffinePushfwd{(:μ,)}, x) f = getfield(d, :f) smf(parent(d), inverse(f)(x)) end @inline function smf(d::AffinePushfwd{(:μ, :σ)}, x) f = getfield(d, :f) p = smf(parent(d), inverse(f)(x)) d.σ > 0 ? p : one(p) - p end @inline function smf(d::AffinePushfwd{(:σ,)}, x) f = getfield(d, :f) p = smf(parent(d), inverse(f)(x)) d.σ > 0 ? p : one(p) - p end @inline function smf(d::AffinePushfwd{(:λ,)}, x) f = getfield(d, :f) p = smf(parent(d), inverse(f)(x)) d.λ > 0 ? p : one(p) - p end @inline function smf(d::AffinePushfwd{(:μ, :λ)}, x) f = getfield(d, :f) p = smf(parent(d), inverse(f)(x)) d.λ > 0 ? p : one(p) - p end ############################################################################### # invsmf @inline function invsmf(d::AffinePushfwd{(:μ,)}, p) f = getfield(d, :f) f(invsmf(parent(d), p)) end @inline function invsmf(d::AffinePushfwd{(:μ, :σ)}, p) p = d.σ > 0 ? p : one(p) - p f = getfield(d, :f) f(invsmf(parent(d), p)) end @inline function invsmf(d::AffinePushfwd{(:σ,)}, p) p = d.σ > 0 ? p : one(p) - p f = getfield(d, :f) f(invsmf(parent(d), p)) end @inline function invsmf(d::AffinePushfwd{(:λ,)}, p) p = d.λ > 0 ? p : one(p) - p f = getfield(d, :f) f(invsmf(parent(d), p)) end @inline function invsmf(d::AffinePushfwd{(:μ, :λ)}, p) p = d.λ > 0 ? p : one(p) - p f = getfield(d, :f) f(invsmf(parent(d), p)) end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
3596
using DynamicIterators import DynamicIterators: dub, dyniterate, evolve using Base.Iterators: SizeUnknown, IsInfinite export Chain struct Chain{K,M} <: AbstractMeasure κ::K μ::M end Pretty.quoteof(c::Chain) = :(Chain($(Pretty.quoteof(c.κ)), $(Pretty.quoteof(c.μ)))) Base.length(::Chain) = ∞ @inline function basemeasure(mc::Chain) Chain(basemeasure ∘ mc.κ, basemeasure(mc.μ)) end Base.IteratorEltype(mc::Chain) = Base.HasEltype() Base.eltype(::Type{C}) where {K,M,C<:Chain{K,M}} = eltype(M) @inline function logdensity_def(mc::Chain, x) μ = mc.μ ℓ = 0.0 for xj in x ℓ += logdensity_def(μ, xj) μ = mc.κ(xj) end return ℓ end DynamicIterators.evolve(mc::Chain, μ) = μ ⋅ mc.κ DynamicIterators.evolve(mc::Chain) = mc.μ dyniterate(E::Chain, value) = dub(evolve(E, value)) dyniterate(E::Chain, ::Nothing) = dub(evolve(E)) Base.iterate(E::Chain) = dyniterate(E, nothing) Base.iterate(E::Chain, value) = dyniterate(E, value) function DynamicIterators.dyniterate(r::Chain, (x, rng)::Sample) μ = r.κ(x) y = rand(rng, μ) return (μ ↝ y), Sample(y, rng) end Base.IteratorSize(::Chain) = IsInfinite() Base.IteratorSize(::Type{Chain}) = IsInfinite() function Base.rand(rng::AbstractRNG, T::Type, chain::Chain) r = ResettableRNG(rng) return RealizedSamples(r, chain) end ############################################################################### # DynamicFor # A `DynamicFor` is produced when `For` is called on a `DynamicIterator`. struct DynamicFor{T,K,S} <: AbstractMeasure κ::K iter::S end function Pretty.quoteof(r::DynamicFor) :(DynamicFor($(Pretty.quoteof(r.κ)), $(Pretty.quoteof(r.iter)))) end function DynamicFor(κ::K, iter::S) where {K,S} T = typeof(κ(first(iter))) DynamicFor{T,K,S}(κ, iter) end function Base.rand(rng::AbstractRNG, T::Type, df::DynamicFor) r = ResettableRNG(rng) return RealizedSamples(r, df) end @inline function logdensity_def(df::DynamicFor{M}, y::T) where {M,T} # ℓ = zero(float(Core.Compiler.return_type(logdensity_def, Tuple{M,T}))) ℓ = 0.0 for (xj, yj) in zip(df.iter, y) ℓ += logdensity_def(df.κ(xj), yj) end return ℓ end Base.eltype(::Type{D}) where {T,D<:DynamicFor{T}} = eltype(T) Base.IteratorEltype(d::DynamicFor) = Base.HasEltype() Base.IteratorSize(d::DynamicFor) = Base.IteratorSize(d.iter) function Base.iterate(d::DynamicFor) (x, s) = iterate(d.iter) (d.κ(x), s) end function Base.iterate(d::DynamicFor, s) (x, s) = iterate(d.iter, s) (d.κ(x), s) end Base.length(d::DynamicFor) = length(d.iter) For(f, r::Realized) = DynamicFor(f, copy(r)) function Base.rand(rng::AbstractRNG, dfor::DynamicFor) r = ResettableRNG(rng) return RealizedSamples(r, dfor) end function dyniterate(df::DynamicFor, st, args...) (val, state) = dyniterate(df.iter, st, args...) return (df.κ(val), state) end For(f, it::DynamicIterator) = DynamicFor(f, it) For(f, it::DynamicFor) = DynamicFor(f, it) function dyniterate(df::DynamicFor, state) ϕ = dyniterate(df.iter, state) ϕ === nothing && return nothing u, state = ϕ df.κ(u), state end function Base.collect(r::Realized) next = iterate(r) isnothing(next) && return [] (x, s) = next a = similar(r.iter, typeof(x)) i = 1 @inbounds a[i] = x while !isnothing(next) (x, s) = next @inbounds a[i] = x i += 1 next = iterate(r, s) end return a end function testvalue(mc::Chain) μ = mc.μ κ = mc.κ rand(Chain(Dirac ∘ testvalue ∘ κ, (Dirac ∘ testvalue)(μ))) end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git
[ "MIT" ]
0.19.0
923a7b76a9d4be260d4225db1703cd30472b60cc
code
8121
export For using Random import Base struct For{T,F,I} <: AbstractProductMeasure f::F inds::I @inline function For{T}(f::F, inds::I) where {T,F,I<:Tuple} new{T,Core.Typeof(f),I}(f, inds) end @inline For{T,F,I}(f::F, inds::I) where {T,F,I} = new{T,F,I}(f, inds) end @generated function For(f::F, inds::I) where {F,I<:Tuple} eltypes = Tuple{eltype.(I.types)...} quote $(Expr(:meta, :inline)) T = Core.Compiler.return_type(f, $eltypes) For{T,F,I}(f, inds) end end as(d::For) = as(Array, as(first(marginals(d))), size(first(d.inds))...) # For(f, gen::Base.Generator) = ProductMeasure(Base.Generator(f ∘ gen.f, gen.iter)) # @inline function tailcall_iter(f, iter) # iter_result::Tuple = iterate(iter) # (val, state) = iter_result # tailcall_iter(f, iter, (val, state)) # end # @inline function tailcall_iter(f, iter, ::Nothing) # return unit(f) # end # unit(+) = false # @inline function tailcall_iter(f, iter, (val, state)) # tailcall_iter(f, iter, (val, state), unit(f)) # end # @inline function tailcall_iter(f, iter, (val, state), acc) # tailcall_iter(f, iter, iterate(iter, state), f(val, acc)) # end # @inline function tailcall_iter(f, iter, ::Nothing, acc) # return acc # end # @inline function logdensity_def(d::For{T,F,I}, x::AbstractVector{X}; exec=SequentialEx(simd = true)) where {X,T,F,I<:Tuple{<:AbstractVector}} # f(j) = @inbounds logdensity_def(d.f(j), x[j]) # f(j, ℓ) = ℓ + @inbounds logdensity_def(d.f(j), x[j]) # tailcall_iter(f, eachindex(x)) # end @inline function logdensity_def( d::For{T,F,I}, x::AbstractVector{X}; ) where {X,T,F,I<:Tuple{<:AbstractVector}} ind = only(d.inds) sum(eachindex(x)) do j i = getindex(ind, j) @inbounds logdensity_def(d.f(i), x[j]) end end @inline function logdensity_def( d::For{T,F,I}, x::AbstractVector{X}; ) where {X,T,F,I<:Tuple{<:AbstractUnitRange}} ind = only(d.inds) Δj = firstindex(x) - first(ind) sum(ind) do j @inbounds logdensity_def(d.f(j), x[j+Δj]) end end function logdensity_def(d::For, x::AbstractVector) get_i(j) = map(Base.Fix2(getindex, j), d.inds) # get_i(j) = (getindex(ind, j) for ind in d.inds) # get_i(j) = tuple((getindex(ind, j) for ind in d.inds)...) sum(eachindex(x)) do j i = get_i(j) @inbounds logdensity_def(d.f(i...), x[j]) end end function marginals(d::For{T,F,Tuple{I}}) where {T,F,I} f = d.f data = first(d.inds) MappedArrays.ReadonlyMappedArray{T,ndims(data),typeof(data),typeof(f)}(f, data) end function marginals(d::For{T,F,I}) where {T,F,I} f = d.f data = d.inds MappedArrays.ReadonlyMultiMappedArray{T,ndims(first(data)),typeof(data),typeof(f)}( f, data, ) end function marginals(d::For{T,F,I}) where {N,T,F,I<:NTuple{N,<:Base.Generator}} Iterators.map(d.f, d.inds...) end function basemeasure(d::For{T,F,I}) where {T,F,I} B = typeof(basemeasure(d.f(map(first, d.inds)...))) sing = static(Base.issingletontype(B)) _basemeasure(d, B, sing) end @inline function _basemeasure( d::For{T,F,I}, ::Type{<:WeightedMeasure{StaticFloat64{0.0},B}}, ::True, ) where {T,F,I,B} dim = size(first(d.inds)) instance(B)^dim end @inline function _basemeasure( d::For{T,F,I}, ::Type{<:WeightedMeasure{StaticFloat64{N},B}}, ::True, ) where {T,F,I,N,B} dim = size(first(d.inds)) weightedmeasure(static(N) * prod(dim), instance(B)^dim) end @inline function _basemeasure( d::For{T,F,I}, ::Type{<:WeightedMeasure{StaticFloat64{N},B}}, ::False, ) where {T,F,I,N,B} dim = size(first(d.inds)) f(args...) = basemeasure(d.f(args...)).base base = For(f, d.inds...) weightedmeasure(static(N) * prod(dim), base) end @inline function _basemeasure(d::For{T,F,I}, ::Type{B}, ::True) where {T,F,I,B} instance(B)^size(first(d.inds)) end @inline function _basemeasure( d::For{T,F,I}, ::Type{B}, ::False, ) where {T,F,I,B<:AbstractMeasure} f = basekernel(d.f) For{B}(f, d.inds) end @inline function _basemeasure(d::For{T,F,I}, ::Type{B}, ::False) where {T,F,I,B} MeasureBase.productmeasure(basemeasure.(marginals(d))) end function _basemeasure( d::For{T,F,I}, ::Type{B}, ::True, ) where {N,T<:AbstractMeasure,F,I<:NTuple{N,<:Base.Generator},B} return instance(B)^minimum(length, d.inds) end function _basemeasure( d::For{T,F,I}, ::Type{B}, ::False, ) where {N,T<:AbstractMeasure,F,I<:NTuple{N,<:Base.Generator},B} f = basekernel(d.f) For{B}(f, d.inds) end function Pretty.tile(d::For{T}) where {T} result = Pretty.literal("For{") result *= Pretty.tile(T) result *= Pretty.literal("}") result *= Pretty.list_layout([ Pretty.literal(func_string(d.f, Tuple{_eltype.(d.inds)...})), Pretty.literal(sprint(show, d.inds; context = :compact => true)), ]) end """ For(f, base...) `For` provides a convenient way to construct a `ProductMeasure`. There are several options for the `base`. With Julia's `do` notation, this can look very similar to a standard `for` loop, while maintaining semantics structure that's easier to work with. ------------ # `For(f, base::Int...)` When one or several `Int` values are passed for `base`, the result is treated as depending on `CartesianIndices(base)`. ``` julia> For(3) do λ Exponential(λ) end |> marginals 3-element mappedarray(MeasureBase.var"#17#18"{var"#15#16"}(var"#15#16"()), ::CartesianIndices{1, Tuple{Base.OneTo{Int64}}}) with eltype Exponential{(:λ,), Tuple{Int64}}: Exponential(λ = 1,) Exponential(λ = 2,) Exponential(λ = 3,) ``` ``` julia> For(4,3) do μ,σ Normal(μ,σ) end |> marginals 4×3 mappedarray(MeasureBase.var"#17#18"{var"#11#12"}(var"#11#12"()), ::CartesianIndices{2, Tuple{Base.OneTo{Int64}, Base.OneTo{Int64}}}) with eltype Normal{(:μ, :σ), Tuple{Int64, Int64}}: Normal(μ = 1, σ = 1) Normal(μ = 1, σ = 2) Normal(μ = 1, σ = 3) Normal(μ = 2, σ = 1) Normal(μ = 2, σ = 2) Normal(μ = 2, σ = 3) Normal(μ = 3, σ = 1) Normal(μ = 3, σ = 2) Normal(μ = 3, σ = 3) Normal(μ = 4, σ = 1) Normal(μ = 4, σ = 2) Normal(μ = 4, σ = 3) ``` ------- # `For(f, base::AbstractArray...)`` In this case, `base` behaves as if the arrays are `zip`ped together before applying the map. ``` julia> For(randn(3)) do x Exponential(x) end |> marginals 3-element mappedarray(x->Main.Exponential(x), ::Vector{Float64}) with eltype Exponential{(:λ,), Tuple{Float64}}: Exponential(λ = -0.268256,) Exponential(λ = 1.53044,) Exponential(λ = -1.08839,) ``` ``` julia> For(1:3, 1:3) do μ,σ Normal(μ,σ) end |> marginals 3-element mappedarray((:μ, :σ)->Main.Normal(μ, σ), ::UnitRange{Int64}, ::UnitRange{Int64}) with eltype Normal{(:μ, :σ), Tuple{Int64, Int64}}: Normal(μ = 1, σ = 1) Normal(μ = 2, σ = 2) Normal(μ = 3, σ = 3) ``` ---- # `For(f, base::Base.Generator)` For `Generator`s, the function maps over the values of the generator: ``` julia> For(eachrow(rand(4,2))) do x Normal(x[1], x[2]) end |> marginals |> collect 4-element Vector{Normal{(:μ, :σ), Tuple{Float64, Float64}}}: Normal(μ = 0.255024, σ = 0.570142) Normal(μ = 0.970706, σ = 0.0776745) Normal(μ = 0.731491, σ = 0.505837) Normal(μ = 0.563112, σ = 0.98307) ``` """ @inline For{T}(f, inds...) where {T} = For{T}(f, inds) @inline For{T}(f, n::Integer) where {T} = For{T}(f, static(1):n) @inline function For{T}(f, inds::Integer...) where {T} For{T}(i -> f(Tuple(i)...), Base.CartesianIndices(inds)) end @inline For(f, inds...) = For(f, inds) @inline For(f, n::Integer) = For(f, static(1):n) @inline For(f, inds::Integer...) = For(i -> f(Tuple(i)...), Base.CartesianIndices(inds)) # For(f, inds::Base.Generator) = productmeasure(mymap(f, inds)) function Random.rand!(rng::AbstractRNG, d::For{T,F,I}, x) where {T,F,I} mar = marginals(d) @inbounds for (j, dⱼ) in enumerate(mar) x[j] = rand(rng, dⱼ) end return x end function Base.rand(rng::AbstractRNG, ::Type{T}, d::For{M,F,I}) where {T,M,F,I} MeasureBase._rand_product(rng, T, marginals(d), M) end
MeasureTheory
https://github.com/JuliaMath/MeasureTheory.jl.git