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" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
26013
# Source/receiver geometry structure # Author: Philipp Witte, [email protected] # Date: January 2017 # export Geometry, compareGeometry, GeometryIC, GeometryOOC, get_nsrc, n_samples, super_shot_geometry export reciprocal_geom, get_nt, get_dt, get_t, get_t0 abstract type Geometry{T} end mutable struct GeometryException <: Exception msg :: String end const CoordT{T} = Union{Vector{T}, Vector{Vector{T}}} where T<:Number (::Type{CoordT{T}})(x::Vector{Any}) where {T<:Real} = rebuild_maybe_jld(x) Base.convert(::Type{CoordT}, a::Vector{Any}) = Vector{typeof(a[1])}(a) # In-core geometry structure for seismic header information mutable struct GeometryIC{T} <: Geometry{T} xloc::CoordT{T} # Array of receiver positions (fixed for all experiments) yloc::CoordT{T} zloc::CoordT{T} taxis::Vector{<:StepRangeLen{T}} # Legacy function GeometryIC{T}(xloc::CoordT{T}, yloc::CoordT{T}, zloc::CoordT{T}, dt::Vector{T}, nt::Vector{<:Integer}, ::Vector{T}) where T tranges = [StepRangeLen(T(0), T(dti), nti) for (dti, nti) in zip(dt, nt)] new(xloc, yloc, zloc, tranges) end # Default constructor GeometryIC{T}(xloc::CoordT{T}, yloc::CoordT{T}, zloc::CoordT{T}, t::Vector{<:StepRangeLen{T}}) where T = new{T}(xloc, yloc, zloc, t) end function getproperty(G::Geometry, s::Symbol) # Nrec for in core if s == :nrec && isa(G, GeometryIC) return length.(G.xloc) end # Legacy dt/nt/t if s in [:dt, :t, :nt, :t0] return eval(Symbol("get_$(s)"))(G) end return getfield(G, s) end # Out-of-core geometry structure, contains look-up table instead of coordinates mutable struct GeometryOOC{T} <: Geometry{T} container::Vector{SegyIO.SeisCon} taxis::Vector{<:StepRangeLen{T}} nrec::Vector{<:Integer} key::String segy_depth_key::String # Legacy function GeometryOOC{T}(container::Vector{SegyIO.SeisCon}, dt::Vector{T}, nt::Vector{<:Integer}, ::Vector{T}, nrec::Vector{<:Integer}, key::String, segy_depth_key::String) where T tranges = [StepRangeLen(T(0), T(dti), nti) for (dti, nti) in zip(dt, nt)] return new{T}(container, tranges, nrec, key, segy_depth_key) end # Default constructor GeometryOOC{T}(container::Vector{SegyIO.SeisCon}, t::Vector{<:StepRangeLen{T}}, nrec::Vector{<:Integer}, key::String, segy_depth_key::String) where T = new{T}(container, t, nrec, key, segy_depth_key) end display(G::Geometry) = println("$(typeof(G)) wiht $(get_nsrc(G)) sources") show(io::IO, G::Geometry) = print(io, "$(typeof(G)) wiht $(get_nsrc(G)) sources") show(io::IO, ::MIME{Symbol("text/plain")}, G::Geometry) = println(io, "$(typeof(G)) wiht $(get_nsrc(G)) sources") ######################## shapes easy access ################################ get_nsrc(g::GeometryIC) = length(g.xloc) get_nsrc(g::GeometryOOC) = length(g.container) get_nsrc(S::SeisCon) = length(S) get_nsrc(S::Vector{SeisCon}) = length(S) get_nsrc(S::SeisBlock) = length(unique(get_header(S, "FieldRecord"))) n_samples(g::GeometryOOC, nsrc::Integer) = sum(g.nrec .* get_nt(g)) n_samples(g::GeometryIC, nsrc::Integer) = sum([length(g.xloc[j])*get_nt(g, j) for j=1:nsrc]) n_samples(g::Geometry) = n_samples(g, get_nsrc(g)) get_nt(g::Geometry) = length.(g.taxis) get_nt(g::Geometry, srcnum::Integer) = length(g.taxis[srcnum]) get_dt(g::Geometry) = step.(g.taxis) get_dt(g::Geometry, srcnum::Integer) = step(g.taxis[srcnum]) get_t(g::Geometry) = last.(g.taxis) get_t(g::Geometry, srcnum::Integer) = last(g.taxis[srcnum]) get_t0(g::Geometry) = first.(g.taxis) get_t0(g::Geometry, srcnum::Integer) = first(g.taxis[srcnum]) rec_space(G::Geometry) = AbstractSize((:src, :time, :rec), (get_nsrc(G), get_nt(G), G.nrec)) ################################################ Constructors #################################################################### """ GeometryIC xloc::Array{Array{T, 1},1} yloc::Array{Array{T, 1},1} zloc::Array{Array{T, 1},1} t::Vector{StepRangeLen{T}} Geometry structure for seismic sources or receivers. Each field is a cell array, where individual cell entries contain values or arrays with coordinates and sampling information for the corresponding shot position. The first three entries are in meters and the last three entries in milliseconds. GeometryOOC{T} <: Geometry{T} container::Array{SegyIO.SeisCon,1} t::Vector{StepRangeLen{T}} nrec::Array{Integer,1} key::String segy_depth_key::String Constructors ============ Only pass `dt` and `n` and automatically set `t`: Geometry(xloc, yloc, zloc; dt=[], nt=[]) Pass single array as coordinates/parameters for all `nsrc` experiments: Geometry(xloc, yloc, zloc, dt=[], nt=[], nsrc=1) Create geometry structure for either source or receivers from a SegyIO.SeisBlock object. `segy_depth_key` is the SegyIO keyword that contains the depth coordinate and `key` is set to either `source` for source geometry or `receiver` for receiver geometry: Geometry(SeisBlock; key="source", segy_depth_key="") Create geometry structure for from a SegyIO.SeisCon object (seismic data container): Geometry(SeisCon; key="source", segy_depth_key="") Examples ======== (1) Set up receiver geometry for 2D experiment with 4 source locations and 80 fixed receivers: xrec = range(100,stop=900,length=80) yrec = range(0,stop=0,length=80) zrec = range(50,stop=50,length=80) dt = 4f0 t = 1000f0 rec_geometry = Geometry(xrec, yrec, zrec; dt=dt, t=t, nsrc=4) (2) Set up corresponding source geometry (coordinates can be of type `linspace` or regular arrays): xsrc = [200,400,600,800] ysrc = [0,0,0,0] zsrc = [50,50,50,50] src_geometry = Geometry(xsrc, ysrc, zsrc; dt=dt, t=t, nsrc=4) (3) Read source and receiver geometries from SEG-Y file: using SegyIO seis_block = segy_read("test_file.segy") rec_geometry = Geometry(seis_block; key="receiver", segy_depth_key="RecGroupElevation") src_geometry = Geometry(seis_block; key="source", segy_depth_key="SourceDepth") Check the seis_block's header entries to findall out which keywords contain the depth coordinates. The source depth keyword is either `SourceDepth` or `SourceSurfaceElevation`. The receiver depth keyword is typically `RecGroupElevation`. (4) Read source and receiver geometries from out-of-core SEG-Y files (for large data sets). Returns an out-of-core geometry object `GeometryOOC` without the source/receiver coordinates, but a lookup table instead: using SegyIO seis_container = segy_scan("/path/to/data/directory","filenames",["GroupX","GroupY","RecGroupElevation","SourceDepth","dt"]) rec_geometry = Geometry(seis_container; key="receiver", segy_depth_key="RecGroupElevation") src_geometry = Geometry(seis_container; key="source", segy_depth_key="SourceDepth") """ function Geometry(xloc, yloc, zloc; dt=nothing, t=nothing, nsrc=nothing, t0=0) check_time(dt, t) if any(typeof(x) <: AbstractRange for x=[xloc, yloc, zloc]) args = [typeof(x) <: AbstractRange ? collect(x) : x for x=[xloc, yloc, zloc]] isnothing(nsrc) && (return Geometry(args...; dt=dt, t=t)) return Geometry(args...; dt=dt, t=t, nsrc=nsrc) end isnothing(nsrc) && (return Geometry(tof32(xloc), tof32(yloc), tof32(zloc); dt=dt, t=t)) return Geometry(tof32(xloc), tof32(yloc), tof32(zloc); dt=dt, t=t, nsrc=nsrc, t0=t0) end Geometry(xloc::CoordT, yloc::CoordT, zloc::CoordT, dt::Vector{T}, nt::Vector{<:Integer}, t::Vector{T}) where {T<:Real} = GeometryIC{T}(xloc,yloc,zloc,dt,nt, t) Geometry(xloc::CoordT, yloc::CoordT, zloc::CoordT, dt::Vector{T}, nt::Vector{T}, t::Vector{T}) where {T<:Real} = GeometryIC{T}(xloc,yloc,zloc,dt,convert(Vector{Int64}, nt), t) Geometry(xloc::CoordT, yloc::CoordT, zloc::CoordT, t::StepRangeLen{T}) where {T<:Real} = GeometryIC{T}(xloc,yloc,zloc,[t]) Geometry(xloc::CoordT, yloc::CoordT, zloc::CoordT, t::Vector{<:StepRangeLen{T}}) where {T<:Real} = GeometryIC{T}(xloc,yloc,zloc,t) # For easy 2D setup Geometry(xloc, zloc; kw...) = Geometry(xloc, 0 .* xloc, zloc; kw...) # Constructor if nt is not passed function Geometry(xloc::Array{Array{T, 1},1}, yloc::CoordT, zloc::Array{Array{T, 1},1}; dt=nothing, t=nothing, t0=0) where {T<:Real} check_time(dt, t) nsrc = length(xloc) dt = as_src_list(dt, nsrc) t = as_src_list(t, nsrc) t0 = as_src_list(t0, nsrc) tranges = [StepRangeLen(T(t0i), T(dti), floor.(Int, ti / dti) .+ 1) for (t0i, dti, ti) in zip(t0, dt, t)] return GeometryIC{T}(xloc, yloc, zloc, tranges) end # Constructor if coordinates are not passed as a cell arrays function Geometry(xloc::Array{T, 1}, yloc::CoordT, zloc::Array{T, 1}; dt=nothing, t=nothing, nsrc::Integer=1, t0=0) where {T<:Real} check_time(dt, t) xlocCell = [xloc for j=1:nsrc] ylocCell = [yloc for j=1:nsrc] zlocCell = [zloc for j=1:nsrc] dt = as_src_list(dt, nsrc) t = as_src_list(t, nsrc) t0 = as_src_list(t0, nsrc) tranges = [StepRangeLen(T(t0i), T(dti), floor.(Int, ti / dti) .+ 1) for (t0i, dti, ti) in zip(t0, dt, t)] return GeometryIC{T}(xlocCell, ylocCell, zlocCell, tranges) end ################################################ Constructors from SEGY data #################################################### # Utility function to prepare dtCell, ntCell, tCell from SEGY or based on user defined dt and t. # Useful when creating geometry for Forward Modeling with custom timings. _get_p(v, S, nsrc, P) = throw(GeometryException("User defined `dt` is neither: Real, Array of Real or the length of Array doesn't match the number of sources in SEGY")) _get_p(::Nothing, S::SeisBlock, nsrc::Integer, p, ::Type{T}, s::T) where T = fill(T(get_header(S, p)[1]/s), nsrc) _get_p(::Nothing, S::SeisCon, nsrc::Integer, p, ::Type{T}, s::T) where T = [T(_get_p_SeisCon(S, p, j)/s) for j=1:nsrc] _get_p(::Nothing, S::Vector{SeisCon}, nsrc::Integer, p, ::Type{T}, s::T) where T = [T(_get_p_SeisCon(S[j], p, 1)/s) for j=1:nsrc] _get_p(v::Real, data, nsrc::Integer, p, ::Type{T}, s::T) where T = fill(T(v), nsrc) _get_p(v::Vector, data, nsrc::Integer, p, ::Type{T}, s::T) where T = convert(Vector{T}, v) _get_p_SeisCon(S::SeisCon, p::String, b::Integer) = try S.blocks[b].summary[p][1] catch; getfield(S, Symbol(p)); end function timings_from_segy(data, dt=nothing, t=nothing, t0=nothing) # Get nsrc nsrc = get_nsrc(data) dtCell = _get_p(dt, data, nsrc, "dt", Float32, 1f3) if isnothing(t0) t0 = [segy_t0(data, i) for i=1:nsrc] else t0 = as_src_list(t0, nsrc) end if isnothing(t) ntCell = _get_p(nothing, data, nsrc, "ns", Int, 1) tCell = Float32.((ntCell .- 1) .* dtCell .+ t0) else tCell = as_src_list(t, nsrc) end return [range(t0[j], step=dtCell[j], stop=tCell[j]) for j=1:nsrc] end segy_t0(b::Vector{SeisCon}, i) = segy_t0(b[i], 1) segy_t0(b::SeisBlock, i) = segy_t0(b) segy_t0(b::SeisCon, i) = segy_t0(b.blocks[i]) segy_t0(b::SeisBlock) = segy_t0(b.fileheader.bfh) segy_t0(b::BlockScan) = segy_t0(read_fileheader(b.file).bfh) segy_t0(b::BinaryFileHeader) = (b.nsOrig - b.ns) * (b.dtOrig / 1000f0) # Set up source geometry object from in-core data container function Geometry(data::SegyIO.SeisBlock; key="source", segy_depth_key="", dt=nothing, t=nothing, t0=nothing) check_time(dt, t, true) src = get_header(data,"FieldRecord") usrc = unique(src) nsrc = length(usrc) if key=="source" isempty(segy_depth_key) && (segy_depth_key="SourceSurfaceElevation") params = ["SourceX","SourceY",segy_depth_key] gt = Float32 elseif key=="receiver" isempty(segy_depth_key) && (segy_depth_key="RecGroupElevation") params = ["GroupX","GroupY",segy_depth_key] gt = Array{Float32, 1} else throw(GeometryException("Specified keyword not supported")) end xloc = Vector{gt}(undef, nsrc) yloc = Vector{gt}(undef, nsrc) zloc = Vector{gt}(undef, nsrc) xloc_full = get_header(data, params[1]) yloc_full = get_header(data, params[2]) zloc_full = get_header(data, params[3]) for j=1:nsrc traces = findall(src .== usrc[j]) if key=="source" # assume same source location for all traces within one shot record xloc[j] = convert(gt, xloc_full[traces][1]) yloc[j] = convert(gt, yloc_full[traces][1]) zloc[j] = abs.(convert(gt, zloc_full[traces][1])) else xloc[j] = convert(gt, xloc_full[traces]) yloc[j] = convert(gt, yloc_full[traces]) zloc[j] = abs.(convert(gt, zloc_full[traces])) end end if key == "source" xloc = convertToCell(xloc) yloc = convertToCell(yloc) zloc = convertToCell(zloc) end tCell = timings_from_segy(data, dt, t, t0) return GeometryIC{Float32}(xloc,yloc,zloc,tCell) end # Set up geometry summary from out-of-core data container function Geometry(data::SegyIO.SeisCon; key="source", segy_depth_key="", dt=nothing, t=nothing, t0=nothing) check_time(dt, t, true) if key=="source" isempty(segy_depth_key) && (segy_depth_key="SourceSurfaceElevation") elseif key=="receiver" isempty(segy_depth_key) && (segy_depth_key="RecGroupElevation") else throw(GeometryException("Specified keyword not supported")) end # read either source or receiver geometry nsrc = length(data) container = Array{SegyIO.SeisCon}(undef, nsrc) nrec = Array{Integer}(undef, nsrc) for j=1:nsrc container[j] = split(data,j) nrec[j] = key=="source" ? 1 : Int((data.blocks[j].endbyte - data.blocks[j].startbyte)/(240 + data.ns*4)) end tCell = timings_from_segy(data, dt, t, t0) return GeometryOOC{Float32}(container,tCell,nrec,key,segy_depth_key) end # Set up geometry summary from out-of-core data container passed as cell array function Geometry(data::Array{SegyIO.SeisCon,1}; key="source", segy_depth_key="", dt=nothing, t=nothing, t0=nothing) check_time(dt, t, true) if key=="source" isempty(segy_depth_key) && (segy_depth_key="SourceSurfaceElevation") elseif key=="receiver" isempty(segy_depth_key) && (segy_depth_key="RecGroupElevation") else throw(GeometryException("Specified keyword not supported")) end nsrc = length(data) container = Array{SegyIO.SeisCon}(undef, nsrc) nrec = Array{Integer}(undef, nsrc) for j=1:nsrc container[j] = data[j] nrec[j] = key=="source" ? 1 : Int((data[j].blocks[1].endbyte - data[j].blocks[1].startbyte)/(240 + data[j].ns*4)) end tCell = timings_from_segy(data, dt, t, t0) return GeometryOOC{Float32}(container,tCell,nrec,key,segy_depth_key) end # Load geometry from out-of-core Geometry container function Geometry(geometry::GeometryOOC; rel_origin=(0, 0, 0), project=nothing) nsrc = length(geometry.container) ox, oy, oz = rel_origin # read either source or receiver geometry if geometry.key=="source" params = ["SourceX","SourceY",geometry.segy_depth_key,"dt","ns"] gt = Float32 elseif geometry.key=="receiver" params = ["GroupX","GroupY",geometry.segy_depth_key,"dt","ns"] gt = Array{Float32, 1} else throw(GeometryException("Specified keyword not supported")) end xloc = Array{gt, 1}(undef, nsrc) yloc = Array{gt, 1}(undef, nsrc) zloc = Array{gt, 1}(undef, nsrc) for j=1:nsrc header = read_con_headers(geometry.container[j], params, 1) if geometry.key=="source" if project == "2d" xtmp = get_header(header, params[1])[1] .- ox ytmp = get_header(header, params[2])[1] .- oy xloc[j] = sqrt.(xtmp.^2 .+ ytmp.^2) .* sign.(xtmp) yloc[j] = 0 .* xtmp else xloc[j] = get_header(header, params[1])[1] .- ox yloc[j] = get_header(header, params[2])[1] .- oy end zloc[j] = abs.(get_header(header, params[3]))[1] .- oz else if project == "2d" xtmp = get_header(header, params[1]) .- ox ytmp = get_header(header, params[2]) .- oy xloc[j] = sqrt.(xtmp.^2 .+ ytmp.^2) .* sign.(xtmp) yloc[j] = 0 .* xtmp else xloc[j] = get_header(header, params[1]) .- ox yloc[j] = get_header(header, params[2]) .- oy end zloc[j] = abs.(get_header(header, params[3])) .- oz end end if geometry.key == "source" xloc = convertToCell(xloc) yloc = convertToCell(yloc) zloc = convertToCell(zloc) end return GeometryIC{Float32}(xloc,yloc,zloc,geometry.taxis) end function Geometry(geometry::GeometryIC; rel_origin=(0, 0, 0), project=nothing) if isnothing(project) && origin == 0 return geometry end xloc = similar(geometry.xloc) yloc = similar(geometry.yloc) zloc = similar(geometry.zloc) for s=1:get_nsrc(geometry) xloc[s] = geometry.xloc[s] .- rel_origin[1] yloc[s] = geometry.yloc[s] .- rel_origin[2] zloc[s] = geometry.zloc[s] .- rel_origin[3] if project == "2d" xloc[s] = sqrt.(xloc[s].^2 .+ yloc[s].^2) .* sign.(xloc[s]) yloc[s] = 0 .* xloc[s] end end return GeometryIC{Float32}(xloc, yloc, zloc, geometry.taxis) end Geometry(v::Array{T}) where T = v Geometry(::Nothing) = nothing ########################################################################################################################################### subsample(g::Geometry, I) = getindex(g, I) # getindex in-core geometry structure function getindex(geometry::GeometryIC{T}, srcnum::RangeOrVec) where T xsub = geometry.xloc[srcnum] ysub = geometry.yloc[srcnum] zsub = geometry.zloc[srcnum] tsub = geometry.taxis[srcnum] geometry = GeometryIC{T}(xsub, ysub, zsub, tsub) return geometry end function getindex(geometry::GeometryOOC{T}, srcnum::RangeOrVec) where T container = geometry.container[srcnum] tsub = geometry.taxis[srcnum] nrec = geometry.nrec[srcnum] return GeometryOOC{T}(container, tsub, nrec, geometry.key, geometry.segy_depth_key) end getindex(geometry::Geometry, srcnum::Integer) = getindex(geometry, srcnum:srcnum) ########################################################################################################################################### # Compare if geometries match function compareGeometry(geometry_A::Geometry, geometry_B::Geometry) if isequal(geometry_A.xloc, geometry_B.xloc) && isequal(geometry_A.yloc, geometry_B.yloc) && isequal(geometry_A.zloc, geometry_B.zloc) && isequal(geometry_A.t, geometry_B.t) return true else return false end end ==(geometry_A::Geometry, geometry_B::Geometry) = compareGeometry(geometry_A, geometry_B) isapprox(geometry_A::Geometry, geometry_B::Geometry; kw...) = compareGeometry(geometry_A, geometry_B) function compareGeometry(geometry_A::GeometryOOC, geometry_B::GeometryOOC) check = true for j=1:length(geometry_A.container) if ~isequal(geometry_A.container[j].blocks[1].summary["GroupX"], geometry_B.container[j].blocks[1].summary["GroupX"]) || ~isequal(geometry_A.container[j].blocks[1].summary["GroupY"], geometry_B.container[j].blocks[1].summary["GroupY"]) || ~isequal(geometry_A.container[j].blocks[1].summary["SourceX"], geometry_B.container[j].blocks[1].summary["SourceX"]) || ~isequal(geometry_A.container[j].blocks[1].summary["SourceY"], geometry_B.container[j].blocks[1].summary["SourceY"]) || ~isequal(geometry_A.container[j].blocks[1].summary["dt"], geometry_B.container[j].blocks[1].summary["dt"]) check = false end end return check end ==(geometry_A::GeometryOOC, geometry_B::GeometryOOC) = compareGeometry(geometry_A, geometry_B) compareGeometry(geometry_A::GeometryOOC, geometry_B::Geometry) = true compareGeometry(geometry_A::Geometry, geometry_B::GeometryOOC) = true ########################################################################################################################################### for G in [GeometryOOC, GeometryIC] @eval function push!(G1::$G, G2::$G) for k in fieldnames($G) pushfield!(getfield(G1, k), getfield(G2, k)) end end end pushfield!(a::Array, b::Array) = append!(a, b) pushfield!(a, b) = nothing # Gets called by judiVector constructor to be sure that geometry is consistent with the data. # Data may be any of: Array, Array of Array, SeisBlock, SeisCon check_geom(geom::Geometry, data::Array{T}) where T = all([check_geom(geom[s], data[s]) for s=1:get_nsrc(geom)]) check_geom(geom::Geometry, data::Array{T}) where {T<:Number} = _check_geom(get_nt(geom, 1), size(data, 1)) && _check_geom(geom.nrec[1], size(data, 2)) function check_geom(geom::Geometry, data::SeisBlock) nt_segy = max(data.fileheader.bfh.ns, data.fileheader.bfh.nsOrig) get_nt(geom, 1) <= nt_segy || _geom_missmatch(get_nt(geom, 1), nt_segy) end function check_geom(geom::Geometry, data::SeisCon) for s = 1:get_nsrc(geom) fh = read_fileheader(data.blocks[s].file) nt_segy = max(fh.bfh.ns, fh.bfh.nsOrig) get_nt(geom, s) <= nt_segy || _geom_missmatch(get_nt(geom, s), nt_segy) end end _check_geom(nt::Integer, ns::Integer) = nt == ns || _geom_missmatch(nt, ns) _check_geom(nt::Integer, ns::Tuple{Integer, Integer}) = nt == ns[1] || nt == ns[2] || _geom_missmatch(nt, ns[1]) check_time(dt::Number, t::Number, segy::Bool=false) = (t/dt == div(t, dt, RoundNearest)) || throw(GeometryException("Recording time t=$(t) not divisible by sampling rate dt=$(dt)")) check_time(::Nothing, ::Nothing, segy::Bool=false) = segy || throw(GeometryException("Recording time `t` and sampling rate `dt` must be provided")) check_time(::Nothing, ::Number, segy::Bool=false) = segy || throw(GeometryException("Recording time `t` and sampling rate `dt` must be provided")) check_time(dt::AbstractVector, t::AbstractVector, segy::Bool=false) = check_time.(dt, t) _geom_missmatch(nt::Integer, ns::Integer) = throw(judiMultiSourceException("Geometry's number of samples doesn't match the data: $(nt), $(ns)")) ################################# Merge geometries ############################################################## allsame(x, val=first(x)) = all(y->y==val, x) as_coord_set(x::Vector{T}, y::T, z::Vector{T}) where T = OrderedSet(zip(x, z)) as_coord_set(x::Vector{T}, y::Vector{T}, z::Vector{T}) where T = OrderedSet(zip(x, y, z)) yloc(y::Vector{T}, ::Val{1}) where T<:Number = y[1] yloc(y::T, ::Val{1}) where T<:Number = y yloc(y, ::Val) = y _get_coords(G::Geometry, ny::Val) = begin gloc = Geometry(G); return tuple(gloc.xloc[1], yloc(gloc.yloc[1], ny), gloc.zloc[1]) end function as_coord_set(G::Geometry) @assert allsame(G.t) G0 = Geometry(G[1]) ny = Val(length(G0.yloc[1])) s = as_coord_set(_get_coords(G0, ny::Val)...) nsrc = get_nsrc(G) if nsrc > 1 map(i->union!(s, as_coord_set(_get_coords(G[i], ny::Val)...)), 2:nsrc) end sort!(s) return s end coords_from_set(S::OrderedSet{Tuple{T, T}}) where T = tuple([first.(S)], [[0f0]], [last.(S)]) coords_from_set(S::OrderedSet{Tuple{T, T, T}}) where T = tuple([first.(S)], [getindex.(S, 2)], [last.(S)]) coords_from_keys(S::Vector{Tuple{T, T}}) where T = tuple([first.(S)], [[0f0]], [last.(S)]) coords_from_keys(S::Vector{Tuple{T, T, T}}) where T = tuple([first.(S)], [getindex.(S, 2)], [last.(S)]) """ super_shot_geometry(Geometry) Merge all the sub-geometries `1:get_nsrc(Geometry)` into a single supershot geometry """ function super_shot_geometry(G::Geometry{T}) where T as_set = coords_from_set(as_coord_set(G)) return GeometryIC{T}(as_set..., [G.taxis[1]]) end ###################### reciprocity ############################### """ reciprocal_geom(sourceGeom, recGeom) Applies reciprocity to the par of geometries `sourceGeom` and `recGeom` where each source becomes a receiver and each receiver becomes a source. This method expects: - Both geometries to be In Core. If the geometries are OOC they will be converted to in core geometries - The metadata to be compatible. In details all the time sampling rates (dt) and recording times (t) must be the same - The source to be single point sources. This method will error if a simultaneous sources (multiple poisiton for a single source) are used. """ function reciprocal_geom(sGeom::GeometryIC{T}, rGeom::GeometryIC{T}) where T # The geometry need to have the same recording and sampling times @assert sGeom.t == rGeom.t @assert allsame(sGeom.t) # Make sure it's not simultaneous sources if !all(length(x) == 1 for x in sGeom.xloc) throw(GeometryException("Cannot apply reciprocity to simultaneous sources")) end # Curretnly only support geometry with all sources seeing the same receivers if !allsame(rGeom.xloc) throw(GeometryException("Currently expects all sources to see the same receivers (i.e OBNs)")) end # Reciprocal source geom xsrc = convertToCell(rGeom.xloc[1]) if length(rGeom.yloc[1]) > 1 ysrc = convertToCell(rGeom.yloc[1]) else ysrc = 0 .* xsrc end zsrc = convertToCell(rGeom.zloc[1]) sgeom = Geometry(xsrc, ysrc, zsrc; dt=dt(rGeom, 1), t=t(rGeom, 1)) # Reciprocal recc geom xrec = Vector{T}([x[1] for x in sGeom.xloc]) yrec = Vector{T}([x[1] for x in sGeom.yloc]) zrec = Vector{T}([x[1] for x in sGeom.zloc]) rgeom = Geometry(xrec, yrec, zrec; dt=dt(rGeom, 1), t=t(rGeom, 1), nsrc=length(xsrc)) return sgeom, rgeom end function reciprocal_geom(sGeom::Geometry, rGeom::Geometry) @warn "reciprocal_geom only supports in core geometries, converting" return reciprocal_geom(Geometry(sGeom), Geometry(rGeom)) end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
20277
# Model structure # Author: Philipp Witte, [email protected] # Date: January 2017 # Author Mathias Louboutin # Date: 2017-2022 # export Model, PhysicalParameter, get_dt, size, origin, spacing, nbl abstract type AbstractModel{T, N} end struct DiscreteGrid{T<:Real, N} n::NTuple{N, Int64} d::NTuple{N, <:T} o::NTuple{N, <:T} nb::Int64 # number of absorbing boundaries points on each side end size(G::DiscreteGrid) = G.n origin(G::DiscreteGrid) = G.o spacing(G::DiscreteGrid) = G.d nbl(G::DiscreteGrid) = G.nb size(G::DiscreteGrid, i::Int) = G.n[i] origin(G::DiscreteGrid, i::Int) = G.o[i] spacing(G::DiscreteGrid, i::Int) = G.d[i] ################################################################################################### # PhysicalParameter abstract vector """ PhysicalParameter n::NTuple{N, T} d::NTuple{N, Tf} o::NTuple{N, Tf} data::Union{Array, Number} PhysicalParameter structure for physical space parameter. `n`: number of gridpoints in (x,y,z) for 3D or (x,z) for 2D `d`: grid spacing in (x,y,z) or (x,z) (in meters) `o`: origin of coordinate system in (x,y,z) or (x,z) (in meters) `data`: the array of the parameter values of size n Constructor =========== A `PhysicalParameter` can be constructed in various ways but always require the origin `o` and grid spacing `d` that cannot be infered from the array. PhysicalParameter(v::Array{T}, d, o) where `v` is an n-dimensional array and n=size(v) PhysicalParameter(n, d, o; T=Float32) Creates a zero PhysicalParameter PhysicalParameter(v::Array{T}, A::PhysicalParameter{T, N}) where {T<:Real, N} Creates a PhysicalParameter from the Array `v` with n, d, o from `A` PhysicalParameter(v::Array{T, N}, n::NTuple{N, T}, d::NTuple{N, T}, o::Tuple) where `v` is a vector or nd-array that is reshaped into shape `n` PhysicalParameter(v::T, n::NTuple{N, T}, d::NTuple{N, T}, o::Tuple) Creates a constant (single number) PhyicalParameter """ mutable struct PhysicalParameter{T, N} <: DenseArray{T, N} n::NTuple{N, Int64} d::NTuple{N, T} o::NTuple{N, T} data::Union{Array{T, N}, T} PhysicalParameter(n::NTuple{N, <:Number}, d::NTuple{N, <:Number}, o::NTuple{N, <:Number}, data::Union{Array{T, N}, T}) where {T, N} = new{T, N}(Int.(n), T.(d), T.(o), data) end mutable struct PhysicalParameterException <: Exception msg :: String end PhysicalParameter(v::BitArray{N}, args...) where N = v PhysicalParameter(v::Array{Bool, N}, ::NTuple, ::NTuple) where N = v function PhysicalParameter(v::Array{T, N}, d::NTuple, o::NTuple) where {T<:Real, N} n = size(v) length(n) != length(o) && throw(PhysicalParameterException("Input array should be $(length(o))-dimensional")) return PhysicalParameter(n, d, o, v) end PhysicalParameter(n::NTuple{N}, d::NTuple{N}, o::NTuple{N}; DT::Type{dT}=eltype(d)) where {dT<:Real, N} = PhysicalParameter(n, d, o, zeros(dT, n)) PhysicalParameter(v::Array{T, N}, A::PhysicalParameter{ADT, N}) where {T<:Real, ADT<:Real, N} = PhysicalParameter(A.n, A.d, A.o, reshape(v, A.n)) function PhysicalParameter(v::Array{T, N1}, n::NTuple{N, Int}, d::NTuple{N, T}, o::NTuple{N, T}) where {T<:Real, N, N1} length(v) != prod(n) && throw(PhysicalParameterException("Incompatible number of element in input $(length(v)) with n=$(n)")) N1 == 1 && (v = reshape(v, n)) return PhysicalParameter(n, d, o, v) end PhysicalParameter(v::Real, n::NTuple{N}, d::NTuple{N}, o::NTuple{N}) where {N} = PhysicalParameter(n, d, o, v) PhysicalParameter(v::Integer, n::NTuple{N}, d::NTuple{N}, o::NTuple{N}) where {N} = PhysicalParameter(n, d, o, Float32.(v)) PhysicalParameter(v::Array{T, N}, n::NTuple{N}, d::NTuple{N}, o::NTuple{N}) where {T<:Real, N} = PhysicalParameter(n, d, o, v) PhysicalParameter(p::PhysicalParameter{T, N}, ::NTuple{N, Int}, ::NTuple{N, T}, ::NTuple{N, T}) where {T<:Real, N} = p PhysicalParameter(p::PhysicalParameter{T, N}) where {T<:Real, N} = p PhysicalParameter(p::PhysicalParameter{T, N}, v::Array{T, Nv}) where {T<:Real, N, Nv} = PhysicalParameter(p.n, p.d, p.o, reshape(v, p.n)) # transpose and such..... conj(x::PhysicalParameter{T, N}) where {T<:Real, N} = x transpose(x::PhysicalParameter{T, N}) where {T<:Real, N} = PhysicalParameter(x.n[N:-1:1], x.d[N:-1:1], x.o[N:-1:1], permutedims(x.data, N:-1:1)) adjoint(x::PhysicalParameter{T, N}) where {T<:Real, N} = transpose(x) # Basic overloads size(A::PhysicalParameter{T, N}) where {T<:Real, N} = A.n length(A::PhysicalParameter{T, N}) where {T<:Real, N} = prod(A.n) function norm(A::PhysicalParameter{T, N}, order::Real=2) where {T<:Real, N} return norm(vec(A.data), order) end dot(A::PhysicalParameter{T, N}, B::PhysicalParameter{T, N}) where {T<:Real, N} = dot(vec(A.data), vec(B.data)) dot(A::PhysicalParameter{T, N}, B::Array{T, N}) where {T<:Real, N} = dot(vec(A.data), vec(B)) dot(A::Array{T, N}, B::PhysicalParameter{T, N}) where {T<:Real, N} = dot(vec(A), vec(B.data)) _repr(A::PhysicalParameter{T, N}) where {T<:Real, N} = "$(typeof(A)) of size $(A.n) with origin $(A.o) and spacing $(A.d)" display(A::PhysicalParameter{T, N}) where {T<:Real, N} = println(_repr(A)) show(io::IO, A::PhysicalParameter{T, N}) where {T<:Real, N} = print(io, _repr(A)) summary(io::IO, A::PhysicalParameter{T, N}) where {T<:Real, N} = print(io, _repr(A)) showarg(io::IO, A::PhysicalParameter, toplevel) = print(io, _repr(A)) show(io::IO, ::MIME{Symbol("text/plain")}, A::PhysicalParameter{T, N}) where {T<:Real, N} = println(io, _repr(A)) # Indexing firstindex(A::PhysicalParameter{T, N}) where {T<:Real, N} = 1 lastindex(A::PhysicalParameter{T, N}) where {T<:Real, N} = length(A) lastindex(A::PhysicalParameter{T, N}, dim::Int) where {T<:Real, N} = A.n[dim] function promote_shape(p::PhysicalParameter{T, N}, A::Array{T, Na}) where {T, N, Na} (size(A) != p.n && N>1) && return promote_shape(p.data, A) (length(A) == prod(p.n) && N==1) && return size(A) return promote_shape(A, A) end promote_shape(A::Array{T, Na}, p::PhysicalParameter{T, N}) where {T<:Real, N, Na} = promote_shape(p, A) reshape(p::PhysicalParameter{T, N}, n::Tuple{Vararg{Int64,N}}) where {T<:Real, N} = (n == p.n ? p : reshape(p.data, n)) reshape(p::PhysicalParameter, pr::PhysicalParameter) = (p.n == pr.n ? p : throw(ArgumentError("Incompatible PhysicalParameter sizes ($(p.n), $(po.n))"))) dotview(m::PhysicalParameter, i) = Base.dotview(m.data, i) getindex(A::PhysicalParameter{T, N}, i::Int) where {T<:Real, N} = A.data[i] getindex(A::PhysicalParameter{T, N}, ::Colon) where {T<:Real, N} = A.data[:] elsize(A::PhysicalParameter) = elsize(A.data) get_step(r::StepRange) = r.step get_step(r) = 1 function getindex(A::PhysicalParameter{T, N}, I::Vararg{Union{Int, BitArray, Function, StepRange{Int}, UnitRange{Int}}, Ni}) where {N, Ni, T<:Real} new_v = getindex(A.data, I...) length(size(new_v)) != length(A.n) && (return new_v) s = [i == Colon() ? 0 : i[1]-1 for i=I] st = [get_step(i) for i=I] new_o = [ao+i*d for (ao, i, d)=zip(A.o, s, A.d)] new_d = [d*s for (d, s)=zip(A.d, st)] PhysicalParameter(size(new_v), tuple(new_d...), tuple(new_o...), new_v) end setindex!(A::PhysicalParameter{T, N}, v, I::Vararg{Union{Int, Function, UnitRange{Int}}, Ni}) where {T<:Real, N, Ni} = setindex!(A.data, v, I...) setindex!(A::PhysicalParameter{T, N}, v, i::Int) where {T<:Real, N} = (A.data[i] = v) # Constructiors by copy similar(x::PhysicalParameter{T, N}) where {T<:Real, N} = PhysicalParameter(x.n, x.d, x.o, fill!(similar(x.data), 0)) function similar(p::PhysicalParameter{T, N}, ::Type{nT}, s::AbstractSize) where {T, N, nT} nn = tuple(last.(sort(collect(s.dims), by = x->x[1]))...) return PhysicalParameter(nn, p.d, p.o, zeros(nT, nn)) end copy(x::PhysicalParameter{T, N}) where {T<:Real, N} = PhysicalParameter(x.n, x.d, x.o, copy(x.data)) unsafe_convert(::Type{Ptr{T}}, p::PhysicalParameter{T, N}) where {T<:Real, N} = unsafe_convert(Ptr{T}, p.data) Base.Vector{T}(m::PhysicalParameter) where T = Vector{T}(m.data[:]) # Equality ==(A::PhysicalParameter{T, N}, B::PhysicalParameter{T, N}) where {T<:Real, N} = (A.data == B.data && A.o == B.o && A.d == B.d) isapprox(A::PhysicalParameter{T, N}, B::PhysicalParameter{T, N}; kwargs...) where {T<:Real, N} = (isapprox(A.data, B.data) && A.o == B.o && A.d == B.d) isapprox(A::PhysicalParameter{T, N}, B::AbstractArray{T, N}; kwargs...) where {T<:Real, N} = isapprox(A.data, B) isapprox(A::AbstractArray{T, N}, B::PhysicalParameter{T, N}; kwargs...) where {T<:Real, N} = isapprox(A, B.data) # # Arithmetic operations compare(A::PhysicalParameter{T, N}, B::PhysicalParameter{T, N}) where {T<:Real, N} = (A.o == B.o && A.d == B.d && A.n == B.n) function combine(op, A::PhysicalParameter{T, N}, B::PhysicalParameter{T, N}) where {T<:Real, N} A.d == B.d || throw(PhysicalParameterException("Incompatible grids: ($(A.d), $(B.d))")) o = min.(A.o, B.o) sa = floor.(Int, (A.o .- o) ./ A.d) .+ 1 ea = sa .+ A.n .- 1 sb = floor.(Int, (B.o .- o) ./ B.d) .+ 1 eb = sb .+ B.n .- 1 mn = max.(ea, eb) ia = [s:e for (s, e) in zip(sa, ea)] ib = [s:e for (s, e) in zip(sb, eb)] if isnothing(op) @assert A.n == mn A.data[ib...] .= B.data return nothing else out = zeros(T, mn) out[ia...] .= A.data broadcast!(op, view(out, ib...), view(out, ib...), B.data) return PhysicalParameter(mn, A.d, o, out) end end combine!(A::PhysicalParameter{T, N}, B::PhysicalParameter{T, N}) where {T<:Real, N} = combine(nothing, A, B) for op in [:+, :-, :*, :/] @eval function $(op)(A::PhysicalParameter{T, N}, B::PhysicalParameter{T, N}) where {T<:Real, N} if compare(A, B) return PhysicalParameter(broadcast($(op), A.data, B.data), A) elseif A.d == B.d # same grid but difference origin/shape, merging return combine($(op), A, B) else throw(PhysicalParameterException("Incompatible grids: ($(A.d), $(B.d))")) end end @eval $(op)(A::PhysicalParameter{T, N}, B::T2) where {T<:Real, T2<:Number, N} = PhysicalParameter(broadcast($(op), A.data, T(B)), A) @eval $(op)(A::T2, B::PhysicalParameter{T, N}) where {T<:Real, T2<:Number, N} = PhysicalParameter(broadcast($(op), T(A), B.data), B) end function *(A::Union{joMatrix, joLinearFunction, joLinearOperator, joCoreBlock}, p::PhysicalParameter{RDT, N}) where {RDT<:Real, N} @warn "JOLI linear operator, returning julia Array" return A*vec(p.data) end # Brodacsting BroadcastStyle(::Type{<:PhysicalParameter}) = Broadcast.ArrayStyle{PhysicalParameter}() function similar(bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{PhysicalParameter}}, ::Type{ElType}) where ElType # Scan the inputs A = find_bc(bc, PhysicalParameter) # Use the char field of A to create the output newT = ElType <: Nothing ? eltype(A) : ElType Ad = zeros(newT, axes(A.data)) PhysicalParameter(Ad, A.d, A.o) end similar(bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{PhysicalParameter}}) = similar(bc, nothing) function materialize!(A::PhysicalParameter{T, N}, ev::PhysicalParameter{T, N}) where {T<:Real, N} if compare(A, ev) A.data .= ev.data else A.n = ev.n A.d = ev.d A.o = ev.o A.data = copy(ev.data) end nothing end materialize!(A::PhysicalParameter{T, N}, B::Broadcast.Broadcasted{Broadcast.DefaultArrayStyle{PhysicalParameter}}) where {T<:Real, N} = materialize!(A, B.f(B.args...)) materialize!(A::PhysicalParameter{T, N}, B::Broadcast.Broadcasted{Broadcast.DefaultArrayStyle{Na}}) where {T<:Real, N, Na} = materialize!(A.data, reshape(materialize(B), A.n)) materialize!(A::AbstractArray{T, N}, B::Broadcast.Broadcasted{Broadcast.ArrayStyle{PhysicalParameter}}) where {T<:Real, N} = materialize!(A, reshape(materialize(B).data, size(A))) for op in [:+, :-, :*, :/, :\] @eval begin broadcasted(::typeof($op), A::PhysicalParameter{T, N}, B::DenseVector{T}) where {T<:Real, N} = PhysicalParameter(A.n, A.d, A.o, materialize(broadcasted($(op), A.data, reshape(B, A.n)))) broadcasted(::typeof($op), B::DenseVector{T}, A::PhysicalParameter{T, N}) where {T<:Real, N} = PhysicalParameter(A.n, A.d, A.o, materialize(broadcasted($(op), reshape(B, A.n), A.data))) broadcasted(::typeof($op), A::PhysicalParameter{T, N}, B::DenseArray{T, N}) where {T<:Real, N} = PhysicalParameter(A.n, A.d, A.o, materialize(broadcasted($(op), A.data, B))) broadcasted(::typeof($op), B::DenseArray{T, N}, A::PhysicalParameter{T, N}) where {T<:Real, N} = PhysicalParameter(A.n, A.d, A.o, materialize(broadcasted($(op), B, A.data))) broadcasted(::typeof($op), A::PhysicalParameter{T, N}, B::PhysicalParameter{T, N}) where {T<:Real, N} = $(op)(A, B) broadcasted(::typeof($op), A::PhysicalParameter{T, N}, B::T2) where {T<:Real, T2<:Number, N} = PhysicalParameter(broadcast($(op), A.data, T(B)), A) broadcasted(::typeof($op), A::T2, B::PhysicalParameter{T, N}) where {T<:Real, T2<:Number, N} = PhysicalParameter(broadcast($(op), T(A), B.data), B) end end # For ploting NpyArray(p::PhysicalParameter{T, N}, revdims::Bool) where {T<:Real, N} = NpyArray(p.data, revdims) ################################################################################################### const ModelParam{N} = Union{<:Pdtypes, PhysicalParameter{<:Pdtypes, N}} # Acoustic struct IsoModel{T, N} <: AbstractModel{T, N} G::DiscreteGrid{T, N} m::ModelParam{N} rho::ModelParam{N} end # VTI/TTI struct TTIModel{T, N} <: AbstractModel{T, N} G::DiscreteGrid{T, N} m::ModelParam{N} rho::ModelParam{N} epsilon::ModelParam{N} delta::ModelParam{N} theta::ModelParam{N} phi::ModelParam{N} end # Elastic struct IsoElModel{T, N} <: AbstractModel{T, N} G::DiscreteGrid{T, N} lam::ModelParam{N} mu::ModelParam{N} b::ModelParam{N} end # Visco-acoustic struct ViscIsoModel{T, N} <: AbstractModel{T, N} G::DiscreteGrid{T, N} m::ModelParam{N} rho::ModelParam{N} qp::ModelParam{N} end _params(m::IsoModel) = ((:m, m.m), (:rho, m.rho)) _params(m::TTIModel) = ((:m, m.m), (:rho, m.rho), (:epsilon, m.epsilon), (:delta, m.delta), (:theta, m.theta), (:phi, m.phi)) _params(m::IsoElModel) = ((:lam, m.lam), (:mu, m.mu), (:b, m.b)) _params(m::ViscIsoModel) = ((:m, m.m), (:rho, m.rho), (:qp, m.qp)) _mparams(m::AbstractModel) = first.(_params(m)) ################################################################################################### # Constructors _scalar(::Nothing, ::Type{T}, def=1) where T = T(def) _scalar(v::Number, ::Type{T}, def=1) where T = T(v) """ Model(n, d, o, m; epsilon=nothing, delta=nothing, theta=nothing, phi=nothing, rho=nothing, qp=nothing, vs=nothing, nb=40) The parameters `n`, `d`, `o` and `m` are mandatory, whith `nb` and other physical parameters being optional input arguments. where `m`: velocity model in slowness squared (s^2/km^2) `epsilon`: Epsilon thomsen parameter ( between -1 and 1) `delta`: Delta thomsen parameter ( between -1 and 1 and delta < epsilon) `theta`: Anisotopy dip in radian `phi`: Anisotropy asymuth in radian `rho`: density (g / m^3) `qp`: P-wave attenuation for visco-acoustic models `vs`: S-wave velocity for elastic models. `nb`: Number of ABC points """ function Model(d, o, m::Array{mT, N}; epsilon=nothing, delta=nothing, theta=nothing, phi=nothing, rho=nothing, qp=nothing, vs=nothing, nb=40) where {mT<:Real, N} # Currently force single precision m = as_Pdtype(m) T = Float32 # Convert dimension to internal types n = size(m) d = tuple(Float32.(d)...) o = tuple(Float32.(o)...) G = DiscreteGrid{T, N}(n, d, o, nb) size(m) == n || throw(ArgumentError("Grid size $n and squared slowness size $(size(m)) don't match")) # Elastic if !isnothing(vs) rho = isa(rho, Array) ? rho : _scalar(rho, T) if any(!isnothing(p) for p in [epsilon, delta, theta, phi]) @warn "Thomsen parameters no supported for elastic (vs) ignoring them" end lambda = PhysicalParameter(as_Pdtype((m.^(-1) .- T(2) .* vs.^2) .* rho), n, d, o) mu = PhysicalParameter(as_Pdtype(vs.^2 .* rho), n, d, o) b = isa(rho, Array) ? PhysicalParameter(as_Pdtype(1 ./ rho), n, d, o) : _scalar(rho, T) return IsoElModel{T, N}(G, lambda, mu, b) end ## Visco if !isnothing(qp) if any(!isnothing(p) for p in [epsilon, delta, theta, phi]) @warn "Thomsen parameters no supported for elastic (vs) ignoring them" end qp = isa(qp, Array) ? PhysicalParameter(as_Pdtype(qp), n, d, o) : _scalar(qp, T) m = PhysicalParameter(m, n, d, o) rho = isa(rho, Array) ? PhysicalParameter(as_Pdtype(rho), n, d, o) : _scalar(rho, T) return ViscIsoModel{T, N}(G, m, rho, qp) end ## TTI if !isnothing(epsilon) || !isnothing(delta) || !isnothing(theta) || !isnothing(phi) if any(!isnothing(p) for p in [vs, qp]) @warn "Elastic (vs) and attenuation (qp) not supported for TTI/VTI" end m = PhysicalParameter(m, n, d, o) rho = isa(rho, Array) ? PhysicalParameter(as_Pdtype(rho), n, d, o) : _scalar(rho, T) epsilon = isa(epsilon, Array) ? PhysicalParameter(as_Pdtype(epsilon), n, d, o) : _scalar(epsilon, T, 0) delta = isa(delta, Array) ? PhysicalParameter(as_Pdtype(delta), n, d, o) : _scalar(delta, T, 0) # For safety remove delta values unsupported (delta > epsilon) _clip_delta!(delta, epsilon) theta = isa(theta, Array) ? PhysicalParameter(as_Pdtype(theta), n, d, o) : _scalar(theta, T, 0) phi = isa(phi, Array) ? PhysicalParameter(as_Pdtype(phi), n, d, o) : _scalar(phi, T, 0) return TTIModel{T, N}(G, m, rho, epsilon, delta, theta, phi) end # None of the advanced models, return isotropic acoustic m = PhysicalParameter(m, n, d, o) rho = isa(rho, Array) ? PhysicalParameter(as_Pdtype(rho), n, d, o) : _scalar(rho, T) return IsoModel{T, N}(G, m, rho) end as_Pdtype(x::Array{T, N}) where {T<:Pdtypes, N} = x as_Pdtype(x::Array{T, N}) where {T, N} = convert(Array{Float32, N}, x) Model(n, d, o, m::Array, rho::Array; nb=40) = Model(d, o, reshape(m, n...); rho=reshape(rho, n...), nb=nb) Model(n, d, o, m::Array, rho::Array, qp::Array; nb=40) = Model(d, o, reshape(m, n...); rho=reshape(rho, n...), qp=reshape(qp, n...), nb=nb) Model(n, d, o, m::Array; kw...) = Model(d, o, reshape(m, n...); kw...) size(m::MT) where {MT<:AbstractModel} = size(m.G) origin(m::MT) where {MT<:AbstractModel} = origin(m.G) spacing(m::MT) where {MT<:AbstractModel} = spacing(m.G) nbl(m::MT) where {MT<:AbstractModel} = nbl(m.G) size(m::MT, i::Int) where {MT<:AbstractModel} = size(m.G, i) origin(m::MT, i::Int) where {MT<:AbstractModel} = origin(m.G, i) spacing(m::MT, i::Int) where {MT<:AbstractModel} = spacing(m.G, i) eltype(::AbstractModel{T, N}) where {T, N} = T get_dt(m::AbstractModel; dt=nothing) = calculate_dt(m; dt=dt) similar(::PhysicalParameter{T, N}, m::AbstractModel) where {T<:Real, N} = PhysicalParameter(size(m), spacing(m), origin(m); DT=T) similar(x::Array, m::AbstractModel) = similar(x, size(m)) ndims(m::AbstractModel{T, N}) where {T, N} = N _repr(m::AbstractModel) = "Model (n=$(size(m)), d=$(spacing(m)), o=$(origin(m))) with parameters $(_mparams(m))" display(m::AbstractModel) = println(_repr(m)) show(io::IO, m::AbstractModel) = print(io, _repr(m)) show(io::IO, ::MIME{Symbol("text/plain")}, m::AbstractModel) = print(io, _repr(m)) # Pad gradient if aperture doesn't match full domain _project_to_physical_domain(p, ::Any) = p function _project_to_physical_domain(p::PhysicalParameter, model::AbstractModel) size(p) == size(model) && (return p) pp = similar(p, model) pp .+= p return pp end # Utils _clip_delta!(::T, epsilon) where {T<:Number} = nothing _clip_delta!(delta::PhysicalParameter{T}, epsilon::T) where {T<:Number} = delta.data[delta.data .>= epsilon] .= T(.99) * epsilon _clip_delta!(delta::PhysicalParameter{T}, epsilon::PhysicalParameter{T}) where {T<:Number} = delta.data[delta.data .>= epsilon.data] .= T(.99) * epsilon[delta.data .>= epsilon.data]
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
5324
# Options structure # Author: Philipp Witte, [email protected] # Date: May 2017 # export Options, JUDIOptions # Object for velocity/slowness models mutable struct JUDIOptions space_order::Int64 free_surface::Bool limit_m::Bool buffer_size::Float32 save_data_to_disk::Bool file_path::String file_name::String sum_padding::Bool optimal_checkpointing::Bool frequencies::Array IC::String subsampling_factor::Int64 dft_subsampling_factor::Int64 return_array::Bool dt_comp::Union{Float32, Nothing} f0::Float32 end """ JUDIOptions space_order::Integer free_surface::Bool limit_m::Bool buffer_size::AbstractFloat save_rate::AbstractFloat save_data_to_disk::Bool file_path::String file_name::String sum_padding::Bool optimal_checkpointing::Bool frequencies::Array IC::String subsampling_factor::Integer dft_subsampling_factor::Integer return_array::Bool dt_comp::Real f0::Real Options structure for seismic modeling. `space_order`: finite difference space order for wave equation (default is 8, needs to be multiple of 4) `free_surface`: set to `true` to enable a free surface boundary condition. `limit_m`: for 3D modeling, limit modeling domain to area with receivers (saves memory) `buffer_size`: if `limit_m=true`, define buffer area on each side of modeling domain (in meters) `save_data_to_disk`: if `true`, saves shot records as separate SEG-Y files `file_path`: path to directory where data is saved `file_name`: shot records will be saved as specified file name plus its source coordinates `sum_padding`: when removing the padding area of the gradient, sum into boundary rows/columns for true adjoints `optimal_checkpointing`: instead of saving the forward wavefield, recompute it using optimal checkpointing `frequencies`: calculate the FWI/LS-RTM gradient in the frequency domain for a given set of frequencies `subsampling_factor`: compute forward wavefield on a time axis that is reduced by a given factor (default is 1) `dft_subsampling_factor`: compute on-the-fly DFTs on a time axis that is reduced by a given factor (default is 1) `IC`: Imaging condition. Options are 'as, isic, fwi' with "as" for adjoint state, isic for the inverse scattering imaging condition and FWI for the complement of isic (i.e isic + fwi = as) `isic`: Inverse scattering imaging condition. Deprecated, use `IC="isic"` instead. `return_array`: return data from nonlinear/linear modeling as a plain Julia array. `dt_comp`: overwrite automatically computed computational time step with this value. `f0`: define peak frequency. Constructor ========== All arguments are optional keyword arguments with the following default values: Options(;space_order=8, free_surface=false, limit_m=false, buffer_size=1e3, save_data_to_disk=false, file_path="", file_name="shot", sum_padding=false, optimal_checkpointing=false, num_checkpoints=nothing, checkpoints_maxmem=nothing, frequencies=[], isic=false, subsampling_factor=1, dft_subsampling_factor=1, return_array=false, dt_comp=nothing, f0=0.015f0) """ function Options(;space_order=8, free_surface=false, limit_m=false, buffer_size=1e3, save_data_to_disk=false, file_path="", file_name="shot", sum_padding=false, optimal_checkpointing=false, frequencies=[], subsampling_factor=1, dft_subsampling_factor=1, return_array=false, dt_comp=nothing, f0=0.015f0, IC="as", kw...) ic = imcond(get(kw, :isic, false), IC) if optimal_checkpointing && get(ENV, "DEVITO_DECOUPLER", 0) != 0 @warn "Optimal checkpointing is not supported with the Decoupler, disabling" optimal_checkpointing = false end return JUDIOptions(space_order, free_surface, limit_m, buffer_size, save_data_to_disk, file_path, file_name, sum_padding, optimal_checkpointing, frequencies, ic, subsampling_factor, dft_subsampling_factor, return_array, dt_comp, f0) end JUDIOptions(;kw...) = Options(kw...) update!(::JUDIOptions, ::Nothing) = nothing function update!(O::JUDIOptions, other::JUDIOptions) for f in fieldnames(JUDIOptions) setfield!(O, f, getfield(other, f)) end end function getindex(options::JUDIOptions, srcnum) if isempty(options.frequencies) return options else opt_out = deepcopy(options) floc = options.frequencies[srcnum] typeof(floc) <: Array && (opt_out.frequencies = floc) return opt_out end end subsample(options::JUDIOptions, srcnum) = getindex(options, srcnum) function imcond(isic::Bool, IC::String) if isic Base.depwarn("Deprecared isic argument use IC=\"isic\" ", :Options; force = true) return "isic" end return lowercase(IC) end function Base.show(io::IO, options::JUDIOptions) println(io, "JUDI Options : \n") for f in fieldnames(JUDIOptions) println(io, @sprintf("%-25s : %10s", f, getfield(options, f))) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
9374
export subsample ############################################################################################################################ # Base multi source abstract type abstract type judiMultiSourceVector{T} <: AbstractVector{T} end mutable struct judiMultiSourceException <: Exception msg :: String end display(ms::judiMultiSourceVector) = println("$(string(typeof(ms))) with $(ms.nsrc) sources") show(io::IO, ms::judiMultiSourceVector) = print(io, "$(string(typeof(ms))) with $(ms.nsrc) sources") showarg(io::IO, ms::judiMultiSourceVector, toplevel) = print(io, "$(string(typeof(ms))) with $(ms.nsrc) sources") summary(io::IO, ms::judiMultiSourceVector) = print(io, string(typeof(ms))) show(io::IO, ::MIME{Symbol("text/plain")}, ms::judiMultiSourceVector) = println(io, "$(typeof(ms)) with $(ms.nsrc) sources") # Size and type eltype(::judiMultiSourceVector{T}) where T = T size(jv::judiMultiSourceVector) = (jv.nsrc,) length(jv::judiMultiSourceVector{T}) where {T} = sum([length(jv.data[i]) for i=1:jv.nsrc]) # Comparison isequal(ms1::judiMultiSourceVector, ms2::judiMultiSourceVector) = ms1 == ms2 ==(ms1::judiMultiSourceVector, ms2::judiMultiSourceVector) = all(getfield(ms1, s) == getfield(ms2, s) for s in fieldnames(typeof(ms1))) isapprox(x::judiMultiSourceVector, y::judiMultiSourceVector; rtol::AbstractFloat=sqrt(eps()), atol::AbstractFloat=0.0) = all(isapprox(getfield(x, f), getfield(y, f); rtol=rtol, atol=atol) for f in fieldnames(typeof(x))) check_compat(ms::Vararg{judiMultiSourceVector, N}) where N = true check_compat(x::Number, ms::judiMultiSourceVector) = true check_compat(ms::judiMultiSourceVector, x::Number) = true # Copy copyto!(ms::judiMultiSourceVector, a::Vector{Array{T, N}}) where {T, N} = copyto!(ms.data, a) copyto!(a::Vector{Array{T, N}}, ms::judiMultiSourceVector) where {T, N} = copyto!(a, ms.data) copy(ms::judiMultiSourceVector{T}) where {T} = begin y = zero(T, ms); y.data = deepcopy(ms.data); y end deepcopy(ms::judiMultiSourceVector{T}) where {T} = copy(ms) unsafe_convert(::Type{Ptr{T}}, msv::judiMultiSourceVector{T}) where {T} = unsafe_convert(Ptr{T}, msv.data) # indexing IndexStyle(::Type{<:judiMultiSourceVector}) = IndexLinear() setindex!(ms::judiMultiSourceVector{T}, v::Array{T, N}, i::Integer) where {T, N} = begin ms.data[i] = v; nothing end getindex(ms::judiMultiSourceVector{T}, i::Integer) where {T} = i > ms.nsrc ? 0 : ms[i:i] getindex(ms::judiMultiSourceVector{T}, ::Colon) where {T} = vec(ms) firstindex(ms::judiMultiSourceVector) = 1 lastindex(ms::judiMultiSourceVector) = ms.nsrc iterate(S::judiMultiSourceVector, state::Integer=1) = state > S.nsrc ? nothing : (S[state], state+1) # Backward compat subsample subsample(ms::judiMultiSourceVector, i) = getindex(ms, i) zero(::Type{T}, x::judiMultiSourceVector) where T = throw(judiMultiSourceException("$(typeof(x)) does not implement zero copy zero(::Type{T}, x)")) similar(x::judiMultiSourceVector{T}) where T = zero(T, x) similar(x::judiMultiSourceVector, nsrc::Integer) = nsrc < x.nsrc ? zero(eltype(ET), x; nsrc=nsrc) : zero(eltype(ET), x) similar(x::judiMultiSourceVector, ::Type{ET}) where ET = zero(eltype(ET), x) similar(x::judiMultiSourceVector, ::Type{ET}, dims::AbstractUnitRange) where ET = similar(x, ET) similar(x::judiMultiSourceVector, ::Type{ET}, nsrc::Integer) where ET = nsrc <= x.nsrc ? zero(eltype(ET), x; nsrc=nsrc) : similar(x, ET) similar(x::judiMultiSourceVector, ::Type{ET}, dims::AbstractSize) where ET = similar(x, ET) jo_convert(::Type{Array{T, N}}, v::judiMultiSourceVector, B::Bool) where {T, N} = jo_convert(T, v, B) fill!(x::judiMultiSourceVector, val) = fill!.(x.data, val) sum(x::judiMultiSourceVector) = sum(sum(x.data)) isfinite(v::judiMultiSourceVector) = all(all(isfinite.(v.data[i])) for i=1:v.nsrc) conj(A::judiMultiSourceVector{vDT}) where vDT = A transpose(A::judiMultiSourceVector{vDT}) where vDT = A adjoint(A::judiMultiSourceVector{vDT}) where vDT = A maximum(a::judiMultiSourceVector{avDT}) where avDT = max([maximum(a.data[i]) for i=1:a.nsrc]...) minimum(a::judiMultiSourceVector{avDT}) where avDT = min([minimum(a.data[i]) for i=1:a.nsrc]...) vec(x::judiMultiSourceVector) = vcat(vec.(x.data)...) time_sampling(ms::judiMultiSourceVector) = [1 for i=1:ms.nsrc] reshape(ms::judiMultiSourceVector, dims::Dims{N}) where N = reshape(vec(ms), dims) ############################################################################################################################ # Linear algebra `*` (msv::judiMultiSourceVector{mT})(x::DenseArray{T}) where {mT, T<:Number} = x (msv::judiMultiSourceVector{mT})(x::AbstractVector{T}) where {mT, T<:Number} = x (msv::judiMultiSourceVector{T})(x::judiMultiSourceVector{T}) where {T<:Number} = x (msv::judiMultiSourceVector{mT})(x::AbstractVector{T}) where {mT, T<:Array} = begin y = deepcopy(msv); y.data .= x; return y end function *(J::joAbstractLinearOperator, x::judiMultiSourceVector{vDT}) where vDT outvec = try J.fop(x) catch; J*vec(x) end outdata = try reshape(outvec, size(x.data[1]), x.nsrc) catch; outvec end return x(outdata) end function *(J::joCoreBlock, x::judiMultiSourceVector{vDT}) where vDT outvec = vcat([J.fop[i]*x for i=1:J.l]...) outdata = try reshape(outvec, size(x.data[1]), J.l*x.nsrc); catch; outvec end return x(outdata) end function *(M::Matrix{vDT}, x::judiMultiSourceVector{vDT}) where vDT if size(M, 2) == x.nsrc return simsource(M, x) end # Not a per source matrix, reverting to standard matvec outvec = M*vec(x) outdata = try reshape(outvec, size(x.data[1]), x.nsrc) catch; outvec end return x(outdata) end # Propagation input make_input(ms::judiMultiSourceVector) = throw(judiMultiSourceException("$(typeof(ms)) must implement `make_input(ms, dt)` for propagation")) make_input(a::Array) = a as_src(ms::judiMultiSourceVector{T}) where T = ms as_src(p::AbstractVector{T}) where T = p as_src(p) = vec(p) ############################################################################################################################ # Linear algebra norm/abs/cat... function norm(a::judiMultiSourceVector{T}, p::Real=2) where T if p == Inf return maximum([norm(a.data[i], p) for i=1:a.nsrc]) end x = 0.f0 dt = time_sampling(a) for j=1:a.nsrc x += dt[j] * norm(a.data[j], p)^p end return T(x^(1.f0/p)) end # inner product function dot(a::judiMultiSourceVector{T}, b::judiMultiSourceVector{T}) where T # Dot product for data containers size(a) == size(b) || throw(judiMultiSourceException("dimension mismatch: $(size(a)) != $(size(b))")) dotprod = 0f0 dt = time_sampling(a) for j=1:a.nsrc dotprod += dt[j] * dot(a.data[j], b.data[j]) end return T(dotprod) end dot(a::judiMultiSourceVector{T}, b::Array{T}) where T = dot(vec(a), vec(b)) dot(a::Array{T}, b::judiMultiSourceVector{T}) where T = dot(b, a) # abs function abs(a::judiMultiSourceVector{T}) where T b = deepcopy(a) for j=1:a.nsrc b.data[j] = abs.(a.data[j]) end return b end # vcat vcat(a::Array{<:judiMultiSourceVector, 1}) = vcat(a...) function vcat(ai::Vararg{T, N}) where {T<:judiMultiSourceVector, N} N == 1 && (return ai[1]) N > 2 && (return vcat(ai[1], vcat(ai[2:end]...))) a, b = ai res = deepcopy(a) push!(res, b) return res end # Combine as simsource function simsource(M::Matrix{T}, x::judiMultiSourceVector{T}) where T nout = size(M, 1) simmsv = zero(T, x; nsrc=nout) for so = 1:nout simmsv.data[so] = mapreduce((x, y)-> x*y, +, M[so, :], x.data) end return simmsv end ############################################################################################################################ # Diff/cumsum function cumsum(x::judiMultiSourceVector;dims=1) y = deepcopy(x) cumsum!(y, x; dims=dims) return y end function cumsum!(y::judiMultiSourceVector, x::judiMultiSourceVector;dims=1) dims == 1 || dims == 2 || throw(judiMultiSourceException("Dimension $(dims) is out of range for a 2D array")) h = dims == 1 ? time_sampling(x) : [1f0 for i=1:x.nsrc] # receiver dimension is non-dimensional for i = 1:x.nsrc cumsum!(y.data[i], x.data[i], dims=dims) lmul!(h[i], y.data[i]) end return y end function diff(x::judiMultiSourceVector; dims=1) # note that this is not the same as default diff in julia, the first entry stays in the diff result dims == 1 || dims == 2 || throw(judiMultiSourceException("Dimension $(dims) is out of range for a 2D array")) y = 1f0 * x # receiver dimension is non-dimensional h = dims == 1 ? time_sampling(x) : [1f0 for i=1:x.nsrc] for i = 1:x.nsrc n = size(y.data[i],dims) selectdim(y.data[i], dims, 2:n) .-= selectdim(y.data[i], dims, 1:n-1) lmul!(1 / h[i], y.data[i]) end return y end ############################################################################################################################ # Type conversions tof32(x::Number) = [Float32(x)] tof32(x::Array{T, N}) where {N, T<:Real} = T==Float32 ? x : Float32.(x) tof32(x::Array{Array{T, N}, 1}) where {N, T<:Real} = T==Float32 ? x : tof32.(x) tof32(x::Vector{Any}) = try Float32.(x) catch e tof32.(x) end tof32(x::T) where {T<:StepRangeLen} = convert(Vector{Float32}, x) tof32(x::Vector{<:StepRangeLen}) = tof32.(x)
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
3321
BroadcastStyle(::Type{<:judiMultiSourceVector}) = ArrayStyle{judiMultiSourceVector}() function similar(bc::Broadcast.Broadcasted{ArrayStyle{judiMultiSourceVector}}, ::Type{ElType}) where ElType # Scan the inputs A = find_bc(bc, judiMultiSourceVector) return similar(A, ElType) end "`A = find_pm(As)` returns the first PhysicalParameter among the arguments." find_bc(bc::Base.Broadcast.Broadcasted, ::Type{T}) where T = find_bc(bc.args, T) find_bc(args::Tuple, ::Type{T}) where T = find_bc(find_bc(args[1], T), Base.tail(args), T) find_bc(x, ::Type{T}) where T = x find_bc(::Tuple{}, ::Type{T}) where T = nothing find_bc(a::T, rest, ::Type{T}) where T = a find_bc(::Any, rest, ::Type{T}) where T = find_bc(rest, T) extrude(x::judiMultiSourceVector) = extrude(x.data) # Add broadcasting by hand due to the per source indexing for func ∈ [:lmul!, :rmul!, :rdiv!, :ldiv!] @eval begin $func(ms::judiMultiSourceVector, x::Number) = $func(ms.data, x) $func(x::Number, ms::judiMultiSourceVector) = $func(x, ms.data) end end # Broadcasted custom type check_compat() = true get_src(ms::judiMultiSourceVector, j) = make_input(ms[j]) get_src(v::Vector{<:Array}, j) = v[j] get_src(v::Array{T, N}, j) where {T<:Number, N} = v get_src(n::Number, j) = n struct MultiSource <: Base.AbstractBroadcasted m1 m2 op end function materialize(bc::MultiSource) m1, m2 = materialize(bc.m1), materialize(bc.m2) ms = deepcopy(isa(m1, judiMultiSourceVector) ? m1 : m2) check_compat(m1, m2) for i=1:ms.nsrc ms.data[i] .= materialize(broadcasted(bc.op, get_src(m1, i), get_src(m2, i))) end ms end function materialize!(ms::judiMultiSourceVector, bc::MultiSource) m1, m2 = materialize(bc.m1), materialize(bc.m2) check_compat(ms, m1) check_compat(ms, m2) for i=1:ms.nsrc broadcast!(bc.op, ms.data[i], get_src(m1, i), get_src(m2, i)) end nothing end for op ∈ [:+, :-, :*, :/] # Two multi source vectors @eval begin $(op)(ms1::judiMultiSourceVector, ms2::judiMultiSourceVector) = materialize(broadcasted($op, ms1, ms2)) end # External types and broadcasting for LT in [Number, Real, Vector{<:Array}, Array{<:Number, <:Integer}] # +/*/... julia type vs multi source @eval $(op)(ms1::$(LT), ms2::judiMultiSourceVector) = materialize(broadcasted($op, ms1, ms2)) @eval $(op)(ms1::judiMultiSourceVector, ms2::$(LT)) = materialize(broadcasted($op, ms1, ms2)) # broadcasted julia type vs multi source vector or broadcast for MS in [judiMultiSourceVector, MultiSource] @eval broadcasted(::typeof($op), ms1::$(LT), ms2::$(MS)) = MultiSource(ms1, ms2, $op) @eval broadcasted(::typeof($op), ms1::$(MS), ms2::$(LT)) = MultiSource(ms1, ms2, $op) end end # multi source with multi source @eval broadcasted(::typeof($op), ms1::judiMultiSourceVector, ms2::MultiSource) = MultiSource(ms1, ms2, $op) @eval broadcasted(::typeof($op), ms1::MultiSource, ms2::judiMultiSourceVector) = MultiSource(ms1, ms2, $op) @eval broadcasted(::typeof($op), ms1::judiMultiSourceVector, ms2::judiMultiSourceVector) = MultiSource(ms1, ms2, $op) @eval broadcasted(::typeof($op), ms1::MultiSource, ms2::MultiSource) = MultiSource(ms1, ms2, $op) end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
8482
""" Vector of a judiVector and a judiWeight """ mutable struct judiVStack{vDT<:Number} m::Integer n::Integer components::Array{Any, 1} end concrete_msv = [judiVector, judiWeights, judiWavefield] for c in concrete_msv for c2 in concrete_msv if c2 != c @eval function vcat(x::$(c){T}, y::$(c2){T}) where {T<:Number} components = Array{Any}(undef, 2) components[1] = x components[2] = y m = length(x)+length(y) n = 1 return judiVStack{T}(m, n, components) end end end end function vcat(x::judiVStack{T}, y::judiMultiSourceVector{T}) where {T<:Number} components = Array{Any}(undef, length(x.components) + 1) for i=1:length(x.components) components[i] = x.components[i] end components[end] = y m = x.m+length(y) n = 1 return judiVStack{T}(m, n, components) end function vcat(x::judiMultiSourceVector{T}, y::judiVStack{T}) where {T<:Number} components = Array{Any}(undef, length(y.components) + 1) components[1] = x for i=2:length(y.components)+1 components[i] = y.components[i-1] end m = y.m + length(x) n = 1 return judiVStack{T}(m, n, components) end function vcat(x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} nx = length(x.components) ny = length(y.components) components = Array{Any}(undef, nx+ny) for i=1:nx components[i] = x.components[i] end for i=nx+1:nx+ny components[i] = y.components[i-nx] end m = x.m + y.m n = 1 return judiVStack{T}(m, n, components) end function *(F::joAbstractLinearOperator, v::judiVStack{T}) where {T<:Number} return sum(F.fop[i]*v[i] for i=1:length(v.components)) end (msv::judiMultiSourceVector{T})(x::judiVStack{T}) where {T} = x ############################################################ ## overloaded Base functions # conj(jo) conj(a::judiVStack{vDT}) where vDT = judiVStack{vDT}(a.m,a.n,a.components) # transpose(jo) transpose(a::judiVStack{vDT}) where vDT = judiVStack{vDT}(a.n,a.m,a.components) # adjoint(jo) adjoint(a::judiVStack{vDT}) where vDT = judiVStack{vDT}(a.n,a.m,a.components) ########################################################## # Utilities size(x::judiVStack{T}) where {T<:Number} = (x.m, x.n) size(x::judiVStack{T}, ind::Integer) where {T<:Number} = (x.m, x.n)[ind] length(x::judiVStack{T}) where {T<:Number} = x.m eltype(::judiVStack{vDT}) where {vDT} = vDT similar(x::judiVStack{T}) where {T<:Number} = judiVStack{Float32}(x.m, x.n, 0f0 .* x.components) similar(x::judiVStack{T}, ::DataType, ::Union{AbstractUnitRange, Integer}...) where {T<:Number} = similar(x) getindex(x::judiVStack{T}, a) where {T<:Number} = x.components[a] firstindex(x::judiVStack{T}) where {T<:Number} = 1 lastindex(x::judiVStack{T}) where {T<:Number} = length(x.components) dot(x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} = T(sum(dot(x[i],y[i]) for i=1:length(x.components))) function norm(x::judiVStack{T}, order::Real=2) where {T<:Number} if order == Inf return max([norm(x[i], Inf) for i=1:length(x.components)]...) end out = sum(norm(x[i], order)^order for i=1:length(x.components))^(1/order) return T(out) end iterate(S::judiVStack{T}, state::Integer=1) where {T<:Number} = state > length(S.components) ? nothing : (S.components[state], state+1) isfinite(S::judiVStack{T}) where {T<:Number} = all(isfinite(c) for c in S) ########################################################## # minus -(a::judiVStack{T}) where {T<:Number} = -1*a +(a::judiVStack{T}, b::judiVStack{T}) where {T<:Number} = judiVStack{T}(a.m, a.n, a.components + b.components) -(a::judiVStack{T}, b::judiVStack{T}) where {T<:Number} = judiVStack{T}(a.m, a.n, a.components - b.components) +(a::judiVStack{T}, b::Number) where {T<:Number} = judiVStack{T}(a.m, a.n,a.components .+ b) -(a::judiVStack{T}, b::Number) where {T<:Number} = judiVStack{T}(a.m, a.n,a.components .- b) -(a::Number, b::judiVStack{T}) where {T<:Number} = judiVStack{T}(b.m, b.n, a .- b.components) *(a::judiVStack{T}, b::Number) where {T<:Number} = judiVStack{T}(a.m, a.n, b .* a.components) *(a::Number, b::judiVStack{T}) where {T<:Number} = b * a +(a::Number, b::judiVStack{T}) where {T<:Number} = b + a /(a::judiVStack{T}, b::Number) where {T<:Number} = judiVStack{T}(a.m, a.n, a.components ./ b) ########################################################## BroadcastStyle(::Type{judiVStack}) = Base.Broadcast.DefaultArrayStyle{1}() broadcasted(::typeof(+), x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} = x + y broadcasted(::typeof(-), x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} = x - y broadcasted(::typeof(+), x::judiVStack{T}, y::Number) where {T<:Number} = x + y broadcasted(::typeof(-), x::judiVStack{T}, y::Number) where {T<:Number} = x - y broadcasted(::typeof(+), y::Number, x::judiVStack{T}) where {T<:Number} = x + y broadcasted(::typeof(-), y::Number, x::judiVStack{T}) where {T<:Number} = x - y function broadcasted(::typeof(*), x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} size(x) == size(y) || throw(judiWeightsException("dimension mismatch")) z = deepcopy(x) for j=1:length(x.components) z.components[j] = x.components[j] .* y.components[j] end return z end function broadcasted!(::typeof(*), x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} size(x) == size(y) || throw(judiWeightsException("dimension mismatch")) z = deepcopy(x) for j=1:length(x.components) z.components[j] = x.components[j] .* y.components[j] end return z end function broadcasted(::typeof(/), x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} size(x) == size(y) || throw(judiWeightsException("dimension mismatch")) z = deepcopy(x) for j=1:length(x.components) z.components[j] = x.components[j] ./ y.components[j] end return z end function broadcasted(::typeof(*), x::judiVStack{T}, y::Number) where {T<:Number} z = deepcopy(x) for j=1:length(x.components) z.components[j] .*= y end return z end broadcasted(::typeof(*), y::Number, x::judiVStack{T}) where {T<:Number} = x .* y function broadcasted(::typeof(/), x::judiVStack{T}, y::Number) where {T<:Number} z = deepcopy(x) for j=1:length(x.components) z.components[j] ./= y end return z end function materialize!(x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} size(x) == size(y) || throw(judiWeightsException("dimension mismatch")) for j=1:length(x.components) try x.components[j].data .= y.components[j].data catch e x.components[j].weights .= y.components[j].weights end end return x end function broadcast!(::typeof(identity), x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} size(x) == size(y) || throw(judiWeightsException("dimension mismatch")) copy!(x,y) end broadcasted(::typeof(identity), x::judiVStack{T}) where {T<:Number} = x function copy!(x::judiVStack{T}, y::judiVStack{T}) where {T<:Number} size(x) == size(y) || throw(judiWeightsException("dimension mismatch")) for j=1:length(x.components) try x.components[j].data .= y.components[j].data catch e x.components[j].weights .= y.components[j].weights end end end function isapprox(x::judiVStack{T}, y::judiVStack; rtol::AbstractFloat=sqrt(eps()), atol::AbstractFloat=0.0) where {T<:Number} x.m == y.m || throw("Shape error") all(isapprox(xx, yy; rtol=rtol, atol=atol) for (xx, yy)=zip(x.components, y.components)) end ############################################################ function A_mul_B!(x::judiMultiSourceVector{Ts}, F::joCoreBlock{T, Ts}, y::judiVStack{T}) where {T<:Number, Ts<:Number} F.m == size(y, 1) ? z = adjoint(F)*y : z = F*y x.data .= z.data end function A_mul_B!(x::judiVStack{Tv}, F::joCoreBlock{T, Tv}, y::judiMultiSourceVector{T}) where {T<:Number, Tv<:Number} F.m == size(y, 1) ? z = adjoint(F)*y : z = F*y for j=1:length(x.components) x.components[j].data .= z.components[j].data end end mul!(x::judiMultiSourceVector{Ts}, J::joCoreBlock{T, Ts}, y::judiVStack{T}) where {T<:Number, Ts<:Number} = A_mul_B!(x, J, y) mul!(x::judiVStack{Tv}, J::joCoreBlock{T, Tv}, y::judiMultiSourceVector{T}) where {T<:Number, Tv<:Number} = A_mul_B!(x, J, y)
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
15132
############################################################ # judiVector # ################################################# ############################################################ # Authors: Philipp Witte ([email protected]), Henryk Modzelewski ([email protected]) # Date: January 2017 export judiVector, judiVector_to_SeisBlock, src_to_SeisBlock export write_shot_record, get_data, convert_to_array, rebuild_jv, simsource import Base: mergewith! ############################################################ # structure for seismic data as an abstract vector mutable struct judiVector{T, AT} <: judiMultiSourceVector{T} nsrc::Integer geometry::Geometry data::Vector{AT} end ############################################################ ## outer constructors """ judiVector nsrc::Integer geometry::Geometry data::Vector Abstract vector for seismic data. This vector-like structure contains the geometry and data for either\\ receiver data (shot records) or source data (wavelets). Constructors ============ Construct vector from `Geometry` structure and cell array of shot records or wavelets. The `data` keyword\\ can also be a single (non-cell) array, in which case the data is the same for all source positions: judiVector(geometry, data) Construct vector for observed data from `SeisBlock`. `segy_depth_key` is the `SegyIO` keyword \\ that contains the receiver depth coordinate: judiVector(SeisBlock; segy_depth_key="RecGroupElevation") Construct vector for observed data from out-of-core data container of type `SeisCon`: judiVector(SeisCon; segy_depth_key="RecGroupElevation") Examples ======== (1) Construct data vector from `Geometry` structure and a cell array of shot records: dobs = judiVector(rec_geometry, shot_records) (2) Construct data vector for a seismic wavelet (can be either cell arrays of individual\\ wavelets or a single wavelet as an array): q = judiVector(src_geometry, wavelet) (3) Construct data vector from `SeisBlock` object: using SegyIO seis_block = segy_read("test_file.segy") dobs = judiVector(seis_block; segy_depth_key="RecGroupElevation") (4) Construct out-of-core data vector from `SeisCon` object (for large SEG-Y files): using SegyIO seis_container = segy_scan("/path/to/data/directory","filenames",["GroupX","GroupY","RecGroupElevation","SourceDepth","dt"]) dobs = judiVector(seis_container; segy_depth_key="RecGroupElevation") """ function judiVector(geometry::Geometry, data::Array{T, N}) where {T, N} check_geom(geometry, data) T == Float32 || (data = tof32(data)) N < 3 || throw(judiMultiSourceException("Only 1D (trace) and 2D (record) input data supported")) nsrc = get_nsrc(geometry) dataCell = Vector{Array{T, N}}(undef, nsrc) for j=1:nsrc dataCell[j] = deepcopy(data) end return judiVector{T, Array{T, N}}(nsrc, geometry, dataCell) end # constructor if data is passed as a cell array function judiVector(geometry::Geometry, data::Vector{Array{T, N}}) where {T, N} check_geom(geometry, data) T == Float32 || (data = tof32.(data)) nsrcd = length(data) nsrcg = get_nsrc(geometry) nsrcd == nsrcg || throw(judiMultiSourceException("Number of sources in geometry and data don't match $(nsrcd) != $(nsrcg)")) return judiVector{T, Array{T, N}}(nsrcd, geometry, data) end # contructor for in-core data container and given geometry function judiVector(geometry::Geometry, data::SeisBlock) check_geom(geometry, data) # length of data vector src = get_header(data,"FieldRecord") nsrc = length(unique(src)) # fill data vector with pointers to data location dataCell = Vector{Array{Float32, 2}}(undef, nsrc) for j=1:nsrc traces = findall(src .== unique(src)[j]) dataCell[j] = convert(Array{Float32, 2}, data.data[1:get_nt(geometry, j), traces]) end return judiVector{Float32, Array{Float32, 2}}(nsrc, geometry, dataCell) end # contructor for single out-of-core data container and given geometry function judiVector(geometry::Geometry, data::SeisCon) check_geom(geometry, data) # length of data vector nsrc = length(data) # fill data vector with pointers to data location dataCell = Vector{SeisCon}(undef, nsrc) for j=1:nsrc dataCell[j] = split(data,j) end return judiVector{Float32, SeisCon}(nsrc, geometry,dataCell) end judiVector(data::SeisBlock; kw...) = judiVector(Geometry(data; key="receiver", kw...), data) judiVector(data::SeisCon; kw...)= judiVector(Geometry(data; key="receiver", kw...), data) judiVector(data::Vector{SeisCon}; kw...) = judiVector(Geometry(data; key="receiver", kw...), data) judiVector(geometry::Geometry, data::Vector{SeisCon}) = judiVector{Float32, SeisCon}(length(data), geometry, data) ############################################################ ## overloaded multi_source functions time_sampling(jv::judiVector) = get_dt(jv.geometry) ############################################################ # JOLI conversion jo_convert(::Type{T}, jv::judiVector{T, Array{T, N}}, ::Bool) where {T<:AbstractFloat, N} = jv jo_convert(::Type{T}, jv::judiVector{vT, Array{vT, N}}, B::Bool) where {T<:AbstractFloat, vT, N} = judiVector{T, Array{T, N}}(jv.nsrc, jv.geometry, jo_convert.(T, jv.data, B)) function zero(::Type{T}, v::judiVector{vT, AT}; nsrc::Integer=v.nsrc) where {T, vT, AT} zgeom = deepcopy(v.geometry[1:nsrc]) zdata = [zeros(T, get_nt(v.geometry, i), v.geometry.nrec[i]) for i=1:nsrc] return judiVector{T, Matrix{T}}(nsrc, zgeom, zdata) end function copy!(jv::judiVector, jv2::judiVector) jv.geometry = deepcopy(jv2.geometry) jv.data .= jv2.data jv end copyto!(jv::judiVector, jv2::judiVector) = copy!(jv, jv2) make_input(jv::judiVector{T, Matrix{T}}) where T = jv.data[1] make_input(jv::judiVector{T, Vector{T}}) where T = reshape(jv.data[1], :, 1) make_input(jv::judiVector{T, SeisCon}) where T = get_data(jv).data[1] check_compat(ms::Vararg{judiVector, N}) where N = all(y -> compareGeometry(y.geometry, first(ms).geometry), ms) function as_ordered_dict(x::judiVector{T, AT}; v=1) where {T, AT} x.nsrc == 1 || throw(ArgumentError("as_ordered_dict only supported for single shot records")) jdict = OrderedDict(zip(as_coord_set(x.geometry[1]), collect.(eachcol(v.*make_input(x))))) return jdict end function from_ordered_dict(d::OrderedDict{NTuple{N, T}}, t::AbstractRange{T}) where {N, T} Gnew = GeometryIC{T}(coords_from_keys(d.keys)..., [t]) return judiVector{T, Matrix{T}}(1, Gnew, [hcat(d.vals...)]) end function pad_zeros(zpad::OrderedDict, m::T, d::judiVector{T, AT}) where {T, AT} @assert d.nsrc == 1 dloc = as_ordered_dict(d; v=m) sort!(merge!(.+, dloc, zpad)) return from_ordered_dict(dloc, d.geometry.taxis[1]) end function simsource(M::Vector{T}, x::judiVector{T, AT}; reduction=+, minimal::Bool=false) where {T, AT} reduction in [+, nothing] || throw(ArgumentError("$(reduction): Only + and nothing supported for reduction (supershot or supershot before sum)")) # Without reduction, add zero trace for all missing coords if isnothing(reduction) sgeom = as_coord_set(x.geometry) zpad = OrderedDict(zip(sgeom, [zeros(Float32, get_nt(x.geometry, 1)) for s=1:length(sgeom)])) dOut = vcat([pad_zeros(zpad, M[s], x[s]) for s=1:x.nsrc]...) # With reduction. COuld reuse the previous but cheaper to compute the sum directly else reduction = minimal ? PopZero() : reduction sdict = mergewith!(reduction, map((d, m)->as_ordered_dict(d; v=m), x, M)...) sort!(sdict) dOut = from_ordered_dict(sdict, x.geometry.taxis[1]) end return dOut end function simsource(M::Matrix{T}, x::judiVector{T, AT}; reduction=+, minimal::Bool=false) where {T, AT} isnothing(reduction) && @assert size(M, 1) == 1 return vcat([simsource(vec(M[si,:]), x; reduction=reduction, minimal=minimal) for si=1:size(M, 1)]...) end ## Merging utility struct PopZero end no_sim_msg = """ No common receiver poisiton found to construct a super shot. You can - Input shot records with at least one receiver position in common - Use `simsource(M, data; minimal=false)`or `M*data` to construct a supershot with zero-padded missing traces. """ function mergewith!(::PopZero, d1::OrderedDict{K, V}, d2::OrderedDict{K, V}) where {K, V} k1 = keys(d1) k2 = keys(d2) mergekeys = intersect(k1, k2) if isempty(mergekeys) @show k1, k2 throw(ArgumentError(no_sim_msg)) end for k in mergekeys d1[k] .+= d2[k] end Base.filter!(p->p.first in mergekeys, d1) return d1 end ########################################################## # Overload needed base function for SegyIO objects vec(x::SeisCon) = vec(x[1].data) dot(x::SeisCon, y::SeisCon) = dot(x[1].data, y[1].data) norm(x::SeisCon, p::Real=2) = norm(x[1].data, p) abs(x::SegyIO.IBMFloat32) = abs(Float32(x)) *(::Number, ::SeisCon) = throw(judiMultiSourceException("Cannot multiply out of core SeisCon byt scalar")) length(jv::judiVector{T, SeisCon}) where T = n_samples(jv.geometry) # push! function push!(a::judiVector{T, mT}, b::judiVector{T, mT}) where {T, mT} typeof(a.geometry) == typeof(b.geometry) || throw(judiMultiSourceException("Geometry type mismatch")) append!(a.data, b.data) a.nsrc += b.nsrc push!(a.geometry, b.geometry) end # getindex data container """ getindex(x,source_numbers) getindex seismic data vectors or matrix-free linear operators and extract the entries that correspond\\ to the shot positions defined by `source_numbers`. Works for inputs of type `judiVector`, `judiModeling`, \\ `judiProjection`, `judiJacobian`, `Geometry`, `judiRHS`, `judiPDE`, `judiPDEfull`. Examples ======== (1) Extract 2 shots from `judiVector` vector: dsub = getindex(dobs,[1,2]) (2) Extract geometry for shot location 100: geometry_sub = getindex(dobs.geometry,100) (3) Extract Jacobian for shots 10 and 20: Jsub = getindex(J,[10,20]) """ function getindex(a::judiVector{avDT, AT}, srcnum::RangeOrVec) where {avDT, AT} geometry = getindex(a.geometry, srcnum) # Geometry of getindexd data container return judiVector{avDT, AT}(length(srcnum), geometry, a.data[srcnum]) end # Create SeisBlock from judiVector container to write to file function judiVector_to_SeisBlock(d::judiVector{avDT, AT}, q::judiVector{avDT, QT}; source_depth_key="SourceSurfaceElevation", receiver_depth_key="RecGroupElevation") where {avDT, AT, QT} return judiVector_to_SeisBlock(Geometry(d.geometry), Geometry(q.geometry), d.data, q.data; source_depth_key=source_depth_key, receiver_depth_key=receiver_depth_key) end function judiVector_to_SeisBlock(Gr::GeometryIC, Gs::GeometryIC, Dr::Vector{<:VecOrMat}, Ds::Vector{<:VecOrMat}; source_depth_key="SourceSurfaceElevation", receiver_depth_key="RecGroupElevation") nsrc = get_nsrc(Gr) blocks = Array{Any}(undef, nsrc) count = 0 for j=1:nsrc # create SeisBlock blocks[j] = SeisBlock(Dr[j]) numTraces = size(Dr[j],2) traceNumbers = convert(Array{Integer,1},count+1:count+numTraces) # set headers set_header!(blocks[j], "GroupX", Int.(round.(Gr.xloc[j]*1f3))) if length(Gr.yloc[j]) == 1 set_header!(blocks[j], "GroupY", Int(round(Gr.yloc[j][1]*1f3))) else set_header!(blocks[j], "GroupY", convert(Array{Integer,1},round.(Gr.yloc[j]*1f3))) end set_header!(blocks[j], receiver_depth_key, Int.(round.(Gr.zloc[j]*1f3))) set_header!(blocks[j], "SourceX", Int.(round.(Gs.xloc[j][1]*1f3))) set_header!(blocks[j], "SourceY", Int.(round.(Gs.yloc[j][1]*1f3))) set_header!(blocks[j], source_depth_key, Int.(round.(Gs.zloc[j][1]*1f3))) set_header!(blocks[j], "dt", Int(get_dt(Gr, j)*1f3)) set_header!(blocks[j], "FieldRecord",j) set_header!(blocks[j], "TraceNumWithinLine", traceNumbers) set_header!(blocks[j], "TraceNumWithinFile", traceNumbers) set_header!(blocks[j], "TraceNumber", traceNumbers) set_header!(blocks[j], "ElevationScalar", -1000) set_header!(blocks[j], "RecSourceScalar", -1000) count += numTraces end # merge into single block fullblock = blocks[1] for j=2:nsrc fullblock = merge(fullblock,blocks[j]) blocks[j] = [] end return fullblock end function src_to_SeisBlock(q::judiVector{avDT, QT}; source_depth_key="SourceSurfaceElevation", receiver_depth_key="RecGroupElevation") where {avDT, QT} return judiVector_to_SeisBlock(Geometry(q.geometry), Geometry(q.geometry), q.data, q.data; source_depth_key=source_depth_key, receiver_depth_key=receiver_depth_key) end function write_shot_record(srcGeometry::GeometryIC, srcData, recGeometry::GeometryIC, recData, options) pos = [srcGeometry.xloc[1][1], srcGeometry.yloc[1][1], srcGeometry.zloc[1][1]] pos = join(["_"*string(trunc(p; digits=2)) for p in pos]) file = join([string(options.file_name), pos,".segy"]) block_out = judiVector_to_SeisBlock(recGeometry, srcGeometry, recData, srcData) segy_write(join([options.file_path,"/",file]), block_out) container = scan_file(join([options.file_path,"/",file]), ["GroupX", "GroupY", "dt", "SourceSurfaceElevation", "RecGroupElevation"]) return container end #################################################################################################### # Load OOC function get_data(x::judiVector{T, AT}; rel_origin=(0, 0, 0), project=nothing) where {T, AT} shots = Vector{Matrix{Float32}}(undef, x.nsrc) rec_geometry = Geometry(x.geometry; rel_origin=rel_origin, project=project) for j=1:x.nsrc shots[j] = data_matrix(x, j) end return judiVector{T, Array{Float32, 2}}(x.nsrc, rec_geometry, shots) end convert_to_array(x::judiVector) = vcat(vec.(x.data)...) data_matrix(x::judiVector{T, SeisCon}, i::Integer) where T = convert(Matrix{Float32}, x.data[i][1].data)[1:get_nt(x.geometry, i), :] data_matrix(x::judiVector{T, Matrix{T}}, i::Integer) where T = x.data[i] ##### Rebuild bad vector """ reuild_jv(v) rebuild a judiVector from previous version type or JLD2 reconstructed type """ rebuild_jv(v::judiVector{T, AT}) where {T, AT} = v rebuild_jv(v) = judiVector(convgeom(v), convdata(v)) function rebuild_maybe_jld(x::Vector{Any}) try return tof32(x) catch e if hasproperty(x[1], :offset) return [Float32.(StepRangeLen(xi.ref, xi.step, xi.len, xi.offset)) for xi in x] end return x end end # Rebuild for backward compatinility convgeom(x) = GeometryIC{Float32}([getfield(x.geometry, s) for s=fieldnames(GeometryIC)]...) convdata(x) = convert(Array{Array{Float32, 2}, 1}, x.data)
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
3729
############################################################ # judiWavefield ############################################## ############################################################ # Authors: Philipp Witte ([email protected]), Henryk Modzelewski ([email protected]) # Date: June 2017 export judiWavefield, fft, ifft ############################################################ mutable struct judiWavefield{T} <: judiMultiSourceVector{T} nsrc::Integer dt::Vector{T} data::Vector{<:Union{Array{T, N}, PyArray}} where N end ############################################################ ## outer constructors """ judiWavefield nsrc::Integer dt::AbstractFloat data Abstract vector for seismic wavefields. Constructors ============ Construct wavefield vector from an info structure, a cell array of wavefields and the computational \\ time step dt: judiWavefield(nsrc, dt, data) """ function judiWavefield(nsrc::Integer, dt::AbstractFloat, data::Array{T, N}) where {T<:Number, N} # length of vector dataCell = [convert(Array{Float32, N}, data) for j=1:nsrc] return judiWavefield{Float32}(nsrc, [Float32(dt) for i=1:nsrc], dataCell) end function judiWavefield(dt::AbstractFloat, data::Vector{Array{T, N}}) where {T, N} # length of vector nsrc = length(data) T != Float32 && (data = tof32.(data)) return judiWavefield{Float32}(nsrc, [Float32(dt) for i=1:nsrc], data) end judiWavefield(dt::AbstractFloat, nsrc::Integer, data::Array{T, N}) where {T<:Number, N} = judiWavefield(nsrc, dt, data) judiWavefield(dt::AbstractFloat, data::Vector{Any}) = judiWavefield(dt, tof32.(data)) judiWavefield(dt::AbstractFloat, data::Array{T, N}) where {T<:Number, N} = judiWavefield(1, dt, data) conj(w::judiWavefield{T}) where {T<:Complex} = judiWavefield{R}(w.nsrc, w.dt, conj(w.data)) ############################################################ ## overloaded multi_source functions time_sampling(jv::judiWavefield) = jv.dt #################################################################### # JOLI conversion jo_convert(::Type{T}, jw::judiWavefield{T}, ::Bool) where {T<:Number} = jw jo_convert(::Type{T}, jw::judiWavefield{vT}, B::Bool) where {T<:Number, vT} = judiWavefield{T}(jw.nsrc, jv.dt, jo_convert.(T, jw.data, B)) zero(::Type{T}, v::judiWavefield{vT}; nsrc::Integer=v.nsrc) where {T, vT} = judiWavefield{T}(nsrc, v.dt, T(0) .* v.data[1:nsrc]) zero(::Type{T}, v::judiWavefield{vT}; nsrc::Integer=v.nsrc) where {T<:AbstractFloat, vT<:Complex} = judiWavefield{T}(nsrc, v.dt, T(0) .* real(v.data[1:nsrc])) (w::judiWavefield)(x::Vector{<:Array}) = judiWavefield(w.dt, x) function copy!(jv::judiWavefield, jv2::judiWavefield) v.data .= jv2.data jv.dt = jv2.dt jv end copyto!(jv::judiWavefield, jv2::judiWavefield) = copy!(jv, jv2) make_input(w::judiWavefield) = w.data[1] check_compat(ms::Vararg{judiWavefield, N}) where N = all(y -> y.dt == first(ms).dt, ms) getindex(a::judiWavefield{T}, srcnum::RangeOrVec) where T = judiWavefield{T}(length(srcnum), a.dt[srcnum], a.data[srcnum]) #################################################################### function push!(a::judiWavefield{T}, b::judiWavefield{T}) where T append!(a.data, b.data) append!(a.dt, b.dt) a.nsrc += b.nsrc end # DFT operator for wavefields, acts along time dimension function fft(x_in::judiWavefield{T}) where T x = similar(x_in, Complex{Float32}) for i=1:x_in.nsrc x.data[i] = fft(x_in.data[i], 1)/sqrt(size(x_in.data[i], 1)) end return x end function ifft(x_in::judiWavefield{T}) where T x = similar(x_in, Float32) for i=1:x_in.nsrc x.data[i] = real(ifft(x_in.data[i], 1)) * sqrt(size(x_in.data[i], 1)) end return x end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
3404
############################################################ # judiWeights ############################################## ############################################################ # Authors: Philipp Witte ([email protected]), Henryk Modzelewski ([email protected]) # Date: June 2019 # Updated by Ziyi Yin ([email protected]), Nov 2020 export judiWeights ############################################################ # structure for seismic data as an abstract vector mutable struct judiWeights{T<:Number} <: judiMultiSourceVector{T} nsrc::Integer data::Vector{Array{T, N}} where N end # Bypass mismatch in naming and fields for backward compat Base.getproperty(obj::judiWeights, sym::Symbol) = sym == :weights ? getfield(obj, :data) : getfield(obj, sym) ############################################################ ## outer constructors """ judiWeights nsrc weights Abstract vector for weighting an extended source, which is injected at every grid point, as weighted by this vector. Constructors ============ Construct vector cell array of weights. The `weights` keyword\\ can also be a single (non-cell) array, in which case the weights are the same for all source positions: judiWeights(weights; nsrc=1) """ function judiWeights(weights::Array{T, N}; nsrc=1) where {T<:AbstractFloat, N} weights = convert(Array{Float32}, weights) # length of vector weightsCell = [deepcopy(weights) for j=1:nsrc] return judiWeights{Float32}(nsrc, weightsCell) end # constructor if weights are passed as a cell array judiWeights(weights::Vector{Array}) = judiWeights(convert.(Array{Float32, length(size(weights[1]))}, weights)) function judiWeights(weights::Vector{Array{T, N}}) where {T<:Number, N} nsrc = length(weights) weights = convert.(Array{Float32, N}, weights) return judiWeights{Float32}(nsrc, weights) end ############################################################ # JOLI conversion jo_convert(::Type{T}, jw::judiWeights{T}, ::Bool) where {T<:AbstractFloat} = jw jo_convert(::Type{T}, jw::judiWeights{vT}, B::Bool) where {T<:AbstractFloat, vT} = judiWavefield{T}(jv.nsrc, jo_convert.(T, jw.weights, B)) zero(::Type{T}, v::judiWeights{vT}; nsrc::Integer=v.nsrc) where {T, vT} = judiWeights{T}(nsrc, T(0) .* v.data[1:nsrc]) (w::judiWeights)(x::Vector{<:Array}) = judiWeights(x) function copy!(jv::judiWeights, jv2::judiWeights) jv.data .= jv2.data jv end copyto!(jv::judiWeights, jv2::judiWeights) = copy!(jv, jv2) function push!(a::judiWeights{T}, b::judiWeights{T}) where T append!(a.weights, b.weights) a.nsrc += b.nsrc end make_input(w::judiWeights) = w.data[1] # getindex weights container """ getindex(x,source_numbers) getindex seismic weights vectors or matrix-free linear operators and extract the entries that correspond\\ to the shot positions defined by `source_numbers`. Works for inputs of type `judiWeights`, `judiModeling`, \\ `judiProjection`, `judiJacobian`, `Geometry`, `judiRHS`, `judiPDE`, `judiPDEfull`. Examples ======== (1) Extract 2 shots from `judiWeights` vector: dsub = getindex(dobs,[1,2]) (2) Extract geometry for shot location 100: geometry_sub = getindex(dobs.geometry,100) (3) Extract Jacobian for shots 10 and 20: Jsub = getindex(J,[10,20]) """ getindex(a::judiWeights{avDT}, srcnum::RangeOrVec) where avDT = judiWeights{avDT}(length(srcnum), a.data[srcnum])
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
2550
struct LazyData{D} <: AbstractVector{D} msv::judiMultiSourceVector{D} end getindex(ld::LazyData{D}, i) where D = get_data(ld.msv[i]).data setindex!(::LazyData{D}, ::Any, ::Any) where D = throw(MethodError(setindex!, "LazyData is read-only")) size(A::LazyData) = size(A.msv) get_data(ld::LazyData{D}) where D = get_data(ld.msv) """ LazyAdd nsrc A B sign Lazy addition of two RHS (currently only judiVector). The addition isn't evaluated to avoid large memory allocation but instead evaluates the addition (with sign `sign`) `A + sign * B` for a single source at propagation time. """ struct LazyAdd{D} <: judiMultiSourceVector{D} nsrc::Integer A B sign end getindex(la::LazyAdd{D}, i::RangeOrVec) where D = LazyAdd{D}(length(i), la.A[i], la.B[i], la.sign) function eval(ls::LazyAdd{D}) where D aloc = eval(ls.A) bloc = eval(ls.B) ga = aloc.geometry gb = bloc.geometry @assert (ga.nt == gb.nt && ga.dt == gb.dt && ga.t == gb.t) xloc = [vcat(ga.xloc[1], gb.xloc[1])] yloc = [vcat(ga.yloc[1], gb.yloc[1])] zloc = [vcat(ga.zloc[1], gb.zloc[1])] geom = GeometryIC{D}(xloc, yloc, zloc, ga.dt, ga.nt, ga.t) data = hcat(aloc.data[1], ls.sign*bloc.data[1]) judiVector{D, Matrix{D}}(1, geom, [data]) end function make_src(ls::LazyAdd{D}) where D q = eval(ls) return q.geometry[1], q.data[1] end """ LazyMul nsrc A B sign Lazy addition of two RHS (currently only judiVector). The addition isn't evaluated to avoid large memory allocation but instead evaluates the addition (with sign `sign`) `A + sign * B` for a single source at propagation time. """ struct LazyMul{D} <: judiMultiSourceVector{D} nsrc::Integer P::joAbstractLinearOperator msv::judiMultiSourceVector{D} end getindex(la::LazyMul{D}, i::RangeOrVec) where D = LazyMul{D}(length(i), la.P[i], la.msv[i]) length(lm::LazyMul) = length(lm.msv) zero(::Type{T}, lm::LazyMul; nsrc::Integer=lm.nsrc) where T = zero(T, lm.msv; nsrc=nsrc) function make_input(lm::LazyMul{D}) where D @assert lm.nsrc == 1 return make_input(lm.P * get_data(lm.msv)) end get_data(lm::LazyMul{D}) where D = lm.P * get_data(lm.msv) materialize(lm::LazyMul{D}) where D = get_data(lm) deepcopy(lm::LazyMul{D}) where D = deepcopy(lm.msv) function getproperty(lm::LazyMul{D}, s::Symbol) where D if s == :data return LazyData(lm) elseif s == :geometry return lm.msv.geometry else return getfield(lm, s) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
25655
# Auxiliary functions for TimeModeling module # Author: Philipp Witte, [email protected] # Date: September 2016 # # Mathias Louboutin, [email protected] # Updated July 2020 export ricker_wavelet, get_computational_nt, calculate_dt, setup_grid, setup_3D_grid export convertToCell, limit_model_to_receiver_area, remove_out_of_bounds_receivers, extend_gradient export remove_padding, subsample, process_input_data export generate_distribution, select_frequencies export devito_model, pad_array export transducer, as_vec export Gardner """ devito_model(model, options;dm=nothing) Creates a python side model strucutre for devito. Parameters * `model`: JUDI Model structure. * `options`: JUDI Options structure. * `dm`: Squared slowness perturbation (optional), Array or PhysicalParameter. """ function devito_model(model::MT, options::JUDIOptions, dm) where {MT<:AbstractModel} # Set up Python model structure physpar = Dict((n, isa(v, PhysicalParameter) ? v.data : v) for (n, v) in _params(model)) modelPy = rlock_pycall(pm."Model", PyObject, origin(model), spacing(model), size(model), fs=options.free_surface, nbl=nbl(model), space_order=options.space_order, dt=options.dt_comp, dm=dm; physpar...) return modelPy end devito_model(model::AbstractModel, options::JUDIOptions, dm::PhysicalParameter) = devito_model(model, options, reshape(dm.data, size(model))) devito_model(model::AbstractModel, options::JUDIOptions, dm::Vector{T}) where T = devito_model(model, options, reshape(dm, size(model))) devito_model(model::AbstractModel, options::JUDIOptions) = devito_model(model, options, nothing) """ pad_array(m, nb; mode=:border) Pads to the input array with either copying the edge value (:border) or zeros (:zeros) Parameters * `m`: Array to be padded. * `nb`: Size of padding. Array of tuple with one (nb_left, nb_right) tuple per dimension. * `mode`: Padding mode (optional), defaults to :border. """ function pad_array(m::Array{DT}, nb::NTuple{N, Tuple{Int64, Int64}}; mode::Symbol=:border) where {DT, N} n = size(m) new_size = Tuple([n[i] + sum(nb[i]) for i=1:length(nb)]) Ei = [] for i=1:length(nb) left, right = nb[i] push!(Ei, joExtend(n[i], mode;pad_upper=right, pad_lower=left, RDT=DT, DDT=DT)) end padded = joKron(Ei...) * PermutedDimsArray(m, length(n):-1:1)[:] return PyReverseDims(reshape(padded, reverse(new_size))) end pad_array(::Nothing, ::NTuple{N, Tuple{Int64, Int64}}; s::Symbol=:border) where N = nothing pad_array(m::Number, ::NTuple{N, Tuple{Int64, Int64}}; s::Symbol=:border) where N = m """ remove_padding(m, nb; true_adjoint=False) Removes the padding from array `m`. This is the adjoint of [`pad_array`](@ref). Parameters * `m`: Array to remvove padding from. * `nb`: Size of padding. Array of tuple with one (nb_left, nb_right) tuple per dimension. * `true_adjoint`: Unpadding mode, defaults to False. Will sum the padding to the edge point with `true_adjoint=true` and should only be used this way for adjoint testing purpose. """ function remove_padding(gradient::AbstractArray{DT}, nb::NTuple{ND, Tuple{Int64, Int64}}; true_adjoint::Bool=false) where {ND, DT} N = size(gradient) if true_adjoint for (dim, (nbl, nbr)) in enumerate(nb) selectdim(gradient, dim, nbl+1) .+= dropdims(sum(selectdim(gradient, dim, 1:nbl), dims=dim), dims=dim) selectdim(gradient, dim, N[dim]-nbr) .+= dropdims(sum(selectdim(gradient, dim, N[dim]-nbr+1:N[dim]), dims=dim), dims=dim) end end out = gradient[[nbl+1:nn-nbr for ((nbl, nbr), nn) in zip(nb, N)]...] return out end """ limit_model_to_receiver_area(srcGeometry, recGeometry, model, buffer; pert=nothing) Crops the `model` to the area of the source an receiver with an extra buffer. This reduces the size of the problem when the model si large and the source and receiver located in a small part of the domain. In the cartoon below, the full model will be cropped to the center area containg the source (o) receivers (x) and buffer area (*) - o Source position - x receiver positions - * Extra buffer (grid spacing in that simple case) -------------------------------------------- \n | . . . . . . . . . . . . . . . . . . . . . | \n | . . . . . . . . . . . . . . . . . . . . . | \n | . . . . * * * * * * * * * * * * . . . . . | \n | . . . . * x x x x x x x x x x * . . . . . | \n | . . . . * x x x x x x x x x x * . . . . . | \n | . . . . * x x x x x x x x x x * . . . . . | \n | . . . . * x x x x x o x x x x * . . . . . | \n | . . . . * x x x x x x x x x x * . . . . . | \n | . . . . * x x x x x x x x x x * . . . . . | \n | . . . . * x x x x x x x x x x * . . . . . | \n | . . . . * * * * * * * * * * * * . . . . . | \n | . . . . . . . . . . . . . . . . . . . . . | \n | . . . . . . . . . . . . . . . . . . . . . | \n -------------------------------------------- \n Parameters * `srcGeometry`: Geometry of the source. * `recGeometry`: Geometry of the receivers. * `model`: Model to be croped. * `buffer`: Size of the buffer on each side. * `pert`: Model perturbation (optional) to be cropped as well. """ function limit_model_to_receiver_area(srcGeometry::Geometry{T}, recGeometry::Geometry{T}, model::MT, buffer::Number; pert=nothing) where {MT<:AbstractModel, T<:Real} # Restrict full velocity model to area that contains either sources and receivers ndim = length(size(model)) n_orig = size(model) # scan for minimum and maximum x and y source/receiver coordinates min_x = min(minimum(recGeometry.xloc[1]), minimum(srcGeometry.xloc[1])) max_x = max(maximum(recGeometry.xloc[1]), maximum(srcGeometry.xloc[1])) if ndim == 3 min_y = min(minimum(recGeometry.yloc[1]), minimum(srcGeometry.yloc[1])) max_y = max(maximum(recGeometry.yloc[1]), maximum(srcGeometry.yloc[1])) end # add buffer zone if possible min_x = max(origin(model, 1), min_x - buffer) max_x = min(origin(model, 1) + spacing(model, 1)*(size(model, 1)-1), max_x + buffer) if ndim == 3 min_y = max(origin(model, 2), min_y - buffer) max_y = min(origin(model, 2) + spacing(model, 2)*(size(model, 2)-1), max_y + buffer) end # extract part of the model that contains sources/receivers nx_min = Int((min_x-origin(model, 1)) ÷ spacing(model, 1)) + 1 nx_max = Int((max_x-origin(model, 1)) ÷ spacing(model, 1)) + 1 inds = [max(1, nx_min):nx_max, 1:size(model)[end]] if ndim == 3 ny_min = Int((min_y-origin(model, 2)) ÷ spacing(model, 2)) + 1 ny_max = Int((max_y-origin(model, 2)) ÷ spacing(model, 2)) + 1 insert!(inds, 2, max(1, ny_min):ny_max) end # Extract relevant model part from full domain newp = OrderedDict() for (p, v) in _params(model) newp[p] = isa(v, AbstractArray) ? v[inds...] : v end p = findfirst(x->isa(x, PhysicalParameter), newp) o, n = newp[p].o, newp[p].n new_model = MT(DiscreteGrid(n, spacing(model), o, nbl(model)), values(newp)...) isnothing(pert) && (return new_model, nothing) newpert = reshape(pert, n_orig)[inds...] return new_model, newpert[1:end] end """ remove_out_of_bounds_receivers(recGeometry, model) Removes receivers that are positionned outside the computational domain defined by the model. Parameters * `recGeometry`: Geometry of receivers in which out of bounds will be removed. * `model`: Model defining the computational domain. """ function remove_out_of_bounds_receivers(recGeometry::Geometry{T}, model::AbstractModel{T, N}) where {T<:Real, N} # Only keep receivers within the model xmin, xmax = origin(model, 1), origin(model, 1) + (size(model)[1] - 1)*spacing(model, 1) if typeof(recGeometry.xloc[1]) <: Array idx_xrec = findall(x -> xmax >= x >= xmin, recGeometry.xloc[1]) recGeometry.xloc[1] = recGeometry.xloc[1][idx_xrec] length(recGeometry.yloc[1]) > 1 && (recGeometry.yloc[1] = recGeometry.yloc[1][idx_xrec]) recGeometry.zloc[1] = recGeometry.zloc[1][idx_xrec] end # For 3D shot records, scan also y-receivers if length(size(model)) == 3 && typeof(recGeometry.yloc[1]) <: Array ymin, ymax = origin(model, 2), origin(model, 2) + (size(model, 2) - 1)*spacing(model, 2) idx_yrec = findall(x -> ymax >= x >= ymin, recGeometry.yloc[1]) recGeometry.xloc[1] = recGeometry.xloc[1][idx_yrec] recGeometry.yloc[1] = recGeometry.yloc[1][idx_yrec] recGeometry.zloc[1] = recGeometry.zloc[1][idx_yrec] end return recGeometry end """ remove_out_of_bounds_receivers(recGeometry, recData, model) Removes receivers that are positionned outside the computational domain defined by the model. Parameters * `recGeometry`: Geometry of receivers in which out of bounds will be removed. * `recData`: Shot record for that geometry in which traces will be removed. * `model`: Model defining the computational domain. """ function remove_out_of_bounds_receivers(recGeometry::Geometry{T}, recData::Matrix{T}, model::AbstractModel) where {T<:Real} # Only keep receivers within the model xmin, xmax = origin(model, 1), origin(model, 1) + (size(model)[1] - 1)*spacing(model, 1) if typeof(recGeometry.xloc[1]) <: Array idx_xrec = findall(x -> xmax >= x >= xmin, recGeometry.xloc[1]) recGeometry.xloc[1] = recGeometry.xloc[1][idx_xrec] length(recGeometry.yloc[1]) > 1 && (recGeometry.yloc[1] = recGeometry.yloc[1][idx_xrec]) recGeometry.zloc[1] = recGeometry.zloc[1][idx_xrec] recData = recData[:, idx_xrec] end # For 3D shot records, scan also y-receivers if length(size(model)) == 3 && typeof(recGeometry.yloc[1]) <: Array ymin, ymax = origin(model, 2), origin(model, 2) + (size(model, 2) - 1)*spacing(model, 2) idx_yrec = findall(x -> ymax >= x >= ymin, recGeometry.yloc[1]) recGeometry.xloc[1] = recGeometry.xloc[1][idx_yrec] recGeometry.yloc[1] = recGeometry.yloc[1][idx_yrec] recGeometry.zloc[1] = recGeometry.zloc[1][idx_yrec] recData = recData[:, idx_yrec] end return recGeometry, recData end remove_out_of_bounds_receivers(G::Geometry, ::Nothing, M::AbstractModel) = (remove_out_of_bounds_receivers(G, M), nothing) remove_out_of_bounds_receivers(::Nothing, ::Nothing, M::AbstractModel) = (nothing, nothing) remove_out_of_bounds_receivers(w, r::AbstractArray, ::AbstractModel) = (w, r) remove_out_of_bounds_receivers(G::Geometry, r::AbstractArray, M::AbstractModel) = remove_out_of_bounds_receivers(G, convert(Matrix{Float32}, r), M) remove_out_of_bounds_receivers(w::AbstractArray, ::Nothing, M::AbstractModel) = (w, nothing) """ convertToCell(x) Convert an array `x` to a cell array (`Array{Any,1}`) with `length(x)` entries,\\ where the i-th cell contains the i-th entry of `x`. Parameters * `x`: Array to be converted into and array of array """ function convertToCell(x::Vector{T}) where T<:Number n = length(x) y = Array{Array{T, 1}, 1}(undef, n) for j=1:n y[j] = [x[j]] end return y end convertToCell(x::Vector{Array{T, N}}) where {T<:Number, N} = x convertToCell(x::StepRangeLen) = convertToCell(Float32.(x)) convertToCell(x::Number) = convertToCell([x]) # 1D source time function """ ricker_wavelet(tmax, dt, f0) Create seismic Ricker wavelet of length `tmax` (in milliseconds) with sampling interval `dt` (in milliseonds)\\ and central frequency `f0` (in kHz). """ function ricker_wavelet(tmax::T, dt::T, f0::T; t0=nothing) where {T<:Real} isnothing(t0) ? t0 = T(0) : tmax = T(tmax - t0) nt = floor(Int, tmax / dt) + 1 t = range(t0, stop=tmax, length=nt) r = (pi * f0 * (t .- 1 / f0)) q = zeros(T, nt, 1) q[:,1] .= (T(1) .- T(2) .* r.^T(2)) .* exp.(-r.^T(2)) return q end ricker_wavelet(tmax::T, dt, f0; t0=nothing) where {T<:Real} = ricker_wavelet(tmax, T(dt), T(f0); t0=t0) """ calculate_dt(model; dt=nothing) Compute the computational time step based on the CFL condition and physical parameters in the model. Parameters * `model`: Model structure * `dt`: User defined time step (optional), will be the value returned if provided. """ function calculate_dt(model::Union{ViscIsoModel{T, N}, IsoModel{T, N}}; dt=nothing) where {T<:Real, N} if ~isnothing(dt) return dt end m = minimum(model.m) modelPy = rlock_pycall(pm."Model", PyObject, origin=origin(model), spacing=spacing(model), shape=ntuple(_ -> 11, N), m=m, nbl=0) return calculate_dt(modelPy) end function calculate_dt(model::IsoElModel{T, N}; dt=nothing) where {T<:Real, N} if ~isnothing(dt) return dt end lam = maximum(model.lam) mu = maximum(model.mu) modelPy = rlock_pycall(pm."Model", PyObject, origin=origin(model), spacing=spacing(model), shape=ntuple(_ -> 11, N), lam=lam, mu=mu, nbl=0) return calculate_dt(modelPy) end function calculate_dt(model::TTIModel{T, N}; dt=nothing) where {T<:Real, N} if ~isnothing(dt) return dt end m = minimum(model.m) epsilon = maximum(model.epsilon) modelPy = rlock_pycall(pm."Model", PyObject, origin=origin(model), spacing=spacing(model), shape=ntuple(_ -> 11, N), m=m, epsilon=epsilon, nbl=0) return calculate_dt(modelPy) end calculate_dt(modelPy::PyObject) = convert(Float32, modelPy."critical_dt") """ get_computational_nt(srcGeometry, recGeoemtry, model; dt=nothing) Estimate the number of computational time steps. Required for calculating the dimensions\\ of the matrix-free linear modeling operators. `srcGeometry` and `recGeometry` are source\\ and receiver geometries of type `Geometry` and `model` is the model structure of type \\ `Model`. """ function get_computational_nt(srcGeometry::Geometry{T}, recGeometry::Geometry{T}, model::AbstractModel; dt=nothing) where {T<:Real} # Determine number of computational time steps nsrc = get_nsrc(srcGeometry) nt = Vector{Int64}(undef, nsrc) dtComp = calculate_dt(model; dt=dt) for j=1:nsrc ntRec = length(0:dtComp:(dtComp*ceil(get_t(recGeometry, j)/dtComp))) ntSrc = length(0:dtComp:(dtComp*ceil(get_t(srcGeometry, j)/dtComp))) nt[j] = max(ntRec, ntSrc) end return nt end """ get_computational_nt(Geoemtry, model; dt=nothing) Estimate the number of computational time steps. Required for calculating the dimensions\\ of the matrix-free linear modeling operators. `srcGeometry` and `recGeometry` are source\\ and receiver geometries of type `Geometry` and `model` is the model structure of type \\ `Model`. """ function get_computational_nt(Geometry::Geometry{T}, model::AbstractModel; dt=nothing) where {T<:Real} # Determine number of computational time steps nsrc = get_nsrc(Geometry) nt = Array{Integer}(undef, nsrc) dtComp = calculate_dt(model; dt=dt) for j=1:nsrc nt[j] = length(0:dtComp:(dtComp*ceil(get_t(Geometry, j)/dtComp))) end return nt end """ setup_grid(geometry, n) Sets up the coordinate arrays for Devito. Parameters: * `geometry`: Geometry containing the coordinates * `n`: Domain size """ setup_grid(geometry::GeometryIC{T}, ::NTuple{3, <:Integer}) where {T<:Real} = hcat(geometry.xloc[1], geometry.yloc[1], geometry.zloc[1]) setup_grid(geometry::GeometryIC{T}, ::NTuple{2, <:Integer}) where {T<:Real} = hcat(geometry.xloc[1], geometry.zloc[1]) setup_grid(geometry::GeometryIC{T}, ::NTuple{1, <:Integer}) where {T<:Real} = geometry.xloc[1] """ setup_3D_grid(x, y, z) Converts one dimensional input (x, y, z) into three dimensional coordinates. The number of point created is `length(x)*lenght(y)` with all the x/y pairs and each pair at depth z[idx[x]]. `x` and `z` must have the same size. Parameters: * `x`: X coordinates. * `y`: Y coordinates. * `z`: Z coordinates. """ function setup_3D_grid(xrec::Vector{<:AbstractVector{T}},yrec::Vector{<:AbstractVector{T}},zrec::AbstractVector{T}) where T<:Real # Take input 1d x and y coordinate vectors and generate 3d grid. Input are cell arrays nsrc = length(xrec) xloc = Vector{Vector{T}}(undef, nsrc) yloc = Vector{Vector{T}}(undef, nsrc) zloc = Vector{Vector{T}}(undef, nsrc) for i=1:nsrc nxrec = length(xrec[i]) nyrec = length(yrec[i]) xloc[i] = zeros(T, nxrec*nyrec) yloc[i] = zeros(T, nxrec*nyrec) zloc[i] = zeros(T, nxrec*nyrec) idx = 1 for k=1:nyrec for j=1:nxrec xloc[i][idx] = xrec[i][j] yloc[i][idx] = yrec[i][k] zloc[i][idx] = zrec[i] idx += 1 end end end return xloc, yloc, zloc end """ setup_3D_grid(x, y, z) Converts one dimensional input (x, y, z) into three dimensional coordinates. The number of point created is `length(x)*lenght(y)` with all the x/y pairs and each pair at same depth z. Parameters: * `x`: X coordinates. * `y`: Y coordinates. * `z`: Z coordinate. """ function setup_3D_grid(xrec::AbstractVector{T},yrec::AbstractVector{T}, zrec::T) where T<:Real # Take input 1d x and y coordinate vectors and generate 3d grid. Input are arrays/ranges nxrec = length(xrec) nyrec = length(yrec) xloc = zeros(T, nxrec*nyrec) yloc = zeros(T, nxrec*nyrec) zloc = zeros(T, nxrec*nyrec) idx = 1 for k=1:nyrec for j=1:nxrec xloc[idx] = xrec[j] yloc[idx] = yrec[k] zloc[idx] = zrec idx += 1 end end return xloc, yloc, zloc end setup_3D_grid(xrec, yrec, zrec) = setup_3D_grid(tof32(xrec), tof32(yrec), tof32(zrec)) function setup_3D_grid(xrec::Vector{Any}, yrec::Vector{Any}, zrec::Vector{Any}) xrec, yrec, zrec = convert(Vector{typeof(xrec[1])},xrec), convert(Vector{typeof(yrec[1])}, yrec), convert(Vector{typeof(zrec[1])},zrec) setup_3D_grid(xrec, yrec, zrec) end """ generate_distribution(x; src_no=1) Generates a probability distribution for the discrete input judiVector `x`. Parameters * `x`: judiVector. Usualy a source with a single trace per source position. * `src_no`: Index of the source to select out of `x` """ function generate_distribution(x::judiVector{T, Matrix{T}}; src_no=1) where {T<:Real} # Generate interpolator to sample from probability distribution given # from spectrum of the input data # sampling information nt = get_nt(x.geometry, src_no) dt = get_dt(x.geometry, src_no) t = get_t(x.geometry, src_no) # frequencies fs = 1/dt # sampling rate fnyq = fs/2 # nyquist frequency df = fnyq/nt # frequency interval f = 0:2*df:fnyq # frequencies # amplitude spectrum of data (serves as probability density function) ns = nt ÷ 2 + 1 amp = abs.(fft(x.data[src_no]))[1:ns] # get first half of spectrum # convert to cumulative probability distribution (integrate) pd = zeros(ns) pd[1] = dt*amp[1] for j=2:ns pd[j] = pd[j-1] + amp[j]*df end pd /= pd[end] # normalize return Spline1D(pd, f) end """ select_frequencies(q_dist; fmin=0f0, fmax=Inf, nf=1) Selects `nf` frequencies based on the source distribution `q_dist` computed with [`generate_distribution`](@ref). Parameters * `q_dist`: Distribution to sample from. * `f_min`: Minimum acceptable frequency to sample (defaults to 0). * `f_max`: Maximum acceptable frequency to sample (defaults to Inf). * `fd`: Number of frequnecies to sample (defaults to 1). """ function select_frequencies(q_dist::Spline1D; fmin=0f0, fmax=Inf, nf=1) freq = zeros(Float32, nf) for j=1:nf while (freq[j] <= fmin) || (freq[j] > fmax) freq[j] = q_dist(rand(1)[1])[1] end end return freq end """ process_input_data(input, geometry, nsrc) Preprocesses input Array into an Array of Array for modeling Parameters: * `input`: Input to preprocess. * `geometry`: Geometry containing physical parameters. * `nsrc`: Number of sources """ function process_input_data(input::DenseArray{T}, geometry::Geometry{T}) where {T<:Real} # Input data is pure Julia array: assume fixed no. # of receivers and reshape into data cube nt x nrec x nsrc nt = get_nt(geometry, 1) nrec = geometry.nrec[1] nsrc = length(geometry.xloc) data = reshape(input, nt, nrec, nsrc) dataCell = Vector{Matrix{T}}(undef, nsrc) for j=1:nsrc dataCell[j] = data[:,:,j] end return dataCell end """ process_input_data(input, model, nsrc) Preprocesses input Array into an Array of Array for modeling Parameters: * `input`: Input to preprocess. * `model`: Model containing physical parameters. * `nsrc`: Number of sources """ function process_input_data(input::DenseArray{T}, model::AbstractModel{T, N}, nsrc::Integer) where {T<:Real, N} dataCell = Vector{Array{T, N}}(undef, nsrc) input = reshape(input, size(model)..., nsrc) nd = ndims(input) for j=1:nsrc dataCell[j] = selectdim(input, nd, j) end return dataCell end process_input_data(input::DenseArray{T}, model::AbstractModel{T, N}) where {T<:Real, N} = process_input_data(input, model, length(input) ÷ prod(size(model))) process_input_data(input::judiVector{T, AT}, ::Geometry{T}) where {T<:Real, AT} = input process_input_data(input::judiVector{T, AT}) where {T<:Real, AT} = input.data process_input_data(input::judiWeights{T}, ::AbstractModel{T, N}) where {T<:Real, N} = input.weights function process_input_data(input::DenseArray{T}, v::Vector{<:Array}) where T nsrc = length(v) dataCell = Vector{Vector{T}}(undef, nsrc) input = reshape(input, :, nsrc) for j=1:nsrc dataCell[j] = input[:, j] end return dataCell end """ reshape(x::Array{Float32, 1}, geometry::Geometry) Reshapes input vector into a 3D `nt x nrec x nsrc` Array. """ function reshape(x::AbstractArray{T}, geometry::Geometry{T}) where {T<:Real} nt = get_nt(geometry, 1) nrec = geometry.nrec[1] nsrc = Int(length(x) / nt / nrec) return reshape(x, nt, nrec, nsrc) end """ reshape(V::Vector{T}, n::Tuple, nblock::Integer) Reshapes input vector into a `Vector{Array{T, N}}` of length `nblock` with each subarray of size `n` """ function reshape(x::Vector{T}, d::Dims, nsrc::Integer) where {T<:Real} length(x) == prod(d)*nsrc || throw(judiMultiSourceException("Incompatible size")) as_nd = reshape(x, d..., nsrc) return [collect(selectdim(as_nd, ndims(as_nd), s)) for s=1:nsrc] end """ transducer(q, d, r, theta) Create the JUDI soure for a circular transducer Theta=0 points downward: . . . . - - - . . . . . . . . . . + + + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Theta=pi/2 points right: . . . . - + . . . . . . . . . . . - + . . . . . . . . . . . - + . . . . . . . . . . . . . . . . . . . . 2D only, to extend to 3D """ function transducer(q::judiVector{T, AT}, d::Tuple, r::Number, theta) where {T<:Real, AT} length(theta) != length(q.geometry.xloc) && throw("Need one angle per source position") size(q.data[1], 2) > 1 && throw("Only point sources can be converted to transducer source") # Array of source nsrc_loc = 11 nsrc = length(q.geometry.xloc) x_base = collect(range(-r, r, length=nsrc_loc)) y_base = zeros(nsrc_loc) y_base_b = zeros(nsrc_loc) .- d[end] # New coords and data xloc = Vector{Vector{T}}(undef, nsrc) yloc = Vector{Vector{T}}(undef, nsrc) zloc = Vector{Vector{T}}(undef, nsrc) data = Vector{Matrix{T}}(undef, nsrc) t = q.geometry.taxis[1:1] for i=1:nsrc # Build the rotated array of dipole R = T.([cos(theta[i] - pi/2) sin(theta[i] - pi/2);-sin(theta[i] - pi/2) cos(theta[i] - pi/2)]) # +1 coords r_loc = R * [x_base';y_base'] # -1 coords r_loc_b = R * [x_base';y_base_b'] xloc[i] = q.geometry.xloc[i] .+ vec(vcat(r_loc[1, :], r_loc_b[1, :])) zloc[i] = q.geometry.zloc[i] .+ vec(vcat(r_loc[2, :], r_loc_b[2, :])) yloc[i] = zeros(T, 2*nsrc_loc) data[i] = zeros(T, length(q.data[i]), 2*nsrc_loc) data[i][:, 1:nsrc_loc] .= q.data[i]/nsrc_loc data[i][:, nsrc_loc+1:end] .= -q.data[i]/nsrc_loc end return judiVector(GeometryIC{Float32}(xloc, yloc, zloc, t), data) end ########################################### Misc defaults # Vectorization of single variable (not defined in Julia) Base.vec(x::Float64) = x; Base.vec(x::Float32) = x; Base.vec(x::Int64) = x; Base.vec(x::Int32) = x; Base.vec(::Nothing) = nothing """ as_vec(x, ::Val{Bool}) Vectorizes output when `return_array` is set to `true`. """ as_vec(x, ::Val) = x as_vec(x::Tuple, v::Val) = tuple((as_vec(xi, v) for xi in x)...) as_vec(x::Ref, ::Val) = x[] as_vec(x::PhysicalParameter, ::Val{true}) = vec(x.data) as_vec(x::judiMultiSourceVector, ::Val{true}) = vec(x) as_src_list(x::Number, nsrc::Integer) = fill(x, nsrc) as_src_list(x::Vector{<:Number}, nsrc::Integer) = x as_src_list(::Nothing, nsrc::Integer) = fill(0, nsrc) ######### backward compat extend_gradient(model_full, model, array) = array ### Filter out PyObject none and nothing pynone(::AbstractArray) = false pynone(m) = (m == PyObject(nothing) || isnothing(m)) function filter_none(args::Tuple) out = filter(m-> ~pynone(m), args) out = length(out) == 1 ? out[1] : out return out end filter_none(x) = x function Gardner(vp::Array{T, N}; vwater=1.51) where {T<:Real, N} rho = (T(0.31) .* (T(1e3) .* vp).^(T(0.25))) # Make sure "water" is at 1 rho[vp .< vwater] .= 1 return rho end Gardner(vp::PhysicalParameter{T}; vwater=1.51) where T<:Real = PhysicalParameter(Gardner(vp.data; vwater=vwater), vp.n, vp.d, vp.o)
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
6564
export time_resample """ time_resample(data, geometry_in, dt_new) Resample the input data with sinc interpolation from the current time sampling (geometrty_in) to the new time sampling `dt_new`. Parameters * `data`: Data to be reampled. If data is a matrix, resamples each column. * `geometry_in`: Geometry on which `data` is defined. * `dt_new`: New time sampling rate to interpolate onto. """ function time_resample(data::AbstractArray{T, N}, G_in::Geometry, dt_new::Real) where {T<:Real, N} new_t = first(G_in.taxis[1]):dt_new:last(G_in.taxis[1]) return time_resample(data, G_in.taxis[1], new_t) end """ time_resample(data, dt_in, dt_new) Resample the input data with sinc interpolation from the current time sampling dt_in to the new time sampling `dt_new`. Parameters * `data`: Data to be reampled. If data is a matrix, resamples each column. * `dt_in`: Time sampling of input * `dt_new`: New time sampling rate to interpolate onto. """ function time_resample(data::AbstractArray{T, N}, t_in::StepRangeLen, t_new::StepRangeLen) where {T<:Real, N} dt_in, dt_new = step(t_in), step(t_new) if dt_new==dt_in idx1 = Int64(div((first(t_new) - first(t_in)), dt_new) + 1) return data[idx1:end, :] elseif (dt_new % dt_in) == 0 rate = Int64(div(dt_new, dt_in)) dataInterp = _time_resample(data, rate) idx1 = Int64(div((first(t_new) - first(t_in)), dt_new) + 1) return dataInterp[idx1:end, :] else @juditime "Data time sinc-interpolation" begin dataInterp = Float32.(SincInterpolation(data, t_in, t_new)) end return dataInterp end end time_resample(data::AbstractArray{T, N}, dt_in::Number, dt_new::Number, t::Number) where {T<:Real, N} = time_resample(data, 0:dt_in:(dt_in*ceil(t/dt_in)), 0:dt_new:(dt_new*ceil(t/dt_new))) """ time_resample(data, dt_in, geometry_in) Resample the input data with sinc interpolation from the current time sampling (dt_in) to the new time sampling `geometry_out`. Parameters * `data`: Data to be reampled. If data is a matrix, resamples each column. * `geometry_out`: Geometry on which `data` is to be interpolated. * `dt_in`: Time sampling rate of the `data.` """ function time_resample(data::AbstractArray{T, N}, dt_in::Real, G_out::Geometry{T}) where {T<:Real, N} currt = range(0f0, step=dt_in, length=size(data, 1)) return time_resample(data, currt, G_out.taxis[1]) end function time_resample(data::AbstractArray{T, N}, dt_in::Real, G_in::Geometry{T}, G_out::Geometry{T}) where {T<:Real, N} t0 = min(get_t0(G_in, 1), get_t0(G_out, 1)) currt = range(t0, step=dt_in, length=size(data, 1)) dout = time_resample(data, currt, G_out.taxis[1]) if size(dout, 1) != G_out.nt[1] @show currt, G_out.taxis[1], size(data, 1), size(dout, 1), G_out.nt[1] end return dout end _time_resample(data::Matrix{T}, rate::Integer) where T = data[1:rate:end, :] _time_resample(data::PermutedDimsArray{T, 2, (2, 1), (2, 1), Matrix{T}}, rate::Integer) where {T<:Real} = data.parent[:, 1:rate:end]' SincInterpolation(Y::AbstractMatrix{T}, S::StepRangeLen{T}, Up::StepRangeLen{T}) where T<:Real = sinc.( (Up .- S') ./ (S[2] - S[1]) ) * Y """ _maybe_pad_t0(q, qGeom, data, dataGeom) Pad zeros for data with non-zero t0, usually from a segy file so that time axis and array size match for the source and data. """ function _maybe_pad_t0(qIn::Matrix{T}, qGeom::Geometry, dObserved::Matrix{T}, dataGeom::Geometry, dt::T=qGeom.dt[1]) where T<:Number dt0 = get_t0(dataGeom, 1) - get_t0(qGeom, 1) Dt = get_t(dataGeom, 1) - get_t(qGeom, 1) dsize = size(qIn, 1) - size(dObserved, 1) # Same times, do nothing if dsize == 0 && dt0 == 0 && Dt == 0 return qIn, dObserved # First case, same size, then it's a shift elseif dsize == 0 && dt0 != 0 && Dt != 0 # Shift means both t0 and t same sign difference @assert sign(dt0) == sign(Dt) pad_size = Int(div(abs(dt0), dt)) if dt0 > 0 # Data has larger t0, pad data left and q right dObserved = vcat(zeros(T, pad_size, size(dObserved, 2)), dObserved) qIn = vcat(qIn, zeros(T, pad_size, size(qIn, 2))) else # q has larger t0, pad data right and q left dObserved = vcat(dObserved, zeros(T, pad_size, size(dObserved, 2))) qIn = vcat(zeros(T, pad_size, size(qIn, 2)), qIn) end elseif dsize !=0 # We might still have differnt t0 and t # Pad so that we go from smaller dt to largest t ts = min(get_t0(qGeom, 1), get_t0(dataGeom, 1)) te = max(get_t(qGeom, 1), get_t(dataGeom, 1)) pdatal = Int(div(get_t0(dataGeom, 1) - ts, dt)) pdatar = Int(div(te - get_t(dataGeom, 1), dt)) dObserved = vcat(zeros(T, pdatal, size(dObserved, 2)), dObserved, zeros(T, pdatar, size(dObserved, 2))) pql = Int(div(get_t0(qGeom, 1) - ts, dt)) pqr = Int(div(te - get_t(qGeom, 1), dt)) qIn = vcat(zeros(T, pql, size(qIn, 2)), qIn, zeros(T, pqr, size(qIn, 2))) # Pad in case of mismatch leftover = size(qIn, 1) - size(dObserved, 1) if leftover > 0 dObserved = vcat(dObserved, zeros(T, leftover, size(dObserved, 2))) elseif leftover < 0 qIn = vcat(qIn, zeros(T, -leftover, size(qIn, 2))) end else throw(judiMultiSourceException(""" Data and source have different t0 : $((get_t0(dataGeom, 1), get_t0(qGeom, 1))) and t: $((get_t(dataGeom, 1), get_t(qGeom, 1))) and are not compatible in size for padding: $((size(qIn, 1), size(dObserved, 1)))""")) end return qIn, dObserved end pad_msg = """ This is an internal method for single source propatation, only single-source judiVectors are supported """ function _maybe_pad_t0(qIn::judiVector{T, Matrix{T}}, dObserved::judiVector{T, Matrix{T}}, dt=In.geometry.dt[1]) where{T<:Number} @assert qIn.nsrc == 1 || throw(judiMultiSourceException(pad_msg)) return _maybe_pad_t0(qIn.data[1], qIn.geometry[1], dObserved.data[1], dObserved.geometry[1], dt) end _maybe_pad_t0(qIn::judiVector{T, AT}, dObserved::judiVector{T, AT}, dt=qIn.geometry.dt[1]) where{T<:Number, AT} = _maybe_pad_t0(get_data(qIn), get_data(dObserved), dt) _maybe_pad_t0(qIn::Matrix{T}, qGeom::Geometry, dataGeom::Geometry, dt=qGeom.dt[1]) where T<:Number = _maybe_pad_t0(qIn, qGeom, zeros(T, length(dataGeom.t0[1]:dt:dataGeom.t[1]), 1) , dataGeom, dt)[1]
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
4236
# Test 2D modeling # The receiver positions and the source wavelets are the same for each of the four experiments. # Author: Philipp Witte, [email protected] # Date: January 2017 # # Mathias Louboutin, [email protected] # Updated July 2020 using JUDI using Test, Printf, Aqua using SegyIO, LinearAlgebra, Distributed, JOLI using TimerOutputs: TimerOutputs, @timeit set_verbosity(false) # Collect timing and allocations information to show in a clear way. const TIMEROUTPUT = TimerOutputs.TimerOutput() timeit_include(path::AbstractString) = @timeit TIMEROUTPUT path include(path) # Utilities const success_log = Dict(true => "\e[32m SUCCESS \e[0m", false => "\e[31m FAILED \e[0m") # Test set const GROUP = get(ENV, "GROUP", "JUDI") # JUDI seismic utils include("seismic_utils.jl") const nlayer = 2 const tti = contains(GROUP, "TTI") const fs = contains(GROUP, "FS") const viscoacoustic = contains(GROUP, "VISCO") # Utility macro to run block of code with a single omp threa macro single_threaded(expr) return quote nthreads = ENV["OMP_NUM_THREADS"] ENV["OMP_NUM_THREADS"] = "1" local val = $(esc(expr)) ENV["OMP_NUM_THREADS"] = nthreads val end end # Testing Utilities include("testing_utils.jl") base = ["test_geometry.jl", "test_judiVector.jl", "test_composite.jl", "test_judiWeights.jl", "test_judiWavefield.jl", "test_linear_operators.jl", "test_physicalparam.jl", "test_compat.jl"] devito = ["test_all_options.jl", "test_linearity.jl", "test_preconditioners.jl", "test_adjoint.jl", "test_jacobian.jl", "test_gradients.jl", "test_multi_exp.jl", "test_rrules.jl"] extras = ["test_modeling.jl", "test_basics.jl", "test_linear_algebra.jl"] issues = ["test_issues.jl"] # custom if endswith(GROUP, ".jl") timeit_include(GROUP) end # Basic JUDI objects tests, no Devito if GROUP == "JUDI" || GROUP == "All" for t=base timeit_include(t) try Base.GC.gc(); catch; gc() end end # Test resolved issues Due to some data type incomaptibilities only test 1.7 if VERSION >= v"1.7" for t=issues timeit_include(t) try Base.GC.gc(); catch; gc() end end end end # Generic mdeling tests if GROUP == "BASICS" || GROUP == "All" println("JUDI generic modelling tests") for t=extras timeit_include(t) @everywhere try Base.GC.gc(); catch; gc() end end end # Isotropic Acoustic tests if GROUP == "ISO_OP" || GROUP == "All" println("JUDI iso-acoustic operators tests (parallel)") # Basic test of LA/CG/LSQR needs for t=devito timeit_include(t) @everywhere try Base.GC.gc(); catch; gc() end end end # Isotropic Acoustic tests with a free surface if GROUP == "ISO_OP_FS" || GROUP == "All" println("JUDI iso-acoustic operators with free surface tests") for t=devito timeit_include(t) try Base.GC.gc(); catch; gc() end end end # Anisotropic Acoustic tests if GROUP == "TTI_OP" || GROUP == "All" println("JUDI TTI operators tests") set_devito_config("safe-math", true) # TTI tests for t=devito timeit_include(t) try Base.GC.gc(); catch; gc() end end end # Anisotropic Acoustic tests with free surface if GROUP == "TTI_OP_FS" || GROUP == "All" println("JUDI TTI operators with free surface tests") set_devito_config("safe-math", true) for t=devito timeit_include(t) try Base.GC.gc(); catch; gc() end end end # Viscoacoustic tests if GROUP == "VISCO_AC_OP" || GROUP == "All" println("JUDI Viscoacoustic operators tests") # Viscoacoustic tests for t=devito timeit_include(t) try Base.GC.gc(); catch; gc() end end end # Code quality check if GROUP == "AQUA" || GROUP == "All" || GROUP == "JUDI" @testset "code quality" begin # Prevent ambiguities from PyCall and other packages Aqua.test_all(JUDI; ambiguities=false) Aqua.test_ambiguities(JUDI; Aqua.askwargs(true)...) end end # Testing memory and runtime summary show(TIMEROUTPUT; compact=true, sortby=:firstexec)
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
4163
# Author: Mathias Louboutin, [email protected] # Date: July 2020 export setup_model, parse_commandline, setup_geom export example_src_geometry, example_rec_geometry, example_model, example_info """ Simple 2D model setup used for the tests. """ function smooth(v, sigma=3) v0 = 1f0 .* v for i=-sigma:sigma i != 0 && (v0[:, sigma+1:end-sigma] .+= v[:, sigma+i+1:end-sigma+i]) end v0[:, sigma+1:end-sigma] .*= 1/(2*sigma+1) return v0 end """ Sets up a simple 2D layered model for the wave equation operators tests """ function setup_model(tti=false, viscoacoustic=false, nlayer=2; n=(301, 151), d=(10., 10.)) tti && viscoacoustic && throw("The inputs can't be tti and viscoacoustic at the same time") ## Set up model structure o = (0., 0.) lw = n[2] ÷ nlayer v = ones(Float32, n) .* 1.5f0 vp_i = range(1.5f0, 3.5f0, length=nlayer) for i in range(2, nlayer, step=1) v[:, (i-1)*lw+ 1:end] .= vp_i[i] # Bottom velocity end v0 = smooth(v, 7) rho0 = (v .+ .5f0) ./ 2 # Slowness squared [s^2/km^2] m = (1f0 ./ v).^2 m0 = (1f0 ./ v0).^2 # Setup model structure if tti println("TTI Model") epsilon = smooth((v0[:, :] .- 1.5f0)/12f0, 3) delta = smooth((v0[:, :] .- 1.5f0)/14f0, 3) theta = smooth((v0[:, :] .- 1.5f0)/4, 3) .* rand([0, 1]) # makes sure VTI is tested model0 = Model(n, d, o, m0; epsilon=epsilon, delta=delta, theta=theta) model = Model(n, d, o, m; epsilon=epsilon, delta=delta, theta=theta) elseif viscoacoustic println("Viscoacoustic Model") qp0 = 3.516f0 .* ((v0 .* 1000f0).^2.2f0) .* 10f0^(-6f0) model = Model(n,d,o,m,rho0,qp0) model0 = Model(n,d,o,m0,rho0,qp0) else model = Model(n, d, o, m, rho0) model0 = Model(n, d, o, m0, rho0) @test all(Model(n, d, o, m0; rho=rho0).rho[:] .== rho0[:]) @test Model(n, d, o, m0; rho=rho0).rho == model0.rho end dm = model.m - model0.m return model, model0, dm end """ Sets up a simple 2D acquisition for the wave equation operators tests """ function setup_geom(model; nsrc=1, tn=1500f0, dt=nothing) ## Set up receiver geometry nxrec = size(model, 1) - 2 xrec = collect(range(spacing(model, 1), stop=(size(model, 1)-2)*spacing(model, 1), length=nxrec)) yrec = collect(range(0f0, stop=0f0, length=nxrec)) zrec = collect(range(50f0, stop=50f0, length=nxrec)) # receiver sampling and recording time T = tn # receiver recording time [ms] dt = isnothing(dt) ? .75f0 : dt # receiver sampling interval [ms] T = dt * div(T, dt) # Set up receiver structure recGeometry = Geometry(xrec, yrec, zrec; dt=dt, t=T, nsrc=nsrc) ## Set up source geometry (cell array with source locations for each shot) ex = (size(model, 1) - 1) * spacing(model, 1) nsrc > 1 ? xsrc = range(.25f0 * ex, stop=.75f0 * ex, length=nsrc) : xsrc = .5f0 * ex xsrc = convertToCell(xsrc) ysrc = convertToCell(range(0f0, stop=0f0, length=nsrc)) zsrc = convertToCell(range(2*spacing(model, 2), stop=2*spacing(model, 2), length=nsrc)) # Set up source structure srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dt, t=T) # setup wavelet f0 = 0.015f0 # MHz wavelet = ricker_wavelet(T, dt, f0) q = judiVector(srcGeometry, wavelet) return q, srcGeometry, recGeometry, f0 end # Example structures example_model(; n=(120,100), d=(10f0, 10f0), o=(0f0, 0f0), m=randn(Float32, n)) = Model(n, d, o, m) function example_rec_geometry(; nsrc=2, nrec=120, cut=false) startr = cut ? 150f0 : 50f0 endr = cut ? 1050f0 : 1150f0 xrec = range(startr, stop=endr, length=nrec) yrec = 0f0 zrec = range(50f0, stop=50f0, length=nrec) return Geometry(xrec, yrec, zrec; dt=4f0, t=1000f0, nsrc=nsrc) end function example_src_geometry(; nsrc=2) xsrc = nsrc == 1 ? 500f0 : range(300f0, stop=900f0, length=nsrc) ysrc = nsrc == 1 ? 0f0 : zeros(Float32, nsrc) zsrc = range(50f0, stop=50f0, length=nsrc) return Geometry(convertToCell(xsrc), convertToCell(ysrc), convertToCell(zsrc); dt=4f0, t=1000f0) end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
4275
# Adjoint test for F and J # Author: Mathias Louboutin, [email protected] # Date: May 2020 # nw = 2 # # Set parallel if specified if nw > 1 && nworkers() < nw addprocs(nw-nworkers() + 1; exeflags=["--code-coverage=user", "--inline=no", "--check-bounds=yes"]) end @everywhere using JUDI, LinearAlgebra, Test, Distributed ### Model model, model0, dm = setup_model(tti, viscoacoustic, nlayer) q, srcGeometry, recGeometry, f0 = setup_geom(model; nsrc=nw) dt = srcGeometry.dt[1] # testing parameters and utils tol = 5f-4 (tti && fs) && (tol = 5f-3) maxtry = viscoacoustic ? 5 : 3 ################################################################################################# # adjoint test utility function so that can retry if fails function run_adjoint(F, q, y, dm; test_F=true, test_J=true) adj_F, adj_J = !test_F, !test_J if test_F # Forward-adjoint d_hat = F*q q_hat = F'*y # Result F a = dot(y, d_hat) b = dot(q, q_hat) @printf(" <F x, y> : %2.5e, <x, F' y> : %2.5e, relative error : %2.5e \n", a, b, (a - b)/(a + b)) adj_F = isapprox(a/(a+b), b/(a+b), atol=tol, rtol=0) end if test_J # Linearized modeling J = judiJacobian(F, q) ld_hat = J*dm dm_hat = J'*y c = dot(ld_hat, y) d = dot(dm_hat, dm) @printf(" <J x, y> : %2.5e, <x, J' y> : %2.5e, relative error : %2.5e \n", c, d, (c - d)/(c + d)) adj_J = isapprox(c/(c+d), d/(c+d), atol=tol, rtol=0) end return adj_F, adj_J end test_adjoint(f::Bool, j::Bool, last::Bool) = (test_adjoint(f, last), test_adjoint(j, last)) test_adjoint(adj::Bool, last::Bool) = (adj || last) ? (@test adj) : (@test_skip adj) ################################################################################################### # Modeling operators @testset "Adjoint test with $(nlayer) layers and tti $(tti) and viscoacoustic $(viscoacoustic) and freesurface $(fs)" begin @timeit TIMEROUTPUT "Adjoint" begin opt = Options(sum_padding=true, dt_comp=dt, free_surface=fs, f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) @show q.nsrc # Nonlinear modeling y = F*q # Run test until succeeds in case of bad case adj_F, adj_J = false, false ntry = 0 while (!adj_F || !adj_J) && ntry < maxtry wave_rand = (.5f0 .+ rand(Float32, size(q.data[1]))).*q.data[1] q_rand = judiVector(srcGeometry, wave_rand) adj_F, adj_J = run_adjoint(F, q_rand, y, dm; test_F=!adj_F, test_J=!adj_J) ntry +=1 test_adjoint(adj_F, adj_J, ntry==maxtry) end println("Adjoint test after $(ntry) tries, F: $(success_log[adj_F]), J: $(success_log[adj_J])") end end ################################################################################################### # Extended source modeling @testset "Extended source adjoint test with $(nlayer) layers and tti $(tti) and viscoacoustic $(viscoacoustic) and freesurface $(fs)" begin @timeit TIMEROUTPUT "Extended source adjoint" begin opt = Options(sum_padding=true, dt_comp=dt, free_surface=fs, f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) Pr = judiProjection(recGeometry) Fw = judiModeling(model0; options=opt) Pw = judiLRWF(srcGeometry.dt[1], circshift(q.data[1], 51)) Fw = Pr*Fw*adjoint(Pw) # Extended source weights w = zeros(Float32, model0.n...) w[141:160, 65:84] .= randn(Float32, 20, 20) w = judiWeights(w; nsrc=nw) # Nonlinear modeling y = F*q # Run test until succeeds in case of bad case adj_F, adj_J = false, false ntry = 0 while (!adj_F || !adj_J) && ntry < maxtry wave_rand = (.5f0 .+ rand(Float32, size(q.data[1]))).*q.data[1] q_rand = judiVector(srcGeometry, wave_rand) adj_F, adj_J = run_adjoint(F, q_rand, y, dm; test_F=!adj_F, test_J=!adj_J) ntry +=1 test_adjoint(adj_F, adj_J, ntry==maxtry) end println("Adjoint test after $(ntry) tries, F: $(success_log[adj_F]), J: $(success_log[adj_J])") end end rmprocs(workers())
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
7390
# Author: Mathias Louboutin, [email protected] # Date: July 2020 ### Model model, model0, dm = setup_model(tti, viscoacoustic, nlayer) q, srcGeometry, recGeometry, f0 = setup_geom(model) dt = srcGeometry.dt[1] @testset "Gradient options test with $(nlayer) layers and tti $(tti) and freesurface $(fs)" begin ##################################ISIC######################################################## printstyled("Testing isic \n"; color = :blue) @timeit TIMEROUTPUT "ISIC" begin opt = Options(sum_padding=true, free_surface=fs, IC="isic", f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) # Linearized modeling J = judiJacobian(F, q) @test norm(J*(0f0.*dm)) == 0 y0 = F*q y_hat = J*dm x_hat1 = adjoint(J)*y0 c = dot(y0, y_hat) d = dot(dm, x_hat1) @printf(" <J x, y> : %2.5e, <x, J' y> : %2.5e, relative error : %2.5e \n", c, d, c/d - 1) @test isapprox(c, d, rtol=5f-2) @test !isnan(norm(y0)) @test !isnan(norm(y_hat)) @test !isnan(norm(x_hat1)) end ##################################ISIC######################################################## printstyled("Testing fwi \n"; color = :blue) @timeit TIMEROUTPUT "fwi" begin opt = Options(sum_padding=true, free_surface=fs, IC="fwi", f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) # Linearized modeling J = judiJacobian(F, q) @test norm(J*(0f0.*dm)) == 0 y0 = F*q y_hat = J*dm x_hat1 = adjoint(J)*y0 c = dot(y0, y_hat) d = dot(dm, x_hat1) @printf(" <J x, y> : %2.5e, <x, J' y> : %2.5e, relative error : %2.5e \n", c, d, c/d - 1) @test isapprox(c, d, rtol=5f-2) @test !isnan(norm(y0)) @test !isnan(norm(y_hat)) @test !isnan(norm(x_hat1)) end ##################################checkpointing############################################### printstyled("Testing checkpointing \n"; color = :blue) @timeit TIMEROUTPUT "Checkpointing" begin opt = Options(sum_padding=true, free_surface=fs, optimal_checkpointing=true, f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) # Linearized modeling J = judiJacobian(F, q) y_hat = J*dm x_hat2 = adjoint(J)*y0 c = dot(y0, y_hat) d = dot(dm, x_hat2) @printf(" <J x, y> : %2.5e, <x, J' y> : %2.5e, relative error : %2.5e \n", c, d, c/d - 1) @test isapprox(c, d, rtol=1f-2) @test !isnan(norm(y_hat)) @test !isnan(norm(x_hat2)) end ##################################DFT######################################################### printstyled("Testing DFT \n"; color = :blue) @timeit TIMEROUTPUT "DFT" begin opt = Options(sum_padding=true, free_surface=fs, frequencies=[2.5, 4.5], f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) # Linearized modeling J = judiJacobian(F, q) @test norm(J*(0f0.*dm)) == 0 y_hat = J*dm x_hat3 = adjoint(J)*y0 c = dot(y0, y_hat) d = dot(dm, x_hat3) @printf(" <J x, y> : %2.5e, <x, J' y> : %2.5e, relative error : %2.5e \n", c, d, c/d - 1) @test !isnan(norm(y_hat)) @test !isnan(norm(x_hat3)) end ################################## DFT time subsampled######################################### printstyled("Testing subsampled in time DFT \n"; color = :blue) @timeit TIMEROUTPUT "Subsampled DFT" begin opt = Options(sum_padding=true, free_surface=fs, frequencies=[2.5, 4.5], dft_subsampling_factor=4, f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) # Linearized modeling J = judiJacobian(F, q) @test norm(J*(0f0.*dm)) == 0 y_hat = J*dm x_hat3 = adjoint(J)*y0 c = dot(y0, y_hat) d = dot(dm, x_hat3) @printf(" <J x, y> : %2.5e, <x, J' y> : %2.5e, relative error : %2.5e \n", c, d, c/d - 1) @test !isnan(norm(y_hat)) @test !isnan(norm(x_hat3)) end ##################################subsampling################################################# printstyled("Testing subsampling \n"; color = :blue) @timeit TIMEROUTPUT "Subsampling" begin opt = Options(sum_padding=true, free_surface=fs, subsampling_factor=4, f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) # Linearized modeling J = judiJacobian(F, q) y_hat = J*dm x_hat4 = adjoint(J)*y0 c = dot(y0, y_hat) d = dot(dm, x_hat4) @printf(" <J x, y> : %2.5e, <x, J' y> : %2.5e, relative error : %2.5e \n", c, d, c/d - 1) @test isapprox(c, d, rtol=1f-2) @test !isnan(norm(y_hat)) @test !isnan(norm(x_hat4)) end ##################################ISIC + DFT ######################################################### printstyled("Testing isic+dft \n"; color = :blue) @timeit TIMEROUTPUT "ISIC+DFT" begin opt = Options(sum_padding=true, free_surface=fs, IC="isic", frequencies=[2.5, 4.5], f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) # Linearized modeling J = judiJacobian(F, q) @test norm(J*(0f0.*dm)) == 0 y_hat = J*dm x_hat5 = adjoint(J)*y0 c = dot(y0, y_hat) d = dot(dm, x_hat5) @printf(" <J x, y> : %2.5e, <x, J' y> : %2.5e, relative error : %2.5e \n", c, d, c/d - 1) @test !isnan(norm(y_hat)) @test !isnan(norm(x_hat5)) end ##################################fwi + DFT ######################################################### printstyled("Testing fwi+dft \n"; color = :blue) @timeit TIMEROUTPUT "FWI+DFT" begin opt = Options(sum_padding=true, free_surface=fs, IC="fwi", frequencies=[2.5, 4.5], f0=f0) F = judiModeling(model0, srcGeometry, recGeometry; options=opt) # Linearized modeling J = judiJacobian(F, q) @test norm(J*(0f0.*dm)) == 0 y_hat = J*dm x_hat5 = adjoint(J)*y0 c = dot(y0, y_hat) d = dot(dm, x_hat5) @printf(" <J x, y> : %2.5e, <x, J' y> : %2.5e, relative error : %2.5e \n", c, d, c/d - 1) @test !isnan(norm(y_hat)) @test !isnan(norm(x_hat5)) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
7687
# Author: Mathias Louboutin, [email protected] # Date: May 2020 # ftol = 1f-6 function test_model(ndim; tti=false, elas=false, visco=false) n = Tuple(121 for i=1:ndim) # non zero origin to check 'limit_model_to_receiver_area' o = (10, 0, 0)[1:ndim] d = Tuple(10. for i=1:ndim) m = .5f0 .+ rand(Float32, n...) if tti epsilon = .1f0 * m delta = .05f0 * m theta = .23f0 * m phi = .12f0 * m model = Model(n, d, o, m; nb=10, epsilon=epsilon, delta=delta, theta=theta, phi=phi) @test all(k in JUDI._mparams(model) for k in [:m, :epsilon, :delta, :theta, :phi]) @test isa(model, JUDI.TTIModel) delta2 = 1.1f0 * model.epsilon @test sum(delta2 .>= epsilon) == length(delta2) JUDI._clip_delta!(delta2, model.epsilon) @test sum(delta2 .>= epsilon) == 0 elseif elas vs = .1f0 * m model = Model(n, d, o, m; nb=10, vs=vs,) @test all(k in JUDI._mparams(model) for k in [:lam, :mu, :b]) @test isa(model, JUDI.IsoElModel) elseif visco qp = .1f0 * m model = Model(n, d, o, m; nb=10, qp=qp) @test all(k in JUDI._mparams(model) for k in [:m, :qp, :rho]) @test isa(model, JUDI.ViscIsoModel) else model = Model(n, d, o, m; nb=10) @test [JUDI._mparams(model)...] == [:m, :rho] @test isa(model, JUDI.IsoModel) end return model end function test_density(ndim) n = Tuple(121 for i=1:ndim) # non zero origin to check 'limit_model_to_receiver_area' o = (10, 0, 0)[1:ndim] d = Tuple(10. for i=1:ndim) m = .5f0 .+ rand(Float32, n...) rho = rand(Float32, n) .+ 1f0 model = Model(n, d, o, m, rho; nb=0) @test :rho in JUDI._mparams(model) modelpy = devito_model(model, Options()) @test isapprox(modelpy.irho.data, 1 ./ model.rho) rho[61] = 1000 model = Model(n, d, o, m, rho; nb=0) @test :rho in JUDI._mparams(model) modelpy = devito_model(model, Options()) @test isapprox(modelpy.rho.data, model.rho) end # Test padding and its adjoint function test_padding(ndim) model = test_model(ndim; tti=false) modelPy = devito_model(model, Options()) m0 = model.m mcut = remove_padding(deepcopy(modelPy.m.data), modelPy.padsizes; true_adjoint=true) mdata = deepcopy(modelPy.m.data) @show dot(m0, mcut)/dot(mdata, mdata) @test isapprox(dot(m0, mcut), dot(mdata, mdata)) end function test_limit_m(ndim, tti) model = test_model(ndim; tti=tti) @test get_dt(model) == calculate_dt(model) mloc = model.m model.m .*= 0f0 @test norm(model.m) == 0 model.m .= mloc @test model.m == mloc srcGeometry = example_src_geometry() recGeometry = example_rec_geometry(cut=true) buffer = 100f0 dm = rand(Float32, model.n...) dmb = PhysicalParameter(0 .* dm, model.n, model.d, model.o) new_mod, dm_n = limit_model_to_receiver_area(srcGeometry, recGeometry, deepcopy(model), buffer; pert=dm) # check new_mod coordinates # as long as func 'example_rec_geometry' uses '0' for 'y' we check only 'x' limits min_x = min(minimum(recGeometry.xloc[1]), minimum(srcGeometry.xloc[1])) max_x = max(maximum(recGeometry.xloc[1]), maximum(srcGeometry.xloc[1])) @test isapprox(new_mod.o[1], min_x-buffer; rtol=ftol) @test isapprox(new_mod.o[1] + new_mod.d[1]*(new_mod.n[1]-1), max_x+buffer; rtol=ftol) # check inds # 5:115 because of origin[1] = 10 (if origin[1] = 0 then 6:116) inds = ndim == 3 ? [5:115, 1:11, 1:121] : [5:115, 1:121] @test new_mod.n[1] == 111 @test new_mod.n[end] == 121 if ndim == 3 @test new_mod.n[2] == 11 end @test isapprox(new_mod.m, model.m[inds...]; rtol=ftol) @test isapprox(dm_n, vec(dm[inds...]); rtol=ftol) if tti @test isapprox(new_mod.epsilon, model.epsilon[inds...]; rtol=ftol) @test isapprox(new_mod.delta, model.delta[inds...]; rtol=ftol) @test isapprox(new_mod.theta, model.theta[inds...]; rtol=ftol) @test isapprox(new_mod.phi, model.phi[inds...]; rtol=ftol) end dmt = PhysicalParameter(dm_n, new_mod.n, model.d, new_mod.o) ex_dm = dmb + dmt @test ex_dm.o == model.o @test ex_dm.n == model.n @test ex_dm.d == model.d @test norm(ex_dm) == norm(dm_n) end function setup_3d() xrec = Array{Any}(undef, 2) yrec = Array{Any}(undef, 2) zrec = Array{Any}(undef, 2) for i=1:2 xrec[i] = i .+ collect(0:10) yrec[i] = i .+ collect(0:10) zrec[i] = i end x3d, y3d, z3d = setup_3D_grid(xrec[1],yrec[1],zrec[1]) for k=1:11 @test all(y3d[(11*(k-1))+1:(11*(k-1))+11] .== k) @test all(x3d[k:11:end] .== k) end @test all(z3d[:] .== 1) x3d, y3d, z3d = setup_3D_grid(xrec,yrec,zrec) for i=1:2 for k=1:11 @test all(y3d[i][(11*(k-1))+1:(11*(k-1))+11] .== k + i -1) @test all(x3d[i][k:11:end] .== k + i - 1) end @test all(z3d[i][:] .== i) end end function test_ftp() ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_model_2D.h5") @test isfile("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5") rm("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5") ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI", "overthrust_model_2D.h5") @test isfile("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5") rm("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5") end function test_serial() @test !get_serial() set_serial() @test get_serial() set_parallel() @test !get_serial() set_serial(true) @test get_serial() set_serial(false) @test !get_serial() end @testset "Test basic utilities" begin @timeit TIMEROUTPUT "Basic setup utilities" begin test_ftp() test_serial() setup_3d() for ndim=[2, 3] test_padding(ndim) test_density(ndim) end opt = Options(frequencies=[[2.5, 4.5], [3.5, 5.5]]) @test subsample(opt, 1).frequencies == [2.5, 4.5] @test subsample(opt, 2).frequencies == [3.5, 5.5] for ndim=[2, 3] for tti=[true, false] test_limit_m(ndim, tti) end end # Test model for ndim=[2, 3] for (tti, elas, visco) in [(false, false, false), (true, false, false), (false, true, false), (false, false, true)] model = test_model(ndim; tti=tti, elas=elas, visco=visco) # Default dt modelPy = devito_model(model, Options()) @test isapprox(modelPy.critical_dt, calculate_dt(model)) @test get_dt(model) == calculate_dt(model) @test isapprox(calculate_dt(model; dt=.5f0), .5f0) # Input dt modelPy = devito_model(model, Options(dt_comp=.5f0)) @test modelPy.critical_dt == .5f0 # Verify nt srcGeometry = example_src_geometry() recGeometry = example_rec_geometry(cut=true) nt1 = get_computational_nt(srcGeometry, recGeometry, model) nt2 = get_computational_nt(srcGeometry, model) nt3 = get_computational_nt(srcGeometry, recGeometry, model; dt=1f0) nt4 = get_computational_nt(srcGeometry, model; dt=1f0) dtComp = calculate_dt(model) @test all(nt1 .== length(0:dtComp:(dtComp*ceil(1000f0/dtComp)))) @test all(nt1 .== nt2) @test all(nt3 .== 1001) @test all(nt4 .== 1001) end end end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
1621
# Test backward compatibility ### Model nsrc = 2 model, model0, dm = setup_model(tti, viscoacoustic, nlayer) q, srcGeometry, recGeometry = setup_geom(model; nsrc=nsrc) dt = srcGeometry.dt[1] nt = srcGeometry.nt[1] nrec = length(recGeometry.xloc[1]) @testset "Backward compatibility" begin @timeit TIMEROUTPUT "Backward compatibility" begin info = Info(prod(model.n), nt, nsrc) @test_logs (:warn, "Info is deprecated and will be removed in future versions") Info(prod(model.G.n), nt, nsrc) @test_logs (:warn, "judiModeling(info::Info, ar...; kw...) is deprecated, use judiModeling(ar...; kw...)") judiModeling(info, model) @test_logs (:warn, "judiModeling(info::Info, ar...; kw...) is deprecated, use judiModeling(ar...; kw...)") judiModeling(info, model; options=Options()) @test_logs (:warn, "judiProjection(info::Info, ar...; kw...) is deprecated, use judiProjection(ar...; kw...)") judiProjection(info, recGeometry) @test_logs (:warn, "judiWavefield(info::Info, ar...; kw...) is deprecated, use judiWavefield(ar...; kw...)") judiWavefield(info, dt, nsrc, randn(nt, model.G.n...)) @test_logs (:warn, "Deprecated model.n, use size(model)") model.n @test_logs (:warn, "Deprecated model.d, use spacing(model)") model.d @test_logs (:warn, "Deprecated model.o, use origin(model)") model.o @test_logs (:warn, "Deprecated model.nb, use nbl(model)") model.nb @test_throws ArgumentError judiRHS(info, recGeometry, randn(Float32, nt, nrec)) @test_throws ArgumentError judiLRWF(info, nsrc, randn(nt)) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
6475
# Unit tests for judiComposite # Mathias Louboutin ([email protected]) # July 2021 # number of sources/receivers nsrc = 2 nrec = 120 ns = 251 ftol = 1f-6 @testset "judiVStack Unit Tests with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiVStack (nsrc=$(nsrc))" begin # set up judiVector from array n = (10, 10) # (x,y,z) or (x,z) dsize = (nsrc*nrec*ns, 1) rec_geometry = example_rec_geometry(nsrc=nsrc, nrec=nrec) data = randn(Float32, ns, nrec) d_obs = judiVector(rec_geometry, data) w0 = judiWeights([randn(Float32,n) for i = 1:nsrc]) # Composite objs c1 = [d_obs; w0] c1_b = deepcopy(c1) c1_z = similar(c1) c2 = [w0; d_obs] c2_b = deepcopy(c2) @test firstindex(c1) == 1 @test lastindex(c1) == 2 @test isapprox(length(c1), length(d_obs) + length(w0)) @test eltype(c1) == Float32 @test isfinite(c1) @test isapprox(c1[1], c1.components[1]) @test isapprox(c1.components[1], d_obs) @test isapprox(c2.components[2], d_obs) @test isapprox(c2.components[1], w0) @test isapprox(c1.components[2], w0) @test isapprox(c1.components[1], c1_b.components[1]) @test isapprox(c1.components[2], c1_b.components[2]) @test isapprox(c2.components[1], c2_b.components[1]) @test isapprox(c2.components[2], c2_b.components[2]) @test size(c1, 1) == length(d_obs) + length(w0) @test size(c2, 1) == length(d_obs) + length(w0) @test size(c1, 2) == 1 @test size(c2, 2) == 1 # Transpose c1_a = transpose(c1) @test size(c1_a, 1) == 1 @test size(c1_a, 2) == length(d_obs) + length(w0) @test isapprox(c1_a.components[1],d_obs) @test isapprox(c1_a.components[2], w0) # Adjoint c1_a = adjoint(c1) @test size(c1_a, 1) == 1 @test size(c1_a, 2) == length(d_obs) + length(w0) @test isapprox(c1_a.components[1], d_obs) @test isapprox(c1_a.components[2], w0) # Conj c1_a = conj(c1) @test size(c1_a, 2) == 1 @test size(c1_a, 1) == length(d_obs) + length(w0) @test isapprox(c1_a.components[1], d_obs) @test isapprox(c1_a.components[2], w0) # Test arithithmetic u = [d_obs; w0] v = [2f0 * d_obs; w0 + 1f0] w = [d_obs + 1f0; 2f0 * w0] a = .5f0 + rand(Float32) b = .5f0 + rand(Float32) @test isapprox(u + (v + w), (u + v) + w; rtol=ftol) @test isapprox(2f0*u, 2f0.*u; rtol=ftol) @test isapprox(u + v, v + u; rtol=ftol) @test isapprox(u, u + 0; rtol=ftol) @test iszero(norm(u + u*(-1))) @test isapprox(-u, -1f0 * u; rtol=ftol) @test isapprox(a .* (b .* u), (a * b) .* u; rtol=ftol) @test isapprox(u, u .* 1; rtol=ftol) @test isapprox(a .* (u + v), a .* u + a .* v; rtol=1f-5) @test isapprox((a + b) .* v, a .* v + b .* v; rtol=1f-5) # Test the norm u_scale = deepcopy(u) @test isapprox(norm(u_scale, 2), sqrt(norm(d_obs, 2)^2 + norm(w0, 2)^2)) @test isapprox(norm(u_scale, 2), sqrt(dot(u_scale, u_scale))) @test isapprox(norm(u_scale, 1), norm(d_obs, 1) + norm(w0, 1)) @test isapprox(norm(u_scale, Inf), max(norm(d_obs, Inf), norm(w0, Inf))) @test isapprox(norm(u_scale - 1f0, 1), norm(u_scale .- 1f0, 1)) @test isapprox(norm(1f0 - u_scale, 1), norm(1f0 .- u_scale, 1)) @test isapprox(norm(u_scale/2f0, 1), norm(u_scale, 1)/2f0) # Test broadcasting u_scale = deepcopy(u) v_scale = deepcopy(v) u_scale .*= 2f0 @test isapprox(u_scale, 2f0 * u) v_scale .+= 2f0 @test isapprox(v_scale, 2f0 + v) u_scale ./= 2f0 @test isapprox(u_scale, u) u_scale .= 2f0 .* u_scale .+ v_scale @test isapprox(u_scale, 2f0 * u + (2f0 + v)) u_scale .= u .+ v @test isapprox(u_scale, u + v) u_scale .= u .- v @test isapprox(u_scale, u - v) u_scale .= u .* v @test isapprox(u_scale[1], u[1].*v[1]) u_scale .= u ./ v @test isapprox(u_scale[1], u[1]./v[1]) # Test multi-vstack u1 = [u; 2f0*d_obs] u2 = [3f0*d_obs; u] @test size(u2) == size(u1) @test size(u2, 1) == u.m + length(d_obs) @test isapprox(u1.components[1], d_obs) @test isapprox(u1.components[2], w0) @test isapprox(u1.components[3], 2f0*d_obs) @test isapprox(u2.components[1], 3f0*d_obs) @test isapprox(u2.components[2], d_obs) @test isapprox(u2.components[3], w0) v1 = [u; 2f0 * w0] v2 = [3f0 * w0; u] @test size(v2) == size(v1) @test size(v2, 1) == u.m + length(w0) @test isapprox(v1.components[1], d_obs) @test isapprox(v1.components[2], w0) @test isapprox(v1.components[3], 2f0*w0) @test isapprox(v2.components[1], 3f0*w0) @test isapprox(v2.components[2], d_obs) @test isapprox(v2.components[3], w0) w1 = [c1; 2f0.*c2] w2 = [c2./2f0; c1] @test size(w1) == size(w2) @test size(w2, 1) == c1.m + c2.m @test isapprox(w1.components[1], d_obs) @test isapprox(w1.components[2], w0) @test isapprox(w1.components[3], 2f0*w0) @test isapprox(w1.components[4], 2f0*d_obs) @test isapprox(w2.components[1], w0 / 2f0) @test isapprox(w2.components[2], d_obs / 2f0) @test isapprox(w2.components[3], d_obs) @test isapprox(w2.components[4], w0) @test isapprox(w2.components[1], w0 / 2f0) @test isapprox(w2.components[2], d_obs / 2f0) @test isapprox(w2.components[3], d_obs) @test isapprox(w2.components[4], w0) # Test joDirac pertains judiWeights structure I = joDirac(nsrc*prod(n),DDT=Float32,RDT=Float32) @test isapprox(I*w0, w0) lambda = randn(Float32) @test isapprox(lambda*I*w0, lambda*w0) @test isapprox(I'*w0, w0) @test isapprox((lambda*I)'*w0, lambda * w0) # Test Forward and Adjoint joCoreBlock * judiVStack J = joOnes(nsrc*prod(n),DDT=Float32,RDT=Float32) a = [I;J]*w0 b = [w0; J*w0] @test isapprox(a[1], b[1]) @test isapprox(a[2:end], b[2:end]) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
10358
# Unit tests for JUDI Geometry structure # Philipp Witte ([email protected]) # May 2018 # # Mathias Louboutin, [email protected] # Updated July 2020 datapath = joinpath(dirname(pathof(JUDI)))*"/../data/" @testset "Geometry Unit Test with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "Geometry (nsrc=$(nsrc))" begin # Constructor if nt is not passed xsrc = convertToCell(range(100f0, stop=1100f0, length=2)[1:nsrc]) ysrc = convertToCell(range(0f0, stop=0f0, length=nsrc)) zsrc = convertToCell(range(20f0, stop=20f0, length=nsrc)) # Error handling @test_throws JUDI.GeometryException Geometry(xsrc, ysrc, zsrc; dt=.75f0, t=70f0) @test_throws JUDI.GeometryException Geometry(xsrc, ysrc, zsrc) # Geometry for testing geometry = Geometry(xsrc, ysrc, zsrc; dt=2f0, t=1000f0) geometry_t = Geometry(xsrc, ysrc, zsrc; dt=2, t=1000) @test geometry_t == geometry @test isa(geometry.xloc, Vector{Array{Float32,1}}) @test isa(geometry.yloc, Vector{Array{Float32,1}}) @test isa(geometry.zloc, Vector{Array{Float32,1}}) @test isa(geometry.nt, Vector{Int}) @test isa(geometry.dt, Vector{Float32}) @test isa(geometry.t, Vector{Float32}) @test isa(geometry.t0, Vector{Float32}) @test isa(geometry.taxis, Vector{<:StepRangeLen{Float32}}) # Constructor if coordinates are not passed as a cell arrays xsrc = range(100f0, stop=1100f0, length=2)[1:nsrc] ysrc = range(0f0, stop=0f0, length=nsrc) zsrc = range(20f0, stop=20f0, length=nsrc) geometry = Geometry(xsrc, ysrc, zsrc; dt=4f0, t=1000f0, nsrc=nsrc) @test isa(geometry.xloc, Vector{Array{Float32,1}}) @test isa(geometry.yloc, Vector{Array{Float32,1}}) @test isa(geometry.zloc, Vector{Array{Float32,1}}) @test isa(geometry.nt, Vector{Int}) @test isa(geometry.dt, Vector{Float32}) @test isa(geometry.t, Vector{Float32}) @test isa(geometry.t0, Vector{Float32}) @test isa(geometry.taxis, Vector{<:StepRangeLen{Float32}}) # Set up source geometry object from in-core data container block = segy_read(datapath*"unit_test_shot_records_$(nsrc).segy"; warn_user=false) src_geometry = Geometry(block; key="source", segy_depth_key="SourceSurfaceElevation") rec_geometry = Geometry(block; key="receiver", segy_depth_key="RecGroupElevation") @test isa(src_geometry, GeometryIC{Float32}) @test isa(rec_geometry, GeometryIC{Float32}) @test isequal(get_header(block, "SourceSurfaceElevation")[1], src_geometry.zloc[1][1]) @test isequal(get_header(block, "RecGroupElevation")[1], rec_geometry.zloc[1][1]) @test isequal(get_header(block, "SourceX")[1], src_geometry.xloc[1][1]) @test isequal(get_header(block, "GroupX")[1], rec_geometry.xloc[1][1]) # Set up geometry summary from out-of-core data container container = segy_scan(datapath, "unit_test_shot_records_$(nsrc)", ["GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"]) src_geometry = Geometry(container; key="source", segy_depth_key="SourceSurfaceElevation") rec_geometry = Geometry(container; key="receiver", segy_depth_key="RecGroupElevation") @test isa(src_geometry, GeometryOOC{Float32}) @test isa(rec_geometry, GeometryOOC{Float32}) @test isequal(src_geometry.key, "source") @test isequal(rec_geometry.key, "receiver") @test isequal(src_geometry.segy_depth_key, "SourceSurfaceElevation") @test isequal(rec_geometry.segy_depth_key, "RecGroupElevation") @test isequal(prod(size(block.data)), sum(rec_geometry.nrec .* rec_geometry.nt)) # Set up geometry summary from out-of-core data container passed as cell array container_cell = Array{SegyIO.SeisCon}(undef, nsrc) for j=1:nsrc container_cell[j] = split(container, j) end src_geometry = Geometry(container_cell; key="source", segy_depth_key="SourceSurfaceElevation") rec_geometry = Geometry(container_cell; key="receiver", segy_depth_key="RecGroupElevation") @test isa(src_geometry, GeometryOOC{Float32}) @test isa(rec_geometry, GeometryOOC{Float32}) @test isequal(src_geometry.key, "source") @test isequal(rec_geometry.key, "receiver") @test isequal(src_geometry.segy_depth_key, "SourceSurfaceElevation") @test isequal(rec_geometry.segy_depth_key, "RecGroupElevation") @test isequal(prod(size(block.data)), sum(rec_geometry.nrec .* rec_geometry.nt)) # Load geometry from out-of-core Geometry container src_geometry_ic = Geometry(src_geometry) rec_geometry_ic = Geometry(rec_geometry) @test isa(src_geometry_ic, GeometryIC{Float32}) @test isa(rec_geometry_ic, GeometryIC{Float32}) @test isequal(get_header(block, "SourceSurfaceElevation")[1], src_geometry_ic.zloc[1][1]) @test isequal(get_header(block, "RecGroupElevation")[1], rec_geometry_ic.zloc[1][1]) @test isequal(get_header(block, "SourceX")[1], src_geometry_ic.xloc[1][1]) @test isequal(get_header(block, "GroupX")[1], rec_geometry_ic.xloc[1][1]) # Subsample in-core geometry structure src_geometry_sub = subsample(src_geometry_ic, 1) @test isa(src_geometry_sub, GeometryIC{Float32}) @test isequal(length(src_geometry_sub.xloc), 1) src_geometry_sub = subsample(src_geometry_ic, 1:1) @test isa(src_geometry_sub, GeometryIC{Float32}) @test isequal(length(src_geometry_sub.xloc), 1) inds = nsrc > 1 ? (1:nsrc) : 1 src_geometry_sub = subsample(src_geometry_ic, inds) @test isa(src_geometry_sub, GeometryIC{Float32}) @test isequal(length(src_geometry_sub.xloc), nsrc) # Subsample out-of-core geometry structure src_geometry_sub = subsample(src_geometry, 1) @test isa(src_geometry_sub, GeometryOOC{Float32}) @test isequal(length(src_geometry_sub.dt), 1) @test isequal(src_geometry_sub.segy_depth_key, "SourceSurfaceElevation") src_geometry_sub = subsample(src_geometry, inds) @test isa(src_geometry_sub, GeometryOOC{Float32}) @test isequal(length(src_geometry_sub.dt), nsrc) @test isequal(src_geometry_sub.segy_depth_key, "SourceSurfaceElevation") # Compare if geometries match @test compareGeometry(src_geometry_ic, src_geometry_ic) @test compareGeometry(rec_geometry_ic, rec_geometry_ic) @test compareGeometry(src_geometry, src_geometry) @test compareGeometry(rec_geometry, rec_geometry) # test supershot geometry if nsrc == 2 # same geom geometry = Geometry(xsrc, ysrc, zsrc; dt=4f0, t=1000f0, nsrc=nsrc) sgeom = super_shot_geometry(geometry) @test get_nsrc(sgeom) == 1 @test sgeom.xloc[1] == xsrc @test sgeom.yloc[1] == ysrc @test sgeom.zloc[1] == zsrc @test sgeom.dt[1] == 4f0 @test sgeom.t[1] == 1000f0 # now make two geoms xall = collect(1f0:4f0) geometry = Geometry([[1f0, 2f0], [.5f0, 1.75f0]], [[0f0], [0f0]], [[0f0, 0f0], [0f0, 0f0]]; dt=4f0, t=1000f0) sgeom = super_shot_geometry(geometry) @test get_nsrc(sgeom) == 1 @test sgeom.xloc[1] == [.5f0, 1f0, 1.75f0, 2f0] @test sgeom.yloc[1] == [0f0] @test sgeom.zloc[1] == zeros(Float32, 4) @test sgeom.dt[1] == 4f0 @test sgeom.t[1] == 1000f0 end end @timeit TIMEROUTPUT "Geometry t0/t" begin # Test resample with different t0 and t # Same size but shited data1, data2 = rand(Float32, 10, 1), rand(Float32, 10, 1) taxis1 = 1f0:10f0 taxis2 = 2f0:11f0 g1 = Geometry([0f0], [0f0], [0f0], taxis1) g2 = Geometry([0f0], [0f0], [0f0], [taxis2]) d1r, d2r = JUDI._maybe_pad_t0(data1, g1, data2, g2) @test d1r[end] == 0 @test d2r[1] == 0 @test size(d1r) == size(d2r) == (11, 1) # Same t0 different t data1, data2 = rand(Float32, 11, 1), rand(Float32, 12, 1) taxis1 = 0f0:10f0 taxis2 = 0f0:11f0 g1 = Geometry([0f0], [0f0], [0f0], taxis1) g2 = Geometry([0f0], [0f0], [0f0], [taxis2]) d1r, d2r = JUDI._maybe_pad_t0(data1, g1, data2, g2) @test d1r[end] == 0 @test size(d1r) == size(d2r) == (12, 1) # Different t0 same t data1, data2 = rand(Float32, 11, 1), rand(Float32, 12, 1) taxis1 = 1f0:11f0 taxis2 = 0f0:11f0 g1 = Geometry([0f0], [0f0], [0f0], taxis1) g2 = Geometry([0f0], [0f0], [0f0], [taxis2]) d1r, d2r = JUDI._maybe_pad_t0(data1, g1, data2, g2) @test d1r[1] == 0 @test size(d1r) == size(d2r) == (12, 1) # Different t0 and t data1, data2 = rand(Float32, 10, 1), rand(Float32, 12, 1) taxis1 = 1f0:10f0 taxis2 = 0f0:11f0 g1 = Geometry([0f0], [0f0], [0f0], taxis1) g2 = Geometry([0f0], [0f0], [0f0], [taxis2]) d1r, d2r = JUDI._maybe_pad_t0(data1, g1, data2, g2) @test d1r[end] == 0 @test d1r[1] == 0 @test size(d1r) == size(d2r) == (12, 1) # Different t0 and t not contained in one data1, data2 = rand(Float32, 10, 1), rand(Float32, 12, 1) taxis1 = -1f0:8f0 taxis2 = 0f0:11f0 g1 = Geometry([0f0], [0f0], [0f0], taxis1) g2 = Geometry([0f0], [0f0], [0f0], [taxis2]) d1r, d2r = JUDI._maybe_pad_t0(data1, g1, data2, g2) @test all(d1r[11:13] .== 0) @test d2r[1] == 0 @test size(d1r) == size(d2r) == (13, 1) # Segy handling block = SeisBlock(randn(Float32, 10, 1)) set_header!(block, "nsOrig", 12) set_header!(block, "ns", 10) set_header!(block, "dt", 1000) set_header!(block, "dtOrig", 1000) segy_write("test.segy", block) block = segy_read("test.segy") g = Geometry(block) @test g.nt[1] == 10 @test g.dt[1] == 1f0 @test g.t0[1] == 2f0 @test g.t[1] == 11 rm("test.segy") end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
5166
# 2D LS-RTM gradient test with 1 source # The receiver positions and the source wavelets are the same for each of the four experiments. # Author: Philipp Witte, [email protected] # Date: January 2017 # # Mathias Louboutin, [email protected] # Updated July 2020 # # Ziyi Yin, [email protected] # Updated July 2021 ### Model model, model0, dm = setup_model(tti, viscoacoustic, 4) q, srcGeometry, recGeometry, f0 = setup_geom(model) dt = srcGeometry.dt[1] opt = Options(sum_padding=true, free_surface=fs, f0=f0) F = judiModeling(model, srcGeometry, recGeometry; options=opt) F0 = judiModeling(model0, srcGeometry, recGeometry; options=opt) J = judiJacobian(F0, q) # Observed data dobs = F*q dobs0 = F0*q dm1 = 2f0*circshift(dm, 10) ftol = (tti | fs | viscoacoustic) ? 1f-1 : 1f-2 ################################################################################################### @testset "FWI gradient test with $(nlayer) layers and tti $(tti) and viscoacoustic $(viscoacoustic) and freesurface $(fs)" begin # FWI gradient and function value for m0 Jm0, grad = fwi_objective(model0, q, dobs; options=opt) # Check get same misfit as l2 misifit on forward data Jm01 = .5f0 * norm(F(model0)*q - dobs)^2 @test Jm0 ≈ Jm01 grad_test(x-> .5f0*norm(F(;m=x)*q - dobs)^2, model0.m , dm, grad) end ################################################################################################### @testset "FWI preconditionners test with $(nlayer) layers and tti $(tti) and viscoacoustic $(viscoacoustic) and freesurface $(fs)" begin Ml = judiDataMute(q.geometry, dobs.geometry; t0=.2) Ml2 = judiTimeDerivative(dobs.geometry, 1) Jm0, grad = fwi_objective(model0, q, dobs; options=opt, data_precon=Ml) ghand = J'*Ml*(F0*q - dobs) @test isapprox(norm(grad - ghand)/norm(grad+ghand), 0f0; rtol=0, atol=ftol) Jm0, grad = fwi_objective(model0, q, dobs; options=opt, data_precon=[Ml, Ml2]) ghand = J'*Ml*Ml2*(F0*q - dobs) @test isapprox(norm(grad - ghand)/norm(grad+ghand), 0f0; rtol=0, atol=ftol) Jm0, grad = fwi_objective(model0, q, dobs; options=opt, data_precon=Ml*Ml2) @test isapprox(norm(grad - ghand)/norm(grad+ghand), 0f0; rtol=0, atol=ftol) end @testset "LSRTM preconditionners test with $(nlayer) layers and tti $(tti) and viscoacoustic $(viscoacoustic) and freesurface $(fs)" begin Mr = judiTopmute(model0; taperwidth=10) Ml = judiDataMute(q.geometry, dobs.geometry) Ml2 = judiTimeDerivative(dobs.geometry, 1) Mr2 = judiIllumination(J) Jm0, grad = lsrtm_objective(model0, q, dobs, dm; options=opt, data_precon=Ml, model_precon=Mr) ghand = J'*Ml*(J*Mr*dm - dobs) @test isapprox(norm(grad - ghand)/norm(grad+ghand), 0f0; rtol=0, atol=ftol) Jm0, grad = lsrtm_objective(model0, q, dobs, dm; options=opt, data_precon=[Ml, Ml2], model_precon=[Mr, Mr2]) ghand = J'*Ml*Ml2*(J*Mr2*Mr*dm - dobs) @test isapprox(norm(grad - ghand)/norm(grad+ghand), 0f0; rtol=0, atol=ftol) Jm0, grad = lsrtm_objective(model0, q, dobs, dm; options=opt, data_precon=Ml*Ml2, model_precon=Mr*Mr2) @test isapprox(norm(grad - ghand)/norm(grad+ghand), 0f0; rtol=0, atol=ftol) end ################################################################################################### @testset "LSRTM gradient test with $(nlayer) layers, tti $(tti), viscoacoustic $(viscoacoustic). freesurface $(fs), nlind $(nlind)" for nlind=[true, false] @timeit TIMEROUTPUT "LSRTM gradient test, nlind=$(nlind)" begin # LS-RTM gradient and function value for m0 dD = nlind ? (dobs - dobs0) : dobs Jm0, grad = lsrtm_objective(model0, q, dD, dm; options=opt, nlind=nlind) # Gradient test grad_test(x-> lsrtm_objective(model0, q, dD, x;options=opt, nlind=nlind)[1], dm, dm1, grad) # test that with zero dm we get the same as fwi_objective for residual if nlind Jls, gradls = @single_threaded lsrtm_objective(model0, q, dobs, 0f0.*dm; options=opt, nlind=true) Jfwi, gradfwi = @single_threaded fwi_objective(model0, q, dobs; options=opt) @test isapprox(Jls, Jfwi; rtol=0f0, atol=0f0) @test isapprox(gradls, gradfwi; rtol=0f0, atol=0f0) end end end # Test if lsrtm_objective produces the same value/gradient as is done by the correct algebra @testset "LSRTM gradient linear algebra test with $(nlayer) layers, tti $(tti), viscoacoustic $(viscoacoustic), freesurface $(fs)" begin # Draw a random case to avoid long CI. ic = rand(["isic", "fwi", "as"]) printstyled("LSRTM validity with dft, IC=$(ic)\n", color=:blue) @timeit TIMEROUTPUT "LSRTM validity with dft, IC=$(ic)" begin ftol = fs ? 1f-3 : 5f-4 freq = [[2.5, 4.5],[3.5, 5.5],[10.0, 15.0], [30.0, 32.0]] J.options.free_surface = fs J.options.IC = ic J.options.frequencies = freq d_res = dobs0 + J*dm1 - dobs Jm0_1 = 0.5f0 * norm(d_res)^2f0 grad_1 = @single_threaded J'*d_res opt = J.options Jm0, grad = @single_threaded lsrtm_objective(model0, q, dobs, dm1; options=opt, nlind=true) Jm01, grad1 = @single_threaded lsrtm_objective(model0, q, dobs-dobs0, dm1; options=opt, nlind=false) @test isapprox(grad, grad_1; rtol=ftol) @test isapprox(Jm0, Jm0_1; rtol=ftol) @test isapprox(grad, grad1; rtol=ftol) @test isapprox(Jm0, Jm01; rtol=ftol) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
4256
using JLD2 @testset "Test issue #83" begin @timeit TIMEROUTPUT "Issue 83" begin nxrec = 120 nyrec = 100 xrec = range(50f0, stop=1150f0, length=nxrec) yrec = range(100f0, stop=900f0, length=nyrec) zrec = 50f0 # Construct 3D grid from basis vectors (x3d, y3d, z3d) = setup_3D_grid(xrec, yrec, zrec) for k=1:nyrec s = (k - 1) * nxrec + 1 e = s + nxrec - 1 @test all(x3d[k:nxrec:end] .== xrec[k]) @test all(y3d[s:e] .== yrec[k]) end @test all(z3d .== zrec) end end @testset "Test backward comp issue" begin @timeit TIMEROUTPUT "Backward compatibility" begin datapath = joinpath(dirname(pathof(JUDI)))*"/../data/" # Load file with old judiVector type and julia <1.7 StepRangeLen @load "$(datapath)backward_comp.jld" dat @show dat.geometry @test typeof(dat) == judiVector{Float32, Matrix{Float32}} @test typeof(dat.geometry) == GeometryIC{Float32} @test typeof(dat.geometry.xloc) == Vector{Vector{Float32}} end end @testset "Test issue #130" begin @timeit TIMEROUTPUT "Issue 130" begin model, model0, dm = setup_model(tti, viscoacoustic, nlayer) q, srcGeometry, recGeometry, f0 = setup_geom(model; nsrc=1) opt = Options(save_data_to_disk=true, file_path=pwd(), # path to files file_name="test_wri") # saves files as file_name_xsrc_ysrc.segy F = judiModeling(model, srcGeometry, recGeometry; options=opt) dobs = F*q f, gm, gy = twri_objective(model0, q, dobs, nothing; options=opt, optionswri=TWRIOptions(params=:all)) @test typeof(f) <: Number @test typeof(gy) <: judiVector @test typeof(gm) <: PhysicalParameter end end @testset "Test issue #140" begin @timeit TIMEROUTPUT "Issue 140" begin n = (120, 100) # (x,y,z) or (x,z) d = (10., 10.) o = (0., 0.) v = ones(Float32,n) .+ 0.5f0 v[:,Int(round(end/2)):end] .= 3.5f0 rho = ones(Float32,n) ; rho[1,1] = .09;# error but .1 makes rho go to b and then it is happy m = (1f0 ./ v).^2 nsrc = 2 # number of sources model = Model(n, d, o, m;rho=rho) q, srcGeometry, recGeometry, f0 = setup_geom(model; nsrc=nsrc) F = judiModeling(model, srcGeometry, recGeometry) dobs = F*q @test ~isnan(norm(dobs)) end end @testset "Tests limit_m issue 156" begin @timeit TIMEROUTPUT "Issue 156" begin model, model0, dm = setup_model(tti, viscoacoustic, nlayer) q, srcGeometry, recGeometry, f0 = setup_geom(model; nsrc=1) # Restrict rec to middle of the model recGeometry.xloc[1] .= range(11*model.d[1], stop=(model.n[1] - 12)*model.d[1], length=length(recGeometry.xloc[1])) # Data F = judiModeling(model, srcGeometry, recGeometry) dobs = F*q # Run gradient and check output size opt = Options(limit_m=true, buffer_size=0f0) F0 = judiModeling(model0, srcGeometry, recGeometry; options=opt) # fwi wrapper g_ap = JUDI.multi_src_fg(model0, q , dobs, nothing, opt)[2] @test g_ap.n == (model.n .- (22, 0)) @test g_ap.o[1] == model.d[1]*11 g1 = fwi_objective(model0, q, dobs; options=opt)[2] @test g1.n == model.n @test norm(g1.data[1:10, :]) == 0 @test norm(g1.data[end-10:end, :]) == 0 # lsrtm wrapper g_ap = JUDI.multi_src_fg(model0, q , dobs, dm, opt, lin=true)[2] @test g_ap.n == (model.n .- (22, 0)) @test g_ap.o[1] == model.d[1]*11 g2 = lsrtm_objective(model0, q, dobs, dm; options=opt)[2] @test g2.n == model.n @test norm(g2.data[1:10, :]) == 0 @test norm(g2.data[end-10:end, :]) == 0 # Lin op Jp = judiJacobian(F0, q)' g_ap = JUDI.propagate(Jp, dobs) @test g_ap.n == (model.n .- (22, 0)) @test g_ap.o[1] == model.d[1]*11 g3 = Jp * dobs @test g3.n == model.n @test norm(g3.data[1:10, :]) == 0 @test norm(g3.data[end-10:end, :]) == 0 end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
2645
# Example for basic 2D modeling: # The receiver positions and the source wavelets are the same for each of the four experiments. # Author: Philipp Witte, [email protected] # Date: January 2017 # # Author: Mathias Louboutin, [email protected] # Update Date: July 2020 ### Model model, model0, dm = setup_model(tti, viscoacoustic, nlayer) q, srcGeometry, recGeometry, f0 = setup_geom(model; nsrc=2) dt = srcGeometry.dt[1] m0 = model0.m ######################## WITH DENSITY ############################################ @testset "Jacobian test with $(nlayer) layers and tti $(tti) and viscoacoustic $(viscoacoustic) freesurface $(fs)" begin @timeit TIMEROUTPUT "Jacobian generic tests" begin # Write shots as segy files to disk opt = Options(sum_padding=true, dt_comp=dt, free_surface=fs, f0=f0) # Setup operators F = judiModeling(model, srcGeometry, recGeometry; options=opt) F0 = judiModeling(model0, srcGeometry, recGeometry; options=opt) J = judiJacobian(F0, q) # Linear modeling dobs = F*q dD = J*dm dlin0 = J*(0f0.*dm) @test norm(dlin0) == 0 @test isapprox(dD, J*vec(dm.data); rtol=1f-6) # Gradient test grad_test(x-> F(;m=x)*q, m0, dm, dD; data=true) # Check return_array returns correct size with zero dm and multiple shots J.options.return_array = true dlin0v = J*(0f0.*dm) @test length(dlin0) == length(vec(dlin0)) end end ### Extended source @testset "Extended source Jacobian test with $(nlayer) layers and tti $(tti) and freesurface $(fs)" for ra=[true, false] @timeit TIMEROUTPUT "Extended source Jacobian return_array=$(ra)" begin opt = Options(sum_padding=true, dt_comp=dt, return_array=ra, free_surface=fs, f0=f0) DT = ra ? Vector{Float32} : judiVector{Float32, Matrix{Float32}} QT = ra ? Vector{Float32} : judiWeights{Float32} # Setup operators Pr = judiProjection(recGeometry) F = judiModeling(model; options=opt) F0 = judiModeling(model0; options=opt) Pw = judiLRWF(q.geometry.dt, q.data) # Combined operators A = Pr*F*adjoint(Pw) A0 = Pr*F0*adjoint(Pw) # Extended source weights w = judiWeights(randn(Float32, model0.n); nsrc=2) J = judiJacobian(A0, w) # Nonlinear modeling dobs = A0*w wa = adjoint(A0)*dobs @test typeof(dobs) == DT @test typeof(wa) == QT dD = J*dm @test typeof(dD) == DT # Gradient test grad_test(x-> A(;m=x)*w, m0, dm, dD; data=true) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
19896
# Unit tests for judiVector # Philipp Witte ([email protected]) # May 2018 # # Mathias Louboutin, [email protected] # Updated July 2020 datapath = joinpath(dirname(pathof(JUDI)))*"/../data/" # number of sources/receivers nrec = 120 ftol = 1e-6 ################################################# test constructors #################################################### @testset "judiVector Unit Tests with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiVector (nsrc=$(nsrc))" begin # set up judiVector from array dsize = (nsrc,) rec_geometry = example_rec_geometry(nsrc=nsrc, nrec=nrec) data = randn(Float32, rec_geometry.nt[1], nrec) d_obs = judiVector(rec_geometry, data) @test typeof(d_obs) == judiVector{Float32, Array{Float32, 2}} @test isequal(process_input_data(d_obs, rec_geometry), d_obs) @test isequal(process_input_data(d_obs), d_obs.data) @test isequal(d_obs.nsrc, nsrc) @test isequal(typeof(d_obs.data), Array{Array{Float32, 2}, 1}) @test isequal(typeof(d_obs.geometry), GeometryIC{Float32}) @test iszero(norm(d_obs.data[1] - d_obs.data[end])) @test isequal(size(d_obs), dsize) # set up judiVector from cell array data = Array{Array{Float32, 2}, 1}(undef, nsrc) for j=1:nsrc data[j] = randn(Float32, rec_geometry.nt[1], nrec) end d_obs = judiVector(rec_geometry, data) @test isequal(d_obs.nsrc, nsrc) @test isequal(typeof(d_obs.data), Array{Array{Float32, 2}, 1}) @test isequal(typeof(d_obs.geometry), GeometryIC{Float32}) @test iszero(norm(d_obs.data - d_obs.data)) @test isequal(size(d_obs), dsize) @test isapprox(convert_to_array(d_obs), vcat([vec(d) for d in data]...); rtol=ftol) # contructor for in-core data container block = segy_read(datapath*"unit_test_shot_records_$(nsrc).segy"; warn_user=false) d_block = judiVector(block; segy_depth_key="RecGroupElevation") dsize = (nsrc,) @test isequal(d_block.nsrc, nsrc) @test isequal(typeof(d_block.data), Array{Array{Float32, 2}, 1}) @test isequal(typeof(d_block.geometry), GeometryIC{Float32}) @test isequal(size(d_block), dsize) # contructor for in-core data container and given geometry rec_geometry = Geometry(block; key="receiver", segy_depth_key="RecGroupElevation") d_block = judiVector(rec_geometry, block) @test isequal(d_block.nsrc, nsrc) @test isequal(typeof(d_block.data), Array{Array{Float32, 2}, 1}) @test isequal(typeof(d_block.geometry), GeometryIC{Float32}) @test isequal(rec_geometry, d_block.geometry) @test isequal(size(d_block), dsize) # contructor for out-of-core data container from single container container = segy_scan(datapath, "unit_test_shot_records_$(nsrc)", ["GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"]) d_cont = judiVector(container; segy_depth_key="RecGroupElevation") @test typeof(d_cont) == judiVector{Float32, SeisCon} @test isequal(d_cont.nsrc, nsrc) @test isequal(typeof(d_cont.data), Array{SegyIO.SeisCon, 1}) @test isequal(typeof(d_cont.geometry), GeometryOOC{Float32}) @test isequal(size(d_cont), dsize) # contructor for single out-of-core data container and given geometry d_cont = judiVector(rec_geometry, container) @test isequal(d_cont.nsrc, nsrc) @test isequal(typeof(d_cont.data), Array{SegyIO.SeisCon, 1}) @test isequal(typeof(d_cont.geometry), GeometryIC{Float32}) @test isequal(rec_geometry, d_cont.geometry) @test isequal(size(d_cont), dsize) # contructor for out-of-core data container from cell array of containers container_cell = Array{SegyIO.SeisCon}(undef, nsrc) for j=1:nsrc container_cell[j] = split(container, j) end d_cont = judiVector(container_cell; segy_depth_key="RecGroupElevation") @test isequal(d_cont.nsrc, nsrc) @test isequal(typeof(d_cont.data), Array{SegyIO.SeisCon, 1}) @test isequal(typeof(d_cont.geometry), GeometryOOC{Float32}) @test isequal(size(d_cont), dsize) # contructor for out-of-core data container from cell array of containers and given geometry d_cont = judiVector(rec_geometry, container_cell) @test isequal(d_cont.nsrc, nsrc) @test isequal(typeof(d_cont.data), Array{SegyIO.SeisCon, 1}) @test isequal(typeof(d_cont.geometry), GeometryIC{Float32}) @test isequal(rec_geometry, d_cont.geometry) @test isequal(size(d_cont), dsize) ########## Test t0 ####### d_contt0 = judiVector(container; segy_depth_key="RecGroupElevation", t0=50f0) @test all(get_t0(d_contt0.geometry) .== 50f0) @test all(get_t(d_contt0.geometry) .== (get_t(d_cont.geometry) .+ 50f0)) @test all(get_nt(d_contt0.geometry) .== get_nt(d_cont.geometry)) # Time resampling adds back the t0 for consistent modeling data0 = get_data(d_contt0[1]).data[1] newdt = div(get_dt(d_contt0.geometry, 1), 2) dinterp = time_resample(data0, Geometry(d_contt0.geometry[1]), newdt) @test size(dinterp, 1) == 2*size(data0, 1) - 1 if nsrc == 2 @test_throws JUDI.judiMultiSourceException JUDI._maybe_pad_t0(d_cont, d_contt0) end _, dinterpt0 = JUDI._maybe_pad_t0(d_cont[1], d_contt0[1]) @test size(dinterpt0, 1) == size(data0, 1) + div(50f0, get_dt(d_contt0.geometry, 1)) #################################################### test operations ################################################### # conj, transpose, adjoint @test isequal(size(d_obs), size(conj(d_obs))) @test isequal(size(d_block), size(conj(d_block))) @test isequal(size(d_cont), size(conj(d_cont))) @test isequal(reverse(size(d_obs)), size(transpose(d_obs))) @test isequal(reverse(size(d_block)), size(transpose(d_block))) @test isequal(reverse(size(d_cont)), size(transpose(d_cont))) @test isequal(reverse(size(d_obs)), size(adjoint(d_obs))) @test isequal(reverse(size(d_block)), size(adjoint(d_block))) @test isequal(reverse(size(d_cont)), size(adjoint(d_cont))) # +, -, *, / @test iszero(norm(2*d_obs - (d_obs + d_obs))) @test iszero(norm(d_obs - (d_obs + d_obs)/2)) @test iszero(norm(2*d_block - (d_block + d_block))) @test iszero(norm(d_block - (d_block + d_block)/2)) # lmul!, rmul!, ldiv!, rdiv! data_ones = Array{Array{Float32, 2}, 1}(undef, nsrc) for j=1:nsrc data_ones[j] = ones(Float32, rec_geometry.nt[1], nrec) end d1 = judiVector(rec_geometry, data_ones) lmul!(2f0, d1) @test all([all(d1.data[i] .== 2f0) for i = 1:d1.nsrc]) rmul!(d1, 3f0) @test all([all(d1.data[i] .== 6f0) for i = 1:d1.nsrc]) ldiv!(2f0,d1) @test all([all(d1.data[i] .== 3f0) for i = 1:d1.nsrc]) rdiv!(d1, 3f0) @test all([all(d1.data[i] .== 1f0) for i = 1:d1.nsrc]) # vcat d_vcat = [d_block; d_block] @test isequal(length(d_vcat), 2*length(d_block)) @test isequal(d_vcat.nsrc, 2*d_block.nsrc) @test isequal(d_vcat.geometry.xloc[1], d_block.geometry.xloc[1]) # dot, norm, abs @test isapprox(norm(d_block), sqrt(dot(d_block, d_block))) @test isapprox(norm(d_cont), sqrt(dot(d_cont, d_cont))) @test isapprox(abs.(d_block.data[1]), abs(d_block).data[1]) # need to add iterate for JUDI vector # vector space axioms u = judiVector(rec_geometry, randn(Float32, rec_geometry.nt[1], nrec)) v = judiVector(rec_geometry, randn(Float32, rec_geometry.nt[1], nrec)) w = judiVector(rec_geometry, randn(Float32, rec_geometry.nt[1], nrec)) a = .5f0 + rand(Float32) b = .5f0 + rand(Float32) @test isapprox(u + (v + w), (u + v) + w; rtol=ftol) @test isapprox(u + v, v + u; rtol=ftol) @test isapprox(-u, -1f0 * u; rtol=ftol) @test iszero(norm(u + u*(-1))) @test isapprox(a .* (b .* u), (a * b) .* u; rtol=ftol) @test isapprox(u, u .* 1; rtol=ftol) @test isapprox(a .* (u + v), a .* u + a .* v; rtol=1f-5) @test isapprox((a + b) .* v, a .* v + b .* v; rtol=1f-5) # subsamling d_block_sub = d_block[1] @test isequal(d_block_sub.nsrc, 1) @test isequal(typeof(d_block_sub.geometry), GeometryIC{Float32}) @test isequal(typeof(d_block_sub.data), Array{Array{Float32, 2}, 1}) inds = nsrc > 1 ? (1:nsrc) : 1 d_block_sub = d_block[inds] @test isequal(d_block_sub.nsrc, nsrc) @test isequal(typeof(d_block_sub.geometry), GeometryIC{Float32}) @test isequal(typeof(d_block_sub.data), Array{Array{Float32, 2}, 1}) d_cont = judiVector(container_cell; segy_depth_key="RecGroupElevation") d_cont_sub = d_cont[1] @test isequal(d_cont_sub.nsrc, 1) @test isequal(typeof(d_cont_sub.geometry), GeometryOOC{Float32}) @test isequal(typeof(d_cont_sub.data), Array{SegyIO.SeisCon, 1}) d_cont_sub = d_cont[inds] @test isequal(d_cont_sub.nsrc, nsrc) @test isequal(typeof(d_cont_sub.geometry), GeometryOOC{Float32}) @test isequal(typeof(d_cont_sub.data), Array{SegyIO.SeisCon, 1}) # Conversion to SegyIO.Block src_geometry = Geometry(block; key="source", segy_depth_key="SourceSurfaceElevation") wavelet = randn(Float32, src_geometry.nt[1]) q = judiVector(src_geometry, wavelet) block_out = judiVector_to_SeisBlock(d_block, q; source_depth_key="SourceSurfaceElevation", receiver_depth_key="RecGroupElevation") @test isapprox(block.data, block_out.data) @test isapprox(get_header(block, "SourceX"), get_header(block_out, "SourceX"); rtol=1f-6) @test isapprox(get_header(block, "GroupX"), get_header(block_out, "GroupX"); rtol=1f-6) @test isapprox(get_header(block, "RecGroupElevation"), get_header(block_out, "RecGroupElevation"); rtol=1f-6) @test isequal(get_header(block, "ns"), get_header(block_out, "ns")) @test isequal(get_header(block, "dt"), get_header(block_out, "dt")) block_obs = judiVector_to_SeisBlock(d_obs, q; source_depth_key="SourceSurfaceElevation", receiver_depth_key="RecGroupElevation") d_obs1 = judiVector(block_obs) @test isapprox(d_obs1.data, d_obs.data) block_q = src_to_SeisBlock(q) q_1 = judiVector(block_q) for i = 1:nsrc vec(q_1.data[i]) == vec(q.data[i]) end # scale a = .5f0 + rand(Float32) d_scale = deepcopy(d_block) # Test norms d_ones = judiVector(rec_geometry, 2f0 .* ones(Float32, rec_geometry.nt[1], nrec)) @test isapprox(norm(d_ones, 2), sqrt(rec_geometry.dt[1]*nsrc*rec_geometry.nt[1]*nrec*4)) @test isapprox(norm(d_ones, 1), rec_geometry.dt[1]*nsrc*rec_geometry.nt[1]*nrec*2) @test isapprox(norm(d_ones, Inf), 2) # Indexing and utilities @test isfinite(d_obs) @test ndims(judiVector{Float32, Array{Float32, 2}}) == 1 @test isapprox(sum(d_obs), sum(sum([vec(d) for d in d_obs]))) d0 = copy(d_obs) fill!(d0, 0f0) @test iszero(norm(d0)) @test firstindex(d_obs) == 1 @test lastindex(d_obs) == nsrc @test axes(d_obs) == (Base.OneTo(nsrc),) @test ndims(d_obs) == 1 d0[1] = d_obs.data[1] @test isapprox(d0.data[1], d_obs.data[1]) # broadcast multiplication u = judiVector(rec_geometry, randn(Float32, rec_geometry.nt[1], nrec)) v = judiVector(rec_geometry, randn(Float32, rec_geometry.nt[1], nrec)) u_scale = deepcopy(u) v_scale = deepcopy(v) u_scale .*= 2f0 @test isapprox(u_scale, 2f0 * u; rtol=ftol) v_scale .+= 2f0 @test isapprox(v_scale, 2f0 + v; rtol=ftol) u_scale ./= 2f0 @test isapprox(u_scale, u; rtol=ftol) u_scale .= 2f0 .* u_scale .+ v_scale @test isapprox(u_scale, 2f0 * u + 2f0 + v; rtol=ftol) u_scale .= u .+ v @test isapprox(u_scale, u + v) u_scale .= u .- v @test isapprox(u_scale, u - v) u_scale .= u .* v @test isapprox(u_scale.data[1], u.data[1].*v.data[1]) u_scale .= u ./ v @test isapprox(u_scale.data[1], u.data[1]./v.data[1]) # broadcast identity u = judiVector(rec_geometry, randn(Float32, rec_geometry.nt[1], nrec)) v = judiVector(rec_geometry, randn(Float32, rec_geometry.nt[1], nrec)) u_id = deepcopy(u) v_id = deepcopy(v) broadcast!(identity, u_id, v_id) # copy v_id into u_id @test isapprox(v, v_id) @test isapprox(v, u_id) # in-place overwrite u = judiVector(rec_geometry, randn(Float32, rec_geometry.nt[1], nrec)) v = judiVector(rec_geometry, randn(Float32, rec_geometry.nt[1], nrec)) u_cp = deepcopy(u) v_cp = deepcopy(v) copy!(v_cp, u_cp) @test isapprox(u, u_cp) @test isapprox(u, v_cp) # similar d_zero = similar(d_block, Float32) @test isequal(d_zero.geometry, d_block.geometry) @test isequal(size(d_zero), size(d_block)) # retrieve out-of-core data d_get = get_data(d_cont) @test isapprox(d_block, d_get) # Test copies/similar w1 = deepcopy(d_obs) @test isapprox(w1, d_obs) w1 = similar(d_obs) @test w1.nsrc == d_obs.nsrc w1 .= d_obs @test w1.nsrc == d_obs.nsrc @test isapprox(w1.data, d_obs.data) # Test transducer q = judiVector(Geometry(0f0, 0f0, 0f0; dt=2, t=1000), randn(Float32, 501)) tr = transducer(q, (10, 10), 30, pi/2) @test length(tr.geometry.xloc[1]) == 22 @test tr.geometry.xloc[1][1:11] == range(-30., 30., length=11) @test tr.geometry.xloc[1][12:end] == range(-30., 30., length=11) @test all(tr.geometry.zloc[1][12:end] .== -10f0) @test all(tr.geometry.zloc[1][1:11] .== 0f0) q = judiVector(Geometry(0f0, 0f0, 0f0; dt=2, t=1000), randn(Float32, 501)) tr = transducer(q, (10, 10), 30, pi) @test length(tr.geometry.xloc[1]) == 22 @test isapprox(tr.geometry.zloc[1][1:11], range(30., -30., length=11); atol=1f-14, rtol=1f-14) @test isapprox(tr.geometry.zloc[1][12:end], range(30., -30., length=11); atol=1f-14, rtol=1f-14) @test isapprox(tr.geometry.xloc[1][12:end], -10f0*ones(11); atol=1f-14, rtol=1f-14) @test isapprox(tr.geometry.xloc[1][1:11], zeros(11); atol=1f-14, rtol=1f-14) # Test exception if number of samples in geometry doesn't match ns of data @test_throws JUDI.judiMultiSourceException judiVector(Geometry(0f0, 0f0, 0f0; dt=2, t=1000), randn(Float32, 10)) @test_throws JUDI.judiMultiSourceException judiVector(rec_geometry, randn(Float32, 10)) # Test integral & derivative refarray = Array{Array{Float32, 2}, 1}(undef, nsrc) for j=1:nsrc refarray[j] = randn(Float32, rec_geometry.nt[1], nrec) end d_orig = judiVector(rec_geometry, refarray) dt = rec_geometry.dt[1] d_cumsum = cumsum(d_orig) for i = 1:d_orig.nsrc @test isapprox(dt * cumsum(refarray[i],dims=1), d_cumsum.data[i]) end d_diff = diff(d_orig) for i = 1:d_orig.nsrc @test isapprox(1/dt * refarray[i][1,:], d_diff.data[i][1,:]) @test isapprox(d_diff.data[i][2:end,:], 1/dt * diff(refarray[i],dims=1)) end @test isapprox(cumsum(d_orig,dims=1),cumsum(d_orig)) @test isapprox(diff(d_orig,dims=1),diff(d_orig)) d_cumsum_rec = cumsum(d_orig,dims=2) for i = 1:d_orig.nsrc @test isapprox(cumsum(refarray[i],dims=2), d_cumsum_rec.data[i]) end d_diff_rec = diff(d_orig,dims=2) for i = 1:d_orig.nsrc @test isapprox(refarray[i][:,1], d_diff_rec.data[i][:,1]) @test isapprox(d_diff_rec.data[i][:,2:end], diff(refarray[i],dims=2)) end # test simsources with fixed rec geom if nsrc == 2 dic = judiVector(rec_geometry, refarray) for jvec in [dic, d_obs, d_cont] for nsim=1:3 M1 = randn(Float32, nsim, 2) ds = M1 * jvec @test ds.nsrc == nsim for s=1:nsim @test ds.data[s] ≈ mapreduce((x, y)->x*y, +, M1[s,:], get_data(jvec).data) end gtest = Geometry(jvec.geometry[1]) @test all(ds.geometry[i] == gtest for i=1:nsim) end end # test simsources with "marine" rec geom refarray = randn(Float32, 251, 2) dic = judiVector(example_src_geometry(), [refarray[:, 1:1], refarray[:, 2:2]]) for nsim=1:3 M1 = randn(Float32, nsim, 2) ds = M1 * dic @test ds.nsrc == nsim @test all(ds.geometry.nrec .== 2) for s=1:nsim @test ds.data[s] ≈ hcat(M1[s,1]*refarray[:, 1],M1[s, 2]*refarray[:, 2]) end @test ds.geometry[1].xloc[1][1] == dic.geometry[1].xloc[1][1] @test ds.geometry[1].xloc[1][2] == dic.geometry[2].xloc[1][1] end # Test "simsource" without reduction refarray = randn(Float32, 251, 4) dic = judiVector(example_src_geometry(), [refarray[:, 1:1], refarray[:, 2:2]]) M1 = randn(Float32, 2) @test all(dic.geometry.nrec .== 1) sd1 = simsource(M1, dic; reduction=nothing) @test sd1.nsrc == 2 @test all(sd1.geometry.nrec .== 2) @test norm(sd1.data[1][:, 2]) == 0 @test norm(sd1.data[2][:, 1]) == 0 @test isapprox(sd1.data[1][:, 1], M1[1]*refarray[:, 1]) @test isapprox(sd1.data[2][:, 2], M1[2]*refarray[:, 2]) dic = judiVector(example_rec_geometry(nsrc=2, nrec=2), [refarray[:, 1:2], refarray[:, 3:4]]) @test all(dic.geometry.nrec .== 2) sd1 = simsource(M1[:], dic; reduction=nothing) @test sd1.nsrc == 2 @test all(sd1.geometry.nrec .== 2) @test isapprox(sd1.data[1], M1[1]*refarray[:, 1:2]) @test isapprox(sd1.data[2], M1[2]*refarray[:, 3:4]) # Test minimal supershot (only keep common coordinates) geometry = Geometry([[1f0, 2f0], [.5f0, 2f0]], [[0f0], [0f0]], [[0f0, 0.25f0], [0f0, 0.25f0]]; dt=4f0, t=1000f0) refarray = randn(Float32, 251, 4) dic = judiVector(geometry, [refarray[:, 1:2], refarray[:, 3:4]]) M1 = randn(Float32, 1, 2) dsim = simsource(M1, dic; minimal=true) @test dsim.nsrc == 1 @test dsim.geometry.nrec[1] == 1 @test dsim.geometry.xloc[1] == [2f0] @test dsim.geometry.zloc[1] == [.25f0] # Check no common receiver errors geometry = Geometry([[1f0, 2f0], [.5f0, 1.5f0]], [[0f0], [0f0]], [[0f0, 0.25f0], [0f0, 0.25f0]]; dt=4f0, t=1000f0) refarray = randn(Float32, 251, 4) dic = judiVector(geometry, [refarray[:, 1:2], refarray[:, 3:4]]) M1 = randn(Float32, 1, 2) @test_throws ArgumentError dsim = simsource(M1, dic; minimal=true) end end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
3348
# Unit tests for judiWeights # Rafael Orozco ([email protected]) # July 2021 # # Mathias Louboutin, [email protected] # Updated July 2020 # number of sources/receivers nsrc = 1 nrec = 120 nx = 4 ny = 4 nt = 10 dt = 2f0 ftol = 1f-6 ################################################# test constructors #################################################### @testset "judiWavefield Unit Tests with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiWavefield (nsrc=$(nsrc))" begin # Extended source weights wf = Array{Array{Float32, 3}, 1}(undef, nsrc) for j=1:nsrc wf[j] = randn(Float32, nt, ny, ny) end w = judiWavefield(dt, wf) w1 = similar(w) .+ 1f0 @test isequal(length(w.data), nsrc) @test isequal(length(w.data), nsrc) @test isequal(w.nsrc, nsrc) @test isequal(typeof(w.data), Array{Array{Float32, 3}, 1}) @test isequal(size(w), (nsrc,)) @test isfinite(w) #################################################### test operations ################################################### # conj, transpose, adjoint @test isequal(size(w), size(conj(w))) @test isequal(reverse(size(w)), size(transpose(w))) @test isequal(reverse(size(w)), size(adjoint(w))) # +, -, *, / @test iszero(norm(2*w - (w + w))) @test iszero(norm(w - (w + w)/2)) @test iszero(norm(1f0 - w1)) @test isequal(norm(1f0 + w1, 1), 2f0 * norm(w1, 1)) #test unary operator @test iszero(norm((-w) - (-1*w))) # vcat w_vcat = [w; w] @test isequal(length(w_vcat), 2*length(w)) @test isequal(w_vcat.nsrc, 2*nsrc) @test isequal(length(w_vcat.data), 2*nsrc) # dot, norm, abs @test isapprox(norm(w), sqrt(dot(w, w))) @test isapprox(abs.(w.data[1]), abs(w).data[1]) # Test the norm d_ones = judiWavefield(nsrc, dt, 2f0 .* ones(Float32, nt, nx, ny)) @test isapprox(norm(d_ones, 2), sqrt(dt*nt*nx*ny*4*nsrc)) @test isapprox(norm(d_ones, 1), dt*nt*nx*ny*2*nsrc) @test isapprox(norm(d_ones, Inf), 2) # vector space axioms u = judiWavefield(nsrc, dt, randn(Float32, nt, nx, ny)) v = judiWavefield(nsrc, dt, randn(Float32, nt, nx, ny)) w = judiWavefield(nsrc, dt, randn(Float32, nt, nx, ny)) a = .5f0 + rand(Float32) b = .5f0 + rand(Float32) @test isapprox(u + (v + w), (u + v) + w; rtol=ftol) @test isapprox(u + v, v + u; rtol=ftol) @test isapprox(u, u + 0; rtol=ftol) @test iszero(norm(u + u*(-1))) @test isapprox(-u, (-1f0)*u; rtol=ftol) @test isapprox(a .* (b .* u), (a * b) .* u; rtol=ftol) @test isapprox(u, u .* 1; rtol=ftol) @test isapprox(a .* (u + v), a .* u + a .* v; rtol=1f-5) @test isapprox((a + b) .* v, a .* v + b.* v; rtol=1f-5) # test fft fw = fft(w) fwf = ifft(fw) @test isapprox(dot(fwf, w), real(dot(fw, fw)); rtol=ftol) @test isapprox(fwf, w; rtol=ftol) # SimSources if nsrc == 2 M = randn(Float32, 1, nsrc) sw = M*w @test sw.nsrc == 1 @test isapprox(sw.data[1], M[1]*w.data[1] + M[2]*w.data[2]) end end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
6395
# Unit tests for judiWeights # Rafael Orozco ([email protected]) # July 2021 # # Mathias Louboutin, [email protected] # Updated July 2020 # number of sources/receivers nrec = 120 weight_size_x = 4 weight_size_y = 4 ftol = 1f-6 ################################################# test constructors #################################################### @testset "judiWeights Unit Tests with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiWeights (nsrc=$(nsrc))" begin # Extended source weights w = judiWeights([randn(Float64,weight_size_x,weight_size_y) for i = 1:nsrc]) @test isequal(w.nsrc, nsrc) @test isequal(typeof(w.weights), Array{Array{Float32,2},1}) @test isequal(size(w), (nsrc,)) @test isfinite(w) w_cell = judiWeights(convertToCell([randn(Float32,weight_size_x,weight_size_y) for i = 1:nsrc])) @test isequal(w_cell.nsrc, nsrc) @test isequal(typeof(w_cell.weights), Array{Array{Float32, 2},1}) @test isequal(size(w_cell), (nsrc,)) @test isfinite(w_cell) w_multi = judiWeights(randn(Float64,weight_size_x,weight_size_y); nsrc=3) @test isequal(w_multi.nsrc, 3) @test isequal(typeof(w_multi.weights), Array{Array{Float32, 2},1}) @test isequal(size(w_multi), (3,)) @test isfinite(w_multi) @test isapprox(w_multi[1],w_multi[2]) @test isapprox(w_multi[2],w_multi[3]) I2 = ones(Float32, 1, nsrc*weight_size_x*weight_size_y) w2 = I2*w @test isapprox(w2[1], sum(sum(w.weights))) I2 = joOnes(1, nsrc*weight_size_x*weight_size_y; DDT=Float32, RDT=Float32) w2 = I2*w @test isapprox(w2[1], sum(sum(w.weights))) I3 = [I2;I2] w3 = I3*w @test isapprox(w3[1], sum(sum(w.weights))) @test isapprox(w3[2], sum(sum(w.weights))) #################################################### test operations ################################################### # Indexing/reshape/... @test isapprox(w[1].weights[1], w.weights[1]) @test isapprox(subsample(w, 1).weights[1], w.weights[1]) # conj, transpose, adjoint @test isequal(size(w), size(conj(w))) @test isequal(reverse(size(w)), size(transpose(w))) @test isequal(reverse(size(w)), size(adjoint(w))) # +, -, *, / @test iszero(norm(2*w - (w + w))) @test iszero(norm(w - (w + w)/2)) #test unary operator @test iszero(norm((-w) - (-1*w))) # Copies and iter utilities w2 = copy(w) @test isequal(w2.weights, w.weights) @test isequal(w2.nsrc, w.nsrc) @test firstindex(w) == 1 @test lastindex(w) == nsrc @test ndims(w) == 1 w2 = similar(w, Float32, 1:nsrc) @test isequal(w2.nsrc, w.nsrc) @test firstindex(w) == 1 @test lastindex(w) == nsrc @test ndims(w) == 1 w3 = similar(w, Float32, 1) @test isequal(w3.nsrc, 1) copy!(w2, w) @test isequal(w2.weights, w.weights) @test isequal(w2.nsrc, w.nsrc) @test firstindex(w) == 1 @test lastindex(w) == nsrc @test ndims(w) == 1 # vcat w_vcat = [w; w] @test isequal(length(w_vcat), 2*length(w)) @test isequal(w_vcat.nsrc, 2*w.nsrc) # dot, norm, abs @test isapprox(norm(w), sqrt(dot(w, w))) @test isapprox(abs.(w.weights[1]), abs(w).weights[1]) # max, min w_max_min = judiWeights([ones(Float32,weight_size_x,weight_size_y) for i = 1:nsrc]) w_max_min.weights[1][1,1] = 1f3 w_max_min.weights[nsrc][end,end] = 1f-3 @test isapprox(maximum(w_max_min),1f3) @test isapprox(minimum(w_max_min),1f-3) # Test the norm d_ones = judiWeights(2f0 .* ones(Float32, weight_size_x, weight_size_y); nsrc=nsrc) @test isapprox(norm(d_ones, 2), sqrt(nsrc*weight_size_x*weight_size_y*4)) @test isapprox(norm(d_ones, 2), sqrt(dot(d_ones, d_ones))) @test isapprox(norm(d_ones, 1), nsrc*weight_size_x*weight_size_y*2) @test isapprox(norm(d_ones, Inf), 2) # vector space axioms u = judiWeights(randn(Float32, weight_size_x, weight_size_y); nsrc=nsrc) v = judiWeights(randn(Float32, weight_size_x, weight_size_y); nsrc=nsrc) w = judiWeights(randn(Float32, weight_size_x, weight_size_y); nsrc=nsrc) a = .5f0 + rand(Float32) b = .5f0 + rand(Float32) @test isapprox(u + (v + w), (u + v) + w; rtol=ftol) @test isapprox(u + v, v + u; rtol=ftol) @test isapprox(u, u + 0; rtol=ftol) @test iszero(norm(u + u*(-1))) @test isapprox(-u, (-1f0)*u; rtol=ftol) @test isapprox(a .* (b .* u), (a * b) .* u; rtol=ftol) @test isapprox(u, u .* 1; rtol=ftol) @test isapprox(a .* (u + v), a .* u + a .* v; rtol=1f-5) @test isapprox((a + b) .* v, a .* v + b.* v; rtol=1f-5) # broadcast multiplication u = judiWeights(randn(Float32, weight_size_x, weight_size_y); nsrc=nsrc) v = judiWeights(randn(Float32, weight_size_x, weight_size_y); nsrc=nsrc) u_scale = deepcopy(u) v_scale = deepcopy(v) u_scale .*= 2f0 @test isapprox(u_scale, 2f0 * u; rtol=ftol) v_scale .+= 2f0 @test isapprox(v_scale, 2f0 + v; rtol=ftol) u_scale ./= 2f0 @test isapprox(u_scale, u; rtol=ftol) u_scale .= 2f0 .* u_scale .+ v_scale @test isapprox(u_scale, 2f0 * u + 2f0 + v; rtol=ftol) u_scale .= u .+ v @test isapprox(u_scale, u + v) u_scale .= u .- v @test isapprox(u_scale, u - v) u_scale .= u .* v @test isapprox(u_scale.weights[1], u.weights[1].*v.weights[1]) u_scale .= u ./ v @test isapprox(u_scale.weights[1], u.weights[1]./v.weights[1]) # Test copies/similar w1 = deepcopy(w) @test isapprox(w1, w) w1 = similar(w) @test w1.nsrc == w.nsrc w1 .= w @test w1.nsrc == w.nsrc @test isapprox(w1.weights, w.weights) # SimSources if nsrc == 2 M = randn(Float32, 1, nsrc) sw = M*w @test sw.nsrc == 1 @test isapprox(sw.data[1], M[1]*w.data[1] + M[2]*w.data[2]) end end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
2626
# Author: Mathias Louboutin, [email protected] # Date: July 2020 @testset "Arithmetic test with $(nlayer) layers and tti $(tti) and freesurface $(fs)" begin @timeit TIMEROUTPUT "LA Arithmetic tests" begin # Test 2D find_water_bottom dm2D = zeros(Float32,10,10) dm2D[:,6:end] .= 1f0 @test find_water_bottom(dm2D) == 6*ones(Integer,10) ### Model model, model0, dm = setup_model(tti, viscoacoustic, nlayer) wb = find_water_bottom(model.m .- maximum(model.m)) q, srcGeometry, recGeometry = setup_geom(model) dt = srcGeometry.dt[1] nt = length(q.data[1]) nrec = length(recGeometry.xloc[1]) opt = Options(free_surface=fs) opta = Options(free_surface=fs, return_array=true) ftol = 5f-5 w = judiWeights(randn(Float32, model0.n)) # Build operators Pr = judiProjection(recGeometry) F = judiModeling(model; options=opt) Fa = judiModeling(model; options=opta) Ps = judiProjection(srcGeometry) Pw = judiLRWF(q.geometry.dt[1], q.data[1]) J = judiJacobian(Pr*F*adjoint(Ps), q) Jw = judiJacobian(Pr*F*adjoint(Pw), w) dobs = Pr * F * Ps' * q dobsa = Pr * Fa * Ps' * q dobs_w = Pr * F * Pw' * w dobs_wa = Pr * Fa * Pw' * w dobs_out = 0f0 .* dobs dobs_outa = 0f0 .* dobsa dobs_w_out = 0f0 .* dobs_w dobs_w_outa = 0f0 .* dobs_wa q_out = 0f0 .* q w_out = 0f0 .* w # mul! mul!(dobs_out, Pr * F * Ps', q) mul!(dobs_w_out, Pr * F * Pw', w) mul!(dobs_outa, Pr * Fa * Ps', q) mul!(dobs_w_outa, Pr * Fa * Pw', w) @test isapprox(dobs, dobs_out; rtol=ftol) @test isapprox(dobsa, dobs_outa; rtol=ftol) @test isapprox(dobs_w, dobs_w_out; rtol=ftol) @test isapprox(dobs_wa, dobs_w_outa; rtol=ftol) mul!(w_out, adjoint(Pr * F * Pw'), dobs_w_out) w_a = adjoint(Pr * Fa * Pw') * dobs_w_out w_outa = 0f0 .* w_a mul!(w_outa, adjoint(Pr * Fa * Pw'), dobs_w_out) @test isapprox(w_out, adjoint(Pr * F * Pw') * dobs_w_out; rtol=ftol) @test isapprox(w_outa, w_a; rtol=ftol) # jacobian dm2 = copy(dm) dmd = copy(dm2.data) mul!(dm2, J', dobs) mul!(dmd, J', dobs) @test isapprox(dm2, J'*dobs) @test isapprox(dmd, dm2) mul!(dobs_out, J, dm) mul!(dobs, J, dm.data) dlin = J*dm @test isapprox(dobs_out, dlin; rtol=ftol) @test isapprox(dobs_out, dobs; rtol=ftol) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
18210
# Unit tests for JUDI linear operators (without PDE solves) # Philipp Witte ([email protected]) # May 2018 # # Mathias Louboutin, [email protected] # Updated July 2020 # Tests function test_transpose(Op) @test isequal(size(Op), size(conj(Op))) @test isequal(reverse(size(Op)), size(transpose(Op))) @test isequal(reverse(size(Op)), size(adjoint(Op))) @test isequal(reverse(size(Op)), size(transpose(Op))) end sub_dim(v::Vector{<:Integer}, i::Integer) = v[i:i] sub_dim(v::Vector{<:Integer}, i::AbstractRange) = v[i] sub_dim(v::Integer, i) = v check_dims(v::Integer, vo::Integer) = v == vo check_dims(v::Vector{<:Integer}, vo::Vector{<:Integer}) = v == vo check_dims(v::Integer, vo::Vector{<:Integer}) = (length(vo) == 1 && v == vo[1]) check_dims(v::Vector{<:Integer}, vo::Integer) = (length(v) == 1 && v[1] == vo) function test_getindex(Op, nsrc) so = size(Op) Op_sub = Op[1] @test isequal(Op_sub.model, Op.model) # Check sizes. Same dimensions but subsampled source @test issetequal(keys(size(Op_sub)), keys(size(Op))) s = size(Op_sub) for i=1:2 for (k, v) ∈ s[i] vo = k == :src ? 1 : so[i][k] @test check_dims(v, sub_dim(vo, 1)) end end inds = 1:nsrc Op_sub = Op[inds] @test isequal(Op_sub.model, Op.model) @test isequal(keys(size(Op_sub)), keys(size(Op))) s = size(Op_sub) for i=1:2 for (k, v) ∈ s[i] vo = k == :src ? nsrc : so[i][k] @test check_dims(v, sub_dim(vo, inds)) end end end model = example_model() ########################################################## judiModeling ############################################### @testset "judiModeling Unit Test with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiModeling nsrc=$(nsrc)" begin F_forward = judiModeling(model; options=Options()) F_adjoint = adjoint(F_forward) test_transpose(F_forward) @test isequal(size(F_forward)[1], time_space(model.n)) @test isequal(size(F_forward)[2], time_space(model.n)) @test isequal(size(F_adjoint)[1], time_space(model.n)) @test isequal(size(F_adjoint)[2], time_space(model.n)) @test issetequal(keys(size(F_forward)[1]), [:time, :x, :z]) @test issetequal(keys(size(F_forward)[2]), [:time, :x, :z]) # Time is uninitialized until first multiplication since there is no info # on propagation time @test issetequal(values(size(F_forward)[1]), [[0], model.n...]) @test Int(size(F_forward)[1]) == 0 # Update size for check nt = 10 size(F_forward)[1][:time] = [nt for i=1:nsrc] @test Int(size(F_forward)[1]) == nsrc * nt * prod(model.n) @test adjoint(F_adjoint) == F_forward @test isequal(typeof(F_forward), judiModeling{Float32, :forward, JUDI.IsoModel{Float32, 2}}) @test isequal(typeof(F_adjoint), judiModeling{Float32, :adjoint, JUDI.IsoModel{Float32, 2}}) # get index test_getindex(F_forward, nsrc) test_getindex(F_adjoint, nsrc) # get index test_getindex(F_forward, nsrc) test_getindex(F_adjoint, nsrc) if VERSION>v"1.2" a0 = a = randn(Float32, model.n...) for a in [a0, a0[:]] F2 = F_forward(;m=a) @test isapprox(F2.model.m, a0) F2 = F_forward(Model(model.n, model.d, model.o, a)) @test isapprox(F2.model.m, a0) @test F2.model.n == model.n end end end end @testset "judiPointSourceModeling Unit Test with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiPointSourceModeling nsrc=$(nsrc)" begin src_geometry = example_src_geometry(nsrc=nsrc) F_forward = judiModeling(model; options=Options()) * judiProjection(src_geometry)' F_adjoint = adjoint(F_forward) test_transpose(F_forward) @test isequal(size(F_forward)[1], time_space_src(nsrc, src_geometry.nt, model.n)) @test isequal(size(F_forward)[2], rec_space(src_geometry)) @test isequal(size(F_adjoint)[1], rec_space(src_geometry)) @test isequal(size(F_adjoint)[2], time_space_src(nsrc, src_geometry.nt, model.n)) @test issetequal(keys(size(F_forward)[1]), (:src, :time, :x, :z)) @test issetequal(keys(size(F_forward)[2]), (:src, :time, :rec)) # With the composition, everything should be initialized @test issetequal(values(size(F_forward)[1]), (nsrc, src_geometry.nt, model.n...)) @test issetequal(values(size(F_forward)[2]), (nsrc, src_geometry.nt, src_geometry.nrec)) @test Int(size(F_forward)[1]) == prod(model.n) * sum(src_geometry.nt) @test Int(size(F_forward)[2]) == sum(src_geometry.nrec .* src_geometry.nt) @test adjoint(F_adjoint) == F_forward @test isequal(typeof(F_forward), judiPointSourceModeling{Float32, :forward}) @test isequal(typeof(F_adjoint), judiDataModeling{Float32, :adjoint}) # get index test_getindex(F_forward, nsrc) test_getindex(F_adjoint, nsrc) # get index test_getindex(F_forward, nsrc) test_getindex(F_adjoint, nsrc) if VERSION>v"1.2" a0 = a = randn(Float32, model.n...) for a in [a0, a0[:]] F2 = F_forward(;m=a) @test isapprox(F2.model.m, a0) F2 = F_forward(Model(model.n, model.d, model.o, a)) @test isapprox(F2.model.m, a0) @test F2.model.n == model.n end end # SimSources if nsrc == 2 M = randn(Float32, 1, nsrc) Fs = M*F_forward @test isequal(size(Fs)[1], time_space_src(1, src_geometry[1].nt, model.n)) @test isequal(size(Fs)[2], rec_space(example_rec_geometry(;nrec=2, nsrc=1))) @test get_nsrc(Fs.qInjection) == 1 Fs = M*F_adjoint @test isequal(size(Fs)[1], rec_space(example_rec_geometry(;nrec=2, nsrc=1))) @test isequal(size(Fs)[2], time_space_src(1, src_geometry[1].nt, model.n)) @test get_nsrc(Fs.rInterpolation) == 1 end end end @testset "judiDataModeling Unit Test with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiDataModeling nsrc=$(nsrc)" begin rec_geometry = example_rec_geometry(nsrc=nsrc) F_forward = judiProjection(rec_geometry)*judiModeling(model; options=Options()) F_adjoint = adjoint(F_forward) test_transpose(F_forward) @test isequal(size(F_forward)[1], rec_space(rec_geometry)) @test isequal(size(F_forward)[2], time_space_src(nsrc, rec_geometry.nt, model.n)) @test isequal(size(F_adjoint)[1], time_space_src(nsrc, rec_geometry.nt, model.n)) # With the composition, everything should be initialized @test issetequal(values(size(F_forward)[2]), (nsrc, rec_geometry.nt, model.n...)) @test issetequal(values(size(F_forward)[1]), (nsrc, rec_geometry.nt, rec_geometry.nrec)) @test Int(size(F_forward)[2]) == prod(model.n) * sum(rec_geometry.nt) @test Int(size(F_forward)[1]) == sum(rec_geometry.nrec .* rec_geometry.nt) @test adjoint(F_adjoint) == F_forward @test isequal(typeof(F_forward), judiDataModeling{Float32, :forward}) @test isequal(typeof(F_adjoint), judiPointSourceModeling{Float32, :adjoint}) # get index test_getindex(F_forward, nsrc) test_getindex(F_adjoint, nsrc) # get index test_getindex(F_forward, nsrc) test_getindex(F_adjoint, nsrc) if VERSION>v"1.2" a0 = a = randn(Float32, model.n...) for a in [a0, a0[:]] F2 = F_forward(;m=a) @test isapprox(F2.model.m, a0) F2 = F_forward(Model(model.n, model.d, model.o, a)) @test isapprox(F2.model.m, a0) @test F2.model.n == model.n end end # SimSources if nsrc == 2 M = randn(Float32, 1, nsrc) Fs = M*F_adjoint @test isequal(size(Fs)[1], time_space_src(1, rec_geometry[1].nt, model.n)) @test isequal(size(Fs)[2], rec_space(rec_geometry[1])) @test get_nsrc(Fs.qInjection) == 1 Fs = M*F_forward @test isequal(size(Fs)[1], rec_space(rec_geometry[1])) @test isequal(size(Fs)[2], time_space_src(1, rec_geometry[1].nt, model.n)) @test get_nsrc(Fs.rInterpolation) == 1 end end end @testset "judiDataSourceModeling Unit Test with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiDataSourceModeling nsrc=$(nsrc)" begin rec_geometry = example_rec_geometry(nsrc=nsrc) src_geometry = example_src_geometry(nsrc=nsrc) F_forward = judiModeling(model, src_geometry, rec_geometry; options=Options()) F_adjoint = adjoint(F_forward) test_transpose(F_forward) @test isequal(size(F_forward)[2], rec_space(src_geometry)) @test isequal(size(F_forward)[1], rec_space(rec_geometry)) @test isequal(size(F_adjoint)[2], rec_space(rec_geometry)) @test isequal(size(F_adjoint)[1], rec_space(src_geometry)) @test issetequal(keys(size(F_forward)[1]), (:src, :time, :rec)) @test issetequal(keys(size(F_forward)[2]), (:src, :time, :rec)) # With the composition, everything should be initialized @test issetequal(values(size(F_forward)[2]), (nsrc, src_geometry.nt, src_geometry.nrec)) @test issetequal(values(size(F_forward)[1]), (nsrc, rec_geometry.nt, rec_geometry.nrec)) @test Int(size(F_forward)[2]) == sum(src_geometry.nrec .* src_geometry.nt) @test Int(size(F_forward)[1]) == sum(rec_geometry.nrec .* rec_geometry.nt) @test adjoint(F_adjoint) == F_forward @test isequal(typeof(F_forward), judiDataSourceModeling{Float32, :forward}) @test isequal(typeof(F_adjoint), judiDataSourceModeling{Float32, :adjoint}) # get index test_getindex(F_forward, nsrc) test_getindex(F_adjoint, nsrc) # get index test_getindex(F_forward, nsrc) test_getindex(F_adjoint, nsrc) if VERSION>v"1.2" a0 = a = randn(Float32, model.n...) for a in [a0, a0[:]] F2 = F_forward(;m=a) @test isapprox(F2.model.m, a0) F2 = F_forward(Model(model.n, model.d, model.o, a)) @test isapprox(F2.model.m, a0) @test F2.model.n == model.n end end # SimSources if nsrc == 2 M = randn(Float32, 1, nsrc) Fs = M*F_forward @test isequal(size(Fs)[1], rec_space(rec_geometry[1])) @test isequal(size(Fs)[2], rec_space(example_rec_geometry(;nrec=2, nsrc=1))) @test get_nsrc(Fs.qInjection) == 1 Fs = M*F_adjoint @test isequal(size(Fs)[1], rec_space(example_rec_geometry(;nrec=2, nsrc=1))) @test isequal(size(Fs)[2], rec_space(rec_geometry[1])) @test get_nsrc(Fs.rInterpolation) == 1 end end end ######################################################## judiJacobian ################################################## @testset "judiJacobian Unit Test with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiJacobian nsrc=$(nsrc)" begin rec_geometry = example_rec_geometry(nsrc=nsrc) src_geometry = example_src_geometry(nsrc=nsrc) wavelet = randn(Float32, src_geometry.nt[1]) PDE = judiModeling(model, src_geometry, rec_geometry; options=Options()) q = judiVector(src_geometry, wavelet) J = judiJacobian(PDE, q) # Check sizes @test isequal(size(J)[1], rec_space(rec_geometry)) @test isequal(size(J)[2], space(model.n)) @test issetequal(keys(size(J)[2]), (:x, :z)) @test Int(size(J)[2]) == prod(model.n) @test Int(size(J)[1]) == sum(rec_geometry.nrec .* rec_geometry.nt) @test isequal(typeof(J), judiJacobian{Float32, :born, typeof(PDE)}) @test isequal(J.F.rInterpolation.geometry, rec_geometry) @test isequal(J.F.qInjection.geometry, src_geometry) @test isequal(J.q.geometry, src_geometry) @test all(isequal(J.q.data[i], wavelet) for i=1:nsrc) test_transpose(J) # get index J_sub = J[1] @test isequal(J_sub.model, J.model) @test isequal(J_sub.F, J.F[1]) @test isequal(J_sub.q, q[1]) inds = nsrc > 1 ? (1:nsrc) : 1 J_sub = J[inds] @test isequal(J_sub.model, J.model) @test isequal(J_sub.F, J.F[inds]) @test isequal(J_sub.q, q[inds]) inds = nsrc > 1 ? (1:nsrc) : 1 J_sub = J[inds] @test isequal(J_sub.model, J.model) @test isequal(size(J_sub), size(J)) # SimSources if nsrc == 2 M = randn(Float32, 1, nsrc) Fs = M*J @test isequal(size(Fs)[1], rec_space(rec_geometry[1])) @test isequal(size(Fs)[2], space(model.n)) @test Fs.q.nsrc == 1 end end end ######################################################## judiJacobian ################################################## @testset "judiJacobianExtended Unit Test with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiJacobianExtended nsrc=$(nsrc)" begin rec_geometry = example_rec_geometry(nsrc=nsrc) wavelet = randn(Float32, rec_geometry.nt[1]) # Setup operators Pr = judiProjection(rec_geometry) F = judiModeling(model) Pw = judiLRWF(rec_geometry.dt, wavelet) w = judiWeights(randn(Float32, model.n); nsrc=nsrc) J = judiJacobian(Pr*F*Pw', w) # Check sizes @test isequal(size(J)[1], rec_space(rec_geometry)) @test isequal(size(J)[2], space(model.n)) @test issetequal(keys(size(J)[2]), (:x, :z)) @test Int(size(J)[2]) == prod(model.n) @test Int(size(J)[1]) == sum(rec_geometry.nrec .* rec_geometry.nt) rec_geometry = example_rec_geometry(nsrc=nsrc) wavelet = randn(Float32, rec_geometry.nt[1]) # Setup operators Pr = judiProjection(rec_geometry) F = judiModeling(model) Pw = judiLRWF(nsrc, rec_geometry.dt[1], wavelet) w = judiWeights(randn(Float32, model.n); nsrc=nsrc) PDE = Pr*F*Pw' J = judiJacobian(PDE, w) @test isequal(typeof(J), judiJacobian{Float32, :born, typeof(PDE)}) @test isequal(J.F.rInterpolation.geometry, rec_geometry) for i=1:nsrc @test isapprox(J.F.qInjection.wavelet[i], wavelet) @test isapprox(J.q.data[i], w.data[i]) end @test isequal(size(J)[2], space(model.n)) test_transpose(J) # get index J_sub = J[1] @test isequal(J_sub.model, J.model) @test isapprox(J_sub.q.weights[1], J.q.weights[1]) inds = 1:nsrc J_sub = J[inds] @test isequal(J_sub.model, J.model) @test isapprox(J_sub.q.weights, J.q.weights[inds]) # Test Pw alone P1 = subsample(Pw, 1) @test isapprox(P1.wavelet, Pw[1].wavelet) @test isapprox(conj(Pw).wavelet, Pw.wavelet) @test size(conj(Pw)) == size(Pw) @test isapprox(transpose(Pw).wavelet, Pw.wavelet) end end ####################################################### judiProjection ################################################# @testset "judiProjection Unit Test with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiProjection nsrc=$(nsrc)" begin rec_geometry = example_rec_geometry(nsrc=nsrc) P = judiProjection(rec_geometry) # Check sizes and that's it's unitialized since not combined with any propagator @test size(P)[2] == time_space_src(get_nsrc(rec_geometry), rec_geometry.nt, 3) @test size(P)[1] == rec_space(rec_geometry) # Size is zero since un-initialized @test Int(size(P)[2]) == 0 @test Int(size(P)[1]) == sum(rec_geometry.nrec .* rec_geometry.nt) @test isequal(typeof(P), judiProjection{Float32}) @test isequal(P.geometry, rec_geometry) Pr_sub = P[1] @test isequal(get_nsrc(Pr_sub.geometry), 1) @test get_nsrc(Pr_sub.geometry) == 1 inds = nsrc > 1 ? (1:nsrc) : 1 Pr_sub = P[inds] @test isequal(Pr_sub.geometry, rec_geometry[inds]) @test get_nsrc(Pr_sub.geometry) == nsrc # SimSources if nsrc == 2 M = randn(Float32, 1, nsrc) Fs = M*P @test size(Fs)[2] == time_space_src(get_nsrc(rec_geometry[1]), rec_geometry[1].nt, 3) @test size(Fs)[1] == rec_space(rec_geometry[1]) @test get_nsrc(Fs.geometry) == 1 end end end @testset "judiLRWF Unit Test with $(nsrc) sources" for nsrc=[1, 2] @timeit TIMEROUTPUT "judiLRWF nsrc=$(nsrc)" begin src_geometry = example_src_geometry(nsrc=nsrc) wavelet = randn(Float32, src_geometry.nt[1]) P = judiLRWF(src_geometry.dt, wavelet) @test isequal(typeof(P), judiLRWF{Float32}) # Check sizes and that's it's unitialized since not combined with any propagator @test size(P)[1] == space_src(nsrc) @test size(P)[2] == time_space_src(nsrc, src_geometry.nt) # Size is zero since un-initialized @test Int(size(P)[1]) == 0 @test Int(size(P)[2]) == 0 for i=1:nsrc @test isequal(P.wavelet[i], wavelet) @test isequal(P.dt[i], src_geometry.dt[i]) end @test length(P.wavelet) == nsrc P_sub = P[1] @test isequal(P_sub.wavelet[1], wavelet) @test isequal(P_sub.dt[1], src_geometry.dt[1]) @test length(P_sub.wavelet) == 1 inds = nsrc > 1 ? (1:nsrc) : 1 Pr_sub = P[inds] for i=1:nsrc @test isequal(Pr_sub.wavelet[i], wavelet) @test isequal(Pr_sub.dt[i], src_geometry.dt[i]) end @test length(Pr_sub.wavelet) == nsrc end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
9833
# Test linearity of sources # Author: Philipp Witte, [email protected] # Date: January 2017 # # Mathias Louboutin, [email protected] # Updated July 2020 ### Model model, model0, dm = setup_model(tti, viscoacoustic, nlayer) q1, srcGeometry1, recGeometry, f0 = setup_geom(model) srcGeometry2 = deepcopy(srcGeometry1) srcGeometry2.xloc[:] .= .9*srcGeometry2.xloc[:] srcGeometry2.zloc[:] .= .9*srcGeometry2.zloc[:] dt = srcGeometry1.dt[1] opt = Options(free_surface=fs, f0=f0) ftol = 5f-5 ####################### Modeling operators ########################################## @testset "Linearity test with $(nlayer) layers and tti $(tti) and viscoacoustic $(viscoacoustic) and freesurface $(fs)" begin @timeit TIMEROUTPUT "Linearity" begin # Modeling operators Pr = judiProjection(recGeometry) Ps1 = judiProjection(srcGeometry1) Ps2 = judiProjection(srcGeometry2) F = judiModeling(model; options=opt) q2 = judiVector(srcGeometry2,q1.data[1]) A1 = Pr*F*adjoint(Ps1) A2 = Pr*F*adjoint(Ps2) J = judiJacobian(A1, q1) d1 = A1*q1 d2 = A2*q2 d3 = Pr*F*(adjoint(Ps1)*q1 + adjoint(Ps2)*q2) d4 = Pr*F*(adjoint(Ps1)*q1 - adjoint(Ps2)*q2) d5 = A1 * (2f0 * q1) d6 = (2f0 * A1) * q1 q3 = adjoint(A1) * d1 q4 = adjoint(A1) * (2f0 * d1) q5 = (2f0 * adjoint(A1)) * d1 # Test linearity F * (a + b) == F * a + F * b println("Test linearity of F: F * (a + b) == F * a + F * b") nd1 = norm(d3) nd2 = norm(d1 + d2) nd3 = norm(d3 - d1 - d2)/norm(d3) @printf(" F * (a + b): %2.5e, F * a + F * b : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) nd1 = norm(d4) nd2 = norm(d1 - d2) nd3 = norm(d4 - d1 + d2)/norm(d4) @printf(" F * (a - b): %2.5e, F * a - F * b : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) @test isapprox(d3, d1 + d2, rtol=ftol) @test isapprox(d4, d1 - d2, rtol=ftol) # Test linearity F a x == a F x println("Test linearity of F: F * (a * b) == a * F * b") nd1 = norm(2f0 * d1) nd1_b = norm(d6) nd2 = norm(d5) nd3 = norm(2f0 * d1 - d5)/norm(d5) nd4 = norm(d6 - d5)/norm(d5) nm1 = norm(2f0 * q3) nm1_b = norm(q5) nm2 = norm(q4) nm3 = norm(2f0 * q3 - q4)/norm(q4) nm4 = norm(q5 - q4)/norm(q4) @printf(" a (F x): %2.5e, F a x : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) @printf(" (a F) x: %2.5e, F a x : %2.5e, relative error : %2.5e \n", nd1_b, nd2, nd4) @printf(" a (F' x): %2.5e, F' a x : %2.5e, relative error : %2.5e \n", nm1, nm2, nm3) @printf(" (a F') x: %2.5e, F' a x : %2.5e, relative error : %2.5e \n", nm1_b, nm2, nm4) @test isapprox(2f0 * d1, d5, rtol=ftol) @test isapprox(2f0 * d1, d6, rtol=ftol) @test isapprox(2f0 * q3, q4, rtol=ftol) @test isapprox(2f0 * q3, q5, rtol=ftol) # Test linearity J * (a + b) == J * a + J * b dm2 = .5f0 * dm dm2.data .= circshift(dm2.data, (0, 20)) lind = J * dm lind2 = J * (2f0 .* dm) lind3 = J * dm2 lind4 = J * (dm + dm2) lind5 = J * (dm - dm2) lind6 = (2f0 * J) * dm println("Test linearity of J: J * (a + b) == J * a + J * b") nd1 = norm(lind4) nd2 = norm(lind + lind3) nd3 = norm(lind4 - lind - lind3)/norm(lind4) @printf(" J * (a + b): %2.5e, J * a + J * b : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) nd1 = norm(lind5) nd2 = norm(lind - lind3) nd3 = norm(lind5 - lind + lind3)/norm(lind5) @printf(" J * (a - b): %2.5e, J * a - J * b : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) @test isapprox(lind4, lind + lind3, rtol=ftol) @test isapprox(lind5, lind - lind3, rtol=ftol) # Test linearity J a x == a J x println("Test linearity of J: J * (a * b) == a * J * b") nd1 = norm(2f0 * lind) nd1_b = norm(lind6) nd2 = norm(lind2) nd3 = norm(2f0 * lind - lind2)/norm(lind2) nd4 = norm(lind6 - lind2)/norm(lind2) # Adjoint J dma = adjoint(J) * d1 dmb = adjoint(J) * (2f0 * d1) dmc = adjoint(J) * d2 dmd = adjoint(J) * (d1 + d2) dme = adjoint(2f0 * J) * d1 nm1 = norm(2f0 * dma) nm1_b = norm(dme) nm2 = norm(dmb) nm3 = norm(2f0*dma - dmb)/norm(dmb) nm4 = norm(dme - dmb)/norm(dmb) @printf(" a (J x): %2.5e, J a x : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) @printf(" (a J) x: %2.5e, J a x : %2.5e, relative error : %2.5e \n", nd1_b, nd2, nd4) @printf(" a (J' x): %2.5e, J' a x : %2.5e, relative error : %2.5e \n", nm1, nm2, nm3) @printf(" (a J') x: %2.5e, J' a x : %2.5e, relative error : %2.5e \n", nm1_b, nm2, nm4) @test isapprox(2f0 * lind, lind2, rtol=ftol) @test isapprox(2f0 * lind, lind6, rtol=ftol) @test isapprox(2f0 * dma, dmb, rtol=ftol) @test isapprox(2f0 * dma, dme, rtol=ftol) end end ####################### Extended source operators ########################################## if tti ftol = 5f-4 end @testset "Extended source linearity test with $(nlayer) layers and tti $(tti) and freesurface $(fs)" begin @timeit TIMEROUTPUT "Extended source Linearity" begin # Modeling operators Pr = judiProjection(recGeometry) F = judiModeling(model; options=opt) Pw = judiLRWF(q1.geometry.dt[1], q1.data[1]) A = Pr*F*adjoint(Pw) Aa = adjoint(A) # Extended source weights w = randn(Float32, model0.n) x = randn(Float32, model0.n) w[:, 1] .= 0f0; w = vec(w) x[:, 1] .= 0f0; x = vec(x) J = judiJacobian(A, w) d1 = A*w d2 = A*x d3 = A*(w+x) d4 = A*(w-x) d5 = A*(2f0 * w) d6 = (2f0 * A) * w q3 = Aa * d1 q4 = Aa * (2f0 * d1) q5 = (2f0 * Aa) * d1 dm2 = .5f0 * dm dm2.data .= circshift(dm2.data, (0, 20)) lind = J * dm lind2 = J * (2f0 .* dm) lind3 = J * dm2 lind4 = J * (dm + dm2) lind5 = J * (dm - dm2) lind6 = (2f0 * J) * dm dma = adjoint(J) * d1 dmb = adjoint(J) * (2f0 * d1) dmc = adjoint(J) * d2 dmd = adjoint(J) * (d1 + d2) dme = adjoint(2f0 * J) * d1 # Test linearity F * (a + b) == F * a + F * b println("Test linearity of F: F * (a + b) == F * a + F * b") nd1 = norm(d3) nd2 = norm(d1 + d2) nd3 = norm(d3 - d1 - d2)/norm(d3) @printf(" F * (a + b): %2.5e, F * a + F * b : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) nd1 = norm(d4) nd2 = norm(d1 - d2) nd3 = norm(d4 - d1 + d2)/norm(d4) @printf(" F * (a - b): %2.5e, F * a - F * b : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) @test isapprox(d3, d1 + d2, rtol=ftol) @test isapprox(d4, d1 - d2, rtol=ftol) # Test linearity F a x == a F x println("Test linearity of F: F * (a * b) == a * F * b") nd1 = norm(2f0 * d1) nd1_b = norm(d6) nd2 = norm(d5) nd3 = norm(2f0 * d1 - d5)/norm(d5) nd4 = norm(d6 - d5)/norm(d5) nm1 = norm(2f0 * q3) nm1_b = norm(q5) nm2 = norm(q4) nm3 = norm(2f0 * q3 - q4)/norm(q4) nm4 = norm(q5 - q4)/norm(q4) @printf(" a (F x): %2.5e, F a x : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) @printf(" (a F) x: %2.5e, F a x : %2.5e, relative error : %2.5e \n", nd1_b, nd2, nd4) @printf(" a (F' x): %2.5e, F' a x : %2.5e, relative error : %2.5e \n", nm1, nm2, nm3) @printf(" (a F') x: %2.5e, F' a x : %2.5e, relative error : %2.5e \n", nm1_b, nm2, nm4) @test isapprox(2f0 * d1, d5, rtol=ftol) @test isapprox(2f0 * d1, d6, rtol=ftol) @test isapprox(2f0 * q3, q4, rtol=ftol) @test isapprox(2f0 * q3, q5, rtol=ftol) # Test linearity J * (a + b) == J * a + J * b println("Test linearity of J: J * (a + b) == J * a + J * b") nd1 = norm(lind4) nd2 = norm(lind + lind3) nd3 = norm(lind4 - lind - lind3)/norm(lind4) @printf(" J * (a + b): %2.5e, J * a + J * b : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) nd1 = norm(lind5) nd2 = norm(lind - lind3) nd3 = norm(lind5 - lind + lind3)/norm(lind5) @printf(" J * (a - b): %2.5e, J * a - J * b : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) @test isapprox(lind4, lind + lind3, rtol=ftol) @test isapprox(lind5, lind - lind3, rtol=ftol) # Test linearity J a x == a J x println("Test linearity of J: J * (a * b) == a * J * b") nd1 = norm(2f0 * lind) nd1_b = norm(lind6) nd2 = norm(lind2) nd3 = norm(2f0 * lind - lind2)/norm(lind2) nd4 = norm(lind6 - lind2)/norm(lind2) nm1 = norm(2f0 * dma) nm1_b = norm(dme) nm2 = norm(dmb) nm3 = norm(2f0*dma - dmb)/norm(dmb) nm4 = norm(dme - dmb)/norm(dmb) @printf(" a (J x): %2.5e, J a x : %2.5e, relative error : %2.5e \n", nd1, nd2, nd3) @printf(" (a J) x: %2.5e, J a x : %2.5e, relative error : %2.5e \n", nd1_b, nd2, nd4) @printf(" a (J' x): %2.5e, J' a x : %2.5e, relative error : %2.5e \n", nm1, nm2, nm3) @printf(" (a J') x: %2.5e, J' a x : %2.5e, relative error : %2.5e \n", nm1_b, nm2, nm4) @test isapprox(2f0 * lind, lind2, rtol=ftol) @test isapprox(2f0 * lind, lind6, rtol=ftol) @test isapprox(2f0 * dma, dmb, rtol=ftol) @test isapprox(2f0 * dma, dme, rtol=ftol) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
4378
# Test 2D modeling # The receiver positions and the source wavelets are the same for each of the four experiments. # Author: Philipp Witte, [email protected] # Date: January 2017 # # Mathias Louboutin, [email protected] # Updated July 2020 nw = 2 # Set parallel if specified if nw > 1 && nworkers() < nw addprocs(nw-nworkers() + 1; exeflags=["--code-coverage=user", "--inline=no", "--check-bounds=yes"]) end @everywhere using JOLI, JUDI, LinearAlgebra, Test, Distributed ### Model model, model0, dm = setup_model(tti, viscoacoustic, nlayer; n=(101, 101), d=(10., 10.)) q, srcGeometry, recGeometry, f0 = setup_geom(model; nsrc=nw, tn=500f0) dt = srcGeometry.dt[1] # Modeling operators println("Generic modeling and misc test with ", nlayer, " layers and tti: ", tti) ftol = 1f-5 ######################## WITH DENSITY ############################################ cases = [(true, true), (true, false), (false, true), (false, false)] @testset "Generic tests with limit_m = $(limit_m) and save to disk = $(disk)" for (limit_m, disk)=cases @timeit TIMEROUTPUT "Modeling limit_m=$(limit_m), save_to_disk=$(disk)" begin # Options structures opt = Options(save_data_to_disk=disk, limit_m=limit_m, buffer_size=100f0, f0=f0, file_path=pwd(), # path to files file_name="shot_record") # saves files as file_name_xsrc_ysrc.segy opt0 = Options(save_data_to_disk=disk, limit_m=limit_m, buffer_size=100f0, f0=f0, file_path=pwd(), # path to files file_name="smooth_shot_record") # saves files as file_name_xsrc_ysrc.segy optJ = Options(save_data_to_disk=disk, limit_m=limit_m, buffer_size=100f0, f0=f0, file_path=pwd(), # path to files file_name="linearized_shot_record") # saves files as file_name_xsrc_ysrc.segy # Setup operators Pr = judiProjection(recGeometry) F = judiModeling(model; options=opt) F0 = judiModeling(model0; options=opt0) Ps = judiProjection(srcGeometry) # Combined operator Pr*F*adjoint(Ps) Ffull = judiModeling(model, srcGeometry, recGeometry) J = judiJacobian(Pr*F0*adjoint(Ps),q; options=optJ) # equivalent to J = judiJacobian(Ffull,q) # Nonlinear modeling d1 = Pr*F*adjoint(Ps)*q # equivalent to d = Ffull*q dfull = Ffull*q @test isapprox(get_data(d1), dfull, rtol=ftol) qad = Ps*adjoint(F)*adjoint(Pr)*d1 qfull = adjoint(Ffull)*d1 @test isapprox(get_data(qad), qfull, rtol=ftol) # fwi objective function f, g = fwi_objective(model0, q, d1; options=opt) f, g = fwi_objective(model0, getindex(q,1), getindex(d1,1); options=opt) # Indexing (per source) for inds=[2, [1, 2]] dsub = getindex(dfull, inds) qsub = getindex(q, inds) Fsub = getindex(F, inds) Jsub = getindex(J, inds) Ffullsub = getindex(Ffull, inds) Pssub = getindex(Ps, inds) Prsub = getindex(Pr, inds) ds1 = Ffullsub*qsub ds2 = Prsub * Fsub * adjoint(Pssub) *qsub @test isapprox(ds1, get_data(ds2), rtol=ftol) @test isapprox(ds1, dsub, rtol=ftol) @test isapprox(get_data(ds2), dsub, rtol=ftol) end # vcat, norms, dot dcat = [d1, d1] @test isapprox(norm(d1)^2, .5f0*norm(dcat)^2) @test isapprox(dot(d1, d1), norm(d1)^2) end end ############################# Full wavefield ############################################ if VERSION >= v"1.7" @testset "Basic judiWavefield modeling tests" begin @timeit TIMEROUTPUT "Wavefield modeling" begin opt = Options(dt_comp=dt, f0=f0) F = judiModeling(model; options=opt) Fa = adjoint(F) Ps = judiProjection(srcGeometry) Pr = judiProjection(recGeometry) # Return wavefields u = F * adjoint(Ps) * q # Adjoint from data dobs = Pr*F*u v = Fa*adjoint(Pr)*dobs a = dot(u, v) b = dot(dobs, dobs) @printf(" <F x, y> : %2.5e, <x, F' y> : %2.5e, relative error : %2.5e \n", b, a, (a-b)/(a+b)) @test isapprox(a/(a+b), b/(a+b), atol=2.5f-5, rtol=0) # Forward from data qa = Ps*Fa*v a = dot(u, v) b = dot(q, qa) @printf(" <F x, y> : %2.5e, <x, F' y> : %2.5e, relative error : %2.5e \n", b, a, (a-b)/(a+b)) @test isapprox(a/(a+b), b/(a+b), atol=2.5f-5, rtol=0) # Wavefields as source + return wavefields u2 = F*u v2 = Fa*v a = dot(u2, v) b = dot(v2, u) @printf(" <F x, y> : %2.5e, <x, F' y> : %2.5e, relative error : %2.5e \n", a, b, (a-b)/(a+b)) @test isapprox(a/(a+b), b/(a+b), atol=1f-4, rtol=0) end end end rmprocs(workers())
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
3892
# 2D LSRTM/FWI parallelization test with 2 sources and 2 vintages # # Ziyi Yin, [email protected] # August 2021 @testset "test reduction from distributed tasks" begin @timeit TIMEROUTPUT "Test reduction" begin function judiWeightsConst(i::Int) return judiWeights(i*ones(Float32,10*i,10*i)) end f = Vector{Future}(undef, 6) for i = 1:6 f[i] = @spawn judiWeightsConst(i) end using JUDI:reduce! w = reduce!(f) @info "test if stacking follows the correct order through reduction" for i = 1:6 @test w.data[i] == i*ones(Float32,10*i,10*i) end # Test objective function f1 = @spawn (Ref{Float32}(1f0), randn(10)) f2 = @spawn (Ref{Float32}(2f0), randn(10)) JUDI.local_reduce!(f1, f2) res = fetch(f1) @test res[1][] == 3f0 @test typeof(res[1]) == Base.RefValue{Float32} res = JUDI.as_vec(res, Val(false)) @test res[1] == 3f0 @test typeof(res[1]) == Float32 end end ### Model model, model0, dm = setup_model(tti, viscoacoustic, 4) q, srcGeometry, recGeometry, f0 = setup_geom(model; nsrc=4) q1 = q[[1,4]] q2 = q[[2,3]] srcGeometry1 = subsample(srcGeometry,[1,4]) srcGeometry2 = subsample(srcGeometry,[2,3]) recGeometry1 = subsample(recGeometry,[1,4]) recGeometry2 = subsample(recGeometry,[2,3]) opt = Options(sum_padding=true, free_surface=fs, f0=f0, dt_comp=dt) F1 = judiModeling(model, srcGeometry1, recGeometry1; options=opt) F2 = judiModeling(model, srcGeometry2, recGeometry2; options=opt) # Observed data dobs1 = F1*q1 dobs2 = F2*q2 # Perturbations dm1 = 2f0*circshift(dm, 10) dm2 = 2f0*circshift(dm, 30) @testset "Multi-experiment arg processing" begin @timeit TIMEROUTPUT "Process multi exp" begin for (nm, m) in zip([1, 2], [model0, [model0, model0]]) for (nq, q) in zip([1, 2], [q1, [q1, q2]]) for (nd, d) in zip([1, 2], [dobs1, [dobs1, dobs2]]) for dmloc in [dm1, dm1[:]] for (ndm, dm) in zip([1, 2], [dmloc, [dmloc, dmloc]]) args = m, q, d, dm @test JUDI.check_args(args...) == maximum((nm, nq, nd, ndm)) for (a, expected) in zip(args, (model0, q1, dobs1, dmloc)) @test JUDI.get_exp(a, 1) == expected end end end end end end @test_throws ArgumentError JUDI.check_args([model0, model0], [dobs1, dobs2, dobs1]) @test_throws ArgumentError JUDI.check_args([model0, model0], [dobs1, dobs2], [dm1, dm2, dm1]) @test_throws ArgumentError JUDI.check_args(model0, [dobs1, dobs2], [dm1, dm2, dm1]) end end @testset "FWI/LSRTM objective multi-level parallelization test with $(nlayer) layers and tti $(tti) and freesurface $(fs)" begin @timeit TIMEROUTPUT "Multi FWI/LSRTM" begin ftol = 1f-5 Jm0, grad = lsrtm_objective([model0, model0], [q1, q2], [dobs1, dobs2], [dm1, dm2]; options=opt, nlind=true) Jm01, grad1 = lsrtm_objective(model0, q1, dobs1, dm1; options=opt, nlind=true) Jm02, grad2 = lsrtm_objective(model0, q2, dobs2, dm2; options=opt, nlind=true) @test isapprox(Jm01+Jm02, Jm0; rtol=ftol) @test isapprox(grad1, grad[1]; rtol=ftol) @test isapprox(grad2, grad[2]; rtol=ftol) _Jm0, _grad = fwi_objective([model0, model0], [q1, q2], [dobs1, dobs2]; options=opt) _Jm01, _grad1 = fwi_objective(model0, q1, dobs1; options=opt) _Jm02, _grad2 = fwi_objective(model0, q2, dobs2; options=opt) @test isapprox(_Jm01+_Jm02, _Jm0; rtol=ftol) @test isapprox(_grad1, _grad[1]; rtol=ftol) @test isapprox(_grad2, _grad[2]; rtol=ftol) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
7083
# Author: Mathias Louboutin, [email protected] # Updated July 2020 ftol = 1f-5 @testset "PhysicalParameter Unit Tests in $(nd) dimensions" for nd=[2, 3] @timeit TIMEROUTPUT "PhysicalParameter in $(nd) dimensions" begin n = Tuple(11+i for i=1:nd) d = Tuple(1f0+i for i=1:nd) o = Tuple(0f0+i for i=1:nd) a = randn(Float32, n...) p = PhysicalParameter(a, d, o) @test PhysicalParameter(p) == p @test PhysicalParameter(p, n, d, o) == p @test PhysicalParameter(p.data, n, d, o) == p @test PhysicalParameter(vec(p.data), n, d, o) == p @test size(p) == n @test size(conj(p)) == n @test size(adjoint(p)) == n[end:-1:1] @test adjoint(p).n == p.n[end:-1:1] @test adjoint(p).d == p.d[end:-1:1] @test adjoint(p).o == p.o[end:-1:1] @test isapprox(adjoint(p).data, permutedims(p.data, nd:-1:1)) @test size(transpose(p)) == n[end:-1:1] @test transpose(p).n == p.n[end:-1:1] @test transpose(p).d == p.d[end:-1:1] @test transpose(p).o == p.o[end:-1:1] @test isapprox(transpose(p).data, permutedims(p.data, nd:-1:1)) ps = similar(p, Model(n, d, o, a)) @test norm(ps) == 0 @test ps.n == n @test ps.d == d @test ps.o == o @test isequal(p.data, a) p .= zeros(Float32, n...) p .= a @test isequal(p.data, a) @test p.d == d @test p.n == n @test p.o == o # indexing @test firstindex(p) == 1 @test lastindex(p) == prod(n) @test p == p @test isapprox(p, a) @test isapprox(a, p) # Subsampling inds = [3:11 for i=1:nd] b = p[inds...] @test b.o == tuple([o+d*2 for (o,d)=zip(p.o,p.d)]...) @test b.n == tuple([9 for i=1:nd]...) @test b.d == p.d inds = [3:2:11 for i=1:nd] b = p[inds...] @test b.o == tuple([o+d*2 for (o,d)=zip(p.o,p.d)]...) @test b.n == tuple([5 for i=1:nd]...) @test b.d == tuple([d*2 for d=p.d]...) # copies p2 = similar(p) @test p2.n == p.n @test norm(p2) == 0 p2 = copy(p) @test p2.n == p.n @test norm(p2) == norm(p) p2 = 0f0 .* p .+ 1f0 @test norm(p2, 1) == prod(n) # Some basics pl = PhysicalParameter(n, d, o) @test norm(pl) == 0 pl = PhysicalParameter(0, n, d, o) @test pl.data == 0 @test isapprox(dot(p, p), norm(p)^2) @test isapprox(dot(ones(Float32, n), p), sum(p.data)) @test isapprox(dot(p, ones(Float32, n)), sum(p.data)) # broadcast multiplication u = p v = p2 u_scale = deepcopy(p) v_scale = deepcopy(p2) c = ones(Float32, v.n) u_scale .*= 2f0 @test isapprox(u_scale, 2f0 * u; rtol=ftol) v_scale .+= 2f0 @test isapprox(v_scale, 2f0 .+ v; rtol=ftol) u_scale ./= 2f0 @test isapprox(u_scale, u; rtol=ftol) u_scale .= 2f0 .* u_scale .+ v_scale @test isapprox(u_scale, 2f0 * u .+ 2f0 + v; rtol=ftol) u_scale .= u .+ v @test isapprox(u_scale, u + v) u_scale .= u .- v @test isapprox(u_scale, u - v) u_scale .= u .* v @test isapprox(u_scale.data[1], u.data[1].*v.data[1]) u_scale .= u ./ v @test isapprox(u_scale.data[1], u.data[1]./v.data[1]) @test isapprox(u .* c, u) @test isapprox(c .* u, u) @test isapprox(u ./ c, u) @test isapprox(c ./ u, 1 ./u) @test isapprox(c .+ u, 1 .+ u) @test isapprox(c .- u, 1 .- u) @test isapprox(u .+ c, 1 .+ u) @test isapprox(u .- c, u .- 1) # Arithmetic v = PhysicalParameter(randn(Float32, n...), d, o) w = PhysicalParameter(randn(Float32, n...), d, o) a = .5f0 + rand(Float32) b = .5f0 + rand(Float32) @test isapprox(u + (v + w), (u + v) + w; rtol=ftol) @test isapprox(u + v, v + u; rtol=ftol) @test isapprox(u, u .+ 0; rtol=ftol) @test iszero(norm(u + u.*(-1))) @test isapprox(-u, (-1f0).*u; rtol=ftol) @test isapprox(a .* (b .* u), (a * b) .* u; rtol=ftol) @test isapprox(u, u .* 1; rtol=ftol) @test isapprox(a .* (u + v), a .* u + a .* v; rtol=1f-5) @test isapprox((a + b) .* v, a .* v + b.* v; rtol=1f-5) @test isapprox(c + v, 1 .+ v) @test isapprox(c - v, 1 .- v) @test isapprox(v + c, 1 .+ v) @test isapprox(v - c, v .- 1) @test isapprox(v * v, v.^2) @test isapprox(v / v, 0f0.*v .+1) a = zeros(Float32, n...) a .= v @test isapprox(a, v.data) v = PhysicalParameter(ones(Float32, n...), d, o) v[v .> 0] .= -1 @test all(v .== -1) # Indexing u = PhysicalParameter(randn(Float32, n), d, o) u[:] .= 0f0 @test norm(u) == 0f0 u[1] = 1f0 @test norm(u) == 1f0 @test u.data[1] == 1f0 u[1:10] .= 1:10 @test norm(u, 1) == 55 @test u[1:10] == 1:10 @test u.data[1:10] == 1:10 @test u[11] == 0f0 u .= u.data[:] @test norm(u, 1) == 55 @test u[1:10] == 1:10 @test u.data[1:10] == 1:10 @test u[11] == 0f0 if nd == 2 tmp = randn(Float32, u[1:10, :].n) u[1:10, :] .= tmp @test u.data[1:10, :] == tmp @test size(u[:, 1]) == (n[1],) @test size(u[1, :]) == (n[2],) @test u[2:end, 2:3].n == (n[1]-1, 2) u[:, 1] .= ones(Float32, n[1]) @test all(u.data[:, 1] .== 1f0) else tmp = randn(Float32, u[1:10, :, :].n) u[1:10, :, :] .= tmp @test u.data[1:10, :, :] == tmp @test size(u[:, :, 1]) == (n[1], n[2]) @test size(u[:, 1, :]) == (n[1], n[3]) @test size(u[1, :, :]) == (n[2], n[3]) @test size(u[1, 2:3, 1:end]) == (2, n[3]) @test u[1:2, 2:3, 1:end].n == (2, 2, n[3]) u[:, 1:end-2, 1] .= ones(Float32, n[1]) @test all(u.data[:, 1:end-2, 1] .== 1f0) end # Test that works with JOLI A = joEye(length(v); DDT=Float32, RDT=Float32) u2 = A*u @test isequal(u2, vec(u.data)) u2 = [A;A]*u @test length(u2) == 2 * length(u) @test u2[1:length(u)] == vec(u.data) @test u2[length(u)+1:end] == vec(u.data) # Test combinations n = (120, 100) # (x,y,z) or (x,z) d = (10., 10.) on = ones(Float32, n) m1 = PhysicalParameter(n, d, (0f0, 0f0), on) m2 = PhysicalParameter(n, d, (100f0, 100f0), on) m12 = m1 + m2 @test m12.o == m1.o @test m12.d == m1.d @test m12.n == (130, 110) # Check values overlap edges z edges x corners @test norm(m12.data, 1) == (110*90*2 + 10*90*2 + 10*110*2 + 10*10*2) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
10707
# Author: Mathias Louboutin, [email protected] # Date: November 2022 model, model0, dm = setup_model(tti, viscoacoustic, nlayer) wb = find_water_bottom(model.m .- maximum(model.m)) q, srcGeometry, recGeometry = setup_geom(model; nsrc=2) ftol = 1f-5 # Propagator if needed FM = judiModeling(model, srcGeometry, recGeometry) J = judiJacobian(FM, q) dobs = FM * q dobs_out = 0 .* dobs dm = model0.m - model.m @testset "Preconditioners test with $(nlayer) layers and tti $(tti) and freesurface $(fs)" begin @timeit TIMEROUTPUT "Data Preconditioners tests" begin F = judiFilter(recGeometry, .002, .030) Mdr = judiDataMute(srcGeometry, recGeometry; mode=:reflection) Mdt = judiDataMute(srcGeometry, recGeometry; mode=:turning) Mdg = judiTimeGain(recGeometry, 2f0) Mm = judiTopmute(model.n, 10, 1) order = .25f0 Dt = judiTimeDerivative(recGeometry, order) It = judiTimeIntegration(recGeometry, order) # Time differential only @test inv(It) == Dt @test inv(Dt) == It dinv = inv(It) * It * dobs @test isapprox(dinv, dobs; atol=0f0, rtol=ftol) dinv = inv(Dt) * Dt * dobs @test isapprox(dinv, dobs; atol=0f0, rtol=ftol) dinv = Dt * It * dobs @test isapprox(dinv, dobs; atol=0f0, rtol=ftol) # Time gain inverse is just 1/pow @test inv(Mdg) == judiTimeGain(recGeometry, -2f0) # conj/transpose for Pc in [F, Mdr, Mdt, Mdg, Dt, It] @test conj(Pc) == Pc @test transpose(Pc) == Pc end # DataPrecon getindex for Pc in [F, Mdr, Mdt, Mdg, Dt, It] @test Pc[1] * dobs[1] == (Pc * dobs)[1] @test Pc[1] * dobs.data[1][:] ≈ (Pc * dobs).data[1][:] rtol=ftol end # Time resample newt = 0f0:5f0:recGeometry.t[1] for Pc in [F, Mdr, Mdt, Mdg, Dt, It] @test_throws AssertionError time_resample(Pc, newt) @test time_resample(Pc[1], newt).recGeom.taxis[1] == newt end multiP = time_resample((F[1], Mdr[1]), newt) @test isa(multiP, JUDI.MultiPreconditioner) @test isa(multiP.precs[1], JUDI.FrequencyFilter) @test isa(multiP.precs[2], JUDI.DataMute) @test all(Pi.recGeom.taxis[1] == newt for Pi in multiP.precs) multiP = time_resample([F[1], Mdr[1]], newt) @test isa(multiP, JUDI.MultiPreconditioner) @test isa(multiP.precs[1], JUDI.FrequencyFilter) @test isa(multiP.precs[2], JUDI.DataMute) @test all(Pi.recGeom.taxis[1] == newt for Pi in multiP.precs) # Test in place DataPrecon for Pc in [F, Mdr, Mdt, Mdg, Dt, It] mul!(dobs_out, Pc, dobs) @test isapprox(dobs_out, Pc*dobs; rtol=ftol) mul!(dobs_out, Pc', dobs) @test isapprox(dobs_out, Pc'*dobs; rtol=ftol) # Check JUDI-JOLI compat mul!(dobs_out, Pc*J, dm) mul!(dobs, Pc*J, vec(dm.data)) dlin = Pc*J*dm @test isapprox(dobs_out, dlin; rtol=ftol) @test isapprox(dobs_out, dobs; rtol=ftol) end # check JOLI operator w/ judiVector DFT = joDFT(dm.n...; DDT=Float32, RDT=ComplexF32) dm1 = adjoint(J*DFT') * dobs dm2 = similar(dm1) mul!(dm2, adjoint(J*DFT'), dobs) @test isapprox(dm1, dm2; rtol=ftol) dm1 = Mm * J' * Mdr * dobs @test length(dm1) == prod(model0.n) @test dm1[1] == 0 # test out-of-place dobs1 = deepcopy(dobs) for Op in [F, F', Mdr , Mdr', Mdt, Mdt', Mdg, Mdg', Dt, Dt', It, It'] m = Op*dobs # Test that dobs wasn't modified @test isapprox(dobs, dobs1, rtol=eps()) # Test that it did compute something @test m != dobs end end @timeit TIMEROUTPUT "Model Preconditioners tests" begin # JUDI precon make sure it runs Ds = judiDepthScaling(model) Mm = judiTopmute(model.n, 20, 1) Mm2 = judiTopmute(model.n, 20 * ones(model.n[1]), 1) # conj/transpose for Pc in [Ds, Mm, Mm2] @test conj(Pc) == Pc @test transpose(Pc) == Pc end w = judiWeights(randn(Float32, model0.n)) w_out = judiWeights(zeros(Float32, model0.n)) mul!(w_out, Ds, w) @test isapprox(w_out, Ds*w; rtol=ftol) @test isapprox(w_out.weights[1][end, end]/w.weights[1][end, end], sqrt((model.n[2]-1)*model.d[2]); rtol=ftol) mul!(w_out, Ds', w) @test isapprox(w_out, Ds'*w; rtol=ftol) @test isapprox(w_out.weights[1][end, end]/w.weights[1][end, end], sqrt((model.n[2]-1)*model.d[2]); rtol=ftol) mul!(w_out, Mm, w) @test isapprox(w_out, Mm*w; rtol=ftol) @test isapprox(norm(w_out.weights[1][:, 1:19]), 0f0; rtol=ftol) mul!(w_out, Mm', w) @test isapprox(w_out, Mm'*w; rtol=ftol) w1 = deepcopy(w) for Op in [Ds, Ds'] m = Op*w # Test that w wasn't modified @test isapprox(w, w1,rtol=eps()) w_expect = deepcopy(w) for j = 1:model.n[2] w_expect.weights[1][:,j] = w.weights[1][:,j] * Float32(sqrt(model.d[2]*(j-1))) end @test isapprox(w_expect,m) end for Op in [Mm , Mm', Mm2, Mm2'] m = Op*w # Test that w wasn't modified @test isapprox(w,w1,rtol=eps()) @test all(isapprox.(m.weights[1][:,1:18], 0)) @test isapprox(m.weights[1][:,21:end],w.weights[1][:,21:end]) end # Depth scaling n = (100,100,100) d = (10f0,10f0,10f0) o = (0.,0.,0.) m = 0.25*ones(Float32,n) model3D = Model(n,d,o,m) D3 = judiDepthScaling(model3D) @test isa(inv(D3), DepthScaling{Float32, 3, -.5f0}) dmr = randn(Float32, prod(n)) dm1 = deepcopy(dmr) for Op in [D3, D3'] opt_out = Op*dmr # Test that dm wasn't modified @test dm1 == dmr dm_expect = zeros(Float32, model3D.n) for j = 1:model3D.n[3] dm_expect[:,:,j] = reshape(dmr, model3D.n)[:,:,j] * Float32(sqrt(model3D.d[3]*(j-1))) end @test isapprox(vec(dm_expect), opt_out) Op*model3D.m end M3 = judiTopmute(model3D.n, 20, 1) for Op in [M3, M3'] opt_out = Op*dmr # Test that dm wasn't modified @test dm1 == dmr @test all(isapprox.(reshape(opt_out,model3D.n)[:,:,1:18], 0)) @test isapprox(reshape(opt_out,model3D.n)[:,:,21:end],reshape(dmr,model3D.n)[:,:,21:end]) Op*model3D.m end # test find_water_bottom in 3D dm3D = ones(Float32,10,10,10) dm3D[:,:,4:end] .= 2f0 @test find_water_bottom(dm3D) == 4*ones(Integer,10,10) # Illumination I = judiIllumination(FM; mode="v") dloc = FM*q # forward only, nothing done @test I.illums["v"].data == ones(Float32, model.n) I = judiIllumination(FM; mode="u", recompute=false) dloc = FM[1]*q[1] @test norm(I.illums["u"]) != norm(ones(Float32, model.n)) bck = copy(I.illums["u"].data) dloc = FM[2]*q[2] # No recompute should not have changed @test I.illums["u"].data == bck # New mode Iv = I("v") @test "v" ∈ keys(Iv.illums) @test "u" ∉ keys(Iv.illums) @test norm(Iv.illums["v"]) == norm(ones(Float32, model.n)) # Test Product @test inv(I)*I*model0.m ≈ model0.m rtol=ftol atol=0 # Test in place ModelPrecon for Pc in [Ds, Mm, Mm2, I] mul!(dm, Pc, model.m) @test isapprox(dm, Pc*model.m; rtol=ftol) mul!(dm, Pc', model.m) @test isapprox(dm, Pc'*model.m; rtol=ftol) # Check JUDI-JOLI compat mul!(dm, Pc*J', dobs) dml = Pc*J'*dobs @test isapprox(dm, dml; rtol=ftol) mul!(dm, Pc*J', vec(dobs)) @test isapprox(dm, dml; rtol=ftol) end end @timeit TIMEROUTPUT "OOC Data Preconditioners tests" begin datapath = joinpath(dirname(pathof(JUDI)))*"/../data/" # OOC judiVector container = segy_scan(datapath, "unit_test_shot_records_2", ["GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"]) d_cont = judiVector(container; segy_depth_key="RecGroupElevation") src_geometry = Geometry(container; key = "source", segy_depth_key = "SourceDepth") wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.005) q_cont = judiVector(src_geometry, wavelet) # Make sure we test OOC @test typeof(d_cont) == judiVector{Float32, SeisCon} @test isequal(d_cont.nsrc, 2) @test isequal(typeof(d_cont.data), Array{SegyIO.SeisCon, 1}) @test isequal(typeof(d_cont.geometry), GeometryOOC{Float32}) # Make OOC preconditioner Mdt = judiDataMute(q_cont, d_cont) Mdg = judiTimeGain(d_cont, 2f0) # Test OOC DataPrecon for Pc in [Mdt, Mdg] # mul m = Pc * d_cont @test isa(m, JUDI.LazyMul{Float32}) @test m.nsrc == d_cont.nsrc @test m.P == Pc @test m.msv == d_cont ma = Pc' * d_cont @test isa(ma, JUDI.LazyMul{Float32}) @test isa(ma[1], JUDI.LazyMul{Float32}) @test ma.nsrc == d_cont.nsrc @test ma.P == Pc' @test ma.msv == d_cont # getindex m1 = m[1] @test isa(m1, JUDI.LazyMul{Float32}) @test m1.nsrc == 1 @test m1.msv == d_cont[1] @test get_data(m1) == get_data(Pc[1] * d_cont[1]) # data @test isa(m.data, JUDI.LazyData{Float32}) @test_throws MethodError m.data[1] = 1 @test m.data[1] ≈ (Pc[1] * get_data(d_cont[1])).data @test get_data(m.data) ≈ Pc * get_data(d_cont) # Propagation Fooc = judiModeling(model, src_geometry, d_cont.geometry) d_syn = Fooc' * Pc' * d_cont d_synic = Fooc' * Pc' * get_data(d_cont) @test isapprox(d_syn, d_synic; rtol=1f-5) f, g = fwi_objective(model0, Pc*d_cont, q_cont) f2, g2 = fwi_objective(model0, get_data(Pc*d_cont), get_data(q_cont)) @test isapprox(f, f2) @test isapprox(g, g2) end end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
8855
# Gradient tests for adjoint extended modeling # Author: Mathias Louboutin, [email protected] # April 2022 using Flux import JUDI: judiPropagator, LazyPropagation import Base.Broadcast: broadcasted Flux.Random.seed!(2022) ### Model nsrc = 1 dt = 1f0 model, model0, dm = setup_model(tti, viscoacoustic, 2) m, m0 = model.m.data, model0.m.data q, srcGeometry, recGeometry, f0 = setup_geom(model; nsrc=nsrc, dt=dt) # Common op Pr = judiProjection(recGeometry) Ps = judiProjection(srcGeometry) Pw = judiLRWF(dt, q.data[1]) function GenSimSourceMulti(xsrc_index, zsrc_index, nsrc, n) weights = zeros(Float32, n[1], n[2], 1, nsrc) for j=1:nsrc weights[xsrc_index[j], zsrc_index[j], 1, j] = 1f0 end return weights end randx(x::Array{Float32}) = x .* (1 .+ randn(Float32, size(x))) perturb(x::Vector{T}) where T = circshift(x, rand(1:20)) perturb(x::Array{T, N}) where {T, N} = circshift(x, (rand(1:20), zeros(N-1)...)) perturb(x::judiVector) = judiVector(x.geometry, [randx(x.data[i]) for i=1:x.nsrc]) reverse(x::judiVector) = judiVector(x.geometry, [x.data[i][end:-1:1, :] for i=1:x.nsrc]) misfit_objective_2p(d_obs, q0, m0, F) = .5f0*norm(F(m0, q0) - d_obs)^2 misfit_objective_1p(d_obs, q0, m0, F) = .5f0*norm(F(m0)*q0 - d_obs)^2 function loss(misfit, d_obs, q0, m0, F) local ϕ # Reshape as ML size if returns array d_obs = F.options.return_array ? reshape(d_obs, F.rInterpolation, F.model; with_batch=true) : d_obs # Misfit and gradient g = gradient(Flux.params(q0, m0)) do ϕ = misfit(d_obs, q0, m0, F) return ϕ end return ϕ, g[q0], g[m0] end xsrc_index, zsrc_index = rand(30:model.n[1]-30, nsrc), rand(30:model.n[2]-30, nsrc) w = GenSimSourceMulti(xsrc_index, zsrc_index, nsrc, model.n); # Put the point source at the same location for easy comparison q.geometry.xloc[1] .= (xsrc_index[1] - 1) * model.d[1] q.geometry.zloc[1] .= (zsrc_index[1] - 1) * model.d[2] sinput = zip(["Point", "Extended"], [Ps, Pw], (q, w)) ##################################################################################### ftol = sqrt(eps(1f0)) @testset "AD correctness check return_array:$(ra)" for ra in [true, false] opt = Options(return_array=ra, sum_padding=true, f0=f0) A_inv = judiModeling(model; options=opt) A_inv0 = judiModeling(model0; options=opt) @testset "AD correctness check source type: $(stype)" for (stype, Pq, q) in sinput @timeit TIMEROUTPUT "$(stype) source AD, array=$(ra)" begin printstyled("$(stype) source AD test ra: $(ra) \n", color=:blue) # Linear operators q0 = perturb(q) # Operators F = Pr*A_inv*adjoint(Pq) F0 = Pr*A_inv0*adjoint(Pq) d_obs = F(m, q) # PDE accept model as input but AD expect the actual model param (model.m) d_obs2 = F(model, q) @test d_obs ≈ d_obs2 rtol=ftol J = judiJacobian(F0, q0) gradient_m = adjoint(J)*(F(m0, q0) - d_obs) gradient_m2 = adjoint(J)*(F(model0.m, q0) - d_obs) @test gradient_m ≈ gradient_m2 rtol=ftol # Reshape d_obs into ML size (nt, nrec, 1, nsrc) d_obs = ra ? reshape(d_obs, Pr, model; with_batch=true) : d_obs # Gradient with m array gs_inv = gradient(x -> misfit_objective_2p(d_obs, q0, x, F), m0) if ~ra gs_inv1 = gradient(x -> misfit_objective_1p(d_obs, q0, x, F), model0.m) @test gs_inv[1][:] ≈ gs_inv1[1][:] rtol=ftol end # Gradient with m PhysicalParameter gs_inv2 = gradient(x -> misfit_objective_2p(d_obs, q0, x, F), model0.m) @test gs_inv[1][:] ≈ gs_inv2[1][:] rtol=ftol if ~ra gs_inv21 = gradient(x -> misfit_objective_1p(d_obs, q0, x, F), model0.m) @test gs_inv21[1][:] ≈ gs_inv2[1][:] rtol=ftol end g1 = vec(gradient_m) g2 = vec(gs_inv[1]) @test isapprox(norm(g1 - g2) / norm(g1 + g2), 0f0; atol=ftol) @test isapprox(dot(g1, g2)/norm(g1)^2,1f0;rtol=ftol) @test isapprox(dot(g1, g2)/norm(g2)^2,1f0;rtol=ftol) end end end @testset "AD Gradient test return_array=$(ra)" for ra in [true, false] opt = Options(return_array=ra, sum_padding=true, f0=f0, dt_comp=dt) F = judiModeling(model; options=opt) ginput = zip(["Point", "Extended"], [Pr*F*Ps', Pr*F*Pw'], (q, w)) @testset "Gradient test: $(stype) source" for (stype, F, q) in ginput @timeit TIMEROUTPUT "$(stype) source gradient, array=$(ra)" begin # Initialize source for source perturbation q0 = perturb(q) # Data and source perturbation d, dq = F*q, q-q0 misf = ra ? [(2, misfit_objective_2p)] : [(1, misfit_objective_1p), (2, misfit_objective_2p)] m00 = ra ? m0 : model0.m ##################################################################################### for (mi, misfit) in misf printstyled("$(stype) source gradient test for $(mi)-input operator\n"; color = :blue) f0, gq, gm = loss(misfit, d, q0, m00, F) # Gradient test for extended modeling: source printstyled("\nGradient test source $(stype) source, array=$(ra)\n"; color = :blue) grad_test(x-> misfit(d, x, m00, F), q0, dq, gq) # Gradient test for extended modeling: model printstyled("\nGradient test model $(stype) source, array=$(ra)\n"; color = :blue) grad_test(x-> misfit(d, q0, x, F), m00, dm, gm) end end end end @testset "AD Gradient test Jacobian w.r.t q with $(nlayer) layers, tti $(tti), viscoacoustic $(viscoacoustic), freesurface $(fs)" begin @timeit TIMEROUTPUT "Jacobian gradient w.r.t source" begin opt = Options(sum_padding=true, free_surface=fs) J = judiJacobian(judiModeling(model0, srcGeometry, recGeometry; options=opt), q) q0 = judiVector(q.geometry, ricker_wavelet(srcGeometry.t[1], srcGeometry.dt[1], 0.0125f0)) dq = q0 - q δd = J*dm rtm = J'*δd # derivative of J w.r.t to `q` printstyled("Gradient J(q) w.r.t q\n"; color = :blue) f0q, gm, gq = loss(misfit_objective_1p, δd, dm, q0, J) @test isa(gm, JUDI.LazyPropagation) @test isa(JUDI.eval_prop(gm), PhysicalParameter) grad_test(x-> misfit_objective_1p(δd, dm, x, J), q0, dq, gq) printstyled("Gradient J'(q) w.r.t q\n"; color = :blue) f0qt, gd, gqt = loss(misfit_objective_1p, rtm, δd, q0, adjoint(J)) @test isa(gd, JUDI.LazyPropagation) @test isa(JUDI.eval_prop(gd), judiVector) grad_test(x-> misfit_objective_1p(rtm, δd, x, adjoint(J)), q0, dq, gqt) end end ##################################################################################### struct TestPropagator{D, O} <: judiPropagator{D, O} v::D end Base.:*(T::TestPropagator{D, O}, x::Vector{D}) where {D, O} = T.v .* x Base.:*(T::TestPropagator{D, O}, x::Matrix{D}) where {D, O} = T.v .* x T1 = TestPropagator{Float32, :test}(2) T2 = TestPropagator{Float32, :test}(3) xtest1 = randn(Float32, 16) xtest2 = randn(Float32, 16) xtest3 = randn(Float32, 4, 4) xeval = reshape(2 .* xtest1, 4, 4) xeval2 = reshape(3 .* xtest2, 4, 4) p = x -> reshape(x, 4, 4) LP1 = LazyPropagation(p, T1, xtest1) LP2 = LazyPropagation(p, T2, xtest2) @testset "LazyPropagation tests" begin @timeit TIMEROUTPUT "LazyPropagation" begin # Manipulation @test collect(reshape(LP1, 8, 2)) == reshape(xeval, 8, 2) @test JUDI.eval_prop(LP1) == reshape(xeval, 4, 4) @test collect(LP1) == reshape(xeval, 4, 4) # Arithmetic for op in [Base.:+, Base.:-, Base.:*, Base.:/] @test op(LP1, xtest3) ≈ op(xeval, xtest3) @test op(xtest3, LP1) ≈ op(xtest3, xeval) @test op(LP1, LP2) ≈ op(xeval, xeval2) @test op.(LP1, LP2) ≈ op.(xeval, xeval2) @test op.(LP1, xtest3) ≈ op.(xeval, xtest3) @test op.(xtest3, LP2) ≈ op.(xtest3, xeval2) end @test LP1.^2 ≈ xeval.^2 @test T2 * LP1 ≈ reshape(6 .* xtest1, 4, 4) @test collect(adjoint(LP1)) ≈ collect(adjoint(xeval)) @test norm(LP1) ≈ norm(xeval) copyto!(xtest3, LP1) @test xtest3 ≈ xeval end end ##################################################################################### # Preconditioners @testset "Preconditionners AD tests" begin @timeit TIMEROUTPUT "Preconditionners AD" begin T = judiDepthScaling(model) b = T*model.m g = gradient(x->.5f0*norm(T*x - b)^2, model0.m) @test g[1] ≈ T'*(T*model0.m - b) end end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
code
888
mean(x) = sum(x)/length(x) function grad_test(misfit, x0, dx, g; maxiter=6, h0=5f-2, data=false, stol=1f-1) # init err1 = zeros(Float32, maxiter) err2 = zeros(Float32, maxiter) gdx = data ? g : dot(g, dx) f0 = misfit(x0) h = h0 @printf("%11.5s, %11.5s, %11.5s, %11.5s, %11.5s, %11.5s \n", "h", "gdx", "e1", "e2", "rate1", "rate2") for j=1:maxiter f = misfit(x0 + h*dx) err1[j] = norm(f - f0, 1) err2[j] = norm(f - f0 - h*gdx, 1) j == 1 ? prev = 1 : prev = j - 1 @printf("%5.5e, %5.5e, %5.5e, %5.5e, %5.5e, %5.5e \n", h, h*norm(gdx, 1), err1[j], err2[j], err1[prev]/err1[j], err2[prev]/err2[j]) h = h * .8f0 end rate1 = err1[1:end-1]./err1[2:end] rate2 = err2[1:end-1]./err2[2:end] @test isapprox(mean(rate1), 1.25f0; atol=stol) @test isapprox(mean(rate2), 1.5625f0; atol=stol) end
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
17634
# The Julia Devito Inversion framework (JUDI) | **Documentation** | **Build Status** | | |:--------------------------------------:|:-----------------------------------------------:|:----------------------------------------------------:| | [![][docs-stable-img]][docs-stable-status] [![][docs-dev-img]][docs-dev-status] | [![][build-img]][build-status] [![][codecov-img]][codecov-status] [![][aqua-img]][aqua-status] | [![][license-img]][license-status] [![][zenodo-img]][zenodo-status] [![][docker-img]][docker-url]| ## Overview [JUDI] is a framework for large-scale seismic modeling and inversion and is designed to enable rapid translations of algorithms to fast and efficient code that scales to industry-size 3D problems. The focus of the package lies on seismic modeling as well as PDE-constrained optimization such as full-waveform inversion (FWI) and imaging (LS-RTM). Wave equations in [JUDI] are solved with [Devito], a Python domain-specific language for automated finite-difference (FD) computations. JUDI's modeling operators can also be used as layers in (convolutional) neural networks to implement physics-augmented deep learning algorithms thanks to its implementation of [ChainRules](https://github.com/JuliaDiff/ChainRules.jl)'s `rrule` for the linear operators representing the discre wave equation. ## Interact and contribute We gladly welcome and encourage contributions from the community to improve our software and its usability. Feel free to: - Open [issues](https://github.com/slimgroup/JUDI.jl/issues) for bugs - Start [discussions](https://github.com/slimgroup/JUDI.jl/discussions) to interact with the developer and ask any questions - Open [PR](https://github.com/slimgroup/JUDI.jl/pulls) for bug fixes and improvements ## FAQ You can find an FAQ with answers to issues at [FAQ](https://github.com/slimgroup/JUDI.jl/wiki/FAQ) ## Installation and prerequisites You can find installation instructions in our Wiki at [Installation](https://github.com/slimgroup/JUDI.jl/wiki/Installation) ## GPU [JUDI] supports the computation of the wave equation on GPU via [Devito](https://www.devitoproject.org)'s GPU offloading support. **NOTE**: Only the wave equation part will be computed on GPU, the Julia arrays will still be CPU arrays and `CUDA.jl` is not supported. ### Installation To enable gpu support in JUDI, you will need to install one of [Devito](https://www.devitoproject.org)'s supported offloading compilers. We strongly recommend checking the [Wiki](https://github.com/devitocodes/devito/wiki) for installation steps and to reach out to the Devito community for GPU compiler related issues. - [x] `nvc/pgcc`. This is recommended and the simplest installation. You can install the compiler following Nvidia's installation instruction at [HPC-sdk](https://developer.nvidia.com/hpc-sdk) - [ ] `aompcc`. This is the AMD compiler that is necessary for running on AMD GPUs. This installation is not tested with [JUDI] and we recommend to reach out to Devito's team for installation guidelines. - [ ] `openmp5/clang`. This installation requires the compilation from source `openmp`, `clang` and `llvm` to install the latest version of `openmp5` enabling gpu offloading. You can find instructions on this installation in Devito's [Wiki](https://github.com/devitocodes/devito/wiki) ### Setup The only required setup for GPU support are the environment variables for [Devito]. For the currently supported `nvc+openacc` setup these are: ``` export DEVITO_LANGUAGE=openacc export DEVITO_ARCH=nvc export DEVITO_PLATFORM=nvidiaX ``` ## Running with Docker If you do not want to install JUDI, you can run [JUDI] as a [docker image](https://hub.docker.com/repository/docker/mloubout/judi). The first possibility is to run the docker container as a Jupyter notebook. [JUDI] provides two docker images for the latest [JUDI] release for Julia versions `1.6` (LTS) and `1.7` (latest stable version). The images names are `mloubout/judi:JVER-latest` where `JVER` is the Julia version. This docker images contain pre-installed compilers for CPUs (gcc-10) and Nvidia GPUs (nvc) via the nvidia HPC sdk. The environment is automatically set for [Devito] based on the hardware available. **Note**: If you wish to use your gpu, you will need to install [nvidia-docker](https://docs.nvidia.com/ai-enterprise/deployment-guide/dg-docker.html) and run `docker run --gpus all` in order to make the GPUs available at runtime from within the image. To run [JUDI] via docker execute the following command in your terminal: ```bash docker run -p 8888:8888 mloubout/judi:1.7-latest ``` This command downloads the image and launches a container. You will see a link that you can copy-paste to your browser to access the notebooks. Alternatively, you can run a bash session, in which you can start a regular interactive Julia session and run the example scripts. Download/start the container as a bash session with: ```bash docker run -it mloubout/judi:1.7-latest /bin/bash ``` Inside the container, all examples are located in the directory `/app/judi/examples/scripts`. **Previous versions**: As of version `v2.6.7` of JUDI, we also ship version-tagged images as `mloubout/judi:JVER-ver` where `ver` is the version of [JUDI] wanted, for example the current [JUDI] version with Julia 1.7 is `mloubout/judi:1.7-v2.6.7` **Development version**: Additionally, we provide two images corresponding to the latest development version of [JUDI] (latest state of the master branch). These images are called `mloubout/judi:JVER-dev` and can be used in a similar way. ## Testing A complete test suite is included with [JUDI] and is tested via GitHub Actions. You can also run the test locally via: ```Julia Julia --project -e 'using Pkg;Pkg.test(coverage=false)' ``` By default, only the [JUDI] base API will be tested. However, the testing suite supports other modes controlled via the environment variable `GROUP` such as: ```Julia GROUP=JUDI Julia --project -e 'using Pkg;Pkg.test(coverage=false)' ``` The supported modes are: - JUDI : Only the base API (linear operators, vectors, ...) - BASICS: Generic modeling and inversion tests such as out of core behavior - ISO_OP : Isotropic acoustic operators - ISO_OP_FS : Isotropic acoustic operators with free surface - TTI_OP : Transverse tilted isotropic operators - TTI_OP_FS : Transverse tilted isotropic operators with free surface - filename : you can also provide just a filename (i.e `GROUP=test_judiVector.jl`) and only this one test file will be run. Single files with TTI or free surface are not currently supported as it relies on `Base.ARGS` for the setup. ## Configure compiler and OpenMP Devito uses just-in-time compilation for the underlying wave equation solves. The default compiler is intel, but can be changed to any other specified compiler such as `gnu`. Either run the following command from the command line or add it to your ~/.bashrc file: ```bash export DEVITO_ARCH=gnu ``` Devito uses shared memory OpenMP parallelism for solving PDEs. OpenMP is disabled by default, but you can enable OpenMP and define the number of threads (per PDE solve) as follows: ```bash export DEVITO_LANGUAGE=openmp # Enable OpenMP. export OMP_NUM_THREADS=4 # Number of OpenMP threads ``` ## Full-waveform inversion [JUDI] is designed to let you set up objective functions that can be passed to standard packages for (gradient-based) optimization. The following example demonstrates how to perform FWI on the 2D Overthrust model using a spectral projected gradient algorithm from the minConf library, which is included in the software. A small test dataset (62 MB) and the model can be downloaded from this FTP server: ```Julia run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_2D.segy`) run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_2D_initial_model.h5`) ``` The first step is to load the velocity model and the observed data into Julia, as well as setting up bound constraints for the inversion, which prevent too high or low velocities in the final result. Furthermore, we define an 8 Hertz Ricker wavelet as the source function: ```Julia using PyPlot, HDF5, SegyIO, JUDI, SlimOptim, Statistics, Random # Load starting model n, d, o, m0 = read(h5open("overthrust_2D_initial_model.h5", "r"), "n", "d", "o", "m0") model0 = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0) # need n, d, o as tuples and m0 as array # Bound constraints vmin = ones(Float32, model0.n) .+ 0.3f0 vmax = ones(Float32, model0.n) .+ 5.5f0 mmin = vec((1f0 ./ vmax).^2) # convert to slowness squared [s^2/km^2] mmax = vec((1f0 ./ vmin).^2) # Load segy data block = segy_read("overthrust_2D.segy") dobs = judiVector(block) # Set up wavelet src_geometry = Geometry(block; key="source", segy_depth_key="SourceDepth") # read source position geometry wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.008f0) # 8 Hz wavelet q = judiVector(src_geometry, wavelet) ``` For this FWI example, we define an objective function that can be passed to the minConf optimization library, which is included in the Julia Devito software package. We allow a maximum of 20 function evaluations using a spectral-projected gradient (SPG) algorithm. To save computational cost, each function evaluation uses a randomized subset of 20 shot records, instead of all 97 shots: ```Julia # Optimization parameters fevals = 20 # number of function evaluations batchsize = 20 # number of sources per iteration fvals = zeros(21) opt = Options(optimal_checkpointing = false) # set to true to enable checkpointing # Objective function for minConf library count = 0 function objective_function(x) model0.m = reshape(x, model0.n); # fwi function value and gradient i = randperm(dobs.nsrc)[1:batchsize] fval, grad = fwi_objective(model0, q[i], dobs[i]; options=opt) grad = reshape(grad, model0.n); grad[:, 1:21] .= 0f0 # reset gradient in water column to 0. grad = .1f0*grad/maximum(abs.(grad)) # scale gradient for line search global count; count += 1; fvals[count] = fval return fval, vec(grad.data) end # FWI with SPG ProjBound(x) = median([mmin x mmax], dims=2) # Bound projection options = spg_options(verbose=3, maxIter=fevals, memory=3) x, fsave, funEvals= minConf_SPG(objective_function, vec(m0), ProjBound, options) ``` This example script can be run in parallel and requires roughly 220 MB of memory per source location. Execute the following code to generate figures of the initial model and the result, as well as the function values: ```Julia figure(); imshow(sqrt.(1./adjoint(m0))); title("Initial model") figure(); imshow(sqrt.(1./adjoint(reshape(x, model0.n)))); title("FWI") figure(); plot(fvals); title("Function value") ``` ![fwi](docs/src/figures/fwi.png) ## Least squares reverse-time migration [JUDI] includes matrix-free linear operators for modeling and linearized (Born) modeling, that let you write algorithms for migration that follow the mathematical notation of standard least squares problems. This example demonstrates how to use Julia Devito to perform least-squares reverse-time migration on the 2D Marmousi model. Start by downloading the test data set (1.1 GB) and the model: ```Julia run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_2D.segy`) run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_migration_velocity.h5`) ``` Once again, load the starting model and the data and set up the source wavelet. For this example, we use a Ricker wavelet with 30 Hertz peak frequency. For setting up matrix-free linear operators, an `info` structure with the dimensions of the problem is required: ```Julia using PyPlot, HDF5, JUDI, SegyIO, Random # Load smooth migration velocity model n,d,o,m0 = read(h5open("marmousi_migration_velocity.h5","r"), "n", "d", "o", "m0") model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0) # Load data block = segy_read("marmousi_2D.segy") dD = judiVector(block) # Set up wavelet src_geometry = Geometry(block; key="source", segy_depth_key="SourceDepth") wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.03) # 30 Hz wavelet q = judiVector(src_geometry,wavelet) # Set up info structure ntComp = get_computational_nt(q.geometry,dD.geometry,model0) # no. of computational time steps info = Info(prod(model0.n),dD.nsrc,ntComp) ``` To speed up the convergence of our imaging example, we set up a basic preconditioner for each the model- and the data space, consisting of mutes to suppress the ocean-bottom reflection in the data and the source/receiver imprint in the image. The operator `J` represents the linearized modeling operator and its adjoint `J'` corresponds to the migration (RTM) operator. The forward and adjoint pair can be used for a basic LS-RTM example with (stochastic) gradient descent: ```Julia # Set up matrix-free linear operators opt = Options(optimal_checkpointing = true) # set to false to disable optimal checkpointing F = judiModeling(model0, q.geometry, dD.geometry; options=opt) J = judiJacobian(F, q) # Right-hand preconditioners (model topmute) Mr = judiTopmute(model0.n, 52, 10) # mute up to grid point 52, with 10 point taper # Left-hand preconditioners Ml = judiDataMute(q.geometry, dD.geometry; t0=.120) # data topmute starting at 120ms (30 samples) # Stochastic gradient x = zeros(Float32, info.n) # zero initial guess batchsize = 10 # use subset of 10 shots per iteration niter = 32 fval = zeros(Float32, niter) for j=1:niter println("Iteration: ", j) # Select batch and set up left-hand preconditioner i = randperm(dD.nsrc)[1:batchsize] # Compute residual and gradient r = Ml[i]*J[i]*Mr*x - Ml[i]*dD[i] g = adjoint(Mr)*adjoint(J[i])*adjoint(Ml[i])*r # Step size and update variable fval[j] = .5f0*norm(r)^2 t = norm(r)^2/norm(g)^2 global x -= t*g end ``` ![lsrtm](docs/src/figures/lsrtm.png) ## Machine Learning [JUDI] implements [ChainRulesCore] reverse rules to integrate the modeling operators into convolutional neural networks for deep learning. For example, the following code snippet shows how to create a shallow CNN consisting of two convolutional layers with a nonlinear forward modeling layer in-between them. [JUDI] enables backpropagation through [Flux]' automatic differentiation tools, but calls the corresponding adjoint [JUDI] operators under the hood. ```Julia # Jacobian W1 = judiJacobian(F0, q) b1 = randn(Float32, num_samples) # Fully connected layer W2 = randn(Float32, n_out, num_samples) b2 = randn(Float32, n_out) # Network and loss network(x) = W2*(W1*x .+ b1) .+ b2 loss(x, y) = Flux.mse(network(x), y) # Compute gradient w/ Flux p = params(x, y, W1, b1, b2) gs = Tracker.gradient(() -> loss(x, y), p) gs[x] # gradient w.r.t. to x ``` [JUDI] allows implementing physics-augmented neural networks for seismic inversion, such as loop-unrolled seismic imaging algorithms. For example, the following results are a conventional RTM image, an LS-RTM image and a loop-unrolled LS-RTM image for a single simultaneous shot record. ![flux](docs/src/figures/figure1.png) ## Authors This package was written by [Philipp Witte](https://www.linkedin.com/in/philipp-witte/) and [Mathias Louboutin](https://mloubout.github.io/) from the Seismic Laboratory for Imaging and Modeling (SLIM) at the Georgia Institute of Technology. If you use our software for your research, please cite our [Geophysics paper](https://library.seg.org/doi/abs/10.1190/geo2018-0174.1#): ```bibtex @article{witteJUDI2019, author = {Philipp A. Witte and Mathias Louboutin and Navjot Kukreja and Fabio Luporini and Michael Lange and Gerard J. Gorman and Felix J. Herrmann}, title = {A large-scale framework for symbolic implementations of seismic inversion algorithms in Julia}, journal = {GEOPHYSICS}, volume = {84}, number = {3}, pages = {F57-F71}, year = {2019}, doi = {10.1190/geo2018-0174.1}, URL = {https://doi.org/10.1190/geo2018-0174.1}, eprint = {https://doi.org/10.1190/geo2018-0174.1} } ``` Also visit the Devito homepage at <https://www.devitoproject.org/publications> for more information and references. Contact authors via: [email protected]. [docs-stable-img]:https://img.shields.io/badge/docs-stable-blue.svg?style=plastic [docs-stable-status]:https://slimgroup.github.io/JUDI.jl/stable [docs-dev-img]:https://img.shields.io/badge/docs-dev-blue.svg [docs-dev-status]:https://slimgroup.github.io/JUDI.jl/dev [build-img]:https://github.com/slimgroup/JUDI.jl/workflows/CI-tests/badge.svg?style=plastic [build-status]:https://github.com/slimgroup/JUDI.jl/actions?query=workflow%3ACI-tests [codecov-img]:https://codecov.io/gh/slimgroup/JUDI.jl/branch/master/graph/badge.svg?style=plastic [codecov-status]:https://codecov.io/gh/slimgroup/JUDI.jl [aqua-img]:https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg?style=plastic [aqua-status]:https://github.com/JuliaTesting/Aqua.jl [zenodo-img]:https://zenodo.org/badge/DOI/10.5281/zenodo.3878711.svg?style=plastic [zenodo-status]:https://doi.org/10.5281/zenodo.3878711 [license-img]:http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat?style=plastic [license-status]:LICENSE.md [docker-img]:https://img.shields.io/docker/v/mloubout/judi?color=blueviolet&label=docker&sort=semver [docker-url]:https://hub.docker.com/r/mloubout/judi [JUDI]:https://github.com/slimgroup/JUDI.jl [Devito]:https://github.com/devitocodes/devito [ChainRulesCore]:https://github.com/JuliaDiff/ChainRulesCore.jl [Flux]:https://github.com/FluxML/Flux.jl
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
2242
# Authors This package was written by [Philipp Witte](https://www.linkedin.com/in/philipp-witte/) and [Mathias Louboutin](https://mloubout.github.io) from the Seismic Laboratory for Imaging and Modeling (SLIM) at the Georgia Institute of Technology. People involved in the development of JUDI include: - Philipp A. Witte^* (Now MSFT) - Mathias Louboutin (Georgia Institute of Technology) - Henryk Modzelewski (The Univeristy of British Columbia) - Felix J. Herrmann (Georgia Institute of Technology) And you can find the full list of collaborators on github at [Contributors](https://github.com/slimgroup/JUDI.jl/graphs/contributors). ## Cite us If you use our software for your research, please cite our [Geophysics paper](https://library.seg.org/doi/abs/10.1190/geo2018-0174.1#): ``` @article{witteJUDI2019, author = {Philipp A. Witte and Mathias Louboutin and Navjot Kukreja and Fabio Luporini and Michael Lange and Gerard J. Gorman and Felix J. Herrmann}, title = {A large-scale framework for symbolic implementations of seismic inversion algorithms in Julia}, journal = {GEOPHYSICS}, volume = {84}, number = {3}, pages = {F57-F71}, year = {2019}, doi = {10.1190/geo2018-0174.1}, URL = {https://doi.org/10.1190/geo2018-0174.1}, eprint = {https://doi.org/10.1190/geo2018-0174.1} } ``` Also visit the Devito homepage at <https://www.devitoproject.org/publications> for more information and references. If you need to cite a specific version of JUDI, you can find our citeable archives on [Zenodo](https://doi.org/10.5281/zenodo.3878711). ## Contribution and community We gladly welcome and encorage contributions from the community to improve our software and its usability. Feel free to: - Open [issues](https://github.com/slimgroup/JUDI.jl/issues) for bugs - Start [discussions](https://github.com/slimgroup/JUDI.jl/discussions) to interat with the developper and ask any questions - Open [PR](https://github.com/slimgroup/JUDI.jl/pulls) for bug fixes and improvements ## Field examples An example of using JUDI to invert field data is provided for the [Viking Graben Line 12](https://github.com/slimgroup/JUDI.jl/examples/field_examples/viking_graben_line12) which includes data preprocessing steps using Madagascar.
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
4251
# Abstract Vectors JUDI provides abstract vector types that encapsulate seismic related objects. In particula, JUDI defines thre main types for seismic data [`judiVector`](@ref), full time-space wavefields [`judiWavefield`](@ref) and extended source weights [`judiWeights`](@ref). ```@contents Pages = ["abstract_vectors.md"] ``` At the core of JUDI's vector types is the abstract type `judiMultiSourceVector` that represent a dimensionalized `Vector{Array}` where each sub-array correspond to a single source. All JUDI vector types inhert from this abstract type that implements most of the arithmetic and julia core utilities. As an abstract types, `judiMultiSourceVector` should not be instantiated but new concrete types based on it should be created if one desire to create its own JUDI multi-source vector type. All sub-type of `judiMultiSourceVector` must implement the following methods to be compatible with JUDI. The following JUDI core types are examples of sub-types. ## judiVector The class `judiVector` is the basic data structure for seismic shot records or seismic sources. From JUDI's perspective, both are treated the same and can be multiplied with modeling operators. **Construction:** In the most basic way, `judiVectors` are contstructed from a `Geometry` object (containing either source or receiver geometry) and a cell array of data: ```@docs judiVector(geometry::Geometry, data::Array{T, N}) where {T, N} ``` **Access fields (in-core data containers):** ```julia # Access i-th shot record x.data[i] # Extract judiVector for i-th shot x1 = x[i] # Access j-th receiver location of i-th shot x.geometry.xloc[i][j] ``` **Access fields (out-of-core data containers):** ```julia # Access data container of i-th shot x.data[i] # Read data from i-th shot into memory x.data[i][1].data # Access out-of-core geometry x.geometry # Load OOC geometry into memory Geometry(x.geometry) ``` **Operations:** In-core `judiVectors` can be used like regular Julia arrays and support common operations such as: ```julia x = judiVector(geometry, data) # Size (as if all data was vectorized) size(x) # Norms norm(x) # Inner product dot(x, x) # Addition, subtraction (geometries must match) y = x + x z = x - y # Scaling α = 2f0 y = x * α # Concatenate y = vcat(x, x) ``` ## judiWavefield Abstract vector class for wavefields. **Construction:** ```@docs judiWavefield ``` **Access fields:** ```julia # Access wavefield from i-th shot location u.data[i] ``` **Operations:** Supports some basic arithmetric operations: ```julia # Size size(u) # Norms norm(u) # Inner product dot(u, y) # Addition, subtraction v = u + u z = u - v # Absolute value abs(u) # Concatenation v = vcat(u, u) ``` ## judiRHS Abstract vector class for a right-hand-side (RHS). A RHS has the size of a full wavefield, but only contains the data of the source wavelet of shot records in memory, as well as the geometry information of where the data is injected during modeling. **Construction:** ```julia rhs = judiRHS(geometry, data) ``` A JUDI RHS can also be constructed by multplying a `judiVector` and the corresponding transpose of a `judiProjection` operator: ```julia rhs1 = Ps'*q rhs2 = Pr'*d_obs ``` where `Ps` and `Pr` are `judiProjection` operators for sources and receivers respectively and `q` and `d_obs` are `judiVectors` with the source and receiver data. **Access fields:** Accessible fields include: ```julia # Source/receiver data rhs.data # Source/receiver geometry rhs.geometry # Info structure rhs.info ``` ## judiWeights Abstract vector class for extended source weights. The weights for each shot location have the dimensions of the model (namely `model.n`). **Construction:** ```@docs judiWeights(weights::Array{T, N}; nsrc=1, vDT::DataType=Float32) where {T<:Real, N} ``` **Parameters:** * `weights`: Cell array with one cell per shot location. Each cell contains a 2D/3D Julia array with the weights for the spatially extended source. Alternatively: pass a single Julia array which will be used for all source locations. **Access fields:** ```julia # Access weights of i-th shot locatoin w.weights[i] ``` **Operations:** Supports the same arithmetric operations as a `judiVector`.
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
24452
# Getting Started These tutorials provide instructions of how to set up various modeling or inversion scenarios with JUDI. For a list of runnable Julia scripts and reproducable research, please also check out the examples: - The [examples](https://github.com/slimgroup/JUDI.jl/tree/master/examples/scripts) scripts contain simple modeling and inversion examples such as FWI, LSRTM, and medical modeling. - The [machine-learning](https://github.com/slimgroup/JUDI.jl/tree/master/examples/machine-learning) scripts contain examples of machine learning using Flux. ```@contents Pages = ["tutorials.md"] ``` ## 2D Modeling Quickstart To set up a simple 2D modeling experiment with JUDI with an OBN-type acquisition (receivers everywhere), we start by loading the module and building a two layer model: ```julia using JUDI # Grid n = (120, 100) # (x,z) d = (10., 10.) o = (0., 0.) # Velocity [km/s] v = ones(Float32, n) .* 1.4f0 v[:, 50:end] .= 5f0 # Squared slowness m = (1f0 ./ v).^2 ``` For working with JUDI operators, we need to set up a model structure, which contains the grid information, as well as the slowness. Optionally, we can provide an array of the density in `g/cm^3` (by default a density of 1 is used): ```julia # Density (optional) rho = ones(Float32, n) # Model structure: model = Model(n, d, o, m; rho=rho) ``` Next, we define our source acquisition geometry, which needs to be defined as a `Geometry` structure. The `Geometry` function requires the x-, y- and z-coordinates of the source locations as input, as well as the modeling time and samping interval of the wavelet. In general, each parameter can be passed as a cell array, where each cell entry provides the information for the respective source location. The helper function `convertToCell` converts a Julia `range` to a cell array, which makes defining the source geometry easier: ```julia # Set up source geometry nsrc = 4 # no. of sources xsrc = convertToCell(range(400f0, stop=800f0, length=nsrc)) ysrc = convertToCell(range(0f0, stop=0f0, length=nsrc)) zsrc = convertToCell(range(20f0, stop=20f0, length=nsrc)) # Modeling time and sampling interval time = 1000f0 # ms dt = 2f0 # ms # Set up source structure src_geometry = Geometry(xsrc, ysrc, zsrc; dt=dt, t=time) ``` Now we can define our source wavelet. The source must be defined as a `judiVector`, which takes the source geometry, as well as the source data (i.e. the wavelet) as an input argument: ```julia # Source wavelet f0 = 0.01f0 # kHz wavelet = ricker_wavelet(time, dt, f0) q = judiVector(src_geometry, wavelet) ``` In general, `wavelet` can be a cell array with a different wavelet in each cell, i.e. for every source location. Here, we want to use the same wavelet for all 4 source experiments, so we can simply pass a single vector. As we already specified in our `src_geometry` object that we want to have 4 source locations, `judiVector` will automaticallty copy the wavelet for every experiment. Next, we set up the receiver acquisition geometry. Here, we define an OBN acquisition, where the receivers are spread out over the entire domain and each source experiment uses the same set of receivers. Again, we can in principle pass the coordinates as cell arrays, with one cell per source location. Since we want to use the same geometry for every source, we can use a short cut and define the coordinates as Julia `ranges` and pass `nsrc=nsrc` as an optional argument to the `Geometry` function. This tells the function that we want to use our receiver set up for `nsrc` distinct source experiments: ```julia # Set up receiver geometry (for 2D, set yrec to zero) nxrec = 120 xrec = range(50f0, stop=1150f0, length=nxrec) yrec = 0f0 zrec = range(50f0, stop=50f0, length=nxrec) # Set up receiver structure rec_geometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc) ``` Next, we can define separate operators for source/receiver projections and a forward modeling operator: ```julia # Setup operators Pr = judiProjection(rec_geometry) A_inv = judiModeling(model) Ps = judiProjection(src_geometry) ``` We can see, that from JUDI's perspective, source and receivers are treated equally and are represented by the same operators (`judiProjection`) and vectors (`judiVector`). We also could've skipped setting up the projection operators and directly created: ```julia F = judiModeling(model, src_geometry, rec_geometry) ``` which is equivalent to creating the combined operator: ```julia F = Pr*A_inv*Ps' ``` Finally, to model our seismic data, we run: ```julia d_obs = Pr*A_inv*Ps'*q # or d_obs = F*q ``` We can plot a 2D shot record by accessing the `.data` field of the `judiVector`, which contains the data in the original (non-vectorized) dimensions: ```julia using PyPlot imshow(d_obs.data[1], vmin=-5, vmax=5, cmap="seismic", aspect="auto") ``` We can also set up a Jacobian operator for Born modeling and reverse-time migration. First we set up a (constant) migration velocity model: ```julia v0 = ones(Float32, n) .* 1.4f0 m0 = (1f0 ./ v0).^2 dm = m - m0 # model perturbation/image # Model structure model0 = Model(n, d, o, m0) ``` We can create the Jacobian directly from a (non-linear) modeling operator and a source vector: ```julia A0_inv = judiModeling(model0) # modeling operator for migration velocity J = judiJacobian(Pr*A0_inv*Ps', q) ``` We can use this operator to model single scattered data, as well as for migration our previous data: ```julia d_lin = J*vec(dm) # RTM rtm = J'*d_obs ``` To plot, first reshape the image: ```julia rtm = reshape(rtm, model0.n) imshow(rtm', cmap="gray", vmin=-1e3, vmax=1e3) ``` ## 3D Modeling Quickstart Setting up a 3D experiment largely follows the instructions for the 2D example. Instead of a 2D model, we define our velocity model as: ```julia using JUDI # Grid n = (120, 100, 80) # (x,y,z) d = (10., 10., 10.) o = (0., 0., 0.) # Velocity [km/s] v = ones(Float32, n) .* 1.4f0 v[:, :, 40:end] .= 5f0 # Squared slowness and model structure m = (1f0 ./ v).^2 model = Model(n, d, o, m) ``` Our source coordinates now also need to have the y-coordinate defined: ```julia # Set up source geometry nsrc = 4 # no. of sources xsrc = convertToCell(range(400f0, stop=800f0, length=nsrc)) ysrc = convertToCell(range(200f0, stop=1000f0, length=nsrc)) zsrc = convertToCell(range(20f0, stop=20f0, length=nsrc)) # Modeling time and sampling interval time = 1000f0 # ms dt = 2f0 # ms # Set up source structure src_geometry = Geometry(xsrc, ysrc, zsrc; dt=dt, t=time) ``` Our source wavelet, is set up as in the 2D case: ```julia # Source wavelet f0 = 0.01f0 # kHz wavelet = ricker_wavelet(time, dt, f0) q = judiVector(src_geometry, wavelet) ``` For the receivers, we generally need to define each coordinate (x, y, z) for every receiver. I.e. `xrec`, `yrec` and `zrec` each have the length of the total number of receivers. However, oftentimes we are interested in a regular receiver grid, which can be defined by two basis vectors and a constant depth value for all receivers. We can then use the `setup_3D_grid` helper function to create the full set of coordinates: ```julia # Receiver geometry nxrec = 120 nyrec = 100 xrec = range(50f0, stop=1150f0, length=nxrec) yrec = range(100f0, stop=900f0, length=nyrec) zrec = 50f0 # Construct 3D grid from basis vectors (xrec, yrec, zrec) = setup_3D_grid(xrec, yrec, zrec) # Set up receiver structure rec_geometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc) ``` Setting up the modeling operators is done as in the previous 2D case: ```julia # Setup operators Pr = judiProjection(rec_geometry) A_inv = judiModeling(model) Ps = judiProjection(src_geometry) # Model data d_obs = Pr*A_inv*Ps'*q ``` The 3D shot records are still saved as 2D arrays of dimensions `time x (nxrec*nyrec)`: ```julia using PyPlot imshow(d_obs.data[1], vmin=-.4, vmax=.4, cmap="seismic", aspect="auto") ``` ## Vertical and tilted-transverse isotropic modeling (VTI, TTI) JUDI supports both VTI and TTI modeling based on a coupled pseudo-acoustic wave equation. To enable VTI/TTI modeling, simply pass Thomsen parameters as well as the tilt angles to the `Model` structure as optional keyword arguments: ```julia # Grid and model n = (120, 100, 80) d = (10., 10., 10) o = (0., 0., 0.) # Velocity v = ones(Float32, n) .* 1.5f0 m = 1f0 ./ v.^2 # Thomsen parameters epsilon = ones(Float32, n) .* 0.2f0 delta = ones(Float32, n) .* 0.1f0 # Tile angles for TTI theta = ones(Float32, n) .* pi/2f0 phi = ones(Float32, n) .* pi/3f0 # 3D only # Set up model structure with Thomsen parameters model = Model(n, d, o, m; rho=rho, epsilon=epsilon, delta=delta, theta=theta, delta=delta) ``` ## Modeling with density To use density, pass `rho` in the units of `[g/cm^3]` as an optional keyword argument to the Model structure. The default density is `rho=1f0` (i.e. density of water): ```julia # Grid and model n = (120, 100) d = (10., 10.) o = (0., 0.) v = ones(Float32, n) .* 1.5f0 m = 1f0 ./ v.^2 rho = ones(Float32, n) .* 1.1f0 # Set up model structure with density model = Model(n, d, o, m; rho=rho) ``` ## 2D Marine streamer acquisition For a marine streamer acquisition, we need to define a moving set of receivers representing a streamer that is towed behind a seismic source vessel. In JUDI, this is easily done by defining a different set of receivers for each source location. Here, we explain how to set up the `Geometry` objects for a 2D marine streamer acquisition. If we define that our streamer is to the right side of the source vessel, this has the effect that part of the streamer is outside the grid while our vessel is in the right side of the model. To circumvent this, we can say that our streamer is on the right side of the source while the vessel is in the left-hand side of the model and vice versa. This way, we get the full maximum offset coverage for every source location (assuming that the maximum offset is less or equal than half the domain size). First, we have to specify our domain size (the physical extent of our model), as well as the number of receivers and the minimum and maximum offset: ```julia domain_x = (model.n[1] - 1)*model.d[1] # horizontal extent of model nrec = 120 # no. of receivers xmin = 50f0 # leave buffer zone w/o source and receivers of this size xmax = domain_x - 50f0 min_offset = 10f0 # distance between source and first receiver max_offset = 400f0 # distance between source and last xmid = domain_x / 2 # midpoint of model source_spacing = 25f0 # source interval [m] ``` For the JUDI `Geometry` objects, we need to create cell arrays for the source and receiver coordinates, with one cell entry per source location: ```julia # Source/receivers nsrc = 20 # number of shot locations # Receiver coordinates xrec = Array{Any}(undef, nsrc) yrec = Array{Any}(undef, nsrc) zrec = Array{Any}(undef, nsrc) # Source coordinates xsrc = Array{Any}(undef, nsrc) ysrc = Array{Any}(undef, nsrc) zsrc = Array{Any}(undef, nsrc) ``` Next, we compute the source and receiver coordinates for when the vessel moves from left to right in the right-hand side of the model: ```julia # Vessel goes from left to right in right-hand side of model nsrc_half = Int(nsrc/2) for j=1:nsrc_half xloc = xmid + (j-1)*source_spacing # Current receiver locations xrec[j] = range(xloc - max_offset, xloc - min_offset, length=nrec) yrec[j] = 0. zrec[j] = range(50f0, 50f0, length=nrec) # Current source xsrc[j] = xloc ysrc[j] = 0f0 zsrc[j] = 20f0 end ``` Then, we repeat this for the case where the vessel goes from right to left in the left-hand model side: ```julia # Vessel goes from right to left in left-hand side of model for j=1:nsrc_half xloc = xmid - (j-1)*source_spacing # Current receiver locations xrec[nsrc_half + j] = range(xloc + min_offset, xloc + max_offset, length=nrec) yrec[nsrc_half + j] = 0f0 zrec[nsrc_half + j] = range(50f0, 50f0, length=nrec) # Current source xsrc[nsrc_half + j] = xloc ysrc[nsrc_half + j] = 0f0 zsrc[nsrc_half + j] = 20f0 end ``` Finally, we can set the modeling time and sampling interval and create the `Geometry` objects: ```julia # receiver sampling and recording time time = 10000f0 # receiver recording time [ms] dt = 4f0 # receiver sampling interval # Set geometry objects rec_geometry = Geometry(xrec, yrec, zrec; dt=dt, t=time) src_geometry = Geometry(xsrc, ysrc, zsrc; dt=dt, t=time) ``` You can find a full (reproducable) example for generating a marine streamer data set for the Sigsbee 2A model [here](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/Sigsbee2A/generate_data_sigsbee.jl). ## Simultaneous sources To set up a simultaneous source with JUDI, we first create a cell array with `nsrc` cells, where `nsrc` is the number of separate experiments (here `nsrc=1`). For a simultaneous source, we create an array of source coordinates for each cell entry. In fact, this is exactly like setting up the receiver geometry, in which case we define multiple receivers per shot location. Here, we define a single experiment with a simultaneous source consisting of four sources: ```julia nsrc = 1 # single simultaneous source xsrc = Vector{Float32}(undef, nsrc) ysrc = Vector{Float32}(undef, nsrc) zsrc = Vector{Float32}(undef, nsrc) # Set up source geometry xsrc[1] = [250f0, 500f0, 750f0, 1000f0] # four simultaneous sources ysrc[1] = 0f0 zsrc[1] = [50f0, 50f0, 50f0, 50f0] # Source sampling and number of time steps time = 2000f0 dt = 4f0 # Set up source structure src_geometry = Geometry(xsrc, ysrc, zsrc; dt=dt, t=time) ``` With the simultaneous source geometry in place, we can now create our simultaneous data. As we have four sources per sim. source, we create an array of dimensions `4 x src_geometry.nt[1]` and fill it with wavelets of different time shifts: ```julia # Create wavelet f0 = 0.01 # source peak frequencies q = ricker_wavelet(500f0, dt, f0) # 500 ms wavelet # Create array with different time shifts of the wavelet wavelet = zeros(Float32, 4, src_geometry.nt[1]) wavelet[1, 1:1+length(q)-1] = q wavelet[2, 41:41+length(q)-1] = q wavelet[3, 121:121+length(q)-1] = q wavelet[4, 201:201+length(q)-1] = q ``` Finally, we create our simultaneous source as a `judiVector`: ```julia # Source wavelet q = judiVector(src_geometry, wavelet) ``` ## Computational simultaneous sources (super shots) The computational simultaneous sources refer to superposition of sequentially-fired sources and shot records from the field. These computational simultaneous shot records are not acquired in the field simultaneously, but computational simultaneous sources introduce randomness to the optimization problems like FWI and LS-RTM, which takes advantage of the knowledge in randomized linear algebra to make optimization faster and more robust. The implementation of computational simultaneous sources follows the journal article [Fast randomized full-waveform inversion with compressive sensing](https://slim.gatech.edu/content/fast-randomized-full-waveform-inversion-compressive-sensing) The simultaneous sources experiments are generated by superposition of shot records with random weights drawn from Gaussian distribution. ```julia # assume dobs is generated by sequentially fired point sources q nsimsrc = 8 # Set up random weights weights = randn(Float32,nsimsrc,q.nsrc) # Create SimSource q_sim = weights * q data_sim = weights * dobs # We can also apply the weights to the operator and check the equivalence d_sim = (weights * F) * q_sim isapprox(data_sim, d_sim) ``` ## Working with wavefields JUDI allows computing full time domain wavefields and using them as right-hand sides for wave equations solves. This tutorial shows how. We start by setting up a basic 2D experiment: ```julia using JUDI # Grid n = (120, 100) # (x,z) d = (10., 10.) o = (0., 0.) # Velocity [km/s] v = ones(Float32, n) .* 1.4f0 v[:, 50:end] .= 5f0 # Squared slowness m = (1f0 ./ v).^2 # Model structure: model = Model(n, d, o, m) ``` Next, we set up the source geometry for a single source experiment: ```julia # Set up source geometry nsrc = 1 # no. of sources xsrc = convertToCell([600f0]) ysrc = convertToCell([0f0]) zsrc = convertToCell([20f0]) # Modeling time and sampling interval time = 600f0 # ms dt = 4f0 # ms # Set up source structure src_geometry = Geometry(xsrc, ysrc, zsrc; dt=dt, t=time) # Source wavelet f0 = 0.01f0 # kHz wavelet = ricker_wavelet(time, dt, f0) q = judiVector(src_geometry, wavelet) ``` As in the 2D quick start tutorial, we create our modeling operator and source projection operator: ```julia # Setup operators A_inv = judiModeling(model) Ps = judiProjection(src_geometry) ``` To model a wavefield, we simply omit the receiver sampling operator: ```julia u = A_inv*Ps'*q ``` This return an abstract data vector called `judiWavefield`. Similar to `judiVectors`, we can access the data for each source number `i` via `u.data[i]`. The data is a 3D array of size `(nt, nx, nz)` for 2D and a 4D array of size `(nt, nx, ny, nz)` for 3D. We can plot the wavefield of the 600th time step with: ```julia using PyPlot imshow(u.data[1][600, :, :]', vmin=-5, vmax=5, cmap="seismic", aspect="auto") ``` We can also use the computed wavefield `u` as a right-hand side for forward and adjoint wave equation solves: ```julia v = A_inv*u w = A_inv'*u ``` Similarly, by setting up a receiver projection operator, we can use wavefields as right-hand sides, but restrict the output to the receiver locations. ## Extended source modeling JUDI supports extened source modeling, which injects a 1D wavelet `q` at every point in the subsurface weighted by a spatially varying extended source. To demonstrate extended source modeling, we first set up a runnable 2D experiment with JUDI. We start with defining the model: ```julia using JUDI # Grid n = (120, 100) # (x,z) d = (10., 10.) o = (0., 0.) # Velocity [km/s] v = ones(Float32, n) .* 1.4f0 v[:, 50:end] .= 5f0 # Squared slowness m = (1f0 ./ v).^2 # Model structure: model = Model(n, d, o, m) ``` Next, we set up the receiver geometry: ```julia # Number of experiments nsrc = 2 # Set up receiver geometry nxrec = 120 xrec = range(50f0, stop=1150f0, length=nxrec) yrec = 0f0 zrec = range(50f0, stop=50f0, length=nxrec) # Modeling time and receiver sampling interval time = 2000 dt = 4 # Set up receiver structure rec_geometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc) ``` For the extended source, we do not need to set up a source geometry object, but we need to define a wavelet function: ```julia # Source wavelet f0 = 0.01f0 # MHz wavelet = ricker_wavelet(time, dt, f0) ``` As before, we set up a modeling operator and a receiver sampling operator: ```julia # Setup operators A_inv = judiModeling(model) Pr = judiProjection(rec_geometry) ``` We define our extended source as a so called `judiWeights` vector. Similar to a `judiVector`, the data of this abstract vector is stored as a cell array, where each cell corresponds to one source experiment. We create a cell array of length two and create a random array of the size of the model as our extended source: ```julia weights = Array{Array}(undef, nsrc) for j=1:nsrc weights[j] = randn(Float32, model.n) end w = judiWeights(weights) ``` To inject the extended source into the model and weight it by the wavelet, we create a special projection operator called `judiLRWF` (for JUDI low-rank wavefield). This operator needs to know the wavelet we defined earlier. We can then create our full modeling operator, by combining `Pw` with `A_inv` and the receiver sampling operator: ```julia # Create operator for injecting the weights, multiplied by the provided wavelet(s) Pw = judiLRWF(wavelet) # Model observed data w/ extended source F = Pr*A_inv*adjoint(Pw) ``` Extended source modeling supports both forward and adjoint modeling: ```julia # Simultaneous observed data d_sim = F*w dw = adjoint(F)*d_sim ``` As for regular modeling, we can create a Jacobian for linearized modeling and migration. First we define a migration velocity model and the corresponding modeling operator `A0_inv`: ```julia # Migration velocity and squared slowness v0 = ones(Float32, n) .* 1.4f0 m0 = (1f0 ./ v0).^2 # Model structure and modeling operator for migration velocity model0 = Model(n, d, o, m0) A0_inv = judiModeling(model0) # Jacobian and RTM J = judiJacobian(Pr*A0_inv*adjoint(Pw), w) rtm = adjoint(J)*d_sim ``` As before, we can plot the image after reshaping it into its original dimensions: ```julia rtm = reshape(rtm, model.n) imshow(rtm', cmap="gray", vmin=-3e6, vmax=3e6) ``` Please also refer to the reproducable example on github for [2D](https://github.com/slimgroup/JUDI.jl/blob/master/examples/scripts/modeling_extended_source_2D.jl) and [3D](https://github.com/slimgroup/JUDI.jl/blob/master/examples/scripts/modeling_extended_source_3D.jl) extended modeling. ## Impedance imaging (inverse scattering) JUDI supports imaging (RTM) and demigration (linearized modeling) using the linearized inverse scattering imaging condition (ISIC) and its corresponding adjoint. ISIC can be enabled via the `Options` class. You can set this options when you initially create the modeling operator: ```julia # Options strucuture opt = Options(isic=true) # Set up modeling operator A0_inv = judiModeling(model0; options=opt) ``` When you create a Jacobian from a forward modeling operator, the Jacobian inherits the options from `A0_inv`: ```julia J = judiJacobian(Pr*A0_inv*Ps', q) J.options.isic # -> true ``` Alternatively, you can directly set the option in your Jacobian: ```julia J.options.isic = true # enable isic J.options.isic = false # disable isic ``` ## Optimal checkpointing JUDI supports optimal checkpointing via Devito's interface to the Revolve library. To enable checkpointing, use the `Options` class: ```julia # Options strucuture opt = Options(optimal_checkpointing=true) # Set up modeling operator A0_inv = judiModeling(model0; options=opt) ``` When you create a Jacobian from a forward modeling operator, the Jacobian inherits the options from `A0_inv`: ```julia J = judiJacobian(Pr*A0_inv*Ps', q) J.options.optimal_checkpointing # -> true ``` Alternatively, you can directly set the option in your Jacobian: ``` J.options.optimal_checkpointing = true # enable checkpointing J.options.optimal_checkpointing = false # disable checkpointing ``` ## On-the-fly Fourier transforms JUDI supports seismic imaging in the frequency domain using on-the-fly discrete Fourier transforms (DFTs). To compute an RTM image in the frequency domain for a given set of frequencies, we first create a cell array for the frequencies of each source experiment: ```julia nsrc = 4 # assume 4 source experiments frequencies = Array{Any}(undef, nsrc) ``` Now we can define single or multiple frequencies for each shot location for which the RTM image will be computed: ```julia # For every source location, compute RTM image for 10 and 20 Hz for j=1:nsrc frequencies[j] = [0.001, 0.002] end ``` The frequencies are passed to the Jacobian via the options field. Assuming we already have a Jacobian set up, we set the frequencies via: ```julia J.options.frequencies = frequencies ``` Instead of the same two frequencies for each source experiment, we could have chosen different random sets of frequencies, which creates an RTM with incoherent noise. We can also draw random frequencies using the frequency spectrum of the true source as the probability density function. To create a distribution for a given source `q` (`judiVector`) from which we can draw frequency samples, use: ```julia q_dist = generate_distribution(q) ``` Then we can assigne a random set of frequencies in a specified range as follows: ```julia nfreq = 10 # no. of frequencies per source location for j=1:nsrc J.options.frequencies[j] = select_frequencies(q_dist; fmin=0.003, fmax=0.04, nf=nfreq) end ``` Once the `options.frequencies` field is set, on-the-fly DFTs are used for both born modeling and RTM. To save computational cost, we can limit the number of DFTs that are performed. Rather than computing the DFT at every time step, we can define a subsampling factor as follows: ```julia # Compute DFT every 4 time steps J.options.dft_subsampling_factor=4 ```
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
2530
# Data structures ```@contents Pages = ["data_structures.md"] ``` ## Physical Parameter Data structure for physical parameter array in JUDI. A `PhysicalParameter` inherits from julia `AbstractVector` ```@docs PhysicalParameter ``` Unless specified otherwise with the `return_array` option in [`Options`](@ref), the result of a migration/FWIgradient([`judiJacobian`](@ref), [`fwi_objective`](@ref), [`lsrtm_objective`](@ref)) will be wrapped into a `PhysicalParameter`. THis allow better handling of different model parts and a better representation of the dimensional array. ## Model structure Data structure for velocity models in JUDI. ```@docs Model ``` Accessible fields include all of the above parameters `p.n, p.d, p.o, p.data`. Additionaly, arithmetic operation are all impemented such as addition, multiplication, broadcasting and indexing. Linear algebra operation are implemented as well but will return a standard Julia vector if the matrix used is external to JUDI. **Access fields:** Accessible fields include all of the above parameters, which can be accessed as follows: ```julia # Access model model.m # Access number of grid points model.n ``` ## Geometry structure JUDI's geometry structure contains the information of either the source **or** the receiver geometry. Construct an (in-core) geometry object for **either** a source or receiver set up: ```@docs Geometry ``` From the optional arguments, you have to pass (at least) **two** of `dt`, `nt` and `t`. The third value is automatically determined and set from the two other values. a `Geometry` can be constructed in a number of different ways for in-core and out-of-core cases. Check our examples and the source for additional details while the documentation is being extended. **Access fields:** Accessible fields include all of the above parameters, which can be accessed as follows: ```julia # Access cell arrays of x coordinates: geometry.xloc # Access x coordinates of the i-th source location geometry.xloc[i] # Access j-th receiver location (in x) of the i-th source location geometry.xloc[i][j] ``` ### Geometry utilities A few utilities to manipulates geometries are provided as well. ```@docs super_shot_geometry reciprocal_geom ``` ## Options structure The options structure allows setting several modeling parameters. ```@docs Options ``` **notes** `Option` has been renamed `JUDIOptions` as of JUDI version `4.0` to avoid potential (and exisiting) conflicts wiht other packages exporting an Options structure.
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
2659
# Helper functions JUDI provides numerous helper and utility functions need for seismic modeling and inversion. ```@contents Pages = ["helper.md"] ``` ## Ricker wavelet Create a 1D Ricker wavelet: ```@docs ricker_wavelet(tmax, dt, f0; t0=nothing) ``` ## Compute CFL time stepping interval Calculate the time stepping interval based on the CFL condition ```@dcs calculate_dt ``` ## Compute number of computational time steps Estimate the number of computational time steps. Required for calculating the dimensions of the matrix-free linear modeling operators: ```@docs get_computational_nt ``` ## Set up 3D acquisition grid Helper function to create a regular acquisition grid for a 3D survey. ```julia setup_3D_grid ``` ## Data interpolation Time interpolation for source/receiver data using splines. For modeling, the data is interpolated automatically onto the computational time axis, so generally, these functions are not needed for users. ```@docs time_resample ``` ## Generate and sample from frequency distribution Create a probability distribution with the shape of the source spectrum from which we can draw random frequencies. ```@docs generate_distribution select_frequencies ``` We can draw random samples from `dist` by passing it values between 0 and 1: ```julia # Draw a single random frequency f = dist(rand(1)) # Draw 10 random frequencies f = dist(rand(10)) ``` Alternatively, we can use the function: ```julia f = select_frequencies(dist; fmin=0f0, fmax=Inf, nf=1) ``` to draw `nf` number of frequencies for a given distribution `dist` in the frequency range of `fmin` to `fmax` (both in kHz). ## Read data from out of core container In the case where a `judiVector` is out of core (points to a segy file) it is possible to convert it or part of it into an in core `judiVecor` with the `get_data` function. ```julia d_ic = get_data(d_ooc, inds) ``` where `inds` is either a single index, a list of index or a range of index. ## Restrict model to acquisition In practice, and in particular for marine data, the aperture of a single shot is much smaller than the full model size. We provide a function (automatically used when the option `limit_m` is set in [`Options`](@ref)) that limits the model to the acquisition area. ```@docs limit_model_to_receiver_area ``` We also provide it's complement that removes receivers outside of the computational domain if the dataset contains locations that are not wanted ```@docs remove_out_of_bounds_receivers ``` ## Additional miscellanous utilities ```@docs devito_model setup_grid remove_padding convertToCell process_input_data reshape transducer as_vec ```
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
1642
# The Julia Devito Inversion framework (JUDI.jl) JUDI is a framework for large-scale seismic modeling and inversion and designed to enable rapid translations of algorithms to fast and efficient code that scales to industry-size 3D problems. Wave equations in JUDI are solved with [Devito](https://www.devitoproject.org/), a Python domain-specific language for automated finite-difference (FD) computations. ## Docs overview This documentation provides an overview over JUDI's basic data structures and abstract operators: * [Installation](@ref): Install guidlines for JUDI and compilers. * [Getting Started](@ref): A few simple guided examples to get familiar with JUDI. * [Data structures](@ref): Explains the `Model`, `Geometry` and `Options` data structures and how to set up acquisition geometries. * [Abstract Vectors](@ref): Documents JUDI's abstract vector classes `judiVector`, `judiWavefield`, `judiRHS`, `judiWeights` and `judiExtendedSource`. * [Linear Operators](@ref): Lists and explains JUDI's abstract linear operators `judiModeling`, `judiJacobian`, `judiProjection` and `judiLRWF`. * [Input/Output](@ref): Read SEG-Y data and set up `judiVectors` for shot records and sources. Read velocity models. * [Helper functions](@ref): API of functions that make your life easier. * [Seismic Inversion](@ref): Inversion utility functions to avoid recomputation and memry overhead. * [Seismic Preconditioners](@ref): Basic preconditioners for seismic imaging. * [pysource package](@ref): API reference for the propagators implementation with Devito in python. The API is the backend of JUDI handled with PyCall.
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
6751
# Installation JUDI is a linear algebra abstraction built on top of [Devito](https://github.com/devitocodes/devito). Because [Devito](https://github.com/devitocodes/devito) is a just-in-time compiler, you will need to have a standard C compiler installed. by default most system come with a gcc compiler (except Windows where we recommend to use docker or WSL) which unfortunately isnt' very reliable. It is therefore recommended to install a proper compiler (gcc>=7, icc). For GPU offloading, you will then need to install a proper offloading compiler such as Nvidia's nvc or the latest version of clang (*not Apple clang*). ## Standard installation JUDI is registered and can be installed directly in julia REPL ```julia ] add JUDI ``` This will install JUDI, and the `build` will install the necessary dependencies including [Devito](https://github.com/devitocodes/devito). ## Custom installation In some case you may want to have your own installation of Devito you want JUDI to use in which case you should foloow these steps. You can find installation instruction in our Wiki at [Installation](https://github.com/slimgroup/JUDI.jl/wiki/Installation). JUDI is a registered package and can therefore be easily installed from the General registry with `]add/dev JUDI` ## GPU JUDI supports the computation of the wave equation on GPU via [Devito](https://www.devitoproject.org)'s GPU offloading support. **NOTE**: Only the wave equation part will be computed on GPU, the julia arrays will still be CPU arrays and `CUDA.jl` is not supported. ### Compiler installation To enable gpu support in JUDI, you will need to install one of [Devito](https://www.devitoproject.org)'s supported offloading compilers. We strongly recommend checking the [Wiki](https://github.com/devitocodes/devito/wiki) for installation steps and to reach out to the Devito community for GPU compiler related issues. - [x] `nvc/pgcc`. This is recommended and the simplest installation. You can install the compiler following Nvidia's installation instruction at [HPC-sdk](https://developer.nvidia.com/hpc-sdk) - [ ] `aompcc`. This is the AMD compiler that is necessary for running on AMD GPUs. This installation is not tested with JUDI and we recommend to reach out to Devito's team for installation guidelines. - [ ] `openmp5/clang`. This installation requires the compilation from source `openmp`, `clang` and `llvm` to install the latest version of `openmp5` enabling gpu offloading. You can find instructions on this installation in Devito's [Wiki](https://github.com/devitocodes/devito/wiki) ### Setup The only required setup for GPU support are the environment variables for [Devito](https://www.devitoproject.org). For the currently supported `nvc+openacc` setup these are: ``` export DEVITO_LANGUAGE=openacc export DEVITO_ARCH=nvc export DEVITO_PLATFORM=nvidiaX ``` ## Running with Docker If you do not want to install JUDI, you can run [JUDI](https://github.com/slimgroup/JUDI.jl) as a [docker image](https://hub.docker.com/repository/docker/mloubout/judi). The first possibility is to run the docker container as a Jupyter notebook. [JUDI](https://github.com/slimgroup/JUDI.jl) provides two docker images for the latest [JUDI](https://github.com/slimgroup/JUDI.jl) release for Julia versions `1.6` (LTS) and `1.7` (latest stable version). The images names are `mloubout/judi:JVER-latest` where `JVER` is the Julia version. This docker images contain pre-installed compilers for CPUs (gcc-10) and Nvidia GPUs (nvc) via the nvidia HPC sdk. The environment is automatically set for [Devito] based on the hardware available. **Note**: If you wish to use your gpu, you will need to install [nvidia-docker](https://docs.nvidia.com/ai-enterprise/deployment-guide/dg-docker.html) and run `docker run --gpus all` in order to make the GPUs available at runtime from within the image. To run [JUDI](https://github.com/slimgroup/JUDI.jl) via docker execute the following command in your terminal: ```bash docker run -p 8888:8888 mloubout/judi:1.7-latest ``` This command downloads the image and launches a container. You will see a link that you can copy-paste to your browser to access the notebooks. Alternatively, you can run a bash session, in which you can start a regular interactive Julia session and run the example scripts. Download/start the container as a bash session with: ```bash docker run -it mloubout/judi:1.7-latest /bin/bash ``` Inside the container, all examples are located in the directory `/app/judi/examples/scripts`. **Previous versions**: As of version `v2.6.7` of JUDI, we also ship version-tagged images as `mloubout/judi:JVER-ver` where `ver` is the version of [JUDI](https://github.com/slimgroup/JUDI.jl) wanted, for example the current [JUDI](https://github.com/slimgroup/JUDI.jl) version with Julia 1.7 is `mloubout/judi:1.7-v2.6.7` **Development version**: Additionally, we provide two images corresponding to the latest development version of [JUDI](https://github.com/slimgroup/JUDI.jl) (latest state of the master branch). These images are called `mloubout/judi:JVER-dev` and can be used in a similar way. ## Testing A complete test suite is included with JUDI and is tested via GitHub Actions. You can also run the test locally via: ```julia julia --project -e 'using Pkg;Pkg.test(coverage=false)' ``` By default, only the JUDI base API will be tested, however the testing suite supports other modes controlled via the environemnt variable `GROUP` such as: ```julia GROUP=JUDI julia --project -e 'using Pkg;Pkg.test(coverage=false)' ``` The supported modes are: - JUDI : Only the base API (linear operators, vectors, ...) - ISO_OP : Isotropic acoustic operators - ISO_OP_FS : Isotropic acoustic operators with free surface - TTI_OP : Transverse tilted isotropic operators - TTI_OP_FS : Transverse tilted isotropic operators with free surface - filename : you can also provide just a filename (i.e `GROUP=test_judiVector.jl`) and only this one test file will be run. Single files with TTI or free surface are not currently supported as it relies on `Base.ARGS` for the setup. ## Configure compiler and OpenMP Devito uses just-in-time compilation for the underlying wave equation solves. The default compiler is intel, but can be changed to any other specified compiler such as `gnu`. Either run the following command from the command line or add it to your ~/.bashrc file: ``` export DEVITO_ARCH=gnu ``` Devito uses shared memory OpenMP parallelism for solving PDEs. OpenMP is disabled by default, but you can enable OpenMP and define the number of threads (per PDE solve) as follows: ``` export DEVITO_LANGUAGE=openmp # Enable OpenMP. export OMP_NUM_THREADS=4 # Number of OpenMP threads ```
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
8908
# Seismic Inversion ```@contents Pages = ["inversion.md"] ``` ## Introduction We currently introduced the linear operators that allow to write seismic modeling and inversion in a high-level, linear algebra way. These linear operator allow the script to closely follow the mathematics and to be readable and understandable. However, these come with overhead. In particular, consider the following compuation on the FWI gradient: ```julia d_syn = F*q r = judiJacobian(F, q)' * (d_syn - d_obs) ``` In this two lines, the forward modeling is performed twice: once to compute `d_syn` then once again to compute the Jacobian adjoint. In order to avoid this overhead for practical inversion, we provide utility function that directly comput the gradient and objective function (L2- misfit) of FWI, LSRTM and TWRI with minimum overhead. ## FWI ```@docs fwi_objective ``` ### Example JUDI is designed to let you set up objective functions that can be passed to standard packages for (gradient-based) optimization. The following example demonstrates how to perform FWI on the 2D Overthrust model using a spectral projected gradient algorithm from the minConf library, which is included in the software. A small test dataset (62 MB) and the model can be downloaded from this FTP server: ```julia run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_2D.segy`) run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_2D_initial_model.h5`) ``` The first step is to load the velocity model and the observed data into Julia, as well as setting up bound constraints for the inversion, which prevent too high or low velocities in the final result. Furthermore, we define an 8 Hertz Ricker wavelet as the source function: ```julia using PyPlot, HDF5, SegyIO, JUDI, SlimOptim, Statistics, Random # Load starting model n, d, o, m0 = read(h5open("overthrust_2D_initial_model.h5", "r"), "n", "d", "o", "m0") model0 = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0) # need n, d, o as tuples and m0 as array # Bound constraints vmin = ones(Float32, model0.n) .+ 0.3f0 vmax = ones(Float32, model0.n) .+ 5.5f0 mmin = vec((1f0 ./ vmax).^2) # convert to slowness squared [s^2/km^2] mmax = vec((1f0 ./ vmin).^2) # Load segy data block = segy_read("overthrust_2D.segy") dobs = judiVector(block) # Set up wavelet src_geometry = Geometry(block; key="source", segy_depth_key="SourceDepth") # read source position geometry wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.008f0) # 8 Hz wavelet q = judiVector(src_geometry, wavelet) ``` For this FWI example, we define an objective function that can be passed to the minConf optimization library, which is included in the Julia Devito software package. We allow a maximum of 20 function evaluations using a spectral-projected gradient (SPG) algorithm. To save computational cost, each function evaluation uses a randomized subset of 20 shot records, instead of all 97 shots: ```julia # Optimization parameters fevals = 20 # number of function evaluations batchsize = 20 # number of sources per iteration fvals = zeros(21) opt = Options(optimal_checkpointing = false) # set to true to enable checkpointing # Objective function for minConf library count = 0 function objective_function(x) model0.m = reshape(x, model0.n); # fwi function value and gradient i = randperm(dobs.nsrc)[1:batchsize] fval, grad = fwi_objective(model0, q[i], dobs[i]; options=opt) grad = reshape(grad, model0.n); grad[:, 1:21] .= 0f0 # reset gradient in water column to 0. grad = .1f0*grad/maximum(abs.(grad)) # scale gradient for line search global count; count += 1; fvals[count] = fval return fval, vec(grad.data) end # FWI with SPG ProjBound(x) = median([mmin x mmax], dims=2) # Bound projection options = spg_options(verbose=3, maxIter=fevals, memory=3) res = spg(objective_function, vec(m0), ProjBound, options) ``` This example script can be run in parallel and requires roughly 220 MB of memory per source location. Execute the following code to generate figures of the initial model and the result, as well as the function values: ```julia figure(); imshow(sqrt.(1. /adjoint(m0))); title("Initial model") figure(); imshow(sqrt.(1. /adjoint(reshape(x, model0.n)))); title("FWI") figure(); plot(fvals); title("Function value") ``` ![fwi](./figures/fwi.png) ## LSRTM ```@docs lsrtm_objective ``` ### Example JUDI includes matrix-free linear operators for modeling and linearized (Born) modeling, that let you write algorithms for migration that follow the mathematical notation of standard least squares problems. This example demonstrates how to use Julia Devito to perform least-squares reverse-time migration on the 2D Marmousi model. Start by downloading the test data set (1.1 GB) and the model: ```julia run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_2D.segy`) run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_migration_velocity.h5`) ``` Once again, load the starting model and the data and set up the source wavelet. For this example, we use a Ricker wavelet with 30 Hertz peak frequency. ```julia using PyPlot, HDF5, JUDI, SegyIO, Random # Load smooth migration velocity model n,d,o,m0 = read(h5open("marmousi_migration_velocity.h5","r"), "n", "d", "o", "m0") model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0) # Load data block = segy_read("marmousi_2D.segy") dD = judiVector(block) # Set up wavelet src_geometry = Geometry(block; key="source", segy_depth_key="SourceDepth") wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.03) # 30 Hz wavelet q = judiVector(src_geometry,wavelet) # Set up info structure ntComp = get_computational_nt(q.geometry,dD.geometry,model0) # no. of computational time steps info = Info(prod(model0.n),dD.nsrc,ntComp) ``` To speed up the convergence of our imaging example, we set up a basic preconditioner for each the model- and the data space, consisting of mutes to suppress the ocean-bottom reflection in the data and the source/receiver imprint in the image. The operator `J` represents the linearized modeling operator and its adjoint `J'` corresponds to the migration (RTM) operator. The forward and adjoint pair can be used for a basic LS-RTM example with (stochastic) gradient descent: ```julia # Set up matrix-free linear operators opt = Options(optimal_checkpointing = true) # set to false to disable optimal checkpointing F = judiModeling(model0, q.geometry, dD.geometry; options=opt) J = judiJacobian(F, q) # Right-hand preconditioners (model topmute) Mr = judiTopmute(model0; taperwidth=10) # mute up to grid point 52, with 10 point taper # Left-hand side preconditioners Ml = judiDatMute(q.geometry, dD.geometry; t0=.120) # data topmute starting at time 120ms # Stochastic gradient x = zeros(Float32, info.n) # zero initial guess batchsize = 10 # use subset of 10 shots per iteration niter = 32 fval = zeros(Float32, niter) for j=1:niter println("Iteration: ", j) # Select batch and set up left-hand preconditioner i = randperm(dD.nsrc)[1:batchsize] # Compute residual and gradient r = Ml[i]*J[i]*Mr*x - Ml[i]*dD[i] g = adjoint(Mr)*adjoint(J[i])*adjoint(Ml[i])*r # Step size and update variable fval[j] = .5f0*norm(r)^2 t = norm(r)^2/norm(g)^2 global x -= t*g end ``` ![lsrtm](./figures/lsrtm.png) ## TWRI ```@docs twri_objective ``` and related TWRI options ```@docs TWRIOptions ``` ## Machine Learning [ChainRules.jl](https://github.com/JuliaDiff/ChainRules.jl) allows integrating JUDI modeling operators into convolutional neural networks for deep learning. For example, the following code snippet shows how to create a shallow CNN consisting of two convolutional layers with a nonlinear forward modeling layer in-between them. The integration of ChainRules and JUDI enables backpropagation through Flux' automatic differentiation tool, but calls the corresponding adjoint JUDI operators under the hood. For more details, please check out [this tutorial](https://github.com/slimgroup/JUDI.jl/blob/master/examples/notebooks/06_automatic_differentiation.ipynb). ```julia # Jacobian W1 = judiJacobian(F0, q) b1 = randn(Float32, num_samples) # Fully connected layer W2 = randn(Float32, n_out, num_samples) b2 = randn(Float32, n_out) # Network and loss network(x) = W2*(W1*x .+ b1) .+ b2 loss(x, y) = Flux.mse(network(x), y) # Compute gradient w/ Flux p = params(x, y, W1, b1, b2) gs = Tracker.gradient(() -> loss(x, y), p) gs[x] # gradient w.r.t. to x ``` Integration with ChainRules allows implementing physics-augmented neural networks for seismic inversion, such as loop-unrolled seismic imaging algorithms. For example, the following results are a conventional RTM image, an LS-RTM image and a loop-unrolled LS-RTM image for a single simultaneous shot record. ![flux](./figures/figure1.png)
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
4770
# Input/Output For reading and writing SEG-Y data, JUDI uses the [SegyIO.jl](https://github.com/slimgroup/SegyIO.jl) package. JUDI supports reading SEG-Y from disk into memory, as well as working with out-of-core (OOC) data containers. In the latter case, `judiVectors` contain look-up tables that allow accessing the underlying data in constant time. ## Reading SEG-Y files into memory To read a single SEG-Y file into memory, use the `segy_read` function: ```julia using SegyIO block = segy_read("data.segy") ``` From a `SegyIO` data block, you can create an in-core `judiVector`, as well as a `Geometry` object for the source: ``` # judiVector for observed data d_obs = judiVector(block; segy_depth_key="RecGroupElevation") # Source geometry src_geometry = Geometry(block; key="source", segy_depth_key="SourceDepth") ``` The optional keyword `segy_depth_key` specifies which SEG-Y header stores the depth coordinate. After reading a `block`, you can check `block.traceheaders` to see which trace headers are set and where to find the depth coordinates for sources or receivers. The `d_obs` vector constains the receiver geometry in `d_obs.geometry`, so there is no need to set up a separate geometry object manually. However, in principle we can set up a receiver `Geometry` object as follows: ``` rec_geometry = Geometry(block; key="receiver", segy_depth_key="RecGroupElevation") ``` ## Writing SEG-Y files To write a `judiVector` as a SEG-Y file, we need a `judiVector` containing the receiver data and geometry, as well as a `judiVector` with the source coordinates. From the `judiVectors`, we first create a `SegyIO` block: ```julia block = judiVector_to_SeisBlock(d_obs, q) ``` where `d_obs` and `q` are `judiVectors` for receiver and source data respectively. To save only the source `q`, we can do ```julia block = src_to_SeisBlock(q) ``` Next, we can write a SEG-Y file from a `SegyIO block`: ```julia segy_write("new_file.segy", block) # writes a SEG-Y file called new_file.segy ``` ## Reading out-of-core SEG-Y files For SEG-Y files that do not fit into memory, JUDI provides the possibility to work with OOC data containers. First, `SegyIO` scans also available files and then creates a lookup table, including a summary of the most important SEG-Y header values. See `SegyIO's` [documentation](https://github.com/slimgroup/SegyIO.jl/wiki/Scanning) for more information. First we provide the path to the directory that we want to scan, as well as a string that appears in all the files we want to scan. For example, here we want to scan all files that contain the string `"bp_observed_data"`. The third argument is a list of SEG-Y headers for which we create a summary. For creating OOC `judiVectors`, **always** include the `"GroupX"`, `"GroupY"` and `"dt"` keyworkds, as well as the keywords that carry the source and receiver depth coordinates: ```julia # Specify direcotry to scan path_to_data = "/home/username/data_directory/" # Scan files in given directory and create OOC data container container = segy_scan(path_to_data, "bp_observed_data", ["GroupX", "GroupY", "RecGroupElevation", "SourceDepth", "dt"]) ``` Depending of the number and size of the underlying files, this process can take multiple hours, but it only has to be executed once! Furthermore, [parallel scanning](https://github.com/slimgroup/SegyIO.jl/wiki/Scanning) is supported as well. Once we have scanned all files in the directory, we can create an OOC `judiVector` and source `Geometry` object as follows: ```julia # Create OOC judiVector d_obs = judiVector(container; segy_depth_key="RecGroupElevation") # Create OOC source geometry object src_geometry = Geometry(container; key="source", segy_depth_key="SourceDepth") ``` ## Reading and writing velocity models JUDI does not require velocity models to be read or saved in any specific format. Any file format that allows reading the velocity model as a two or three-dimensional Julia array will work. In our examples, we often use the [JLD](https://github.com/JuliaIO/JLD.jl) or [HDF5](https://github.com/JuliaIO/HDF5.jl) packages to read/write velocity models and the corresponing meta data (i.e. grid spacings and origins). If your model is a SEG-Y file, use the `segy_read` function from `SegyIO` as shown above. * Create an example model to write and read: ```julia n = (120, 100) d = (10.0, 10.0) o = (0.0, 0.0) v = ones(Float32, n) .* 1.5f0 m = 1f0 ./ v.^2 ``` * Write a model as a `.jld` file: ```julia using JLD save("my_model.jld", "n", n, "d", d, "o", o, "m", m) ``` * Read a model from a `.jld` file: ```julia # Returns a Julia dictionary M = load("my_model.jld") n = M["n"] d = M["d"] o = M["o"] m = M["m"] # Set up a Model object model = Model(n, d, o, m) ```
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
4544
# Linear Operators JUDI is building on [JOLI.jl](https://github.com/slimgroup/JOLI.jl) to implement matrix-free linear operators. These operators represent the discretized wave-equations and sensitivit (Jacobian) for different acquisition schemes. ```@contents Pages = ["linear_operators.md"] ``` ## judiModeling Seismic modeling operator for solving a wave equation for a given right-hand-side. ```@docs judiModeling{DDT, RDT} ``` **Construction:** * Construct a modeling operator **without** source/receiver projections: ```julia F = judiModeling(model; options=opt) ``` * Construct a modeling operator **with** source/receiver projections: ```julia F = judiModeling(model, src_geometry, rec_geometry) ``` * Construct a modeling operator from an **existing** operator without geometries and projection operators: ```julia F = Pr*F*Ps' ``` where `Ps` and `Pr` are source/receiver projection operators of type `judiProjection`. * Construct a modeling operator for **extended source modeling**: ```julia F = Pr*F*Pw' ``` where `Pw` is a `judiLRWF` (low-rank-wavefield) projection operator. **Accessible fields:** ```julia # Model structure F.model # Source injection (if available) and geometry F.qInjection F.qInjection.geometry # Receiver interpolation (if available) and geometry F.rInterpolation F.rInterpolation.geometry # Options structure F.options ``` **Usage:** ```julia # Forward modeling (F w/ geometries) d_obs = F*q # Adjoint modeling (F w/ geometries) q_ad = F'*d_obs # Forward modeling (F w/o geometries) d_obs = Pr*F*Ps'*q # Adjoint modelng (F w/o geometries) q_ad = Ps*F'*Pr'*d_obs # Extended source modeling (F w/o geometries) d_obs = Pr*F*Pw'*w # Adjoint extended source modeling (F w/o geometries) w_ad = Pw*F'*Pr'*d_obs # Forward modeling and return full wavefield (F w/o geometries) u = F*Ps'*q # Adjoint modelnig and return wavefield (F w/o geometries) v = F'*Pr'*d_obs # Forward modeling with full wavefield as source (F w/o geometries) d_obs = Pr*F*u # Adjoint modeling with full wavefield as source (F w/o geometries) q_ad = Ps*F*v ``` ## judiJacobian Jacobian of a non-linear forward modeling operator. Corresponds to linearized Born modeling (forward mode) and reverse-time migration (adjoint mode). ```@docs judiJacobian ``` **Construction:** * A `judiJacobian` operator can be create from an exisiting forward modeling operator and a source vector: ```julia J = judiJacobian(F, q) # F w/ geometries ``` ```julia J = judiJacobian(Pr*F*Ps', q) # F w/o geometries ``` where `Ps` and `Pr` are source/receiver projection operators of type `judiProjection`. * A Jacobian can also be created for an extended source modeling operator: ```julia J = judiJacobian(Pr*F*Pw', w) ``` where `Pw` is a `judiLRWF` operator and `w` is a `judiWeights` vector (or 2D/3D Julia array). **Accessible fields::** ```julia # Model structure J.model # Underlying propagator J.F # Source injection (if available) and geometry throughpropagator J.F.qInjection J.F.qInjection.geometry # Receiver interpolation (if available) and geometry through propagator J.F.rInterpolation J.F.rInterpolation.geometry # Source term, can be a judiWeights, judiWavefield, or a judiVector J.q # Options structure J.options ``` **Usage:** ```julia # Linearized modeilng d_lin = J*dm # RTM rtm = J'*d_lin # Matrix-free normal operator H = J'*J ``` ## judiProjection Abstract linear operator for source/receiver projections. A (transposed) `judiProjection` operator symbolically injects the data with which it is multiplied during modeling. If multiplied with a forward modeling operator, it samples the wavefield at the specified source/receiver locations. ```@docs judiProjection ``` **Accessible fields:** ```julia # Source/receiver geometry P.geometry ``` **Usage:** ```julia # Multiply with judiVector to create a judiRHS rhs1 = Pr'*d_obs rhs2 = Ps'*q # Sample wavefield at source/receiver location during modeling d_obs = Pr*F*Ps'*q q_ad = Ps*F*Pr'*d_obs ``` ## judiLRWF Abstract linear operator for sampling a seismic wavefield as a sum over all time steps, weighted by a time-varying wavelet. Its transpose *injects* a time-varying wavelet at every grid point in the model. ```@docs judiWavelet ``` **Accessible fields:** ```julia # Wavelet of i-th source location P.wavelet[i] ``` **Usage:** ```julia # Multiply with a judiWeight vector to create a judiExtendedSource ex_src = Pw'*w # Sample wavefield as a sum over time, weighted by the source u_ex = Pw*F'*Pr'*d_obs ```
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
4826
# Seismic Preconditioners JUDI provides a selected number of preconditioners known to be beneficial to FWI and RTM. We welcome additional preconditioners from the community. Additionnaly, any JOLI operator can be used as a preconditiner in conbination with JUDI operator thanks to the fundamental interface between JUDI and JOLI. ```@contents Pages = ["preconditioners.md"] ``` ## Model domain preconditioners Model space preconditioners acts on model size arrays such as the velocity model or the FWI/RTM gradient. These preconditioners are indepenedent of the number of sources and therefore should not be indexed. ### Water column muting (top mute) Create a linear operator for a 2D model topmute, i.e. for muting the water column: ```@docs TopMute ``` **Usage:** ```julia # Forward m_mute = Mr*vec(m) # Adjoint m_mute = Mr'*vec(m) ``` As `Mr` is self adjoint, `Mr` is equal to `Mr'`. **legacy:** The legacy constructor `judiTopmute(n, wb, taperwidth)` is still available to construct a muting operator with user specified muting depth. ### Model depth scaling Create a 2D model depth scaling. This preconditionenr is the most simple form of inverse Hessain approximation compensating for illumination in the subsurface. We also describe below a more accurate diagonal approximation of the Hessian with the illlumination operator. Additionnaly, as a simple diagonal approximation, this operator is invertible and can be inverted with the standard julia `inv` function. ```@docs DepthScaling ``` **Usage:** ```julia # Forward m_mute = Mr*vec(m) # Adjoint m_mute = Mr'*vec(m) ``` ### Illumination The illumination computed the energy of the wavefield along time for each grid point. This provides a first order diagonal approximation of the Hessian of FWI/LSRTM helping the ocnvergence and quality of an update. ```@docs judiIllumination ``` **Usage:** ```julia # Forward m_mute = I*vec(m) # Adjoint m_mute = I'*vec(m) ``` ## Data preconditioners These preconditioners are design to act on the shot records (data). These preconditioners are indexable by source number so that working with a subset of shot is trivial to implement. Additionally, all [DataPreconditionner](@ref) are compatible with out-of-core JUDI objects such as `judiVector{SeisCon}` so that the preconditioner is only applied to single shot data at propagation time. ### Data topmute Create a data topmute for the data based on the source and receiver geometry (i.e based on the offsets between each souurce-receiver pair). THis operator allows two modes, `:reflection` for the standard "top-mute" direct wave muting and `:turning` for its opposite muting the reflection to compute gradients purely based on the turning waves. The muting operators uses a cosine taper at the mask limit to allow for a smooth transition. ```@docs DataMute ``` ### Band pass filter While not purely a preconditioner, because this operator acts on the data and is traditionally used fro frequency continuation in FWI, we implemented this operator as a source indexable linear operator as well. Additionally, the filtering function is available as a standalone julia function for general usage ```@docs FrequencyFilter filter_data ``` ### Data time derivative/intergraton A `TimeDifferential{K}` is a linear operator that implements a time derivative (K>0) or time integration (K<0) of order `K` for any real `K` including fractional values. ```@docs TimeDifferential ``` ## Inversion wrappers For large scale and practical cases, the inversions wrappers [fwi_objective](@ref) and [lsrtm_objective](@ref) are used to minimize the number of PDE solves. Those wrapper support the use of preconditioner as well for better results. **Usage:** For fwi, you can use the `data_precon` keyword argument to be applied to the residual (the preconditioner is applied to both the field and synthetic data to ensure better misfit): ```julia fwi_objective(model, q, dobs; data_precon=precon) ``` where `precon` can be: - A single [DataPreconditionner](@ref) - A list/tuple of [DataPreconditionner](@ref) - A product of [DataPreconditionner](@ref) Similarly, for LSRTM, you can use the `model_precon` keyword argument to be applied to the perturbation `dm` and the `data_precon` keyword argument to be applied to the residual: ```julia lsrtm_objective(model, q, dobs, dm; model_precon=dPrec, data_precon=dmPrec) ``` where `dPrec` and `dmPrec` can be: - A single preconditioner ([DataPreconditionner](@ref) for `data_precon` and [ModelPreconditionner](@ref) for `model_precon`) - A list/tuple of preconditioners ([DataPreconditionner](@ref) for `data_precon` and [ModelPreconditionner](@ref) for `model_precon`) - A product of preconditioners ([DataPreconditionner](@ref) for `data_precon` and [ModelPreconditionner](@ref) for `model_precon`)
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
32887
# pysource package ## Submodules ## FD_utils module ### FD_utils.R_mat(model) Rotation matrix according to tilt and asymut. * **Parameters** **model** (*Model*) – Model structure ### FD_utils.divs(func, so_fact=1, side=- 1) GrDivergenceadient shifted by half a grid point, only to be used in combination with grads. ### FD_utils.grads(func, so_fact=1, side=1) Gradient shifted by half a grid point, only to be used in combination with divs. ### FD_utils.laplacian(v, irho) Laplacian with density div( 1/rho grad) (u) ### FD_utils.sa_tti(u, v, model) Tensor factorized SSA TTI wave equation spatial derivatives. * **Parameters** * **u** (*TimeFunction*) – first TTI field * **v** (*TimeFunction*) – second TTI field * **model** (*Model*) – Model structure ### FD_utils.thomsen_mat(model) Diagonal Matrices with Thomsen parameters for vectorial temporaries computation. * **Parameters** **model** (*Model*) – Model structure ## checkpoint module ### _class_ checkpoint.CheckpointOperator(op, \*\*kwargs) Devito’s concrete implementation of the ABC pyrevolve.Operator. This class wraps devito.Operator so it conforms to the pyRevolve API. pyRevolve will call apply with arguments t_start and t_end. Devito calls these arguments t_s and t_e so the following dict is used to perform the translations between different names. * **Parameters** * **op** (*Operator*) – devito.Operator object that this object will wrap. * **args** (*dict*) – If devito.Operator.apply() expects any arguments, they can be provided here to be cached. Any calls to CheckpointOperator.apply() will automatically include these cached arguments in the call to the underlying devito.Operator.apply(). #### apply(t_start, t_end) If the devito operator requires some extra arguments in the call to apply they can be stored in the args property of this object so pyRevolve calls pyRevolve.Operator.apply() without caring about these extra arguments while this method passes them on correctly to devito.Operator #### t_arg_names(_ = {'t_end': 'time_M', 't_start': 'time_m'_ ) ### _class_ checkpoint.DevitoCheckpoint(objects) Devito’s concrete implementation of the Checkpoint abstract base class provided by pyRevolve. Holds a list of symbol objects that hold data. #### _property_ dtype() data type #### get_data(timestep) returns the data (wavefield) for the time-step timestep #### get_data_location(timestep) returns the data (wavefield) for the time-step timestep #### load() NotImplementedError #### save() NotImplementedError #### _property_ size() The memory consumption of the data contained in a checkpoint. ### checkpoint.get_symbol_data(symbol, timestep) Return the symbol corresponding to the data at time-step timestep ## geom_utils module ### geom_utils.src_rec(model, u, src_coords=None, rec_coords=None, wavelet=None, fw=True, nt=None) Generates the source injection and receiver interpolation. This function is fully abstracted and does not care whether this is a forward or adjoint wave-equation. The source is the source term of the equation The receiver is the measurment term Therefore, for the adjoint, this function has to be called as: src_rec(model, v, src_coords=rec_coords, …) because the data is the sources * **Parameters** * **model** (*Model*) – Physical model * **u** (*TimeFunction** or **tuple*) – Wavefield to inject into and read from * **src_coords** (*Array*) – Physical coordinates of the sources * **rec_coords** (*Array*) – Physical coordinates of the receivers * **wavelet** (*Array*) – Data for the source * **fw=True** – Whether the direction is forward or backward in time * **nt** (*int*) – Number of time steps ## interface module ### interface.J_adjoint(model, src_coords, wavelet, rec_coords, recin, space_order=8, checkpointing=False, n_checkpoints=None, t_sub=1, maxmem=None, freq_list=[], dft_sub=None, isic=False, ws=None) Jacobian (adjoint fo born modeling operator) operator on a shot record as a source (i.e data residual). Supports three modes: \* Checkpinting \* Frequency compression (on-the-fly DFT) \* Standard zero lag cross correlation over time * **Parameters** * **model** (*Model*) – Physical model * **src_coords** (*Array*) – Coordiantes of the source(s) * **wavelet** (*Array*) – Source signature * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **recin** (*Array*) – Receiver data * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **checkpointing** (*Bool*) – Whether or not to use checkpointing * **n_checkpoints** (*Int*) – Number of checkpoints for checkpointing * **maxmem** (*Float*) – Maximum memory to use for checkpointing * **freq_list** (*List*) – List of frequencies for on-the-fly DFT * **dft_sub** (*Int*) – Subsampling factor for on-the-fly DFT * **isic** (*Bool*) – Whether or not to use ISIC imaging condition * **ws** (*Array*) – Extended source spatial distribution * **Returns** Adjoint jacobian on the input data (gradient) * **Return type** Array ### interface.J_adjoint_checkpointing(model, src_coords, wavelet, rec_coords, recin, space_order=8, is_residual=False, n_checkpoints=None, born_fwd=False, maxmem=None, return_obj=False, isic=False, ws=None, t_sub=1, nlind=False) Jacobian (adjoint fo born modeling operator) operator on a shot record as a source (i.e data residual). Outputs the gradient with Checkpointing. * **Parameters** * **model** (*Model*) – Physical model * **src_coords** (*Array*) – Coordiantes of the source(s) * **wavelet** (*Array*) – Source signature * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **recin** (*Array*) – Receiver data * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **checkpointing** (*Bool*) – Whether or not to use checkpointing * **n_checkpoints** (*Int*) – Number of checkpoints for checkpointing * **maxmem** (*Float*) – Maximum memory to use for checkpointing * **isic** (*Bool*) – Whether or not to use ISIC imaging condition * **ws** (*Array*) – Extended source spatial distribution * **is_residual** (*Bool*) – Whether to treat the input as the residual or as the observed data * **born_fwd** (*Bool*) – Whether to use the forward or linearized forward modeling operator * **nlind** (*Bool*) – Whether to remove the non linear data from the input data. This option is only available in combination with born_fwd * **Returns** Adjoint jacobian on the input data (gradient) * **Return type** Array ### interface.J_adjoint_freq(model, src_coords, wavelet, rec_coords, recin, space_order=8, freq_list=[], is_residual=False, return_obj=False, nlind=False, dft_sub=None, isic=False, ws=None, t_sub=1, born_fwd=False) Jacobian (adjoint fo born modeling operator) operator on a shot record as a source (i.e data residual). Outputs the gradient with Frequency compression (on-the-fly DFT). * **Parameters** * **model** (*Model*) – Physical model * **src_coords** (*Array*) – Coordiantes of the source(s) * **wavelet** (*Array*) – Source signature * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **recin** (*Array*) – Receiver data * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **freq_list** (*List*) – List of frequencies for on-the-fly DFT * **dft_sub** (*Int*) – Subsampling factor for on-the-fly DFT * **isic** (*Bool*) – Whether or not to use ISIC imaging condition * **ws** (*Array*) – Extended source spatial distribution * **is_residual** (*Bool*) – Whether to treat the input as the residual or as the observed data * **born_fwd** (*Bool*) – Whether to use the forward or linearized forward modeling operator * **nlind** (*Bool*) – Whether to remove the non linear data from the input data. This option is only available in combination with born_fwd * **Returns** Adjoint jacobian on the input data (gradient) * **Return type** Array ### interface.J_adjoint_standard(model, src_coords, wavelet, rec_coords, recin, space_order=8, is_residual=False, return_obj=False, born_fwd=False, isic=False, ws=None, t_sub=1, nlind=False) Adjoint Jacobian (adjoint fo born modeling operator) operator on a shot record as a source (i.e data residual). Outputs the gradient with standard zero lag cross correlation over time. * **Parameters** * **model** (*Model*) – Physical model * **src_coords** (*Array*) – Coordiantes of the source(s) * **wavelet** (*Array*) – Source signature * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **recin** (*Array*) – Receiver data * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **isic** (*Bool*) – Whether or not to use ISIC imaging condition * **ws** (*Array*) – Extended source spatial distribution * **is_residual** (*Bool*) – Whether to treat the input as the residual or as the observed data * **born_fwd** (*Bool*) – Whether to use the forward or linearized forward modeling operator * **nlind** (*Bool*) – Whether to remove the non linear data from the input data. This option is only available in combination with born_fwd * **Returns** Adjoint jacobian on the input data (gradient) * **Return type** Array ### interface.adjoint_no_rec(model, rec_coords, data, space_order=8) Adjoint/backward modeling of a shot record (receivers as source) without source sampling F^T\*Pr^T\*d_obs. * **Parameters** * **model** (*Model*) – Physical model * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **data** (*Array*) – Shot gather * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** Adjoint wavefield * **Return type** Array ### interface.adjoint_rec(model, src_coords, rec_coords, data, space_order=8) Adjoint/backward modeling of a shot record (receivers as source) Ps\*F^T\*Pr^T\*d. * **Parameters** * **model** (*Model*) – Physical model * **src_coords** (*Array*) – Coordiantes of the source(s) * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **data** (*Array*) – Shot gather * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** Shot record (adjoint wavefield at source position(s)) * **Return type** Array ### interface.adjoint_w(model, rec_coords, data, wavelet, space_order=8) Adjoint/backward modeling of a shot record (receivers as source) for an extended source setup Pw\*F^T\*Pr^T\*d_obs. * **Parameters** * **model** (*Model*) – Physical model * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **data** (*Array*) – Shot gather * **wavelet** (*Array*) – Time signature of the forward source for stacking along time * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** spatial distribution * **Return type** Array ### interface.adjoint_wf_src(model, u, src_coords, space_order=8) Adjoint/backward modeling of a full wavefield (full wavefield as adjoint source) Ps\*F^T\*u. * **Parameters** * **model** (*Model*) – Physical model * **u** (*Array** or **TimeFunction*) – Time-space dependent source * **src_coords** (*Array*) – Source coordinates * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** Shot record (sampled at source position(s)) * **Return type** Array ### interface.adjoint_wf_src_norec(model, u, space_order=8) Adjoint/backward modeling of a full wavefield (full wavefield as adjoint source) F^T\*u. * **Parameters** * **model** (*Model*) – Physical model * **u** (*Array** or **TimeFunction*) – Time-space dependent source * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** Adjoint wavefield * **Return type** Array ### interface.born_rec(model, src_coords, wavelet, rec_coords, space_order=8, isic=False) Linearized (Born) modeling of a point source for a model perturbation (square slowness) dm. * **Parameters** * **model** (*Model*) – Physical model * **src_coords** (*Array*) – Coordiantes of the source(s) * **wavelet** (*Array*) – Source signature * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **isic** (*Bool*) – Whether or not to use ISIC imaging condition * **Returns** Shot record * **Return type** Array ### interface.born_rec_w(model, weight, wavelet, rec_coords, space_order=8, isic=False) Linearized (Born) modeling of an extended source for a model perturbation (square slowness) dm with an extended source * **Parameters** * **model** (*Model*) – Physical model * **weight** (*Array*) – Spatial distriubtion of the extended source * **wavelet** (*Array*) – Source signature * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **isic** (*Bool*) – Whether or not to use ISIC imaging condition * **Returns** Shot record * **Return type** Array ### interface.forward_no_rec(model, src_coords, wavelet, space_order=8) Forward modeling of a point source without receiver. * **Parameters** * **model** (*Model*) – Physical model * **src_coords** (*Array*) – Coordiantes of the source(s) * **wavelet** (*Array*) – Source signature * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** Wavefield * **Return type** Array ### interface.forward_rec(model, src_coords, wavelet, rec_coords, space_order=8) Forward modeling of a point source with receivers Pr\*F\*Ps^T\*q. * **Parameters** * **model** (*Model*) – Physical model * **src_coords** (*Array*) – Coordiantes of the source(s) * **wavelet** (*Array*) – Source signature * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** Shot record * **Return type** Array ### interface.forward_rec_w(model, weight, wavelet, rec_coords, space_order=8) Forward modeling of an extended source with receivers Pr\*F\*Pw^T\*w * **Parameters** * **model** (*Model*) – Physical model * **weights** (*Array*) – Spatial distribution of the extended source. * **wavelet** (*Array*) – Source signature * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** Shot record * **Return type** Array ### interface.forward_rec_wf(model, src_coords, wavelet, rec_coords, t_sub=1, space_order=8) Forward modeling of a point source Pr\*F\*Ps^T\*q and return wavefield. * **Parameters** * **model** (*Model*) – Physical model * **src_coords** (*Array*) – Coordiantes of the source(s) * **wavelet** (*Array*) – Source signature * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** * *Array* – Shot record * *TimeFunction* – Wavefield ### interface.forward_wf_src(model, u, rec_coords, space_order=8) Forward modeling of a full wavefield source Pr\*F\*u. * **Parameters** * **model** (*Model*) – Physical model * **u** (*TimeFunction** or **Array*) – Time-space dependent wavefield * **rec_coords** (*Array*) – Coordiantes of the receiver(s) * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** Shot record * **Return type** Array ### interface.forward_wf_src_norec(model, u, space_order=8) Forward modeling of a full wavefield source without receiver F\*u. * **Parameters** * **model** (*Model*) – Physical model * **u** (*TimeFunction** or **Array*) – Time-space dependent wavefield * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** Wavefield * **Return type** Array ### interface.grad_fwi(model, recin, rec_coords, u, space_order=8) FWI gradient, i.e adjoint Jacobian on a data residual. * **Parameters** * **model** (*Model*) – Physical model * **recin** (*Array*) – Data residual * **rec_coords** (*Array*) – Receivers coordinates * **u** (*TimeFunction*) – Forward wavefield * **space_order** (*Int** (**optional**)*) – Spatial discretization order, defaults to 8 * **Returns** FWI gradient * **Return type** Array ### interface.wri_func(model, src_coords, wavelet, rec_coords, recin, yin, space_order=8, isic=False, ws=None, t_sub=1, grad='m', grad_corr=False, alpha_op=False, w_fun=None, eps=0, freq_list=[], wfilt=None) Time domain wavefield reconstruction inversion wrapper ## kernels module ### kernels.acoustic_kernel(model, u, fw=True, q=None) Acoustic wave equation time stepper * **Parameters** * **model** (*Model*) – Physical model * **u** (*TimeFunction** or **tuple*) – wavefield (tuple if TTI) * **fw** (*Bool*) – Whether forward or backward in time propagation * **q** (*TimeFunction** or **Expr*) – Full time-space source ### kernels.tti_kernel(model, u1, u2, fw=True, q=None) TTI wave equation (one from my paper) time stepper * **Parameters** * **model** (*Model*) – Physical model * **u1** (*TimeFunction*) – First component (pseudo-P) of the wavefield * **u2** (*TimeFunction*) – First component (pseudo-P) of the wavefield * **fw** (*Bool*) – Whether forward or backward in time propagation * **q** (*TimeFunction** or **Expr*) – Full time-space source as a tuple (one value for each component) ### kernels.wave_kernel(model, u, fw=True, q=None) Pde kernel corresponding the the model for the input wavefield * **Parameters** * **model** (*Model*) – Physical model * **u** (*TimeFunction** or **tuple*) – wavefield (tuple if TTI) * **fw** (*Bool*) – Whether forward or backward in time propagation * **q** (*TimeFunction** or **Expr*) – Full time-space source ## models module ### _class_ models.Model(origin, spacing, shape, m, space_order=2, nbl=40, dtype=<class 'numpy.float32'>, epsilon=None, delta=None, theta=None, phi=None, rho=1, dm=None, fs=False, \*\*kwargs) The physical model used in seismic inversion processes. * **Parameters** * **origin** (*tuple of floats*) – Origin of the model in m as a tuple in (x,y,z) order. * **spacing** (*tuple of floats*) – Grid size in m as a Tuple in (x,y,z) order. * **shape** (*tuple of int*) – Number of grid points size in (x,y,z) order. * **space_order** (*int*) – Order of the spatial stencil discretisation. * **m** (*array_like** or **float*) – Squared slownes in s^2/km^2 * **nbl** (*int**, **optional*) – The number of absorbin layers for boundary damping. * **dtype** (*np.float32** or **np.float64*) – Defaults to 32. * **epsilon** (*array_like** or **float**, **optional*) – Thomsen epsilon parameter (0<epsilon<1). * **delta** (*array_like** or **float*) – Thomsen delta parameter (0<delta<1), delta<epsilon. * **theta** (*array_like** or **float*) – Tilt angle in radian. * **phi** (*array_like** or **float*) – Asymuth angle in radian. * **dt** (*Float*) – User provided computational time-step #### _property_ critical_dt() Critical computational time step value from the CFL condition. #### _property_ dm() Model perturbation for linearized modeling #### _property_ dt() User provided dt #### _property_ is_tti() Whether the model is TTI or isotopic #### _property_ m() Function holding the squared slowness in s^2/km^2. #### _property_ space_order() Spatial discretization order #### _property_ spacing_map() Map between spacing symbols and their values for each SpaceDimension. #### _property_ vp() Symbolic representation of the velocity vp = sqrt(1 / m) ## propagators module ### propagators.adjoint(model, y, src_coords, rcv_coords, space_order=8, q=0, dft_sub=None, save=False, ws=None, norm_v=False, w_fun=None, freq_list=None) Low level propagator, to be used through interface.py Compute adjoint wavefield v = adjoint(F(m))\*y and related quantities (||v||_w, v(xsrc)) ### propagators.born(model, src_coords, rcv_coords, wavelet, space_order=8, save=False, q=None, return_op=False, isic=False, freq_list=None, dft_sub=None, ws=None, t_sub=1, nlind=False) Low level propagator, to be used through interface.py Compute linearized wavefield U = J(m)\* δ m and related quantities. ### propagators.forward(model, src_coords, rcv_coords, wavelet, space_order=8, save=False, q=None, return_op=False, freq_list=None, dft_sub=None, ws=None, t_sub=1, \*\*kwargs) Low level propagator, to be used through interface.py Compute forward wavefield u = A(m)^{-1}\*f and related quantities (u(xrcv)) ### propagators.forward_grad(model, src_coords, rcv_coords, wavelet, v, space_order=8, q=None, ws=None, isic=False, w=None, freq=None, \*\*kwargs) Low level propagator, to be used through interface.py Compute forward wavefield u = A(m)^{-1}\*f and related quantities (u(xrcv)) ### propagators.gradient(model, residual, rcv_coords, u, return_op=False, space_order=8, w=None, freq=None, dft_sub=None, isic=False) Low level propagator, to be used through interface.py Compute the action of the adjoint Jacobian onto a residual J’\* δ d. ### propagators.name(model) ## sensitivity module ### sensitivity.basic_src(model, u, \*\*kwargs) Basic source for linearized modeling * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield (tuple of fields for TTI or dft) * **model** (*Model*) – Model containing the perturbation dm ### sensitivity.crosscorr_freq(u, v, model, freq=None, dft_sub=None, \*\*kwargs) Standard cross-correlation imaging condition with on-th-fly-dft * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield (tuple of fields for TTI or dft) * **v** (*TimeFunction** or **Tuple*) – Adjoint wavefield (tuple of fields for TTI) * **model** (*Model*) – Model structure * **freq** (*Array*) – Array of frequencies for on-the-fly DFT * **factor** (*int*) – Subsampling factor for DFT ### sensitivity.crosscorr_time(u, v, model, \*\*kwargs) Cross correlation of forward and adjoint wavefield * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield (tuple of fields for TTI or dft) * **v** (*TimeFunction** or **Tuple*) – Adjoint wavefield (tuple of fields for TTI) * **model** (*Model*) – Model structure ### sensitivity.func_name(freq=None, isic=False) Get key for imaging condition/linearized source function ### sensitivity.grad_expr(gradm, u, v, model, w=None, freq=None, dft_sub=None, isic=False) Gradient update stencil * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield (tuple of fields for TTI or dft) * **v** (*TimeFunction** or **Tuple*) – Adjoint wavefield (tuple of fields for TTI) * **model** (*Model*) – Model structure * **w** (*Float** or **Expr** (**optional**)*) – Weight for the gradient expression (default=1) * **freq** (*Array*) – Array of frequencies for on-the-fly DFT * **factor** (*int*) – Subsampling factor for DFT * **isic** (*Bool*) – Whether or not to use inverse scattering imaging condition (not supported yet) ### sensitivity.inner_grad(u, v) Inner product of the gradient of two Function. * **Parameters** * **u** (*TimeFunction** or **Function*) – First wavefield * **v** (*TimeFunction** or **Function*) – Second wavefield ### sensitivity.isic_freq(u, v, model, \*\*kwargs) Inverse scattering imaging condition * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield (tuple of fields for TTI or dft) * **v** (*TimeFunction** or **Tuple*) – Adjoint wavefield (tuple of fields for TTI) * **model** (*Model*) – Model structure ### sensitivity.isic_src(model, u, \*\*kwargs) ISIC source for linearized modeling * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield (tuple of fields for TTI or dft) * **model** (*Model*) – Model containing the perturbation dm ### sensitivity.isic_time(u, v, model, \*\*kwargs) Inverse scattering imaging condition * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield (tuple of fields for TTI or dft) * **v** (*TimeFunction** or **Tuple*) – Adjoint wavefield (tuple of fields for TTI) * **model** (*Model*) – Model structure ### sensitivity.lin_src(model, u, isic=False) Source for linearized modeling * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield (tuple of fields for TTI or dft) * **model** (*Model*) – Model containing the perturbation dm ## sources module ### _class_ sources.PointSource(\*args, \*\*kwargs) Symbolic data object for a set of sparse point sources * **Parameters** * **name** (*String*) – Name of the symbol representing this source * **grid** (*Grid*) – Grid object defining the computational domain. * **coordinates** (*Array*) – Point coordinates for this source * **data** (*(**Optional**) **Data*) – values to initialise point data * **ntime** (*Int** (**Optional**)*) – Number of timesteps for which to allocate data * **npoint** (*Int** (**Optional**)*) – * **of sparse points represented by this source** (*Number*) – * **dimension** (*Dimension** (**Optional**)*) – object for representing the number of points in this source * **either the dimensions ntime and npoint**** or ****the fully** (*Note**,*) – * **data array need to be provided.** (*initialised*) – #### default_assumptions(_ = {'commutative': True, 'complex': True, 'extended_real': True, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'real': True_ ) #### is_commutative(_ = Tru_ ) #### is_complex(_ = Tru_ ) #### is_extended_real(_ = Tru_ ) #### is_finite(_ = Tru_ ) #### is_hermitian(_ = Tru_ ) #### is_imaginary(_ = Fals_ ) #### is_infinite(_ = Fals_ ) #### is_real(_ = Tru_ ) ### sources.Receiver() alias of `sources.PointSource` ### _class_ sources.RickerSource(\*args, \*\*kwargs) Symbolic object that encapsulate a set of sources with a pre-defined Ricker wavelet: [http://subsurfwiki.org/wiki/Ricker_wavelet](http://subsurfwiki.org/wiki/Ricker_wavelet) name: Name for the resulting symbol grid: `Grid` object defining the computational domain. f0: Peak frequency for Ricker wavelet in kHz time: Discretized values of time in ms #### default_assumptions(_ = {'commutative': True, 'complex': True, 'extended_real': True, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'real': True_ ) #### is_commutative(_ = Tru_ ) #### is_complex(_ = Tru_ ) #### is_extended_real(_ = Tru_ ) #### is_finite(_ = Tru_ ) #### is_hermitian(_ = Tru_ ) #### is_imaginary(_ = Fals_ ) #### is_infinite(_ = Fals_ ) #### is_real(_ = Tru_ ) #### wavelet(timev) ### _class_ sources.TimeAxis(start=None, step=None, num=None, stop=None) Data object to store the TimeAxis. Exactly three of the four key arguments must be prescribed. Because of remainder values it is not possible to create a TimeAxis that exactly adhears to the inputs therefore start, stop, step and num values should be taken from the TimeAxis object rather than relying upon the input values. The four possible cases are: \* start is None: start = step\*(1 - num) + stop \* step is None: step = (stop - start)/(num - 1) \* num is None: num = ceil((stop - start + step)/step) and because of remainder stop = step\*(num - 1) + start \* stop is None: stop = step\*(num - 1) + start * **Parameters** * **start** (*float**, **optional*) – Start of time axis. * **step** (*float**, **optional*) – Time interval. * **num** (*int**, **optional*) – Number of values (Note: this is the number of intervals + 1). Stop value is reset to correct for remainder. * **stop** (*float**, **optional*) – End time. #### time_values() ## wave_utils module ### wave_utils.extended_src_weights(model, wavelet, v) Adjoint of extended source. This function returns the expression to obtain the spatially varrying weights from the wavefield and time-dependent wavelet * **Parameters** * **model** (*Model*) – Physical model structure * **wavelet** (*Array*) – Time-serie for the time-varying source * **v** (*TimeFunction*) – Wavefield to get the weights from ### wave_utils.extented_src(model, weight, wavelet, q=0) Extended source for modelling where the source is the outer product of a spatially varying weight and a time-dependent wavelet i.e.: u.dt2 - u.laplace = w(x)\*q(t) This function returns the extended source w(x)\*q(t) * **Parameters** * **model** (*Model*) – Physical model structure * **weight** (*Array*) – Array of weight for the spatial Function * **wavelet** (*Array*) – Time-serie for the time-varying source * **q** (*Symbol** or **Expr** (**optional**)*) – Previously existing source to be added to (source will be q + w(x)\*q(t)) ### wave_utils.freesurface(model, eq) Generate the stencil that mirrors the field as a free surface modeling for the acoustic wave equation * **Parameters** * **model** (*Model*) – Physical model * **eq** (*Eq** or **List of Eq*) – Equation to apply mirror to ### wave_utils.idft(v, freq=None) Symbolic inverse dft of v * **Parameters** * **v** (*TimeFunction** or **Tuple*) – Wavefield to take inverse DFT of * **freq** (*Array*) – Array of frequencies for on-the-fly DFT ### wave_utils.otf_dft(u, freq, dt, factor=None) On the fly DFT wavefield (frequency slices) and expression * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield * **freq** (*Array*) – Array of frequencies for on-the-fly DFT * **factor** (*int*) – Subsampling factor for DFT ### wave_utils.sub_time(time, factor, dt=1, freq=None) Subsampled time axis * **Parameters** * **time** (*Dimension*) – time Dimension * **factor** (*int*) – Subsampling factor ### wave_utils.wavefield(model, space_order, save=False, nt=None, fw=True, name='', t_sub=1) Create the wavefield for the wave equation * **Parameters** * **model** (*Model*) – Physical model * **space_order** (*int*) – Spatial discretization order * **save** (*Bool*) – Whether or not to save the time history * **nt** (*int** (**optional**)*) – Number of time steps if the wavefield is saved * **fw** (*Bool*) – Forward or backward (for naming) * **name** (*string*) – Custom name attached to default (u+name) ### wave_utils.wavefield_subsampled(model, u, nt, t_sub, space_order=8) Create a subsampled wavefield * **Parameters** * **model** (*Model*) – Physical model * **u** (*TimeFunction*) – Forward wavefield for modeling * **nt** (*int*) – Number of time steps on original time axis * **t_sub** (*int*) – Factor for time-subsampling * **space_order** (*int*) – Spatial discretization order ### wave_utils.weighted_norm(u, weight=None) Space-time norm of a wavefield, split into norm in time first then in space to avoid breaking loops * **Parameters** * **u** (*TimeFunction** or **Tuple of TimeFunction*) – Wavefield to take the norm of * **weight** (*String*) – Spacial weight to apply ### wave_utils.wf_as_src(v, w=1, freq_list=None) Weighted source as a time-space wavefield * **Parameters** * **u** (*TimeFunction** or **Tuple*) – Forward wavefield (tuple of fields for TTI or dft) * **w** (*Float** or **Expr** (**optional**)*) – Weight for the source expression (default=1) ## Module contents
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
2503
# JUDI Examples This directory contains examples of how to use JUDI for modeling and inversion, as well as code to reproduce results from journal papers. ## Required packages The examples require some additional Julia packages. These packages are not required for the core package, but need to be installed in order to run the following examples. You can install the packages by running the following code from the Julia terminal: ``` using Pkg # IO Pkg.add("HDF5") Pkg.add("JLD") Pkg.add("JLD2") # Plotting Pkg.add("PyPlot") Pkg.add("SlimPlotting") # Optimization Pkg.add("NLopt") Pkg.add("IterativeSolvers") Pkg.add("Optim") Pkg.add("LineSearches") ``` ## Overview * Generic JUDI examples can be found in [scripts](https://github.com/slimgroup/JUDI.jl/tree/master/examples/scripts) * Jupyter notebooks for FWI can be found in [notebooks](https://github.com/slimgroup/JUDI.jl/tree/master/examples/notebooks) * Reproducable examples for *A large-scale framework for symbolic implementations of seismic inversion algorithms in Julia* are available in [software_paper](https://github.com/slimgroup/JUDI.jl/tree/master/examples/software_paper) * Reproducable examples for *Compressive least squares migration with on-the-fly Fourier transforms* are available in [compressive_splsrtm](https://github.com/slimgroup/JUDI.jl/tree/master/examples/compressive_splsrtm) * Examples related to *A dual formulation of wavefield reconstruction inversion for large-scale seismic inversion* are available in [twri](https://github.com/slimgroup/JUDI.jl/tree/master/examples/twri) ## References * Philipp A. Witte, Mathias Louboutin, Navjot Kukreja, Fabio Luporini, Michael Lange, Gerard J. Gorman and Felix J. Herrmann. A large-scale framework for symbolic implementations of seismic inversion algorithms in Julia. GEOPHYSICS, Vol. 84 (3), pp. F57-F71, 2019. <https://library.seg.org/doi/abs/10.1190/geo2018-0174.1> * Philipp A. Witte, Mathias Louboutin, Fabio Luporini, Gerard J. Gorman and Felix J. Herrmann. Compressive least-squares migration with on-the-fly Fourier transforms. GEOPHYSICS, vol. 84 (5), pp. R655-R672, 2019. <https://library.seg.org/doi/abs/10.1190/geo2018-0490.1> * Gabrio Rizzuti, Mathias Louboutin, Rongrong Wang, and Felix J. Herrmann. A dual formulation of wavefield reconstruction inversion for large-scale seismic inversion. Submitted to Geophysics. <https://slim.gatech.edu/content/dual-formulation-wavefield-reconstruction-inversion-large-scale-seismic-inversion>
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
6759
# Compressive least squares migration with on-the-fly Fourier transforms ## Overview This repository contains instructions and the scripts to reproduce the examples from the paper ["Compressive least squares migration with on-the-fly Fourier transforms" (Witte et al, 2019)](https://library.seg.org/doi/abs/10.1190/geo2018-0490.1). Running the examples requires Julia (version 1.1.0) and the JUDI package. Follow the instructions from the [main page](https://github.com/slimgroup/JUDI.jl) to install JUDI and its required packages. For questions, contact Philipp Witte at [email protected]. ## Abstract Least-squares seismic imaging is an inversion-based approach for accurately imaging the earth's subsurface. However, in the time-domain, the computational cost and memory requirements of this approach scale with the size and recording length of the seismic experiment, thus making this approach often prohibitively expensive in practice. To overcome these issues, we borrow ideas from compressive sensing and signal processing and introduce an algorithm for sparsity-promoting seismic imaging using on-the-fly Fourier transforms. By computing gradients and functions values for random subsets of source locations and frequencies, we considerably limit the number of wave equation solves, while on-the-fly Fourier transforms allow computing an arbitrary number of monochromatic frequency-domain wavefields with a time-domain modeling code and without having to solve large-scale Helmholtz equations. The memory requirements of this approach are independent of the number of time steps and solely depend on the number of frequencies, which determine the amount of crosstalk and subsampling artifacts in the image. We show the application of our approach to several large-scale open source data sets and compare the results to a conventional time-domain approach with optimal checkpointing. ## Obtaining the velocity models The velocity models for our example (Sigsbee 2A and BP 2004 Synthetic model) are available on the SLIM ftp server. Follow [the link](ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/) or run the following command from the terminal to download the velocity models and supplementary files: ### Sigsbee 2A ``` wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/sigsbee2A_model.jld ``` ### BP Synthetic 2004 Generating the observed data requires the true velocity model, as well as the density model. Furthermore, we need the header geometry, which was extracted from the [original data](https://wiki.seg.org/wiki/2004_BP_velocity_estimation_benchmark_model) released by BP and saved as a Julia file. ``` wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_true_velocity.jld wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_density.jld wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_header_geometry.jld ``` For running the RTM and SPLS-RTM examples, we need the migration velocity model, which is a slightyl smoothed version of the true velocity. Furthermore, we use a mask to zero out the water column. ``` wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_migration_velocity.jld wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_water_bottom.jld ``` ## The linearized inverse scattering imaging condition To reproduce Figure 1 from the paper, run the script [compare_imaging_conditions.jl](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/Figure1/compare_imaging_conditions.jl). Forward and adjoint linearized modeling using on-the-fly DFTs with the two different imaging conditions is implemented using [Devito](https://github.com/opesci/devito). The linearized wave equations are set up as symbolic python objects and are defined in the JUDI source code. Follow [this link](https://github.com/slimgroup/JUDI.jl/blob/master/src/Python/JAcoustic_codegen.py) to see the implementations of the operators. #### Figure: {#f1} ![](Figure1/figure1.png){width=80%} ## Time vs frequency domain imaging To reproduce Figure 2 from the paper, run the script [compare_imaging_time_frequency.jl](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/Figure2/compare_imaging_time_frequency.jl). #### Figure: {#f2} ![](Figure2/figure2.png){width=80%} ## Sigsbee 2A example First generate the observed (linearized) data by running the [generate_data_sigsbee.jl](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/Sigsbee2A/generate_data_sigsbee.jl) script. The RTM results can be reproduced using the [rtm_sigsbee.jl](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/Sigsbee2A/rtm_sigsbee.jl) script. The time and frequency-domain SPLS-RTM results can be reproduced with the scripts [splsrtm_sigsbee_time_domain.jl](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/Sigsbee2A/splsrtm_sigsbee_time_domain.jl) and [splsrtm_sigsbee_frequency_domain.jl](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/Sigsbee2A/splsrtm_sigsbee_frequency_domain.jl). #### Figure: {#f3} ![](Sigsbee2A/figure1.png){width=80%} #### Figure: {#f4} ![](Sigsbee2A/figure2.png){width=80%} ## BP Synthetic 2004 example First, we generate the observed (non-linear) data using the true velocity model and the density. The data can be generated by running the script [generate_data_bp2004.jl](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/BP_synthetic_2004/generate_data_bp2004.jl). The scripts [rtm_bp_2004_freq.jl](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/BP_synthetic_2004/rtm_bp_2004_freq.jl) and [splsrtm_bp_2004_freq.jl](https://github.com/slimgroup/JUDI.jl/blob/master/examples/compressive_splsrtm/BP_synthetic_2004/splsrtm_bp_2004_freq.jl) reproduce the frequency-domain RTM and SPLS-RTM results. #### Figure: {#f5} ![](BP_synthetic_2004/figure1.png){width=80%} #### Figure: {#f6} ![](BP_synthetic_2004/figure2.png){width=80%} ## References The reproducible examples on this page are featured in the following journal publication: * Philipp A. Witte, Mathias Louboutin, Fabio Luporini, Gerard J. Gorman and Felix J. Herrmann. Compressive least-squares migration with on-the-fly Fourier transforms. GEOPHYSICS, vol. 84 (5), pp. R655-R672, 2019. <https://library.seg.org/doi/abs/10.1190/geo2018-0490.1> * Copyright (c) 2019 Geophysics * DOI: 10.1190/geo2018-0490.1 Contact authors via: [email protected] and [email protected].
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
1537
# Viking Graben Line 12 [Viking Graben Line 12](https://wiki.seg.org/wiki/Mobil_AVO_viking_graben_line_12) is an open source marine 2D seismic datasets. ## Dataset To download the data use `download_data.sh` script (don't forget to make it executable `chmod +x download_data.sh`). It contains segy data, source signature, well logs and the description. ## Preprocessing To preprocess the data [Madagascar](https://www.reproducibility.org/wiki/Main_Page) open source seismic processing software is required. The processing scripts are located in `proc` subfolder. ## Inversion ### Configuration To initialize this project, go to the example directory (location of `Project.toml`) and run: ```bash julia -e 'using Pkg;Pkg.add("DrWatson");Pkg.activate(".");Pkg.instantiate()' ``` this will install all required dependency at the version used to create these examples. ## FWI and RTM After preprocessing is done FWI is the way to go. Inversion scripts is in `fwi` subfolder. Inversion/migration are done using [JUDI](https://github.com/slimgroup/JUDI.jl) interface. The last steps are RTM and LSRTM wich are in `rtm` and `lsrtm` subfolders repectively. Before runnig FWI/RTM be sure to preinstall julia dependencies: `julia requirements.jl` To run FWI/RTM examples you will probably need to have 20-30 Gb RAM available. Here are the results of FWI/RTM/LSRTM. ![FWI](fwi/fwi.png "FWI") ![RTM](rtm/rtm.png "RTM") ![LSRTM](lsrtm/lsrtm.png "LSRTM") The example is provided by [Kerim Khemraev](https://github.com/kerim371)
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
614
# Full Waveform Inversion FWI is done using JUDI. The idea is the following: 1. Prepare initial model 2. Trim segy to 4 sec to reduce computation time 3. Run 10 iteration of FWI at a given frequency Steps 2 and 3 run recursively while increasing low-pass frequency. Possible frequencies are: 0.005, 0.008, 0.012, 0.018, 0.025, 0.035 kHz (don't forget to increase space order JUDI option to 32 points for frequencies > 0.012 kHz) To reduce the amount of RAM one may want to try to add `subsampling_factor=10` to JUDI options. Usually at low frequencies 10 times subsampling doesn't affect the result of FWI.
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
785
# Viking Graben Line 12: processing The processing is done using [Madagascar](https://www.reproducibility.org/wiki/Main_Page) open source software. Thus we assume that Madagascar is present on the system. To install python dependencies use `requirements.txt` file: `python -m pip install -r requirements.txt` The processing is partly based on [Rodrigo Morelatto work](https://github.com/rmorel/Viking). The graph is pretty straightforward: 0. Geometry correction 1. Deghosting 2. Gain 3. Turning waves muting 4. Turning waves supression using dip filter (not necessary but good for Madagascar use experience) 5. Multiples supression using Radon transform 6. Automatic velocity picking 7. Export to segy The result of processing (exported to segy) is used by JUDI while RTM/LSRTM.
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
318
# Reverse Time Migration RTM is done using JUDI. Before running this one should process the data (see `../proc` directory) and complete the FWI to prepare accurate velocity model (see `../fwi` directory). Be sure to set the correct path to the model computed at FWI step to `model_file` variable in `rtm.jl` script.
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
3.4.7
21f9b9ae041be1caba073bb496235bceaa1d2ff0
docs
3000
# A large-scale framework for symbolic implementations of seismic inversion algorithms in Julia ## Overview This repository contains instructions and the scripts to reproduce the examples from the paper ["A large-scale framework for symbolic implementations of seismic inversion algorithms in Julia" (Witte et al, 2019)](https://library.seg.org/doi/abs/10.1190/geo2018-0174.1). Running the examples requires Julia (version 1.1.0) and the JUDI package. Follow the instructions from the [main page](https://github.com/slimgroup/JUDI.jl) to install JUDI and its required packages. For questions, contact Philipp Witte at [email protected]. ## Abstract Writing software packages for seismic inversion is a very challenging task because problems such as full-waveform inversion or least-squares imaging are algorithmically and computationally demanding due to the large number of unknown parameters and the fact that waves are propagated over many wavelengths. Therefore, software frameworks need to combine versatility and performance to provide geophysicists with the means and flexibility to implement complex algorithms that scale to exceedingly large 3D problems. Following these principles, we have developed the Julia Devito Inversion framework, an open-source software package in Julia for large-scale seismic modeling and inversion based on Devito, a domain-specific language compiler for automatic code generation. The framework consists of matrix-free linear operators for implementing seismic inversion algorithms that closely resemble the mathematical notation, a flexible resilient parallelization, and an interface to Devito for generating optimized stencil code to solve the underlying wave equations. In comparison with many manually optimized industry codes written in low-level languages, our software is built on the idea of independent layers of abstractions and user interfaces with symbolic operators. Through a series of numerical examples, we determined that this allows users to implement a series of increasingly complex algorithms for waveform inversion and imaging as simple Julia scripts that scale to large-scale 3D problems. This illustrates that software based on the paradigms of abstract user interfaces and automatic code generation and makes it possible to manage the complexity of the algorithms and performance optimizations, thus providing a high-performance research and production framework. ## References The reproducible examples on this page are featured in the following journal publication: * Philipp A. Witte, Mathias Louboutin, Navjot Kukreja, Fabio Luporini, Michael Lange, Gerard J. Gorman and Felix J. Herrmann. A large-scale framework for symbolic implementations of seismic inversion algorithms in Julia. GEOPHYSICS, Vol. 84 (3), pp. F57-F71, 2019. <https://library.seg.org/doi/abs/10.1190/geo2018-0174.1> * Copyright (c) 2019 Geophysics * DOI: 10.1190/geo2018-0174.1 Contact authors via: [email protected] and [email protected].
JUDI
https://github.com/slimgroup/JUDI.jl.git
[ "MIT" ]
0.3.1
bbfc9bc9ca7d544672591addd06bd2cae47750f2
code
4665
# Julia GARCH package # Copyright 2013 Andrey Kolev # Distributed under MIT license (see LICENSE.md) "Generalized Autoregressive Conditional Heteroskedastic (GARCH) models for Julia." module GARCH using NLopt, Distributions, Printf, LinearAlgebra, SpecialFunctions export garchFit, predict include("stattests.jl") "Fitted GARCH model object." struct GarchFit data::Vector params::Vector llh::Float64 status::Symbol converged::Bool sigma::Vector hessian::Array{Float64,2} cvar::Array{Float64,2} secoef::Vector tval::Vector end function Base.show(io::IO ,fit::GarchFit) pnorm(x) = 0.5 * (1 + erf(x / sqrt(2))) prt(x) = 2 * (1 - pnorm(abs(x))) jbstat, jbp = jbtest(fit.data./fit.sigma) @printf io "Fitted garch model \n" @printf io " * Coefficient(s): %-15s%-15s%-15s\n" "ω" "α" "β" @printf io "%-22s%-15.5g%-15.5g%-15.5g\n" "" fit.params[1] fit.params[2] fit.params[3] @printf io " * Log Likelihood: %.5g\n" fit.llh @printf io " * Converged: %s\n" fit.converged @printf io " * Solver status: %s\n\n" fit.status @printf io " * Standardised Residuals Tests:\n" @printf io " %-26s%-15s%-15s\n" "" "Statistic" "p-Value" @printf io " %-21s%-5s%-15.5g%-15.5g\n\n" "Jarque-Bera Test" "χ²" jbstat jbp @printf io " * Error Analysis:\n" @printf io " %-7s%-15s%-15s%-15s%-15s\n" "" "Estimate" "Std.Error" "t value" "Pr(>|t|)" @printf io " %-7s%-15.5g%-15.5g%-15.5g%-15.5g\n" "ω" fit.params[1] fit.secoef[1] fit.tval[1] prt(fit.tval[1]) @printf io " %-7s%-15.5g%-15.5g%-15.5g%-15.5g\n" "α" fit.params[2] fit.secoef[2] fit.tval[2] prt(fit.tval[2]) @printf io " %-7s%-15.5g%-15.5g%-15.5g%-15.5g\n" "β" fit.params[3] fit.secoef[3] fit.tval[3] prt(fit.tval[3]) end "Estimate Hessian using central difference approximation." function cdHessian(params, f) eps = 1e-4 * params n = length(params) H = zeros(n, n) function step(x, i1, i2, d1, d2) xc = copy(x) xc[i1] += d1 xc[i2] += d2 f(xc) end for i in 1:n for j in 1:n H[i,j] = (step(params, i, j, eps[i], eps[j]) - step(params, i, j, eps[i], -eps[j]) - step(params, i, j, -eps[i], eps[j]) + step(params, i, j, -eps[i], -eps[j])) / (4.0*eps[i]*eps[j]) end end H end "Simulate GARCH process." function garchSim(ɛ²::Vector, ω, α, β) h = similar(ɛ²) h[1] = mean(ɛ²) for i = 2:length(ɛ²) h[i] = ω + α*ɛ²[i-1] + β*h[i-1] end h end "Normal GARCH log likelihood function." function garchLLH(y::Vector, params::Vector) ɛ² = y.^2 T = length(y) h = garchSim(ɛ², params...) -0.5*(T-1)*log(2π) - 0.5*sum(log.(h) + (y./sqrt.(h)).^2) end """ predict(fit::GarchFit, n::Integer=1) Make n-step prediction using fitted object returned by garchFit (default step=1). # Arguments * `fit::GarchFit` : fitted model object returned by garchFit. * `n::Integer` : the number of time-steps to be forecasted, by default 1 (returns scalar for n=1 and array for n>1). # Examples ``` fit = garchFit(ret) predict(fit, n=2) ``` """ function predict(fit::GarchFit, n::Integer=1) if n < 1 throw(ArgumentError("n shoud be >= 1 !")) end ω, α, β = fit.params y = fit.data ɛ² = y.^2 h = garchSim(ɛ², ω, α, β) pred = ω + α*ɛ²[end] + β*h[end] if n == 1 return sqrt(pred) end pred = [pred] for i in 2:n push!(pred, ω + (α + β)*pred[end]) end sqrt.(pred) end """ garchFit(y::Vector) Estimate parameters of the univariate normal GARCH process. # Arguments * `y::Vector`: univariate time-series array # Examples ``` filename = Pkg.dir("GARCH", "test", "data", "price.csv") price = Array{Float64}(readdlm(filename, ',')[:,2]) ret = diff(log.(price)) ret = ret - mean(ret) fit = garchFit(ret) ``` """ function garchFit(y::Vector) ɛ² = y.^2 T = length(y) h = zeros(T) #opt = Opt(Sys.isapple() ? (:LN_PRAXIS) : (:LN_SBPLX), 3) # LN_SBPLX has a problem on mac currently opt = Opt(:LN_SBPLX, 3) lower_bounds!(opt, [1e-10, 0.0, 0.0]) upper_bounds!(opt, [1, 0.3, 0.99]) min_objective!(opt, (params, grad) -> -garchLLH(y, params)) (minf, minx, ret) = optimize(opt, [1e-5, 0.09, 0.89]) h = garchSim(ɛ², minx...) converged = minx[1] > 0 && all(minx[2:3] .>= 0) && sum(minx[2:3]) < 1.0 H = cdHessian(minx, x -> garchLLH(y, x)) cvar = -inv(H) secoef = sqrt.(diag(cvar)) tval = minx ./ secoef GarchFit(y, minx, -minf, ret, converged, sqrt.(h), H, cvar, secoef, tval) end end #module
GARCH
https://github.com/AndreyKolev/GARCH.jl.git
[ "MIT" ]
0.3.1
bbfc9bc9ca7d544672591addd06bd2cae47750f2
code
362
"Test the null of normality using the Jarque-Bera test statistic." function jbtest(x::Vector) n = length(x) m1 = sum(x)/n m2 = sum((x .- m1).^2)/n m3 = sum((x .- m1).^3)/n m4 = sum((x .- m1).^4)/n b1 = (m3/m2^(3/2))^2 b2 = (m4/m2^2) statistic = n * b1/6 + n*(b2 - 3)^2/24 d = Chisq(2.) pvalue = 1. - cdf(d, statistic) statistic, pvalue end
GARCH
https://github.com/AndreyKolev/GARCH.jl.git
[ "MIT" ]
0.3.1
bbfc9bc9ca7d544672591addd06bd2cae47750f2
code
470
using GARCH using Pkg, Test, DelimitedFiles, Statistics filename = Pkg.dir("GARCH", "test", "data", "price.csv") price = Array{Float64}(readdlm(filename, ',')[:,2]) ret = diff(log.(price)) ret = ret .- mean(ret) fit = garchFit(ret) param = [2.469347e-06, 1.142268e-01, 8.691734e-01] #R fGarch garch(1,1) estimated params @test fit.params ≈ param atol=1e-3 @test predict(fit) ≈ 0.005617744 atol = 1e-4 @test predict(fit, 2) ≈ [0.005617744, 0.005788309] atol = 1e-4
GARCH
https://github.com/AndreyKolev/GARCH.jl.git
[ "MIT" ]
0.3.1
bbfc9bc9ca7d544672591addd06bd2cae47750f2
docs
2063
# Julia GARCH package [![Build Status](https://travis-ci.org/AndreyKolev/GARCH.jl.svg?branch=master)](https://travis-ci.org/AndreyKolev/GARCH.jl) Generalized Autoregressive Conditional Heteroskedastic ([GARCH](http://en.wikipedia.org/wiki/Autoregressive_conditional_heteroskedasticity)) models for Julia. ## What is implemented * garchFit - estimates parameters of univariate normal GARCH process. * predict - make n-step prediction using fitted object returned by garchFit * Jarque-Bera residuals test * Error analysis * Package test (compares model parameters and predictions with those obtained using R fGarch) Analysis of model residuals - currently only Jarque-Bera Test implemented. ## What is not ready yet * Asymmetric and non-normal GARCH models * Comprehensive set of residuals tests ## Usage ### garchFit estimates parameters of univariate normal GARCH process. #### arguments: data - data vector #### returns: Structure containing details of the GARCH fit with the fllowing fields: * data - orginal data * params - vector of model parameters (omega,alpha,beta) * llh - likelihood * status - status of the solver * converged - boolean convergence status, true if constraints are satisfied * sigma - conditional volatility * hessian - Hessian matrix * secoef - standard errors * tval - t-statistics ### predict make n-step volatility prediction #### arguments: * fit - fitted object returned by garchFit * n - the number of time-steps to be forecasted, by default 1 #### returns: n-step-ahead volatility forecast ## Example using GARCH using Quandl quotes = quandl("YAHOO/INDEX_GSPC", format="DataFrame") ret = diff(log(Array{Float64}(quotes[:Adjusted_Close]))) fit = garchFit(ret) ## Author Andrey Kolev ## References * T. Bollerslev (1986): Generalized Autoregressive Conditional Heteroscedasticity. Journal of Econometrics 31, 307–327. * R. F. Engle (1982): Autoregressive Conditional Heteroscedasticity with Estimates of the Variance of United Kingdom Inflation. Econometrica 50, 987–1008.
GARCH
https://github.com/AndreyKolev/GARCH.jl.git
[ "MIT" ]
0.1.0
c98b725e0f8884f952e06f80001047d5552bb7c0
code
11863
module FractalAnimation using ProgressMeter: @showprogress using ColorSchemes using Continuables using Plots: gif using Logging using VideoIO using CUDA using Pipe include("anim_utils.jl") export SetParams, juliaset, juliaprogression, animateprogression export show_mandelbrot_traversal, mandelbrotset, to_gpu, batched_animate, continuous_animate """ escapeeval(f, threshold[, c, z, maxiter]) Evaluate the divergence speed for a given function of z,c in the complex plane. For julia and fatou sets pass the whole complex plane as z For mandelbrot-esque sets pass the whole complex plane as c """ function escapeeval(f::Function, threshold::Real, c::Union{Complex, Matrix{Complex}} = 1, z::Union{Complex, Matrix{Complex}} = 0, maxiter::Integer = 255) for i = 1:maxiter z = f(z, c) if abs(z) ≥ threshold return i end end return -0 end function _setdims(max_coord, min_coord, resolution) dim = (max_coord - min_coord) * resolution dim == 0 ? error("Height or width cannot be 0!") : return ceil(dim) |> Int64 end """ Essentially meshgrid to produce a Complex plane array of the given size """ function _genplane(min_coord::Complex, max_coord::Complex, width::Integer, height::Integer, gpu::Bool) real = range(min_coord.re, max_coord.re,length=width) imag = range(min_coord.im, max_coord.im,length=height) complexplane = zeros(Complex{Float64},(height, width)) for (i,x) ∈ collect(enumerate(real)) complexplane[:,i] .+= x end for (i,y) ∈ collect(enumerate(imag)) complexplane[i,:] .+= (y * 1im) end reverse!(complexplane, dims=1) gpu == true ? (return cu(complexplane)) : (return complexplane) end """ SetParams(min_coord, max_coord, resolution, threshold, nr_frames[, gpu]) #Feilds - `min_coord::ComplexF64`: The coordinate of the bottom-left of the image frame. - `max_coord::ComplexF64`: The coordinate of the top-right of the image frame. - `resolution::Int64`: The number of pixels in a 1x1 square in the complex plane - `width::Int64`: The width of the image frame - `height::Int64`: The height of the image frame - `plane::Union{Matrix{Complex{Float64}},CuArray{Complex{Float32}}}`: A `min_coord × max_coord` coordinate grid of the complex plane. - `threshold::Float64`: The distance from which we consider a point to have diverged - `nr_frames::Int64`: The number of images to generate for a progression - `gpu::Bool`: Whether to use the GPU """ struct SetParams min_coord::Complex{Float64} max_coord::Complex{Float64} resolution::Int64 width::Int64 height::Int64 plane::Union{Matrix{Complex{Float64}},CuArray{Complex{Float32}}} threshold::Float64 nr_frames::Int64 gpu::Bool """ The resolution, minimum, & maximum coordiantes determine the width & height """ function SetParams(min_coord::Complex, max_coord::Complex, resolution::Integer, threshold::Real, nr_frames::Integer, gpu::Bool = false) if min_coord.re ≥ max_coord.re; error("Max real component cannot be less than or equal to Min real component!") end if min_coord.im ≥ max_coord.im; error("Max imaginary component cannot be less than or equal to Min imaginary component!") end width = _setdims(max_coord.re, min_coord.re, resolution)::Int64 height = _setdims(max_coord.im, min_coord.im, resolution)::Int64 plane = _genplane(min_coord, max_coord, width, height, gpu)::Union{Matrix{Complex{Float64}},CuArray{Complex{Float32}}} return new( min_coord, max_coord, resolution, width, height, plane, threshold, nr_frames, gpu ) end end """ to_gpu(p) Return a new SetParams sruct allocated on the GPU This is a convenience method only! For initial construction pass `true` to the `gpu` feild of `SetParams`. """ function to_gpu(p::SetParams) if p.gpu == true return p else p = SetParams(p.min_coord, p.max_coord, p.resolution, p.threshold, p.nr_frames, true) return p end end """ mandelbrotset(set_p, f[ z, maxiter]) Return an array of the Mandelbrot-esque set for function `f` given initial value `z` """ mandelbrotset(set_p::SetParams, f::Function, z::Complex = 0.0+0.0im, maxiter::Integer = 255) = set_p.gpu == true ? exec_gpu_kernel_mandelbrot(set_p, f, z, maxiter) |> Array : escapeeval.(f, set_p.threshold, set_p.plane, z, maxiter) """ juliaset(set_p, f, c[, maxiter]) Return an array of the Julia set for function `f` around point `c` """ juliaset(set_p::SetParams, f::Function, c::Complex, maxiter::Integer = 255) = set_p.gpu == true ? exec_gpu_kernel_julia(set_p, f, c, maxiter) |> Array : escapeeval.(f, set_p.threshold, c, set_p.plane, maxiter) """ ------- Progression Functions ------- """ """ juliaprogression(set_p, points, f[, maxiter]) Return a Vector of julia sets for vector of `points` for function `f` """ juliaprogression(set_p::SetParams, points::Vector, f::Function, maxiter::Integer = 255) = [(c,juliaset(set_p, f, c, maxiter)) for c ∈ points] """ show_mandelbrot_traversal(set_p, γ, f[; <keyword arguments>]) Overlay and display the set of points `γ` over the Mandelbrot set for function `f` # Arguments - `set_p::SetParams` - `γ::Vector` - `f::Function` - `heat_c::Symbol=:terrain`: Color scheme for the heatmap of the Mandelbrot-esque set - `line_c::Symbol=:red`: Color of the line for vector `γ` """ function show_mandelbrot_traversal(set_p::SetParams, γ::Vector, f::Function; heat_c=:terrain, line_c=:red) plane = set_p.plane |> Array mapped_points = map_points_to_plane(γ, plane) mandelset = mandelbrotset(set_p, f) begin heatmap(mandelset, size=(set_p.width, set_p.height), c=heat_c, leg=false) plot!(mapped_points, size=(set_p.width, set_p.height), color=line_c) end end function animateprogression(progression::Vector, cscheme=ColorSchemes.terrain) sets = [set for (_,set) ∈ progression] max = get_maxval(sets) images = apply_colorscheme(cscheme, sets, max) anim = gen_animation(images) @debug "Animation temp directory: $(anim.dir)" return anim end """ batched_animate(set_p, γ, func[, filepath, cscheme, batchsize, maxiter]) Generate a video showing the julia progression along vector `γ` for function `func` with parameters `set_p` Divides the task of generating and writing the video into batches to avoid overwhelimg memory. """ function batched_animate(set_p::SetParams, γ::Vector, func::Function, filepath::String = "progression.mp4", cscheme = ColorSchemes.terrain, batchsize::Integer = 30, maxiter::Integer = 255) encoder_options = (crf=0, preset="ultrafast") pointsets = Iterators.partition(γ,batchsize) .|> Vector open_video_out(filepath, RGB{N0f8}, (set_p.height,set_p.width), framerate=60, encoder_options=encoder_options, codec_name="libx264rgb") do writer @showprogress "Processing Batches..." for pointset ∈ pointsets progression = juliaprogression(set_p, pointset, func, maxiter) sets = [set for (_,set) ∈ progression] imgstack = apply_colorscheme(cscheme, sets, maxiter) for img ∈ imgstack write(writer,img) end end close_video_out!(writer) end return nothing end """ continuous_animate(set_p, γ, func[, filepath, cscheme, maxiter]) Generate a video showing the julia progression along vector `γ` for function `func` with parameters `set_p` Uses Continous.jl to gererate sets as needed then write them to the video file. """ function continuous_animate(set_p::SetParams, γ::Vector, func::Function, filepath::String = "progression.mp4", cscheme = ColorSchemes.terrain, maxiter::Integer = 255) encoder_options = (crf=0, preset="ultrafast") open_video_out(filepath, RGB{N0f8}, (set_p.height,set_p.width), framerate=60, encoder_options=encoder_options, codec_name="libx264rgb") do writer writer_write(img) = write(writer, img) continuous_juliasets(set_p, func, γ, cscheme, maxiter)(writer_write) close_video_out!(writer) end return nothing end """ Provide a python-esque generator for julia set images """ continuous_juliasets(set_p::SetParams, func::Function, γ::Vector, cscheme, maxiter::Int) = @cont begin for c ∈ γ @pipe juliaset(set_p, func, c, maxiter) |> apply_colorscheme(cscheme, _, maxiter) |> cont end end """ ------- GPU Related Functions ------- """ """ CUDA kernel for julia sets Algorithm from: https://github.com/vini-fda/Mandelbrot-julia/blob/main/src/Mandelbrot_gpu.ipynb """ function kernel_julia_gpu!(out, in, f::Function, c::Complex, threshold::Real, maxiter::Integer) id = (blockIdx().x - 1) * blockDim().x + threadIdx().x stride = blockDim().x * gridDim().x w, h = size(in) cind = CartesianIndices((w, h)) for k=id:stride:w*h i = cind[k][1] j = cind[k][2] z = in[i,j] itrs = 0 while CUDA.abs2(z) < threshold if itrs ≥ maxiter itrs = 0 break end z = f(z,c) itrs += 1 end @inbounds out[i,j] = itrs end return nothing end """ Wrapper for CUDA kernel """ function exec_gpu_kernel_julia(set_p::SetParams, f::Function, c::Complex, maxiter::Integer=255) plane_trace = CuArray{ComplexF32}(undef, set_p.height, set_p.width) out_trace = CuArray{Float32}(undef, set_p.height, set_p.width) kernel = @cuda name="juliaset" launch=false kernel_julia_gpu!(out_trace, plane_trace, f, c, set_p.threshold, maxiter) config = launch_configuration(kernel.fun) threads = Base.min(length(out_trace), config.threads) blocks = cld(length(out_trace), threads) out = CUDA.zeros(Float32,(set_p.plane |> size)...) CUDA.@sync kernel(out, set_p.plane, f, c, set_p.threshold, maxiter; threads=threads, blocks=blocks) return out end """ CUDA kernel for mandelbrot sets """ function kernel_mandelbrot_gpu!(out, in, f::Function, z_init::Complex, threshold::Real, maxiter::Integer) id = (blockIdx().x - 1) * blockDim().x + threadIdx().x stride = blockDim().x * gridDim().x w, h = size(in) cind = CartesianIndices((w, h)) for k = id:stride:w*h i = cind[k][1] j = cind[k][2] c = in[i,j] z = z_init itrs = 0 while CUDA.abs2(z) < threshold if itrs ≥ maxiter itrs = 0 break end z = f(z,c) itrs += 1 end @inbounds out[i,j] = itrs end return nothing end """ Wrapper for CUDA kernel """ function exec_gpu_kernel_mandelbrot(set_p::SetParams, f::Function, z_init::Complex = 0, maxiter::Integer=255) plane_trace = CuArray{ComplexF32}(undef, set_p.height, set_p.width) out_trace = CuArray{Float32}(undef, set_p.height, set_p.width) kernel = @cuda name="juliaset" launch=false kernel_mandelbrot_gpu!(out_trace, plane_trace, f, z_init, set_p.threshold, maxiter) config = launch_configuration(kernel.fun) threads = Base.min(length(out_trace), config.threads) blocks = cld(length(out_trace), threads) out = cu(zeros(set_p.plane |> size)) CUDA.@sync kernel(out, set_p.plane, f, z_init, set_p.threshold, maxiter; threads=threads, blocks=blocks) return out end end
FractalAnimation
https://github.com/ErrolSeders/FractalAnimation.jl.git
[ "MIT" ]
0.1.0
c98b725e0f8884f952e06f80001047d5552bb7c0
code
1334
using ColorTypes: RGB, N0f8 using Images using Plots: Animation, plot!, heatmap using Printf: @sprintf import Plots: frame struct ImageWrapper img::Matrix{RGB} end function frame(anim::Animation, iw::ImageWrapper) i = length(anim.frames) + 1 filename = @sprintf("%010d.png", i) save(joinpath(anim.dir,filename), iw.img) push!(anim.frames, filename) end function gen_animation(images::Vector) anim = Animation() wrapped_images = ImageWrapper.(images) map((x)->frame(anim, x), wrapped_images) return anim end get_maxval(sets::Vector) = maximum(map((maximum ∘ collect ∘ Iterators.flatten), sets)) |> Integer apply_colorscheme(csheme::ColorScheme, sets::Vector, maxval::Integer) :: Vector{Matrix{RGB{N0f8}}} = map((x) -> get(csheme, x, (0, maxval)) .|> RGB{N0f8}, sets) apply_colorscheme(csheme::ColorScheme, set::AbstractArray, maxval::Integer) :: Matrix{RGB{N0f8}} = get(csheme, set, (0, maxval)) .|> RGB{N0f8} complex_euclidean_distance(u::Complex, v::Complex) = sqrt((u.re - v.re)^2 + (u.im - v.im)^2) function find_location(val::Complex, plane::AbstractArray) distances = complex_euclidean_distance.(val, plane) return findmin(distances)[2] end map_points_to_plane(points::Vector, plane::AbstractArray) = map((point) -> find_location(point,plane), points) .|> Tuple .|> reverse
FractalAnimation
https://github.com/ErrolSeders/FractalAnimation.jl.git
[ "MIT" ]
0.1.0
c98b725e0f8884f952e06f80001047d5552bb7c0
code
11852
using FractalAnimation using CUDA using Test @testset "FractalAnimation.jl" begin CUDA_available = CUDA.functional() @testset "Parmeter Bounds" begin @test_throws ErrorException SetParams(-2.0-2.0im, 2.0+2.0im, 0, 20.0, 60) @test_throws ErrorException SetParams(-2.0+2.0im, 2.0+2.0im, 20, 20.0, 60) @test_throws ErrorException SetParams(2.0-2.0im, 2.0+2.0im, 20, 20.0, 60) @test_throws ErrorException SetParams(2.0+2.0im, 2.0+2.0im, 0, 20.0, 60) end params = SetParams(-2.0-2.0im, 2.0+2.0im, 200, 20.0, 360) @testset "Parameter Type" begin @test params.plane isa Matrix{Complex{Float64}} end @testset "GPU Parameters" begin if CUDA_available gpu_params = SetParams(-2.0-2.0im, 2.0+2.0im, 200, 20.0, 360, true) @test gpu_params.plane isa CuArray{Complex{Float32},2, CUDA.Mem.DeviceBuffer} @testset "to_gpu" begin p_to_gpu = params |> to_gpu @test p_to_gpu.gpu == true end end end @testset "Paths" begin sin_path = Path(t-> t + 2im*sin(t),0,2π) @testset "Path Parameterization" begin @test sin_path.parameterization(0) ≈ 0 + 0im atol=0.01 @test sin_path.parameterization(2π) ≈ 2π + 0im atol=0.01 @test pointsonpath(sin_path,2) ≈ [0.0+0.0im, 2π + 0im] atol=0.01 end @testset "Bad Paths" begin @test_throws ErrorException pointsonpath(sin_path, 0) @test_throws ErrorException pointsonpath(sin_path, -2) end end @testset "Set Generation" begin test_params = SetParams(-1.0-1.0im, 1.0+1.0im, 10, 20.0, 4) func = (z,c) -> z^2 + c c = 0.30+0.53im correct_result_julia = [ 5 6 0 16 13 8 7 7 7 8 13 37 8 5 5 4 4 4 3 3 ; 5 7 11 0 0 12 0 9 9 0 0 0 8 6 5 4 4 4 3 3 ; 8 23 0 0 0 0 0 18 12 0 0 0 9 7 6 5 4 4 4 3 ; 0 16 0 0 0 0 0 0 70 32 0 15 15 9 8 5 4 4 4 4 ; 0 8 9 9 15 0 0 0 0 30 39 0 0 20 10 6 5 4 4 4 ; 6 6 7 8 11 24 28 0 0 0 0 23 0 13 8 6 5 4 4 4 ; 5 5 6 7 8 12 11 14 16 0 0 35 11 9 7 6 5 4 4 4 ; 5 5 5 6 7 8 9 12 0 0 0 0 14 9 7 6 5 5 4 4 ; 4 5 5 6 6 7 9 0 0 0 0 0 15 25 8 6 5 5 4 4 ; 4 5 5 5 6 7 0 0 0 0 0 0 0 0 8 6 5 5 4 4 ; 4 4 5 5 6 8 0 0 0 0 0 0 0 0 7 6 5 5 5 4 ; 4 4 5 5 6 8 25 15 0 0 0 0 0 9 7 6 6 5 5 4 ; 4 4 5 5 6 7 9 14 0 0 0 0 12 9 8 7 6 5 5 5 ; 4 4 4 5 6 7 9 11 35 0 0 16 14 11 12 8 7 6 5 5 ; 4 4 4 5 6 8 13 0 23 0 0 0 0 28 24 11 8 7 6 6 ; 4 4 4 5 6 10 20 0 0 39 30 0 0 0 0 15 9 9 8 0 ; 4 4 4 4 5 8 9 15 15 0 32 70 0 0 0 0 0 0 16 0 ; 3 4 4 4 5 6 7 9 0 0 0 12 18 0 0 0 0 0 23 8 ; 3 3 4 4 4 5 6 8 0 0 0 9 9 0 12 0 0 11 7 5 ; 3 3 4 4 4 5 5 8 37 13 8 7 7 7 8 13 16 0 6 5 ] @test juliaset(test_params, func, c) == correct_result_julia correct_result_mandelbrot = [ 5 5 5 5 6 6 7 8 12 12 7 6 5 5 5 5 4 4 4 4 ; 5 5 6 6 6 7 7 10 41 14 8 7 6 6 5 5 5 4 4 4 ; 5 6 6 6 7 8 9 14 0 0 10 8 7 6 6 5 5 4 4 4 ; 6 6 7 8 11 10 13 15 0 0 13 11 9 12 6 5 5 5 4 4 ; 7 7 7 9 89 0 0 0 0 0 0 38 34 19 7 6 5 5 4 4 ; 7 8 8 16 34 0 0 0 0 0 0 0 0 11 7 6 5 5 4 4 ; 11 9 10 23 0 0 0 0 0 0 0 0 0 28 9 6 5 5 5 4 ; 0 19 13 0 0 0 0 0 0 0 0 0 0 0 8 6 5 5 5 4 ; 0 0 35 0 0 0 0 0 0 0 0 0 0 0 8 6 5 5 5 4 ; 0 0 0 0 0 0 0 0 0 0 0 0 0 10 7 6 5 5 5 4 ; 0 0 0 0 0 0 0 0 0 0 0 0 0 10 7 6 5 5 5 4 ; 0 0 35 0 0 0 0 0 0 0 0 0 0 0 8 6 5 5 5 4 ; 0 19 13 0 0 0 0 0 0 0 0 0 0 0 8 6 5 5 5 4 ; 11 9 10 23 0 0 0 0 0 0 0 0 0 28 9 6 5 5 5 4 ; 7 8 8 16 34 0 0 0 0 0 0 0 0 11 7 6 5 5 4 4 ; 7 7 7 9 89 0 0 0 0 0 0 38 34 19 7 6 5 5 4 4 ; 6 6 7 8 11 10 13 15 0 0 13 11 9 12 6 5 5 5 4 4 ; 5 6 6 6 7 8 9 14 0 0 10 8 7 6 6 5 5 4 4 4 ; 5 5 6 6 6 7 7 10 41 14 8 7 6 6 5 5 5 4 4 4 ; 5 5 5 5 6 6 7 8 12 12 7 6 5 5 5 5 4 4 4 4 ; ] @test mandelbrotset(test_params, func) == correct_result_mandelbrot end @testset "GPU Set Generation" begin if CUDA_available gpu_test_params = SetParams(-1.0-1.0im, 1.0+1.0im, 10, 20.0, 4, true) func = (z,c) -> z^2 + c c = 0.30+0.53im correct_result_julia_gpu = [ 4 5 0 15 12 7 6 6 6 7 12 36 7 4 4 3 3 3 2 2 ; 4 6 10 0 0 11 0 8 8 0 0 0 7 5 4 3 3 3 2 2 ; 7 22 0 0 0 0 0 17 11 0 0 0 8 6 5 4 3 3 3 2 ; 0 15 0 0 0 0 0 0 69 31 0 14 14 8 7 4 3 3 3 2 ; 0 7 8 8 14 0 0 0 0 29 38 0 0 19 9 5 4 3 3 3 ; 5 5 6 7 10 23 27 0 0 0 0 22 0 12 7 5 4 3 3 3 ; 4 4 5 6 7 11 10 13 15 0 0 34 10 8 6 5 4 3 3 3 ; 4 4 4 5 6 7 8 11 0 0 0 0 13 8 6 5 4 4 3 3 ; 3 4 4 5 5 6 8 0 0 0 0 0 14 24 7 5 4 4 3 3 ; 3 4 4 4 5 6 0 0 0 0 0 0 0 0 7 5 4 4 3 3 ; 3 3 4 4 5 7 0 0 0 0 0 0 0 0 6 5 4 4 4 3 ; 3 3 4 4 5 7 24 14 0 0 0 0 0 8 6 5 5 4 4 3 ; 3 3 4 4 5 6 8 13 0 0 0 0 11 8 7 6 5 4 4 4 ; 3 3 3 4 5 6 8 10 34 0 0 15 13 10 11 7 6 5 4 4 ; 3 3 3 4 5 7 12 0 22 0 0 0 0 27 23 10 7 6 5 5 ; 3 3 3 4 5 9 19 0 0 38 29 0 0 0 0 14 8 8 7 0 ; 2 3 3 3 4 7 8 14 14 0 31 69 0 0 0 0 0 0 15 0 ; 2 3 3 3 4 5 6 8 0 0 0 11 17 0 0 0 0 0 22 7 ; 2 2 3 3 3 4 5 7 0 0 0 8 8 0 11 0 0 10 6 4 ; 2 2 3 3 3 4 4 7 36 12 7 6 6 6 7 12 15 0 5 4 ; ] @test juliaset(gpu_test_params, func, c) .|> Int == correct_result_julia_gpu correct_result_mandelbrot_gpu = [ 4 4 4 4 5 5 5 7 11 11 6 5 4 4 4 4 3 3 3 3 ; 4 4 5 5 5 6 6 9 40 13 7 6 5 5 4 4 4 3 3 3 ; 5 5 5 5 6 7 8 13 0 0 9 7 6 5 5 4 4 3 3 3 ; 5 5 6 7 10 9 12 14 0 0 12 10 8 11 5 4 4 4 3 3 ; 5 6 6 8 88 0 0 0 0 0 0 37 33 18 6 5 4 4 3 3 ; 6 7 7 15 33 0 0 0 0 0 0 0 0 10 6 5 4 4 3 3 ; 10 8 9 22 0 0 0 0 0 0 0 0 0 27 8 5 4 4 4 3 ; 0 18 12 0 0 0 0 0 0 0 0 0 0 0 7 5 4 4 4 3 ; 0 0 34 0 0 0 0 0 0 0 0 0 0 0 7 5 4 4 4 3 ; 0 0 0 0 0 0 0 0 0 0 0 0 0 9 6 5 4 4 4 3 ; 0 0 0 0 0 0 0 0 0 0 0 0 0 9 6 5 4 4 4 3 ; 0 0 34 0 0 0 0 0 0 0 0 0 0 0 7 5 4 4 4 3 ; 0 18 12 0 0 0 0 0 0 0 0 0 0 0 7 5 4 4 4 3 ; 10 8 9 22 0 0 0 0 0 0 0 0 0 27 8 5 4 4 4 3 ; 6 7 7 15 33 0 0 0 0 0 0 0 0 10 6 5 4 4 3 3 ; 5 6 6 8 88 0 0 0 0 0 0 37 33 18 6 5 4 4 3 3 ; 5 5 6 7 10 9 12 14 0 0 12 10 8 11 5 4 4 4 3 3 ; 5 5 5 5 6 7 8 13 0 0 9 7 6 5 5 4 4 3 3 3 ; 4 4 5 5 5 6 6 9 40 13 7 6 5 5 4 4 4 3 3 3 ; 4 4 4 4 5 5 5 7 11 11 6 5 4 4 4 4 3 3 3 3 ; ] @test mandelbrotset(gpu_test_params, func) .|> Int == correct_result_mandelbrot_gpu end end end
FractalAnimation
https://github.com/ErrolSeders/FractalAnimation.jl.git
[ "MIT" ]
1.1.0
fa3ac66572ddf2ae24b03b6b8e17b5dd52259af5
code
3082
""" HolidayJp The `HolidayJp` module provides features for detecting holiday in Japan. ```jldoctest julia> using Dates julia> HolidayJp.isholiday(Date(2018, 02, 23)) false julia> HolidayJp.isholiday(Date(2018, 12, 23)) true julia> HolidayJp.isholiday(Date(2019, 2, 23)) true julia> HolidayJp.isholiday(Date(2019, 12, 23)) false ``` """ module HolidayJp import Dates: Date, DateTime, Day, year, month, day import OrderedCollections: OrderedDict, rehash! import YAML """ HolidayJp.Holiday `Holiday` represents a holiday in Japan. """ Base.@kwdef struct Holiday date::Date week::String week_en::String name::String name_en::String end function Holiday(params::AbstractDict) Holiday(date=Date(params["date"]), week=string(params["week"]), week_en=string(params["week_en"]), name=string(params["name"]), name_en=string(params["name_en"])) end const HolidayDict = OrderedDict{Date, Holiday} function load_holidays() data_dir = joinpath(dirname(@__DIR__), "data") dataset = YAML.load_file(joinpath(data_dir, "holidays_detailed.yml"); dicttype=OrderedDict{Any, Any}) HolidayDict(date => Holiday(params) for (date, params) in dataset) end const HOLIDAYS = load_holidays() _datelike(d::Date) = d _datelike(dl::T) where {T} = Date(year(dl), month(dl), day(dl)) """ isholiday(d) -> Bool isholiday(year, month, day) -> Bool Return `true` if the given date is a holiday in Japan. The date can be specified using a date-like object or by providing the year, month, and day separately. """ isholiday(d::Date) = haskey(HOLIDAYS, d) isholiday(year::I, month::I, day::I) where {I<:Integer} = isholiday(Date(year, month, day)) isholiday(dl::DateLike) where {DateLike} = isholiday(_datelike(dl)) """ getholiday(d) -> Union{Nothing,HolidayJp.Holiday} getholiday(year, month, day) -> Union{Nothing,HolidayJp.Holiday} Return the holiday information for the given date. When the given date is not a holiday in Japan, `nothing` is returned. The date can be specified using a date-like object or by providing the year, month, and day separately. """ getholiday(d::Date) = get(HOLIDAYS, d, nothing) getholiday(year::I, month::I, day::I) where {I<:Integer} = getholiday(Date(year, month, day)) getholiday(dl::DateLike) where {DateLike} = getholiday(_datelike(dl)) """ between(lower_limit, upper_limit) -> Vector{HolidayJp.Holiday} Return a vector of `HolidayJp.Holiday` objects that fall within the date range defined by the `lower_limit` and the `upper_limit`. The `lower_limit` and the `upper_limit` can be specified using a date-like objects. """ function between(lower_limit::Date, upper_limit::Date) if lower_limit > upper_limit error("lower_limit must be earlier than upper_limit (lower_limit=$(lower_limit), upper_limit=$(upper_limit))") end [h for h in values(HOLIDAYS) if lower_limit <= h.date <= upper_limit] end between(ll::LL, ul::UL) where {LL, UL} = between(_datelike(ll), _datelike(ul)) function __init__() rehash!(HOLIDAYS) end end
HolidayJp
https://github.com/mrkn/HolidayJp.jl.git
[ "MIT" ]
1.1.0
fa3ac66572ddf2ae24b03b6b8e17b5dd52259af5
code
415
module BruteForceTest using Test import HolidayJp: HolidayJp, YAML import Dates: Day data_dir = joinpath(dirname(@__DIR__), "data") data = YAML.load_file(joinpath(data_dir, "holidays.yml")) date_begin, date_end = extrema(keys(data)) for d in date_begin:Day(1):date_end h = haskey(data, d) @testset "$(d) is$(h ? "" : " not") a holiday" begin @test HolidayJp.isholiday(d) === h end end end
HolidayJp
https://github.com/mrkn/HolidayJp.jl.git
[ "MIT" ]
1.1.0
fa3ac66572ddf2ae24b03b6b8e17b5dd52259af5
code
4003
module TestHolidayJp using Test import HolidayJp import Dates: Dates, Date, DateTime struct DateLike year month day end Dates.year(d::DateLike) = d.year Dates.month(d::DateLike) = d.month Dates.day(d::DateLike) = d.day @testset "HolidayJp.jl" begin @testset "isholiday" begin @testset "when the given object is a Date" begin @test HolidayJp.isholiday(Date("2000-01-01")) === true @test HolidayJp.isholiday(Date("2000-01-02")) === false end @testset "when the given object is a DateTime" begin @test HolidayJp.isholiday(DateTime("2000-01-01", "yyyy-mm-dd")) === true @test HolidayJp.isholiday(DateTime("2000-01-02", "yyyy-mm-dd")) === false end @testset "when the given object responds to Dates.year, Dates.month, and Dates.day" begin @test HolidayJp.isholiday(DateLike(2000, 1, 1)) === true @test HolidayJp.isholiday(DateLike(2000, 1, 2)) === false end @testset "when the year, the month, and the day are specified separately" begin @test HolidayJp.isholiday(2000, 1, 1) === true @test HolidayJp.isholiday(2000, 1, 2) === false end end @testset "getholiday" begin @testset "returns a Holiday when the given date is a holiday" begin @test HolidayJp.getholiday(Date("2000-01-01")) isa HolidayJp.Holiday @test HolidayJp.getholiday(DateTime("2000-01-01", "yyyy-mm-dd")) isa HolidayJp.Holiday @test HolidayJp.getholiday(DateLike(2000, 1, 1)) isa HolidayJp.Holiday @test HolidayJp.getholiday(2000, 1, 1) isa HolidayJp.Holiday end @testset "returns nothing when the given Date is not a holiday" begin @test HolidayJp.getholiday(Date("2000-01-02")) === nothing @test HolidayJp.getholiday(DateTime("2000-01-02", "yyyy-mm-dd")) === nothing @test HolidayJp.getholiday(DateLike(2000, 1, 2)) === nothing @test HolidayJp.getholiday(2000, 1, 2) === nothing end end @testset "between" begin expected = [ Date("2000-01-01"), Date("2000-01-10"), Date("2000-02-11"), Date("2000-03-20"), Date("2000-04-29"), Date("2000-05-03"), Date("2000-05-04"), Date("2000-05-05"), Date("2000-07-20"), Date("2000-09-15"), Date("2000-09-23"), Date("2000-10-09"), Date("2000-11-03"), Date("2000-11-23"), Date("2000-12-23") ] @testset "returns all holidays when two Date objects are passed" begin result = HolidayJp.between(Date("2000-01-01"), Date("2000-12-31")) @test result isa Vector{HolidayJp.Holiday} @test [h.date::Date for h in result] == expected end @testset "accepts date-like objects as its arguments" begin result = HolidayJp.between(Date(2000, 1, 1), DateLike(2000, 12, 31)) @test [h.date::Date for h in result] == expected result = HolidayJp.between(DateLike(2000, 1, 1), Date(2000, 12, 31)) @test [h.date::Date for h in result] == expected result = HolidayJp.between(DateLike(2000, 1, 1), DateLike(2000, 12, 31)) @test [h.date::Date for h in result] == expected end @testset "returns Holiday[] when the given range are out of scope" begin @test HolidayJp.Holiday[] == HolidayJp.between(Date("1900-01-01"), Date("1900-12-31")) year = Dates.year(Dates.today()) + 500 @test HolidayJp.Holiday[] == HolidayJp.between(Date(year, 1, 1), Date(year, 12, 31)) end @testset "raise error when the lower limit is future than the upper limit" begin @test_throws ErrorException HolidayJp.between(Date("2000-01-02"), Date("2000-01-01")) end end end end include("bruteforce.jl")
HolidayJp
https://github.com/mrkn/HolidayJp.jl.git
[ "MIT" ]
1.1.0
fa3ac66572ddf2ae24b03b6b8e17b5dd52259af5
docs
1020
# HolidayJp [![Build Status](https://github.com/mrkn/HolidayJp.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/mrkn/HolidayJp.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://coveralls.io/repos/github/mrkn/HolidayJp.jl/badge.svg?branch=main)](https://coveralls.io/github/mrkn/HolidayJp.jl?branch=main) ## Description HolidayJp provides functions related to Japanese holidays for Julia language. This uses the Japanese holiday dataset in [holiday_jp/holiday_jp](https://github.com/holiday-jp/holiday_jp). ## Usage ```julia import Dates: Date import HolidadyJp HolidayJP.isholiday(Date("2024-02-23")) # true HolidayJp.isholiday(2024, 12, 23) # false HolidayJp.getholiday(2024, 2, 23).name # "天皇誕生日" HolidayJp.getholiday(2024, 12, 23) # nothing [h.date for h in HolidayJp.between(Date("2024-01-01"), Date("2025-01-01"))] # 21-element Vector{Date}: # 2024-01-01 # 2024-01-08 # ... # 2024-11-23 ``` ## Installation ``` julia> ] add HolidayJp ``` ## LICENSE MIT
HolidayJp
https://github.com/mrkn/HolidayJp.jl.git
[ "MIT" ]
1.1.0
fa3ac66572ddf2ae24b03b6b8e17b5dd52259af5
docs
1484
# holiday_jp [![test](https://github.com/holiday-jp/holiday_jp/workflows/test/badge.svg)](https://github.com/holiday-jp/holiday_jp/actions) Japanese holiday datasets ## holiday_jp Versions | Version | 振替休日の表記 | | --- | --- | | v0.x | `振替休日` | | v1.x | `勤労感謝の日 振替休日` | | Version | 休日の表記 | | --- | --- | | v0.x | `国民の休日` | | v1.x | `国民の休日`, `休日` | | >= v1.2.2 | `休日` | ## Implementations | Implementation | Release version using holiday_jp v0.x | Release version using holiday_jp v1.x | | --- | --- | --- | | [Ruby](https://github.com/holiday-jp/holiday_jp-ruby) | v0.7.x | - | | [JavaScript](https://github.com/holiday-jp/holiday_jp-js) | v1.x | v2.x | | [PHP](https://github.com/holiday-jp/holiday_jp-php) | v1.x | v2.x | | [Java](https://github.com/holiday-jp/holiday_jp-java) | - | v2.x | | [Swift](https://github.com/holiday-jp/holiday_jp-swift) | v0.1.x | v0.2.x | | [Go](https://github.com/holiday-jp/holiday_jp-go) | - | master | | [Elixir](https://github.com/holiday-jp/holiday_jp-elixir) | v0.2.2 | >= v0.2.3 | | [C#.net](https://github.com/holiday-jp/holiday_jp-csharp) | - | v1.x | | [Python](https://github.com/holiday-jp/holiday_jp-python) | - | latest | ## "Datasets" idea [Project Woothee](https://woothee.github.io/) ## Test by syukujitsu.csv syukujitsu.csv 出典:内閣府ホームページ ( https://www8.cao.go.jp/chosei/shukujitsu/gaiyou.html ) ## Test by Google Calendar API https://calendar.google.com/calendar/embed?src=ja.japanese%[email protected]
HolidayJp
https://github.com/mrkn/HolidayJp.jl.git
[ "MIT" ]
1.0.0
9705b15a0706290337e49d6edb3f1d9e44fa21dd
code
602
using TruncatedStreams using Documenter DocMeta.setdocmeta!(TruncatedStreams, :DocTestSetup, :(using TruncatedStreams); recursive=true) makedocs(; modules=[TruncatedStreams], authors="Phil Killewald <[email protected]> and contributors", sitename="TruncatedStreams.jl", format=Documenter.HTML(; canonical="https://reallyasi9.github.io/TruncatedStreams.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/reallyasi9/TruncatedStreams.jl", devbranch="main", )
TruncatedStreams
https://github.com/reallyasi9/TruncatedStreams.jl.git
[ "MIT" ]
1.0.0
9705b15a0706290337e49d6edb3f1d9e44fa21dd
code
216
module TruncatedStreams export TruncatedIO export FixedLengthIO export SentinelIO @static if VERSION < v"1.7" include("compat.jl") end include("io.jl") include("fixedlengthio.jl") include("sentinelio.jl") end
TruncatedStreams
https://github.com/reallyasi9/TruncatedStreams.jl.git
[ "MIT" ]
1.0.0
9705b15a0706290337e49d6edb3f1d9e44fa21dd
code
373
# circshift!, taken straight from Julia source, modified to only use the signature we need function circshift!(a::Vector{UInt8}, shift::Integer) n = length(a) n == 0 && return a shift = mod(shift, n) shift == 0 && return a l = lastindex(a) reverse!(a, firstindex(a), l-shift) reverse!(a, l-shift+1, lastindex(a)) reverse!(a) return a end
TruncatedStreams
https://github.com/reallyasi9/TruncatedStreams.jl.git
[ "MIT" ]
1.0.0
9705b15a0706290337e49d6edb3f1d9e44fa21dd
code
2828
""" FixedLengthIO(io, length) <: TruncatedIO A truncated source that reads `io` up to `length` bytes. ```jldoctest fixedlengthio_1 julia> io = IOBuffer(collect(0x00:0xff)); julia> fio = FixedLengthIO(io, 10); julia> read(fio) 10-element Vector{UInt8}: 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 julia> eof(fio) true ``` As soon as a read from a `FixedLengthIO` object would read past `length` bytes of the underlying IO stream, EOF is signalled, potentially leading to an `EOFError` being thrown. ```jldoctest fixedlengthio_1 julia> read(fio, Int) ERROR: EOFError: read end of file [...] ``` Seeking does not affect the length at which the stream is truncated, but may affect how many bytes are available to read. ```jldoctest fixedlengthio_1 julia> seek(fio, 8); read(fio) 2-element Vector{UInt8}: 0x08 0x09 ``` Writing to a `FixedLengthIO` object does not affect the length at which the stream is truncated, but may affect how many bytes are available to read. ```jldoctest fixedlengthio_2 julia> io = IOBuffer(collect(0x00:0x05); read=true, write=true); fio = FixedLengthIO(io, 10); julia> read(fio) 6-element Vector{UInt8}: 0x00 0x01 0x02 0x03 0x04 0x05 julia> write(fio, collect(0x06:0xff)); julia> seekstart(fio); # writing advances the IOBuffer's read pointer julia> read(fio) 10-element Vector{UInt8}: 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 ``` """ mutable struct FixedLengthIO{S<:IO} <: TruncatedIO wrapped::S length::Int remaining::Int FixedLengthIO(io::S, length::Integer) where {S} = new{S}(io, length, length) end unwrap(s::FixedLengthIO) = s.wrapped Base.bytesavailable(s::FixedLengthIO) = min(s.remaining, bytesavailable(unwrap(s))) Base.eof(s::FixedLengthIO) = eof(unwrap(s)) || s.remaining <= 0 function Base.unsafe_read(s::FixedLengthIO, p::Ptr{UInt8}, n::UInt) # note that the convention from IOBuffer is to read as much as possible first, # then throw EOF if the requested read was beyond the number of bytes available. available = bytesavailable(s) to_read = min(available, n) unsafe_read(unwrap(s), p, to_read) s.remaining -= to_read if to_read < n throw(EOFError()) end return nothing end function Base.seek(s::FixedLengthIO, n::Integer) pos = clamp(n, 0, s.length) s.remaining = s.length - pos return seek(unwrap(s), n) end Base.seekend(s::FixedLengthIO) = seek(s, s.length) function Base.skip(s::FixedLengthIO, n::Integer) # negative numbers will add bytes back to bytesremaining bytes = clamp(Int(n), s.remaining - s.length, s.remaining) return seek(s, position(s) + bytes) end function Base.reset(s::FixedLengthIO) pos = reset(unwrap(s)) seek(s, pos) # seeks the underlying stream as well, but that should be a noop return pos end
TruncatedStreams
https://github.com/reallyasi9/TruncatedStreams.jl.git
[ "MIT" ]
1.0.0
9705b15a0706290337e49d6edb3f1d9e44fa21dd
code
2342
""" TruncatedIO <: IO Wraps a streaming IO object that reads only as much as should be read and not a byte more. Objects inheriting from this abstract type pass along all IO methods to the wrapped stream except for `bytesavailable(io)` and `eof(io)`. Inherited types _must_ implement: - `TruncatedStreams.unwrap(::TruncatedIO)::IO`: return the wrapped IO stream. - `Base.eof(::TruncatedIO)::Bool`: report whether the stream cannot produce any more bytes. In order to implement truncation, some number of these methods will likely need to be implemented: - `Base.unsafe_read(::TruncatedIO, p::Ptr{UInt8}, n::UInt)::Nothing`: copy `n` bytes from the stream into memory pointed to by `p`. - `Base.read(::TruncatedIO, T::Type)::T`: read and return an object of type `T` from the stream. - `Base.bytesavailable(::TruncatedIO)::Int`: report the number of bytes available to read from the stream until EOF or a buffer refill. - `Base.seek(::TruncatedIO, p::Integer)` and `Base.seekend(::TruncatedIO)`: seek stream to position `p` or end of stream. - `Base.reset(::TruncatedIO)`: reset a marked stream to the saved position. - `Base.reseteof(::TruncatedIO)::Nothing`: reset EOF status. Note that writing to the stream does not affect truncation. """ abstract type TruncatedIO <: IO end """ unwrap(s<:TruncatedIO) -> IO Return the wrapped source. """ function unwrap end # unary functions for func in ( :lock, :unlock, :isopen, :close, :flush, :position, :mark, :unmark, :reset, :ismarked, :isreadable, :iswritable, :seekend, ) @eval Base.$func(s::TruncatedIO) = Base.$func(unwrap(s)) end # newer functions for half-duplex close @static if VERSION >= v"1.8" for func in (:closewrite,) @eval Base.$func(s::TruncatedIO) = Base.$func(unwrap(s)) end end # n-ary functions Base.seek(s::TruncatedIO, n::Integer) = seek(unwrap(s), n) Base.skip(s::TruncatedIO, n::Integer) = skip(unwrap(s), n) Base.unsafe_read(s::TruncatedIO, p::Ptr{UInt8}, n::UInt) = unsafe_read(unwrap(s), p, n) Base.unsafe_write(s::TruncatedIO, p::Ptr{UInt8}, n::UInt) = unsafe_write(unwrap(s), p, n) # required to override byte-level reading of objects by delegating to unsafe_read function Base.read(s::TruncatedIO, ::Type{UInt8}) r = Ref{UInt8}() unsafe_read(s, r, 1) return r[] end
TruncatedStreams
https://github.com/reallyasi9/TruncatedStreams.jl.git
[ "MIT" ]
1.0.0
9705b15a0706290337e49d6edb3f1d9e44fa21dd
code
8176
""" SentinelIO(io, sentinel) <: TruncatedIO A truncated source that reads `io` until `sentinel` is found. ```jldoctest sentinelio_1 julia> io = IOBuffer(collect(0x00:0xff)); julia> sio = SentinelIO(io, [0x0a, 0x0b]); julia> read(sio) 10-element Vector{UInt8}: 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 julia> eof(sio) true ``` As soon as a read from a `SentinelIO` object would read the start of a byte sequence matching `sentinel` from the underlying IO stream, EOF is signalled, potentially leading to an `EOFError` being thrown. ```jldoctest sentinelio_1 julia> read(sio, Int) ERROR: EOFError: read end of file [...] ``` Seeking does not affect reading of the sentinel, but may affect how many bytes are available to read. ```jldoctest sentinelio_1 julia> seek(sio, 8); read(sio) 2-element Vector{UInt8}: 0x08 0x09 ``` Writing to a `SentinelIO` object does not affect the length at which the stream is truncated, but may affect how many bytes are available to read. ```jldoctest sentinelio_2 julia> io = IOBuffer(collect(0x00:0x07); read=true, write=true); sio = SentinelIO(io, [0x06, 0x07]); julia> read(sio) 6-element Vector{UInt8}: 0x00 0x01 0x02 0x03 0x04 0x05 julia> write(sio, collect(0x01:0xff)); julia> seekstart(sio); # writing advances the IOBuffer's read pointer julia> read(sio) # still the same output because the sentinel is still there 6-element Vector{UInt8}: 0x00 0x01 0x02 0x03 0x04 0x05 ``` Detection of eof can be reset with the `Base.reseteof()` method. Use this if the sentinel that was read is determined upon further inspection to be bogus. ```jldoctest sentinelio_2 julia> Base.reseteof(sio) # that last sentinel was fake, so reset EOF and read again julia> read(sio) # returns the first sentinel found and continues to read until the next one is found 7-element Vector{UInt8}: 0x06 0x07 0x01 0x02 0x03 0x04 0x05 ``` !!! note If the wrapped stream does not contain a sentinel, reading to the end of the stream will throw `EOFError`. ```jldoctest sentinelio_3 julia> io = IOBuffer(collect(0x00:0x07)); sio = SentinelIO(io, [0xff, 0xfe]); julia> read(sio) ERROR: EOFError: read end of file [...] ``` """ mutable struct SentinelIO{S<:IO} <: TruncatedIO wrapped::S sentinel::Vector{UInt8} buffer::Vector{UInt8} failure_function::Vector{Int} skip_next_eof::Bool buffer_length_at_mark::Int function SentinelIO(io::S, sentinel::AbstractVector{UInt8}) where {S<:IO} sen = Vector{UInt8}(sentinel) # so I have a real Vector ns = length(sen) # generate the failure function for the Knuth–Morris–Pratt algorithm ff = Vector{Int}(undef, ns) ff[1] = 0 pos = 2 cnd = 1 while pos <= ns if sentinel[pos] == sentinel[cnd] ff[pos] = ff[cnd] else ff[pos] = cnd while cnd > 0 && ff[pos] != ff[cnd] cnd = ff[cnd] end end pos += 1 cnd += 1 end # lazily fill the buffer only when needed buffer = UInt8[] return new{S}(io, sen, buffer, ff, false, 0) end end SentinelIO(io::IO, sentinel::AbstractString) = SentinelIO(io, codeunits(sentinel)) unwrap(s::SentinelIO) = s.wrapped # count the number of bytes before a prefix match on the next sentinel function count_safe_bytes(s::SentinelIO, stop_early::Bool=false) nb = length(s.buffer) if eof(unwrap(s)) # make sure the last bytes in the buffer can be read if s.buffer != s.sentinel return nb else return 0 end end # an empty buffer needs to be filled before searching for the sentinel if nb < length(s.sentinel) nb = readbytes!(unwrap(s), s.buffer, length(s.sentinel)) end # search the buffer for the longest prefix match of the sentinel jb = 1 # buffer index ks = 1 # sentinel index while jb <= nb if s.sentinel[ks] == s.buffer[jb] # byte matches sentinel, move to next jb += 1 ks += 1 else if stop_early return jb end # byte does not match, determine where in the sentinel to restart the search ks = s.failure_function[ks] if ks == 0 # next byte not in sentinel, reset to beginning jb += 1 ks = 1 end end end # at this point, ks-1 bytes have matched at the end of the buffer remaining = nb - ks + 1 if remaining == 0 && s.skip_next_eof return 1 # allow a single byte to be read else return remaining end end Base.bytesavailable(s::SentinelIO) = count_safe_bytes(s) Base.eof(s::SentinelIO) = count_safe_bytes(s, true) == 0 # fill the first n bytes of the buffer from the wrapped stream, overwriting what is there function fill_buffer(s::SentinelIO, n::Integer=length(s.sentinel)) to_read = min(n, length(s.sentinel)) nb = readbytes!(unwrap(s), s.buffer, to_read) return nb end function Base.unsafe_read(s::SentinelIO, p::Ptr{UInt8}, n::UInt) # read available bytes, checking for sentinel each time to_read = n ptr = 0 available = bytesavailable(s) while to_read > 0 && available > 0 this_read = min(to_read, available) # buffer: [ safe_1, safe_2, ..., safe_(available), unsafe_1, unsafe_2, ..., unsafe_(end)] buf = s.buffer GC.@preserve buf unsafe_copyto!(p + ptr, pointer(buf), this_read) ptr += this_read n_read = fill_buffer(s, this_read) # buffer: [ new_1, new_2, ..., new_(this_read), safe_(this_read+1), ..., safe_(available), unsafe_1, unsafe_2, ..., unsafe_(end)] circshift!(buf, -this_read) # buffer: [ safe_(this_read + 1), safe_(this_read + 2), ..., safe_(available), unsafe_1, unsafe_2, ..., unsafe_(end), new_1, new_2, ..., new_(this_read)] # a successful read of anything resets the eof skip s.skip_next_eof = false if n_read < this_read # this happens because we fell off the face of the planet, so clear the buffer copyto!(s.buffer, s.sentinel) throw(EOFError()) end to_read -= this_read available = bytesavailable(s) end if to_read > 0 # this happens because we couldn't read everything we wanted to read, so clear the buffer copyto!(s.buffer, s.sentinel) throw(EOFError()) end return nothing end Base.position(s::SentinelIO) = position(unwrap(s)) - length(s.buffer) # lie about where we are in the stream function Base.seek(s::SentinelIO, n::Integer) # seeking backwards is only possible if the wrapped stream allows it. # seeking forwards is easier done as reading and dumping data. pos = max(n, 0) p = position(s) bytes = pos - p if bytes <= 0 seek(unwrap(s), pos) # fill the buffer again, which should be guaranteed to work, but check just in case nb = fill_buffer(s) if nb != length(s.sentinel) throw(EOFError()) end else # drop remainder on the floor read(s, bytes) end return s end Base.seekend(s::SentinelIO) = read(s) # read until the end Base.skip(s::SentinelIO, n::Integer) = seek(s, position(s) + n) function Base.mark(s::SentinelIO) pos = mark(unwrap(s)) # lie about where we are in the stream # noting that the length of the buffer might change nb = length(s.buffer) s.buffer_length_at_mark = nb return pos - nb end function Base.reset(s::SentinelIO) pos = reset(unwrap(s)) # refill the buffer manually, which should be guaranteed to work, but check just in case seek(unwrap(s), pos - s.buffer_length_at_mark) nb = fill_buffer(s) if nb != length(s.sentinel) throw(EOFError()) end # lie about where the current position is return pos - s.buffer_length_at_mark end function Base.reseteof(s::SentinelIO) Base.reseteof(unwrap(s)) s.skip_next_eof = true return nothing end
TruncatedStreams
https://github.com/reallyasi9/TruncatedStreams.jl.git
[ "MIT" ]
1.0.0
9705b15a0706290337e49d6edb3f1d9e44fa21dd
code
6182
using TestItemRunner @testitem "Ambiguities" begin @test isempty(detect_ambiguities(Base, Core, TruncatedStreams)) end @testitem "FixedLengthIO" begin using Random rng = MersenneTwister(42) content_length = 1024 content = rand(rng, UInt8, content_length) fixed_length = 16 io = IOBuffer(content; read=true, write=true) fio = FixedLengthIO(io, fixed_length) @test bytesavailable(fio) == fixed_length # read < fixed_length bytes n = 8 a = read(fio, n) @test a == first(content, n) @test bytesavailable(fio) == fixed_length - n # read everything else b = read(fio) @test b == content[n+1:fixed_length] @test bytesavailable(fio) == 0 @test eof(fio) # try reading again c = read(fio) @test isempty(c) @test eof(fio) # try really hard to read again d = read(fio, 1) @test isempty(d) @test eof(fio) # try really, really hard to read again @test_throws EOFError read(fio, UInt8) @test eof(fio) # seek and try again seek(fio, n) @test bytesavailable(fio) == fixed_length - n e = read(fio) @test e == content[n+1:fixed_length] @test eof(fio) # seek more and try again seekstart(fio) @test bytesavailable(fio) == fixed_length f = read(fio) @test f == first(content, fixed_length) @test eof(fio) # skip and try again skip(fio, -n) @test bytesavailable(fio) == n g = read(fio) @test g == content[n+1:fixed_length] @test eof(fio) # pass through mark, reset, and unmark seek(fio, n) @test !ismarked(fio) @test mark(fio) == n @test ismarked(fio) seekstart(fio) @test read(fio) == first(content, fixed_length) @test reset(fio) == n @test read(fio) == content[n+1:fixed_length] @test !ismarked(fio) @test_throws ArgumentError reset(fio) @test unmark(fio) == false mark(fio) @test ismarked(fio) @test unmark(fio) == true @test !ismarked(fio) # pass through position seek(fio, n) @test position(fio) == n seekstart(fio) @test position(fio) == 0 seekend(fio) @test position(fio) == fixed_length end @testitem "SentinelIO" begin using Random rng = MersenneTwister(42) content_length = 1024 content = rand(rng, UInt8, content_length) sentinel_length = 16 sentinel = rand(rng, UInt8, sentinel_length) fixed_length = 256 content[fixed_length+1:fixed_length+sentinel_length] = sentinel # add a second sentinel for reseteof test content[fixed_length*2+sentinel_length+1:fixed_length*2+sentinel_length*2] = sentinel io = IOBuffer(content) sio = SentinelIO(io, sentinel) @test bytesavailable(sio) <= fixed_length # likely going to be length(sentinel), but always <= fixed_length # read < fixed_length bytes n = 8 a = read(sio, n) @test a == first(content, n) @test bytesavailable(sio) <= fixed_length - n # read everything else b = read(sio) @test b == content[n+1:fixed_length] @test bytesavailable(sio) == 0 @test eof(sio) # try reading again c = read(sio) @test isempty(c) @test eof(sio) # try really hard to read again d = read(sio, 1) @test isempty(d) @test eof(sio) # try really, really hard to read again @test_throws EOFError read(sio, UInt8) @test eof(sio) # seek and try again seek(sio, n) @test bytesavailable(sio) <= fixed_length - n e = read(sio) @test e == content[n+1:fixed_length] @test eof(sio) # seek more and try again seekstart(sio) @test bytesavailable(sio) <= fixed_length f = read(sio) @test f == first(content, fixed_length) @test eof(sio) # skip and try again skip(sio, -n) @test bytesavailable(sio) <= n g = read(sio) @test g == content[fixed_length-n+1:fixed_length] @test eof(sio) # pass through mark, reset, and unmark seek(sio, n) @test !ismarked(sio) @test mark(sio) == n @test ismarked(sio) seekstart(sio) @test read(sio) == first(content, fixed_length) @test reset(sio) == n @test read(sio) == content[n+1:fixed_length] @test !ismarked(sio) @test_throws ArgumentError reset(sio) @test unmark(sio) == false mark(sio) @test ismarked(sio) @test unmark(sio) == true @test !ismarked(sio) # pass through position seek(sio, n) @test position(sio) == n seekstart(sio) @test position(sio) == 0 seekend(sio) @test position(sio) == fixed_length # check reseteof and find next sentinel @test eof(sio) Base.reseteof(sio) @test !eof(sio) @test read(sio) == content[fixed_length+1:2*fixed_length + sentinel_length] @test eof(sio) # clear the second sentinel and try to read to end, which should cause an error because the last sentinel was never found Base.reseteof(sio) @test !eof(sio) @test_throws EOFError read(sio) @test eof(sio) # clearing the second sentinel should keep us at eof Base.reseteof(sio) @test eof(sio) @test isempty(read(sio)) end @testitem "SentinelIO lazy buffer" begin using Random rng = MersenneTwister(42) content_length = 1024 content = rand(rng, UInt8, content_length) sentinel_length = 16 sentinel = rand(rng, UInt8, sentinel_length) fixed_length = 256 content[fixed_length+1:fixed_length+sentinel_length] = sentinel io = IOBuffer(content) sio = SentinelIO(io, sentinel) # immediately check position, which should be 0, even though the buffer hasn't been filled yet @test position(sio) == 0 # mark this position, read to fill the buffer, then reset to see if the position is correct @test mark(sio) == 0 a = read(sio) @test a == content[begin:fixed_length] @test position(sio) == fixed_length @test reset(sio) == 0 @test position(sio) == 0 end @testitem "SentinelIO strings" begin content = "Hello, Julia!" sentinel = SubString(content, 6:7) io = IOBuffer(content) sio = SentinelIO(io, sentinel) @test read(sio, String) == "Hello" @test eof(sio) end @run_package_tests verbose = true
TruncatedStreams
https://github.com/reallyasi9/TruncatedStreams.jl.git
[ "MIT" ]
1.0.0
9705b15a0706290337e49d6edb3f1d9e44fa21dd
docs
4306
# TruncatedStreams [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://reallyasi9.github.io/TruncatedStreams.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://reallyasi9.github.io/TruncatedStreams.jl/dev/) [![Build Status](https://github.com/reallyasi9/TruncatedStreams.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/reallyasi9/TruncatedStreams.jl/actions/workflows/CI.yml?query=branch%3Amain) > "...where ignorance is bliss, 'tis folly to be wise" > > _-Thomas Gray, "Ode on a Distant Prospect of Eton College"_ ## Synopsis ```julia using TruncatedStreams io = IOBuffer(collect(0x00:0xff)) fixed_io = FixedLengthIO(io, 10) # only read the first 10 bytes @assert length(read(fixed_io)) == 10 @assert eof(fixed_io) == true @assert eof(io) == false sentinel_io = SentinelIO(io, [0x10, 0x11]) # only read until the sentinel is read @assert length(read(sentinel_io)) == 5 @assert eof(sentinel_io) == true @assert eof(io) == false close(io) ``` ## Lie to me Julia basically offers two methods for reading some but not all the bytes from an IO object: - `read(::IO, ::Integer)`, which reads up to some number of bytes from an IO object, allocating and appending to a `Vector{UInt8}` to hold everything it reads; or - `readuntil(::IO, ::Vector{UInt8})`, which reads bytes from an IO object until a sentinel vector is found, again allocating and appending to a `Vector{UInt8}` to hold everything it reads. But what if you find yourself in the following situation: 1. You want to read values of many different types from an IO object. 2. You know you can safely read some number of bytes from the IO object (either a fixed number or until some sentinel is reached). 3. You do not want to (or cannot) read everything from the IO object into memory at once. This may seem like a contrived situation, but consider an IO object representing a concatenated series of very large files, like what you might see in a TAR or ZIP archive: 1. You want to treat each file in the archive like a file on disk, reading an arbitrary number of values of arbitrary types from the file. 2. The file either starts with a header that tells you how many bytes long the file is or ends with a sentinel so you know when to stop reading. 3. You do not want to (or cannot) read the entire file into memory before parsing. Enter `TruncatedStreams`. This package exports types that inherit from `Base.IO` and wrap other `Base.IO` objects with one purpose in mind: to lie about EOF. This means you can wrap your IO object and blindly read from it until it signals EOF, just like you would any other IO object. And, if the wrapped IO object supports it, you can write to the stream, seek to a position, skip bytes, mark and reset positions, or do whatever basic IO operation you can think of and not have to worry about whether you remembered to add or subtract the right number of bytes from your running tally, or whether your buffered read accidentally captured half of the sentinel at the end. Abstraction is ignorance, and ignorance is bliss. ## Installation ```julia using Pkg; Pkg.install("TruncatedStreams") ``` ## Use ### `FixedLengthIO` `FixedLengthIO` wraps an `IO` object and will read from it until a certain number of bytes is read, after which `FixedLengthIO` will act as if it has reach end of file: ```julia julia> using TruncatedStreams julia> io = IOBuffer(collect(0x00:0xff)); julia> fio = FixedLengthIO(io, 10); # Only read the next 10 bytes julia> read(fio, UInt64) # First 8 bytes 0x0706050403020100 julia> read(fio) # Everything else 2-element Vector{UInt8}: 0x08 0x09 julia> eof(fio) # It's a lie, but it's a useful one! true ``` ### `SentinelIO` `SentinelIO` wraps an `IO` object and will read from in until a sentinel is found, after which `SentinelIO` will act as if it has reach end of file: ```julia julia> using TruncatedStreams julia> io = IOBuffer(collect(0x00:0xff)); julia> sio = SentinelIO(io, [0x10, 0x11, 0x12]); # Only read until [0x10, 0x11, 0x12] is found julia> read(sio, UInt64) # First 8 bytes 0x0706050403020100 julia> read(sio) # Everything else 8-element Vector{UInt8}: 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f julia> eof(sio) # It's a lie, but it's a useful one! true ```
TruncatedStreams
https://github.com/reallyasi9/TruncatedStreams.jl.git
[ "MIT" ]
1.0.0
9705b15a0706290337e49d6edb3f1d9e44fa21dd
docs
218
```@meta CurrentModule = TruncatedStreams ``` # TruncatedStreams Documentation for [TruncatedStreams](https://github.com/reallyasi9/TruncatedStreams.jl). ```@index ``` ```@autodocs Modules = [TruncatedStreams] ```
TruncatedStreams
https://github.com/reallyasi9/TruncatedStreams.jl.git
[ "MIT" ]
0.1.13
05ba0d07cd4fd8b7a39541e31a7b0254704ea581
code
711
using CloseOpenIntervals using Documenter DocMeta.setdocmeta!(CloseOpenIntervals, :DocTestSetup, :(using CloseOpenIntervals); recursive=true) makedocs(; modules=[CloseOpenIntervals], authors="chriselrod <[email protected]> and contributors", repo="https://github.com/JuliaSIMD/CloseOpenIntervals.jl/blob/{commit}{path}#{line}", sitename="CloseOpenIntervals.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://JuliaSIMD.github.io/CloseOpenIntervals.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/JuliaSIMD/CloseOpenIntervals.jl", devbranch = "main", )
CloseOpenIntervals
https://github.com/JuliaSIMD/CloseOpenIntervals.jl.git
[ "MIT" ]
0.1.13
05ba0d07cd4fd8b7a39541e31a7b0254704ea581
code
4568
module CloseOpenIntervals if isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol("@max_methods")) @eval Base.Experimental.@max_methods 1 end using Static: StaticInt, Zero, One export CloseOpen, SafeCloseOpen const IntegerType = Union{Integer,StaticInt} abstract type AbstractCloseOpen{L <: IntegerType, U <: IntegerType} <: AbstractUnitRange{Int} end for T ∈ (:CloseOpen,:SafeCloseOpen) @eval begin struct $T{L <: IntegerType, U <: IntegerType} <: AbstractCloseOpen{L,U} start::L upper::U @inline $T{L,U}(l::L,u::U) where {L <: IntegerType, U <: IntegerType} = new{L,U}(l,u) end @inline $T(s::S, u::U) where {S,U} = $T{S,U}(s, u) @inline $T(len::T) where {T<:IntegerType} = $T{Zero,T}(Zero(), len) end end """ CloseOpen([start=0], U) <: AbstractUnitRange{Int} SafeCloseOpen([start=0], U) <: AbstractUnitRange{Int} Define close-open unit ranges, i.e. `CloseOpen(0,10)` iterates from from `0:9`. Close-open ranges can be more convenient in some circumstances, e.g. when partitioning a larger array. ```julia function foo(x) nt = Threads.nthreads() d, r = divrem(length(x), nt) i = firstindex(x) Threads.@sync for j in 1:nt stop = i + d + (r >= j) Threads.@spawn bar!(\$(@view(x[CloseOpen(i, stop)]))) i = stop end end ``` This saves a few `-1`s on the ends of the ranges if using a normal unit range. `SafeCloseOpen` will not iterate if `U <= start`, while `CloseOpen` doesn't check for this, and thus the behavior is undefined in that case. """ AbstractCloseOpen """ CloseOpen([start=0], U) <: AbstractUnitRange Iterates over the range start:U-1. Guaranteed to iterate at least once, skipping initial empty check. See `?AbstractCloseOpen` for more information. """ CloseOpen """ SafeCloseOpen([start=0], U) <: AbstractUnitRange Iterates over the range start:U-1. Will not iterate if it `isempty`, like a typical range, making it generally the preferred choice over `CloseOpen`. See `?AbstractCloseOpen` for more information. """ SafeCloseOpen @inline Base.first(r::AbstractCloseOpen) = getfield(r,:start) @inline Base.first(r::AbstractCloseOpen{StaticInt{F}}) where {F} = F @inline Base.step(::AbstractCloseOpen) = 1 @inline Base.last(r::AbstractCloseOpen{<:IntegerType,I}) where {I} = getfield(r,:upper) - 1 @inline Base.last(r::AbstractCloseOpen{<:IntegerType,StaticInt{L}}) where {L} = L - 1 @inline Base.length(r::AbstractCloseOpen) = Int(getfield(r,:upper) - getfield(r,:start)) @inline Base.length(r::AbstractCloseOpen{Zero}) = Int(getfield(r,:upper)) @inline Base.iterate(r::CloseOpen) = (i = Int(first(r)); (i, i)) @inline Base.iterate(r::SafeCloseOpen) = (i = Int(first(r)); i ≥ getfield(r, :upper) ? nothing : (i, i)) @inline Base.iterate(r::AbstractCloseOpen, i::IntegerType) = (i += one(i)) ≥ getfield(r, :upper) ? nothing : (i, i) import StaticArrayInterface StaticArrayInterface.known_first(::Type{<:AbstractCloseOpen{StaticInt{F}}}) where {F} = F StaticArrayInterface.known_step(::Type{<:AbstractCloseOpen}) = 1 StaticArrayInterface.known_last(::Type{<:AbstractCloseOpen{<:Any,StaticInt{L}}}) where {L} = L - 1 StaticArrayInterface.known_length(::Type{<:AbstractCloseOpen{StaticInt{F},StaticInt{L}}}) where {F,L} = L - F Base.IteratorSize(::Type{<:AbstractCloseOpen}) = Base.HasShape{1}() Base.IteratorEltype(::Type{<:AbstractCloseOpen}) = Base.HasEltype() @inline Base.size(r::AbstractCloseOpen) = (length(r),) @inline Base.eltype(r::AbstractCloseOpen) = Int @inline Base.eachindex(r::AbstractCloseOpen) = StaticInt(1):StaticArrayInterface.static_length(r) @static if isdefined(Base.IteratorsMD, :OrdinalRangeInt) @inline function Base.IteratorsMD.__inc(state::Tuple{Int,Int,Vararg{Int}}, indices::Tuple{AbstractCloseOpen,Vararg{Base.IteratorsMD.OrdinalRangeInt}}) rng = indices[1] I1 = state[1] + step(rng) if Base.IteratorsMD.__is_valid_range(I1, rng) && state[1] != last(rng) return true, (I1, Base.tail(state)...) end valid, I = Base.IteratorsMD.__inc(Base.tail(state), Base.tail(indices)) return valid, (convert(typeof(I1), first(rng)), I...) end else @inline function Base.IteratorsMD.__inc(state::Tuple{Int,Int,Vararg{Int}}, indices::Tuple{AbstractCloseOpen,Vararg}) rng = indices[1] I1 = state[1] + step(rng) if Base.IteratorsMD.__is_valid_range(I1, rng) && state[1] != last(rng) return true, (I1, Base.tail(state)...) end valid, I = Base.IteratorsMD.__inc(Base.tail(state), Base.tail(indices)) return valid, (convert(typeof(I1), first(rng)), I...) end end end
CloseOpenIntervals
https://github.com/JuliaSIMD/CloseOpenIntervals.jl.git
[ "MIT" ]
0.1.13
05ba0d07cd4fd8b7a39541e31a7b0254704ea581
code
1247
using CloseOpenIntervals using Test function mysum2(X = CartesianIndices((SafeCloseOpen(10), SafeCloseOpen(10)))) s = 0 for I in X s += sum(Tuple(I)) end s end mysum2_allocated() = @allocated(mysum2()) const ArrayInterface = CloseOpenIntervals.StaticArrayInterface @testset "CloseOpenIntervals.jl" begin function mysum(x, N) s = zero(eltype(x)) @inbounds @fastmath for i ∈ CloseOpen(N) s += x[i+1] end s end function mysafesum(x, N) s = zero(eltype(x)) @inbounds @fastmath for i ∈ SafeCloseOpen(N) s += x[i+1] end s end x = rand(128) for n ∈ 1:128 @test mysum(x, n) ≈ mysafesum(x, n) ≈ sum(view(x, 1:n)) @test length(CloseOpen(n)) == n end @test @inferred(mysum(x, 0)) == first(x) @test @inferred(mysafesum(x, 0)) == 0.0 @test @inferred(mysum(x, CloseOpenIntervals.StaticInt(128))) ≈ sum(x) @test @inferred( ArrayInterface.static_length(CloseOpen(CloseOpenIntervals.StaticInt(128))) ) === CloseOpenIntervals.StaticInt(128) @test @inferred(eltype(CloseOpen(7))) === Int @test ArrayInterface.known_length(CloseOpen(CloseOpenIntervals.StaticInt(128))) == 128 @test @inferred(mysum2()) == sum(0:9) * 2 * length(0:9) @test mysum2_allocated() == 0 end
CloseOpenIntervals
https://github.com/JuliaSIMD/CloseOpenIntervals.jl.git
[ "MIT" ]
0.1.13
05ba0d07cd4fd8b7a39541e31a7b0254704ea581
docs
562
# CloseOpenIntervals [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaSIMD.github.io/CloseOpenIntervals.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://JuliaSIMD.github.io/CloseOpenIntervals.jl/dev) [![Build Status](https://github.com/JuliaSIMD/CloseOpenIntervals.jl/workflows/CI/badge.svg)](https://github.com/JuliaSIMD/CloseOpenIntervals.jl/actions) [![Coverage](https://codecov.io/gh/JuliaSIMD/CloseOpenIntervals.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/JuliaSIMD/CloseOpenIntervals.jl)
CloseOpenIntervals
https://github.com/JuliaSIMD/CloseOpenIntervals.jl.git
[ "MIT" ]
0.1.13
05ba0d07cd4fd8b7a39541e31a7b0254704ea581
docs
227
```@meta CurrentModule = CloseOpenIntervals ``` # CloseOpenIntervals Documentation for [CloseOpenIntervals](https://github.com/JuliaSIMD/CloseOpenIntervals.jl). ```@index ``` ```@autodocs Modules = [CloseOpenIntervals] ```
CloseOpenIntervals
https://github.com/JuliaSIMD/CloseOpenIntervals.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
188
module InvariantsCore import Markdown include("interface.jl") include("format.jl") include("invariant.jl") include("wrapinvariant.jl") include("compose.jl") include("highlevel.jl") end
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
2055
abstract type InvariantList <: AbstractInvariant end title(invs::InvariantList) = invs.title description(invs::InvariantList) = invs.description # ## `AllInvariant` struct AllInvariant{I <: AbstractInvariant} <: InvariantList invariants::Vector{I} title::String description::Union{Nothing, String} shortcircuit::Bool end function AllInvariant(invariants, title::String; description = nothing, shortcircuit = true, kwargs...) invariant(AllInvariant(invariants, title, description, shortcircuit); kwargs...) end function satisfies(invs::AllInvariant, input) results = [] keepchecking = true for inv in invs.invariants if !keepchecking push!(results, missing) continue else res = catch_satisfies(inv, input) push!(results, res) if !isnothing(res) && invs.shortcircuit keepchecking = false end end end return all(isnothing, results) ? nothing : results end # ## `AnyInvariant` struct AnyInvariant{I <: AbstractInvariant} <: InvariantList invariants::Vector{I} title::String description::Union{Nothing, String} end function AnyInvariant(invariants, title::String; description = nothing, shortcircuit = true, kwargs...) invariant(AnyInvariant(invariants, title, description); kwargs...) end function satisfies(invs::AnyInvariant, input) results = [] for inv in invs.invariants res = catch_satisfies(inv, input) push!(results, res) if isnothing(res) return nothing end end return results end function catch_satisfies(inv::AbstractInvariant, input) try return satisfies(inv, input) catch e errormsg = sprint(Base.showerror, e, context = :color => true) return md("An uncaught error was thrown while checking this invariant:") * "\n\n" * errormsg end end
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
946
# This file defines `format_markdown`, a helper to turn Markdown strings # into richly formatted text output. struct AsMarkdown{T} s::T end AsMarkdown(am::AsMarkdown) = am function Base.show(io::IO, md::AsMarkdown) print(io, __getmdstr(io, md)) end function __getmdstr(io::IO, md::AsMarkdown) md = Markdown.parse(md.s) buf = IOBuffer() display(TextDisplay(IOContext(buf, :color => get(io, :color, false), :displaysize => get(io, :displaysize, (88, 500)))), md) res = strip(String(take!(buf))) # two calls so it doesn't crash on 1.6 res = replace(res, " " => "") res = replace(res, "\n\n\n" => "\n\n") return res end function Base.string(md::AsMarkdown) return __getmdstr(IOContext(IOBuffer(), :color => true, :displaysize => (88, 500)), md) end const format_markdown = AsMarkdown default_format() = format_markdown
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
5560
# This file defines [`invariant`](#), which allows creating and combining # invariants and should cover most use cases. # # It also defines [`check`](#) for running an innput against an invariant. # # ## `invariant` # # The basic method simply returns an [`Invariant`](#): """ invariant(fn, title; kwargs...) Create an invariant with name `title` that checks an input against `fn` which returns either `nothing` when the invariant is satisfied, or an error message when the invariant is violated. invariant(inv; title=title(inv), kwargs...) Wrap an invariant `inv`, replacing some of its attributes. invariant(title, invariants, all; kwargs...) invariant(title, invariants, any; kwargs...) Combine multiple invariants `invs` logically. The third argument defines how they are combined. If it is `all`, the resulting invariant requires all `invariants` to pass, while a value of `any` results in an invariant where only one of the `invariants` has to be satisfied. ## Keyword arguments Every method additionally accepts the following keyword arguments: - `description::String = ""`: A description of the invariant that gives explanation and points to related resources. - `inputfn = identity`: A function that is applied to an input before checking. Useful when composing multiple invariants. ## Examples Basic usage: {cell} ```julia using Invariants inv = invariant("Is negative") do n n < 0 ? nothing : "`n` is not negative!" end ``` Successful check: {cell} ```julia check(inv, -1) ``` Failing check: {cell} ```julia check(inv, 1) ``` Or just get a Bool: {cell} ```julia check(Bool, inv, -1), check(Bool, inv, 1) ``` Throw an error when an invariant is not satisfied: {cell} ```julia check_throw(inv, 1) ``` """ invariant(fn, title::String; kwargs...) = Invariant(; fn, title, kwargs...) # `invariant` can be called on a vector of invariants, creating an invariant that # logically composes them (either AND or OR): function invariant(title, invariants::AbstractVector{<:AbstractInvariant}; kwargs...) invariant(title, invariants, all; kwargs...) end function invariant(title, invariants::AbstractVector{<:AbstractInvariant}, ::typeof(all); kwargs...) AllInvariant(invariants, title; kwargs...) end function invariant(title, invariants::AbstractVector{<:AbstractInvariant}, ::typeof(any); kwargs...) AnyInvariant(invariants, title; kwargs...) end # `invariant` can also wrap an invariant, changing some of its attributes. # For a general `AbstractInvariant`, this will return a [`WrapInvariant`](#): function invariant(inv::AbstractInvariant; title = nothing, inputfn = identity, description = nothing, format = nothing) if isnothing(title) && inputfn === identity && isnothing(description) && isnothing(format) return inv end return WrapInvariant(inv, title, description, inputfn, format) end # While for an [`Invariant`](#) this will simply return a new [`Invariant`](#) # with changed fields: function invariant(inv::Invariant; title = nothing, inputfn = identity, description = nothing, format = nothing) return Invariant(inv.fn, isnothing(title) ? inv.title : title, isnothing(description) ? inv.description : description, inputfn === identity ? inv.inputfn : inputfn ∘ inv.inputfn, isnothing(format) ? inv.format : format) end # ## `check` """ check(invariant, input) Check an invariant against an input, and return a [`CheckResult`] that gives detailed output in case of an invariant violation. check(Bool, invariant, input) Check an invariant against an input, returning `true` if satisfied, `false` if violated. """ function check(invariant, input) res = catch_satisfies(invariant, input) return CheckResult(invariant, res) end check(::Type{Bool}, invariant, input) = isnothing(satisfies(invariant, input)) check(::Type{Exception}, invariant, input) = check_throw(invariant, input) struct CheckResult{I, R} invariant::I result::R end Base.convert(::Type{Bool}, checkres::CheckResult) = isnothing(checkres.result) function Base.show(io::IO, checkres::CheckResult{<:I, Nothing}) where {I} print(io, "\e[32m✔ Invariant satisfied:\e[0m ") print(io, md(title(checkres.invariant))) end function Base.show(io::IO, checkres::CheckResult) print(io, "\e[1m\e[31m⨯ Invariant not satisfied:\e[0m\e[1m ") print(io, md(title(checkres.invariant))) println(io, "\e[22m\n") errormessage(io, checkres.invariant, checkres.result) end md(s) = string(AsMarkdown(s)) # For cases where violating an invariant should lead to an error be thrown, use # [`check_throw`](#): """ check_throw(invariant, input) Check an invariant and provide a detailed error message if it does not pass. If it passes, return `nothing`. Use in tests in combination with `@test_nowarn`. """ function check_throw(invariant, input) res = satisfies(invariant, input) isnothing(res) && return throw(InvariantException(invariant, res)) end struct InvariantException{I <: AbstractInvariant, M} invariant::I msg::M end function Base.showerror(io::IO, e::InvariantException) println(io, "Invariant violated!") errormessage(io, e.invariant, e.msg) end # Allow calling the invariant so that `check` doesn't need to be imported. (inv::AbstractInvariant)(args...) = check(inv, args...) (inv::AbstractInvariant)(T::Type, args...) = check(T, inv, args...)
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
2286
# This file defines the core interface for defining invariants. """ abstract type AbstractInvariant An `Invariant` checks if an input satisfies some invariant. For example, it may check whether a number is positive. For most use cases, using [`invariant`](#) to create an invariant will suffice and implementing your own subtype of `AbstractInvariant` will rarely be necessary. The interface of `Invariant`s is designed so that - the invariant can be checked, given some input - invariants can be composed to generate more complicated invariants - the creation of rich error messages is possible when an invariant is not satisfied. ## Interface An `Invariant` `I` must implement the following methods: - [`title`](#)`(::I)::String`: Descriptive name for the invariant - [`description`](#)`(::I)::String`: A longer description of the invariant, giving explanation and pointing to related information. - [`satisfies`](#)`(::I, input) -> (nothing | msg)`: Check whether an `input` satisfies the invariant, returning either `nothing` on success or an error message. """ abstract type AbstractInvariant end """ title(invariant) -> String Short summary of an invariant. Is used as a title in reports and error messages. Part of the [`AbstractInvariant`](#) interface. """ function title end """ description(invariant) -> String Return a more detailed description of an invariant. Part of the [`AbstractInvariant`](#) interface. """ description(::AbstractInvariant) = nothing """ satisfies(invariant, input) -> nothing | errormessage Check if `input` satisfies an `invariant`. If it does, return `nothing`. Otherwise return an error message explaining why the invariant is violated. """ function satisfies end # ## Defaults function errormessage(inv::AbstractInvariant, msg) buf = IOBuffer() errormessage(IOContext(buf, :color => true, :displaysize => (88, 500)), inv, msg) return String(take!(buf)) end function errormessage(io::IO, inv::AbstractInvariant, msg) println(io) showdescription(io, inv) println(io) println(io, msg) end function showdescription(io, inv) desc = description(inv) isnothing(desc) || print(io, description(inv)) end function showtitle(io, inv) print(io, title(inv)) end
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
855
# This file defines `Invariant`, a default invariant that should be used # in most cases to construct invariants. """ struct Invariant(fn, title; kwargs...) <: AbstractInvariant Default invariant type. Use [`invariant`](#) to construct invariants. """ Base.@kwdef struct Invariant <: AbstractInvariant fn::Any title::String description::Union{Nothing, String} = nothing inputfn = identity format = default_format() end function Invariant(fn, title::String; description = nothing, inputfn = identity, format = default_format()) Invariant(; fn, title, description, inputfn, format) end title(inv::Invariant) = inv.format(inv.title) function description(inv::Invariant) isnothing(inv.description) ? nothing : inv.format(inv.description) end satisfies(inv::Invariant, input) = inv.fn(inv.inputfn(input))
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
887
# This file defines [`WrapInvariant`](#), which wraps around an invariant, # changing part of its functionality struct WrapInvariant <: AbstractInvariant inv::Any title::Any description::Any inputfn::Any format::Any end function title(wrap::WrapInvariant) t = isnothing(wrap.title) ? title(wrap.inv) : wrap.title format = isnothing(wrap.format) ? identity : wrap.format return format(t) end function description(wrap::WrapInvariant) desc = isnothing(wrap.description) ? description(wrap.inv) : wrap.description format = isnothing(wrap.format) ? identity : wrap.format return format(desc) end satisfies(wrap::WrapInvariant, input) = satisfies(wrap.inv, wrap.inputfn(input)) function errormessage(io::IO, wrap::WrapInvariant, msg) format = isnothing(wrap.format) ? identity : wrap.format errormessage(io, wrap.inv, format(msg)) end
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
3311
module InvariantsCoreTests using InlineTest using InvariantsCore using InvariantsCore: Invariant, WrapInvariant, InvariantException, invariant, title, description, satisfies, check, check_throw # ## Helpers and setup function exampleinvariant(symbol = :n) return Invariant("`$symbol` is positive", description = "The number `$symbol` should be larger than `0`.") do x if !(x isa Number) return "`$symbol` has type $(typeof(x)), but it should be a `Number` type." else x > 0 && return nothing return "`$symbol` is not a positive number, got value `$x`. Please pass a number larger than 0." end end end function testinvariant(inv, input) @test_nowarn title(inv) @test_nowarn description(inv) @test_nowarn satisfies(inv, input) @test_nowarn inv(input) end # ## Tests @testset "Invariant" begin inv = exampleinvariant() testinvariant(inv, 1) @test isnothing(satisfies(inv, 1)) @test occursin("should be", satisfies(inv, "")) @test occursin("larger", satisfies(inv, -1)) @test occursin("0", string(description(inv))) end @testset "WrapInvariant" begin @testset "Pass-through" begin inv = invariant(exampleinvariant()) @test inv isa Invariant end @testset "Title" begin inv = invariant(exampleinvariant(), title = "new") @test inv isa Invariant @test string(title(inv)) == "new" end end @testset "invariant" begin @testset "Basic" begin inv = invariant(input -> input ? nothing : "Not true", "title") testinvariant(inv, true) @test string(title(inv)) == "title" @test isnothing(description(inv)) @test check(Bool, inv, true) @test_nowarn check_throw(inv, true) @test_throws InvariantException check_throw(inv, false) end @testset "Wrap" begin _inv = invariant(input -> input ? nothing : "Not true", "title") inv = invariant(_inv, title = "newtitle", inputfn = input -> !input) testinvariant(inv, true) @test string(title(inv)) == "newtitle" @test isnothing(description(inv)) @test check(Bool, inv, false) end @testset "Compose" begin @testset "all" begin invs = invariant("all", [invariant(input -> input ? nothing : "Not true", "child", inputfn = inputs -> inputs[i]) for i in 1:3]) @test check(Bool, invs, [true, true, true]) @test !check(Bool, invs, [true, true, false]) @test_throws InvariantException check_throw(invs, [true, false, false]) end @testset "any" begin invs = invariant("all", [invariant(input -> input ? nothing : "Not true", "child", inputfn = inputs -> inputs[i]) for i in 1:3], any) @test check(Bool, invs, [true, true, true]) @test check(Bool, invs, [true, true, false]) @test !check(Bool, invs, [false, false, false]) @test_throws InvariantException check_throw(invs, [false, false, false]) end end end end
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
113
using InvariantsCore using InlineTest, ReTest include("InvariantsCoreTests.jl") InvariantsCoreTests.runtests()
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
644
""" This script builds the Pollen.jl documentation so that it can be loaded by the frontend. It accepts one argument: the path where the generated files should be stored. > julia docs/make.jl DIR Use `./serve.jl` for interactive development. """ # Create target folder isempty(ARGS) && error("Please pass a file path to make.jl:\n\t> julia docs/make.jl DIR ") DIR = abspath(mkpath(ARGS[1])) # Create Project project = include("project.jl") @info "Rewriting documents..." Pollen.rewritesources!(project) @info "Writing to disk at \"$DIR\"..." Pollen.build(FileBuilder(JSONFormat(), DIR), project)
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
778
using Pollen using Pkg # The main package you are documenting using Invariants, InvariantsCore m = Invariants # Packages that will be indexed in the documentation. Add additional modules # to the list. ms = [m, InvariantsCore] # Add rewriters here project = Project(Pollen.Rewriter[DocumentFolder(Pkg.pkgdir(m), prefix = "documents"), ParseCode(), ExecuteCode(), PackageDocumentation(ms), StaticResources(), DocumentGraph(), SearchIndex(), SaveAttributes((:title,)), LoadFrontendConfig(Pkg.pkgdir(m))])
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
715
""" This script serves the Pollen.jl documentation on a local file server so that it can be loaded by the frontend in development mode. files should be stored. > julia docs/serve.jl Use `./make.jl` to export the generated documents to disk. There are two modes for interactive development: Lazy and Regular. In lazy mode, each document will be built only if it is requested in the frontend, while for Regular mode, each document will be built once before serving. """ using Pollen project = include("project.jl") Pollen.serve(project; lazy = get(ENV, "POLLEN_LAZY", "false") == "true", port = Base.parse(Int, get(ENV, "POLLEN_PORT", "8000")), format = JSONFormat())
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
992
module Invariants using InlineTest using TextWrap: wrap import AbstractTrees import InvariantsCore import InvariantsCore: AbstractInvariant, InvariantList, AnyInvariant, AllInvariant, AsMarkdown, errormessage, satisfies, invariant, check, check_throw, title, description, showdescription, showtitle include("wrapio.jl") include("tree.jl") include("show.jl") include("invariants/hasmethod.jl") include("invariants/hastype.jl") function exampleinvariant(symbol = :n) return invariant("`$symbol` is positive", description = "The number `$symbol` should be larger than `0`.") do x if !(x isa Number) return "`$symbol` has type $(typeof(x)), but it should be a `Number` type." |> md else x > 0 && return nothing return "`$symbol` is not a positive number, got value `$x`. Please pass a number larger than 0." |> md end end end export invariant, check, check_throw end
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
1465
function InvariantsCore.errormessage(io::IO, invs::AllInvariant, msgs) __combinator_errormessage(io, invs, msgs, map(__getmarker, msgs), faint("(All invariants listed below must be satisfied)\n\n ")) end function InvariantsCore.errormessage(io::IO, invs::AnyInvariant, msgs) __combinator_errormessage(io, invs, msgs, map(m -> isnothing(m) ? PASS : FAIL, msgs), faint("(At least one of the invariants listed below must be satisfied)\n\n")) end const PASS = "\e[32m✔ Satisfied:\e[0m\e[2m" const FAIL = "\e[31m⨯ Not satisfied:\e[0m" const UNKNOWN = "\e[33m? \e[2mNot checked:\e[0m\e[2m" function __combinator_errormessage(io::IO, invs, msgs, markers, msg) showdescription(io, invs) println(io) print(io, msg) for (inv, message, marker) in zip(invs.invariants, msgs, markers) __errormessage_child(io, inv; marker, message) end end function __errormessage_child(io, inv; marker = "o", message = nothing, indent = " ") print(io, marker, " ") showtitle(io, inv) print(io, "\e[0m") println(io) if !(isnothing(message) || ismissing(message)) ioi = WrapIO(io; indent, maxwidth = 88) errormessage(ioi, inv, message) end end __getmarker(::Nothing) = PASS __getmarker(::Missing) = UNKNOWN __getmarker(_) = FAIL
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
323
AbstractTrees.children(invs::InvariantList) = invs.invariants Base.show(io::IO, inv::AbstractInvariant) = AbstractTrees.print_tree(io, inv) function AbstractTrees.printnode(io::IO, inv::AbstractInvariant) print(io, nameof(typeof(inv)), "(\"", md(title(inv)), "\")") end AbstractTrees.children(::AbstractInvariant) = ()
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
2802
mutable struct WrapIO{I <: IO} <: IO io::I width::Int indent::String indentfirst::Bool end function WrapIO(io; width = displaysize(io)[2], indent = "", indentfirst = true, maxwidth = nothing) width = isnothing(maxwidth) ? width : min(maxwidth, width) WrapIO(io, width, indent, indentfirst) end function WrapIO(io::WrapIO; width = displaysize(io)[2], indent = "", indentfirst = true, maxwidth = nothing) width = isnothing(maxwidth) ? width : min(maxwidth, width) WrapIO(io.io, min(width, io.width), io.indent * indent, indentfirst) end Base.get(io::WrapIO, k, v) = get(io.io, k, v) function Base.write(io::WrapIO, x::String) isempty(x) && return lines = split(x, '\n') lines = isempty(lines) ? [""] : lines for (i, line) in enumerate(lines) if isempty(line) if io.indentfirst write(io.io, io.indent) end write(io.io, '\n') io.indentfirst = true else if isempty(strip(line)) if io.indentfirst write(io.io, io.indent) end write(io.io, line) io.indentfirst = false else wrappedline = wrap(line, width = io.width, initial_indent = (io.indentfirst || i > 1) ? io.indent : "", subsequent_indent = io.indent, replace_whitespace = false) write(io.io, wrappedline) io.indentfirst = false end if i != length(lines) write(io.io, '\n') io.indentfirst = true else io.indentfirst = isempty(line) end end end end function Base.write(io::WrapIO, b::UInt8) write(io.io, b) end @testset "WrapIO" begin function printwrapped(x; indentfirst = true, kwargs...) buf = IOBuffer() io = WrapIO(buf; indentfirst, kwargs...) print(io, x) String(take!(buf)) end @test printwrapped("hello", indent = " ") == " hello" @test printwrapped("hello", indent = " ") == " hello" @test printwrapped("aaaa\nbbbb", width = 2) == "aa\naa\nbb\nbb" @testset "Composition" begin buf = IOBuffer() io = WrapIO(WrapIO(buf, indent = " "), indent = " ") @test io isa WrapIO @test io.io isa IOBuffer @test io.indent == " " end @test printwrapped("\naaaa\nbbbb", width = 2) == "\naa\naa\nbb\nbb" @test_broken printwrapped("\naa\nbb", width = 2, indent = " ") == "\n a\n a\n b\n b" @test_broken printwrapped("\n a\nbb", width = 2, indent = " ") == "\n  \n a\n b\n b" end
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
2593
md(s) = string(AsMarkdown(s)) function hasmethod_invariant(fn, args...; title = _title_hasmethod(fn, args), kwargs...) return invariant(title; kwargs...) do inputs if !(_validate_hasmethod(args)(inputs)) return "Got invalid inputs $inputs" end argnames = map(arg -> arg isa Symbol ? arg : arg[1], args) argvalues = map(arg -> arg isa Symbol ? inputs[arg] : arg[2], args) try fn(argvalues...) return nothing catch e sig = _signature(fn, argnames, argvalues) if e isa MethodError && e.f == fn return md("""When calling `$fn`, got a `MethodError`. This means that there is no method implemented for the given arguments. To fix this, please implement the following method: """) * "\n\n    " * sig else return (md("When calling `$fn`, got an unexpected error:") * "\n\n" * (sprint(Base.showerror, e; context = (:color => false,)) |> indent |> faint) * "\n\n" * md("""This means that there is a method matching the given arguments, but calling it throws an error. To fix this, please debug the following method:""") * "\n\n    " * sig) end end end end function indent(s, n = 4) wrap(s; initial_indent = repeat(" ", n), subsequent_indent = repeat(" ", n)) end faint(s) = "\e[2m$s\e[22m" function _title_hasmethod(fn, args) buf = IOBuffer() print(buf, "Method `$(nameof(parentmodule(fn))).$(nameof(fn))(") for (i, arg) in enumerate(args) name = arg isa Symbol ? arg : first(arg) print(buf, name) i != length(args) && print(buf, ", ") end print(buf, ")` implemented") return String(take!(buf)) end function _validate_hasmethod(args) return function (inputs) for arg in args inputs isa NamedTuple || return false if arg isa Symbol haskey(inputs, arg) || return false end end return true end end function _signature(fn, argnames, argvalues) buf = IOBuffer() bold(s) = "\e[1m$s\e[22m" print(buf, parentmodule(fn), ".", nameof(fn), faint("(")) for (i, (name, val)) in enumerate(zip(argnames, argvalues)) print(buf, name, faint("::"), bold(nameof(typeof(val)))) i != length(argnames) && print(buf, faint(", ")) end print(buf, faint(")")) return String(take!(buf)) end
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
379
function hastype_invariant(T; var = "x", title = nothing, kwargs...) s_T = nameof(T) title = isnothing(title) ? "`$var` has type `$s_T`" : title return invariant(title; kwargs...) do input IT = input isa Type ? input : typeof(input) if !(IT <: T) return "`$var` should be of type `$T`, but got type `$(IT)`." |> md end end end
Invariants
https://github.com/lorenzoh/Invariants.jl.git
[ "MIT" ]
0.1.0
0c6fbb0af4269cb73215a676aafb2689006eb3a8
code
105
using Invariants import Test using ReTest Invariants.runtests() Test.@testset "Invariants.jl" begin end
Invariants
https://github.com/lorenzoh/Invariants.jl.git