content stringlengths 6 1.03M | input_ids sequencelengths 4 535k | ratio_char_token float64 0.68 8.61 | token_count int64 4 535k |
|---|---|---|---|
struct InterfaceOperators
operators::Any
celltooperator::Any
ncells::Any
numoperators::Any
function InterfaceOperators(operators, celltooperator)
ncells = length(celltooperator)
numcouples, numoperators = size(operators)
@assert numcouples == 4
@assert all(celltooperator .>= 0)
@assert all(celltooperator .<= numoperators)
new(operators, celltooperator, ncells, numoperators)
end
end
function Base.getindex(interfaceoperator::InterfaceOperators, s1, s2, cellid)
row = cell_couple_sign_to_row(s1, s2)
idx = interfaceoperator.celltooperator[cellid]
idx > 0 || error("Cell $cellid does not have an operator")
return interfaceoperator.operators[row, idx]
end
function Base.show(io::IO, interfaceoperator::InterfaceOperators)
ncells = number_of_cells(interfaceoperator)
nops = number_of_operators(interfaceoperator)
str = "InterfaceOperator\n\tNum. Cells: $ncells\n\tNum. Operators: $nops"
print(io, str)
end
function number_of_cells(interfaceoperator::InterfaceOperators)
return interfaceoperator.ncells
end
function number_of_operators(interfaceoperator::InterfaceOperators)
return interfaceoperator.numoperators
end
function interface_mass_operators(basis, interfacequads, cellmap, cellsign, penalty)
ncells = length(cellsign)
hasinterface = cellsign .== 0
numinterfaces = count(hasinterface)
operators = Matrix{Any}(undef, 4, numinterfaces)
celltooperator = zeros(Int, ncells)
dim = dimension(basis)
cellids = findall(hasinterface)
for (idx, cellid) in enumerate(cellids)
normal = interface_normals(interfacequads, cellid)
facescale = scale_area(cellmap, normal)
for s1 in [+1, -1]
quad1 = interfacequads[s1, cellid]
for s2 in [+1, -1]
row = cell_couple_sign_to_row(s1, s2)
quad2 = interfacequads[s2, cellid]
mass = penalty * interface_mass_matrix(basis, quad1, quad2, facescale)
operators[row, idx] = mass
end
end
celltooperator[cellid] = idx
end
return InterfaceOperators(operators, celltooperator)
end
function interface_mass_operators(basis, interfacequads, cutmesh, penalty)
cellmap = cell_map(cutmesh, 1)
cellsign = cell_sign(cutmesh)
return interface_mass_operators(basis, interfacequads, cellmap, cellsign, penalty)
end
function interface_incoherent_mass_operators(
basis,
interfacequads,
cellmap,
cellsign,
penalty,
)
ncells = length(cellsign)
hasinterface = cellsign .== 0
numinterfaces = count(hasinterface)
operators = Matrix{Any}(undef, 4, numinterfaces)
celltooperator = zeros(Int, ncells)
dim = dimension(basis)
cellids = findall(hasinterface)
for (idx, cellid) in enumerate(cellids)
normal = interface_normals(interfacequads, cellid)
components = normal
facescale = scale_area(cellmap, normal)
for s1 in [+1, -1]
quad1 = interfacequads[s1, cellid]
for s2 in [+1, -1]
row = cell_couple_sign_to_row(s1, s2)
quad2 = interfacequads[s2, cellid]
mass =
penalty * interface_component_mass_matrix(
basis,
quad1,
quad2,
components,
facescale,
)
operators[row, idx] = mass
end
end
celltooperator[cellid] = idx
end
return InterfaceOperators(operators, celltooperator)
end
function interface_incoherent_mass_operators(basis, interfacequads, cutmesh, penalty)
cellmap = cell_map(cutmesh, 1)
cellsign = cell_sign(cutmesh)
return interface_incoherent_mass_operators(
basis,
interfacequads,
cellmap,
cellsign,
penalty,
)
end
function interface_traction_operators(basis, interfacequads, stiffness, cellmap, cellsign)
ncells = length(cellsign)
hasinterface = cellsign .== 0
numinterfaces = count(hasinterface)
operators = Matrix{Any}(undef, 4, numinterfaces)
celltooperator = zeros(Int, ncells)
cellids = findall(hasinterface)
for (idx, cellid) in enumerate(cellids)
normal = interface_normals(interfacequads, cellid)
for s1 in [+1, -1]
quad1 = interfacequads[s1, cellid]
for s2 in [+1, -1]
row = cell_couple_sign_to_row(s1, s2)
quad2 = interfacequads[s2, cellid]
top = coherent_traction_operator(
basis,
quad1,
quad2,
normal,
stiffness[s2],
cellmap,
)
operators[row, idx] = top
end
end
celltooperator[cellid] = idx
end
return InterfaceOperators(operators, celltooperator)
end
function interface_traction_operators(basis, interfacequads, stiffness, cutmesh)
cellmap = cell_map(cutmesh, 1)
cellsign = cell_sign(cutmesh)
return interface_traction_operators(basis, interfacequads, stiffness, cellmap, cellsign)
end
function interface_incoherent_traction_operators(basis, interfacequads, stiffness, cutmesh)
cellsign = cell_sign(cutmesh)
cellmap = cell_map(cutmesh, 1)
ncells = length(cellsign)
hasinterface = cellsign .== 0
numinterfaces = count(hasinterface)
operators = Matrix{Any}(undef, 4, numinterfaces)
celltooperator = zeros(Int, ncells)
cellids = findall(hasinterface)
for (idx, cellid) in enumerate(cellids)
normals = interface_normals(interfacequads, cellid)
for s1 in [+1, -1]
quad1 = interfacequads[s1, cellid]
for s2 in [+1, -1]
row = cell_couple_sign_to_row(s1, s2)
quad2 = interfacequads[s2, cellid]
top = incoherent_traction_operator(
basis,
quad1,
quad2,
normals,
stiffness[s2],
cellmap,
)
operators[row, idx] = top
end
end
celltooperator[cellid] = idx
end
return InterfaceOperators(operators, celltooperator)
end
struct InterfaceCondition
tractionoperator::Any
massoperator::Any
penalty::Any
ncells::Any
function InterfaceCondition(
tractionoperator::InterfaceOperators,
massoperator::InterfaceOperators,
penalty,
)
ncells = number_of_cells(massoperator)
@assert number_of_cells(tractionoperator) == ncells
new(tractionoperator, massoperator, penalty, ncells)
end
end
function coherent_interface_condition(basis, interfacequads, stiffness, cutmesh, penalty)
tractionoperator =
interface_traction_operators(basis, interfacequads, stiffness, cutmesh)
massoperator = interface_mass_operators(basis, interfacequads, cutmesh, penalty)
return InterfaceCondition(tractionoperator, massoperator, penalty)
end
function incoherent_interface_condition(basis, interfacequads, stiffness, cutmesh, penalty)
tractionoperator =
interface_incoherent_traction_operators(basis, interfacequads, stiffness, cutmesh)
massoperator =
interface_incoherent_mass_operators(basis, interfacequads, cutmesh, penalty)
return InterfaceCondition(tractionoperator, massoperator, penalty)
end
function traction_operator(interfacecondition::InterfaceCondition, s1, s2, cellid)
return interfacecondition.tractionoperator[s1, s2, cellid]
end
function mass_operator(interfacecondition::InterfaceCondition, s1, s2, cellid)
return interfacecondition.massoperator[s1, s2, cellid]
end
function Base.show(io::IO, interfacecondition::InterfaceCondition)
ncells = interfacecondition.ncells
penalty = interfacecondition.penalty
str = "InterfaceCondition\n\tNum. Cells: $ncells\n\tDisplacement Penalty: $penalty"
print(io, str)
end
function coherent_traction_operator(basis, quad1, quad2, normals, stiffness, cellmap)
numqp = length(quad1)
@assert length(quad2) == size(normals)[2] == numqp
dim = dimension(basis)
nf = number_of_basis_functions(basis)
ndofs = dim * nf
matrix = zeros(ndofs, ndofs)
vectosymmconverter = vector_to_symmetric_matrix_converter()
jac = jacobian(cellmap)
scalearea = scale_area(cellmap, normals)
for qpidx = 1:numqp
p1, w1 = quad1[qpidx]
p2, w2 = quad2[qpidx]
@assert w1 ≈ w2
vals = basis(p1)
grad = transform_gradient(gradient(basis, p2), jac)
normal = normals[:, qpidx]
NK = sum([make_row_matrix(vectosymmconverter[k], grad[:, k]) for k = 1:dim])
N = sum([normal[k] * vectosymmconverter[k]' for k = 1:dim])
NI = interpolation_matrix(vals, dim)
matrix .+= NI' * N * stiffness * NK * scalearea[qpidx] * w1
end
return matrix
end
function component_traction_operator(
basis,
quad1,
quad2,
components,
normals,
stiffness,
cellmap,
)
numqp = length(quad1)
@assert length(quad2) == size(normals)[2] == size(components)[2] == numqp
dim = dimension(basis)
nf = number_of_basis_functions(basis)
ndofs = dim * nf
matrix = zeros(ndofs, ndofs)
vectosymmconverter = vector_to_symmetric_matrix_converter()
jac = jacobian(cellmap)
scalearea = scale_area(cellmap, normals)
for qpidx = 1:numqp
p1, w1 = quad1[qpidx]
p2, w2 = quad2[qpidx]
@assert w1 ≈ w2
vals = basis(p1)
grad = transform_gradient(gradient(basis, p2), jac)
normal = normals[:, qpidx]
component = components[:, qpidx]
projector = component * component'
NK = sum([make_row_matrix(vectosymmconverter[k], grad[:, k]) for k = 1:dim])
N = sum([normal[k] * vectosymmconverter[k]' for k = 1:dim])
NI = interpolation_matrix(vals, dim)
matrix .+= NI' * projector * N * stiffness * NK * scalearea[qpidx] * w1
end
return matrix
end
function incoherent_traction_operator(basis, quad1, quad2, normals, stiffness, cellmap)
components = normals
return component_traction_operator(
basis,
quad1,
quad2,
components,
normals,
stiffness,
cellmap,
)
end
function interface_mass_matrix(basis, quad1, quad2, scale)
numqp = length(quad1)
@assert length(quad2) == length(scale) == numqp
nf = number_of_basis_functions(basis)
dim = dimension(basis)
totaldofs = dim * nf
matrix = zeros(totaldofs, totaldofs)
for qpidx = 1:numqp
p1, w1 = quad1[qpidx]
p2, w2 = quad2[qpidx]
@assert w1 ≈ w2
vals1 = basis(p1)
vals2 = basis(p2)
NI1 = interpolation_matrix(vals1, dim)
NI2 = interpolation_matrix(vals2, dim)
matrix .+= NI1' * NI2 * scale[qpidx] * w1
end
return matrix
end
function interface_component_mass_matrix(basis, quad1, quad2, components, scale)
numqp = length(quad1)
@assert length(quad2) == length(scale) == size(components)[2] == numqp
nf = number_of_basis_functions(basis)
dim = dimension(basis)
totaldofs = dim * nf
matrix = zeros(totaldofs, totaldofs)
for qpidx = 1:numqp
p1, w1 = quad1[qpidx]
p2, w2 = quad2[qpidx]
@assert w1 ≈ w2
component = components[:, qpidx]
projector = component * component'
vals1 = basis(p1)
vals2 = basis(p2)
NI1 = interpolation_matrix(vals1, dim)
NI2 = make_row_matrix(projector, vals2)
matrix .+= NI1' * NI2 * scale[qpidx] * w1
end
return matrix
end
| [
7249,
26491,
18843,
2024,
198,
220,
220,
220,
12879,
3712,
7149,
198,
220,
220,
220,
2685,
1462,
46616,
3712,
7149,
198,
220,
220,
220,
299,
46342,
3712,
7149,
198,
220,
220,
220,
997,
3575,
2024,
3712,
7149,
198,
220,
220,
220,
2163,... | 2.233685 | 5,302 |
# Script
using Distributions, PyPlot, BayesianNonparametricStatistics
β=0.5
θ = sumoffunctions(vcat([faberschauderone],[faberschauder(j,k) for j in 0:4 for k in 1:2^j]),vcat([1.0],[(-1)^(j*k)*2^(-β*j) for j in 0:4 for k in 1:2^j]))
x = 0.0:0.001:1.0
y = θ.(x)
# Uncomment the following lines to plot θ.
# clf()
# plot(x,y)
sde = SDEWithConstantVariance(θ, 1.0, 0.0, 1000.0, 0.01)
X = rand(sde)
# Uncomment the following lines to plot a sample from sde.
# clf()
# plot(X)
M = SDEModel(1.0, 0.0)
Π = FaberSchauderExpansionWithGaussianCoefficients([2^(β*j) for j in 0:4])
postΠ = calculateposterior(Π, X, M )
for k in 1:100
f = rand(postΠ)
y = f.(x)
plot(x,y)
end
| [
2,
12327,
198,
198,
3500,
46567,
507,
11,
9485,
43328,
11,
4696,
35610,
15419,
17143,
19482,
48346,
198,
198,
26638,
28,
15,
13,
20,
198,
138,
116,
796,
2160,
2364,
46797,
7,
85,
9246,
26933,
36434,
364,
354,
29233,
505,
38430,
36434,... | 2.063253 | 332 |
<reponame>JuliaPackageMirrors/Seismic.jl<filename>src/Wavelets/Berlage.jl<gh_stars>0
"""
Berlage(; <keyword arguments>)
Create a Berlage wavelet.
# Arguments
**Keyword arguments**
* `dt::Real=0.002`: sampling interval in secs.
* `f0::Real=20.0`: central frequency in Hz.
* `m::Real=2`: exponential parameter of Berlage wavelet.
* `alpha::Real=180.0`: alpha parameter of Berlage wavelet in rad/secs.
* `phi0::Real`: phase rotation in radians.
# Example
```julia
julia> w = Berlage(); plot(w);
```
**Reference**
* Aldridge, <NAME>., 1990, The berlage wavelet: GEOPHYSICS, 55, 1508--1511.
"""
function Berlage(; dt::Real=0.002, f0::Real=20.0, m::Real=2, alpha::Real=180.0,
phi0::Real=0.0)
nw = floor(Int, 2.2/(f0*dt))
t = dt*collect(0:1:nw-1)
w = (t.^m).*exp(-alpha*t).*cos(2*pi*f0*t + phi0);
w = w/maximum(w)
end
| [
27,
7856,
261,
480,
29,
16980,
544,
27813,
27453,
5965,
14,
4653,
1042,
291,
13,
20362,
27,
34345,
29,
10677,
14,
39709,
5289,
14,
24814,
75,
496,
13,
20362,
27,
456,
62,
30783,
29,
15,
198,
37811,
198,
220,
220,
220,
4312,
75,
49... | 2.171285 | 397 |
struct Lennnon2000Air <: ThermoState.ThermoModel end
const TAU_MAX_EXP_87 = 0.4207493606569795
const lemmon2000_air_R = 8.314510
const lemmon2000_air_T_reducing = 132.6312
const lemmon2000_air_P_reducing = 3.78502E6
const lemmon2000_air_rho_reducing = 10447.7
const lemmon2000_air_rho_reducing_inv = 1.0/lemmon2000_air_rho_reducing
const lemmon2000_air_MW = 28.9586
const lemmon2000_air_P_max = 2000E6
const lemmon2000_air_T_max = 2000.
molecular_weight(::Lennnon2000Air) = lemmon2000_air_MW
function _f0(::Lennnon2000Air, delta,tau)
tau_inv = one(tau)/tau
A0 = (-0.00019536342*tau*sqrt(tau) + 17.275266575*tau + tau_inv*(tau_inv*(6.057194e-8*tau_inv
- 0.0000210274769) - 0.000158860716) + log(delta) + 2.490888032*log(tau)
# These two logs both fail for tau < 1e-18, can be truncated but should not be necessary.
+ 0.791309509*log(1.0 - exp(-25.36365*tau)) + 0.212236768*log(1.0 - exp(-16.90741*tau))
- 13.841928076)
if tau < TAU_MAX_EXP_87
A0 -= 0.197938904*log(exp(87.31279*tau) + (2.0/3.0))
else
A0 -= 17.282597957782162*tau # 17.282... = 87.31279*0.197938904
return A0
end
end
function _fr(::Lennnon2000Air,delta,tau)
delta2 = delta*delta
delta3 = delta*delta2
delta4 = delta2*delta2
delta5 = delta*delta4
delta6 = delta2*delta4
taurt2 = sqrt(tau)
taurt4 = sqrt(taurt2)
tau2 = tau*tau
tau3 = tau*tau2
tau6 = tau3*tau3
tau12 = tau6*tau6
tau_100 = tau^0.01
tau2_100 = tau_100*tau_100
tau4_100 = tau2_100*tau2_100
tau5_100 = tau_100*tau4_100
tau10_100 = tau5_100*tau5_100
tau15_100 = tau5_100*tau10_100
tau8_100 = tau4_100*tau4_100
tau16_100 = tau8_100*tau8_100
tau20_100 = tau4_100*tau16_100
tau32_100 = tau16_100*tau16_100
tau33_100 = tau_100*tau32_100
tau64_100 = tau32_100*tau32_100
tau80_100 = tau16_100*tau64_100
tau40_100 = tau20_100*tau20_100
tau97_100 = tau33_100*tau64_100
tau45_100 = tau5_100*tau40_100
tau90_100 = tau45_100*tau45_100
tau160_100 = tau80_100*tau80_100
tau320_100 = tau160_100*tau160_100
x0 = exp(-delta)
x1 = exp(-delta2)
x2 = tau3*exp(-delta3)
return (-0.101365037911999994*delta*tau160_100*x0 + 0.713116392079000017*delta*tau33_100
- 0.146629609712999986*delta*tau40_100*x1*tau320_100
- 1.61824192067000006*delta*tau4_100*tau97_100 + 0.0148287891978000005*delta*taurt2*x2
+ 0.118160747228999996*delta + 0.0714140178971000017*delta2 + 0.134211176704000013*delta3*tau15_100
- 0.031605587982100003*delta3*tau6*x1 - 0.17381369096999999*delta3*tau80_100*x0
- 0.00938782884667000057*delta3*x2*tau12 - 0.0865421396646000041*delta3 - 0.042053322884200002*delta4*tau20_100
+ 0.0349008431981999989*delta4*tau2_100*tau33_100 + 0.0112626704218000001*delta4
- 0.0472103183731000034*delta5*tau15_100*x0*tau80_100 + 0.000233594806141999996*delta5*tau3*taurt4*x1*delta6
- 0.0122523554252999996*delta6*tau*taurt4*x0 + 0.000164957183186000006*delta6*tau45_100*tau90_100)
end
function αR_impl(mt::SingleVT,::Lennnon2000Air, _rho, T)
R = lemmon2000_air_R
delta = rho*lemmon2000_air_rho_reducing_inv
tau = lemmon2000_air_T_reducing/T
return _fr(model, delta, tau)
end
function α0_impl(mt::SingleVT,::Lennnon2000Air, _rho, T)
R = lemmon2000_air_R
delta = rho*lemmon2000_air_rho_reducing_inv
tau = lemmon2000_air_T_reducing/T
return _f0(model, delta, tau)
end
function mol_helmholtzR_impl(mt::SingleVT,::Lennnon2000Air, v, t)
rho = 1.0e-3 / v
R = lemmon2000_air_R
delta = lemmon2000_air_rho_reducing_inv/v
tau = lemmon2000_air_T_reducing/T
return R*t*_fr(model, delta, tau)
end
function mol_helmholtz0_impl(mt::SingleVT,::Lennnon2000Air, v, t)
rho = 1.0e-3 / v
R = lemmon2000_air_R
delta = lemmon2000_air_rho_reducing_inv/v
tau = lemmon2000_air_T_reducing/T
return R*t*_f0(model, delta, tau)
end
function mol_helmholtz_impl(mt::SingleVT,::Lennnon2000Air, v, t)
rho = 1.0e-3 / v
R = lemmon2000_air_R
delta = lemmon2000_air_rho_reducing_inv/v
tau = lemmon2000_air_T_reducing/T
return R*t*(_f0(model, delta, tau)+_fr(model, delta, tau))
end
| [
7249,
28423,
13159,
11024,
16170,
1279,
25,
12634,
5908,
9012,
13,
35048,
5908,
17633,
886,
198,
9979,
21664,
52,
62,
22921,
62,
49864,
62,
5774,
796,
657,
13,
19,
22745,
2920,
15277,
2996,
3388,
41544,
198,
9979,
443,
76,
2144,
11024,
... | 1.861965 | 2,311 |
<gh_stars>1-10
export SingleLayer
"""
singleLayer
σ(K*s+b)
where K,b are trainable weights
"""
struct SingleLayer
end
mσ(x::AbstractArray{R}) where R<:Real = abs.(x)+log.(R(1) .+ exp.(-R(2)*abs.(x)))
mdσ(x::AbstractArray{R}) where R<:Real = tanh.(x)
md2σ(x::AbstractArray{R}) where R<:Real = one(eltype(x)) .- tanh.(x).^2
"""
evaluate layer for current weights Θ=(K,b)
"""
function (N::SingleLayer)(S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(K,b) = Θ
return mσ(K*S .+ b)
end
"""
compute matvec J_S N(S,Θ)'*Z
"""
function getJSTmv(N::SingleLayer,Z::AbstractArray{R},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(K,b) = Θ
return K'*(mdσ(K*S .+ b) .* Z)
end
function getJSTmv(N::SingleLayer,Z::AbstractArray{R,3},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
t1 = reshape(mdσ(K*S .+ b),size(K,1),1,nex)
t2 = K'*reshape(t1 .* Z, size(K,1),:)
return reshape(t2,size(K,2),size(Z,2),nex)
end
"""
compute hessian matvec
"""
function getTraceHessAndGrad(N::SingleLayer, w::AbstractArray{R},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
t1 = K*S .+ b
Jac = reshape(mdσ(t1),size(K,1),1,nex) .* K
return vec(sum(reshape(md2σ(t1) .* w,size(K,1),:,nex).*(K.^2),dims=(1,2))), Jac
end
function getTraceHessAndGrad(N::SingleLayer, w::AbstractArray{R},Jac::AbstractArray{R,2},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
t1 = K*S .+ b;
Jac = K * Jac
trH = vec(sum(reshape(md2σ(t1) .* w,size(K,1),:,nex).*(Jac).^2,dims=(1,2)))
Jac = reshape(mdσ(t1),size(K,1),1,nex) .* Jac
return trH,Jac
end
function getTraceHessAndGrad(N::SingleLayer, w::AbstractArray{R},Jac::AbstractArray{R,3},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
t1 = K*S .+ b;
Jac = reshape(K* reshape(Jac,size(K,2),:), size(K,1),:,nex)
trH = vec(sum(reshape(md2σ(t1) .* w,size(K,1),:,nex).*(Jac).^2,dims=(1,2)))
Jac = reshape(mdσ(t1),size(K,1),1,nex) .* Jac
return trH,Jac
end
function getTraceHess(N::SingleLayer, w::AbstractArray{R},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
t1 = K*S .+ b
return vec(sum(reshape(md2σ(t1) .* w,size(K,1),:,nex).*(K.^2),dims=(1,2)))
end
function getTraceHess(N::SingleLayer, w::AbstractArray{R},Jac::AbstractArray{R,2},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
t1 = K*S .+ b;
Jac = K * Jac
trH = vec(sum(reshape(md2σ(t1) .* w,size(K,1),:,nex).*(Jac).^2,dims=(1,2)))
return trH
end
function getTraceHess(N::SingleLayer, w::AbstractArray{R},Jac::AbstractArray{R,3},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
t1 = K*S .+ b;
Jac = reshape(K* reshape(Jac,size(K,2),:), size(K,1),:,nex)
trH = vec(sum(reshape(md2σ(t1) .* w,size(K,1),:,nex).*(Jac).^2,dims=(1,2)))
return trH
end
function getDiagHess(N::SingleLayer, w::AbstractArray{R}, Z::AbstractArray{R},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
return sum((md2σ(K*S .+ b) .* w).*(K*Z).^2,dims=1)
end
function getHessmv(N::SingleLayer, w::AbstractArray{R}, Z::AbstractArray{R},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
return K'*(md2σ(K*S .+ b) .* w .* (K*Z))
end
function getHessmv(N::SingleLayer, w::AbstractArray{R}, Z::AbstractArray{R,3},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
t1 = reshape(md2σ(K*S .+ b).*w,size(K,1),1,nex)
t2 = t1 .* reshape(K*reshape(Z,size(K,2),:),size(K,1),:,nex)
t2 = K'* reshape(t2,size(K,1),:)
return reshape(t2,size(K,2),size(Z,2),nex)
end
"""
compute matvec J_S N(S,Θ)*Z
"""
function getJSmv(N::SingleLayer,Z::AbstractArray{R},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(K,b) = Θ
return mdσ(K*S .+ b) .* (K * Z)
end
"""
compute matvec J_S N(S,Θ)*Z
"""
function getJSmv(N::SingleLayer,Z::AbstractArray{R,3},S::AbstractArray{R,2},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
# K * Z
KZ = K*reshape(Z,size(K,2),:)
return reshape(mdσ(K*S .+ b),size(K,1),1,nex) .* reshape(KZ,size(K,1),size(Z,2),nex)
end
"""
compute matvec J_S(J_S N(S,Θ)'*Z(S))
here we use product rule
J_S N(S,Θ)'*dZ + J_S(N(S,Θ)'*Zfix)
"""
function getJSJSTmv(N::SingleLayer,dz::AbstractVector{R},d2z::AbstractArray{R},s::AbstractVector{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(K,b) = Θ
t1 = K*s + b
ndσ = mdσ(t1)
return K'* ( Diagonal(md2σ(t1) .* dz) +
ndσ .* d2z .* ndσ') *K
end
function getJSJSTmv(N::SingleLayer,dZ::AbstractArray{R},d2Z::AbstractArray{R},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(K,b) = Θ
t1 = K* S .+ b
(d,nex) = size(t1)
H1 = getJSJSTmv(N,dZ,S,Θ)
t2 = mdσ(t1)
H2 = reshape(t2,d,1,:) .* d2Z .* reshape(t2,1,d,:)
s1 = K' * reshape(H2,size(K,1),:)
s1 = permutedims(reshape(s1,size(K,2),size(K,1),nex),(2,1,3))
s2 = K'*reshape(s1,size(K,1),:)
return H1 + permutedims(reshape(s2,size(K,2),size(K,2),nex),(2,1,3))
end
function getJSJSTmv(N::SingleLayer,dZ::AbstractArray{R},S::AbstractArray{R,2},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R<:Real
(K,b) = Θ
t1 = K* S .+ b
(d,nex) = size(t1)
dZ2 = reshape(dZ .* md2σ(t1),size(dZ,1),1,nex)
KtdZK = K'*reshape(dZ2.*K,size(K,1),:)
return reshape(KtdZK,size(K,2),size(K,2),nex)
end
function getGradAndHessian(N::SingleLayer,dZ::AbstractArray{R},S::AbstractArray{R,2},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R<:Real
# Here, no d2Z is give, so we assume it is zero
(K,b) = Θ
t1 = K* S .+ b
(d,nex) = size(t1)
t2 = reshape(dZ .* md2σ(t1),size(dZ,1),1,nex)
KtdZK = K'*reshape(t2.*K,size(K,1),:)
H = reshape(KtdZK,size(K,2),size(K,2),nex)
return K'*(mdσ(t1) .* dZ),H
end
function getGradAndHessian(N::SingleLayer,dZ::AbstractArray{R},d2Z::AbstractArray{R},S::AbstractArray{R},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(K,b) = Θ
t1 = K * S .+ b
(d,nex) = size(t1)
t2 = reshape(dZ .* md2σ(t1),size(dZ,1),1,nex)
KtdZK = K'*reshape(t2.*K,size(K,1),:)
H1 = reshape(KtdZK,size(K,2),size(K,2),nex)
dσt = mdσ(t1)
t3 = reshape(dσt,d,1,:) .* d2Z .* reshape(dσt,1,d,:)
s1 = K' * reshape(t3,size(K,1),:)
s1 = permutedims(reshape(s1,size(K,2),size(K,1),nex),(2,1,3))
s2 = K'*reshape(s1,size(K,1),:)
H2 = permutedims(reshape(s2,size(K,2),size(K,2),nex),(2,1,3))
return K'*(dσt .* dZ), H1+H2
end
function getJSJSTmv(N::SingleLayer,d2Z::AbstractArray{R,3},S::AbstractArray{R,2},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}}) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
# K * Z
t1 = reshape(mdσ(K*S .+ b),size(K,1),1,nex)
t1 = K'*reshape(t1 .* d2Z, size(K,1),:)
t1 = reshape(t1,size(K,2),size(d2Z,2),nex)
permutedims!(t1,t1,(2,1,3))
t1 = K'*reshape(t1 .* d2Z, size(K,1),:)
t1 = reshape(t1,size(K,2),size(d2Z,2),nex)
return t1
end
function getJSJSTmv(N::SingleLayer,d2Z::AbstractArray{R,3},S::AbstractArray{R,2},Θ::Tuple{AbstractArray{R,2},AbstractArray{R,1}},hk::R) where R <: Real
(d,nex) = size(S)
(K,b) = Θ
# K * Z
t1 = reshape(mdσ(K*S .+ b),size(K,1),1,nex)
t1 = K'*reshape(t1 .* d2Z, size(K,1),:)
t1 = d2Z + hk .* reshape(t1,size(K,2),size(d2Z,2),nex)
permutedims!(t1,t1,(2,1,3))
t1 = K'*reshape(t1 .* d2Z, size(K,1),:)
t1 = d2Z + hk .* reshape(t1,size(K,2),size(d2Z,2),nex)
return t1
end
| [
27,
456,
62,
30783,
29,
16,
12,
940,
198,
39344,
14206,
49925,
198,
198,
37811,
198,
29762,
49925,
198,
198,
38392,
7,
42,
9,
82,
10,
65,
8,
198,
198,
3003,
509,
11,
65,
389,
4512,
540,
19590,
198,
198,
37811,
198,
7249,
14206,
... | 1.906438 | 4,318 |
"""
parseFunctionNode(nodeDict::Dict)
Parses a [`FunctionNode`](@ref) from a node set configuration file.
"""
function parseFunctionNode(nodeDict::Dict)
func = get(nodeDict, "function", false)
if func == false
error("function field is not set in FunctionNode")
else
aux = 0
try
aux = eval(Meta.parse(func))
catch e
error("The following function: '$func' in FunctionNode is not defined")
end
if typeof(aux) <: Function
func = aux
else
error("The following function: '$func' in FunctionNode is not a function")
end
end
arity = get(nodeDict, "arity", false)
if arity == false
error("arity field is not set in FunctionNode: '$func'")
else
if !(typeof(arity) <: Integer)
error("arity field ($arity) in FunctionNode '$func' must be an integer number")
elseif arity <= 0
error("Arity must be an integer greater than 0 in FunctionNode: '$func'")
end
end
returnType = get(nodeDict, "returnType", "")
if !(typeof(returnType) <: String)
error("returnType field must be a string in FunctionNode: '$func'")
end
if returnType != ""
aux = 0
try
aux = eval(Meta.parse(returnType))
catch e
error("The following type: '$returnType' in TerminalNode: '$func' is not defined")
end
if typeof(aux) <: DataType || typeof(aux) <: Union
returnType = aux
else
error("The following type: '$returnType' in TerminalNode: '$func' is not a type")
end
else
error("Function nodes must have a return type in FunctionNode: '$func'")
end
argTypes = get(nodeDict, "argumentTypes", false)
if argTypes == false
error("Function nodes must have a list of argument types in FunctionNode: '$func'")
end
if arity == 1 && !(typeof(argTypes) <: Array)
argTypes = [argTypes]
elseif arity > 1 && !(typeof(argTypes) <: Array)
error("argumentTypes field must be an array of string when arity is greater than 1 in FunctionNode: '$func'")
elseif arity > 1 && !(typeof(argTypes) <: Array)
error("argumentTypes field must be an array of string when arity is greater than 1 in FunctionNode: '$func'")
end
if length(argTypes) != arity
error("Number of elements in argumentTypes field must match arity field in FunctionNode: '$func'")
end
for i=1:length(argTypes)
if !(typeof(argTypes[i]) <: String)
error("The elements of argumentTypes field must be strings in FunctionNode: '$func'")
end
try
aux = eval(Meta.parse(argTypes[i]))
catch e
error("The following type: '$(argTypes[i])' in TerminalNode: '$func' is not defined")
end
if typeof(aux) <: DataType || typeof(aux) <: Union
argTypes[i] = aux
else
error("The following type: '$(argTypes[i])' in TerminalNode: '$func' is not a type")
end
end
argTypes = Array{Union{DataType, Union}}(argTypes)
return FunctionNode(func, arity, returnType, argTypes)
end # function
"""
parseTerminalNode(nodeDict::Dict)
Parses a [`TerminalNode`](@ref) from a node set configuration file.
"""
function parseTerminalNode(nodeDict::Dict)
terminalNode = 0
kind = get(nodeDict, "kind", false)
if kind == false
error("kind field not specified in TerminalNode")
elseif !(typeof(kind) <: String)
error("kind field in TerminalNode must be one of these strings: \"variable\", \"constant\", \"ephemeralConstant\" or \"terminalFunction\"")
end
if kind == "variable"
name = get(nodeDict, "name", false)
if name == false
error("name field is not set in TerminalNode of kind variable")
else
if !(typeof(name) <: String)
error("name field ($name) in TerminalNode of kind variable '$name' must be a string")
end
end
type = get(nodeDict, "type", false)
if type == false
error("TerminalNode of kind variable '$name' has no type specified")
end
aux = 0
try
aux = eval(Meta.parse(type))
catch e
error("The following type: '$type' in TerminalNode: '$name' is not defined")
end
if typeof(aux) <: DataType
type = aux
else
error("The following type: '$type' in TerminalNode: '$name' is not a type")
end
terminalNode = VariableNode(name, type)
elseif kind == "constant"
value = get(nodeDict, "value", nothing)
if value == nothing
error("TerminalNode of kind constant has no value")
end
try
aux = Meta.parse(value)
value = eval(aux)
catch e
# Empty
end
terminalNode = ConstantNode(value)
elseif kind == "ephemeralConstant"
func = get(nodeDict, "function", false)
if func == false
error("TerminalNode of kind ephemeralConstant has no function")
else
aux = 0
try
aux = eval(Meta.parse(func))
catch e
error("The following function: '$func' in TerminalNode of kind ephemeralConstant is not defined")
end
if typeof(aux) <: Function
func = aux
else
error("The following function: '$func' TerminalNode of kind ephemeralConstant is not a function")
end
end
varArgs = get(nodeDict, "arguments", [])
if !(typeof(varArgs) <: Array)
aux = Array{Any}(undef, 1)
aux[1] = varArgs
varArgs = aux
end
for i=1:length(varArgs)
try
arg = Meta.parse(varArgs[i])
varArgs[i] = eval(arg)
catch e
# Empty
end
end
terminalNode = ConstantNode(func, varArgs)
elseif kind == "terminalFunction"
func = get(nodeDict, "function", false)
if func == false
error("TerminalNode of kind terminalFunction '$func' has no function")
else
aux = 0
try
aux = eval(Meta.parse(func))
catch e
error("The following function: '$func' in TerminalNode of kind terminalFunction is not defined")
end
if typeof(aux) <: Function
func = aux
else
error("The following function: '$func' TerminalNode of kind terminalFunction is not a function")
end
end
terminalNode = NoArgsFunctionNode(func)
else
error("kind field of TerminalNode not supported: '$kind'")
end
return terminalNode
end # function
"""
createNodes(jsonFile::String, verbose::Bool=true)
Parses a node set configuration file that contains the information about the
nodes of a Genetic Programming problem.
"""
function createNodes(jsonFile::String)
if !isfile(jsonFile)
error("File $jsonFile does not exist in working directory")
end
file=open(jsonFile)
dictionary = JSON.parse(file)
close(file)
if get(dictionary, "FunctionNodes", false) == false
error("Nodes configuration file '$jsonFile' must have function nodes")
end
if get(dictionary, "TerminalNodes", false) == false
error("Nodes configuration file '$jsonFile' must have terminal nodes")
end
nFunctions = length(dictionary["FunctionNodes"])
nTerminals = length(dictionary["TerminalNodes"])
if nFunctions == 0
error("Nodes configuration file '$jsonFile' must have function nodes")
end
if nTerminals == 0
error("Nodes configuration file '$jsonFile' must have terminal nodes")
end
functionSet = Array{FunctionNode}(undef, nFunctions)
terminalSet = Array{TerminalNode}(undef, nTerminals)
for i=1:nFunctions
functionSet[i] = parseFunctionNode(dictionary["FunctionNodes"][i]["Node"])
end
for i=1:nTerminals
terminalSet[i] = parseTerminalNode(dictionary["TerminalNodes"][i]["Node"])
end
return functionSet, terminalSet
end # function
| [
37811,
198,
220,
220,
220,
21136,
22203,
19667,
7,
17440,
35,
713,
3712,
35,
713,
8,
198,
198,
47,
945,
274,
257,
685,
63,
22203,
19667,
63,
16151,
31,
5420,
8,
422,
257,
10139,
900,
8398,
2393,
13,
198,
37811,
198,
8818,
21136,
2... | 2.331475 | 3,587 |
export DepthMap
import ImageView
type DepthMap
camera :: M34
depth :: Array{Float32, 2}
nxcorr :: Array{Float32, 2}
end
function DepthMap(view, nbrs, voi, w = 3)
cam = view.camera
im = view.image
(nc, nx, ny) = size(im)
mn = LibAminda.mean_and_inverse_deviation(im, w)
# determine depth range, resolution
bnds = bounds(cam, voi)
near = bnds[1][3]
far = bnds[2][3]
dz = near * camera_resolution(cam)
nz = ceil(Int, (far - near) / dz)
dz = (far - near) / nz
max_nxcorr = LibAminda.fill(nx, ny, -1.0)
depth = LibAminda.fill(nx, ny, near)
for k in 1:nz
z = near + dz*(k-0.5)
nxcorr = LibAminda.fill(nx, ny, -1.0)
for nbr in nbrs
cam2 = nbr.camera
hom = Array(homography(cam, cam2, z))
im2 = LibAminda.map_to_plane(nbr.image, hom, nx, ny)
mn2 = LibAminda.mean_and_inverse_deviation(im2, w)
nxc = LibAminda.normalized_cross_correlation(im, mn, im2, mn2, w)
nxcorr = LibAminda.maximum(nxcorr, nxc)
end
LibAminda.update_depth(nxcorr, max_nxcorr, depth, z)
end
return DepthMap(cam, depth, max_nxcorr)
end
| [
39344,
36350,
13912,
198,
198,
11748,
7412,
7680,
198,
198,
4906,
36350,
13912,
198,
220,
4676,
7904,
337,
2682,
198,
220,
6795,
7904,
15690,
90,
43879,
2624,
11,
362,
92,
198,
220,
299,
87,
10215,
81,
7904,
15690,
90,
43879,
2624,
11... | 2.091429 | 525 |
# This file is a part of Julia. License is MIT: https://julialang.org/license
module REPLCompletions
export completions, shell_completions, bslash_completions, completion_text
using Base.Meta
using Base: propertynames, something
abstract type Completion end
struct KeywordCompletion <: Completion
keyword::String
end
struct PathCompletion <: Completion
path::String
end
struct ModuleCompletion <: Completion
parent::Module
mod::String
end
struct PackageCompletion <: Completion
package::String
end
struct PropertyCompletion <: Completion
value
property::Symbol
end
struct FieldCompletion <: Completion
typ::DataType
field::Symbol
end
struct MethodCompletion <: Completion
func
input_types::Type
method::Method
end
struct BslashCompletion <: Completion
bslash::String
end
struct ShellCompletion <: Completion
text::String
end
struct DictCompletion <: Completion
dict::AbstractDict
key::String
end
# interface definition
function Base.getproperty(c::Completion, name::Symbol)
if name === :keyword
return getfield(c, :keyword)::String
elseif name === :path
return getfield(c, :path)::String
elseif name === :parent
return getfield(c, :parent)::Module
elseif name === :mod
return getfield(c, :mod)::String
elseif name === :package
return getfield(c, :package)::String
elseif name === :property
return getfield(c, :property)::Symbol
elseif name === :field
return getfield(c, :field)::Symbol
elseif name === :method
return getfield(c, :method)::Method
elseif name === :bslash
return getfield(c, :bslash)::String
elseif name === :text
return getfield(c, :text)::String
elseif name === :key
return getfield(c, :key)::String
end
return getfield(c, name)
end
_completion_text(c::KeywordCompletion) = c.keyword
_completion_text(c::PathCompletion) = c.path
_completion_text(c::ModuleCompletion) = c.mod
_completion_text(c::PackageCompletion) = c.package
_completion_text(c::PropertyCompletion) = string(c.property)
_completion_text(c::FieldCompletion) = string(c.field)
_completion_text(c::MethodCompletion) = sprint(io -> show(io, c.method))
_completion_text(c::BslashCompletion) = c.bslash
_completion_text(c::ShellCompletion) = c.text
_completion_text(c::DictCompletion) = c.key
completion_text(c) = _completion_text(c)::String
const Completions = Tuple{Vector{Completion}, UnitRange{Int}, Bool}
function completes_global(x, name)
return startswith(x, name) && !('#' in x)
end
function appendmacro!(syms, macros, needle, endchar)
for s in macros
if endswith(s, needle)
from = nextind(s, firstindex(s))
to = prevind(s, sizeof(s)-sizeof(needle)+1)
push!(syms, s[from:to]*endchar)
end
end
end
function filtered_mod_names(ffunc::Function, mod::Module, name::AbstractString, all::Bool = false, imported::Bool = false)
ssyms = names(mod, all = all, imported = imported)
filter!(ffunc, ssyms)
syms = String[string(s) for s in ssyms]
macros = filter(x -> startswith(x, "@" * name), syms)
appendmacro!(syms, macros, "_str", "\"")
appendmacro!(syms, macros, "_cmd", "`")
filter!(x->completes_global(x, name), syms)
return [ModuleCompletion(mod, sym) for sym in syms]
end
# REPL Symbol Completions
function complete_symbol(sym::String, ffunc, context_module::Module=Main)
mod = context_module
name = sym
lookup_module = true
t = Union{}
val = nothing
if something(findlast(in(non_identifier_chars), sym), 0) < something(findlast(isequal('.'), sym), 0)
# Find module
lookup_name, name = rsplit(sym, ".", limit=2)
ex = Meta.parse(lookup_name, raise=false, depwarn=false)
b, found = get_value(ex, context_module)
if found
val = b
if isa(b, Module)
mod = b
lookup_module = true
elseif Base.isstructtype(typeof(b))
lookup_module = false
t = typeof(b)
end
else # If the value is not found using get_value, the expression contain an advanced expression
lookup_module = false
t, found = get_type(ex, context_module)
end
found || return Completion[]
end
suggestions = Completion[]
if lookup_module
# We will exclude the results that the user does not want, as well
# as excluding Main.Main.Main, etc., because that's most likely not what
# the user wants
p = let mod=mod, modname=nameof(mod)
s->(!Base.isdeprecated(mod, s) && s != modname && ffunc(mod, s)::Bool)
end
# Looking for a binding in a module
if mod == context_module
# Also look in modules we got through `using`
mods = ccall(:jl_module_usings, Any, (Any,), context_module)::Vector
for m in mods
append!(suggestions, filtered_mod_names(p, m::Module, name))
end
append!(suggestions, filtered_mod_names(p, mod, name, true, true))
else
append!(suggestions, filtered_mod_names(p, mod, name, true, false))
end
elseif val !== nothing # looking for a property of an instance
for property in propertynames(val, false)
# TODO: support integer arguments (#36872)
if property isa Symbol && startswith(string(property), name)
push!(suggestions, PropertyCompletion(val, property))
end
end
else
# Looking for a member of a type
if t isa DataType && t != Any
# Check for cases like Type{typeof(+)}
if t isa DataType && t.name === Base._TYPE_NAME
t = typeof(t.parameters[1])
end
# Only look for fields if this is a concrete type
if isconcretetype(t)
fields = fieldnames(t)
for field in fields
s = string(field)
if startswith(s, name)
push!(suggestions, FieldCompletion(t, field))
end
end
end
end
end
suggestions
end
const sorted_keywords = [
"abstract type", "baremodule", "begin", "break", "catch", "ccall",
"const", "continue", "do", "else", "elseif", "end", "export", "false",
"finally", "for", "function", "global", "if", "import",
"let", "local", "macro", "module", "mutable struct",
"primitive type", "quote", "return", "struct",
"true", "try", "using", "while"]
function complete_keyword(s::Union{String,SubString{String}})
r = searchsorted(sorted_keywords, s)
i = first(r)
n = length(sorted_keywords)
while i <= n && startswith(sorted_keywords[i],s)
r = first(r):i
i += 1
end
Completion[KeywordCompletion(kw) for kw in sorted_keywords[r]]
end
function complete_path(path::AbstractString, pos::Int; use_envpath=false, shell_escape=false)
if Base.Sys.isunix() && occursin(r"^~(?:/|$)", path)
# if the path is just "~", don't consider the expanded username as a prefix
if path == "~"
dir, prefix = homedir(), ""
else
dir, prefix = splitdir(homedir() * path[2:end])
end
else
dir, prefix = splitdir(path)
end
local files
try
if isempty(dir)
files = readdir()
elseif isdir(dir)
files = readdir(dir)
else
return Completion[], 0:-1, false
end
catch
return Completion[], 0:-1, false
end
matches = Set{String}()
for file in files
if startswith(file, prefix)
id = try isdir(joinpath(dir, file)) catch; false end
# joinpath is not used because windows needs to complete with double-backslash
push!(matches, id ? file * (@static Sys.iswindows() ? "\\\\" : "/") : file)
end
end
if use_envpath && length(dir) == 0
# Look for files in PATH as well
local pathdirs = split(ENV["PATH"], @static Sys.iswindows() ? ";" : ":")
for pathdir in pathdirs
local actualpath
try
actualpath = realpath(pathdir)
catch
# Bash doesn't expect every folder in PATH to exist, so neither shall we
continue
end
if actualpath != pathdir && in(actualpath,pathdirs)
# Remove paths which (after resolving links) are in the env path twice.
# Many distros eg. point /bin to /usr/bin but have both in the env path.
continue
end
local filesinpath
try
filesinpath = readdir(pathdir)
catch e
# Bash allows dirs in PATH that can't be read, so we should as well.
if isa(e, Base.IOError) || isa(e, Base.ArgumentError)
continue
else
# We only handle IOError and ArgumentError here
rethrow()
end
end
for file in filesinpath
# In a perfect world, we would filter on whether the file is executable
# here, or even on whether the current user can execute the file in question.
if startswith(file, prefix) && isfile(joinpath(pathdir, file))
push!(matches, file)
end
end
end
end
matchList = Completion[PathCompletion(shell_escape ? replace(s, r"\s" => s"\\\0") : s) for s in matches]
startpos = pos - lastindex(prefix) + 1 - count(isequal(' '), prefix)
# The pos - lastindex(prefix) + 1 is correct due to `lastindex(prefix)-lastindex(prefix)==0`,
# hence we need to add one to get the first index. This is also correct when considering
# pos, because pos is the `lastindex` a larger string which `endswith(path)==true`.
return matchList, startpos:pos, !isempty(matchList)
end
function complete_expanduser(path::AbstractString, r)
expanded = expanduser(path)
return Completion[PathCompletion(expanded)], r, path != expanded
end
# Determines whether method_complete should be tried. It should only be done if
# the string endswiths ',' or '(' when disregarding whitespace_chars
function should_method_complete(s::AbstractString)
method_complete = false
for c in reverse(s)
if c in [',', '(']
method_complete = true
break
elseif !(c in whitespace_chars)
method_complete = false
break
end
end
method_complete
end
# Returns a range that includes the method name in front of the first non
# closed start brace from the end of the string.
function find_start_brace(s::AbstractString; c_start='(', c_end=')')
braces = 0
r = reverse(s)
i = firstindex(r)
in_single_quotes = false
in_double_quotes = false
in_back_ticks = false
while i <= ncodeunits(r)
c, i = iterate(r, i)
if !in_single_quotes && !in_double_quotes && !in_back_ticks
if c == c_start
braces += 1
elseif c == c_end
braces -= 1
elseif c == '\''
in_single_quotes = true
elseif c == '"'
in_double_quotes = true
elseif c == '`'
in_back_ticks = true
end
else
if !in_back_ticks && !in_double_quotes &&
c == '\'' && i <= ncodeunits(r) && iterate(r, i)[1] != '\\'
in_single_quotes = !in_single_quotes
elseif !in_back_ticks && !in_single_quotes &&
c == '"' && i <= ncodeunits(r) && iterate(r, i)[1] != '\\'
in_double_quotes = !in_double_quotes
elseif !in_single_quotes && !in_double_quotes &&
c == '`' && i <= ncodeunits(r) && iterate(r, i)[1] != '\\'
in_back_ticks = !in_back_ticks
end
end
braces == 1 && break
end
braces != 1 && return 0:-1, -1
method_name_end = reverseind(s, i)
startind = nextind(s, something(findprev(in(non_identifier_chars), s, method_name_end), 0))::Int
return (startind:lastindex(s), method_name_end)
end
# Returns the value in a expression if sym is defined in current namespace fn.
# This method is used to iterate to the value of a expression like:
# :(REPL.REPLCompletions.whitespace_chars) a `dump` of this expression
# will show it consist of Expr, QuoteNode's and Symbol's which all needs to
# be handled differently to iterate down to get the value of whitespace_chars.
function get_value(sym::Expr, fn)
sym.head !== :. && return (nothing, false)
for ex in sym.args
fn, found = get_value(ex, fn)
!found && return (nothing, false)
end
return (fn, true)
end
get_value(sym::Symbol, fn) = isdefined(fn, sym) ? (getfield(fn, sym), true) : (nothing, false)
get_value(sym::QuoteNode, fn) = isdefined(fn, sym.value) ? (getfield(fn, sym.value), true) : (nothing, false)
get_value(sym, fn) = (sym, true)
# Return the value of a getfield call expression
function get_value_getfield(ex::Expr, fn)
# Example :((top(getfield))(Base,:max))
val, found = get_value_getfield(ex.args[2],fn) #Look up Base in Main and returns the module
(found && length(ex.args) >= 3) || return (nothing, false)
return get_value_getfield(ex.args[3], val) #Look up max in Base and returns the function if found.
end
get_value_getfield(sym, fn) = get_value(sym, fn)
# Determines the return type with Base.return_types of a function call using the type information of the arguments.
function get_type_call(expr::Expr)
f_name = expr.args[1]
# The if statement should find the f function. How f is found depends on how f is referenced
if isa(f_name, GlobalRef) && isconst(f_name.mod,f_name.name) && isdefined(f_name.mod,f_name.name)
ft = typeof(eval(f_name))
found = true
else
ft, found = get_type(f_name, Main)
end
found || return (Any, false) # If the function f is not found return Any.
args = Any[]
for ex in expr.args[2:end] # Find the type of the function arguments
typ, found = get_type(ex, Main)
found ? push!(args, typ) : push!(args, Any)
end
# use _methods_by_ftype as the function is supplied as a type
world = Base.get_world_counter()
matches = Base._methods_by_ftype(Tuple{ft, args...}, -1, world)
length(matches) == 1 || return (Any, false)
match = first(matches)
# Typeinference
interp = Core.Compiler.NativeInterpreter()
return_type = Core.Compiler.typeinf_type(interp, match.method, match.spec_types, match.sparams)
return_type === nothing && return (Any, false)
return (return_type, true)
end
# Returns the return type. example: get_type(:(Base.strip("", ' ')), Main) returns (String, true)
function try_get_type(sym::Expr, fn::Module)
val, found = get_value(sym, fn)
found && return Core.Typeof(val), found
if sym.head === :call
# getfield call is special cased as the evaluation of getfield provides good type information,
# is inexpensive and it is also performed in the complete_symbol function.
a1 = sym.args[1]
if isa(a1,GlobalRef) && isconst(a1.mod,a1.name) && isdefined(a1.mod,a1.name) &&
eval(a1) === Core.getfield
val, found = get_value_getfield(sym, Main)
return found ? Core.Typeof(val) : Any, found
end
return get_type_call(sym)
elseif sym.head === :thunk
thk = sym.args[1]
rt = ccall(:jl_infer_thunk, Any, (Any, Any), thk::Core.CodeInfo, fn)
rt !== Any && return (rt, true)
elseif sym.head === :ref
# some simple cases of `expand`
return try_get_type(Expr(:call, GlobalRef(Base, :getindex), sym.args...), fn)
elseif sym.head === :. && sym.args[2] isa QuoteNode # second check catches broadcasting
return try_get_type(Expr(:call, GlobalRef(Core, :getfield), sym.args...), fn)
end
return (Any, false)
end
try_get_type(other, fn::Module) = get_type(other, fn)
function get_type(sym::Expr, fn::Module)
# try to analyze nests of calls. if this fails, try using the expanded form.
val, found = try_get_type(sym, fn)
found && return val, found
return try_get_type(Meta.lower(fn, sym), fn)
end
function get_type(sym, fn::Module)
val, found = get_value(sym, fn)
return found ? Core.Typeof(val) : Any, found
end
# Method completion on function call expression that look like :(max(1))
function complete_methods(ex_org::Expr, context_module::Module=Main)
args_ex = Any[]
func, found = get_value(ex_org.args[1], context_module)::Tuple{Any,Bool}
!found && return Completion[]
funargs = ex_org.args[2:end]
# handle broadcasting, but only handle number of arguments instead of
# argument types
if ex_org.head === :. && ex_org.args[2] isa Expr
for _ in (ex_org.args[2]::Expr).args
push!(args_ex, Any)
end
else
for ex in funargs
val, found = get_type(ex, context_module)
push!(args_ex, val)
end
end
out = Completion[]
t_in = Tuple{Core.Typeof(func), args_ex...} # Input types
na = length(args_ex)+1
ml = methods(func)
for method in ml
ms = method.sig
# Check if the method's type signature intersects the input types
if typeintersect(Base.rewrap_unionall(Tuple{(Base.unwrap_unionall(ms)::DataType).parameters[1 : min(na, end)]...}, ms), t_in) !== Union{}
push!(out, MethodCompletion(func, t_in, method))
end
end
return out
end
include("latex_symbols.jl")
include("emoji_symbols.jl")
const non_identifier_chars = [" \t\n\r\"\\'`\$><=:;|&{}()[],+-*/?%^~"...]
const whitespace_chars = [" \t\n\r"...]
# "\"'`"... is added to whitespace_chars as non of the bslash_completions
# characters contain any of these characters. It prohibits the
# bslash_completions function to try and complete on escaped characters in strings
const bslash_separators = [whitespace_chars..., "\"'`"...]
# Aux function to detect whether we're right after a
# using or import keyword
function afterusing(string::String, startpos::Int)
(isempty(string) || startpos == 0) && return false
str = string[1:prevind(string,startpos)]
isempty(str) && return false
rstr = reverse(str)
r = findfirst(r"\s(gnisu|tropmi)\b", rstr)
r === nothing && return false
fr = reverseind(str, last(r))
return occursin(r"^\b(using|import)\s*((\w+[.])*\w+\s*,\s*)*$", str[fr:end])
end
function bslash_completions(string::String, pos::Int)
slashpos = something(findprev(isequal('\\'), string, pos), 0)
if (something(findprev(in(bslash_separators), string, pos), 0) < slashpos &&
!(1 < slashpos && (string[prevind(string, slashpos)]=='\\')))
# latex / emoji symbol substitution
s = string[slashpos:pos]
latex = get(latex_symbols, s, "")
if !isempty(latex) # complete an exact match
return (true, (Completion[BslashCompletion(latex)], slashpos:pos, true))
end
emoji = get(emoji_symbols, s, "")
if !isempty(emoji)
return (true, (Completion[BslashCompletion(emoji)], slashpos:pos, true))
end
# return possible matches; these cannot be mixed with regular
# Julian completions as only latex / emoji symbols contain the leading \
if startswith(s, "\\:") # emoji
namelist = Iterators.filter(k -> startswith(k, s), keys(emoji_symbols))
else # latex
namelist = Iterators.filter(k -> startswith(k, s), keys(latex_symbols))
end
return (true, (Completion[BslashCompletion(name) for name in sort!(collect(namelist))], slashpos:pos, true))
end
return (false, (Completion[], 0:-1, false))
end
function dict_identifier_key(str::String, tag::Symbol, context_module::Module = Main)
if tag === :string
str_close = str*"\""
elseif tag === :cmd
str_close = str*"`"
else
str_close = str
end
frange, end_of_identifier = find_start_brace(str_close, c_start='[', c_end=']')
isempty(frange) && return (nothing, nothing, nothing)
obj = context_module
for name in split(str[frange[1]:end_of_identifier], '.')
Base.isidentifier(name) || return (nothing, nothing, nothing)
sym = Symbol(name)
isdefined(obj, sym) || return (nothing, nothing, nothing)
obj = getfield(obj, sym)
end
(isa(obj, AbstractDict) && length(obj)::Int < 1_000_000) || return (nothing, nothing, nothing)
begin_of_key = something(findnext(!isspace, str, nextind(str, end_of_identifier) + 1), # +1 for [
lastindex(str)+1)
return (obj::AbstractDict, str[begin_of_key:end], begin_of_key)
end
# This needs to be a separate non-inlined function, see #19441
@noinline function find_dict_matches(identifier::AbstractDict, partial_key)
matches = String[]
for key in keys(identifier)
rkey = repr(key)
startswith(rkey,partial_key) && push!(matches,rkey)
end
return matches
end
function project_deps_get_completion_candidates(pkgstarts::String, project_file::String)
loading_candidates = String[]
d = Base.parsed_toml(project_file)
pkg = get(d, "name", nothing)::Union{String, Nothing}
if pkg !== nothing && startswith(pkg, pkgstarts)
push!(loading_candidates, pkg)
end
deps = get(d, "deps", nothing)::Union{Dict{String, Any}, Nothing}
if deps !== nothing
for (pkg, _) in deps
startswith(pkg, pkgstarts) && push!(loading_candidates, pkg)
end
end
return Completion[PackageCompletion(name) for name in loading_candidates]
end
function completions(string::String, pos::Int, context_module::Module=Main)
# First parse everything up to the current position
partial = string[1:pos]
inc_tag = Base.incomplete_tag(Meta.parse(partial, raise=false, depwarn=false))
# if completing a key in a Dict
identifier, partial_key, loc = dict_identifier_key(partial, inc_tag, context_module)
if identifier !== nothing
matches = find_dict_matches(identifier, partial_key)
length(matches)==1 && (lastindex(string) <= pos || string[nextind(string,pos)] != ']') && (matches[1]*=']')
length(matches)>0 && return Completion[DictCompletion(identifier, match) for match in sort!(matches)], loc::Int:pos, true
end
# otherwise...
if inc_tag in [:cmd, :string]
m = match(r"[\t\n\r\"`><=*?|]| (?!\\)", reverse(partial))
startpos = nextind(partial, reverseind(partial, m.offset))
r = startpos:pos
expanded = complete_expanduser(replace(string[r], r"\\ " => " "), r)
expanded[3] && return expanded # If user expansion available, return it
paths, r, success = complete_path(replace(string[r], r"\\ " => " "), pos)
if inc_tag === :string &&
length(paths) == 1 && # Only close if there's a single choice,
!isdir(expanduser(replace(string[startpos:prevind(string, first(r))] * paths[1].path,
r"\\ " => " "))) && # except if it's a directory
(lastindex(string) <= pos ||
string[nextind(string,pos)] != '"') # or there's already a " at the cursor.
paths[1] = PathCompletion(paths[1].path * "\"")
end
#Latex symbols can be completed for strings
(success || inc_tag==:cmd) && return sort!(paths, by=p->p.path), r, success
end
ok, ret = bslash_completions(string, pos)
ok && return ret
# Make sure that only bslash_completions is working on strings
inc_tag==:string && return Completion[], 0:-1, false
if inc_tag === :other && should_method_complete(partial)
frange, method_name_end = find_start_brace(partial)
# strip preceding ! operator
s = replace(partial[frange], r"\!+([^=\(]+)" => s"\1")
ex = Meta.parse(s * ")", raise=false, depwarn=false)
if isa(ex, Expr)
if ex.head === :call
return complete_methods(ex, context_module), first(frange):method_name_end, false
elseif ex.head === :. && ex.args[2] isa Expr && (ex.args[2]::Expr).head === :tuple
return complete_methods(ex, context_module), first(frange):(method_name_end - 1), false
end
end
elseif inc_tag === :comment
return Completion[], 0:-1, false
end
dotpos = something(findprev(isequal('.'), string, pos), 0)
startpos = nextind(string, something(findprev(in(non_identifier_chars), string, pos), 0))
# strip preceding ! operator
if (m = match(r"^\!+", string[startpos:pos])) !== nothing
startpos += length(m.match)
end
ffunc = (mod,x)->true
suggestions = Completion[]
comp_keywords = true
if afterusing(string, startpos)
# We're right after using or import. Let's look only for packages
# and modules we can reach from here
# If there's no dot, we're in toplevel, so we should
# also search for packages
s = string[startpos:pos]
if dotpos <= startpos
for dir in Base.load_path()
if basename(dir) in Base.project_names && isfile(dir)
append!(suggestions, project_deps_get_completion_candidates(s, dir))
end
isdir(dir) || continue
for pname in readdir(dir)
if pname[1] != '.' && pname != "METADATA" &&
pname != "REQUIRE" && startswith(pname, s)
# Valid file paths are
# <Mod>.jl
# <Mod>/src/<Mod>.jl
# <Mod>.jl/src/<Mod>.jl
if isfile(joinpath(dir, pname))
endswith(pname, ".jl") && push!(suggestions,
PackageCompletion(pname[1:prevind(pname, end-2)]))
else
mod_name = if endswith(pname, ".jl")
pname[1:prevind(pname, end-2)]
else
pname
end
if isfile(joinpath(dir, pname, "src",
"$mod_name.jl"))
push!(suggestions, PackageCompletion(mod_name))
end
end
end
end
end
end
ffunc = (mod,x)->(Base.isbindingresolved(mod, x) && isdefined(mod, x) && isa(getfield(mod, x), Module))
comp_keywords = false
end
startpos == 0 && (pos = -1)
dotpos < startpos && (dotpos = startpos - 1)
s = string[startpos:pos]
comp_keywords && append!(suggestions, complete_keyword(s))
# The case where dot and start pos is equal could look like: "(""*"").d","". or CompletionFoo.test_y_array[1].y
# This case can be handled by finding the beginning of the expression. This is done below.
if dotpos == startpos
i = prevind(string, startpos)
while 0 < i
c = string[i]
if c in [')', ']']
if c==')'
c_start='('; c_end=')'
elseif c==']'
c_start='['; c_end=']'
end
frange, end_of_identifier = find_start_brace(string[1:prevind(string, i)], c_start=c_start, c_end=c_end)
startpos = first(frange)
i = prevind(string, startpos)
elseif c in ('\'', '\"', '\`')
s = "$c$c"*string[startpos:pos]
break
else
break
end
s = string[startpos:pos]
end
end
append!(suggestions, complete_symbol(s, ffunc, context_module))
return sort!(unique(suggestions), by=completion_text), (dotpos+1):pos, true
end
function shell_completions(string, pos)
# First parse everything up to the current position
scs = string[1:pos]
local args, last_parse
try
args, last_parse = Base.shell_parse(scs, true)::Tuple{Expr,UnitRange{Int}}
catch
return Completion[], 0:-1, false
end
ex = args.args[end]::Expr
# Now look at the last thing we parsed
isempty(ex.args) && return Completion[], 0:-1, false
arg = ex.args[end]
if all(s -> isa(s, AbstractString), ex.args)
arg = arg::AbstractString
# Treat this as a path
# As Base.shell_parse throws away trailing spaces (unless they are escaped),
# we need to special case here.
# If the last char was a space, but shell_parse ignored it search on "".
ignore_last_word = arg != " " && scs[end] == ' '
prefix = ignore_last_word ? "" : join(ex.args)
# Also try looking into the env path if the user wants to complete the first argument
use_envpath = !ignore_last_word && length(args.args) < 2
return complete_path(prefix, pos, use_envpath=use_envpath, shell_escape=true)
elseif isexpr(arg, :incomplete) || isexpr(arg, :error)
partial = scs[last_parse]
ret, range = completions(partial, lastindex(partial))
range = range .+ (first(last_parse) - 1)
return ret, range, true
end
return Completion[], 0:-1, false
end
end # module
| [
2,
770,
2393,
318,
257,
636,
286,
22300,
13,
13789,
318,
17168,
25,
3740,
1378,
73,
377,
498,
648,
13,
2398,
14,
43085,
198,
198,
21412,
45285,
5377,
37069,
507,
198,
198,
39344,
1224,
45240,
11,
7582,
62,
785,
37069,
507,
11,
275,
... | 2.280064 | 13,047 |
"# This file is a part of JuliaFEM.\n# License is MIT: see https://github.com/JuliaFEM/JuliaFEM.jl/b(...TRUNCATED) | [2,770,2393,318,257,636,286,22300,37,3620,13,198,2,13789,318,17168,25,766,3740,1378,12567,13,785,14,(...TRUNCATED) | 2.258367 | 1,494 |
"\nusing StatsBase\n\n# Support some of the weighted statistics function in StatsBase\n# NOTES:\n# -(...TRUNCATED) | [198,3500,20595,14881,198,198,2,7929,617,286,262,26356,7869,2163,287,20595,14881,198,2,5626,1546,25,(...TRUNCATED) | 2.387769 | 1,439 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 1,166